jasonfan commited on
Commit
b22bd2d
·
verified ·
1 Parent(s): cdbbc6d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h +104 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h +91 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h +91 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h +105 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h +228 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h +96 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h +43 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h +64 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h +25 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h +320 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h +90 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/python/init.h +13 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/archive.h +9 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h +120 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h +85 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/tensor.h +25 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/FunctionsManual.h +1158 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/InferenceMode.h +15 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/VariableTypeUtils.h +446 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/anomaly_mode.h +76 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd.h +109 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd_not_implemented_fallback.h +37 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/cpp_hook.h +37 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/custom_function.h +585 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/edge.h +61 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/engine.h +294 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/forward_grad.h +215 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function.h +796 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function_hook.h +77 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h +307 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h +117 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/comm.h +50 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h +19 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h +190 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/utils.h +120 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h +0 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h +60 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h +960 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h +30 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h +103 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h +784 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/grad_mode.h +16 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/graph_task.h +234 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_buffer.h +61 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_metadata.h +137 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/jit_decomp_interface.h +55 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler.h +9 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_kineto.h +230 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_legacy.h +407 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_python.h +12 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adagrad.h ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/nn/pimpl.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/optim/serialize.h>
7
+ #include <torch/serialize/archive.h>
8
+ #include <torch/types.h>
9
+
10
+ #include <utility>
11
+ #include <vector>
12
+
13
+ namespace torch::serialize {
14
+ class OutputArchive;
15
+ class InputArchive;
16
+ } // namespace torch::serialize
17
+
18
+ namespace torch::optim {
19
+
20
+ struct TORCH_API AdagradOptions
21
+ : public OptimizerCloneableOptions<AdagradOptions> {
22
+ AdagradOptions(double lr = 1e-2);
23
+ TORCH_ARG(double, lr) = 1e-2;
24
+ TORCH_ARG(double, lr_decay) = 0;
25
+ TORCH_ARG(double, weight_decay) = 0;
26
+ TORCH_ARG(double, initial_accumulator_value) = 0;
27
+ TORCH_ARG(double, eps) = 1e-10;
28
+
29
+ public:
30
+ void serialize(torch::serialize::InputArchive& archive) override;
31
+ void serialize(torch::serialize::OutputArchive& archive) const override;
32
+ TORCH_API friend bool operator==(
33
+ const AdagradOptions& lhs,
34
+ const AdagradOptions& rhs);
35
+ double get_lr() const override;
36
+ void set_lr(const double lr) override;
37
+ };
38
+
39
+ struct TORCH_API AdagradParamState
40
+ : public OptimizerCloneableParamState<AdagradParamState> {
41
+ TORCH_ARG(torch::Tensor, sum);
42
+ TORCH_ARG(int64_t, step) = 0;
43
+
44
+ public:
45
+ void serialize(torch::serialize::InputArchive& archive) override;
46
+ void serialize(torch::serialize::OutputArchive& archive) const override;
47
+ TORCH_API friend bool operator==(
48
+ const AdagradParamState& lhs,
49
+ const AdagradParamState& rhs);
50
+ };
51
+
52
+ class TORCH_API Adagrad : public Optimizer {
53
+ public:
54
+ explicit Adagrad(
55
+ const std::vector<OptimizerParamGroup>& param_groups,
56
+ AdagradOptions defaults = {})
57
+ : Optimizer(param_groups, std::make_unique<AdagradOptions>(defaults)) {
58
+ TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
59
+ TORCH_CHECK(
60
+ defaults.lr_decay() >= 0,
61
+ "Invalid lr_decay value: ",
62
+ defaults.lr_decay());
63
+ TORCH_CHECK(
64
+ defaults.weight_decay() >= 0,
65
+ "Invalid weight_decay value: ",
66
+ defaults.weight_decay());
67
+ TORCH_CHECK(
68
+ defaults.initial_accumulator_value() >= 0,
69
+ "Invalid initial_accumulator_value value: ",
70
+ defaults.initial_accumulator_value());
71
+ TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
72
+
73
+ for (const auto& group : param_groups_) {
74
+ for (const auto& p : group.params()) {
75
+ auto state = std::make_unique<AdagradParamState>();
76
+ state->step(0);
77
+ state->sum(torch::full_like(
78
+ p.data(),
79
+ defaults.initial_accumulator_value(),
80
+ at::MemoryFormat::Preserve));
81
+ state_[p.unsafeGetTensorImpl()] = std::move(state);
82
+ }
83
+ }
84
+ }
85
+
86
+ explicit Adagrad(std::vector<Tensor> params, AdagradOptions defaults = {})
87
+ : Adagrad({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {
88
+ }
89
+
90
+ torch::Tensor step(LossClosure closure = nullptr) override;
91
+ void save(serialize::OutputArchive& archive) const override;
92
+ void load(serialize::InputArchive& archive) override;
93
+
94
+ private:
95
+ template <typename Self, typename Archive>
96
+ static void serialize(Self& self, Archive& archive) {
97
+ _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adagrad);
98
+ }
99
+ };
100
+ } // namespace torch::optim
101
+
102
+ #else
103
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
104
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adam.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/nn/module.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/optim/serialize.h>
7
+
8
+ #include <utility>
9
+ #include <vector>
10
+
11
+ namespace torch::serialize {
12
+ class OutputArchive;
13
+ class InputArchive;
14
+ } // namespace torch::serialize
15
+
16
+ namespace torch::optim {
17
+
18
+ struct TORCH_API AdamOptions : public OptimizerCloneableOptions<AdamOptions> {
19
+ AdamOptions(double lr = 1e-3);
20
+ TORCH_ARG(double, lr) = 1e-3;
21
+ typedef std::tuple<double, double> betas_t;
22
+ TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999);
23
+ TORCH_ARG(double, eps) = 1e-8;
24
+ TORCH_ARG(double, weight_decay) = 0;
25
+ TORCH_ARG(bool, amsgrad) = false;
26
+
27
+ public:
28
+ void serialize(torch::serialize::InputArchive& archive) override;
29
+ void serialize(torch::serialize::OutputArchive& archive) const override;
30
+ TORCH_API friend bool operator==(
31
+ const AdamOptions& lhs,
32
+ const AdamOptions& rhs);
33
+ double get_lr() const override;
34
+ void set_lr(const double lr) override;
35
+ };
36
+
37
+ struct TORCH_API AdamParamState
38
+ : public OptimizerCloneableParamState<AdamParamState> {
39
+ TORCH_ARG(int64_t, step) = 0;
40
+ TORCH_ARG(torch::Tensor, exp_avg);
41
+ TORCH_ARG(torch::Tensor, exp_avg_sq);
42
+ TORCH_ARG(torch::Tensor, max_exp_avg_sq);
43
+
44
+ public:
45
+ void serialize(torch::serialize::InputArchive& archive) override;
46
+ void serialize(torch::serialize::OutputArchive& archive) const override;
47
+ TORCH_API friend bool operator==(
48
+ const AdamParamState& lhs,
49
+ const AdamParamState& rhs);
50
+ };
51
+
52
+ class TORCH_API Adam : public Optimizer {
53
+ public:
54
+ explicit Adam(
55
+ const std::vector<OptimizerParamGroup>& param_groups,
56
+ AdamOptions defaults = {})
57
+ : Optimizer(param_groups, std::make_unique<AdamOptions>(defaults)) {
58
+ TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
59
+ TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
60
+ auto betas = defaults.betas();
61
+ TORCH_CHECK(
62
+ 0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0,
63
+ "Invalid beta parameter at index 0: ",
64
+ std::get<0>(betas));
65
+ TORCH_CHECK(
66
+ 0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0,
67
+ "Invalid beta parameter at index 1: ",
68
+ std::get<1>(betas));
69
+ TORCH_CHECK(
70
+ defaults.weight_decay() >= 0,
71
+ "Invalid weight_decay value: ",
72
+ defaults.weight_decay());
73
+ }
74
+ explicit Adam(std::vector<Tensor> params, AdamOptions defaults = {})
75
+ : Adam({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {}
76
+
77
+ torch::Tensor step(LossClosure closure = nullptr) override;
78
+ void save(serialize::OutputArchive& archive) const override;
79
+ void load(serialize::InputArchive& archive) override;
80
+
81
+ private:
82
+ template <typename Self, typename Archive>
83
+ static void serialize(Self& self, Archive& archive) {
84
+ _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(Adam);
85
+ }
86
+ };
87
+ } // namespace torch::optim
88
+
89
+ #else
90
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
91
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/adamw.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/nn/module.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/optim/serialize.h>
7
+
8
+ #include <utility>
9
+ #include <vector>
10
+
11
+ namespace torch::serialize {
12
+ class OutputArchive;
13
+ class InputArchive;
14
+ } // namespace torch::serialize
15
+
16
+ namespace torch::optim {
17
+
18
+ struct TORCH_API AdamWOptions : public OptimizerCloneableOptions<AdamWOptions> {
19
+ AdamWOptions(double lr = 1e-3);
20
+ TORCH_ARG(double, lr) = 1e-3;
21
+ typedef std::tuple<double, double> betas_t;
22
+ TORCH_ARG(betas_t, betas) = std::make_tuple(0.9, 0.999);
23
+ TORCH_ARG(double, eps) = 1e-8;
24
+ TORCH_ARG(double, weight_decay) = 1e-2;
25
+ TORCH_ARG(bool, amsgrad) = false;
26
+
27
+ public:
28
+ void serialize(torch::serialize::InputArchive& archive) override;
29
+ void serialize(torch::serialize::OutputArchive& archive) const override;
30
+ TORCH_API friend bool operator==(
31
+ const AdamWOptions& lhs,
32
+ const AdamWOptions& rhs);
33
+ double get_lr() const override;
34
+ void set_lr(const double lr) override;
35
+ };
36
+
37
+ struct TORCH_API AdamWParamState
38
+ : public OptimizerCloneableParamState<AdamWParamState> {
39
+ TORCH_ARG(int64_t, step) = 0;
40
+ TORCH_ARG(torch::Tensor, exp_avg);
41
+ TORCH_ARG(torch::Tensor, exp_avg_sq);
42
+ TORCH_ARG(torch::Tensor, max_exp_avg_sq);
43
+
44
+ public:
45
+ void serialize(torch::serialize::InputArchive& archive) override;
46
+ void serialize(torch::serialize::OutputArchive& archive) const override;
47
+ TORCH_API friend bool operator==(
48
+ const AdamWParamState& lhs,
49
+ const AdamWParamState& rhs);
50
+ };
51
+
52
+ class TORCH_API AdamW : public Optimizer {
53
+ public:
54
+ explicit AdamW(
55
+ const std::vector<OptimizerParamGroup>& param_groups,
56
+ AdamWOptions defaults = {})
57
+ : Optimizer(param_groups, std::make_unique<AdamWOptions>(defaults)) {
58
+ TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
59
+ TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
60
+ auto betas = defaults.betas();
61
+ TORCH_CHECK(
62
+ 0 <= std::get<0>(betas) && std::get<0>(betas) < 1.0,
63
+ "Invalid beta parameter at index 0: ",
64
+ std::get<0>(betas));
65
+ TORCH_CHECK(
66
+ 0 <= std::get<1>(betas) && std::get<1>(betas) < 1.0,
67
+ "Invalid beta parameter at index 1: ",
68
+ std::get<1>(betas));
69
+ TORCH_CHECK(
70
+ defaults.weight_decay() >= 0,
71
+ "Invalid weight_decay value: ",
72
+ defaults.weight_decay());
73
+ }
74
+ explicit AdamW(std::vector<Tensor> params, AdamWOptions defaults = {})
75
+ : AdamW({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {}
76
+
77
+ torch::Tensor step(LossClosure closure = nullptr) override;
78
+ void save(serialize::OutputArchive& archive) const override;
79
+ void load(serialize::InputArchive& archive) override;
80
+
81
+ private:
82
+ template <typename Self, typename Archive>
83
+ static void serialize(Self& self, Archive& archive) {
84
+ _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(AdamW);
85
+ }
86
+ };
87
+ } // namespace torch::optim
88
+
89
+ #else
90
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
91
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/lbfgs.h ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/nn/module.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/optim/serialize.h>
7
+ #include <torch/serialize/archive.h>
8
+
9
+ #include <deque>
10
+ #include <functional>
11
+ #include <memory>
12
+ #include <utility>
13
+ #include <vector>
14
+
15
+ namespace torch::optim {
16
+
17
+ struct TORCH_API LBFGSOptions : public OptimizerCloneableOptions<LBFGSOptions> {
18
+ LBFGSOptions(double lr = 1);
19
+ TORCH_ARG(double, lr) = 1;
20
+ TORCH_ARG(int64_t, max_iter) = 20;
21
+ TORCH_ARG(std::optional<int64_t>, max_eval) = std::nullopt;
22
+ TORCH_ARG(double, tolerance_grad) = 1e-7;
23
+ TORCH_ARG(double, tolerance_change) = 1e-9;
24
+ TORCH_ARG(int64_t, history_size) = 100;
25
+ TORCH_ARG(std::optional<std::string>, line_search_fn) = std::nullopt;
26
+
27
+ public:
28
+ void serialize(torch::serialize::InputArchive& archive) override;
29
+ void serialize(torch::serialize::OutputArchive& archive) const override;
30
+ TORCH_API friend bool operator==(
31
+ const LBFGSOptions& lhs,
32
+ const LBFGSOptions& rhs);
33
+ double get_lr() const override;
34
+ void set_lr(const double lr) override;
35
+ };
36
+
37
+ struct TORCH_API LBFGSParamState
38
+ : public OptimizerCloneableParamState<LBFGSParamState> {
39
+ TORCH_ARG(int64_t, func_evals) = 0;
40
+ TORCH_ARG(int64_t, n_iter) = 0;
41
+ TORCH_ARG(double, t) = 0;
42
+ TORCH_ARG(double, prev_loss) = 0;
43
+ TORCH_ARG(Tensor, d);
44
+ TORCH_ARG(Tensor, H_diag);
45
+ TORCH_ARG(Tensor, prev_flat_grad);
46
+ TORCH_ARG(std::deque<Tensor>, old_dirs);
47
+ TORCH_ARG(std::deque<Tensor>, old_stps);
48
+ TORCH_ARG(std::deque<Tensor>, ro);
49
+ TORCH_ARG(std::optional<std::vector<Tensor>>, al) = std::nullopt;
50
+
51
+ public:
52
+ void serialize(torch::serialize::InputArchive& archive) override;
53
+ void serialize(torch::serialize::OutputArchive& archive) const override;
54
+ TORCH_API friend bool operator==(
55
+ const LBFGSParamState& lhs,
56
+ const LBFGSParamState& rhs);
57
+ };
58
+
59
+ class TORCH_API LBFGS : public Optimizer {
60
+ public:
61
+ explicit LBFGS(
62
+ const std::vector<OptimizerParamGroup>& param_groups,
63
+ LBFGSOptions defaults = {})
64
+ : Optimizer(param_groups, std::make_unique<LBFGSOptions>(defaults)) {
65
+ TORCH_CHECK(
66
+ param_groups_.size() == 1,
67
+ "LBFGS doesn't support per-parameter options (parameter groups)");
68
+ if (defaults.max_eval() == std::nullopt) {
69
+ auto max_eval_val = (defaults.max_iter() * 5) / 4;
70
+ static_cast<LBFGSOptions&>(param_groups_[0].options())
71
+ .max_eval(max_eval_val);
72
+ static_cast<LBFGSOptions&>(*defaults_).max_eval(max_eval_val);
73
+ }
74
+ _numel_cache = std::nullopt;
75
+ }
76
+ explicit LBFGS(std::vector<Tensor> params, LBFGSOptions defaults = {})
77
+ : LBFGS({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {}
78
+
79
+ Tensor step(LossClosure closure) override;
80
+ void save(serialize::OutputArchive& archive) const override;
81
+ void load(serialize::InputArchive& archive) override;
82
+
83
+ private:
84
+ std::optional<int64_t> _numel_cache;
85
+ int64_t _numel();
86
+ Tensor _gather_flat_grad();
87
+ void _add_grad(const double step_size, const Tensor& update);
88
+ std::tuple<double, Tensor> _directional_evaluate(
89
+ const LossClosure& closure,
90
+ const std::vector<Tensor>& x,
91
+ double t,
92
+ const Tensor& d);
93
+ void _set_param(const std::vector<Tensor>& params_data);
94
+ std::vector<Tensor> _clone_param();
95
+
96
+ template <typename Self, typename Archive>
97
+ static void serialize(Self& self, Archive& archive) {
98
+ _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(LBFGS);
99
+ }
100
+ };
101
+ } // namespace torch::optim
102
+
103
+ #else
104
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
105
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/optimizer.h ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/flat_hash_map.h>
7
+
8
+ #include <torch/arg.h>
9
+ #include <torch/csrc/Export.h>
10
+
11
+ #include <algorithm>
12
+ #include <functional>
13
+ #include <iterator>
14
+ #include <memory>
15
+ #include <string>
16
+ #include <vector>
17
+
18
+ // Forward declarations confuse Doxygen
19
+ #ifndef DOXYGEN_SHOULD_SKIP_THIS
20
+ namespace at {
21
+ class Tensor;
22
+ } // namespace at
23
+
24
+ namespace torch {
25
+ using at::Tensor;
26
+ namespace serialize {
27
+ class OutputArchive;
28
+ class InputArchive;
29
+ } // namespace serialize
30
+ } // namespace torch
31
+ #endif // DOXYGEN_SHOULD_SKIP_THIS
32
+
33
+ namespace torch::optim {
34
+
35
+ class TORCH_API OptimizerParamState {
36
+ public:
37
+ OptimizerParamState() = default;
38
+ OptimizerParamState(const OptimizerParamState&) = default;
39
+ OptimizerParamState& operator=(const OptimizerParamState&) = default;
40
+ OptimizerParamState(OptimizerParamState&&) noexcept = default;
41
+ OptimizerParamState& operator=(OptimizerParamState&&) noexcept = default;
42
+ virtual std::unique_ptr<OptimizerParamState> clone() const;
43
+ virtual void serialize(torch::serialize::InputArchive& archive);
44
+ virtual void serialize(torch::serialize::OutputArchive& archive) const;
45
+ virtual ~OptimizerParamState() = default;
46
+ };
47
+
48
+ template <typename Derived>
49
+ class OptimizerCloneableParamState : public OptimizerParamState {
50
+ std::unique_ptr<OptimizerParamState> clone() const override {
51
+ return std::make_unique<Derived>(static_cast<const Derived&>(*this));
52
+ }
53
+ };
54
+
55
+ class TORCH_API OptimizerOptions {
56
+ public:
57
+ OptimizerOptions() = default;
58
+ OptimizerOptions(const OptimizerOptions&) = default;
59
+ OptimizerOptions& operator=(const OptimizerOptions&) = default;
60
+ OptimizerOptions(OptimizerOptions&&) noexcept = default;
61
+ OptimizerOptions& operator=(OptimizerOptions&&) noexcept = default;
62
+ virtual std::unique_ptr<OptimizerOptions> clone() const;
63
+ virtual void serialize(torch::serialize::InputArchive& archive);
64
+ virtual void serialize(torch::serialize::OutputArchive& archive) const;
65
+ virtual ~OptimizerOptions() = default;
66
+ virtual double get_lr() const;
67
+ virtual void set_lr(const double lr);
68
+ };
69
+
70
+ template <typename Derived>
71
+ class OptimizerCloneableOptions : public OptimizerOptions {
72
+ private:
73
+ std::unique_ptr<OptimizerOptions> clone() const override {
74
+ return std::make_unique<Derived>(static_cast<const Derived&>(*this));
75
+ }
76
+ };
77
+
78
+ /// Stores parameters in the param_group and stores a pointer to the
79
+ /// OptimizerOptions
80
+ class TORCH_API OptimizerParamGroup {
81
+ public:
82
+ // NOTE: In order to store `OptimizerParamGroup` in a `std::vector`, it has to
83
+ // be copy-constructible.
84
+ OptimizerParamGroup(const OptimizerParamGroup& param_group)
85
+ : params_(param_group.params()),
86
+ options_(
87
+ param_group.has_options() ? param_group.options().clone()
88
+ : nullptr) {}
89
+ OptimizerParamGroup(OptimizerParamGroup&& param_group) = default;
90
+ OptimizerParamGroup(std::vector<Tensor> params)
91
+ : params_(std::move(params)) {}
92
+ OptimizerParamGroup(
93
+ std::vector<Tensor> params,
94
+ std::unique_ptr<OptimizerOptions> options)
95
+ : params_(std::move(params)), options_(std::move(options)) {}
96
+
97
+ OptimizerParamGroup& operator=(const OptimizerParamGroup& param_group) =
98
+ delete;
99
+ OptimizerParamGroup& operator=(OptimizerParamGroup&& param_group) noexcept =
100
+ default;
101
+ ~OptimizerParamGroup() = default;
102
+ bool has_options() const;
103
+ OptimizerOptions& options();
104
+ const OptimizerOptions& options() const;
105
+ void set_options(std::unique_ptr<OptimizerOptions> options);
106
+ std::vector<Tensor>& params();
107
+ const std::vector<Tensor>& params() const;
108
+
109
+ protected:
110
+ std::vector<Tensor> params_;
111
+ std::unique_ptr<OptimizerOptions> options_;
112
+ };
113
+
114
+ class TORCH_API Optimizer {
115
+ public:
116
+ // The copy constructor is deleted, because the user should use the
117
+ // `state_dict` / `load_state_dict` API to copy an optimizer instead.
118
+ Optimizer(const Optimizer& optimizer) = delete;
119
+ Optimizer(Optimizer&& optimizer) = default;
120
+ Optimizer& operator=(const Optimizer& optimizer) = delete;
121
+ Optimizer& operator=(Optimizer&& optimizer) = default;
122
+
123
+ explicit Optimizer(
124
+ const std::vector<OptimizerParamGroup>& param_groups,
125
+ std::unique_ptr<OptimizerOptions> defaults)
126
+ : defaults_(std::move(defaults)) {
127
+ for (const auto& param_group : param_groups) {
128
+ add_param_group(param_group);
129
+ }
130
+ }
131
+
132
+ /// Constructs the `Optimizer` from a vector of parameters.
133
+ explicit Optimizer(
134
+ std::vector<Tensor> parameters,
135
+ std::unique_ptr<OptimizerOptions> defaults)
136
+ : Optimizer(
137
+ {OptimizerParamGroup(std::move(parameters))},
138
+ std::move(defaults)) {}
139
+
140
+ /// Adds the given param_group to the optimizer's param_group list.
141
+ void add_param_group(const OptimizerParamGroup& param_group);
142
+
143
+ virtual ~Optimizer() = default;
144
+
145
+ using LossClosure = std::function<Tensor()>;
146
+ /// A loss function closure, which is expected to return the loss value.
147
+ virtual Tensor step(LossClosure closure = nullptr) = 0;
148
+
149
+ /// Adds the given vector of parameters to the optimizer's parameter list.
150
+ void add_parameters(const std::vector<Tensor>& parameters);
151
+
152
+ /// Zeros out the gradients of all parameters.
153
+ void zero_grad(bool set_to_none = true);
154
+
155
+ /// Provides a const reference to the parameters in the first param_group this
156
+ /// optimizer holds.
157
+ const std::vector<Tensor>& parameters() const noexcept;
158
+
159
+ /// Provides a reference to the parameters in the first param_group this
160
+ /// optimizer holds.
161
+ std::vector<Tensor>& parameters() noexcept;
162
+
163
+ /// Returns the number of parameters referenced by the optimizer.
164
+ size_t size() const noexcept;
165
+
166
+ OptimizerOptions& defaults() noexcept;
167
+
168
+ const OptimizerOptions& defaults() const noexcept;
169
+
170
+ /// Provides a reference to the param_groups this optimizer holds.
171
+ std::vector<OptimizerParamGroup>& param_groups() noexcept;
172
+
173
+ /// Provides a const reference to the param_groups this optimizer holds.
174
+ const std::vector<OptimizerParamGroup>& param_groups() const noexcept;
175
+
176
+ /// Provides a reference to the state this optimizer holds
177
+ ska::flat_hash_map<void*, std::unique_ptr<OptimizerParamState>>&
178
+ state() noexcept;
179
+
180
+ /// Provides a const reference to the state this optimizer holds
181
+ const ska::flat_hash_map<void*, std::unique_ptr<OptimizerParamState>>& state()
182
+ const noexcept;
183
+
184
+ /// Serializes the optimizer state into the given `archive`.
185
+ virtual void save(serialize::OutputArchive& archive) const;
186
+
187
+ /// Deserializes the optimizer state from the given `archive`.
188
+ virtual void load(serialize::InputArchive& archive);
189
+
190
+ protected:
191
+ std::vector<OptimizerParamGroup> param_groups_;
192
+ ska::flat_hash_map<void*, std::unique_ptr<OptimizerParamState>> state_;
193
+ std::unique_ptr<OptimizerOptions> defaults_;
194
+ };
195
+
196
+ /* How do we decide whether to serialize undefined tensors or
197
+ std::nullopt values into the output archive?
198
+ Answer: we strictly follow the behavior of Python API. To be more specific:
199
+
200
+ For optimizer options:
201
+ a) For undefined tensor: currently no tensor is used as an options argument in
202
+ Python API, so we don't need to worry about it now. b) For std::nullopt value:
203
+ we serialize std::nullopt values into the output archive, to follow the exact
204
+ same behavior as Python API.
205
+
206
+ For optimizer param state:
207
+ a) For undefined tensor: in param state, undefined tensor in C++ impl is
208
+ equivalent to missing key in Python impl. Since we don't serialize missing keys
209
+ in Python API, we skip undefined tensors when serializing the param state. b)
210
+ For std::nullopt value: in param state, std::nullopt value in C++ impl is
211
+ equivalent to missing key in Python impl. Since we don't serialize missing keys
212
+ in Python API, we skip std::nullopt values when serializing the param state. */
213
+
214
+ /// Serializes an `Optimizer` into an `OutputArchive`.
215
+ TORCH_API serialize::OutputArchive& operator<<(
216
+ serialize::OutputArchive& archive,
217
+ const Optimizer& optimizer);
218
+
219
+ /// Deserializes a `Tensor` from an `InputArchive`.
220
+ TORCH_API serialize::InputArchive& operator>>(
221
+ serialize::InputArchive& archive,
222
+ Optimizer& optimizer);
223
+
224
+ } // namespace torch::optim
225
+
226
+ #else
227
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
228
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/rmsprop.h ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/nn/module.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/optim/serialize.h>
7
+ #include <torch/serialize/archive.h>
8
+ #include <torch/types.h>
9
+
10
+ #include <functional>
11
+ #include <memory>
12
+ #include <string>
13
+ #include <utility>
14
+ #include <vector>
15
+
16
+ namespace torch::serialize {
17
+ class OutputArchive;
18
+ class InputArchive;
19
+ } // namespace torch::serialize
20
+
21
+ namespace torch::optim {
22
+
23
+ struct TORCH_API RMSpropOptions
24
+ : public OptimizerCloneableOptions<RMSpropOptions> {
25
+ RMSpropOptions(double lr = 1e-2);
26
+ TORCH_ARG(double, lr) = 1e-2;
27
+ TORCH_ARG(double, alpha) = 0.99;
28
+ TORCH_ARG(double, eps) = 1e-8;
29
+ TORCH_ARG(double, weight_decay) = 0;
30
+ TORCH_ARG(double, momentum) = 0;
31
+ TORCH_ARG(bool, centered) = false;
32
+
33
+ public:
34
+ void serialize(torch::serialize::InputArchive& archive) override;
35
+ void serialize(torch::serialize::OutputArchive& archive) const override;
36
+ TORCH_API friend bool operator==(
37
+ const RMSpropOptions& lhs,
38
+ const RMSpropOptions& rhs);
39
+ double get_lr() const override;
40
+ void set_lr(const double lr) override;
41
+ };
42
+
43
+ struct TORCH_API RMSpropParamState
44
+ : public OptimizerCloneableParamState<RMSpropParamState> {
45
+ TORCH_ARG(int64_t, step) = 0;
46
+ TORCH_ARG(torch::Tensor, square_avg);
47
+ TORCH_ARG(torch::Tensor, momentum_buffer);
48
+ TORCH_ARG(torch::Tensor, grad_avg);
49
+
50
+ public:
51
+ void serialize(torch::serialize::InputArchive& archive) override;
52
+ void serialize(torch::serialize::OutputArchive& archive) const override;
53
+ TORCH_API friend bool operator==(
54
+ const RMSpropParamState& lhs,
55
+ const RMSpropParamState& rhs);
56
+ };
57
+
58
+ class TORCH_API RMSprop : public Optimizer {
59
+ public:
60
+ explicit RMSprop(
61
+ const std::vector<OptimizerParamGroup>& param_groups,
62
+ RMSpropOptions defaults = {})
63
+ : Optimizer(param_groups, std::make_unique<RMSpropOptions>(defaults)) {
64
+ TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
65
+ TORCH_CHECK(defaults.eps() >= 0, "Invalid epsilon value: ", defaults.eps());
66
+ TORCH_CHECK(
67
+ defaults.momentum() >= 0,
68
+ "Invalid momentum value: ",
69
+ defaults.momentum());
70
+ TORCH_CHECK(
71
+ defaults.weight_decay() >= 0,
72
+ "Invalid weight_decay value: ",
73
+ defaults.weight_decay());
74
+ TORCH_CHECK(
75
+ defaults.alpha() >= 0, "Invalid alpha value: ", defaults.alpha());
76
+ }
77
+
78
+ explicit RMSprop(std::vector<Tensor> params, RMSpropOptions defaults = {})
79
+ : RMSprop({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {
80
+ }
81
+
82
+ torch::Tensor step(LossClosure closure = nullptr) override;
83
+ void save(serialize::OutputArchive& archive) const override;
84
+ void load(serialize::InputArchive& archive) override;
85
+
86
+ private:
87
+ template <typename Self, typename Archive>
88
+ static void serialize(Self& self, Archive& archive) {
89
+ _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(RMSprop);
90
+ }
91
+ };
92
+ } // namespace torch::optim
93
+
94
+ #else
95
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
96
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/optim/optimizer.h>
5
+
6
+ #include <torch/csrc/Export.h>
7
+
8
+ namespace torch::optim {
9
+
10
+ class TORCH_API LRScheduler {
11
+ public:
12
+ // This class needs to take a reference of an optimizer from outside such that
13
+ // it can modify its learning rates; due to this the lifetime of said
14
+ // optimizer must be maintained
15
+ LRScheduler(torch::optim::Optimizer& optimizer);
16
+
17
+ virtual ~LRScheduler() = default;
18
+
19
+ void step();
20
+
21
+ protected:
22
+ // A vector of learning rates is calculated and returned from the specific
23
+ // subclass. A vector is returned with each element being a separate learning
24
+ // rate for each param group - although the normal use case would be to return
25
+ // a vector of identical elements.
26
+ virtual std::vector<double> get_lrs() = 0;
27
+
28
+ // Get current learning rates from the optimizer
29
+ std::vector<double> get_current_lrs() const;
30
+
31
+ unsigned step_count_{};
32
+
33
+ private:
34
+ void set_optimizer_lrs(const std::vector<double>& learning_rates);
35
+
36
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
37
+ torch::optim::Optimizer& optimizer_;
38
+ };
39
+ } // namespace torch::optim
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/optim/optimizer.h>
5
+ #include <torch/optim/schedulers/lr_scheduler.h>
6
+
7
+ #include <torch/csrc/Export.h>
8
+
9
+ #include <cmath>
10
+
11
+ namespace torch::optim {
12
+
13
+ class TORCH_API ReduceLROnPlateauScheduler {
14
+ public:
15
+ enum SchedulerMode { min, max };
16
+ enum ThresholdMode { rel, abs };
17
+ ReduceLROnPlateauScheduler(
18
+ Optimizer& optimizer,
19
+ SchedulerMode mode = min,
20
+ float factor = 0.1,
21
+ int patience = 10,
22
+ double threshold = 1e-4,
23
+ ThresholdMode threshold_mode = rel,
24
+ int cooldown = 0,
25
+ const std::vector<float>& min_lr = std::vector<float>(),
26
+ double eps = 1e-8,
27
+ bool verbose = false);
28
+
29
+ virtual ~ReduceLROnPlateauScheduler() = default;
30
+
31
+ void step(float metric);
32
+
33
+ private:
34
+ void reset();
35
+ void reduce_lr(int epoch);
36
+ bool in_cooldown() const;
37
+ bool is_better(float a);
38
+ void init_is_better(
39
+ SchedulerMode mode,
40
+ double threshold,
41
+ ThresholdMode threshold_mode);
42
+
43
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
44
+ Optimizer& optimizer;
45
+ SchedulerMode mode{};
46
+ float mode_worse{};
47
+ float factor;
48
+ int patience;
49
+ double threshold{};
50
+ ThresholdMode threshold_mode{};
51
+ int cooldown{};
52
+ int cooldown_counter{};
53
+ std::vector<float> min_lrs;
54
+ double eps;
55
+ float best{};
56
+ bool verbose;
57
+ int last_epoch{};
58
+ int num_bad_epochs{};
59
+ };
60
+ } // namespace torch::optim
61
+
62
+ #else
63
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
64
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/optim/schedulers/lr_scheduler.h>
5
+
6
+ namespace torch::optim {
7
+
8
+ class TORCH_API StepLR : public LRScheduler {
9
+ public:
10
+ StepLR(
11
+ torch::optim::Optimizer& optimizer,
12
+ const unsigned step_size,
13
+ const double gamma = 0.1);
14
+
15
+ private:
16
+ std::vector<double> get_lrs() override;
17
+
18
+ const unsigned step_size_;
19
+ const double gamma_;
20
+ };
21
+ } // namespace torch::optim
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/serialize.h ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/util/irange.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/serialize/archive.h>
7
+ #include <torch/types.h>
8
+ #include <cstddef>
9
+ #include <cstdint>
10
+ #include <deque>
11
+ #include <string>
12
+ #include <vector>
13
+
14
+ namespace torch::optim {
15
+ namespace detail {
16
+ // Utility function to save state
17
+ template <typename DerivedOptimizerParamState>
18
+ void serialize(
19
+ serialize::OutputArchive& archive,
20
+ const ska::flat_hash_map<void*, std::unique_ptr<OptimizerParamState>>&
21
+ state) {
22
+ for (const auto& item : state) {
23
+ serialize::OutputArchive param_state_archive(archive.compilation_unit());
24
+ std::string tensorimpl_key =
25
+ std::to_string(reinterpret_cast<size_t>(item.first));
26
+ const DerivedOptimizerParamState& curr_state =
27
+ static_cast<const DerivedOptimizerParamState&>(*(item.second));
28
+ curr_state.serialize(param_state_archive);
29
+ archive.write(tensorimpl_key, param_state_archive);
30
+ }
31
+ }
32
+
33
+ // Utility function to load state
34
+ template <typename DerivedOptimizerParamState>
35
+ void serialize(
36
+ serialize::InputArchive& archive,
37
+ ska::flat_hash_map<void*, std::unique_ptr<OptimizerParamState>>& state) {
38
+ std::vector<std::string> tensorimpl_keys = archive.keys();
39
+ for (const std::string& tensorimpl_key : tensorimpl_keys) {
40
+ serialize::InputArchive param_state_archive;
41
+ archive.read(tensorimpl_key, param_state_archive);
42
+ DerivedOptimizerParamState param_state;
43
+ param_state.serialize(param_state_archive);
44
+ // NOLINTNEXTLINE(performance-no-int-to-ptr)
45
+ state[reinterpret_cast<void*>(std::stoull(tensorimpl_key))] =
46
+ std::make_unique<DerivedOptimizerParamState>(param_state);
47
+ }
48
+ }
49
+
50
+ // Utility function to save param_groups
51
+ template <typename DerivedOptimizerParamOptions>
52
+ void serialize(
53
+ serialize::OutputArchive& archive,
54
+ const std::vector<OptimizerParamGroup>& param_groups) {
55
+ archive.write(
56
+ "param_groups/size",
57
+ torch::tensor(static_cast<int64_t>(param_groups.size())));
58
+ for (const auto i : c10::irange(param_groups.size())) {
59
+ serialize::OutputArchive param_group_archive(archive.compilation_unit());
60
+ std::vector<Tensor> params = param_groups[i].params();
61
+ param_group_archive.write(
62
+ "params/size", torch::tensor(static_cast<int64_t>(params.size())));
63
+ for (const auto index : c10::irange(params.size())) {
64
+ param_group_archive.write(
65
+ "params/" + std::to_string(index),
66
+ IValue(std::to_string(
67
+ reinterpret_cast<size_t>(params[index].unsafeGetTensorImpl()))));
68
+ }
69
+ const DerivedOptimizerParamOptions& param_group_options =
70
+ static_cast<const DerivedOptimizerParamOptions&>(
71
+ param_groups[i].options());
72
+ serialize::OutputArchive param_group_options_archive(
73
+ param_group_archive.compilation_unit());
74
+ param_group_options.serialize(param_group_options_archive);
75
+ param_group_archive.write("options", param_group_options_archive);
76
+ archive.write("param_groups/" + std::to_string(i), param_group_archive);
77
+ }
78
+ }
79
+
80
+ // Utility function to load param_groups
81
+ // We take as input vector of pair of string and unique_ptr to optimizer options
82
+ // so that we can retain the state for each param by using the old tensor impl
83
+ // keys (saved during serialization) and map the new tensor impl keys to the
84
+ // correct state for each param
85
+ template <typename DerivedOptimizerParamOptions>
86
+ void serialize(
87
+ serialize::InputArchive& archive,
88
+ std::vector<
89
+ std::pair<std::vector<std::string>, std::unique_ptr<OptimizerOptions>>>&
90
+ param_groups) {
91
+ torch::Tensor param_groups_size_tensor;
92
+ archive.read("param_groups/size", param_groups_size_tensor);
93
+ const int64_t param_groups_size = param_groups_size_tensor.item<int64_t>();
94
+ for (const auto i : c10::irange(param_groups_size)) {
95
+ serialize::InputArchive param_group_archive;
96
+ archive.read("param_groups/" + std::to_string(i), param_group_archive);
97
+ torch::Tensor size_tensor;
98
+ param_group_archive.read("params/size", size_tensor);
99
+ const int64_t size = size_tensor.item<int64_t>();
100
+ std::vector<std::string> params;
101
+ for (const auto index : c10::irange(size)) {
102
+ IValue ivalue;
103
+ param_group_archive.read("params/" + std::to_string(index), ivalue);
104
+ std::string element = ivalue.toStringRef();
105
+ params.emplace_back(element);
106
+ }
107
+ serialize::InputArchive param_group_options_archive;
108
+ param_group_archive.read("options", param_group_options_archive);
109
+ DerivedOptimizerParamOptions param_group_options(0);
110
+ param_group_options.serialize(param_group_options_archive);
111
+ param_groups.emplace_back(std::make_pair(
112
+ params,
113
+ std::make_unique<DerivedOptimizerParamOptions>(param_group_options)));
114
+ }
115
+ }
116
+ } // namespace detail
117
+
118
+ // Note: These functions are all called `serialize()` so they can be called
119
+ // inside a template where the archive type is a template type and can thus be
120
+ // passed such that the appropriate overload is selected.
121
+
122
+ /// Utility function to save a value of `int64_t` type.
123
+ void serialize(
124
+ serialize::OutputArchive& archive,
125
+ const std::string& key,
126
+ const int64_t& value);
127
+
128
+ /// Utility function to load a value of `int64_t` type.
129
+ void serialize(
130
+ serialize::InputArchive& archive,
131
+ const std::string& key,
132
+ int64_t& value);
133
+
134
+ /// Utility function to save a vector of step buffers.
135
+ void serialize(
136
+ serialize::OutputArchive& archive,
137
+ const std::string& key,
138
+ const std::vector<int64_t>& steps);
139
+
140
+ /// Utility function to load a vector of step buffers.
141
+ void serialize(
142
+ serialize::InputArchive& archive,
143
+ const std::string& key,
144
+ std::vector<int64_t>& steps);
145
+
146
+ // Utility function to save state and param_groups
147
+ template <
148
+ typename DerivedOptimizerParamState,
149
+ typename DerivedOptimizerParamOptions>
150
+ void serialize(serialize::OutputArchive& archive, const Optimizer& optimizer) {
151
+ archive.write("pytorch_version", IValue("1.5.0"));
152
+ serialize::OutputArchive state_archive(archive.compilation_unit());
153
+ detail::serialize<DerivedOptimizerParamState>(
154
+ state_archive, optimizer.state());
155
+ archive.write("state", state_archive);
156
+
157
+ serialize::OutputArchive param_groups_archive(archive.compilation_unit());
158
+ detail::serialize<DerivedOptimizerParamOptions>(
159
+ param_groups_archive, optimizer.param_groups());
160
+ archive.write("param_groups", param_groups_archive);
161
+ }
162
+
163
+ // Utility function to load state and param_groups and update state
164
+ template <
165
+ typename DerivedOptimizerParamState,
166
+ typename DerivedOptimizerParamOptions>
167
+ void serialize(serialize::InputArchive& archive, Optimizer& optimizer) {
168
+ IValue pytorch_version;
169
+ archive.read("pytorch_version", pytorch_version);
170
+ TORCH_INTERNAL_ASSERT(pytorch_version.toStringRef() == "1.5.0");
171
+ serialize::InputArchive state_archive;
172
+ archive.read("state", state_archive);
173
+ ska::flat_hash_map<void*, std::unique_ptr<OptimizerParamState>> saved_state;
174
+ detail::serialize<DerivedOptimizerParamState>(state_archive, saved_state);
175
+
176
+ serialize::InputArchive param_groups_archive;
177
+ archive.read("param_groups", param_groups_archive);
178
+ std::vector<
179
+ std::pair<std::vector<std::string>, std::unique_ptr<OptimizerOptions>>>
180
+ saved_param_groups;
181
+ detail::serialize<DerivedOptimizerParamOptions>(
182
+ param_groups_archive, saved_param_groups);
183
+
184
+ // update state and optimizer options
185
+ TORCH_CHECK(
186
+ saved_param_groups.size() == optimizer.param_groups().size(),
187
+ "loaded state dict has a different number of parameter groups");
188
+ for (const auto i : c10::irange(saved_param_groups.size())) {
189
+ std::vector<std::string> param_group_old_keys = saved_param_groups[i].first;
190
+ std::vector<Tensor> params = optimizer.param_groups()[i].params();
191
+ TORCH_CHECK(
192
+ param_group_old_keys.size() == params.size(),
193
+ "loaded state dict contains a parameter group that has a different size than the optimizer's parameter group");
194
+
195
+ for (const auto idx : c10::irange(params.size())) {
196
+ auto param_group_old_key =
197
+ // NOLINTNEXTLINE(performance-no-int-to-ptr)
198
+ reinterpret_cast<void*>(std::stoull(param_group_old_keys[idx]));
199
+ if (saved_state.find(param_group_old_key) != saved_state.end()) {
200
+ optimizer.state()[params[idx].unsafeGetTensorImpl()] =
201
+ std::move(saved_state[param_group_old_key]);
202
+ }
203
+ }
204
+
205
+ auto& saved_options = reinterpret_cast<DerivedOptimizerParamOptions&>(
206
+ *saved_param_groups[i].second);
207
+ auto& current_options = reinterpret_cast<DerivedOptimizerParamOptions&>(
208
+ optimizer.param_groups()[i].options());
209
+ current_options = saved_options;
210
+ }
211
+ }
212
+
213
+ /// Utility function to save a vector of buffers.
214
+ template <typename BufferContainer>
215
+ void serialize(
216
+ serialize::OutputArchive& archive,
217
+ const std::string& key,
218
+ const BufferContainer& buffers) {
219
+ archive.write(
220
+ key + "/size", torch::tensor(static_cast<int64_t>(buffers.size())));
221
+ for (const auto index : c10::irange(buffers.size())) {
222
+ archive.write(
223
+ key + "/" + std::to_string(index), buffers[index], /*is_buffer=*/true);
224
+ }
225
+ }
226
+
227
+ /// Utility function to load a vector of buffers.
228
+ template <typename BufferContainer>
229
+ void serialize(
230
+ serialize::InputArchive& archive,
231
+ const std::string& key,
232
+ BufferContainer& buffers) {
233
+ buffers.clear();
234
+ torch::Tensor size_tensor;
235
+ archive.read(key + "/size", size_tensor);
236
+ const size_t size = size_tensor.item<int64_t>();
237
+ for (const auto index : c10::irange(size)) {
238
+ buffers.emplace_back();
239
+ archive.read(
240
+ key + "/" + std::to_string(index), buffers.back(), /*is_buffer=*/true);
241
+ }
242
+ }
243
+
244
+ template <typename T>
245
+ c10::List<T> deque_to_list(const std::deque<T>& dq) {
246
+ c10::List<T> list;
247
+ list.reserve(dq.size());
248
+ for (const auto& e : dq) {
249
+ list.emplace_back(e);
250
+ }
251
+ return list;
252
+ }
253
+
254
+ template <typename T>
255
+ std::deque<T> list_to_deque(const c10::List<T>& list) {
256
+ std::deque<T> dq;
257
+ for (const auto& e : list) {
258
+ dq.emplace_back(e);
259
+ }
260
+ return dq;
261
+ }
262
+
263
+ #define _TORCH_OPTIM_SERIALIZE(name) \
264
+ torch::optim::serialize(archive, #name, self.name)
265
+
266
+ #define _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(OptimizerName) \
267
+ torch::optim::serialize<OptimizerName##ParamState, OptimizerName##Options>( \
268
+ archive, self)
269
+
270
+ #define _TORCH_OPTIM_SERIALIZE_TORCH_ARG(name) \
271
+ { \
272
+ auto ivalue = torch::IValue(name()); \
273
+ /* do not serialize if name is an undefined tensor*/ \
274
+ if (!(ivalue.isTensor() && \
275
+ ivalue.unsafeToTensorImpl() == \
276
+ at::UndefinedTensorImpl::singleton())) { \
277
+ archive.write(#name, ivalue); \
278
+ } \
279
+ }
280
+
281
+ #define _TORCH_OPTIM_SERIALIZE_TORCH_ARG_DEQUE(name) \
282
+ { \
283
+ c10::IValue ivalue = torch::IValue(deque_to_list(name())); \
284
+ archive.write(#name, ivalue); \
285
+ }
286
+
287
+ #define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG(T, name) \
288
+ { \
289
+ c10::IValue ivalue; \
290
+ bool exists = archive.try_read(#name, ivalue); \
291
+ if (exists) { \
292
+ name(ivalue.to<T>()); \
293
+ } else { \
294
+ constexpr bool is_tensor_type = std::is_base_of_v<torch::Tensor, T>; \
295
+ TORCH_INTERNAL_ASSERT(is_tensor_type); \
296
+ } \
297
+ }
298
+
299
+ #define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_OPTIONAL(T, name) \
300
+ { \
301
+ c10::IValue ivalue; \
302
+ bool exists = archive.try_read(#name, ivalue); \
303
+ if (exists) { \
304
+ name(ivalue.toOptional<T>()); \
305
+ } \
306
+ }
307
+
308
+ #define _TORCH_OPTIM_DESERIALIZE_TORCH_ARG_DEQUE(T, name) \
309
+ { \
310
+ c10::IValue ivalue; \
311
+ archive.read(#name, ivalue); \
312
+ auto list = ivalue.to<c10::List<T::value_type>>(); \
313
+ name(list_to_deque(list)); \
314
+ }
315
+
316
+ } // namespace torch::optim
317
+
318
+ #else
319
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
320
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/optim/sgd.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/nn/module.h>
5
+ #include <torch/optim/optimizer.h>
6
+ #include <torch/optim/serialize.h>
7
+ #include <torch/serialize/archive.h>
8
+ #include <torch/types.h>
9
+
10
+ #include <cstddef>
11
+ #include <utility>
12
+ #include <vector>
13
+
14
+ namespace torch::serialize {
15
+ class OutputArchive;
16
+ class InputArchive;
17
+ } // namespace torch::serialize
18
+
19
+ namespace torch::optim {
20
+
21
+ struct TORCH_API SGDOptions : public OptimizerCloneableOptions<SGDOptions> {
22
+ SGDOptions(double lr);
23
+ TORCH_ARG(double, lr);
24
+ TORCH_ARG(double, momentum) = 0;
25
+ TORCH_ARG(double, dampening) = 0;
26
+ TORCH_ARG(double, weight_decay) = 0;
27
+ TORCH_ARG(bool, nesterov) = false;
28
+
29
+ public:
30
+ void serialize(torch::serialize::InputArchive& archive) override;
31
+ void serialize(torch::serialize::OutputArchive& archive) const override;
32
+ TORCH_API friend bool operator==(
33
+ const SGDOptions& lhs,
34
+ const SGDOptions& rhs);
35
+ double get_lr() const override;
36
+ void set_lr(const double lr) override;
37
+ };
38
+
39
+ struct TORCH_API SGDParamState
40
+ : public OptimizerCloneableParamState<SGDParamState> {
41
+ TORCH_ARG(torch::Tensor, momentum_buffer);
42
+
43
+ public:
44
+ void serialize(torch::serialize::InputArchive& archive) override;
45
+ void serialize(torch::serialize::OutputArchive& archive) const override;
46
+ TORCH_API friend bool operator==(
47
+ const SGDParamState& lhs,
48
+ const SGDParamState& rhs);
49
+ };
50
+
51
+ class TORCH_API SGD : public Optimizer {
52
+ public:
53
+ explicit SGD(
54
+ const std::vector<OptimizerParamGroup>& param_groups,
55
+ SGDOptions defaults)
56
+ : Optimizer(param_groups, std::make_unique<SGDOptions>(defaults)) {
57
+ TORCH_CHECK(defaults.lr() >= 0, "Invalid learning rate: ", defaults.lr());
58
+ TORCH_CHECK(
59
+ defaults.momentum() >= 0,
60
+ "Invalid momentum value: ",
61
+ defaults.momentum());
62
+ TORCH_CHECK(
63
+ defaults.weight_decay() >= 0,
64
+ "Invalid weight_decay value: ",
65
+ defaults.weight_decay());
66
+ TORCH_CHECK(
67
+ !defaults.nesterov() ||
68
+ (defaults.momentum() > 0 && defaults.dampening() == 0),
69
+ "Nesterov momentum requires a momentum and zero dampening");
70
+ }
71
+
72
+ explicit SGD(std::vector<Tensor> params, SGDOptions defaults)
73
+ : SGD({OptimizerParamGroup(std::move(params))}, std::move(defaults)) {}
74
+
75
+ torch::Tensor step(LossClosure closure = nullptr) override;
76
+
77
+ void save(serialize::OutputArchive& archive) const override;
78
+ void load(serialize::InputArchive& archive) override;
79
+
80
+ private:
81
+ template <typename Self, typename Archive>
82
+ static void serialize(Self& self, Archive& archive) {
83
+ _TORCH_OPTIM_SERIALIZE_WITH_TEMPLATE_ARG(SGD);
84
+ }
85
+ };
86
+ } // namespace torch::optim
87
+
88
+ #else
89
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
90
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/python/init.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/utils/python_stub.h>
5
+
6
+ namespace torch::python {
7
+ /// Initializes Python bindings for the C++ frontend.
8
+ void init_bindings(PyObject* module);
9
+ } // namespace torch::python
10
+
11
+ #else
12
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
13
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/archive.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/serialize/input-archive.h>
5
+ #include <torch/serialize/output-archive.h>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/input-archive.h ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/Device.h>
5
+ #include <torch/csrc/Export.h>
6
+ #include <torch/csrc/jit/api/module.h>
7
+ #include <torch/types.h>
8
+ #include <optional>
9
+
10
+ #include <iosfwd>
11
+ #include <memory>
12
+ #include <string>
13
+ #include <utility>
14
+
15
+ namespace at {
16
+ class Tensor;
17
+ } // namespace at
18
+
19
+ namespace torch {
20
+ using at::Tensor;
21
+ namespace jit {
22
+ struct Module;
23
+ } // namespace jit
24
+ } // namespace torch
25
+
26
+ namespace torch::serialize {
27
+
28
+ /// A recursive representation of tensors that can be deserialized from a file
29
+ /// or stream. In most cases, users should not have to interact with this class,
30
+ /// and should instead use `torch::load`.
31
+ class TORCH_API InputArchive final {
32
+ public:
33
+ /// Default-constructs the `InputArchive`.
34
+ InputArchive();
35
+
36
+ // Move is allowed.
37
+ InputArchive(InputArchive&&) = default;
38
+ InputArchive& operator=(InputArchive&&) = default;
39
+
40
+ // Copy is disallowed.
41
+ InputArchive(InputArchive&) = delete;
42
+ InputArchive& operator=(InputArchive&) = delete;
43
+
44
+ ~InputArchive() = default;
45
+
46
+ /// Reads an `IValue` associated with a given `key`.
47
+ void read(const std::string& key, c10::IValue& ivalue);
48
+
49
+ /// Reads an `IValue` associated with a given `key`. If there is no `IValue`
50
+ /// associated with the `key`, this returns false, otherwise it returns true.
51
+ bool try_read(const std::string& key, c10::IValue& ivalue);
52
+
53
+ /// Reads a `tensor` associated with a given `key`. If there is no `tensor`
54
+ /// associated with the `key`, this returns false, otherwise it returns true.
55
+ /// If the tensor is expected to be a buffer (not differentiable), `is_buffer`
56
+ /// must be `true`.
57
+ bool try_read(const std::string& key, Tensor& tensor, bool is_buffer = false);
58
+
59
+ /// Reads a `tensor` associated with a given `key`.
60
+ /// If the tensor is expected to be a buffer (not differentiable), `is_buffer`
61
+ /// must be `true`.
62
+ void read(const std::string& key, Tensor& tensor, bool is_buffer = false);
63
+
64
+ /// Reads a `InputArchive` associated with a given `key`. If there is no
65
+ /// `InputArchive` associated with the `key`, this returns false, otherwise
66
+ /// it returns true.
67
+ bool try_read(const std::string& key, InputArchive& archive);
68
+
69
+ /// Reads an `InputArchive` associated with a given `key`.
70
+ /// The archive can thereafter be used for further deserialization of the
71
+ /// nested data.
72
+ void read(const std::string& key, InputArchive& archive);
73
+
74
+ /// Loads the `InputArchive` from a serialized representation stored in the
75
+ /// file at `filename`. Storage are remapped using device option. If device
76
+ /// is not specified, the module is loaded to the original device.
77
+ void load_from(
78
+ const std::string& filename,
79
+ std::optional<torch::Device> device = std::nullopt);
80
+
81
+ /// Loads the `InputArchive` from a serialized representation stored in the
82
+ /// given `stream`. Storage are remapped using device option. If device
83
+ /// is not specified, the module is loaded to the original device.
84
+ void load_from(
85
+ std::istream& stream,
86
+ std::optional<torch::Device> device = std::nullopt);
87
+
88
+ // Loads given the specified flat array.
89
+ void load_from(
90
+ const char* data,
91
+ size_t size,
92
+ std::optional<torch::Device> device = std::nullopt);
93
+
94
+ // Loads given the specified read and size functions.
95
+ void load_from(
96
+ const std::function<size_t(uint64_t pos, void* buf, size_t nbytes)>&
97
+ read_func,
98
+ const std::function<size_t(void)>& size_func,
99
+ std::optional<torch::Device> device = std::nullopt);
100
+
101
+ // Returns the vector of keys in the input archive.
102
+ std::vector<std::string> keys();
103
+
104
+ /// Forwards all arguments to `read()`.
105
+ /// Useful for generic code that can be reused for both `InputArchive` and
106
+ /// `OutputArchive` (where `operator()` forwards to `write()`).
107
+ template <typename... Ts>
108
+ void operator()(Ts&&... ts) {
109
+ read(std::forward<Ts>(ts)...);
110
+ }
111
+
112
+ private:
113
+ jit::Module module_;
114
+ std::string hierarchy_prefix_;
115
+ };
116
+ } // namespace torch::serialize
117
+
118
+ #else
119
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
120
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/output-archive.h ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/jit/api/module.h>
6
+
7
+ #include <iosfwd>
8
+ #include <memory>
9
+ #include <string>
10
+ #include <utility>
11
+
12
+ namespace at {
13
+ class Tensor;
14
+ } // namespace at
15
+
16
+ namespace torch {
17
+ using at::Tensor;
18
+ namespace jit {
19
+ struct Module;
20
+ } // namespace jit
21
+ } // namespace torch
22
+
23
+ namespace torch::serialize {
24
+ class TORCH_API OutputArchive final {
25
+ public:
26
+ explicit OutputArchive(std::shared_ptr<jit::CompilationUnit> cu);
27
+ explicit OutputArchive()
28
+ : cu_(std::make_shared<jit::CompilationUnit>()),
29
+ module_("__torch__.Module", cu_) {}
30
+
31
+ // Move is allowed.
32
+ OutputArchive(OutputArchive&&) = default;
33
+ OutputArchive& operator=(OutputArchive&&) = default;
34
+
35
+ // Copy is disallowed.
36
+ OutputArchive(OutputArchive&) = delete;
37
+ OutputArchive& operator=(OutputArchive&) = delete;
38
+
39
+ std::shared_ptr<jit::CompilationUnit> compilation_unit() const {
40
+ return cu_;
41
+ }
42
+
43
+ /// Writes an `IValue` to the `OutputArchive`.
44
+ void write(const std::string& key, const c10::IValue& ivalue);
45
+
46
+ /// Writes a `(key, tensor)` pair to the `OutputArchive`, and marks it as
47
+ /// being or not being a buffer (non-differentiable tensor).
48
+ void write(
49
+ const std::string& key,
50
+ const Tensor& tensor,
51
+ bool is_buffer = false);
52
+
53
+ /// Writes a nested `OutputArchive` under the given `key` to this
54
+ /// `OutputArchive`.
55
+ void write(const std::string& key, OutputArchive& nested_archive);
56
+
57
+ /// Saves the `OutputArchive` into a serialized representation in a file at
58
+ /// `filename`.
59
+ void save_to(const std::string& filename);
60
+
61
+ /// Saves the `OutputArchive` into a serialized representation into the given
62
+ /// `stream`.
63
+ void save_to(std::ostream& stream);
64
+
65
+ /// Saves the `OutputArchive` into a serialized representation using the
66
+ /// given writer function.
67
+ void save_to(const std::function<size_t(const void*, size_t)>& func);
68
+
69
+ /// Forwards all arguments to `write()`.
70
+ /// Useful for generic code that can be reused for both `OutputArchive` and
71
+ /// `InputArchive` (where `operator()` forwards to `read()`).
72
+ template <typename... Ts>
73
+ void operator()(Ts&&... ts) {
74
+ write(std::forward<Ts>(ts)...);
75
+ }
76
+
77
+ private:
78
+ std::shared_ptr<jit::CompilationUnit> cu_;
79
+ jit::Module module_;
80
+ };
81
+ } // namespace torch::serialize
82
+
83
+ #else
84
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
85
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/api/include/torch/serialize/tensor.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/serialize/archive.h>
5
+ #include <torch/types.h>
6
+
7
+ namespace torch {
8
+ inline serialize::OutputArchive& operator<<(
9
+ serialize::OutputArchive& archive,
10
+ const Tensor& tensor) {
11
+ archive.write("0", tensor);
12
+ return archive;
13
+ }
14
+
15
+ inline serialize::InputArchive& operator>>(
16
+ serialize::InputArchive& archive,
17
+ Tensor& tensor) {
18
+ archive.read("0", tensor);
19
+ return archive;
20
+ }
21
+ } // namespace torch
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/FunctionsManual.h ADDED
@@ -0,0 +1,1158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // NB: Must be at the top of file to avoid including the deprecated "math.h".
5
+ // https://stackoverflow.com/questions/6563810/m-pi-works-with-math-h-but-not-with-cmath-in-visual-studio
6
+ #ifdef _MSC_VER
7
+ #ifndef _USE_MATH_DEFINES
8
+ #define _USE_MATH_DEFINES
9
+ #endif
10
+ #include <cmath>
11
+ #endif
12
+
13
+ #include <ATen/ATen.h>
14
+ #include <torch/csrc/autograd/generated/Functions.h>
15
+
16
+ namespace torch::autograd::generated::details {
17
+
18
+ extern const char* kCudnnDoubleBackwardMsg;
19
+
20
+ // A simple way to imperatively compute index ranges for slots
21
+ // that have been flattened
22
+ struct TORCH_API IndexRangeGenerator {
23
+ IndexRange range(size_t range_size) {
24
+ i += range_size;
25
+ return {i - range_size, i};
26
+ }
27
+ size_t size() {
28
+ return i;
29
+ }
30
+
31
+ private:
32
+ size_t i = 0;
33
+ };
34
+
35
+ TORCH_API Tensor toNonOptFwGrad(const std::optional<Tensor>& t);
36
+ TORCH_API Tensor toNonOptPrimal(const std::optional<Tensor>& t);
37
+ TORCH_API Tensor toNonOptTensor(const std::optional<Tensor>& t);
38
+
39
+ inline std::optional<Tensor> wrap_opt_if(const Tensor& t, const bool cond) {
40
+ using OptTensor = std::optional<Tensor>;
41
+ return cond ? OptTensor(t) : static_cast<OptTensor>(std::nullopt);
42
+ }
43
+
44
+ TORCH_API Tensor
45
+ apply_loss_reduction(const Tensor& unreduced, int64_t reduction);
46
+ TORCH_API bool any_variable_defined(const variable_list& variables);
47
+ TORCH_API void update_wrapped_number(Tensor& input, Tensor& output);
48
+ TORCH_API void copy_range(
49
+ variable_list& out,
50
+ IndexRange range,
51
+ const at::Tensor& t);
52
+ TORCH_API void copy_range(
53
+ variable_list& out,
54
+ IndexRange range,
55
+ at::ArrayRef<at::Tensor> t);
56
+ TORCH_API at::Tensor copysign_tensor_self_backward(
57
+ const Tensor& grad,
58
+ const Tensor& self,
59
+ const Tensor& result);
60
+ TORCH_API at::Tensor not_implemented(const char* name, const char* reason = "");
61
+ TORCH_API std::vector<Tensor> not_implemented_list(
62
+ const char* name,
63
+ const char* reason = "");
64
+ at::Tensor handle_r_to_c(ScalarType self_st, Tensor gradient_result);
65
+ at::Tensor maybe_multiply(const at::Tensor& t, const at::Scalar& s);
66
+ int64_t _safe_size(IntArrayRef sizes, IntArrayRef dim);
67
+ Tensor restore_reduced_dims(
68
+ const Tensor& output,
69
+ IntArrayRef dims,
70
+ bool keepdim);
71
+ Tensor scale_grad_by_count(
72
+ const Tensor& grad,
73
+ const Tensor& mask,
74
+ IntArrayRef dims);
75
+ at::Tensor norm_backward(
76
+ const at::Tensor& grad,
77
+ const at::Tensor& self,
78
+ const std::optional<at::Scalar>& p_,
79
+ const at::Tensor& norm);
80
+ at::Tensor norm_backward(
81
+ at::Tensor grad,
82
+ const at::Tensor& self,
83
+ const std::optional<at::Scalar>& p_,
84
+ at::Tensor norm,
85
+ at::IntArrayRef dim,
86
+ bool keepdim);
87
+ Tensor norm_jvp(
88
+ const Tensor& self_p,
89
+ const Tensor& self_t,
90
+ const std::optional<Scalar>& p_,
91
+ Tensor norm,
92
+ IntArrayRef dim,
93
+ bool keepdim);
94
+ Tensor norm_jvp(
95
+ const Tensor& grad,
96
+ const Tensor& self,
97
+ const std::optional<Scalar>& p_,
98
+ Tensor norm);
99
+ Tensor _nested_from_padded_backward(
100
+ const Tensor& grad,
101
+ const Tensor& input,
102
+ const bool do_transform_0213);
103
+ std::tuple<Tensor, Tensor, Tensor> linear_double_backward(
104
+ const variable_list& grads,
105
+ const Tensor& self,
106
+ const Tensor& grad_output,
107
+ const Tensor& weight);
108
+ Tensor linalg_vector_norm_jvp(
109
+ const Tensor& self_p,
110
+ const Tensor& self_t,
111
+ const Scalar& scalar_ord,
112
+ Tensor norm,
113
+ const at::OptionalIntArrayRef& opt_dim,
114
+ bool keepdim);
115
+ at::Tensor linalg_vector_norm_backward(
116
+ at::Tensor grad,
117
+ const at::Tensor& self,
118
+ const at::Scalar& ord,
119
+ at::Tensor norm,
120
+ const at::OptionalIntArrayRef& opt_dim,
121
+ bool keepdim);
122
+ at::Tensor pow_backward(
123
+ at::Tensor grad,
124
+ const at::Tensor& self,
125
+ const at::Scalar& exponent_);
126
+ at::Tensor pow_backward_self(
127
+ const at::Tensor& grad,
128
+ const at::Tensor& self,
129
+ const at::Tensor& exponent);
130
+ at::Tensor pow_backward_exponent(
131
+ const at::Tensor& grad,
132
+ const at::Tensor& self,
133
+ const at::Tensor& exponent,
134
+ const at::Tensor& result);
135
+ at::Tensor pow_backward_exponent(
136
+ const at::Tensor& grad,
137
+ const at::Scalar& base,
138
+ const at::Tensor& exponent,
139
+ const at::Tensor& result);
140
+ at::Tensor angle_backward(const at::Tensor& grad, const at::Tensor& self);
141
+ template <typename T>
142
+ at::Tensor mul_tensor_backward(const Tensor& grad, T other, ScalarType self_st);
143
+ template <typename T>
144
+ at::Tensor div_tensor_self_backward(
145
+ const Tensor& grad,
146
+ T other,
147
+ ScalarType self_st,
148
+ const std::optional<std::string_view>& rounding_mode = std::nullopt);
149
+ at::Tensor div_tensor_other_backward(
150
+ const Tensor& grad,
151
+ const Tensor& self,
152
+ const Tensor& other,
153
+ const std::optional<std::string_view>& rounding_mode = std::nullopt);
154
+ at::Tensor mvlgamma_backward(
155
+ const at::Tensor& grad,
156
+ const at::Tensor& self,
157
+ int64_t p);
158
+ at::Tensor permute_backwards(const at::Tensor& grad, at::IntArrayRef fwd_dims);
159
+ at::Tensor rad2deg_backward(const at::Tensor& grad);
160
+ at::Tensor deg2rad_backward(const at::Tensor& grad);
161
+ at::Tensor unsqueeze_multiple(
162
+ const at::Tensor& t,
163
+ at::OptionalIntArrayRef opt_dim,
164
+ size_t n_dims);
165
+ at::Tensor sum_backward(
166
+ const at::Tensor& grad,
167
+ at::SymIntArrayRef sizes,
168
+ at::OptionalIntArrayRef opt_dims,
169
+ bool keepdim);
170
+ at::Tensor sum_backward(
171
+ const at::Tensor& grad,
172
+ c10::SymIntArrayRef sizes,
173
+ c10::IntArrayRef dims,
174
+ bool keepdim);
175
+ at::Tensor nansum_backward(
176
+ const at::Tensor& grad,
177
+ const at::Tensor& self,
178
+ at::OptionalIntArrayRef dims,
179
+ bool keepdim);
180
+ std::vector<int64_t> reverse_list(const at::IntArrayRef list);
181
+ std::vector<c10::SymInt> reverse_list_symint(const c10::SymIntArrayRef list);
182
+ at::Tensor reverse_dim(const at::Tensor& t, int64_t dim);
183
+ at::Tensor prod_safe_zeros_backward(
184
+ const at::Tensor& grad,
185
+ const at::Tensor& inp,
186
+ int64_t dim);
187
+ at::Tensor prod_backward(
188
+ const at::Tensor& grad,
189
+ const at::Tensor& input,
190
+ const at::Tensor& result);
191
+ at::Tensor prod_backward(
192
+ at::Tensor grad,
193
+ const at::Tensor& input,
194
+ at::Tensor result,
195
+ int64_t dim,
196
+ bool keepdim);
197
+ at::Tensor solve_jvp(
198
+ const Tensor& X,
199
+ const Tensor& A,
200
+ const Tensor& dA,
201
+ const Tensor& dB);
202
+ at::Tensor solve_backward_self(
203
+ const at::Tensor& grad,
204
+ const at::Tensor& self,
205
+ const at::Tensor& A);
206
+ at::Tensor solve_backward_A(
207
+ const at::Tensor& grad,
208
+ const at::Tensor& self,
209
+ const at::Tensor& A,
210
+ const at::Tensor& solution);
211
+ at::Tensor cumsum_backward(const at::Tensor& grad, int64_t dim);
212
+ at::Tensor logsumexp_backward(
213
+ at::Tensor grad,
214
+ const at::Tensor& self,
215
+ at::Tensor result,
216
+ at::IntArrayRef dim,
217
+ bool keepdim);
218
+ at::Tensor logsumexp_jvp(
219
+ const at::Tensor& self_p,
220
+ const at::Tensor& self_t,
221
+ IntArrayRef dim,
222
+ bool keepdim);
223
+ at::Tensor safe_logsumexp_jvp(
224
+ const at::Tensor& self_p,
225
+ const at::Tensor& self_t,
226
+ IntArrayRef dim,
227
+ bool keepdim);
228
+ at::Tensor logcumsumexp_backward(
229
+ at::Tensor grad,
230
+ const at::Tensor& self,
231
+ const at::Tensor& result,
232
+ int64_t dim);
233
+ at::Tensor logcumsumexp_jvp(
234
+ const at::Tensor& self_p,
235
+ const at::Tensor& self_t,
236
+ int64_t dim);
237
+ at::Tensor unbind_backward(const variable_list& grads, int64_t dim);
238
+ at::Tensor unbind_backward_nested(
239
+ const variable_list& grads,
240
+ const Tensor& nt_sizes,
241
+ int64_t dim,
242
+ const at::TensorOptions& options);
243
+ at::Tensor unbind_backward_nested_jagged(
244
+ const variable_list& grads,
245
+ const Tensor& self,
246
+ int64_t dim);
247
+ at::Tensor unsqueeze_to(const at::Tensor& self, c10::SymIntArrayRef sym_sizes);
248
+ at::Tensor unsqueeze_to(
249
+ const at::Tensor& self,
250
+ int64_t dim,
251
+ c10::SymIntArrayRef sym_sizes);
252
+ at::Tensor unsqueeze_to(
253
+ const at::Tensor& self,
254
+ IntArrayRef dim,
255
+ c10::SymIntArrayRef sym_sizes);
256
+ std::vector<at::Tensor> cat_tensors_backward(
257
+ const at::Tensor& grad,
258
+ const std::vector<std::vector<c10::SymInt>>& sizes,
259
+ const std::vector<ScalarType>& dtypes,
260
+ int64_t dim);
261
+ std::vector<at::Tensor> stack_tensors_backward(
262
+ const at::Tensor& grad,
263
+ int64_t dim,
264
+ const std::vector<ScalarType>& dtypes);
265
+ std::vector<at::Tensor> block_diag_backward(
266
+ const at::Tensor& grad,
267
+ const std::vector<std::vector<int64_t>>& sizes,
268
+ const std::vector<ScalarType>& dtypes);
269
+ at::Tensor clamp_backward(
270
+ const at::Tensor& grad,
271
+ const at::Tensor& self,
272
+ const std::optional<at::Scalar>& min,
273
+ const std::optional<at::Scalar>& max);
274
+ at::Tensor clamp_backward(
275
+ const at::Tensor& grad,
276
+ const at::Tensor& self,
277
+ const at::Tensor& min,
278
+ const at::Tensor& max);
279
+ std::tuple<at::Tensor, at::Tensor> clamp_backward_min_max(
280
+ const at::Tensor& grad,
281
+ const at::Tensor& self,
282
+ const at::Tensor& min,
283
+ const at::Tensor& max,
284
+ const std::array<bool, 2>& /*grad_input_mask*/);
285
+ at::Tensor clamp_jvp(
286
+ const Tensor& self_p,
287
+ const Tensor& self_t,
288
+ const Tensor& min_p,
289
+ const Tensor& min_t,
290
+ const Tensor& max_p,
291
+ const Tensor& max_t);
292
+ at::SymIntArrayRef strides_or_error(
293
+ const Tensor& input,
294
+ std::string_view const& input_name);
295
+ at::Tensor mm_mat1_backward(
296
+ const Tensor& grad,
297
+ const Tensor& mat2,
298
+ at::SymIntArrayRef mat1_sizes,
299
+ at::SymIntArrayRef mat1_strides,
300
+ c10::Layout mat1_layout,
301
+ const Scalar& alpha);
302
+ at::Tensor mm_mat2_backward(
303
+ const at::Tensor& grad,
304
+ const at::Tensor& mat1,
305
+ at::SymIntArrayRef sizes,
306
+ at::SymIntArrayRef strides,
307
+ c10::Layout layout,
308
+ const at::Scalar& alpha);
309
+ at::Tensor _grouped_mm_mat1_backward(
310
+ const Tensor& grad,
311
+ const Tensor& mat2,
312
+ at::SymIntArrayRef mat1_sizes,
313
+ at::SymIntArrayRef mat1_strides,
314
+ c10::Layout mat1_layout,
315
+ std::optional<Tensor> offs,
316
+ const Scalar& alpha);
317
+ at::Tensor _grouped_mm_mat2_backward(
318
+ const at::Tensor& grad,
319
+ const at::Tensor& mat1,
320
+ at::SymIntArrayRef sizes,
321
+ at::SymIntArrayRef strides,
322
+ c10::Layout layout,
323
+ std::optional<Tensor> offs,
324
+ const at::Scalar& alpha);
325
+ at::Tensor mm_mat1_sparse_backward(
326
+ const at::Tensor& grad,
327
+ const at::Tensor& mat1,
328
+ const at::Tensor& mat2,
329
+ const at::Scalar& alpha);
330
+ std::tuple<Tensor, Tensor, Tensor> sparse_sampled_addmm_backward(
331
+ const Tensor& grad,
332
+ const Tensor& self,
333
+ const std::optional<Tensor>& mat1,
334
+ const std::optional<Tensor>& mat2,
335
+ const Scalar& alpha,
336
+ const Scalar& beta,
337
+ const std::array<bool, 3>& grad_input_mask);
338
+ at::Tensor sparse_mask_backward(
339
+ const at::Tensor& grad,
340
+ const at::Tensor& mask,
341
+ c10::Layout self_layout);
342
+ at::Tensor sparse_sparse_matmul_backward(
343
+ const at::Tensor& grad,
344
+ const at::Tensor& mat1,
345
+ const at::Tensor& mat2,
346
+ int64_t grad_order);
347
+ at::Tensor renorm_backward(
348
+ const at::Tensor& grad,
349
+ const at::Tensor& self,
350
+ const at::Scalar& p,
351
+ int64_t dim,
352
+ const at::Scalar& maxnorm);
353
+ at::Tensor renorm_jvp(
354
+ const at::Tensor& self_p,
355
+ const at::Tensor& self_t,
356
+ const at::Scalar& p,
357
+ int64_t dim,
358
+ const at::Scalar& maxnorm);
359
+ at::Tensor repeat_backward(
360
+ at::Tensor grad,
361
+ at::SymIntArrayRef repeats,
362
+ at::SymIntArrayRef input_shape);
363
+ at::Tensor _fused_dropout_backward(
364
+ const at::Tensor& grad,
365
+ const at::Tensor& mask,
366
+ double p1m);
367
+ at::Tensor infinitely_differentiable_native_dropout_backward(
368
+ const at::Tensor& grad,
369
+ const at::Tensor& mask,
370
+ double scale);
371
+ at::Tensor native_dropout_double_backward(
372
+ const at::Tensor& ggI,
373
+ const at::Tensor& grad,
374
+ const at::Tensor& mask,
375
+ double scale);
376
+ at::Tensor evenly_distribute_backward(
377
+ const at::Tensor& grad,
378
+ const at::Tensor& input,
379
+ const at::Tensor& value);
380
+ Tensor sgn_backward(const Tensor& x, const Tensor& gx, const Tensor& sgn);
381
+ Tensor masked_fill_backward(const Tensor& grad, const Tensor& mask);
382
+ at::Tensor var_backward(
383
+ at::Tensor grad,
384
+ const at::Tensor& self,
385
+ at::OptionalIntArrayRef dim,
386
+ const std::optional<c10::Scalar>& correction,
387
+ bool keepdim);
388
+ at::Tensor var_jvp(
389
+ const at::Tensor& self_t,
390
+ const at::Tensor& self_p,
391
+ const at::Tensor& result,
392
+ at::OptionalIntArrayRef dim_opt,
393
+ const std::optional<c10::Scalar>& correction,
394
+ bool keepdim);
395
+ at::Tensor std_backward(
396
+ const at::Tensor& result,
397
+ const at::Tensor& grad,
398
+ const at::Tensor& self,
399
+ at::OptionalIntArrayRef dim,
400
+ const std::optional<c10::Scalar>& correction,
401
+ bool keepdim);
402
+ Tensor mean_backward(
403
+ const Tensor& grad,
404
+ c10::SymIntArrayRef shape,
405
+ at::OptionalIntArrayRef opt_dim,
406
+ c10::SymInt numel,
407
+ bool keepdim);
408
+ Tensor var_mean_backward(
409
+ const Tensor& gvar,
410
+ const Tensor& gmean,
411
+ const Tensor& self,
412
+ at::OptionalIntArrayRef dim_opt,
413
+ const std::optional<c10::Scalar>& correction,
414
+ bool keepdim);
415
+ Tensor std_mean_backward(
416
+ const Tensor& gstd,
417
+ const Tensor& gmean,
418
+ const Tensor& self,
419
+ const Tensor& std,
420
+ at::OptionalIntArrayRef dim_opt,
421
+ const std::optional<c10::Scalar>& correction,
422
+ bool keepdim);
423
+ at::Tensor cholesky_backward(
424
+ const at::Tensor& grad,
425
+ bool upper,
426
+ const at::Tensor& L);
427
+ at::Tensor cholesky_jvp(
428
+ const at::Tensor& input_tangent,
429
+ const at::Tensor& L,
430
+ bool upper);
431
+ at::Tensor cholesky_inverse_backward(
432
+ const at::Tensor& grad,
433
+ const at::Tensor& L,
434
+ bool upper,
435
+ const at::Tensor& inverse);
436
+ at::Tensor cholesky_inverse_jvp(
437
+ const at::Tensor& F,
438
+ const at::Tensor& dF,
439
+ const at::Tensor& X,
440
+ bool upper);
441
+ Tensor pinv_jvp(const Tensor& A, const Tensor& pinvA, const Tensor& dA);
442
+ Tensor pinv_backward(const Tensor& grad, const Tensor& pinvA, const Tensor& A);
443
+ Tensor chunk_backward_nested(
444
+ const std::vector<torch::autograd::Variable>& grads,
445
+ const Tensor& self,
446
+ int64_t chunks,
447
+ int64_t dim);
448
+ at::Tensor split_with_sizes_backward(
449
+ const std::vector<torch::autograd::Variable>& grads,
450
+ c10::SymIntArrayRef split_sizes,
451
+ int64_t dim,
452
+ c10::SymIntArrayRef sizes,
453
+ const at::TensorOptions& options);
454
+ at::Tensor _nested_split_with_sizes_backward(
455
+ const std::vector<torch::autograd::Variable>& grads,
456
+ c10::SymIntArrayRef split_sizes,
457
+ int64_t dim,
458
+ const Tensor& nt_sizes,
459
+ const at::TensorOptions& options);
460
+ at::Tensor split_backward(
461
+ const std::vector<torch::autograd::Variable>& grads,
462
+ const c10::SymInt& split_size,
463
+ int64_t dim,
464
+ c10::SymIntArrayRef sizes,
465
+ const at::TensorOptions& options);
466
+ at::Tensor max_pool_double_backward(
467
+ const at::Tensor& grad,
468
+ const at::Tensor& indices,
469
+ int dim);
470
+ at::Tensor error_for_max_pool2d_double_backward();
471
+ at::Tensor glu_double_backward(
472
+ const at::Tensor& grad,
473
+ const at::Tensor& grad_output,
474
+ const at::Tensor& input,
475
+ int64_t dim);
476
+ at::Tensor glu_double_backward_grad_output(
477
+ const at::Tensor& grad,
478
+ const at::Tensor& input,
479
+ int64_t dim);
480
+ at::Tensor infinitely_differentiable_silu_backward(
481
+ const at::Tensor& grad_output,
482
+ const at::Tensor& input);
483
+ at::Tensor infinitely_differentiable_mish_backward(
484
+ const at::Tensor& grad_output,
485
+ const at::Tensor& input);
486
+ Tensor infinitely_differentiable_logit_backward(
487
+ const Tensor& grad,
488
+ const Tensor& self,
489
+ std::optional<double> eps);
490
+ Tensor binary_cross_entropy_target_backward(
491
+ const Tensor& grad,
492
+ const Tensor& self,
493
+ const Tensor& target,
494
+ const std::optional<Tensor>& weight,
495
+ int64_t reduction);
496
+ Tensor binary_cross_entropy_double_backward_target(
497
+ const Tensor& grad,
498
+ const Tensor& grad_output,
499
+ const Tensor& self,
500
+ const Tensor& target,
501
+ const std::optional<Tensor>& weight,
502
+ int64_t reduction);
503
+ Tensor binary_cross_entropy_with_logits_backward(
504
+ const Tensor& grad,
505
+ const Tensor& input,
506
+ const Tensor& target,
507
+ const std::optional<Tensor>& weight_opt,
508
+ const std::optional<Tensor>& pos_weight_opt,
509
+ int64_t reduction);
510
+ at::Tensor binary_cross_entropy_with_logits_target_backward(
511
+ const at::Tensor& grad_output,
512
+ const at::Tensor& self,
513
+ const at::Tensor& target,
514
+ const std::optional<at::Tensor>& weight,
515
+ const std::optional<at::Tensor>& pos_weight,
516
+ int64_t reduction);
517
+ at::Tensor log_sigmoid_double_backward(
518
+ const at::Tensor& grad,
519
+ const at::Tensor& input);
520
+ at::Tensor softmax_double_backward(
521
+ const at::Tensor& grad,
522
+ const at::Tensor& grad_output,
523
+ int dim,
524
+ const at::Tensor& output);
525
+ at::Tensor binary_cross_entropy_double_backward(
526
+ const at::Tensor& grad_output,
527
+ const at::Tensor& grad,
528
+ const at::Tensor& input,
529
+ const at::Tensor& target,
530
+ const std::optional<at::Tensor>& weight,
531
+ int64_t reduction);
532
+ at::Tensor binary_cross_entropy_double_backward_grad_output(
533
+ const at::Tensor& grad,
534
+ const at::Tensor& input,
535
+ const at::Tensor& target,
536
+ const std::optional<at::Tensor>& weight,
537
+ int64_t reduction);
538
+ at::Tensor smooth_l1_loss_double_backward(
539
+ const at::Tensor& grad,
540
+ const at::Tensor& input,
541
+ const at::Tensor& target,
542
+ int64_t reduction,
543
+ double beta);
544
+ at::Tensor huber_loss_double_backward(
545
+ const at::Tensor& grad,
546
+ const at::Tensor& input,
547
+ const at::Tensor& target,
548
+ int64_t reduction,
549
+ double delta);
550
+ at::Tensor huber_loss_double_backward_grad_output(
551
+ const at::Tensor& grad,
552
+ const at::Tensor& grad_output,
553
+ const at::Tensor& input,
554
+ const at::Tensor& target,
555
+ int64_t reduction,
556
+ double delta);
557
+ at::Tensor mse_loss_double_backward(
558
+ const at::Tensor& grad,
559
+ const at::Tensor& input,
560
+ int64_t reduction);
561
+ at::Tensor soft_margin_loss_double_backward(
562
+ const at::Tensor& grad,
563
+ const at::Tensor& input,
564
+ const at::Tensor& target,
565
+ int64_t reduction);
566
+ at::Tensor soft_margin_loss_double_backward_grad_output(
567
+ const at::Tensor& grad,
568
+ const at::Tensor& grad_output,
569
+ const at::Tensor& input,
570
+ const at::Tensor& target,
571
+ int64_t reduction);
572
+ at::Tensor softplus_double_backward(
573
+ const at::Tensor& grad,
574
+ const at::Tensor& input,
575
+ const at::Scalar& beta,
576
+ const at::Scalar& threshold);
577
+ std::tuple<at::Tensor, at::Tensor> slogdet_jvp(
578
+ const at::Tensor& LU,
579
+ const at::Tensor& pivots,
580
+ const at::Tensor& dA,
581
+ const at::Tensor& sign,
582
+ const bool use_A_T);
583
+ at::Tensor slogdet_backward(
584
+ const at::Tensor& grad_sign,
585
+ const at::Tensor& grad_logabsdet,
586
+ const at::Tensor& A,
587
+ const at::Tensor& signdet,
588
+ const at::Tensor& LU,
589
+ const at::Tensor& pivots);
590
+ at::Tensor log1p_backward(const at::Tensor& grad, const at::Tensor& self);
591
+ at::Tensor sinc_backward(const at::Tensor& grad, const at::Tensor& self);
592
+ at::Tensor sparse_constructor_values_backward(
593
+ const at::Tensor& sparse_grad_out,
594
+ const at::Tensor& indices);
595
+ at::Tensor embedding_dense_double_backward_symint(
596
+ const at::Tensor& grad,
597
+ const at::Tensor& indices,
598
+ const c10::SymInt& padding_idx);
599
+ at::Tensor index_backward(
600
+ at::Tensor zeros_like_self,
601
+ const torch::List<std::optional<Tensor>>& indices,
602
+ const at::Tensor& grad);
603
+ at::Tensor _cudnn_ctc_loss_backward(
604
+ const at::Tensor& grad_out,
605
+ const at::Tensor& loss,
606
+ const at::Tensor& raw_grad,
607
+ bool zero_infinity);
608
+ at::Tensor elu_double_backward(
609
+ const Tensor& grad,
610
+ const Tensor& grad_output,
611
+ const Scalar& alpha,
612
+ const Scalar& scale,
613
+ const Scalar& input_scale,
614
+ bool is_result,
615
+ const Tensor& self_or_result);
616
+
617
+ Tensor svd_backward(
618
+ const Tensor& gU,
619
+ const Tensor& gS,
620
+ const Tensor& gVh,
621
+ const Tensor& U,
622
+ const Tensor& S,
623
+ const Tensor& Vh);
624
+
625
+ std::tuple<Tensor, Tensor, Tensor> linalg_svd_jvp(
626
+ const Tensor& dA,
627
+ const Tensor& U,
628
+ const Tensor& S,
629
+ const Tensor& Vh,
630
+ const bool full_matrices);
631
+ Tensor slice_backward_wrapper(
632
+ const at::Tensor& grad,
633
+ const c10::SymIntArrayRef& input_sizes,
634
+ int64_t dim,
635
+ std::optional<c10::SymInt> start,
636
+ std::optional<c10::SymInt> end,
637
+ c10::SymInt step);
638
+ std::tuple<Tensor, Tensor> linalg_eig_jvp(
639
+ const Tensor& dA,
640
+ const Tensor& L,
641
+ const Tensor& V,
642
+ const bool is_hermitian);
643
+ Tensor linalg_eig_backward(
644
+ const Tensor& gL,
645
+ const Tensor& gV,
646
+ const Tensor& L,
647
+ const Tensor& V,
648
+ const bool is_hermitian,
649
+ const bool symeig_eigenvectors = true);
650
+ Tensor linalg_lstsq_solution_jvp(
651
+ const Tensor& A,
652
+ const Tensor& B_,
653
+ const Tensor& dA,
654
+ const Tensor& dB_);
655
+ Tensor linalg_lstsq_residuals_jvp(
656
+ const Tensor& A,
657
+ const Tensor& B_,
658
+ const Tensor& dA,
659
+ const Tensor& dB_,
660
+ const Tensor& X_,
661
+ const Tensor& L);
662
+ std::tuple<Tensor, Tensor> triangular_solve_backward(
663
+ const Tensor& grad_x,
664
+ const Tensor& grad_m,
665
+ const Tensor& b,
666
+ const Tensor& a,
667
+ const Tensor& x,
668
+ const bool upper,
669
+ const bool transpose,
670
+ const bool unitriangular,
671
+ std::array<bool, 2> output_mask);
672
+ Tensor triangular_solve_jvp(
673
+ const Tensor& X,
674
+ const Tensor& A,
675
+ const Tensor& dA,
676
+ const Tensor& dB,
677
+ const bool upper,
678
+ const bool transpose,
679
+ const bool unitriangular);
680
+ Tensor linalg_solve_triangular_forward_AD(
681
+ const Tensor& A_t,
682
+ const Tensor& B_t,
683
+ const Tensor& A,
684
+ const Tensor& X,
685
+ const bool upper,
686
+ const bool left,
687
+ const bool unitriangular);
688
+ std::tuple<Tensor, Tensor> linalg_solve_triangular_backward(
689
+ const Tensor& grad,
690
+ const Tensor& A,
691
+ const Tensor& X,
692
+ const bool upper,
693
+ const bool left,
694
+ const bool unitriangular,
695
+ std::array<bool, 2> output_mask);
696
+ std::tuple<Tensor, Tensor, Tensor> _trilinear_backward(
697
+ const Tensor& grad_out,
698
+ const std::optional<Tensor>& i1,
699
+ const std::optional<Tensor>& i2,
700
+ const std::optional<Tensor>& i3,
701
+ IntArrayRef expand1,
702
+ IntArrayRef expand2,
703
+ IntArrayRef expand3,
704
+ IntArrayRef sumdim,
705
+ std::array<bool, 3> grad_mask);
706
+ std::tuple<Tensor, Tensor> linalg_qr_jvp(
707
+ const Tensor& dA,
708
+ const Tensor& Q,
709
+ const Tensor& R,
710
+ const std::string_view mode);
711
+ Tensor linalg_qr_backward(
712
+ const Tensor& gQ,
713
+ const Tensor& gR,
714
+ const Tensor& Q,
715
+ const Tensor& R,
716
+ const std::string_view mode);
717
+ Tensor linalg_matrix_exp_differential(
718
+ const Tensor& self,
719
+ const Tensor& grad,
720
+ bool adjoint);
721
+ std::tuple<Tensor, Tensor, Tensor> batchnorm_double_backward(
722
+ const Tensor& input,
723
+ const std::optional<Tensor>& gamma,
724
+ const Tensor& ggI,
725
+ const Tensor& ggG,
726
+ const Tensor& ggB,
727
+ const Tensor& gO,
728
+ const std::optional<Tensor>& running_mean,
729
+ const std::optional<Tensor>& running_var,
730
+ bool training,
731
+ double eps,
732
+ const std::optional<Tensor>& save_mean,
733
+ const std::optional<Tensor>& save_invstd,
734
+ std::array<bool, 3> output_mask);
735
+ std::tuple<Tensor, Tensor> _euclidean_dist_backward(
736
+ const Tensor& grad,
737
+ const Tensor& x1,
738
+ const Tensor& x2,
739
+ const Tensor& res);
740
+ Tensor fft_backward(
741
+ const Tensor& self,
742
+ const Tensor& grad,
743
+ int64_t signal_ndim,
744
+ bool complex_input,
745
+ bool complex_output,
746
+ bool inverse,
747
+ IntArrayRef checked_signal_sizes,
748
+ int64_t normalization,
749
+ bool onesided,
750
+ IntArrayRef output_sizes);
751
+ Tensor fft_r2c_backward(
752
+ const Tensor& grad,
753
+ at::IntArrayRef dim,
754
+ int64_t normalization,
755
+ bool onesided,
756
+ const c10::SymInt& last_dim_size);
757
+ Tensor fft_c2r_backward(
758
+ const Tensor& grad,
759
+ IntArrayRef dim,
760
+ int64_t normalization);
761
+ Tensor constant_pad_nd_backward(const Tensor& grad, c10::SymIntArrayRef pad);
762
+ std::tuple<Tensor, Tensor> cholesky_solve_backward(
763
+ const Tensor& grad_x,
764
+ const Tensor& self,
765
+ const Tensor& input2,
766
+ const Tensor& result,
767
+ const bool upper,
768
+ std::array<bool, 2> output_mask);
769
+ Tensor cholesky_solve_jvp(
770
+ const Tensor& X,
771
+ const Tensor& U,
772
+ const Tensor& dU,
773
+ const Tensor& dB,
774
+ const bool upper);
775
+ std::tuple<Tensor, Tensor, Tensor>
776
+ infinitely_differentiable_native_group_norm_backward(
777
+ const Tensor& dY,
778
+ const Tensor& dmean,
779
+ const Tensor& drstd,
780
+ const Tensor& X,
781
+ const Tensor& mean,
782
+ const Tensor& rstd,
783
+ const std::optional<Tensor>& gamma,
784
+ c10::SymInt N,
785
+ const c10::SymInt& C,
786
+ c10::SymInt HxW,
787
+ int64_t group,
788
+ double eps,
789
+ std::array<bool, 3> grad_input_mask);
790
+ Tensor gelu_double_backward(
791
+ const Tensor& ggI,
792
+ const Tensor& gO,
793
+ const Tensor& input,
794
+ std::string_view approximate);
795
+ Tensor as_strided_backward(
796
+ Tensor grad,
797
+ const TensorGeometry& input_geometry,
798
+ c10::SymIntArrayRef sizes,
799
+ c10::SymIntArrayRef strides,
800
+ const std::optional<c10::SymInt>& storage_offset_);
801
+ Tensor as_strided_scatter_backward(
802
+ const Tensor& grad,
803
+ const TensorGeometry& input_geometry,
804
+ const TensorGeometry& src_geometry,
805
+ c10::SymIntArrayRef sizes,
806
+ c10::SymIntArrayRef strides,
807
+ std::optional<c10::SymInt> storage_offset);
808
+ std::tuple<Tensor, Tensor> atan2_backward(
809
+ const Tensor& grad,
810
+ const Tensor& self,
811
+ const Tensor& other,
812
+ std::array<bool, 2> output_mask);
813
+ Tensor amaxamin_jvp(
814
+ const Tensor& x,
815
+ const Tensor& dx,
816
+ const Tensor& result,
817
+ IntArrayRef dim,
818
+ bool keepdim);
819
+ std::tuple<Tensor, Tensor, Tensor> layer_norm_double_backward(
820
+ const Tensor& input,
821
+ const std::optional<Tensor>& gamma,
822
+ const Tensor& ggI,
823
+ const Tensor& ggG,
824
+ const Tensor& ggB,
825
+ const Tensor& gO,
826
+ const Tensor& save_mean,
827
+ const Tensor& save_invstd,
828
+ c10::SymIntArrayRef normalized_shape,
829
+ std::array<bool, 3> output_mask);
830
+
831
+ std::tuple<Tensor, Tensor> infinitely_differentiable_native_rms_norm_backward(
832
+ const Tensor& dY,
833
+ const Tensor& drstd,
834
+ const Tensor& input,
835
+ IntArrayRef normalized_shape,
836
+ const Tensor& rstd,
837
+ const std::optional<Tensor>& weight_opt,
838
+ std::array<bool, 2> grad_input_mask);
839
+
840
+ std::tuple<Tensor, Tensor> householder_product_backward(
841
+ const Tensor& grad,
842
+ const Tensor& result,
843
+ const Tensor& input,
844
+ const Tensor& tau,
845
+ const bool flip_order = false);
846
+ Tensor householder_product_jvp(
847
+ const Tensor& dV,
848
+ const Tensor& dtau,
849
+ const Tensor& prod,
850
+ const Tensor& V,
851
+ const Tensor& tau);
852
+ std::tuple<Tensor, Tensor, Tensor> ormqr_backward(
853
+ const Tensor& grad,
854
+ const Tensor& result,
855
+ const Tensor& self,
856
+ const Tensor& tau,
857
+ const Tensor& other,
858
+ bool left,
859
+ bool transpose,
860
+ std::array<bool, 3> grad_output_mask);
861
+ std::tuple<Tensor, Tensor> polar_backward(
862
+ const Tensor& grad,
863
+ const Tensor& result);
864
+ Tensor i1_backward(
865
+ const Tensor& grad,
866
+ const Tensor& self,
867
+ const Tensor& result);
868
+ Tensor i1e_backward(
869
+ const Tensor& grad,
870
+ const Tensor& self,
871
+ const Tensor& result);
872
+ Tensor linalg_lu_solve_LU(
873
+ const Tensor& grad,
874
+ const Tensor& LU,
875
+ const Tensor& pivots,
876
+ const Tensor& X,
877
+ const bool left,
878
+ const bool adjoint);
879
+ Tensor linalg_lu_solve_jvp(
880
+ const Tensor& X,
881
+ const Tensor& LU,
882
+ const Tensor& pivots,
883
+ const Tensor& dLU,
884
+ const Tensor& dB,
885
+ const bool left,
886
+ const bool adjoint);
887
+ std::tuple<Tensor, Tensor> linalg_solve_backward(
888
+ const Tensor& gX,
889
+ const Tensor& X,
890
+ const Tensor& A,
891
+ const Tensor& LU,
892
+ const Tensor& pivots,
893
+ const bool left,
894
+ const bool B_requires_grad);
895
+ Tensor linalg_solve_jvp(
896
+ const Tensor& dA,
897
+ const Tensor& dB,
898
+ const Tensor& X,
899
+ const Tensor& LU,
900
+ const Tensor& pivots,
901
+ const bool left,
902
+ const bool use_A_T);
903
+ Tensor lu_unpack_backward(
904
+ const Tensor& L_grad,
905
+ const Tensor& U_grad,
906
+ const c10::SymInt& m,
907
+ const c10::SymInt& n);
908
+
909
+ Tensor linalg_det_backward(
910
+ const Tensor& grad,
911
+ const Tensor& det,
912
+ const Tensor& A,
913
+ const Tensor& LU,
914
+ const Tensor& pivots);
915
+ Tensor linalg_det_jvp(
916
+ const Tensor& dA,
917
+ const Tensor& det,
918
+ const Tensor& LU,
919
+ const Tensor& pivots,
920
+ const bool use_A_T);
921
+ std::tuple<Tensor, Tensor> linalg_lstsq_backward(
922
+ const Tensor& gX_,
923
+ const Tensor& gL,
924
+ const Tensor& A,
925
+ const Tensor& B_,
926
+ const Tensor& X_,
927
+ const std::array<bool, 2>& grad_input_mask);
928
+ Tensor linalg_lu_backward(
929
+ const Tensor& L_grad,
930
+ const Tensor& U_grad,
931
+ const Tensor& P,
932
+ const Tensor& L,
933
+ const Tensor& U,
934
+ const bool pivot);
935
+
936
+ std::tuple<Tensor, Tensor> linalg_lu_jvp(
937
+ const Tensor& dA,
938
+ const Tensor& P,
939
+ const Tensor& L,
940
+ const Tensor& U,
941
+ const bool pivot);
942
+
943
+ Tensor lu_factor_ex_backward(
944
+ const Tensor& grad,
945
+ const Tensor& LU,
946
+ const Tensor& pivs,
947
+ const bool pivot);
948
+ Tensor lu_factor_ex_jvp(
949
+ const Tensor& dX,
950
+ const Tensor& LU,
951
+ const Tensor& pivs,
952
+ const bool pivot);
953
+
954
+ Tensor batch_norm_jvp(
955
+ const Tensor& input_p,
956
+ const Tensor& input_t,
957
+ const Tensor& weight_p,
958
+ const Tensor& weight_t,
959
+ const Tensor& bias_p,
960
+ const Tensor& bias_t,
961
+ const std::optional<Tensor>& running_mean,
962
+ const std::optional<Tensor>& running_var,
963
+ const Tensor& saved_mean,
964
+ const Tensor& saved_invstd,
965
+ bool train,
966
+ double eps);
967
+
968
+ Tensor layer_norm_jvp(
969
+ const Tensor& input_p,
970
+ const Tensor& input_t,
971
+ const Tensor& weight_p,
972
+ const Tensor& weight_t,
973
+ const Tensor& bias_p,
974
+ const Tensor& bias_t,
975
+ const Tensor& saved_mean,
976
+ const Tensor& saved_invstd,
977
+ c10::SymIntArrayRef normalized_shape);
978
+
979
+ Tensor rms_norm_jvp(
980
+ const Tensor& input_p,
981
+ const Tensor& input_t,
982
+ const Tensor& weight_p,
983
+ const Tensor& weight_t,
984
+ const Tensor& saved_rstd,
985
+ IntArrayRef normalized_shape);
986
+
987
+ Tensor rms_norm_rstd_jvp(
988
+ const Tensor& input_p,
989
+ const Tensor& input_t,
990
+ const Tensor& saved_rstd,
991
+ IntArrayRef normalized_shape);
992
+
993
+ Tensor group_norm_jvp(
994
+ const Tensor& input_p,
995
+ const Tensor& input_t,
996
+ const Tensor& weight_p,
997
+ const Tensor& weight_t,
998
+ const Tensor& bias_p,
999
+ const Tensor& bias_t,
1000
+ const Tensor& saved_mean,
1001
+ const Tensor& saved_invstd,
1002
+ int64_t groups);
1003
+ Tensor group_norm_mean_jvp(
1004
+ const Tensor& input_t,
1005
+ const Tensor& mean_p,
1006
+ int64_t groups);
1007
+ Tensor group_norm_invstd_jvp(
1008
+ const Tensor& input_p,
1009
+ const Tensor& input_t,
1010
+ const Tensor& mean_p,
1011
+ const Tensor& invstd_p,
1012
+ int64_t groups);
1013
+
1014
+ Tensor convolution_jvp(
1015
+ const Tensor& input_p,
1016
+ const Tensor& input_t,
1017
+ const Tensor& weight_p,
1018
+ const Tensor& weight_t,
1019
+ const Tensor& bias_p,
1020
+ const Tensor& bias_t,
1021
+ at::SymIntArrayRef stride,
1022
+ at::SymIntArrayRef padding,
1023
+ at::SymIntArrayRef dilation,
1024
+ bool transposed,
1025
+ at::SymIntArrayRef output_padding,
1026
+ const c10::SymInt& groups);
1027
+
1028
+ Tensor _convolution_jvp(
1029
+ const Tensor& input_p,
1030
+ const Tensor& input_t,
1031
+ const Tensor& weight_p,
1032
+ const Tensor& weight_t,
1033
+ const Tensor& bias_p,
1034
+ const Tensor& bias_t,
1035
+ at::SymIntArrayRef stride,
1036
+ at::SymIntArrayRef padding,
1037
+ at::SymIntArrayRef dilation,
1038
+ bool transposed,
1039
+ at::SymIntArrayRef output_padding,
1040
+ const c10::SymInt& groups,
1041
+ bool benchmark,
1042
+ bool deterministic,
1043
+ bool cudnn_enabled,
1044
+ bool allow_tf32);
1045
+
1046
+ Tensor convolution_backward_jvp_grad_bias(
1047
+ const Tensor& grad_out_t,
1048
+ const Tensor& grad_bias);
1049
+
1050
+ Tensor cat_jvp(const at::ITensorListRef& tensors, int64_t dim);
1051
+ Tensor block_diag_jvp(at::TensorList tensors);
1052
+ Tensor stack_jvp(at::TensorList tensors, int64_t dim);
1053
+ Tensor cumprod_jvp(
1054
+ const Tensor& self_t,
1055
+ const Tensor& self_p,
1056
+ const Tensor& result,
1057
+ int dim);
1058
+ Tensor gather_with_keepdimed_indices(
1059
+ const Tensor& input,
1060
+ int64_t dim,
1061
+ const Tensor& indices,
1062
+ bool keepdim);
1063
+ Tensor evenly_read_jvp(
1064
+ const Tensor& fw_grad,
1065
+ const Tensor& input,
1066
+ const Tensor& value);
1067
+ Tensor warn_backwards(const Tensor& grad_output);
1068
+
1069
+ std::tuple<Tensor, Tensor> _cudnn_convolution_backward(
1070
+ const at::Tensor& self,
1071
+ const at::Tensor& grad_output,
1072
+ const at::Tensor& weight,
1073
+ at::SymIntArrayRef padding,
1074
+ at::SymIntArrayRef output_padding,
1075
+ at::SymIntArrayRef stride,
1076
+ at::SymIntArrayRef dilation,
1077
+ bool transposed,
1078
+ c10::SymInt groups,
1079
+ ::std::array<bool, 2> output_mask);
1080
+
1081
+ Tensor scatter_reduce_jvp(
1082
+ const Tensor& self_p,
1083
+ const Tensor& self_t,
1084
+ int dim,
1085
+ const Tensor& index,
1086
+ const Tensor& src_p,
1087
+ const Tensor& src_t,
1088
+ std::string_view reduce,
1089
+ bool include_self,
1090
+ const Tensor& result);
1091
+
1092
+ std::tuple<Tensor, Tensor> scatter_reduce_backward(
1093
+ const Tensor& grad,
1094
+ const Tensor& self,
1095
+ int dim,
1096
+ const Tensor& index,
1097
+ const Tensor& src,
1098
+ std::string_view reduce,
1099
+ bool include_self,
1100
+ const Tensor& result);
1101
+
1102
+ Tensor _to_copy_backward(
1103
+ const Tensor& grad,
1104
+ const c10::TensorOptions& self_options);
1105
+
1106
+ std::tuple<Tensor, Tensor> index_reduce_backward(
1107
+ const Tensor& grad,
1108
+ const Tensor& self,
1109
+ int dim,
1110
+ const Tensor& index,
1111
+ const Tensor& source,
1112
+ std::string_view reduce,
1113
+ bool include_self,
1114
+ const Tensor& result);
1115
+
1116
+ Tensor take_backward(
1117
+ const Tensor& grad,
1118
+ const Tensor& self,
1119
+ const Tensor& indices);
1120
+
1121
+ Tensor to_sparse_backward(
1122
+ const Tensor& grad,
1123
+ const c10::Layout self_layout,
1124
+ const c10::OptionalArrayRef<c10::SymInt>& self_blocksize);
1125
+
1126
+ std::tuple<Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor>
1127
+ mkldnn_rnn_layer_differentiable_backward(
1128
+ const Tensor& input,
1129
+ const Tensor& weight0,
1130
+ const Tensor& weight1,
1131
+ const Tensor& weight2,
1132
+ const Tensor& weight3,
1133
+ const Tensor& hx_,
1134
+ const Tensor& cx_tmp,
1135
+ const Tensor& output,
1136
+ const Tensor& hy_,
1137
+ const Tensor& cy_,
1138
+ const std::optional<Tensor>& grad_output_r_opt,
1139
+ const std::optional<Tensor>& grad_hy_r_opt,
1140
+ const std::optional<Tensor>& grad_cy_r_opt,
1141
+ bool reverse,
1142
+ int64_t mode,
1143
+ int64_t hidden_size,
1144
+ int64_t num_layers,
1145
+ bool has_biases,
1146
+ bool train,
1147
+ bool bidirectional,
1148
+ at::IntArrayRef batch_sizes,
1149
+ bool batch_first,
1150
+ const at::Tensor& workspace);
1151
+
1152
+ Tensor values_backward(const Tensor& grad, const Tensor& self);
1153
+
1154
+ } // namespace torch::autograd::generated::details
1155
+
1156
+ #else
1157
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1158
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/InferenceMode.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/InferenceMode.h>
5
+ #include <torch/csrc/Export.h>
6
+
7
+ namespace torch::autograd {
8
+
9
+ using InferenceMode = c10::InferenceMode;
10
+
11
+ }
12
+
13
+ #else
14
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
15
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/VariableTypeUtils.h ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/util/irange.h>
5
+
6
+ #include <ATen/core/boxing/KernelFunction.h>
7
+ #include <ATen/core/dispatch/Dispatcher.h>
8
+
9
+ #include <torch/csrc/autograd/edge.h>
10
+ #include <torch/csrc/autograd/function.h>
11
+ #include <torch/csrc/autograd/functions/basic_ops.h>
12
+ #include <torch/csrc/autograd/functions/tensor.h>
13
+ #include <torch/csrc/autograd/grad_mode.h>
14
+ #include <torch/csrc/autograd/saved_variable.h>
15
+ #include <torch/csrc/autograd/variable.h>
16
+
17
+ #include <torch/csrc/autograd/functions/utils.h>
18
+ #include <torch/csrc/autograd/jit_decomp_interface.h>
19
+ #include <torch/csrc/utils/variadic.h>
20
+
21
+ #include <cstddef>
22
+ #include <functional>
23
+ #include <memory>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #ifdef _MSC_VER
28
+ #ifdef Type
29
+ #undef Type
30
+ #endif
31
+ #endif
32
+
33
+ namespace torch::autograd {
34
+ enum class can_mutate_inplace_result {
35
+ success,
36
+ non_default_backward_view,
37
+ view_of_leaf,
38
+ is_leaf,
39
+ };
40
+
41
+ // The requires_grad argument is used to know if the inplace operation needs
42
+ // gradient to be setup for it.
43
+ // In particular, we can have tensor.requires_grad() != requires_grad when
44
+ // writing a Tensor that requires gradients inplace into a Tensor that does not
45
+ // require gradients: a = torch.rand(2) b = torch.rand(2, requires_grad=True)
46
+ // a.copy_(b)
47
+ inline can_mutate_inplace_result can_mutate_inplace(
48
+ const at::Tensor& tensor,
49
+ bool requires_grad) {
50
+ if (!requires_grad || !GradMode::is_enabled()) {
51
+ return can_mutate_inplace_result::success;
52
+ }
53
+ auto diff_view_meta = impl::get_view_autograd_meta(tensor);
54
+ if (diff_view_meta && diff_view_meta->has_bw_view()) {
55
+ if (diff_view_meta->get_creation_meta() != CreationMeta::DEFAULT) {
56
+ return can_mutate_inplace_result::non_default_backward_view;
57
+ }
58
+ if (tensor.requires_grad() && tensor._base().is_leaf()) {
59
+ return can_mutate_inplace_result::view_of_leaf;
60
+ }
61
+ }
62
+ if (tensor.requires_grad() && tensor.is_leaf()) {
63
+ return can_mutate_inplace_result::is_leaf;
64
+ }
65
+ return can_mutate_inplace_result::success;
66
+ }
67
+
68
+ inline void check_inplace(const at::Tensor& tensor, bool requires_grad) {
69
+ switch (can_mutate_inplace(tensor, requires_grad)) {
70
+ case can_mutate_inplace_result::success:
71
+ return;
72
+ case can_mutate_inplace_result::non_default_backward_view: {
73
+ return handle_view_on_rebase(impl::get_view_autograd_meta(tensor));
74
+ }
75
+ case can_mutate_inplace_result::view_of_leaf:
76
+ TORCH_CHECK(
77
+ false,
78
+ "a view of a leaf Variable that requires grad is being used in an in-place operation.");
79
+ break;
80
+
81
+ case can_mutate_inplace_result::is_leaf:
82
+ TORCH_CHECK(
83
+ false,
84
+ "a leaf Variable that requires grad is being used in an in-place operation.");
85
+ break;
86
+ }
87
+ TORCH_INTERNAL_ASSERT(false);
88
+ }
89
+
90
+ inline void check_inplace(at::ITensorListRef tensors, bool requires_grad) {
91
+ for (const auto& tensor : tensors) {
92
+ check_inplace(tensor, requires_grad);
93
+ }
94
+ }
95
+
96
+ inline void throw_error_out_requires_grad(const char* name) {
97
+ TORCH_CHECK(
98
+ false,
99
+ name,
100
+ "(): functions with out=... arguments don't support automatic differentiation, "
101
+ "but one of the arguments requires grad.");
102
+ }
103
+
104
+ inline void throw_error_for_complex_autograd(
105
+ const at::Tensor& tensor,
106
+ const char* name) {
107
+ if (tensor.requires_grad()) {
108
+ TORCH_CHECK(
109
+ !tensor.is_complex(),
110
+ name,
111
+ " does not support automatic differentiation for outputs with complex dtype.");
112
+ }
113
+ }
114
+
115
+ inline void throw_error_if_base_and_tensor_are_same(
116
+ const at::Tensor& base,
117
+ const at::Tensor& tensor) {
118
+ TORCH_CHECK(
119
+ base.unsafeGetTensorImpl() != tensor.unsafeGetTensorImpl(),
120
+ "View operation returned a tensor that is the same as the input base tensor. This "
121
+ "is no longer allowed; you must explicitly create a new tensor (e.g., using .detach()). "
122
+ "As a user, you could have made a mistake implementing __torch_dispatch__ or a Python "
123
+ "operator decomposition or meta registration; if that's not the case, please "
124
+ "report a bug to PyTorch or the backend you are using.");
125
+ }
126
+
127
+ inline void throw_error_for_complex_autograd(
128
+ at::ITensorListRef tensorlist,
129
+ const char* name) {
130
+ for (const auto& tensor : tensorlist) {
131
+ throw_error_for_complex_autograd(tensor, name);
132
+ }
133
+ }
134
+
135
+ // TODO: Blegh, bare references
136
+
137
+ inline void rebase_history(const Variable& var, std::shared_ptr<Node> grad_fn) {
138
+ if (grad_fn && var.defined()) {
139
+ grad_fn->add_input_metadata(var);
140
+ impl::rebase_history(var, {std::move(grad_fn), 0});
141
+ }
142
+ }
143
+
144
+ inline void rebase_history(
145
+ const std::vector<Variable>& vars,
146
+ const std::shared_ptr<Node>& grad_fn) {
147
+ if (grad_fn) {
148
+ for (auto& var : vars) {
149
+ if (var.defined()) {
150
+ auto output_nr = grad_fn->add_input_metadata(var);
151
+ impl::rebase_history(var, {grad_fn, output_nr});
152
+ } else {
153
+ grad_fn->add_input_metadata(Node::undefined_input());
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ inline void increment_version(const at::Tensor& t) {
160
+ impl::bump_version(t);
161
+ }
162
+
163
+ struct Flatten : IterArgs<Flatten> {
164
+ Flatten(variable_list& out) : out(out) {}
165
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
166
+ variable_list& out;
167
+ void operator()(const at::Tensor& x) {
168
+ out.emplace_back(x);
169
+ }
170
+ void operator()(const std::optional<at::Tensor>& x) {
171
+ if (x.has_value())
172
+ out.emplace_back(x.value());
173
+ }
174
+ void operator()(at::ArrayRef<at::Tensor> xs) {
175
+ out.insert(out.end(), xs.begin(), xs.end());
176
+ }
177
+ };
178
+
179
+ template <typename... Args>
180
+ inline variable_list flatten_tensor_args(Args&&... args) {
181
+ variable_list out;
182
+ out.reserve(count_tensors(std::forward<Args>(args)...));
183
+ Flatten(out).apply(std::forward<Args>(args)...);
184
+ return out; // RVO
185
+ }
186
+
187
+ // See NOTE [ Autograd View Variables ] for details.
188
+ inline at::Tensor as_view(
189
+ const at::Tensor& base,
190
+ const at::Tensor& tensor,
191
+ bool is_bw_differentiable,
192
+ bool is_fw_differentiable,
193
+ std::unique_ptr<ViewFunc> view_func = nullptr,
194
+ std::function<at::Tensor(const at::Tensor&)> rev_view_func = nullptr,
195
+ CreationMeta creation_meta = CreationMeta::DEFAULT,
196
+ bool allow_tensor_metadata_change = true) {
197
+ // Note [View of inference tensor]
198
+ // For inference tensor this code can only be hit outside InferenceMode
199
+ // since ADInplaceOrView is in the default_included_set.
200
+ // If Inplace and View were separate dispatch keys we can just put Inplace
201
+ // in the default_included_set, so that view ops on inference tensor doesn't
202
+ // have to go through as_view even outside InferenceMode.
203
+ if (base.is_inference())
204
+ return tensor;
205
+
206
+ auto diff_view_meta = torch::autograd::impl::get_view_autograd_meta(base);
207
+
208
+ // To speed up the most common case, we specially handle when both the forward
209
+ // and backward view infos are the same, and so a single shared ViewInfo can
210
+ // be used for both of them.
211
+ if ((!diff_view_meta || diff_view_meta->shared_view_info()) &&
212
+ is_bw_differentiable && is_fw_differentiable) {
213
+ throw_error_if_base_and_tensor_are_same(base, tensor);
214
+ if (diff_view_meta) {
215
+ creation_meta = propagate_creation_meta(
216
+ diff_view_meta->get_creation_meta(), creation_meta);
217
+ return make_variable_differentiable_view(
218
+ tensor,
219
+ diff_view_meta->get_backward_view().chain(
220
+ base, tensor, std::move(view_func), std::move(rev_view_func)),
221
+ std::nullopt,
222
+ /*shared_view_info*/ true,
223
+ creation_meta,
224
+ allow_tensor_metadata_change);
225
+ } else {
226
+ return make_variable_differentiable_view(
227
+ tensor,
228
+ ViewInfo(base, std::move(view_func), std::move(rev_view_func)),
229
+ std::nullopt,
230
+ /*shared_view_info*/ true,
231
+ creation_meta,
232
+ allow_tensor_metadata_change);
233
+ }
234
+ }
235
+
236
+ // If they cannot be shared, create the required view infos
237
+ std::optional<ViewInfo> new_bw_info;
238
+ std::optional<ViewInfo> new_fw_info;
239
+
240
+ if (is_bw_differentiable) {
241
+ auto bw_view_func = view_func ? view_func->clone_and_set() : nullptr;
242
+ if (diff_view_meta && diff_view_meta->has_bw_view()) {
243
+ const auto& base_bw_info = diff_view_meta->get_backward_view();
244
+ new_bw_info = base_bw_info.chain(
245
+ base, tensor, std::move(bw_view_func), rev_view_func);
246
+ } else {
247
+ new_bw_info = ViewInfo(base, std::move(bw_view_func), rev_view_func);
248
+ }
249
+ } else {
250
+ TORCH_CHECK(
251
+ creation_meta == CreationMeta::DEFAULT,
252
+ "Non-backward differentiable views must have creation_meta=CreationMeta::DEFAULT");
253
+ }
254
+
255
+ if (is_fw_differentiable) {
256
+ // Check if base is a forward differentiable view
257
+ if (diff_view_meta && diff_view_meta->has_fw_view()) {
258
+ const auto& base_fw_info = diff_view_meta->get_forward_view();
259
+ new_fw_info = base_fw_info.chain(
260
+ base, tensor, std::move(view_func), std::move(rev_view_func));
261
+ } else {
262
+ new_fw_info =
263
+ ViewInfo(base, std::move(view_func), std::move(rev_view_func));
264
+ }
265
+ }
266
+
267
+ if (is_fw_differentiable || is_bw_differentiable) {
268
+ if (diff_view_meta && diff_view_meta->has_bw_view()) {
269
+ creation_meta = propagate_creation_meta(
270
+ diff_view_meta->get_creation_meta(), creation_meta);
271
+ }
272
+ throw_error_if_base_and_tensor_are_same(base, tensor);
273
+ return make_variable_differentiable_view(
274
+ tensor,
275
+ std::move(new_bw_info),
276
+ std::move(new_fw_info),
277
+ /*shared_view_info*/ false,
278
+ creation_meta,
279
+ allow_tensor_metadata_change);
280
+ } else {
281
+ return make_variable_non_differentiable_view(
282
+ base, tensor, allow_tensor_metadata_change);
283
+ }
284
+ }
285
+
286
+ inline void check_no_requires_grad(
287
+ const at::Tensor& tensor,
288
+ const char* name,
289
+ const char* fn_name = "",
290
+ bool check_grad_mode = true) {
291
+ TORCH_CHECK(
292
+ !(tensor.defined() && tensor.requires_grad()) ||
293
+ !(check_grad_mode && GradMode::is_enabled()),
294
+ "The function '",
295
+ fn_name,
296
+ "' is not differentiable with respect to argument '",
297
+ name,
298
+ "'. This input cannot have requires_grad True.");
299
+ }
300
+
301
+ inline void check_no_requires_grad(
302
+ const std::optional<at::Tensor>& tensor,
303
+ const char* name,
304
+ const char* fn_name = "") {
305
+ if (tensor.has_value()) {
306
+ check_no_requires_grad(*tensor, name, fn_name);
307
+ }
308
+ }
309
+
310
+ inline void check_no_requires_grad(
311
+ at::ITensorListRef tensors,
312
+ const char* name,
313
+ const char* fn_name = "") {
314
+ // GradMode check is expensive, so check it only once for TensorLists
315
+ if (!GradMode::is_enabled()) {
316
+ return;
317
+ }
318
+ for (auto& tensor : tensors) {
319
+ check_no_requires_grad(tensor, name, fn_name, /*check_grad_mode*/ false);
320
+ }
321
+ }
322
+
323
+ inline void check_no_requires_grad(
324
+ const c10::List<std::optional<at::Tensor>>& tensors,
325
+ const char* name,
326
+ const char* fn_name = "") {
327
+ // GradMode check is expensive, so check it only once for TensorLists
328
+ if (!GradMode::is_enabled()) {
329
+ return;
330
+ }
331
+ for (std::optional<at::Tensor> tensor : tensors) {
332
+ if (tensor.has_value()) {
333
+ check_no_requires_grad(*tensor, name, fn_name, /*check_grad_mode*/ false);
334
+ }
335
+ }
336
+ }
337
+
338
+ // Assumed that saved tensor lists are never inplace outputs
339
+ inline std::vector<SavedVariable> make_saved_variable_list(
340
+ at::ITensorListRef tensors,
341
+ const bool is_output = false) {
342
+ return fmap(tensors, [&is_output](const at::Tensor& tensor) -> SavedVariable {
343
+ return SavedVariable{tensor, is_output /* is output */};
344
+ });
345
+ }
346
+
347
+ // Assumed that saved tensor lists are never inplace outputs
348
+ inline std::vector<SavedVariable> make_saved_variable_list(
349
+ const c10::List<std::optional<at::Tensor>>& tensors,
350
+ const bool is_output = false) {
351
+ return fmap(
352
+ tensors,
353
+ [&is_output](const std::optional<at::Tensor>& tensor) -> SavedVariable {
354
+ if (tensor.has_value()) {
355
+ return SavedVariable{*tensor, is_output /* is output */};
356
+ } else {
357
+ return SavedVariable{at::Tensor(), is_output /* is output */};
358
+ }
359
+ });
360
+ }
361
+
362
+ inline std::vector<std::vector<int64_t>> to_args_sizes(
363
+ at::ITensorListRef tensors) {
364
+ std::vector<std::vector<int64_t>> args_sizes(tensors.size());
365
+ size_t i = 0;
366
+ for (const auto& t : tensors) {
367
+ args_sizes[i++] = t.sizes().vec();
368
+ }
369
+ return args_sizes;
370
+ }
371
+
372
+ inline std::vector<std::vector<c10::SymInt>> to_args_sizes_symint(
373
+ at::ITensorListRef tensors) {
374
+ std::vector<std::vector<c10::SymInt>> args_sizes(tensors.size());
375
+ size_t i = 0;
376
+ for (const auto& t : tensors) {
377
+ args_sizes[i++] = t.sym_sizes().vec();
378
+ }
379
+ return args_sizes;
380
+ }
381
+
382
+ inline std::vector<c10::ScalarType> to_args_scalartypes(
383
+ at::ITensorListRef tensors) {
384
+ std::vector<c10::ScalarType> args_scalartypes(tensors.size());
385
+ size_t i = 0;
386
+ for (const auto& t : tensors) {
387
+ args_scalartypes[i++] = t.scalar_type();
388
+ }
389
+ return args_scalartypes;
390
+ }
391
+
392
+ namespace impl {
393
+
394
+ namespace {
395
+
396
+ // If run_jit_decomposition were not a member function, we would be able
397
+ // to pass this as a template parameter to c10::Boxedkernel::makeFromFunction.
398
+ // However, member functions cannot be passed this way - instead we wrap our
399
+ // call in this functor so it can be passed to c10::BoxedKernel::makeFromFunctor
400
+ class WrapperFunctor final : public c10::OperatorKernel {
401
+ public:
402
+ WrapperFunctor(JitDecompInterface* impl) : impl_(impl) {}
403
+
404
+ void operator()(
405
+ const c10::OperatorHandle& op,
406
+ c10::DispatchKeySet ks,
407
+ torch::jit::Stack* stack) {
408
+ impl_->run_jit_decomposition(op, stack);
409
+ }
410
+ JitDecompInterface* impl_;
411
+ };
412
+
413
+ } // namespace
414
+
415
+ template <class Return, class... Args>
416
+ Return run_jit_decomposition_with_args_for_jvp(
417
+ std::string_view name,
418
+ const c10::OperatorHandle& opHandle,
419
+ c10::DispatchKeySet dispatchKeySet,
420
+ Args&&... args) {
421
+ // see NOTE: [Jit Decomposition Interface]
422
+ JitDecompInterface* impl = getJitDecompImpl();
423
+
424
+ TORCH_CHECK_NOT_IMPLEMENTED(
425
+ impl && impl->has_jit_decomposition(opHandle.schema()),
426
+ "Trying to use forward AD with ",
427
+ name,
428
+ " that does not support it because it has not been implemented yet.\nPlease file an issue "
429
+ "to PyTorch at https://github.com/pytorch/pytorch/issues/new?template=feature-request.yml "
430
+ "so that we can prioritize its implementation or submit a PR adding the implementation to "
431
+ "derivatives.yaml");
432
+
433
+ return c10::KernelFunction::makeFromBoxedKernel(
434
+ c10::BoxedKernel::makeFromFunctor(
435
+ std::make_unique<WrapperFunctor>(impl)))
436
+ .call<Return, Args...>(
437
+ opHandle, dispatchKeySet, std::forward<Args>(args)...);
438
+ }
439
+
440
+ } // namespace impl
441
+
442
+ } // namespace torch::autograd
443
+
444
+ #else
445
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
446
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/anomaly_mode.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <memory>
6
+ #include <string>
7
+
8
+ namespace torch::autograd {
9
+
10
+ // forward declaration of Node from function.h
11
+ struct Node;
12
+
13
+ struct TORCH_API AnomalyMode {
14
+ static bool is_enabled() {
15
+ return _enabled;
16
+ }
17
+ static bool should_check_nan() {
18
+ return _check_nan;
19
+ }
20
+ static void set_enabled(bool enabled, bool check_nan = true) {
21
+ _enabled = enabled;
22
+ _check_nan = check_nan;
23
+ }
24
+
25
+ private:
26
+ static bool _enabled;
27
+ static bool _check_nan;
28
+ };
29
+
30
+ /// A RAII guard that enables Anomaly Detection Mode.
31
+ ///
32
+ /// Anomaly detection mode is useful for debugging problems happening
33
+ /// in the backward, such as unexpectedly modified tensors or NaNs
34
+ /// occurring in the backward.
35
+ ///
36
+ /// The enabling of anomaly mode is global - as soon as there is one
37
+ /// such guard, it is enabled for all computation and threads. It also
38
+ /// comes with a significant performance penalty.
39
+ ///
40
+ /// Example:
41
+ /// @code
42
+ /// auto x = torch::tensor({1.}, torch::requires_grad());
43
+ /// {
44
+ /// torch::autograd::DetectAnomalyGuard detect_anomaly;
45
+ /// auto x = torch::tensor({5.0}, torch::requires_grad());
46
+ /// auto y = x * x;
47
+ /// auto z = y * y;
48
+ /// y += 1;
49
+ /// z.backward();
50
+ /// }
51
+ /// @endcode
52
+ class TORCH_API DetectAnomalyGuard {
53
+ public:
54
+ DetectAnomalyGuard(bool check_nan = true);
55
+ ~DetectAnomalyGuard();
56
+
57
+ private:
58
+ bool prev_check_nan_;
59
+ };
60
+
61
+ struct TORCH_API AnomalyMetadata {
62
+ virtual ~AnomalyMetadata();
63
+ virtual void store_stack();
64
+ virtual void print_stack(const std::string& current_node_name);
65
+ virtual void assign_parent(const std::shared_ptr<Node>& parent_node);
66
+
67
+ private:
68
+ std::string traceback_;
69
+ std::shared_ptr<Node> parent_;
70
+ };
71
+
72
+ } // namespace torch::autograd
73
+
74
+ #else
75
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
76
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/autograd/variable.h>
5
+
6
+ namespace torch::autograd {
7
+
8
+ /// Computes the sum of gradients of given tensors with respect to graph leaves.
9
+ ///
10
+ /// The graph is differentiated using the chain rule. If any of ``tensors``
11
+ /// are non-scalar (i.e. their data has more than one element) and require
12
+ /// gradient, then the Jacobian-vector product would be computed, in this case
13
+ /// the function additionally requires specifying `grad_tensors`. It should be a
14
+ /// sequence of matching length, that contains the "vector" in the
15
+ /// Jacobian-vector product, usually the gradient of the differentiated function
16
+ /// w.r.t. corresponding tensors
17
+ /// (`torch::Tensor()` is an acceptable value for all tensors that don't need
18
+ /// gradient tensors).
19
+ ///
20
+ /// This function accumulates gradients in the leaves - you might need to zero
21
+ /// them before calling it.
22
+ ///
23
+ /// \param tensors Tensors of which the derivative will be computed.
24
+ /// \param grad_tensors The "vector" in the Jacobian-vector product, usually
25
+ /// gradients
26
+ /// w.r.t. each element of corresponding tensors. `torch::Tensor()` values
27
+ /// can be specified for scalar Tensors or ones that don't require grad. If
28
+ /// a `torch::Tensor()` value would be acceptable for all grad_tensors, then
29
+ /// this argument is optional.
30
+ /// \param retain_graph If `false`, the graph used to compute the grad will be
31
+ /// freed.
32
+ /// Note that in nearly all cases setting this option to `true` is not
33
+ /// needed and often can be worked around in a much more efficient way.
34
+ /// Defaults to the value of `create_graph`.
35
+ /// \param create_graph If `true`, graph of the derivative will be constructed,
36
+ /// allowing
37
+ /// to compute higher order derivative products. Defaults to `false`.
38
+ /// \param inputs Inputs w.r.t. which the gradient will be accumulated into
39
+ /// `at::Tensor::grad`. All other Tensors will be ignored. If not provided,
40
+ /// the gradient is accumulated into all the leaf Tensors that were used to
41
+ /// compute param `tensors`.
42
+ // When inputs are provided and a given input is not a leaf,
43
+ // the current implementation will call its grad_fn (even though it is not
44
+ // strictly needed to get this gradients). It is an implementation detail
45
+ // on which the user should not rely. See
46
+ // https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for
47
+ // more details.
48
+ TORCH_API void backward(
49
+ const variable_list& tensors,
50
+ const variable_list& grad_tensors = {},
51
+ std::optional<bool> retain_graph = std::nullopt,
52
+ bool create_graph = false,
53
+ const variable_list& inputs = {});
54
+
55
+ /// Computes and returns the sum of gradients of outputs with respect to the
56
+ /// inputs.
57
+ ///
58
+ /// ``grad_outputs`` should be a sequence of length matching ``output``
59
+ /// containing the "vector" in Jacobian-vector product, usually the pre-computed
60
+ /// gradients w.r.t. each of the outputs. If an output doesn't require_grad,
61
+ /// then the gradient can be ``torch::Tensor()``).
62
+ ///
63
+ /// \param outputs outputs of the differentiated function.
64
+ /// \param inputs Inputs w.r.t. which the gradient will be
65
+ /// returned (and not accumulated into ``at::Tensor::grad``).
66
+ /// \param grad_outputs The "vector" in the Jacobian-vector product.
67
+ /// Usually gradients w.r.t. each output. `torch::Tensor()` values can be
68
+ /// specified for scalar Tensors or ones that don't require grad. If a
69
+ /// `torch::Tensor()` value would be acceptable for all grad_tensors, then
70
+ /// this argument is optional. Default: `{}`.
71
+ /// \param retain_graph If ``false``, the graph used to compute the grad
72
+ /// will be freed. Note that in nearly all cases setting this option to
73
+ /// ``true`` is not needed and often can be worked around in a much more
74
+ /// efficient way. Defaults to the value of ``create_graph``.
75
+ /// \param create_graph If ``true``, graph of the derivative will
76
+ /// be constructed, allowing to compute higher order derivative products.
77
+ /// Default: ``false``.
78
+ /// \param allow_unused If ``false``, specifying inputs that were not
79
+ /// used when computing outputs (and therefore their grad is always zero)
80
+ /// is an error. Defaults to ``false``.
81
+ TORCH_API variable_list grad(
82
+ const variable_list& outputs,
83
+ const variable_list& inputs,
84
+ const variable_list& grad_outputs = {},
85
+ std::optional<bool> retain_graph = std::nullopt,
86
+ bool create_graph = false,
87
+ bool allow_unused = false);
88
+
89
+ namespace forward_ad {
90
+
91
+ /// Creates a new dual level and returns its index. This level index should then
92
+ /// be used to call into the other functions below. This API supports entering a
93
+ /// new level before the previous one is exited. We call them nested forward AD
94
+ /// levels. These can be used to compute higher order derivatives.
95
+ TORCH_API uint64_t enter_dual_level();
96
+
97
+ /// Exits the given level. This will clear up all the gradients from this level
98
+ /// and all dual Tensors that had gradients for this level will become regular
99
+ /// Tensors again. This function can only be used to exit the innermost nesting
100
+ /// level and so exiting must happen in reverse order compared to the entering
101
+ /// that was done with the function above.
102
+ TORCH_API void exit_dual_level(uint64_t level);
103
+
104
+ } // namespace forward_ad
105
+ } // namespace torch::autograd
106
+
107
+ #else
108
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
109
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/autograd_not_implemented_fallback.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/library.h>
5
+
6
+ namespace torch::autograd {
7
+
8
+ // Default DispatchKey::Autograd fallback for built-in operators.
9
+ // Can be registered for custom operators.
10
+ TORCH_API torch::CppFunction autogradNotImplementedFallback();
11
+
12
+ // Default DispatchKey::AdInplaceOrView fallback for built-in operators
13
+ // Can be registered for custom operators.
14
+ TORCH_API torch::CppFunction autogradNotImplementedInplaceOrViewFallback();
15
+
16
+ // Default DispatchKey::Autograd fallback for all other operators (i.e. custom
17
+ // operators)
18
+ TORCH_API torch::CppFunction basicAutogradNotImplementedFallback();
19
+
20
+ enum class AutogradFallbackMode {
21
+ Nothing, // Fallback is a redispatch
22
+ Warn, // Fallback raises a warning if backward is called
23
+ Error, // Fallback raises an error if backward is called
24
+ };
25
+
26
+ // Change the behavior of "basicAutogradNotImplementedFallback"
27
+ // In Python this is:
28
+ // - torch._C._set_autograd_fallback_mode(str) -> None
29
+ // - torch._C._get_autograd_fallback_mode() -> str
30
+ TORCH_API void setAutogradFallbackMode(AutogradFallbackMode mode);
31
+ TORCH_API AutogradFallbackMode getAutogradFallbackMode();
32
+
33
+ } // namespace torch::autograd
34
+
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/cpp_hook.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <torch/csrc/autograd/function_hook.h>
4
+ #include <functional>
5
+ #include <memory>
6
+
7
+ namespace torch::autograd {
8
+
9
+ using hooks_list =
10
+ std::vector<std::function<at::TensorBase(const at::TensorBase&)>>;
11
+
12
+ struct CppFunctionTensorPreHook : public FunctionPreHook {
13
+ CppFunctionTensorPreHook(std::shared_ptr<hooks_list> hooks, size_t value_idx);
14
+ variable_list operator()(const variable_list& values) override;
15
+
16
+ std::shared_ptr<hooks_list> hooks_;
17
+ size_t value_idx_;
18
+ };
19
+
20
+ struct CppFunctionSingleTensorPreHook : public FunctionPreHook {
21
+ CppFunctionSingleTensorPreHook(
22
+ std::function<at::TensorBase(const at::TensorBase&)> hook,
23
+ size_t value_idx);
24
+ variable_list operator()(const variable_list& values) override;
25
+
26
+ void compiled_args(
27
+ torch::dynamo::autograd::CompiledNodeArgs& args) const override;
28
+
29
+ std::function<at::TensorBase(const at::TensorBase&)> hook_;
30
+ size_t value_idx_;
31
+ };
32
+
33
+ } // namespace torch::autograd
34
+
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/custom_function.h ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/ivalue.h>
5
+ #include <c10/core/SymInt.h>
6
+ #include <c10/util/flat_hash_map.h>
7
+ #include <c10/util/irange.h>
8
+ #include <torch/csrc/autograd/function.h>
9
+ #include <torch/csrc/autograd/variable.h>
10
+ #include <torch/csrc/autograd/variable_info.h>
11
+ #include <torch/csrc/dynamo/compiled_autograd.h>
12
+ #include <vector>
13
+
14
+ namespace torch::autograd {
15
+
16
+ using optional_variable_list = std::vector<std::optional<Variable>>;
17
+ using _jvp_fn_t = std::function<variable_list(variable_list, variable_list)>;
18
+ using _view_as_self_fn_t = std::function<at::Tensor(at::Tensor)>;
19
+
20
+ TORCH_API std::vector<std::optional<Variable>> _wrap_outputs(
21
+ const variable_list& input_vars,
22
+ const std::unordered_set<at::TensorImpl*>& non_differentiable,
23
+ const std::unordered_set<at::TensorImpl*>& dirty_inputs,
24
+ const at::ArrayRef<std::optional<Variable>> raw_outputs,
25
+ const std::shared_ptr<Node>& cdata,
26
+ const _jvp_fn_t& jvp_user_function,
27
+ const std::unordered_set<at::TensorImpl*>& to_save_if_setup_context,
28
+ const _view_as_self_fn_t& view_as_self_fn,
29
+ bool pure_view);
30
+
31
+ TORCH_API void check_variable_result(
32
+ const at::TensorBase& original,
33
+ const at::TensorBase& result,
34
+ const std::string& hook_name);
35
+
36
+ // Get the return type of the forward function of the custom Function class X
37
+ template <typename X, typename... Args>
38
+ using forward_t = decltype(X::forward(nullptr, std::declval<Args>()...));
39
+
40
+ /// To use custom autograd operations, implement a Function subclass with
41
+ /// static forward and backward functions:
42
+ ///
43
+ /// `forward` can take as many arguments as you want and should return either a
44
+ /// variable list or a Variable. Use of any direct Variable arguments will be
45
+ /// registered in the graph but no vectors/sets or any other data structures
46
+ /// will be traversed. You can use std::optional<Tensor> as one of the arguments
47
+ /// and it will be registered as a variable in the graph if the argument has a
48
+ /// value. It should take a pointer to `torch::autograd::AutogradContext` as the
49
+ /// first argument. Variables can be saved in the `ctx` using
50
+ /// `ctx->save_for_backward`
51
+ /// (see `torch::autograd::AutogradContext::save_for_backward`) and other data
52
+ /// can be saved in the `ctx->saved_data` map
53
+ /// (see `torch::autograd::AutogradContext::saved_data`)
54
+ /// in the form of `<std::string, at::IValue>` pairs.
55
+ ///
56
+ /// `backward` should take a pointer to `torch::autograd::AutogradContext`
57
+ /// and a variable list containing as many Variables as there were outputs from
58
+ /// `forward` as arguments. It should return as many Variables as there were
59
+ /// inputs with each of them containing the gradient w.r.t. its corresponding
60
+ /// input. Variables saved in `forward` can be accessed with
61
+ /// `ctx->get_saved_variables` (see
62
+ /// `torch::autograd::AutogradContext::get_saved_variables`) and other saved
63
+ /// data can be accessed from `ctx->saved_data`.
64
+ /// To enable compiled autograd support (torch.compile for backward) for your
65
+ /// custom autograd operation, you can set MyFunction::is_traceable
66
+ /// (see Function::istraceable notes below).
67
+ ///
68
+ /// For example:
69
+ /// ```
70
+ /// class MyFunction : public Function<MyFunction> {
71
+ /// public:
72
+ /// static constexpr bool is_traceable = true;
73
+ ///
74
+ /// static variable_list forward(AutogradContext *ctx, int n, Variable var) {
75
+ /// // Save data for backward in context
76
+ /// ctx->saved_data["n"] = n;
77
+ /// var.mul_(n);
78
+ /// // Mark var as modified by inplace operation
79
+ /// ctx->mark_dirty({var});
80
+ /// return {var};
81
+ /// }
82
+ ///
83
+ /// static variable_list backward(AutogradContext *ctx, variable_list
84
+ /// grad_output) {
85
+ /// // Use data saved in forward
86
+ /// auto n = ctx->saved_data["n"].toInt();
87
+ /// return {grad_output[0]*n};
88
+ /// }
89
+ /// };
90
+ /// ```
91
+ ///
92
+ /// To use `MyFunction`:
93
+ /// ```
94
+ /// Variable x;
95
+ /// auto y = MyFunction::apply(6, x);
96
+ /// // Example backward call
97
+ /// y[0].sum().backward();
98
+ /// ```
99
+ template <class T>
100
+ struct TORCH_API Function {
101
+ // We need to use a different template parameter than T here because T will
102
+ // inherit from Function, and when Function<T> is instantiated, T::forward
103
+ // is not declared yet.
104
+ // The enable_if check is to ensure that the user doesn't explicitly provide
105
+ // the parameter X.
106
+ template <typename X = T, typename... Args>
107
+ static auto apply(Args&&... args)
108
+ -> std::enable_if_t<std::is_same_v<X, T>, forward_t<X, Args...>>;
109
+
110
+ // This flag is for an experimental feature: compiled autograd. Not all
111
+ // built-in APIs are supported at the moment e.g. mark_dirty and
112
+ // mark_non_differentiable. Before setting this flag to enable tracing for
113
+ // your custom function <T>, you need to ensure that the backward function is
114
+ // traceable i.e. any variables accessed in the backward other than the input
115
+ // arguments must be handled in a similar manner to built-ins in
116
+ // CppNode::compiled_args and CppNode::apply_with_saved.
117
+ static constexpr bool is_traceable = false;
118
+ };
119
+
120
+ /// Context to save information during `forward` that can be accessed in
121
+ /// `backward` in custom autograd operations (see `torch::autograd::Function`
122
+ /// for details).
123
+ struct TORCH_API AutogradContext {
124
+ AutogradContext() = default;
125
+ AutogradContext(const AutogradContext& other) = delete;
126
+ AutogradContext& operator=(const AutogradContext& other) = delete;
127
+ AutogradContext(AutogradContext&& other) = delete;
128
+ AutogradContext& operator=(AutogradContext&& other) = delete;
129
+ ~AutogradContext() = default;
130
+
131
+ AutogradContext(PackedArgs& packed_args);
132
+
133
+ /// Can be used to save non-variable data for `backward`.
134
+ ska::flat_hash_map<std::string, at::IValue> saved_data;
135
+
136
+ /// Saves the list of variables for a future call to `backward`. This
137
+ /// should be called at most once from inside of `forward`.
138
+ void save_for_backward(variable_list to_save);
139
+ /// Marks variables in the list as modified in an in-place operation. This
140
+ /// should be called at most once from inside of `forward` and all arguments
141
+ /// should be inputs.
142
+ void mark_dirty(const variable_list& inputs);
143
+ /// Marks outputs in the list as not requiring gradients. This should be
144
+ /// called at most once from inside of `forward` and all arguments should be
145
+ /// outputs.
146
+ void mark_non_differentiable(const variable_list& outputs);
147
+ // Sets whether undefined output grad tensors should be expanded to tensors
148
+ // full of zeros before calling backward function. Default value is true.
149
+ void set_materialize_grads(bool value);
150
+
151
+ /// Get the list of variables that were saved in `forward` using
152
+ /// `save_for_backward()`. Before returning them to the user, a check is made
153
+ /// to ensure that they were not modified by any in-place operations.
154
+ variable_list get_saved_variables() const;
155
+ const std::unordered_set<at::TensorImpl*>& get_and_bump_dirty() const;
156
+ const std::unordered_set<at::TensorImpl*>& get_non_differentiable() const;
157
+
158
+ /// Expose the Node's `task_should_compute_output` method to the cpp
159
+ /// custom autograd Function as `needs_input_grad`.
160
+ bool needs_input_grad(size_t output_edge_index) const;
161
+ bool needs_input_grad(std::initializer_list<IndexRange> idxs) const;
162
+
163
+ private:
164
+ std::unordered_set<at::TensorImpl*> non_differentiable_;
165
+ std::unordered_set<at::TensorImpl*> dirty_inputs_;
166
+ std::vector<torch::autograd::SavedVariable> saved_variables_;
167
+ variable_list to_save_;
168
+ bool materialize_grads_{true};
169
+
170
+ // The CppNode in the autograd graph that owns this AutogradContext. We need a
171
+ // weak_ptr to avoid a refcycle. Since grad_fn_ owns this AutogradContext, it
172
+ // will always be alive when we want to use it.
173
+ std::weak_ptr<Node> grad_fn_;
174
+ bool has_freed_buffers_{false};
175
+
176
+ // Compiled autograd overrides saved_variables() and needs_input_grad().
177
+ // We store the values we want to return here.
178
+ std::optional<variable_list> saved_variables_override_;
179
+ std::optional<std::vector<bool>> needs_input_grad_override_;
180
+
181
+ void save_variables();
182
+
183
+ template <class T>
184
+ friend struct CppNode;
185
+ template <class T>
186
+ friend variable_list CppNode_apply_functional(
187
+ variable_list&& inputs,
188
+ AutogradContext& ctx_,
189
+ const std::vector<bool>& is_variable_input_,
190
+ const std::vector<VariableInfo>& output_info_,
191
+ const std::string& name);
192
+ };
193
+
194
+ template <typename T>
195
+ inline variable_list CppNode_apply_functional(
196
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
197
+ variable_list&& inputs,
198
+ AutogradContext& ctx_,
199
+ const std::vector<bool>& is_variable_input_,
200
+ const std::vector<VariableInfo>& output_info_,
201
+ const std::string& name) {
202
+ at::OptionalDeviceGuard _device_guard;
203
+
204
+ auto num_inputs = inputs.size();
205
+ variable_list backward_inputs;
206
+ backward_inputs.reserve(num_inputs);
207
+ for (const auto i : c10::irange(num_inputs)) {
208
+ if (inputs[i].defined() || !ctx_.materialize_grads_) {
209
+ backward_inputs.emplace_back(std::move(inputs[i]));
210
+ } else {
211
+ backward_inputs.emplace_back(output_info_[i].zeros(_device_guard));
212
+ }
213
+ }
214
+
215
+ auto outputs = T::backward(&ctx_, backward_inputs);
216
+
217
+ const auto num_forward_inputs =
218
+ static_cast<int64_t>(is_variable_input_.size());
219
+ auto num_outputs = static_cast<int64_t>(outputs.size());
220
+ // Returning too many results is ok, but only as long as they're all
221
+ // undefined. Truncate the result vector in that case.
222
+ if (num_outputs > num_forward_inputs) {
223
+ bool all_undef = true;
224
+ for (const auto i : c10::irange(num_forward_inputs, num_outputs)) {
225
+ all_undef &= (!outputs[i].defined());
226
+ }
227
+ if (all_undef) {
228
+ outputs.resize(num_forward_inputs);
229
+ num_outputs = num_forward_inputs;
230
+ }
231
+ }
232
+
233
+ TORCH_CHECK(
234
+ num_outputs == num_forward_inputs,
235
+ "function ",
236
+ name,
237
+ " returned an incorrect number of gradients (expected ",
238
+ num_forward_inputs,
239
+ ", got ",
240
+ num_outputs,
241
+ ")");
242
+
243
+ variable_list results;
244
+ results.reserve(num_outputs);
245
+ for (const auto i : c10::irange(num_outputs)) {
246
+ if (!is_variable_input_[i]) {
247
+ TORCH_CHECK(
248
+ outputs[i].defined() == false,
249
+ "function ",
250
+ name,
251
+ " returned a gradient different that is defined at position ",
252
+ i + 1,
253
+ ", std the corresponding forward input was not a Variable");
254
+ continue;
255
+ }
256
+ results.emplace_back(outputs[i]);
257
+ }
258
+
259
+ return results;
260
+ }
261
+
262
+ template <typename T>
263
+ inline variable_list CppNode_apply_functional_ivalue(
264
+ const variable_list& inputs,
265
+ const std::vector<c10::IValue>& args) {
266
+ auto packed_args = PackedArgs(args);
267
+ auto ctx = AutogradContext(packed_args);
268
+ auto output_info = packed_args.unpack<std::vector<VariableInfo>>();
269
+ auto is_variable_input = packed_args.unpack<std::vector<bool>>();
270
+ auto name = packed_args.unpack<std::string>();
271
+ return CppNode_apply_functional<T>(
272
+ variable_list(inputs), ctx, is_variable_input, output_info, name);
273
+ }
274
+
275
+ // CppNode<T> is the Node in the autograd graph that represents the user defined
276
+ // backward function for Function<T>. Calls to CppNode::apply are forward to
277
+ // T::backward().
278
+ template <class T>
279
+ struct CppNode : public Node {
280
+ variable_list apply(variable_list&& inputs) override;
281
+ AutogradContext ctx_;
282
+ std::vector<bool> is_variable_input_;
283
+ std::vector<VariableInfo> input_info_;
284
+ std::vector<VariableInfo> output_info_;
285
+
286
+ void release_variables() override;
287
+
288
+ void set_ctx_grad_fn(const std::shared_ptr<Node>& node);
289
+ void save_variables_to_ctx();
290
+
291
+ void compiled_args(CompiledNodeArgs& args) const override {
292
+ // although neither of the 2 methods below have uniqueness guarantees
293
+ // it is unlikely for them to collide at the same time
294
+ args.collect(static_cast<uint64_t>(typeid(T).hash_code()));
295
+ args.collect(std::string(typeid(T).name()));
296
+
297
+ args.collect(ctx_.saved_data);
298
+ TORCH_INTERNAL_ASSERT(ctx_.non_differentiable_.empty());
299
+ TORCH_INTERNAL_ASSERT(ctx_.dirty_inputs_.empty());
300
+ args.collect(
301
+ ctx_.saved_variables_, true); // always unpacked as output in eager
302
+ TORCH_INTERNAL_ASSERT(ctx_.to_save_.empty());
303
+ args.collect(ctx_.materialize_grads_);
304
+ args.collect(ctx_.has_freed_buffers_);
305
+ args.collect(is_variable_input_);
306
+ args.collect(input_info_);
307
+ args.collect(output_info_);
308
+ }
309
+
310
+ variable_list apply_with_saved(
311
+ const variable_list& inputs,
312
+ SwapSavedVariables& saved) override {
313
+ saved.before(ctx_.saved_data);
314
+ TORCH_INTERNAL_ASSERT(ctx_.non_differentiable_.empty());
315
+ TORCH_INTERNAL_ASSERT(ctx_.dirty_inputs_.empty());
316
+ saved.before(ctx_.saved_variables_);
317
+ TORCH_INTERNAL_ASSERT(ctx_.to_save_.empty());
318
+ saved.before(ctx_.materialize_grads_);
319
+ saved.before(ctx_.has_freed_buffers_);
320
+ saved.before(input_info_);
321
+ saved.before(output_info_);
322
+
323
+ PackedArgs packed_args;
324
+ packed_args.pack_saved_data(ctx_.saved_data);
325
+ variable_list saved_variables = ctx_.get_saved_variables();
326
+ packed_args.pack(saved_variables);
327
+ packed_args.pack(ctx_.materialize_grads_);
328
+ packed_args.pack(ctx_.has_freed_buffers_);
329
+
330
+ std::vector<bool> needs_input_grad;
331
+ {
332
+ auto ptr = ctx_.grad_fn_.lock();
333
+ TORCH_INTERNAL_ASSERT(ptr);
334
+ for (const auto i : c10::irange(ptr->next_edges().size())) {
335
+ needs_input_grad.push_back(ptr->task_should_compute_output(i));
336
+ }
337
+ }
338
+ packed_args.pack(needs_input_grad);
339
+
340
+ packed_args.pack(output_info_);
341
+ packed_args.pack(is_variable_input_);
342
+ packed_args.pack(name());
343
+ auto args = std::move(packed_args).vec();
344
+
345
+ auto output_metadata = torch::dynamo::autograd::
346
+ IValuePacker<std::vector<std::optional<InputMetadata>>>::pack(
347
+ torch::dynamo::autograd::get_input_metadata(next_edges()));
348
+
349
+ const auto& pyinterface = torch::dynamo::autograd::getPyCompilerInterface();
350
+
351
+ // Each time apply_with_saved is called, we bind a new function to Python.
352
+ // This is because the schema might be different on compiled autograd cache
353
+ // misses. An alternative is to pass the schema to Python so that it can be
354
+ // an input to a function, but the schema can't be put into an FX graph
355
+ // right now.
356
+ std::vector<at::TypePtr> schema;
357
+ schema.reserve(args.size());
358
+ for (const auto& ivalue : args) {
359
+ if (ivalue.isTensor()) {
360
+ schema.emplace_back(at::TensorType::get());
361
+ } else {
362
+ schema.emplace_back(ivalue.type());
363
+ }
364
+ }
365
+ static_assert(
366
+ std::is_same_v<std::remove_cv_t<decltype(T::is_traceable)>, bool>);
367
+ auto fn_name = pyinterface->bind_function(
368
+ saved.get_py_compiler(),
369
+ std::string(typeid(T).name()),
370
+ CppNode_apply_functional_ivalue<T>,
371
+ schema,
372
+ /*is_custom_function*/ true,
373
+ /*is_traceable*/ T::is_traceable);
374
+
375
+ auto results = pyinterface->call_function(
376
+ saved.get_py_compiler(),
377
+ "apply_functional",
378
+ fn_name,
379
+ inputs,
380
+ args,
381
+ output_metadata);
382
+
383
+ saved.after(ctx_.saved_data);
384
+ TORCH_INTERNAL_ASSERT(ctx_.non_differentiable_.empty());
385
+ TORCH_INTERNAL_ASSERT(ctx_.dirty_inputs_.empty());
386
+ saved.after(ctx_.saved_variables_);
387
+ TORCH_INTERNAL_ASSERT(ctx_.to_save_.empty());
388
+ saved.after(ctx_.materialize_grads_);
389
+ saved.after(ctx_.has_freed_buffers_);
390
+ saved.after(input_info_);
391
+ saved.after(output_info_);
392
+ return results;
393
+ }
394
+ };
395
+
396
+ struct ExtractVariables : IterArgs<ExtractVariables> {
397
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
398
+ std::vector<bool>& is_var_;
399
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
400
+ variable_list& list_;
401
+ ExtractVariables(std::vector<bool>& is_var, variable_list& list)
402
+ : is_var_(is_var), list_(list) {}
403
+ void operator()(const std::optional<at::Tensor>& x) {
404
+ if (x.has_value() && x.value().defined()) {
405
+ is_var_.push_back(true);
406
+ list_.emplace_back(x.value());
407
+ } else {
408
+ is_var_.push_back(false);
409
+ }
410
+ }
411
+ void operator()(const at::Tensor& x) {
412
+ is_var_.push_back(true);
413
+ list_.emplace_back(x);
414
+ }
415
+ void operator()(const at::TensorList& list) {
416
+ for (const at::Tensor& x : list) {
417
+ is_var_.push_back(true);
418
+ list_.emplace_back(x);
419
+ }
420
+ }
421
+ template <typename T>
422
+ void operator()(const T& x) {
423
+ is_var_.push_back(false);
424
+ }
425
+ };
426
+
427
+ template <typename... Args>
428
+ inline void extract_vars(
429
+ std::vector<bool>& is_var,
430
+ variable_list& list,
431
+ Args&&... args) {
432
+ ExtractVariables(is_var, list).apply(std::forward<Args>(args)...);
433
+ }
434
+
435
+ template <typename T>
436
+ std::enable_if_t<std::is_same_v<T, variable_list>, T> to_output_type(
437
+ std::vector<std::optional<Variable>>& output_list) {
438
+ variable_list result;
439
+ std::transform(
440
+ output_list.begin(),
441
+ output_list.end(),
442
+ std::back_inserter(result),
443
+ [](const std::optional<Variable>& var) { return *var; });
444
+ return result;
445
+ }
446
+
447
+ template <typename T>
448
+ std::enable_if_t<std::is_same_v<T, Variable>, T> to_output_type(
449
+ std::vector<std::optional<Variable>>& output_list) {
450
+ return *output_list[0];
451
+ }
452
+
453
+ inline std::vector<std::optional<Variable>> to_optional(Variable& output) {
454
+ return std::vector<std::optional<Variable>>{output};
455
+ }
456
+
457
+ inline std::vector<std::optional<Variable>> to_optional(variable_list& output) {
458
+ std::vector<std::optional<Variable>> result;
459
+ std::transform(
460
+ output.begin(),
461
+ output.end(),
462
+ std::back_inserter(result),
463
+ [](const Variable& var) { return var; });
464
+ return result;
465
+ }
466
+
467
+ template <class T>
468
+ template <typename X, typename... Args>
469
+ auto Function<T>::apply(Args&&... args)
470
+ -> std::enable_if_t<std::is_same_v<X, T>, forward_t<X, Args...>> {
471
+ const auto& functorch_tls = at::functorch::functorchTLSAccessor();
472
+ if (functorch_tls) {
473
+ // Function support for functorch is handled in Python.
474
+ // Here we are dealing with a (C++) Function, which is not supported.
475
+ // Let's raise an error instead of being silently incorrect.
476
+ functorch_tls->checkSupportsCppAutogradFunction();
477
+ }
478
+
479
+ std::shared_ptr<CppNode<T>> node(new CppNode<T>(), deleteNode);
480
+ variable_list input_vars;
481
+
482
+ const size_t num_inputs = sizeof...(Args);
483
+ input_vars.reserve(num_inputs);
484
+ node->is_variable_input_.reserve(num_inputs);
485
+ // TODO Add tracing here
486
+ extract_vars(node->is_variable_input_, input_vars, args...);
487
+
488
+ bool is_executable =
489
+ GradMode::is_enabled() && any_variable_requires_grad(input_vars);
490
+ auto next_edges =
491
+ (is_executable ? collect_next_edges(input_vars) : edge_list());
492
+ node->set_ctx_grad_fn(node);
493
+ node->set_next_edges(std::move(next_edges));
494
+ node->clear_input_metadata();
495
+
496
+ node->input_info_.reserve(input_vars.size());
497
+ for (auto& var : input_vars) {
498
+ node->input_info_.emplace_back(var);
499
+ }
500
+
501
+ using forward_return_t = forward_t<X, Args...>;
502
+ forward_return_t outputs;
503
+ {
504
+ AutoGradMode grad_mode(false);
505
+ outputs = T::forward(&node->ctx_, std::forward<Args>(args)...);
506
+ }
507
+
508
+ _jvp_fn_t jvp_fn = [](const variable_list& inputs,
509
+ const variable_list& gI) -> variable_list {
510
+ TORCH_CHECK(
511
+ false,
512
+ "jvp is not implemented for the c++ API of custom Function yet.",
513
+ "Please open a feature request on GitHub if you need this.");
514
+ };
515
+
516
+ auto view_as_self_fn = [](const at::Tensor& x) -> at::Tensor {
517
+ return x.view_as(x);
518
+ };
519
+
520
+ auto wrapped_outputs = _wrap_outputs(
521
+ input_vars,
522
+ node->ctx_.get_non_differentiable(),
523
+ node->ctx_.get_and_bump_dirty(),
524
+ to_optional(outputs),
525
+ is_executable ? node : nullptr,
526
+ jvp_fn,
527
+ {},
528
+ view_as_self_fn,
529
+ false);
530
+
531
+ node->output_info_.reserve(wrapped_outputs.size());
532
+ for (auto& output : wrapped_outputs) {
533
+ if (is_executable && output.has_value()) {
534
+ node->output_info_.emplace_back(output.value());
535
+ } else if (is_executable) {
536
+ node->output_info_.emplace_back();
537
+ }
538
+ }
539
+
540
+ if (is_executable) {
541
+ node->save_variables_to_ctx();
542
+ }
543
+
544
+ // wrapped_outputs will be a variable_list so, convert it to the correct
545
+ // return type. Only Variable and variable_list are accepted as return types.
546
+ return to_output_type<forward_return_t>(wrapped_outputs);
547
+ }
548
+
549
+ // The logic here is the same as PyNode::apply, so changes to it should be done
550
+ // in both the places
551
+ template <class T>
552
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
553
+ variable_list CppNode<T>::apply(variable_list&& inputs) {
554
+ // Acquire lock to here protect thread safety on custom C++ Autograd Node
555
+ // This is needed for the custom Autograd Node since we don't know if the
556
+ // user defined Node will write to the shared data during backward.
557
+ // see Note [Thread Safety on Autograd Node]
558
+ std::lock_guard<std::mutex> lock(mutex_);
559
+ return CppNode_apply_functional<T>(
560
+ std::move(inputs), ctx_, is_variable_input_, output_info_, name());
561
+ }
562
+
563
+ template <class T>
564
+ void CppNode<T>::release_variables() {
565
+ // lock to ensure thread safety, see [Thread Safety on Autograd Node]
566
+ std::lock_guard<std::mutex> lock(mutex_);
567
+ ctx_.saved_variables_.clear();
568
+ ctx_.has_freed_buffers_ = true;
569
+ }
570
+
571
+ template <class T>
572
+ void CppNode<T>::save_variables_to_ctx() {
573
+ ctx_.save_variables();
574
+ }
575
+
576
+ template <class T>
577
+ void CppNode<T>::set_ctx_grad_fn(const std::shared_ptr<Node>& node) {
578
+ ctx_.grad_fn_ = node;
579
+ }
580
+
581
+ } // namespace torch::autograd
582
+
583
+ #else
584
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
585
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/edge.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cstdint>
5
+ #include <functional>
6
+ #include <memory>
7
+
8
+ #include <c10/util/hash.h>
9
+
10
+ namespace torch::autograd {
11
+
12
+ struct Node;
13
+
14
+ /// Represents a particular input of a function.
15
+ struct Edge {
16
+ Edge() noexcept : function(nullptr), input_nr(0) {}
17
+
18
+ Edge(std::shared_ptr<Node> function_, uint32_t input_nr_) noexcept
19
+ : function(std::move(function_)), input_nr(input_nr_) {}
20
+
21
+ /// Convenience method to test if an edge is valid.
22
+ bool is_valid() const noexcept {
23
+ return function != nullptr;
24
+ }
25
+
26
+ // Required for use in associative containers.
27
+ bool operator==(const Edge& other) const noexcept {
28
+ return this->function == other.function && this->input_nr == other.input_nr;
29
+ }
30
+
31
+ bool operator!=(const Edge& other) const noexcept {
32
+ return !(*this == other);
33
+ }
34
+
35
+ /// The function this `Edge` points to.
36
+ std::shared_ptr<Node> function;
37
+
38
+ /// The identifier of a particular input to the function.
39
+ uint32_t input_nr;
40
+ };
41
+ } // namespace torch::autograd
42
+
43
+ // The idiomatic way of enabling use of a custom type as the key of hash
44
+ // containers in C++11. This method removes the requirement of having to pass
45
+ // a custom hasher to std::unordered_{map, set}.
46
+ // See http://en.cppreference.com/w/cpp/utility/hash for more information.
47
+ namespace std {
48
+ template <>
49
+ struct hash<torch::autograd::Edge> {
50
+ // These type aliases are required by the standard.
51
+ using argument_type = torch::autograd::Edge;
52
+ using return_type = size_t;
53
+ return_type operator()(const argument_type& edge) const noexcept {
54
+ return c10::get_hash(edge.function, edge.input_nr);
55
+ }
56
+ };
57
+ } // namespace std
58
+
59
+ #else
60
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
61
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/engine.h ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // Engine implements backpropagation from output variables and their gradients
5
+ // to "root" variables (variables created by the user with requires_grad=True).
6
+
7
+ #include <ATen/Tensor.h>
8
+ #include <ATen/ThreadLocalState.h>
9
+ #include <ATen/core/ivalue.h>
10
+ #include <torch/csrc/Export.h>
11
+ #include <torch/csrc/autograd/anomaly_mode.h>
12
+ #include <torch/csrc/autograd/function.h>
13
+ #include <torch/csrc/autograd/functions/basic_ops.h>
14
+ #include <torch/csrc/autograd/graph_task.h>
15
+ #include <torch/csrc/autograd/input_buffer.h>
16
+ #include <torch/csrc/autograd/saved_variable_hooks.h>
17
+ #include <torch/csrc/autograd/utils/warnings.h>
18
+
19
+ #include <exception>
20
+ #include <functional>
21
+ #include <memory>
22
+ #include <queue>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ namespace torch::autograd {
27
+ struct ReadyQueue;
28
+ }
29
+
30
+ namespace torch::autograd {
31
+
32
+ // Maximum reentrant backward depth before switching to a new thread
33
+ // This limit is based on the TSAN's deadlock detector, where it will
34
+ // fail if a program hold more than 65 locks in one thread at once.
35
+ // As we hold mutex in every of our custom C++ autograd Node, we would
36
+ // like to avoid TSAN complains on this when doing reentrant backwards
37
+ // For reference, see https://github.com/google/sanitizers/issues/950
38
+ static constexpr int MAX_DEPTH = 60;
39
+
40
+ void set_device(int device);
41
+ TORCH_API void validate_outputs(
42
+ const edge_list& edges,
43
+ variable_list& grads,
44
+ const std::function<std::string(const std::string&)>& format_error);
45
+ TORCH_API void validate_outputs(
46
+ const std::vector<std::optional<InputMetadata>>& input_metadata,
47
+ variable_list& grads,
48
+ const std::function<std::string(const std::string&)>& format_error);
49
+ TORCH_API std::vector<std::optional<InputMetadata>> collect_input_metadata(
50
+ const edge_list& edges);
51
+
52
+ struct NodeTask {
53
+ std::weak_ptr<GraphTask> base_;
54
+ std::shared_ptr<Node> fn_;
55
+ // This buffer serves as an implicit "addition" node for all of the
56
+ // gradients flowing here. Once all the dependencies are finished, we
57
+ // use the contents of this buffer to run the function.
58
+ InputBuffer inputs_;
59
+ // When worker receives a task with isShutdownTask = true, it will immediately
60
+ // exit. The engine sends a shutdown task to every queue upon its destruction.
61
+ bool isShutdownTask_;
62
+
63
+ int getReentrantDepth() const;
64
+
65
+ NodeTask(
66
+ std::weak_ptr<GraphTask> base,
67
+ std::shared_ptr<Node> fn,
68
+ InputBuffer inputs,
69
+ bool isShutdownTask = false)
70
+ : base_(std::move(base)),
71
+ fn_(std::move(fn)),
72
+ inputs_(std::move(inputs)),
73
+ isShutdownTask_(isShutdownTask) {}
74
+ };
75
+
76
+ // Guard that sets and restores checkpoint_valid
77
+ class CheckpointValidGuard {
78
+ public:
79
+ explicit CheckpointValidGuard(
80
+ const std::shared_ptr<const GraphTask>& graph_task);
81
+ ~CheckpointValidGuard();
82
+
83
+ private:
84
+ bool prev_checkpoint_valid_state;
85
+ };
86
+
87
+ struct ReadyQueue {
88
+ private:
89
+ // Returns true when t2 should be (weakly) BEFORE t1 in the queue.
90
+ // Shutdown tasks are first and then empty NodeTask are next.
91
+ struct CompareNodeTaskTime {
92
+ bool operator()(NodeTask const& t1, NodeTask const& t2) {
93
+ // NOLINTNEXTLINE(bugprone-branch-clone)
94
+ if (t2.isShutdownTask_) {
95
+ return true;
96
+ } else if (!t1.fn_ || t1.isShutdownTask_) {
97
+ return false;
98
+ } else if (!t2.fn_) {
99
+ return true;
100
+ } else if (t1.getReentrantDepth() == t2.getReentrantDepth()) {
101
+ return t1.fn_->sequence_nr() < t2.fn_->sequence_nr();
102
+ } else {
103
+ return t1.getReentrantDepth() < t2.getReentrantDepth();
104
+ }
105
+ }
106
+ };
107
+
108
+ // To notify threads waiting on the ReadyQueue of available tasks on the heap_
109
+ std::condition_variable not_empty_;
110
+ // To protect read and writes to heap_
111
+ mutable std::mutex mutex_;
112
+
113
+ std::priority_queue<NodeTask, std::vector<NodeTask>, CompareNodeTaskTime>
114
+ heap_;
115
+
116
+ public:
117
+ // incrementOutstandingTasks indicates whether or not we should increment
118
+ // 'outstanding_tasks_' for the associated GraphTask. This should mostly
119
+ // always be true and is only set false in certain cases (see docs for
120
+ // DistEngine.execute_graph_task_until_ready_queue_empty)
121
+ void push(NodeTask item, bool incrementOutstandingTasks = true);
122
+ void pushShutdownTask();
123
+ NodeTask pop();
124
+ bool empty() const;
125
+ size_t size() const;
126
+ };
127
+
128
+ // A single instance of this struct should be created through the whole process
129
+ // lifetime. The worker thread creation logic and Engine's destructor rely on
130
+ // this.
131
+ struct TORCH_API Engine {
132
+ /// Returns a reference to a static `Engine` instance.
133
+ static Engine& get_default_engine();
134
+
135
+ static Engine& get_base_engine();
136
+
137
+ // compiled_autograd needs to live in a different .so file so that it
138
+ // can have python symbols, so we add a layer of indirection
139
+ // see [Note: Compiled Autograd]
140
+ typedef variable_list (*compiled_autograd_fn)(
141
+ const std::shared_ptr<Node>& graph_root,
142
+ const GraphTask& graph_task,
143
+ bool accumulate_grad,
144
+ const edge_list& outputs);
145
+ static void set_compiled_autograd(compiled_autograd_fn fn);
146
+
147
+ Engine(const Engine&) = delete;
148
+ Engine(Engine&&) = delete;
149
+ virtual ~Engine();
150
+
151
+ // Given a list of (Node, input number) pairs computes the value of the graph
152
+ // by following next_edge references.
153
+ virtual variable_list execute(
154
+ const edge_list& roots,
155
+ const variable_list& inputs,
156
+ bool keep_graph,
157
+ bool create_graph,
158
+ bool accumulate_grad,
159
+ const edge_list& outputs = {});
160
+
161
+ // Given a pre-populated GraphTask and GraphRoot, computes the backward pass
162
+ // for the graph.
163
+ //
164
+ // NB: This API should only be used by internal autograd specific
165
+ // machinery and shouldn't be exposed to users in anyway.
166
+ virtual c10::intrusive_ptr<at::ivalue::Future> execute_with_graph_task(
167
+ const std::shared_ptr<GraphTask>& graph_task,
168
+ std::shared_ptr<Node> graph_root,
169
+ InputBuffer&& input_buffer);
170
+
171
+ virtual std::unique_ptr<AnomalyMetadata> make_anomaly_metadata() {
172
+ return std::make_unique<AnomalyMetadata>();
173
+ }
174
+
175
+ virtual std::unique_ptr<SavedVariableHooks> get_default_saved_variable_hooks() {
176
+ return nullptr;
177
+ }
178
+
179
+ // We pass cpu_ready_queue to evaluate_function, so that it knows
180
+ // the correct ready queue to push to after a NodeTask is ready
181
+ void evaluate_function(
182
+ std::shared_ptr<GraphTask>& graph_task,
183
+ Node* func,
184
+ InputBuffer& inputs,
185
+ const std::shared_ptr<ReadyQueue>& cpu_ready_queue);
186
+
187
+ void initialize_device_threads_pool();
188
+ virtual void thread_on_exception(
189
+ const std::shared_ptr<GraphTask>& graph_task,
190
+ const std::shared_ptr<Node>& fn,
191
+ std::exception& e);
192
+
193
+ void queue_callback(std::function<void()> callback);
194
+
195
+ bool is_checkpoint_valid();
196
+
197
+ // Should be called after fork to notify that worker threads are gone
198
+ void release_workers();
199
+
200
+ // Must be called by subclass before destructing to avoid a data-race-on-vptr.
201
+ void stop();
202
+
203
+ // Initializes a device thread for the autograd engine.
204
+ virtual void thread_init(
205
+ int device,
206
+ const std::shared_ptr<ReadyQueue>& ready_queue,
207
+ bool should_increment = true);
208
+
209
+ protected:
210
+ Engine();
211
+ void compute_dependencies(Node* root, GraphTask& task, uint64_t min_topo_nr);
212
+
213
+ // initialize the thread local ready queue with the ready queue that is
214
+ // created elsewhere (i.e. thread_init, Engine::execute, etc), or create a new
215
+ // ready queue if ready_queue is not provided.
216
+ void init_local_ready_queue(
217
+ std::shared_ptr<ReadyQueue> ready_queue = nullptr);
218
+
219
+ std::shared_ptr<ReadyQueue> ready_queue(
220
+ std::shared_ptr<ReadyQueue> cpu_ready_queue,
221
+ at::Device device);
222
+ std::shared_ptr<ReadyQueue> ready_queue_by_index(
223
+ std::shared_ptr<ReadyQueue> cpu_ready_queue,
224
+ int device_index);
225
+ // start device threads (CUDA, XLA, etc.) in Engine,
226
+ // note that it does NOT start CPU thread.
227
+ void start_device_threads();
228
+ void increment_non_reentrant_thread_count();
229
+ void decrement_non_reentrant_thread_count();
230
+ virtual void thread_main(const std::shared_ptr<GraphTask>& task);
231
+ void reentrant_thread_init();
232
+ void add_thread_pool_task(const std::weak_ptr<GraphTask>& graph_task);
233
+
234
+ // Safe to read device_ready_queues_ without synchronization after
235
+ // initialization
236
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
237
+ std::vector<std::shared_ptr<ReadyQueue>> device_ready_queues_;
238
+
239
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
240
+ std::vector<std::function<void()>> final_callbacks_;
241
+ // To protect reads and writes to final_callbacks_
242
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
243
+ std::mutex post_callbacks_lock_;
244
+
245
+ // How many nested reentrant calls are allowed until a new thread is used
246
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
247
+ int max_recursion_depth_;
248
+
249
+ struct ThreadPoolShared {
250
+ // Data structures used by the threads for executing reentrant backwards
251
+ // tasks. See Note [Reentrant backwards]
252
+ // Number of available threads for processing new GraphTasks.
253
+ unsigned int num_workers_{0};
254
+ // The threads will wait on work_ to be notified of GraphTasks
255
+ std::condition_variable work_;
256
+ // To protect reads and writes to graphtask_queue_ and num_workers_
257
+ // and for synchronizing creating new threads when needed
258
+ std::mutex mutex_;
259
+ // Workers will process the GraphTasks added to this queue. A GraphTask is
260
+ // allocated inside Engine::execute and lives for the duration of execute
261
+ std::queue<std::weak_ptr<GraphTask>> graphtasks_queue_;
262
+
263
+ ThreadPoolShared() = default;
264
+ };
265
+
266
+ // Temporary workaround until shutting down threads is done
267
+ // We need shared ownership of all these objects because the threads are
268
+ // leaked when Engine shuts down, so there may be threads waiting on work_ for
269
+ // the graphtasks_queue_ to be nonempty.
270
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
271
+ std::shared_ptr<ThreadPoolShared> thread_pool_shared_;
272
+
273
+ private:
274
+ // Number of non-reentrant threads
275
+ std::atomic<uint32_t> non_reentrant_device_thread_count_;
276
+ // Destructor will wait for non-reentrant threads to finish
277
+ std::condition_variable non_reentrant_device_thread_condvar_;
278
+ std::mutex non_reentrant_device_thread_mutex_;
279
+ // stop() must be called before the destruction path goes down to the base
280
+ // class, in order to avoid a data-race-on-vptr. Use this boolean to guard
281
+ // whether stop() has already been called, so we can call this in every
282
+ // destructor of the class hierarchy.
283
+ bool stopped_{false};
284
+ };
285
+
286
+ // allow python_engine to override the default engine when it loads
287
+ using EngineStub = Engine& (*)();
288
+ TORCH_API void set_default_engine_stub(EngineStub stub);
289
+
290
+ } // namespace torch::autograd
291
+
292
+ #else
293
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
294
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/forward_grad.h ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <unordered_set>
6
+
7
+ namespace torch::autograd {
8
+
9
+ // [ Using ForwardGrad ]
10
+ // ForwardGrad needs to be a shared_ptr to satisfy constraints of its inner
11
+ // design. But this shared_ptr must be uniquely associated with the object that
12
+ // stores it (as of writing, either AutogradMeta or SavedVariable). This object
13
+ // is called the "owning object" in the discussions below. This owning object
14
+ // must call `ForwardGrad::clear()` when it is destroyed to ensure that the
15
+ // ForwardGrad is properly de-allocated.
16
+
17
+ struct ForwardGrad;
18
+
19
+ // This file contains two classes that are used to store forward AD gradients
20
+ // and ensure that they are scoped properly. Because forward AD runs
21
+ // concurrently with the evaluation of the function, we need a mechanism to
22
+ // separate different forward AD invocations and be able to compute the right
23
+ // gradients. We model such invocations as levels here. The particular scoping
24
+ // issue mentioned above has two main drivers:
25
+ // - Ensure that we can conveniently use forward AD within a high level API
26
+ // without
27
+ // leaking the forward AD states outside.
28
+ // - Ensure that we can keep the level that we expose to the user API simple
29
+ // (an integer
30
+ // that represents the nesting depth) while avoiding confusions when the
31
+ // level index is reused.
32
+
33
+ // The important external APIs from this file are:
34
+ // - ForwardADLevel::get_next_idx() that can be used to enter a new level and
35
+ // get its index
36
+ // - ForwardADLevel::release_idx() that can be used to exit a given level.
37
+ // - ForwardGrad() can be used to store a given forward gradient that will
38
+ // handle the level
39
+ // tracking automatically.
40
+
41
+ // The basic implementation strategy is as follows:
42
+ // Every tensor has a ForwardGrad, maintaining a map from levels to tangents.
43
+ // ForwardGrad is responsible for registering itself to the appropriate
44
+ // ForwardADLevel when a new tangent is added to it via ForwardGrad::set_value
45
+ // and to un-register itself from this same level if that tangent is removed via
46
+ // ForwardGrad::reset. The ForwardADLevel is created when a new level is entered
47
+ // via ForwardADLevel::get_next_idx. A reference to the new ForwardADLevel is
48
+ // stored into a global (for the whole process) vector that ensure it can be
49
+ // accessed via ForwardADLevel::get_by_idx. This reference is deleted when the
50
+ // index is released by the user when calling ForwardADLevel::release_idx. When
51
+ // it is destructed, the ForwardADLevel is responsible for clearing all the
52
+ // tangents for its level stored in all the ForwardGrad that registered with it.
53
+ //
54
+ // This process-wide level design, compared to a thread local one, allows us to
55
+ // use very simple user facing handle for the level (an int) while enabling
56
+ // cross-thread forward AD. The only required synchronization for the user is
57
+ // when entering and exiting the levels. Some discussion on alternative design
58
+ // is in https://github.com/pytorch/pytorch/pull/49097#discussion_r543716453 and
59
+ // can be refined in the future.
60
+
61
+ // Correctness of concurrency:
62
+ // Each class uses its own lock when reading or modifying internal storages.
63
+ // This allows in particular to safely remove tangents from ForwardGrad when the
64
+ // ForwardADLevel is being exited. We ensure no deadlock by ensuring that a
65
+ // methods never calls into another class's method while the local class's lock
66
+ // is held except in one single case: calling from ForwardADLevel's destructor
67
+ // into ForwardGrad::reset with update_level=false.
68
+
69
+ // The lifetime of these objects is as follows:
70
+ // The ForwardADLevel can be in three states:
71
+ // - Initialized: where one of its reference is held by the global vector
72
+ // and there may be more
73
+ // references held by temporary variables in ForwardGrad's methods.
74
+ // - About to be destructed: where "release_idx" has been called and the
75
+ // only reason for the
76
+ // ForwardADLevel not to be destructed right away is that some methods in
77
+ // ForwardGrad have owning reference to it. This is done so that a
78
+ // ForwardADLevel can never be destructed when a ForwardGrad is
79
+ // registered with it and in the process of adding something to its
80
+ // internal state.
81
+ // - Being destructed: Here the ForwardADLevel is not referenced anymore
82
+ // and can be safely reset
83
+ // all of the ForwardGrad. Note that we can have more than one reset
84
+ // being called here (which is ok) but we are guaranteed that there is at
85
+ // least one.
86
+ // The ForwardGrad is simpler as there is no intermediary state and no special
87
+ // destructor for. The logic to unregister it from the different ForwardADLevel
88
+ // is done when the owning object (AutogradMeta or SavedVariable) is being
89
+ // destroyed.
90
+
91
+ // Other considered design:
92
+ // To avoid having the ForwardGrad::clear, we considered storing weak_ptr inside
93
+ // the ForwardADLevel. While this would work, it would mean that the set inside
94
+ // the ForwardADLevel would only grow unless we do an expensive linear scan to
95
+ // remove all the dangling weak pointers. Hence this approach was not used.
96
+
97
+ // Data structures in this file are optimized for this maximum number of levels.
98
+ // The number of levels corresponds to the degree of the gradient being
99
+ // computed using forward AD and we don't expect more than second order
100
+ // gradients to be common.
101
+ #define EXPECTED_MAX_LEVEL 2
102
+
103
+ struct TORCH_API ForwardADLevel {
104
+ ForwardADLevel(uint64_t idx) : idx_(idx) {}
105
+ ~ForwardADLevel();
106
+
107
+ static uint64_t get_next_idx();
108
+ static void release_idx(uint64_t idx);
109
+ static std::shared_ptr<ForwardADLevel> get_by_idx(uint64_t idx);
110
+ static std::shared_ptr<ForwardADLevel> try_get_by_idx(uint64_t idx);
111
+
112
+ void erase(const std::shared_ptr<ForwardGrad>& grad) {
113
+ std::lock_guard<std::mutex> lock(mutex_);
114
+ grads_.erase(grad);
115
+ }
116
+
117
+ void insert(const std::shared_ptr<ForwardGrad>& grad) {
118
+ std::lock_guard<std::mutex> lock(mutex_);
119
+ grads_.insert(grad);
120
+ }
121
+
122
+ private:
123
+ std::unordered_set<std::shared_ptr<ForwardGrad>> grads_;
124
+ std::mutex mutex_;
125
+ uint64_t idx_;
126
+ };
127
+
128
+ struct TORCH_API ForwardGrad : std::enable_shared_from_this<ForwardGrad> {
129
+ ForwardGrad() = default;
130
+
131
+ // This function must only be called when AutogradMeta or SavedVariable is
132
+ // being destructed as it ensures that:
133
+ // - The only (potential) other references to this ForwardGrad are the
134
+ // different level it is registered to
135
+ // - No other thread will try to call `set_value` or `value` ever from now
136
+ // on
137
+ // - Any of the ForwardADLevel that this ForwardGrad is registered with
138
+ // might
139
+ // call `reset` at any point during this function
140
+ void clear() {
141
+ c10::SmallVector<uint64_t, EXPECTED_MAX_LEVEL> levels_idx;
142
+
143
+ {
144
+ std::lock_guard<std::mutex> lock(mutex_);
145
+ for (auto& c : content_) {
146
+ levels_idx.push_back(c.first);
147
+ }
148
+ }
149
+
150
+ for (auto l_idx : levels_idx) {
151
+ // Use "try" version here as another thread might have deleted this
152
+ // level before we got here
153
+ // This is an owning reference as we want to keep the level alive
154
+ // until we successfully unregister ourselves
155
+ auto level = ForwardADLevel::try_get_by_idx(l_idx);
156
+ if (level) {
157
+ level->erase(shared_from_this());
158
+ }
159
+ }
160
+ }
161
+
162
+ void set_value(const at::Tensor& value, uint64_t level) {
163
+ // Owning reference to ensure the forward_level is not destroyed
164
+ // while we are updating our internal state
165
+ auto forward_level = ForwardADLevel::get_by_idx(level);
166
+ forward_level->insert(shared_from_this());
167
+
168
+ std::lock_guard<std::mutex> lock(mutex_);
169
+ content_.insert({level, value});
170
+ }
171
+
172
+ // This function removes the tangent for a given level from this ForwardGrad
173
+ // Use the update_level flag to disable notifying the level about this reset
174
+ // This flag is most notably used by the ForwardADLevel destructor.
175
+ void reset(uint64_t level, bool update_level = true) {
176
+ if (update_level) {
177
+ ForwardADLevel::get_by_idx(level)->erase(shared_from_this());
178
+ }
179
+
180
+ std::unique_lock<std::mutex> lock(mutex_);
181
+ const auto& it = content_.find(level);
182
+ TORCH_INTERNAL_ASSERT(
183
+ it != content_.end(), "Resetting a non-existent level.");
184
+ // Keep the Tensor alive until we have released the lock
185
+ // This is needed as we can be in a case where this function is called by
186
+ // ForwardADLevel destructor
187
+ auto t = (*it).second;
188
+ content_.erase(level);
189
+ lock.unlock();
190
+ }
191
+
192
+ const at::Tensor& value(uint64_t level) const;
193
+
194
+ bool contains(uint64_t level) {
195
+ std::lock_guard<std::mutex> lock(mutex_);
196
+ return content_.count(level) > 0;
197
+ }
198
+
199
+ bool empty() const {
200
+ return content_.empty();
201
+ }
202
+
203
+ static const at::Tensor& undef_grad();
204
+
205
+ private:
206
+ // TODO(albanD): replace this with a SmallVector
207
+ std::unordered_map<uint64_t, at::Tensor> content_;
208
+ mutable std::mutex mutex_;
209
+ };
210
+
211
+ } // namespace torch::autograd
212
+
213
+ #else
214
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
215
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function.h ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/autograd/anomaly_mode.h>
5
+ #include <torch/csrc/autograd/edge.h>
6
+ #include <torch/csrc/autograd/grad_mode.h>
7
+ #include <torch/csrc/autograd/graph_task.h>
8
+ #include <torch/csrc/autograd/input_metadata.h>
9
+ #include <torch/csrc/autograd/saved_variable.h>
10
+ #include <torch/csrc/autograd/variable.h>
11
+ #include <torch/csrc/utils/python_stub.h>
12
+ #include <torch/csrc/utils/variadic.h>
13
+
14
+ #include <ATen/SequenceNumber.h>
15
+ #include <ATen/core/Tensor.h>
16
+ #include <ATen/record_function.h>
17
+ #include <c10/util/Exception.h>
18
+ #include <c10/util/irange.h>
19
+
20
+ #include <algorithm>
21
+ #include <cstdint>
22
+ #include <initializer_list>
23
+ #include <memory>
24
+ #include <string>
25
+ #include <utility>
26
+ #include <vector>
27
+
28
+ namespace torch::autograd {
29
+
30
+ struct Edge;
31
+ struct FunctionPostHook;
32
+ struct FunctionPreHook;
33
+
34
+ using tensor_list = std::vector<at::Tensor>;
35
+ using variable_list = std::vector<Variable>;
36
+ using edge_list = std::vector<Edge>;
37
+ using saved_variable_list = std::vector<SavedVariable>;
38
+ using ivalue_list = std::vector<c10::IValue>;
39
+ using functional_apply_t = std::function<
40
+ variable_list(const variable_list&, const std::vector<c10::IValue>&)>;
41
+ using IndexRange = std::pair<size_t, size_t>;
42
+ using torch::dynamo::autograd::CompiledNodeArgs;
43
+ using torch::dynamo::autograd::PackedArgs;
44
+ using torch::dynamo::autograd::SwapSavedVariables;
45
+
46
+ // Custom deleter to prevent stack overflows.
47
+ TORCH_API void deleteNode(Node* function);
48
+
49
+ // Guard that sets and restores the evaluating node
50
+ class NodeGuard {
51
+ public:
52
+ explicit NodeGuard(std::shared_ptr<Node> node);
53
+ ~NodeGuard();
54
+
55
+ private:
56
+ std::shared_ptr<Node> last_evaluating_node_;
57
+ };
58
+
59
+ // Return the Node currently being evaluated (if any)
60
+ // This is only set during the backward pass while a Node is being
61
+ // executed.
62
+ TORCH_API std::shared_ptr<Node> get_current_node();
63
+
64
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65
+ // Node
66
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67
+ // A `Node` is an abstract class that represents an operation taking zero
68
+ // or more input `Variable`s and producing zero or more output `Variable`s. All
69
+ // functions in PyTorch's autograd machinery derive from this class and
70
+ // override its `apply` method. Instances of such subclasses will then be
71
+ // invocable via the call operator.
72
+ //
73
+ // Nodes in the Autograd Graph
74
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
75
+ // When viewing the autograd system as a graph, `Node`s are the vertices or
76
+ // nodes, connected to each other via (directed) `Edge`s, which themselves are
77
+ // represented via (`Node`, input_nr) pairs. `Variable`s are the outputs to
78
+ // and inputs of `Node`s, and travel between these edges during execution
79
+ // of the graph. When two or more `Edge`s (from different sources) point at the
80
+ // same input to a `Node`, the values produced along all of these edges are
81
+ // implicitly summed prior to being forwarded to the target `Node`.
82
+ //
83
+ // Hierarchy
84
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
85
+ // Subclasses usually represent differentiable functions as well as their
86
+ // gradient operators. Note, however, that due to the very general definition
87
+ // of a `Node` taking *zero* or more inputs and producing *zero* or more
88
+ // outputs, uses of `Node`s are flexible and extend beyond purely
89
+ // mathematical operations. For example, the `AccumulateGrad` function is a
90
+ // *sink*: it takes one input, but produces no outputs, instead accumulating
91
+ // the input as a side effect. At the other extreme, the `GraphRoot` function
92
+ // receives no inputs from other functions, but produces multiple outputs.
93
+ //
94
+ // Interface
95
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
96
+ // The most important method on `Node` is the call operator, which takes in
97
+ // a list of variables and produces a list of variables. The precise size of
98
+ // these lists can be determined with `num_inputs()` and `num_outputs()`.
99
+ // `Node`s are stitched together via their `next_edge` interface, which let
100
+ // you manipulate the set of outgoing edges of a `Node`. You can add an
101
+ // edge with `add_next_edge()`, retrieve an edge with `next_edge(index)` and
102
+ // iterate over them via the `next_edges()` method. Other methods exist for
103
+ // integration with the JIT and other parts of PyTorch. Every `Node` has a
104
+ // *sequence number* that increases monotonically in the order of `Node`
105
+ // construction. It can be retrieved via the `sequence_nr()` method. Note that
106
+ // this sequence number is *thread local*. This means that when `Node`s
107
+ // `A`, `B` and `C` are created consecutively in the same thread, their
108
+ // sequence numbers will be ordered `A` < `B` < `C`. If, however, `A` and `B`
109
+ // are created in one thread and `C` is created in a new thread, there are *no
110
+ // guarantees* w.r.t. the ordering of `C` relative to `A` or `B`.
111
+ // See NOTE [ Sequence Number] for more details on the usages of sequence
112
+ // number.
113
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
114
+ struct TORCH_API Node : std::enable_shared_from_this<Node> {
115
+ public:
116
+ /// Construct a new `Node` with the given `next_edges`
117
+ explicit Node(uint64_t sequence_nr, edge_list&& next_edges = edge_list())
118
+ : sequence_nr_(sequence_nr), next_edges_(std::move(next_edges)) {
119
+ for (const Edge& edge : next_edges_) {
120
+ update_topological_nr(edge);
121
+ }
122
+
123
+ if (AnomalyMode::is_enabled()) {
124
+ metadata()->store_stack();
125
+
126
+ // If anomaly mode is enabled and graph is constructed, then assign the
127
+ // currently evaluating node as the parent of this node.
128
+ // A parent is a Node where this Node is created.
129
+ // We are tracking the parents to track multiple backward operations.
130
+ assign_parent();
131
+ }
132
+
133
+ // Store the thread_id of the forward operator.
134
+ // See NOTE [ Sequence Numbers ]
135
+ thread_id_ = at::RecordFunction::currentThreadId();
136
+ }
137
+
138
+ explicit Node(edge_list&& next_edges = edge_list())
139
+ : Node(
140
+ /*sequence_nr=*/at::sequence_number::get_and_increment(),
141
+ std::move(next_edges)) {}
142
+
143
+ /// Nodes are neither copyable nor moveable.
144
+ Node(const Node& other) = delete;
145
+ Node(Node&& other) = delete;
146
+ Node& operator=(const Node& other) = delete;
147
+ Node& operator=(Node&& other) = delete;
148
+ virtual ~Node() = default;
149
+
150
+ std::shared_ptr<Node> getptr() {
151
+ return shared_from_this();
152
+ }
153
+ /// Evaluates the function on the given inputs and returns the result of the
154
+ /// function call.
155
+ variable_list operator()(variable_list&& inputs) {
156
+ // In the first iteration of named tensors, autograd ignores names and
157
+ // operates on unnamed tensors. In the long term, autograd should
158
+ // probably operate with names.
159
+ at::NoNamesGuard no_names_guard;
160
+
161
+ #ifdef USE_ROCM
162
+ // Keep track of backward pass for rocblas.
163
+ at::ROCmBackwardPassGuard in_backward;
164
+ #endif
165
+
166
+ auto step_callbacks =
167
+ at::getStepCallbacksUnlessEmpty(at::RecordScope::BACKWARD_FUNCTION);
168
+ if (C10_UNLIKELY(step_callbacks.has_value())) {
169
+ at::RecordFunction guard(std::move(*step_callbacks));
170
+ // Using sequence number and thread id to correlate with
171
+ // the forward pass function
172
+ guard.setForwardThreadId(thread_id_);
173
+ if (guard.needsInputs()) {
174
+ std::vector<c10::IValue> inputs_vec(inputs.begin(), inputs.end());
175
+ guard.before(
176
+ name(),
177
+ c10::ArrayRef<const c10::IValue>(
178
+ inputs_vec.data(), inputs_vec.size()),
179
+ static_cast<int64_t>(sequence_nr()));
180
+ } else {
181
+ guard.before(name(), static_cast<int64_t>(sequence_nr()));
182
+ }
183
+ return apply(std::move(inputs));
184
+ } else {
185
+ return apply(std::move(inputs));
186
+ }
187
+ }
188
+
189
+ // Graph Connectivity API
190
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191
+
192
+ // Inputs. NOTE: inputs of the grad_fn correspond to Tensor outputs of the
193
+ // forward function.
194
+
195
+ // Marker for expected undefined input
196
+ struct undefined_input {};
197
+
198
+ /// Adds the type and shape metadata for a new input. Returns the index of
199
+ /// of the new input.
200
+ uint32_t add_input_metadata(
201
+ const at::TensorOptions& options,
202
+ c10::SymIntArrayRef shape,
203
+ bool is_tensor_subclass,
204
+ bool is_nested,
205
+ std::optional<at::ScalarType> grad_dtype) noexcept {
206
+ uint32_t input_nr = input_metadata_.size();
207
+ auto meta_shape = MetadataShape{std::in_place_type<SymIntSmallVec>, shape};
208
+ input_metadata_.emplace_back(
209
+ options, meta_shape, is_tensor_subclass, is_nested, grad_dtype);
210
+ return input_nr;
211
+ }
212
+
213
+ uint32_t add_input_metadata(const at::Tensor& t) noexcept {
214
+ uint32_t input_nr = input_metadata_.size();
215
+ input_metadata_.emplace_back(t);
216
+ return input_nr;
217
+ }
218
+
219
+ /// Adds a placeholder for an input that will not be used.
220
+ uint32_t add_input_metadata(undefined_input u) noexcept {
221
+ uint32_t input_nr = input_metadata_.size();
222
+ input_metadata_.emplace_back();
223
+ return input_nr;
224
+ }
225
+
226
+ uint32_t num_inputs() const noexcept {
227
+ return input_metadata_.size();
228
+ }
229
+
230
+ const InputMetadata& input_metadata(size_t index) const {
231
+ return input_metadata_[index];
232
+ }
233
+
234
+ // Danger: not thread safe, caller must protect with lock
235
+ InputMetadata& mutable_input_metadata(size_t index) {
236
+ return input_metadata_[index];
237
+ }
238
+
239
+ /**
240
+ * Note: Function Streams
241
+ * A function's stream (for a given device type) is the stream of the first
242
+ * element of its input buffer on a device of that type.
243
+ *
244
+ * If all elements are on the same device they MUST share a stream. If
245
+ * elements are on different devices (across multiple GPUs, for example)
246
+ * they may have different streams.
247
+ */
248
+ std::optional<c10::Stream> stream() {
249
+ auto opt_device_type = at::getAccelerator();
250
+ if (!opt_device_type.has_value()) {
251
+ return std::nullopt;
252
+ }
253
+ for (const auto& metadata : input_metadata_) {
254
+ if (metadata.device().type() == opt_device_type.value())
255
+ return metadata.stream();
256
+ }
257
+
258
+ return std::nullopt;
259
+ }
260
+
261
+ // Used by the engine to determine what device thread to run on
262
+ at::Device device() {
263
+ // Since we pick the first non-CPU tensor, this won't work with
264
+ // mixed device-type operations (e.g., an op that is both CUDA
265
+ // and XLA). This is *incredibly* unlikely, so we don't worry
266
+ // about it.
267
+ for (const auto& metadata : input_metadata_) {
268
+ auto device = metadata.device();
269
+ if (device.type() != at::kCPU) {
270
+ return device;
271
+ }
272
+ }
273
+ // Only report to the CPU thread if there really were no tensors
274
+ // from other devices.
275
+ return at::kCPU;
276
+ }
277
+
278
+ void clear_input_metadata() {
279
+ input_metadata_.clear();
280
+ }
281
+
282
+ // Outputs ("Next Edges")
283
+
284
+ void update_topological_nr(const Edge& edge) {
285
+ TORCH_INTERNAL_ASSERT(
286
+ !has_parent_,
287
+ "Cannot update a node's topological_nr after it already has a parent."
288
+ " If we allow this, we can no longer guarantee that a parent's"
289
+ " topo_nr is always greater than those of all its children")
290
+ Node* node = edge.function.get();
291
+ if (node) {
292
+ auto topo_nr = node->topological_nr();
293
+ if (topological_nr_ <= topo_nr) {
294
+ topological_nr_ = topo_nr + 1;
295
+ }
296
+ }
297
+ }
298
+
299
+ void set_next_edge(size_t index, Edge edge) {
300
+ update_topological_nr(edge);
301
+ next_edges_[index] = std::move(edge);
302
+ }
303
+
304
+ void add_next_edge(Edge edge) {
305
+ update_topological_nr(edge);
306
+ next_edges_.emplace_back(std::move(edge));
307
+ }
308
+
309
+ void set_next_edges(edge_list&& next_edges) {
310
+ next_edges_ = std::move(next_edges);
311
+ for (const auto& next_edge : next_edges_) {
312
+ update_topological_nr(next_edge);
313
+ }
314
+ }
315
+
316
+ const Edge& next_edge(size_t index) const noexcept {
317
+ return next_edges_[index];
318
+ }
319
+
320
+ const edge_list& next_edges() const noexcept {
321
+ return next_edges_;
322
+ }
323
+
324
+ edge_list& next_edges() noexcept {
325
+ return next_edges_;
326
+ }
327
+
328
+ uint32_t num_outputs() const noexcept {
329
+ return next_edges_.size();
330
+ }
331
+
332
+ // Miscellaneous Methods
333
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
334
+
335
+ /// NOTE [ Sequence Number]
336
+ ///
337
+ /// The sequence_nr has two main usages in autograd:
338
+ ///
339
+ /// 1) Helps determine the node's execution priority in the engine.
340
+ /// All else being equal, nodes with higher priority numbers are executed
341
+ /// first. Thus, nodes corresponding to ops executed later are the first to
342
+ /// be executed in the backward pass. One caveat is that we prioritize
343
+ /// AccumulateGrad nodes by explicitly setting its sequence_nr to be
344
+ /// UINT64_MAX.
345
+ /// 2) The sequence number of this `Node` is paired with with thread_id it was
346
+ /// created in
347
+ /// as a unique identifier by the profiler to annotate recorded events.
348
+ /// The purpose of this is to help users (and possibly programs)
349
+ /// interpreting the profiler's output to correlate backward nodes with its
350
+ /// forward ops. We need both sequence_nr and thread_id to identify a node
351
+ /// because sequence_nr is thread_local, i.e., starts counting up from zero
352
+ /// in a new thread
353
+ uint64_t sequence_nr() const noexcept {
354
+ return sequence_nr_;
355
+ }
356
+
357
+ void set_sequence_nr(uint64_t sequence_nr) {
358
+ sequence_nr_ = sequence_nr;
359
+ }
360
+
361
+ // NOTE [ Topological Number ]
362
+ //
363
+ // topological_nr is used to prune branches in the DAG during autograd
364
+ // discovery as maintaining topological_nr helps us check in O(1) if there
365
+ // does NOT exist a directed path between two nodes.
366
+ //
367
+ // The topological order number of this `Node` representing the length of the
368
+ // longest possible path from this Node to any leaf node. If you are leaf
369
+ // node, aka AccumulateGrad, this will be zero. This value has the property
370
+ // that For every pair of nodes X, Y in G, existence of a directed path from X
371
+ // to Y implies topo_nr(X) > topo_nr(Y). The converse is not true, however, so
372
+ // we cannot prove existence of a path from X to Y, only non-existence.
373
+ //
374
+ // One assumption we make when using topo_nr is that once a node
375
+ // has been used, i.e., has a parent node, its own topo_nr does not change
376
+ // we have added some checks with the `has_parent_` field to enforce this.
377
+ //
378
+ // What NOT to do:
379
+ //
380
+ // 1) 2 -> 1 -> 0 In this diagram we label nodes with their
381
+ // topo_nr.
382
+ // 2 -> 1 -> 0 We have two simple graphs that can each
383
+ // arise from
384
+ // `t.exp().exp()`, for example.
385
+ // 2) 2 -> 1 -> 0
386
+ // /
387
+ // 2 -> 1 -> 0 We add 2 as a next edge to 1 even though 1
388
+ // already
389
+ // has a parent.
390
+ // 3) 2 -> 1 -> 0
391
+ // /
392
+ // 2 -> 3 -> 0 2 < 3, yet there exists a path from 2 to 3!
393
+ //
394
+ uint64_t topological_nr() const noexcept {
395
+ has_parent_ = true;
396
+ return topological_nr_;
397
+ }
398
+
399
+ // assigning a node as a parent to this node
400
+ void assign_parent();
401
+
402
+ /// Id of the thread that created Node
403
+ uint64_t thread_id() const noexcept {
404
+ return thread_id_;
405
+ }
406
+
407
+ /// Returns the name of the dynamic type of the function, for debugging.
408
+ virtual std::string name() const;
409
+
410
+ /// The difference between functions `should_compute_output` and
411
+ /// `task_should_compute_output`:
412
+ /// - `should_compute_output` should only be used during graph construction
413
+ /// and takes into account only requires_grad information
414
+ /// - `task_should_compute_output` should only be called during the backward
415
+ /// pass (unless called directly through grad_fn) and takes into account the
416
+ /// current graph task. Specifically, the autograd engine trims unnecessary
417
+ /// edges when `inputs` are specified, and during backward untrimmed nodes
418
+ /// left on the graph can/should check `task_should_compute_output` to see if
419
+ /// any outgoing edges have been trimmed by the engine. If that is the case,
420
+ /// gradient computation wrt those edges can be omitted.
421
+ ///
422
+ /// Returns true if the particular output edge is active, and that particular
423
+ /// output of this function should be computed.
424
+ bool should_compute_output(size_t output_edge_index) const {
425
+ TORCH_CHECK(output_edge_index < num_outputs(), "Index out of range");
426
+ return next_edges_[output_edge_index].is_valid();
427
+ }
428
+
429
+ /// Returns true if any of the output edges in any of the ranges are active.
430
+ bool should_compute_output(std::initializer_list<IndexRange> idxs) const {
431
+ return std::any_of(idxs.begin(), idxs.end(), [this](IndexRange range) {
432
+ for (const auto i : c10::irange(range.first, range.second)) {
433
+ if (should_compute_output(i))
434
+ return true;
435
+ }
436
+ return false;
437
+ });
438
+ }
439
+
440
+ /// Same as the above `should_compute_output` function but will also
441
+ /// check whether this edge is needed within the current graph task.
442
+ bool task_should_compute_output(size_t output_edge_index) const {
443
+ TORCH_CHECK(output_edge_index < num_outputs(), "Index out of range");
444
+ const auto& next = next_edges_[output_edge_index];
445
+ if (next.is_valid()) {
446
+ const auto exec_info = get_current_graph_task_exec_info();
447
+ if (exec_info && !exec_info->empty()) {
448
+ auto it = exec_info->find(next.function.get());
449
+ if (it == exec_info->end() || !it->second.should_execute()) {
450
+ return false; // this edge is not needed for the current graph_task
451
+ }
452
+ }
453
+ return true;
454
+ }
455
+ return false;
456
+ }
457
+
458
+ /// Returns true if any of the output edges in any of the ranges are active
459
+ /// and should be computed in the current graph task.
460
+ bool task_should_compute_output(
461
+ std::initializer_list<IndexRange> idxs) const {
462
+ return std::any_of(idxs.begin(), idxs.end(), [this](IndexRange range) {
463
+ for (const auto i : c10::irange(range.first, range.second)) {
464
+ if (task_should_compute_output(i))
465
+ return true;
466
+ }
467
+ return false;
468
+ });
469
+ }
470
+
471
+ /// Returns the `PyObject` stored for this `Node` (for Python
472
+ /// interaction).
473
+ PyObject* pyobj() const noexcept {
474
+ return pyobj_;
475
+ }
476
+
477
+ /// Sets the `PyObject` stored for this `Node` (for Python interaction).
478
+ void set_pyobj(PyObject* pyobj) noexcept {
479
+ pyobj_ = pyobj;
480
+ }
481
+
482
+ /// Returns the anomaly metadata stored for this `Node`.
483
+ /// If none exist, creates a new empty one.
484
+ AnomalyMetadata* metadata() noexcept;
485
+
486
+ // Hook API
487
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
488
+
489
+ uintptr_t add_post_hook(std::unique_ptr<FunctionPostHook>&& post_hook) {
490
+ post_hooks_.emplace_back(std::move(post_hook));
491
+ // Use the raw pointer as the unique key to identify this hook. This key
492
+ // can then be used in del_post_hook(key) to remove this hook.
493
+ return reinterpret_cast<std::uintptr_t>(post_hooks_.back().get());
494
+ }
495
+
496
+ const std::vector<std::unique_ptr<FunctionPostHook>>& post_hooks()
497
+ const noexcept {
498
+ return post_hooks_;
499
+ }
500
+
501
+ // delete a post hook matching the key
502
+ bool del_post_hook(const uintptr_t& key) {
503
+ for (auto it = post_hooks_.begin(); it != post_hooks_.end(); ++it) {
504
+ if (key == reinterpret_cast<std::uintptr_t>(it->get())) {
505
+ post_hooks_.erase(it);
506
+ return true;
507
+ }
508
+ }
509
+ return false;
510
+ }
511
+
512
+ std::vector<std::unique_ptr<FunctionPostHook>>& post_hooks() noexcept {
513
+ return post_hooks_;
514
+ }
515
+
516
+ void add_pre_hook(std::unique_ptr<FunctionPreHook>&& pre_hook) {
517
+ pre_hooks_.emplace_back(std::move(pre_hook));
518
+ }
519
+
520
+ void add_tensor_pre_hook(std::unique_ptr<FunctionPreHook>&& pre_hook) {
521
+ tensor_pre_hooks_.emplace_back(std::move(pre_hook));
522
+ }
523
+
524
+ void add_retains_grad_hook(
525
+ std::unique_ptr<FunctionPreHook>&& pre_hook,
526
+ size_t output_idx) {
527
+ retains_grad_hooks_[output_idx] = std::move(pre_hook);
528
+ }
529
+
530
+ std::unique_ptr<FunctionPreHook> pop_retains_grad_hook(size_t output_idx) {
531
+ auto ret = std::move(retains_grad_hooks_[output_idx]);
532
+ retains_grad_hooks_.erase(output_idx);
533
+ return ret;
534
+ }
535
+
536
+ const std::vector<std::unique_ptr<FunctionPreHook>>& pre_hooks()
537
+ const noexcept {
538
+ return pre_hooks_;
539
+ }
540
+
541
+ std::vector<std::unique_ptr<FunctionPreHook>>& pre_hooks() noexcept {
542
+ return pre_hooks_;
543
+ }
544
+
545
+ virtual std::vector<std::unique_ptr<FunctionPreHook>>&
546
+ tensor_pre_hooks() noexcept {
547
+ return tensor_pre_hooks_;
548
+ }
549
+
550
+ virtual std::unique_ptr<PostAccumulateGradHook>& tensor_post_acc_grad_hooks()
551
+ const noexcept {
552
+ static std::unique_ptr<PostAccumulateGradHook> empty = nullptr;
553
+ return empty;
554
+ }
555
+
556
+ std::unordered_map<size_t, std::unique_ptr<FunctionPreHook>>&
557
+ retains_grad_hooks() noexcept {
558
+ return retains_grad_hooks_;
559
+ }
560
+
561
+ // Customization Points for Subclasses
562
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
563
+
564
+ /// Releases saved variables if the operation won't be reused.
565
+ virtual void release_variables() {}
566
+
567
+ /// Called before an apply if `release_variables()` is going to be called.
568
+ /// Allows larger ops like `InterpreterAutogradFunction` to incrementally
569
+ /// release variables as they run.
570
+ virtual void will_release_variables() {}
571
+
572
+ /// Returns true if this function is traceable. An op is traceable if all
573
+ /// operations happening within `apply()` are performed on autograd
574
+ /// `Variables` (i.e. apply mostly instantiates and applies other functions).
575
+ virtual bool is_traceable() {
576
+ return false;
577
+ }
578
+
579
+ /// A `Node` is said to pass state transparently to backward, if the
580
+ /// state consists only of (Saved)Variables and only non-variable objects
581
+ /// that parameterize the operation in some way that defines the graph
582
+ /// structure AND the backward function is traceable. In particular,
583
+ /// parametrization MUST NOT depend on the data of any `Variable`.
584
+ /// TODO: it might be possible to handle cases where backward is
585
+ /// non-traceable but state passing could be considered transparent. This
586
+ /// will probably depend on saved_variable_list being mutable.
587
+ /// NOTE: this value matters only if is_traceable() returns false.
588
+ virtual bool passes_state_transparently() {
589
+ return false;
590
+ }
591
+
592
+ // see [Note: Compiled Autograd]
593
+ // Used by compiled autograd to
594
+ // 1) Extract tensors/symint args
595
+ // 2) Collect node information for specialization and caching
596
+ // Implementations in subclasses should call args.collect() with all node
597
+ // attrs. These functions are only called during backward.
598
+ virtual void compiled_args(CompiledNodeArgs& args) const {
599
+ TORCH_CHECK_NOT_IMPLEMENTED(
600
+ false, std::string("compiled_args not implemented: ") + name());
601
+ }
602
+
603
+ // Used by compiled autograd to call apply() with different saved tensors
604
+ // Implementations should call saved.before() on all attrs, then apply(), then
605
+ // saved.after() on all attrs in the same order.
606
+ virtual variable_list apply_with_saved(
607
+ const variable_list& inputs,
608
+ SwapSavedVariables& saved) {
609
+ TORCH_CHECK_NOT_IMPLEMENTED(
610
+ false, std::string("apply_with_saved not implemented: ") + name());
611
+ }
612
+
613
+ // If this node is the AOTBackward node produced by torch.compile.
614
+ // Compiled Autograd special-cases on this information.
615
+ virtual bool is_aot_backward() const {
616
+ return false;
617
+ }
618
+
619
+ protected:
620
+ /// Performs the `Node`'s actual operation.
621
+ virtual variable_list apply(variable_list&& inputs) = 0;
622
+
623
+ /// Calls `apply()`, but instruments it with tracing machinery.
624
+ variable_list traced_apply(variable_list inputs);
625
+
626
+ // Sequence number used to correlate backward nodes with forward ops in the
627
+ // profiler and provide determinism in the engine.
628
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
629
+ uint64_t sequence_nr_;
630
+
631
+ // See NOTE [ Topological Number ]
632
+ uint64_t topological_nr_ = 0;
633
+
634
+ // Tracks whether this node has been added as the next_edge of another node
635
+ // via set_next_edge(s), which always calls topological_nr() of all its
636
+ // children See NOTE [ Topological Number ] for why we need this.
637
+ mutable bool has_parent_ = false;
638
+
639
+ // Id of the thread that created the instance
640
+ uint64_t thread_id_ = 0;
641
+
642
+ // Note [Thread Safety on Autograd Node]
643
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
644
+ // Autograd Engine let the owning thread which calls Engine::execute to drive
645
+ // the GraphTask execution, there might be cases that part of the GraphTask is
646
+ // shared across different `backward()` or `grad()` calls, i.e. fork new
647
+ // threads in the middle of the forward and call `backward()` separately from
648
+ // different threads. We need to protect the thread safety on NodeTask to
649
+ // prevent data racing on shared variables read/write.
650
+ //
651
+ // NB: This is only needed for Autograd Nodes that runs on CPU, technically
652
+ // "CUDA", "XLA" nodes don't need locking because device threads are always
653
+ // single threaded.
654
+ //
655
+ // Here we add a thread mutex to help protect the Node's thread safety, so
656
+ // that different threads cannot race the shared data when executing the same
657
+ // NodeTask from multiple CPU threads. It IS the user/developer responsibility
658
+ // to take advantage of this mutex to protect the thread safety of their
659
+ // autograd Node. The general strategy of thread safety on autograd Node:
660
+ //
661
+ // 1. User should lock the mutex during Node::release_variables() if the Node
662
+ // needs
663
+ // to release the variables on the fly, this serve the purpose that when we
664
+ // release saved_variables from one thread, no other threads can release
665
+ // the saved variables concurrently. call the Node::apply(),
666
+ // 2. User should lock the mutex during Node::apply(), this is to ensure Node
667
+ // that
668
+ // writing to the shared variable are not racing across threads (i.e.
669
+ // AccumulateGrad and custom C++ Autograd Node if writing to shared
670
+ // variables )
671
+ // 3. item 2 and item 3 should work together so that when we release saved
672
+ // variables
673
+ // from one thread, no other threads can call Node::apply(), this ensures
674
+ // the variable references from other threads aren't dangling.
675
+ // 4. if the Node don't release any variables and no shared data read/write in
676
+ // the Node
677
+ // i.e. purely functional, user don't need to lock the mutex
678
+ //
679
+ // This way we could protect the thread safety on Autograd Node, but we could
680
+ // still not protect the thread safety on Node pre/post C++ hooks (python
681
+ // hooks are automatically thread safe), we rely on the user to write thread
682
+ // safe C++ hooks if they want the hook to be correctly applied in
683
+ // multithreading environment.
684
+ std::mutex mutex_;
685
+
686
+ edge_list next_edges_;
687
+ PyObject* pyobj_ = nullptr; // weak reference
688
+ std::unique_ptr<AnomalyMetadata> anomaly_metadata_ = nullptr;
689
+
690
+ // NOTE [Hooks ordering]
691
+ // We have 3 separate fields for pre hooks registered to the autograd nodes
692
+ // because the conditions under which they execute are different, and we
693
+ // want more fine-grained control over the order in which different types
694
+ // of hooks are executed.
695
+ // - pre_hooks are only executed when the node itself is executed
696
+ // - tensor_pre_hook is executed as long as the engine traverses over it
697
+ // even if that node won't be executed.
698
+ // - retains_grad_hook are like tensor_pre_hooks except they are always
699
+ // ordered after all other tensor pre hooks
700
+ std::vector<std::unique_ptr<FunctionPreHook>> pre_hooks_;
701
+ std::vector<std::unique_ptr<FunctionPreHook>> tensor_pre_hooks_;
702
+ std::unordered_map<size_t, std::unique_ptr<FunctionPreHook>>
703
+ retains_grad_hooks_;
704
+ std::vector<std::unique_ptr<FunctionPostHook>> post_hooks_;
705
+ at::SmallVector<InputMetadata, 2> input_metadata_;
706
+ };
707
+
708
+ /// See Node::is_traceable() for definition.
709
+ struct TraceableFunction : public Node {
710
+ using Node::Node;
711
+ bool is_traceable() final {
712
+ return true;
713
+ }
714
+ };
715
+
716
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
717
+ // Associated Free Nodes
718
+ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
719
+
720
+ namespace detail {
721
+ // Implementation of `collect_next_edges` (see below).
722
+ struct MakeNextFunctionList : IterArgs<MakeNextFunctionList> {
723
+ edge_list next_edges;
724
+ using IterArgs<MakeNextFunctionList>::operator();
725
+ void operator()(const Variable& variable) {
726
+ if (variable.defined()) {
727
+ next_edges.emplace_back(impl::gradient_edge(variable));
728
+ } else {
729
+ next_edges.emplace_back();
730
+ }
731
+ }
732
+ void operator()(const Variable* variable) {
733
+ operator()(*variable);
734
+ }
735
+ void operator()(const std::optional<Variable>& variable) {
736
+ if (variable.has_value()) {
737
+ operator()(*variable);
738
+ } else {
739
+ next_edges.emplace_back();
740
+ }
741
+ }
742
+ };
743
+ } // namespace detail
744
+
745
+ /// Create an `Edge` between the given `variable` and the `function`, which is
746
+ /// assumed to be the gradient function of this variable (i.e. the function
747
+ /// through which this variable is backpropagated during the backward pass).
748
+ /// This sets the `grad_fn` property of the `variable`. This function assumes
749
+ /// that the `Variable` is a new input to the gradient function and its
750
+ /// `input_nr` thus equal to `function->num_inputs()`. Additionally, it
751
+ /// increments the `Node`'s number of inputs by one. Approximately
752
+ /// equivalent to `variable.set_gradient_edge(function,
753
+ /// function->add_input_metadata(variable.dispatch_type(), variable.sizes()))`.
754
+ /// If you don't want the `Node`'s `num_inputs` to be incremented, use
755
+ /// `set_gradient_edge` directly.
756
+ inline void create_gradient_edge(
757
+ Variable& variable,
758
+ std::shared_ptr<Node> function) {
759
+ // Copy before move.
760
+ const auto input_nr = function->add_input_metadata(variable);
761
+ impl::set_gradient_edge(variable, {std::move(function), input_nr});
762
+ }
763
+
764
+ /// Return true if any of the variables in the list require a gradient.
765
+ inline bool any_variable_requires_grad(const variable_list& variables) {
766
+ return std::any_of(
767
+ variables.begin(), variables.end(), [](const Variable& variable) {
768
+ return variable.defined() && variable.requires_grad();
769
+ });
770
+ }
771
+
772
+ /// Return the next edges of all the given variables, or tuples of variables.
773
+ template <typename... Variables>
774
+ edge_list collect_next_edges(Variables&&... variables) {
775
+ detail::MakeNextFunctionList make;
776
+ make.apply(std::forward<Variables>(variables)...);
777
+ return std::move(make.next_edges);
778
+ }
779
+
780
+ struct TypeAndSize {
781
+ TypeAndSize() = default;
782
+ /* implicit */
783
+ TypeAndSize(const at::Tensor& t)
784
+ : sym_sizes(t.sym_sizes().vec()), options(t.options()) {}
785
+
786
+ at::Tensor zeros();
787
+
788
+ std::vector<c10::SymInt> sym_sizes;
789
+ at::TensorOptions options;
790
+ };
791
+
792
+ } // namespace torch::autograd
793
+
794
+ #else
795
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
796
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/function_hook.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <torch/csrc/Export.h>
6
+ #include <string>
7
+ #include <vector>
8
+
9
+ namespace torch::dynamo::autograd {
10
+ class CompiledNodeArgs;
11
+ class SwapSavedVariables;
12
+ struct PackedArgs;
13
+ } // namespace torch::dynamo::autograd
14
+
15
+ // A hook that's called on gradients
16
+
17
+ namespace torch::autograd {
18
+
19
+ using Variable = at::Tensor;
20
+ using variable_list = std::vector<Variable>;
21
+
22
+ struct TORCH_API FunctionPreHook {
23
+ virtual ~FunctionPreHook() = default;
24
+ virtual variable_list operator()(const variable_list& grads) = 0;
25
+ // only implemented for python hooks, registers hook with compiled autograd
26
+ virtual void compiled_args(
27
+ torch::dynamo::autograd::CompiledNodeArgs& args) const {
28
+ TORCH_CHECK_NOT_IMPLEMENTED(
29
+ false,
30
+ std::string("compiled_args nyi, see [Note: Compiled Autograd] ") +
31
+ typeid(*this).name());
32
+ }
33
+ };
34
+
35
+ struct TORCH_API FunctionPostHook {
36
+ virtual ~FunctionPostHook() = default;
37
+ virtual variable_list operator()(
38
+ const variable_list& outputs /* grad_inputs */,
39
+ const variable_list& inputs /* grad_outputs */) = 0;
40
+ // only implemented for python hooks, registers hook with compiled autograd
41
+ virtual void compiled_args(
42
+ torch::dynamo::autograd::CompiledNodeArgs& args) const {
43
+ TORCH_CHECK_NOT_IMPLEMENTED(
44
+ false,
45
+ std::string("compiled_args nyi, see [Note: Compiled Autograd] ") +
46
+ typeid(*this).name());
47
+ }
48
+ };
49
+
50
+ struct TORCH_API PostAccumulateGradHook {
51
+ virtual ~PostAccumulateGradHook() = default;
52
+ virtual void operator()(const Variable& tensor) = 0;
53
+ // only implemented for python hooks on nodes, registers hook with compiled
54
+ // autograd
55
+ virtual void compiled_args(
56
+ torch::dynamo::autograd::CompiledNodeArgs& args) const {
57
+ TORCH_CHECK_NOT_IMPLEMENTED(
58
+ false,
59
+ std::string("compiled_args nyi, see [Note: Compiled Autograd] ") +
60
+ typeid(*this).name());
61
+ }
62
+
63
+ virtual void apply_with_saved(
64
+ Variable& /*unused*/,
65
+ torch::dynamo::autograd::SwapSavedVariables& /*unused*/) {
66
+ TORCH_CHECK_NOT_IMPLEMENTED(
67
+ false,
68
+ std::string("compiled_args nyi, see [Note: Compiled Autograd] ") +
69
+ typeid(*this).name());
70
+ }
71
+ };
72
+
73
+ } // namespace torch::autograd
74
+
75
+ #else
76
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
77
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/accumulate_grad.h ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/CachedTensorUtils.h>
5
+ #include <ATen/LegacyBatchedTensorImpl.h>
6
+ #include <ATen/TensorOperators.h>
7
+ #include <torch/csrc/Export.h>
8
+ #include <torch/csrc/autograd/function.h>
9
+ #include <torch/csrc/autograd/utils/grad_layout_contract.h>
10
+ #include <torch/csrc/autograd/variable.h>
11
+
12
+ #ifndef AT_PER_OPERATOR_HEADERS
13
+ #include <ATen/Functions.h>
14
+ #else
15
+ #include <ATen/ops/_sparse_coo_tensor_unsafe.h>
16
+ #endif
17
+
18
+ #include <mutex>
19
+
20
+ namespace torch::autograd {
21
+
22
+ #define CHECK_RESULT(RESULT, VAR) \
23
+ if (!(RESULT.is_sparse() || VAR.is_sparse() || RESULT.is_sparse_csr() || \
24
+ VAR.is_sparse_csr())) { \
25
+ if (!utils::obeys_layout_contract(RESULT, VAR)) { \
26
+ TORCH_WARN_ONCE( \
27
+ "grad and param do not obey the gradient layout contract. " \
28
+ "This is not an error, but may impair performance.\n" \
29
+ "grad.sizes() = ", \
30
+ RESULT.sizes(), \
31
+ ", strides() = ", \
32
+ RESULT.strides(), \
33
+ "\n", \
34
+ "param.sizes() = ", \
35
+ VAR.sizes(), \
36
+ ", strides() = ", \
37
+ VAR.strides()); \
38
+ } \
39
+ }
40
+
41
+ struct TORCH_API AccumulateGrad : public Node {
42
+ explicit AccumulateGrad(Variable variable_);
43
+
44
+ variable_list apply(variable_list&& grads) override;
45
+
46
+ std::vector<std::unique_ptr<FunctionPreHook>>& tensor_pre_hooks() noexcept
47
+ override {
48
+ // NB: Since the AccumulateGrad Node is only a weak ref from the Tensor,
49
+ // it can be destroyed even though the Tensor is still alive (contrary
50
+ // to all other Nodes). So we must lazily read the Tensor hooks here.
51
+ return impl::hooks(variable);
52
+ }
53
+
54
+ std::unique_ptr<PostAccumulateGradHook>& tensor_post_acc_grad_hooks()
55
+ const noexcept override {
56
+ // NB: Since the AccumulateGrad Node is only a weak ref from the Tensor,
57
+ // it can be destroyed even though the Tensor is still alive (contrary
58
+ // to all other Nodes). So we must lazily read the Tensor hooks here.
59
+ return impl::post_acc_grad_hooks(variable);
60
+ }
61
+
62
+ // Note: Gradient Layout Contract
63
+ //
64
+ // AccumulateGrad tries to stash strided (non-sparse) grads with memory layout
65
+ // (strides) such that variables and grads interact efficiently in later
66
+ // optimizer kernels, and grads interact efficiently with c10d::Reducer.cpp.
67
+ //
68
+ // Specifically, AccumulateGrad tries to ensure the following
69
+ // (cf torch/csrc/autograd/utils/grad_layout_contract.h):
70
+ // (1) if variable.is_non_overlapping_and_dense(), the stashed grad's
71
+ // strides match variable.
72
+ // (2) else, stashed grad is rowmajor contiguous.
73
+ // If variable's grad does not exist (!variable_grad.defined())
74
+ // AccumulateGrad steals new_grad if it's stealable and obeys the contract
75
+ // already, otherwise it deep copies new_grad into an obedient clone.
76
+ //
77
+ // If variable's grad already exists (variable_grad.defined()), new_grad must
78
+ // be added to variable_grad. If we aren't setting up for double backward
79
+ // (!GradMode::is_enabled()), AccumulateGrad performs "variable_grad +=
80
+ // new_grad" in-place, which keeps variable_grad's layout. We assume (hope)
81
+ // variable_grad was created obeying (1) or (2) at some point in the past.
82
+ //
83
+ // If we are setting up for double backward, AccumulateGrad updates the grad
84
+ // out-of-place via "variable_grad + new_grad." TensorIterator operator+
85
+ // decides result's layout. Typically TensorIterator matches strides of the
86
+ // first arg, so we once again assume (hope) variable_grad was originally
87
+ // created obeying (1) or (2).
88
+ //
89
+ // AccumulateGrad does not enforce the contract with 100% certainty. Examples:
90
+ // - If a user manually permutes a param or its grad, then runs a fwd+bwd,
91
+ // variable_grad += new_grad keeps variable_grad's layout without
92
+ // rechecking the contract.
93
+ // - If TensorIterator changes its corner cases about operator+'s result
94
+ // (for example, giving more or less priority to channels_last inputs, see
95
+ // https://github.com/pytorch/pytorch/pull/37968) the result may not obey.
96
+ //
97
+ // Fortunately, if a given grad doesn't satisfy (1) or (2), the penalty is
98
+ // degraded performance in Reducer.cpp or optimizer kernels, not death by
99
+ // assert or silently bad numerics.
100
+
101
+ // Gradient Accumulation
102
+ // Given a variable with its current grad as variable_grad, accumulates
103
+ // new_grad into variable_grad if in place accumulation is possible.
104
+ // Otherwise, uses 'update_grad' to update the grad for the variable.
105
+ //
106
+ // Branch breakdown:
107
+ // - Case 1: Param has no existing grad
108
+ // - Case 1.1: Stealable dense new_grad
109
+ // . We aren't setting up for double-backward.
110
+ // . No other user-visible tensor references new_grad.
111
+ // . new_grad obeys the "Gradient Layout Contract", there has a special
112
+ // case, For MKLDNN tensor, which is a opaque tensor, assuming it obeys
113
+ // layout_contract.
114
+ // - Case 1.2: Stealable sparse new_grad
115
+ // . Can't detach sparse tensor (since metadata changes are not allowed
116
+ // after detach), so just create a new one for the grad which is a
117
+ // shallow copy. We need a shallow copy so that modifying the original
118
+ // grad tensor doesn't modify the grad we accumulate.
119
+ // . We only skip clone if indices and values themselves are contiguous
120
+ // for backward compatibility reasons. Since without this optimization,
121
+ // earlier we would clone the entire SparseTensor which cloned indices
122
+ // and values. For details see
123
+ // https://github.com/pytorch/pytorch/issues/34375.
124
+ // - Case 1.3: Cloning sparse/nested new_grad
125
+ // - Case 1.4: Cloning MKLDNN new_grad
126
+ // - Case 1.5: Deep copies new_grad according to the Gradient Layout
127
+ // Contract.
128
+ // - Case 2: Param has existing grad and grad mode is not enabled
129
+ // - This case is not strictly necessary, but it makes the first-order only
130
+ // case slightly more efficient.
131
+ // - Case 2.1: Sparse variable_grad + Dense new_grad
132
+ // . If `variable_grad` is sparse and `new_grad` is not sparse, their
133
+ // sum is not sparse, and we must change the TensorImpl type of
134
+ // `variable_grad` for it to store the result. However, changing the
135
+ // TensorImpl type of a tensor requires changing the tensor itself, and
136
+ // thus in this case we have to change the grad tensor.
137
+ // - Case 2.2: Vmap-incompatible
138
+ // . Ideally we'd perform an in-place operation to avoid changing
139
+ // the grad tensor. However, if that's impossible because the grads
140
+ // are vmap-incompatible (See NOTE: [vmap-incompatible in-place
141
+ // operations]), then we just add them out-of-place.
142
+ // - Case 2.3: In-place addition
143
+ // . In this case we can avoid changing the grad tensor. There are three
144
+ // scenarios when we'll hit this case:
145
+ // . `variable_grad` is sparse, and `new_grad` is sparse.
146
+ // . `variable_grad` is dense, and `new_grad` is sparse.
147
+ // . `variable_grad` is dense, and `new_grad` is dense.
148
+ // . `variable_grad` is mkldnn, and `new_grad` is mkldnn.
149
+ //
150
+ // In all of these four cases, `variable_grad += new_grad` is a
151
+ // valid operation which adds `new_grad` to `variable_grad` in
152
+ // place. `variable_grad` is thus still referring to the same tensor
153
+ // after the operation.
154
+ // . DistributedDataParallel(DDP) package relies on grad being
155
+ // mutated in place for saving peak memory usage. DDP will still
156
+ // work correctly if it is mutated out of place here, but DDP will
157
+ // maintain one extra copy of grad tensors in buffer and thus
158
+ // increase peak memory usage.
159
+ // - Case 3: Param has existing grad and grad mode is enabled
160
+ // - Case 3.1: Sparse variable_grad + Dense new_grad
161
+ // - Case 3.2: Not Sparse variable_grad + Dense new_grad
162
+ //
163
+ // variable: the variable whose grad we're accumulating.
164
+ // variable_grad: the current grad for the variable.
165
+ // new_grad: new grad we want to accumulate for the variable.
166
+ // num_expected_refs: the number of refs we expect to hold internally
167
+ // such that it is safe to avoid cloning the grad
168
+ // if use_count() of the grad is less than or equal
169
+ // to this value (in addition to post_hooks).
170
+ // update_grad: Function that is used to update grad for the variable.
171
+ // The argument to the function is a Tensor which
172
+ // is used to set a new value for the grad.
173
+ template <typename T>
174
+ static void accumulateGrad(
175
+ const Variable& variable,
176
+ at::Tensor& variable_grad,
177
+ const at::Tensor& new_grad,
178
+ size_t num_expected_refs,
179
+ const T& update_grad) {
180
+ if (!variable_grad.defined()) {
181
+ if (!GradMode::is_enabled() && !new_grad.is_sparse() &&
182
+ !new_grad.is_sparse_csr() &&
183
+ !(variable.is_sparse_csr() && new_grad.layout() == at::kStrided) &&
184
+ impl::is_tensor_stealable(
185
+ new_grad,
186
+ num_expected_refs + at::caching::is_cached_tensor(new_grad)) &&
187
+ (new_grad.is_mkldnn() ||
188
+ utils::obeys_layout_contract(new_grad, variable))) {
189
+ // See Case 1.1: Stealable dense new_grad
190
+ update_grad(new_grad.detach());
191
+ } else if (
192
+ !GradMode::is_enabled() && new_grad.is_sparse() &&
193
+ new_grad._indices().is_contiguous() &&
194
+ new_grad._values().is_contiguous() &&
195
+ // Use count for indices and values should always be <=1 since the
196
+ // SparseTensor should be the only one holding a reference to these.
197
+ new_grad._indices().use_count() <= 1 &&
198
+ new_grad._values().use_count() <= 1 &&
199
+ impl::is_tensor_stealable(new_grad, num_expected_refs)) {
200
+ // Case 1.2: Stealable sparse new_grad
201
+ // No scenario where we expect this to be true currently
202
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
203
+ !at::caching::is_cached_tensor(new_grad._indices()) &&
204
+ !at::caching::is_cached_tensor(new_grad._values()) &&
205
+ !at::caching::is_cached_tensor(new_grad));
206
+
207
+ update_grad(at::_sparse_coo_tensor_unsafe(
208
+ new_grad._indices(),
209
+ new_grad._values(),
210
+ new_grad.sizes(),
211
+ new_grad.options()));
212
+ } else {
213
+ if (new_grad.is_sparse() || new_grad.is_sparse_csr() ||
214
+ new_grad.is_nested()) {
215
+ // Case 1.3: Cloning sparse/nested new_grad
216
+ update_grad(new_grad.clone());
217
+ } else {
218
+ if (new_grad.is_mkldnn()) {
219
+ // Case 1.4: Cloning MKLDNN new_grad
220
+ update_grad(new_grad.clone());
221
+ } else {
222
+ // Case 1.5: Deep copies new_grad according to the "Gradient
223
+ // Layout Contract."
224
+ update_grad(utils::clone_obey_contract(new_grad, variable));
225
+ }
226
+ }
227
+ }
228
+ } else if (!GradMode::is_enabled()) {
229
+ // Case 2: Param has existing grad and grad mode is not enabled
230
+ if (variable_grad.is_sparse() && !new_grad.is_sparse()) {
231
+ // Case 2.1: Sparse variable_grad + Dense new_grad
232
+ auto result = new_grad + variable_grad;
233
+ CHECK_RESULT(result, variable);
234
+ update_grad(std::move(result));
235
+ } else if (!at::inplaceIsVmapCompatible(variable_grad, new_grad)) {
236
+ // Case 2.2: Vmap-incompatible
237
+ auto result = variable_grad + new_grad;
238
+ CHECK_RESULT(result, variable);
239
+ update_grad(std::move(result));
240
+ } else {
241
+ // Case 2.3: In-place addition
242
+ variable_grad += new_grad;
243
+ CHECK_RESULT(variable_grad, variable);
244
+ // ^ We could enforce the contract more aggressively here by writing:
245
+ // if (variable_grad.is_sparse() || new_grad.is_sparse()) {
246
+ // variable_grad += new_grad;
247
+ // } else if (obeys_layout_contract(variable_grad, variable)) {
248
+ // variable_grad += new_grad;
249
+ // } else {
250
+ // result = at::empty_strided(variable.sizes(), variable.strides(),
251
+ // variable.options().memory_format(std::nullopt));
252
+ // update_grad(at::native::add_out(result, variable_grad,
253
+ // new_grad, 1.0);
254
+ // }
255
+ // However, that accumulation is sometimes in place and sometimes not,
256
+ // which may break user code.
257
+ }
258
+ } else {
259
+ // Case 3: Param has existing grad and grad mode is enabled
260
+ at::Tensor result;
261
+ if (variable_grad.is_sparse() && !new_grad.is_sparse()) {
262
+ // Case 3.1: Sparse variable_grad + Dense new_grad
263
+ // CPU backend throws an error on sparse + dense, so
264
+ // prefer dense + sparse here.
265
+ result = new_grad + variable_grad;
266
+ } else {
267
+ // Case 3.2: Not Sparse variable_grad + Dense new_grad
268
+ // Assumes operator+ result typically matches strides of first arg,
269
+ // and hopes variable_grad was originally created obeying layout
270
+ // contract.
271
+ result = variable_grad + new_grad;
272
+ }
273
+ CHECK_RESULT(result, variable);
274
+ update_grad(std::move(result));
275
+ // ^ We could enforce the contract more aggressively here by saying
276
+ // if (obeys_layout_contract(new_grad, variable)) {
277
+ // update_grad(new_grad + variable_grad);
278
+ // } else {
279
+ // update_grad(variable_grad + new_grad);
280
+ // }
281
+ // such that the stashed grad is likely to have the right strides if
282
+ // either variable_grad or new_grad already has the right strides.
283
+ // We could enforce the contract with certainty by saying
284
+ // auto result = variable_grad + new_grad (or vice versa), checking
285
+ // result's layout, and copying to an obedient clone if necessary before
286
+ // update_grad. The copy would require another gmem pass. We can't create
287
+ // empty result with the right layout then add_out into it with a single
288
+ // kernel, because GradMode is enabled in this branch, and add_out isn't
289
+ // differentiable. Maybe more trouble than it's worth.
290
+ }
291
+ }
292
+
293
+ void compiled_args(CompiledNodeArgs& args) const override;
294
+ variable_list apply_with_saved(
295
+ const variable_list& inputs,
296
+ SwapSavedVariables& saved) override;
297
+
298
+ Variable variable;
299
+ };
300
+
301
+ #undef CHECK_RESULT
302
+
303
+ } // namespace torch::autograd
304
+
305
+ #else
306
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
307
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/basic_ops.h ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/util/irange.h>
5
+ #include <torch/csrc/Export.h>
6
+ #include <torch/csrc/autograd/function.h>
7
+ #include <torch/csrc/autograd/variable.h>
8
+
9
+ #include <memory>
10
+ #include <string>
11
+ #include <vector>
12
+
13
+ namespace torch::autograd {
14
+
15
+ struct TORCH_API Error : public Node {
16
+ Error(std::string msg, edge_list&& next_edges)
17
+ : Node(std::move(next_edges)), msg(std::move(msg)) {}
18
+
19
+ Error(std::string msg) : msg(std::move(msg)) {}
20
+
21
+ variable_list apply(variable_list&& inputs) override;
22
+ variable_list apply(variable_list&& inputs) const;
23
+
24
+ void compiled_args(CompiledNodeArgs& args) const override;
25
+ variable_list apply_with_saved(
26
+ const variable_list& inputs,
27
+ SwapSavedVariables& saved) override;
28
+
29
+ std::string msg;
30
+ };
31
+
32
+ // We print grad_fn names in tensor printing. For functions with backward
33
+ // NYI, grad_fn=<Error> will be printed if we use Error, which is confusing. So
34
+ // special case with a new NotImplemented function here.
35
+ struct TORCH_API NotImplemented : public Error {
36
+ NotImplemented(const std::string& forward_fn, edge_list&& next_edges)
37
+ : Error(
38
+ "derivative for " + forward_fn + " is not implemented",
39
+ std::move(next_edges)) {}
40
+
41
+ NotImplemented(const std::string& forward_fn)
42
+ : Error("derivative for " + forward_fn + " is not implemented") {}
43
+ };
44
+
45
+ // Identity in forward, Error in backward. Used to implement
46
+ // @once_differentiable
47
+ struct TORCH_API DelayedError : public Node {
48
+ DelayedError(std::string msg, int64_t num_inputs) : msg(std::move(msg)) {
49
+ for ([[maybe_unused]] const auto _ [[maybe_unused]] :
50
+ c10::irange(num_inputs)) {
51
+ add_input_metadata(Node::undefined_input());
52
+ }
53
+ }
54
+
55
+ variable_list apply(variable_list&& inputs) override;
56
+ variable_list apply(variable_list&& inputs) const;
57
+
58
+ std::string msg;
59
+ };
60
+
61
+ struct TORCH_API UndefinedGrad : public Node {
62
+ UndefinedGrad() {
63
+ add_input_metadata(Node::undefined_input());
64
+ }
65
+
66
+ variable_list apply(variable_list&& inputs) override;
67
+ variable_list apply(variable_list&& inputs) const;
68
+ };
69
+
70
+ struct TORCH_API UndefinedGradBackward : public Node {
71
+ UndefinedGradBackward(edge_list&& next_edges) : Node(std::move(next_edges)) {}
72
+
73
+ UndefinedGradBackward() = default;
74
+
75
+ variable_list apply(variable_list&& inputs) override;
76
+ variable_list apply(variable_list&& inputs) const;
77
+
78
+ void compiled_args(CompiledNodeArgs& args) const override {}
79
+ variable_list apply_with_saved(
80
+ const variable_list& inputs,
81
+ SwapSavedVariables& saved) override {
82
+ return apply(variable_list(inputs));
83
+ }
84
+ };
85
+
86
+ struct TORCH_API GraphRoot : public Node {
87
+ GraphRoot(edge_list functions, variable_list inputs)
88
+ : Node(std::move(functions)), outputs(std::move(inputs)) {
89
+ // Ensures calls to stream() on a GraphRoot instance reflect current
90
+ // stream(s) on devices of root grad tensors at the time the instance is
91
+ // constructed.
92
+ for (const auto& t : outputs) {
93
+ add_input_metadata(t);
94
+ }
95
+ }
96
+
97
+ variable_list apply(variable_list&& inputs) override {
98
+ return outputs;
99
+ }
100
+
101
+ void compiled_args(CompiledNodeArgs& args) const override;
102
+ variable_list apply_with_saved(
103
+ const variable_list& inputs,
104
+ SwapSavedVariables& saved) override;
105
+
106
+ variable_list outputs;
107
+ };
108
+
109
+ struct TORCH_API Identity : public Node {
110
+ variable_list apply(variable_list&& inputs) override;
111
+ };
112
+
113
+ } // namespace torch::autograd
114
+
115
+ #else
116
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
117
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/comm.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/autograd/function.h>
6
+ #include <torch/csrc/autograd/variable.h>
7
+
8
+ #include <ATen/ATen.h>
9
+ #include <c10/cuda/CUDAStream.h>
10
+ #include <optional>
11
+
12
+ #include <cstddef>
13
+ #include <vector>
14
+
15
+ namespace torch::autograd {
16
+
17
+ struct TORCH_CUDA_CU_API Scatter : public Node {
18
+ explicit Scatter(
19
+ std::vector<at::Device> devices,
20
+ std::optional<std::vector<int64_t>> chunk_sizes = std::nullopt,
21
+ int64_t dim = 0,
22
+ std::optional<std::vector<std::optional<at::cuda::CUDAStream>>> streams =
23
+ std::nullopt,
24
+ bool unsqueeze_scalars = false);
25
+ ~Scatter() override;
26
+
27
+ variable_list apply(variable_list&& inputs) override;
28
+
29
+ std::vector<at::Device> devices_;
30
+ std::optional<std::vector<int64_t>> chunk_sizes_;
31
+ int64_t dim_;
32
+ std::optional<std::vector<std::optional<at::cuda::CUDAStream>>> streams_;
33
+ bool unsqueeze_scalars_;
34
+ };
35
+
36
+ struct TORCH_CUDA_CU_API Gather : public Node {
37
+ explicit Gather(const at::Device& destination_device, int64_t dim = 0);
38
+ ~Gather() override;
39
+
40
+ variable_list apply(variable_list&& inputs) override;
41
+
42
+ at::Device destination_device_;
43
+ int64_t dim_;
44
+ };
45
+
46
+ } // namespace torch::autograd
47
+
48
+ #else
49
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
50
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/pybind.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <pybind11/pybind11.h>
5
+ #include <pybind11/stl.h>
6
+ #include <torch/csrc/python_headers.h>
7
+ #include <torch/csrc/utils/pybind.h>
8
+
9
+ #include <torch/csrc/autograd/python_cpp_function.h>
10
+ #include <torch/csrc/autograd/python_function.h>
11
+
12
+ // NOLINTNEXTLINE(misc-unused-alias-decls)
13
+ namespace py = pybind11;
14
+
15
+ namespace pybind11::detail {} // namespace pybind11::detail
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/tensor.h ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/autograd/function.h>
6
+ #include <torch/csrc/autograd/variable.h>
7
+
8
+ #include <ATen/TensorGeometry.h>
9
+ #include <ATen/core/DeprecatedTypeProperties.h>
10
+ #include <optional>
11
+
12
+ #include <cstdint>
13
+ #include <memory>
14
+
15
+ namespace torch::autograd {
16
+
17
+ struct TORCH_API CopyBackwards : public Node {
18
+ variable_list apply(variable_list&& grads) override;
19
+ void compiled_args(CompiledNodeArgs& args) const override;
20
+ variable_list apply_with_saved(
21
+ const variable_list& inputs,
22
+ SwapSavedVariables& saved) override;
23
+
24
+ at::TensorOptions src_options;
25
+ };
26
+
27
+ // Note [View + Inplace update for base tensor]
28
+ //
29
+ // This note covers a few important topics related to view + inplace handling.
30
+ // - It explains what is the CopySlices Node and why we need it.
31
+ // - It explains the considerations on what is saved for backward in
32
+ // CopySlices.
33
+ // - It explains why we need to sometimes change the exec_info of the current
34
+ // backward
35
+ //
36
+ // What is CopySlices?
37
+ // ~~~~~~~~~~~~~~~~~~~
38
+ //
39
+ // We support autograd with inplace mutation; e.g., if you write x.mul_(2)
40
+ // the autograd will work as if you now had multiple Tensors under the hood and
41
+ // you did
42
+ // x = t.clone()
43
+ // x0 = x
44
+ // x1 = x0 * 2
45
+ // x = x1
46
+ // As you can see here, after this operation, x.grad_fn now points to x1.grad_fn
47
+ // (the MulBackward node) and this node points to x's original grad_fn (which is
48
+ // also x0.grad_fn). It is important to keep in mind that after the inplace,
49
+ // there is no Tensor object that represents the x0 state anymore. But the graph
50
+ // for it is still around in autograd (in case x was used before being modified
51
+ // inplace). See Example 1 in
52
+ // https://docs.google.com/drawings/d/1-T5DyYfChMX1ONQkY-zU-hj_ayQ2zmA5CBOKDWqvEhE
53
+ // We call this rebasing the history of the Tensor.
54
+ //
55
+ // Now, a difficult situation is what happens if x is a differentiable view
56
+ // of a base b.
57
+ // b = t.clone()
58
+ // x = b.select(0, 0)
59
+ // x *= 2
60
+ // With the same approach as above, this will become
61
+ // b = t.clone()
62
+ // x = b.select(0, 0)
63
+ // b0 = b
64
+ // x0 = x
65
+ // x1 = x0 * 2
66
+ // b1 = b0.select_scatter(x1, 0, 0)
67
+ // x2 = b1.select(0, 0)
68
+ // x = x2
69
+ // b = b1
70
+ // As you can see here, not only we need to modify x's grad_fn, we also need to
71
+ // modify the one from b. We also need to ensure that the new grad_fn on x is
72
+ // linked to b's new grad_fn. The chain the select_scatter, multiplication and
73
+ // select is what CopySlices does, all wrapped into a single Node.
74
+ //
75
+ // See Example 1 in
76
+ // https://docs.google.com/drawings/d/1-T5DyYfChMX1ONQkY-zU-hj_ayQ2zmA5CBOKDWqvEhE
77
+ //
78
+ // What do we need to save in CopySlices to run backward?
79
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
80
+ //
81
+ // We need to perform grad_view = fn(grad_view), but out-of-place.
82
+ // view_fn_ is an optional function saved in DifferentiableViewMeta
83
+ // from forward pass, so that we can recover we when as_strided is not
84
+ // supported. It preserves the invariants:
85
+ // view = view_fn_(base)
86
+ // grad_view = view_fn_(grad_base)
87
+ //
88
+ // When as_strided is supported (e.g. strided CPU/CUDA Tensors), view_fn_
89
+ // is empty and we save TensorGeometry(view) instead.
90
+ // With the TensorGeometry information we can use `as_strided` call which
91
+ // is more efficient to recover views in backward.
92
+ //
93
+ // For example:
94
+ // view_1 = view_op_1(base)
95
+ // view_2 = view_op_2(view_1)
96
+ // ...
97
+ // view_n = view_op_n(view_n-1)
98
+ // view_n = inplace_op(view_n)
99
+ //
100
+ // In CPU/CUDA case where we support efficient as_strided implementation,
101
+ // grad_view_n can be calculated through 1 step.
102
+ //
103
+ // grad_view_n = grad_base.as_strided(view_sizes, view_strides, view_offset);
104
+ //
105
+ // But in XLA backend where we don't have full support of as_strided,
106
+ // it has to save a chained lambda function view_fn_, to exactly
107
+ // replay how the view was done in forward.
108
+ //
109
+ // view_fn_ = view_op_n(...(view_op_2(view_op_1())))
110
+ // grad_view_n = view_fn_(grad_base)
111
+ //
112
+ // This chain view_fn_ works as long as forward view ops are implemented,
113
+ // e.g XLA simulates view without a real Storage behind Tensor, but it's less
114
+ // efficient than the as_strided one so we should be careful to only use it when
115
+ // necessary.
116
+ //
117
+ // - For CPU/CUDA we save TensorGeometry of both base and view tensors,
118
+ // That's all we need to pass into as_strided.
119
+ // E.g. int[] sizes, int[] strides, and int storage_offset.
120
+ // - For XLA we use view_fn_, which captures all forward view op arguments
121
+ // by **value**.
122
+ // E.g for at::narrow, int dim, int start, in length are saved.
123
+ //
124
+ // Theoretically we could also save Tensor `view` in CopySlices Node, but
125
+ // it's far more expensive than what we currently save.
126
+ // 1. We cannot afford keeping large tensors alive to recover views only.
127
+ // 2. There are inplace checks when Tensors are loaded back to make sure
128
+ // they haven't been changed (including size metadata).
129
+ // So saving metadata like TensorGeometry/view arguments is much better
130
+ // because it is minimal information needed to recover views, as well as it
131
+ // allows the user to modify the original Tensor without preventing the
132
+ // backward pass from running.
133
+ //
134
+ // Why do we manually change exec_info in the apply?
135
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136
+ //
137
+ // Using the same example as before,
138
+ // b = t.clone()
139
+ // x = b.select(0, 0)
140
+ // x *= y
141
+ //
142
+ // You can see the visualization at
143
+ // https://docs.google.com/drawings/d/1Bx-Hcz-zlIv7PabQqnPhUIVIs9F8WWi48svqMsAUMFs
144
+ // which contains the wrapped MulBackward Node and show what it links to.
145
+ // Since a backward can happen between any subset of the inputs (t and y) and
146
+ // outputs (o, x, b). It is possible to get into a state where CopySlices's 0th
147
+ // next function (CloneBackward) needs gradient but MulBackward's 0th next
148
+ // function (SelectBackward) is not. This happens if you do autograd.grad
149
+ // between x and t for example.
150
+ // In such a case, we do need to mark SelectBackward as requiring gradient such
151
+ // that, during the execution of MulBackward, we will actually compute gradient
152
+ // for the 0th input.
153
+ //
154
+ // All the other next functions are always shared (this is asserted in the apply
155
+ // code) and so nothing needs to be done for them.
156
+
157
+ // See Note [View + Inplace update for view tensor] for what we do to view
158
+ // tensor when an in-place operation happens.
159
+ struct TORCH_API CopySlices : public Node {
160
+ CopySlices(
161
+ const Variable& base_var,
162
+ at::TensorGeometry view_,
163
+ std::unique_ptr<ViewFunc> view_fn_,
164
+ std::shared_ptr<Node> fn_);
165
+
166
+ // common code between apply/apply_with_saved
167
+ template <typename T>
168
+ variable_list apply_impl(variable_list&& inputs, const T& call_fn);
169
+
170
+ variable_list apply(variable_list&& inputs) override;
171
+ void release_variables() override;
172
+ void compiled_args(CompiledNodeArgs& args) const override;
173
+ variable_list apply_with_saved(
174
+ const variable_list& inputs,
175
+ SwapSavedVariables& saved) override;
176
+ void update_exec_info();
177
+
178
+ at::TensorGeometry base;
179
+ // view and view_fn are redundant and view_fn will be used if available.
180
+ // See Note [View + Inplace update for base tensor] for details.
181
+ at::TensorGeometry view;
182
+ std::unique_ptr<ViewFunc> view_fn;
183
+ std::shared_ptr<Node> fn;
184
+ };
185
+
186
+ } // namespace torch::autograd
187
+
188
+ #else
189
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
190
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/functions/utils.h ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/autograd/InferenceMode.h>
6
+ #include <torch/csrc/autograd/autograd.h>
7
+ #include <torch/csrc/autograd/function.h>
8
+ #include <torch/csrc/autograd/variable.h>
9
+ #include <torch/csrc/utils/variadic.h>
10
+
11
+ #include <ATen/core/Tensor.h>
12
+
13
+ #include <functional>
14
+ #include <memory>
15
+ #include <vector>
16
+
17
+ namespace torch::autograd {
18
+
19
+ using function_constructor = std::function<std::shared_ptr<Node>(edge_list&&)>;
20
+
21
+ /**
22
+ * Wraps the tensor outputs in variables and creates the grad_fn and sets the
23
+ * grad_fn if necessary.
24
+ */
25
+ TORCH_API variable_list wrap_outputs(
26
+ const variable_list& inputs,
27
+ tensor_list&& outputs,
28
+ const function_constructor& ctr);
29
+
30
+ /// Checks that inputs contains exactly `args` items and that the first
31
+ /// `required_args`
32
+ /// items are not nullptr. If not specified, `required_args` defaults to `args`.
33
+ TORCH_API void check_input_variables(
34
+ const char* name,
35
+ const variable_list& inputs,
36
+ int args,
37
+ int required_args = -1,
38
+ bool allow_undefined = false);
39
+
40
+ struct ComputeRequiresGrad : IterArgs<ComputeRequiresGrad> {
41
+ bool out = false;
42
+ using IterArgs<ComputeRequiresGrad>::operator();
43
+ void operator()(const at::Tensor& tensor) {
44
+ const auto& var = static_cast<const Variable&>(tensor);
45
+ if (var.defined() && var.requires_grad()) {
46
+ out = true;
47
+ }
48
+ }
49
+ void operator()(const std::optional<at::Tensor>& tensor) {
50
+ if (tensor.has_value()) {
51
+ (*this)(*tensor);
52
+ }
53
+ }
54
+ bool short_circuit() {
55
+ return out;
56
+ }
57
+ };
58
+
59
+ template <typename... Args>
60
+ inline bool compute_requires_grad(Args&&... args) {
61
+ if (!GradMode::is_enabled()) {
62
+ return false;
63
+ }
64
+ return ComputeRequiresGrad().apply(std::forward<Args>(args)...).out;
65
+ }
66
+
67
+ inline void set_history(
68
+ const at::Tensor& variable,
69
+ const std::shared_ptr<Node>& grad_fn) {
70
+ TORCH_CHECK(grad_fn != nullptr);
71
+ if (variable.defined()) {
72
+ // If the codegen triggers this, you most likely want to add your newly
73
+ // added function to the DONT_REQUIRE_DERIVATIVE list in
74
+ // tools/autograd/gen_variable_type.py
75
+ TORCH_CHECK(
76
+ isDifferentiableType(variable.scalar_type()),
77
+ "Autograd not support dtype: ",
78
+ variable.scalar_type());
79
+ auto output_nr = grad_fn->add_input_metadata(variable);
80
+ impl::set_gradient_edge(variable, {grad_fn, output_nr});
81
+ } else {
82
+ grad_fn->add_input_metadata(Node::undefined_input());
83
+ }
84
+ }
85
+
86
+ inline void set_history(
87
+ const std::vector<Variable>& variables,
88
+ const std::shared_ptr<Node>& grad_fn) {
89
+ for (auto& variable : variables) {
90
+ set_history(variable, grad_fn);
91
+ }
92
+ }
93
+
94
+ inline bool isFwGradDefined(const std::optional<at::Tensor>& t) {
95
+ return t.has_value() && t->defined() && t->_fw_grad(/*level */ 0).defined();
96
+ }
97
+
98
+ inline bool isFwGradDefinedTensorList(const at::ITensorListRef& variables) {
99
+ bool ret = false;
100
+ for (auto& variable : variables) {
101
+ ret |= isFwGradDefined(variable);
102
+ }
103
+ return ret;
104
+ }
105
+
106
+ inline bool isFwGradDefinedTensorList(
107
+ const c10::List<std::optional<at::Tensor>>& li) {
108
+ bool ret = false;
109
+ for (auto i : c10::irange(li.size())) {
110
+ auto t = li.get(i);
111
+ ret |= isFwGradDefined(t);
112
+ }
113
+ return ret;
114
+ }
115
+
116
+ } // namespace torch::autograd
117
+
118
+ #else
119
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
120
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/Functions.h ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/VariableType.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // @generated from ../tools/autograd/templates/VariableType.h
5
+
6
+ #include <ATen/core/Tensor.h>
7
+ #include <ATen/Context.h>
8
+
9
+ #include <c10/util/intrusive_ptr.h>
10
+
11
+ #include <torch/csrc/Export.h>
12
+ #include <torch/csrc/autograd/autograd_not_implemented_fallback.h>
13
+
14
+ #include <cstdint> // for size_t
15
+ #include <functional> // for function
16
+ #include <memory> // for unique_ptr
17
+ #include <string>
18
+ #include <vector>
19
+
20
+ namespace at {
21
+ struct Quantizer;
22
+ }
23
+
24
+ namespace torch { namespace autograd {
25
+
26
+ using Variable = at::Tensor;
27
+ using at::Context;
28
+ using at::Device;
29
+ using at::Dimname;
30
+ using at::DimnameList;
31
+ using at::Generator;
32
+ using at::IntArrayRef;
33
+ using at::MemoryFormat;
34
+ using at::QScheme;
35
+ using at::Scalar;
36
+ using at::ScalarType;
37
+ using at::Storage;
38
+ using at::Tensor;
39
+ using at::TensorList;
40
+ using at::TensorOptions;
41
+ using at::Quantizer;
42
+ using std::optional;
43
+
44
+ namespace VariableType {
45
+ TORCH_API std::vector<at::DeprecatedTypeProperties*> allCUDATypes();
46
+ TORCH_API std::vector<at::DeprecatedTypeProperties*> allXPUTypes();
47
+ TORCH_API std::vector<at::DeprecatedTypeProperties*> allCPUTypes();
48
+ TORCH_API std::vector<at::DeprecatedTypeProperties*> allPrivateUser1Types();
49
+
50
+ at::Tensor & unpack(Tensor & t, const char * name, int pos);
51
+ const at::Tensor & unpack(const Tensor & t, const char * name, int pos);
52
+ at::Tensor unpack_opt(const Tensor & t, const char * name, int pos);
53
+ std::vector<at::Tensor> unpack(const at::ITensorListRef& tl, const char *name, int pos);
54
+ }
55
+
56
+ }} // namespace torch::autograd
57
+
58
+ #else
59
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
60
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/ViewFuncs.h ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // @generated from ../tools/autograd/templates/ViewFuncs.h
5
+
6
+ #include <torch/library.h>
7
+ #include <torch/csrc/autograd/variable.h>
8
+ #include <c10/core/SymIntArrayRef.h>
9
+
10
+ #ifndef AT_PER_OPERATOR_HEADERS
11
+ #include <ATen/Operators.h>
12
+ #else
13
+ #include <ATen/ops/_conj_ops.h>
14
+ #include <ATen/ops/_indices_ops.h>
15
+ #include <ATen/ops/_neg_view_ops.h>
16
+ #include <ATen/ops/_nested_get_values_ops.h>
17
+ #include <ATen/ops/_nested_view_from_buffer_ops.h>
18
+ #include <ATen/ops/_nested_view_from_jagged_ops.h>
19
+ #include <ATen/ops/_reshape_alias_ops.h>
20
+ #include <ATen/ops/_test_autograd_multiple_dispatch_view_ops.h>
21
+ #include <ATen/ops/_values_ops.h>
22
+ #include <ATen/ops/alias_ops.h>
23
+ #include <ATen/ops/as_strided_ops.h>
24
+ #include <ATen/ops/ccol_indices_ops.h>
25
+ #include <ATen/ops/chunk_ops.h>
26
+ #include <ATen/ops/col_indices_ops.h>
27
+ #include <ATen/ops/crow_indices_ops.h>
28
+ #include <ATen/ops/diagonal_ops.h>
29
+ #include <ATen/ops/expand_ops.h>
30
+ #include <ATen/ops/indices_ops.h>
31
+ #include <ATen/ops/narrow_ops.h>
32
+ #include <ATen/ops/permute_ops.h>
33
+ #include <ATen/ops/row_indices_ops.h>
34
+ #include <ATen/ops/select_ops.h>
35
+ #include <ATen/ops/slice_ops.h>
36
+ #include <ATen/ops/slice_inverse_ops.h>
37
+ #include <ATen/ops/split_ops.h>
38
+ #include <ATen/ops/split_with_sizes_ops.h>
39
+ #include <ATen/ops/squeeze_ops.h>
40
+ #include <ATen/ops/squeeze_ops.h>
41
+ #include <ATen/ops/squeeze_ops.h>
42
+ #include <ATen/ops/t_ops.h>
43
+ #include <ATen/ops/transpose_ops.h>
44
+ #include <ATen/ops/unbind_ops.h>
45
+ #include <ATen/ops/unfold_ops.h>
46
+ #include <ATen/ops/unsqueeze_ops.h>
47
+ #include <ATen/ops/values_ops.h>
48
+ #include <ATen/ops/view_ops.h>
49
+ #include <ATen/ops/view_ops.h>
50
+ #include <ATen/ops/view_as_complex_ops.h>
51
+ #include <ATen/ops/view_as_real_ops.h>
52
+ #endif
53
+
54
+ namespace torch::autograd::generated {
55
+
56
+ using at::Scalar;
57
+ using at::Tensor;
58
+ using at::IntArrayRef;
59
+ using at::ArrayRef;
60
+ using at::Type;
61
+ using at::ScalarType;
62
+ using std::optional;
63
+ using c10::fmap;
64
+
65
+ #define _CONJ_VIEW_FUNC_AVAILABLE
66
+ struct _ConjViewFunc : public torch::autograd::ViewFunc {
67
+ _ConjViewFunc()
68
+ {}
69
+ virtual ~_ConjViewFunc() override = default;
70
+ virtual std::vector<c10::SymInt> get_symints() const override;
71
+ virtual size_t num_symints() const override;
72
+ virtual std::vector<at::Tensor> get_tensors() const override;
73
+ virtual size_t num_tensors() const override;
74
+ virtual at::Tensor operator()(const at::Tensor&) const override;
75
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
76
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
77
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
78
+
79
+ protected:
80
+ virtual void set_symints(std::vector<c10::SymInt>) override;
81
+ virtual void set_tensors(std::vector<at::Tensor>) override;
82
+
83
+ private:
84
+
85
+ };
86
+
87
+ #define _INDICES_VIEW_FUNC_AVAILABLE
88
+ struct _IndicesViewFunc : public torch::autograd::ViewFunc {
89
+ _IndicesViewFunc()
90
+ {}
91
+ virtual ~_IndicesViewFunc() override = default;
92
+ virtual std::vector<c10::SymInt> get_symints() const override;
93
+ virtual size_t num_symints() const override;
94
+ virtual std::vector<at::Tensor> get_tensors() const override;
95
+ virtual size_t num_tensors() const override;
96
+ virtual at::Tensor operator()(const at::Tensor&) const override;
97
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
98
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
99
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
100
+
101
+ protected:
102
+ virtual void set_symints(std::vector<c10::SymInt>) override;
103
+ virtual void set_tensors(std::vector<at::Tensor>) override;
104
+
105
+ private:
106
+
107
+ };
108
+
109
+ #define _NEG_VIEW_VIEW_FUNC_AVAILABLE
110
+ struct _NegViewViewFunc : public torch::autograd::ViewFunc {
111
+ _NegViewViewFunc()
112
+ {}
113
+ virtual ~_NegViewViewFunc() override = default;
114
+ virtual std::vector<c10::SymInt> get_symints() const override;
115
+ virtual size_t num_symints() const override;
116
+ virtual std::vector<at::Tensor> get_tensors() const override;
117
+ virtual size_t num_tensors() const override;
118
+ virtual at::Tensor operator()(const at::Tensor&) const override;
119
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
120
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
121
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
122
+
123
+ protected:
124
+ virtual void set_symints(std::vector<c10::SymInt>) override;
125
+ virtual void set_tensors(std::vector<at::Tensor>) override;
126
+
127
+ private:
128
+
129
+ };
130
+
131
+ #define _NESTED_GET_VALUES_VIEW_FUNC_AVAILABLE
132
+ struct _NestedGetValuesViewFunc : public torch::autograd::ViewFunc {
133
+ _NestedGetValuesViewFunc()
134
+ {}
135
+ virtual ~_NestedGetValuesViewFunc() override = default;
136
+ virtual std::vector<c10::SymInt> get_symints() const override;
137
+ virtual size_t num_symints() const override;
138
+ virtual std::vector<at::Tensor> get_tensors() const override;
139
+ virtual size_t num_tensors() const override;
140
+ virtual at::Tensor operator()(const at::Tensor&) const override;
141
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
142
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
143
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
144
+
145
+ protected:
146
+ virtual void set_symints(std::vector<c10::SymInt>) override;
147
+ virtual void set_tensors(std::vector<at::Tensor>) override;
148
+
149
+ private:
150
+
151
+ };
152
+
153
+ #define _NESTED_VIEW_FROM_BUFFER_VIEW_FUNC_AVAILABLE
154
+ struct _NestedViewFromBufferViewFunc : public torch::autograd::ViewFunc {
155
+ _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)
156
+ {}
157
+ virtual ~_NestedViewFromBufferViewFunc() override = default;
158
+ virtual std::vector<c10::SymInt> get_symints() const override;
159
+ virtual size_t num_symints() const override;
160
+ virtual std::vector<at::Tensor> get_tensors() const override;
161
+ virtual size_t num_tensors() const override;
162
+ virtual at::Tensor operator()(const at::Tensor&) const override;
163
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
164
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
165
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
166
+
167
+ protected:
168
+ virtual void set_symints(std::vector<c10::SymInt>) override;
169
+ virtual void set_tensors(std::vector<at::Tensor>) override;
170
+
171
+ private:
172
+ at::Tensor nested_size;
173
+ at::Tensor nested_strides;
174
+ at::Tensor offsets;
175
+ };
176
+
177
+ #define _NESTED_VIEW_FROM_JAGGED_VIEW_FUNC_AVAILABLE
178
+ struct _NestedViewFromJaggedViewFunc : public torch::autograd::ViewFunc {
179
+ _NestedViewFromJaggedViewFunc(const at::Tensor & offsets, const at::Tensor & dummy, const ::std::optional<at::Tensor> & lengths, int64_t ragged_idx, const ::std::optional<at::Tensor> & min_seqlen, const ::std::optional<at::Tensor> & max_seqlen) : offsets(offsets), dummy(dummy), lengths(lengths), ragged_idx(ragged_idx), min_seqlen(min_seqlen), max_seqlen(max_seqlen)
180
+ {}
181
+ virtual ~_NestedViewFromJaggedViewFunc() override = default;
182
+ virtual std::vector<c10::SymInt> get_symints() const override;
183
+ virtual size_t num_symints() const override;
184
+ virtual std::vector<at::Tensor> get_tensors() const override;
185
+ virtual size_t num_tensors() const override;
186
+ virtual at::Tensor operator()(const at::Tensor&) const override;
187
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
188
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
189
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
190
+
191
+ protected:
192
+ virtual void set_symints(std::vector<c10::SymInt>) override;
193
+ virtual void set_tensors(std::vector<at::Tensor>) override;
194
+
195
+ private:
196
+ at::Tensor offsets;
197
+ at::Tensor dummy;
198
+ ::std::optional<at::Tensor> lengths;
199
+ int64_t ragged_idx;
200
+ ::std::optional<at::Tensor> min_seqlen;
201
+ ::std::optional<at::Tensor> max_seqlen;
202
+ };
203
+
204
+ #define _RESHAPE_ALIAS_VIEW_FUNC_AVAILABLE
205
+ struct _ReshapeAliasViewFunc : public torch::autograd::ViewFunc {
206
+ _ReshapeAliasViewFunc(c10::SymIntArrayRef size, c10::SymIntArrayRef stride) : size(size.vec()), stride(stride.vec())
207
+ {}
208
+ virtual ~_ReshapeAliasViewFunc() override = default;
209
+ virtual std::vector<c10::SymInt> get_symints() const override;
210
+ virtual size_t num_symints() const override;
211
+ virtual std::vector<at::Tensor> get_tensors() const override;
212
+ virtual size_t num_tensors() const override;
213
+ virtual at::Tensor operator()(const at::Tensor&) const override;
214
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
215
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
216
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
217
+
218
+ protected:
219
+ virtual void set_symints(std::vector<c10::SymInt>) override;
220
+ virtual void set_tensors(std::vector<at::Tensor>) override;
221
+
222
+ private:
223
+ ::std::vector<c10::SymInt> size;
224
+ ::std::vector<c10::SymInt> stride;
225
+ };
226
+
227
+ #define _TEST_AUTOGRAD_MULTIPLE_DISPATCH_VIEW_VIEW_FUNC_AVAILABLE
228
+ struct _TestAutogradMultipleDispatchViewViewFunc : public torch::autograd::ViewFunc {
229
+ _TestAutogradMultipleDispatchViewViewFunc()
230
+ {}
231
+ virtual ~_TestAutogradMultipleDispatchViewViewFunc() override = default;
232
+ virtual std::vector<c10::SymInt> get_symints() const override;
233
+ virtual size_t num_symints() const override;
234
+ virtual std::vector<at::Tensor> get_tensors() const override;
235
+ virtual size_t num_tensors() const override;
236
+ virtual at::Tensor operator()(const at::Tensor&) const override;
237
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
238
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
239
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
240
+
241
+ protected:
242
+ virtual void set_symints(std::vector<c10::SymInt>) override;
243
+ virtual void set_tensors(std::vector<at::Tensor>) override;
244
+
245
+ private:
246
+
247
+ };
248
+
249
+ #define _VALUES_VIEW_FUNC_AVAILABLE
250
+ struct _ValuesViewFunc : public torch::autograd::ViewFunc {
251
+ _ValuesViewFunc()
252
+ {}
253
+ virtual ~_ValuesViewFunc() override = default;
254
+ virtual std::vector<c10::SymInt> get_symints() const override;
255
+ virtual size_t num_symints() const override;
256
+ virtual std::vector<at::Tensor> get_tensors() const override;
257
+ virtual size_t num_tensors() const override;
258
+ virtual at::Tensor operator()(const at::Tensor&) const override;
259
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
260
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
261
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
262
+
263
+ protected:
264
+ virtual void set_symints(std::vector<c10::SymInt>) override;
265
+ virtual void set_tensors(std::vector<at::Tensor>) override;
266
+
267
+ private:
268
+
269
+ };
270
+
271
+ #define ALIAS_VIEW_FUNC_AVAILABLE
272
+ struct AliasViewFunc : public torch::autograd::ViewFunc {
273
+ AliasViewFunc()
274
+ {}
275
+ virtual ~AliasViewFunc() override = default;
276
+ virtual std::vector<c10::SymInt> get_symints() const override;
277
+ virtual size_t num_symints() const override;
278
+ virtual std::vector<at::Tensor> get_tensors() const override;
279
+ virtual size_t num_tensors() const override;
280
+ virtual at::Tensor operator()(const at::Tensor&) const override;
281
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
282
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
283
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
284
+
285
+ protected:
286
+ virtual void set_symints(std::vector<c10::SymInt>) override;
287
+ virtual void set_tensors(std::vector<at::Tensor>) override;
288
+
289
+ private:
290
+
291
+ };
292
+
293
+ #define AS_STRIDED_VIEW_FUNC_AVAILABLE
294
+ struct AsStridedViewFunc : public torch::autograd::ViewFunc {
295
+ AsStridedViewFunc(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset) : size(size.vec()), stride(stride.vec()), storage_offset(storage_offset)
296
+ {}
297
+ virtual ~AsStridedViewFunc() override = default;
298
+ virtual std::vector<c10::SymInt> get_symints() const override;
299
+ virtual size_t num_symints() const override;
300
+ virtual std::vector<at::Tensor> get_tensors() const override;
301
+ virtual size_t num_tensors() const override;
302
+ virtual at::Tensor operator()(const at::Tensor&) const override;
303
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
304
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
305
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
306
+
307
+ protected:
308
+ virtual void set_symints(std::vector<c10::SymInt>) override;
309
+ virtual void set_tensors(std::vector<at::Tensor>) override;
310
+
311
+ private:
312
+ ::std::vector<c10::SymInt> size;
313
+ ::std::vector<c10::SymInt> stride;
314
+ ::std::optional<c10::SymInt> storage_offset;
315
+ };
316
+
317
+ #define CCOL_INDICES_VIEW_FUNC_AVAILABLE
318
+ struct CcolIndicesViewFunc : public torch::autograd::ViewFunc {
319
+ CcolIndicesViewFunc()
320
+ {}
321
+ virtual ~CcolIndicesViewFunc() override = default;
322
+ virtual std::vector<c10::SymInt> get_symints() const override;
323
+ virtual size_t num_symints() const override;
324
+ virtual std::vector<at::Tensor> get_tensors() const override;
325
+ virtual size_t num_tensors() const override;
326
+ virtual at::Tensor operator()(const at::Tensor&) const override;
327
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
328
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
329
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
330
+
331
+ protected:
332
+ virtual void set_symints(std::vector<c10::SymInt>) override;
333
+ virtual void set_tensors(std::vector<at::Tensor>) override;
334
+
335
+ private:
336
+
337
+ };
338
+
339
+ #define CHUNK_VIEW_FUNC_AVAILABLE
340
+ struct ChunkViewFunc : public torch::autograd::ViewFunc {
341
+ ChunkViewFunc(int64_t chunks, int64_t dim, int64_t view_idx) : chunks(chunks), dim(dim), view_idx(view_idx)
342
+ {}
343
+ virtual ~ChunkViewFunc() override = default;
344
+ virtual std::vector<c10::SymInt> get_symints() const override;
345
+ virtual size_t num_symints() const override;
346
+ virtual std::vector<at::Tensor> get_tensors() const override;
347
+ virtual size_t num_tensors() const override;
348
+ virtual at::Tensor operator()(const at::Tensor&) const override;
349
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
350
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
351
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
352
+
353
+ protected:
354
+ virtual void set_symints(std::vector<c10::SymInt>) override;
355
+ virtual void set_tensors(std::vector<at::Tensor>) override;
356
+
357
+ private:
358
+ int64_t chunks;
359
+ int64_t dim;
360
+ int64_t view_idx;
361
+ };
362
+
363
+ #define COL_INDICES_VIEW_FUNC_AVAILABLE
364
+ struct ColIndicesViewFunc : public torch::autograd::ViewFunc {
365
+ ColIndicesViewFunc()
366
+ {}
367
+ virtual ~ColIndicesViewFunc() override = default;
368
+ virtual std::vector<c10::SymInt> get_symints() const override;
369
+ virtual size_t num_symints() const override;
370
+ virtual std::vector<at::Tensor> get_tensors() const override;
371
+ virtual size_t num_tensors() const override;
372
+ virtual at::Tensor operator()(const at::Tensor&) const override;
373
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
374
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
375
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
376
+
377
+ protected:
378
+ virtual void set_symints(std::vector<c10::SymInt>) override;
379
+ virtual void set_tensors(std::vector<at::Tensor>) override;
380
+
381
+ private:
382
+
383
+ };
384
+
385
+ #define CROW_INDICES_VIEW_FUNC_AVAILABLE
386
+ struct CrowIndicesViewFunc : public torch::autograd::ViewFunc {
387
+ CrowIndicesViewFunc()
388
+ {}
389
+ virtual ~CrowIndicesViewFunc() override = default;
390
+ virtual std::vector<c10::SymInt> get_symints() const override;
391
+ virtual size_t num_symints() const override;
392
+ virtual std::vector<at::Tensor> get_tensors() const override;
393
+ virtual size_t num_tensors() const override;
394
+ virtual at::Tensor operator()(const at::Tensor&) const override;
395
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
396
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
397
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
398
+
399
+ protected:
400
+ virtual void set_symints(std::vector<c10::SymInt>) override;
401
+ virtual void set_tensors(std::vector<at::Tensor>) override;
402
+
403
+ private:
404
+
405
+ };
406
+
407
+ #define DIAGONAL_VIEW_FUNC_AVAILABLE
408
+ struct DiagonalViewFunc : public torch::autograd::ViewFunc {
409
+ DiagonalViewFunc(int64_t offset, int64_t dim1, int64_t dim2) : offset(offset), dim1(dim1), dim2(dim2)
410
+ {}
411
+ virtual ~DiagonalViewFunc() override = default;
412
+ virtual std::vector<c10::SymInt> get_symints() const override;
413
+ virtual size_t num_symints() const override;
414
+ virtual std::vector<at::Tensor> get_tensors() const override;
415
+ virtual size_t num_tensors() const override;
416
+ virtual at::Tensor operator()(const at::Tensor&) const override;
417
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
418
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
419
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
420
+
421
+ protected:
422
+ virtual void set_symints(std::vector<c10::SymInt>) override;
423
+ virtual void set_tensors(std::vector<at::Tensor>) override;
424
+
425
+ private:
426
+ int64_t offset;
427
+ int64_t dim1;
428
+ int64_t dim2;
429
+ };
430
+
431
+ #define EXPAND_VIEW_FUNC_AVAILABLE
432
+ struct ExpandViewFunc : public torch::autograd::ViewFunc {
433
+ ExpandViewFunc(c10::SymIntArrayRef size, bool implicit) : size(size.vec()), implicit(implicit)
434
+ {}
435
+ virtual ~ExpandViewFunc() override = default;
436
+ virtual std::vector<c10::SymInt> get_symints() const override;
437
+ virtual size_t num_symints() const override;
438
+ virtual std::vector<at::Tensor> get_tensors() const override;
439
+ virtual size_t num_tensors() const override;
440
+ virtual at::Tensor operator()(const at::Tensor&) const override;
441
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
442
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
443
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
444
+
445
+ protected:
446
+ virtual void set_symints(std::vector<c10::SymInt>) override;
447
+ virtual void set_tensors(std::vector<at::Tensor>) override;
448
+
449
+ private:
450
+ ::std::vector<c10::SymInt> size;
451
+ bool implicit;
452
+ };
453
+
454
+ #define INDICES_VIEW_FUNC_AVAILABLE
455
+ struct IndicesViewFunc : public torch::autograd::ViewFunc {
456
+ IndicesViewFunc()
457
+ {}
458
+ virtual ~IndicesViewFunc() override = default;
459
+ virtual std::vector<c10::SymInt> get_symints() const override;
460
+ virtual size_t num_symints() const override;
461
+ virtual std::vector<at::Tensor> get_tensors() const override;
462
+ virtual size_t num_tensors() const override;
463
+ virtual at::Tensor operator()(const at::Tensor&) const override;
464
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
465
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
466
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
467
+
468
+ protected:
469
+ virtual void set_symints(std::vector<c10::SymInt>) override;
470
+ virtual void set_tensors(std::vector<at::Tensor>) override;
471
+
472
+ private:
473
+
474
+ };
475
+
476
+ #define NARROW_VIEW_FUNC_AVAILABLE
477
+ struct NarrowViewFunc : public torch::autograd::ViewFunc {
478
+ NarrowViewFunc(int64_t dim, c10::SymInt start, c10::SymInt length) : dim(dim), start(start), length(length)
479
+ {}
480
+ virtual ~NarrowViewFunc() override = default;
481
+ virtual std::vector<c10::SymInt> get_symints() const override;
482
+ virtual size_t num_symints() const override;
483
+ virtual std::vector<at::Tensor> get_tensors() const override;
484
+ virtual size_t num_tensors() const override;
485
+ virtual at::Tensor operator()(const at::Tensor&) const override;
486
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
487
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
488
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
489
+
490
+ protected:
491
+ virtual void set_symints(std::vector<c10::SymInt>) override;
492
+ virtual void set_tensors(std::vector<at::Tensor>) override;
493
+
494
+ private:
495
+ int64_t dim;
496
+ c10::SymInt start;
497
+ c10::SymInt length;
498
+ };
499
+
500
+ #define PERMUTE_VIEW_FUNC_AVAILABLE
501
+ struct PermuteViewFunc : public torch::autograd::ViewFunc {
502
+ PermuteViewFunc(at::IntArrayRef dims) : dims(dims.vec())
503
+ {}
504
+ virtual ~PermuteViewFunc() override = default;
505
+ virtual std::vector<c10::SymInt> get_symints() const override;
506
+ virtual size_t num_symints() const override;
507
+ virtual std::vector<at::Tensor> get_tensors() const override;
508
+ virtual size_t num_tensors() const override;
509
+ virtual at::Tensor operator()(const at::Tensor&) const override;
510
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
511
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
512
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
513
+
514
+ protected:
515
+ virtual void set_symints(std::vector<c10::SymInt>) override;
516
+ virtual void set_tensors(std::vector<at::Tensor>) override;
517
+
518
+ private:
519
+ ::std::vector<int64_t> dims;
520
+ };
521
+
522
+ #define ROW_INDICES_VIEW_FUNC_AVAILABLE
523
+ struct RowIndicesViewFunc : public torch::autograd::ViewFunc {
524
+ RowIndicesViewFunc()
525
+ {}
526
+ virtual ~RowIndicesViewFunc() override = default;
527
+ virtual std::vector<c10::SymInt> get_symints() const override;
528
+ virtual size_t num_symints() const override;
529
+ virtual std::vector<at::Tensor> get_tensors() const override;
530
+ virtual size_t num_tensors() const override;
531
+ virtual at::Tensor operator()(const at::Tensor&) const override;
532
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
533
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
534
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
535
+
536
+ protected:
537
+ virtual void set_symints(std::vector<c10::SymInt>) override;
538
+ virtual void set_tensors(std::vector<at::Tensor>) override;
539
+
540
+ private:
541
+
542
+ };
543
+
544
+ #define SELECT_INT_VIEW_FUNC_AVAILABLE
545
+ struct SelectIntViewFunc : public torch::autograd::ViewFunc {
546
+ SelectIntViewFunc(int64_t dim, c10::SymInt index) : dim(dim), index(index)
547
+ {}
548
+ virtual ~SelectIntViewFunc() override = default;
549
+ virtual std::vector<c10::SymInt> get_symints() const override;
550
+ virtual size_t num_symints() const override;
551
+ virtual std::vector<at::Tensor> get_tensors() const override;
552
+ virtual size_t num_tensors() const override;
553
+ virtual at::Tensor operator()(const at::Tensor&) const override;
554
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
555
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
556
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
557
+
558
+ protected:
559
+ virtual void set_symints(std::vector<c10::SymInt>) override;
560
+ virtual void set_tensors(std::vector<at::Tensor>) override;
561
+
562
+ private:
563
+ int64_t dim;
564
+ c10::SymInt index;
565
+ };
566
+
567
+ #define SLICE_TENSOR_VIEW_FUNC_AVAILABLE
568
+ struct SliceTensorViewFunc : public torch::autograd::ViewFunc {
569
+ SliceTensorViewFunc(int64_t dim, ::std::optional<c10::SymInt> start, ::std::optional<c10::SymInt> end, c10::SymInt step) : dim(dim), start(start), end(end), step(step)
570
+ {}
571
+ virtual ~SliceTensorViewFunc() override = default;
572
+ virtual std::vector<c10::SymInt> get_symints() const override;
573
+ virtual size_t num_symints() const override;
574
+ virtual std::vector<at::Tensor> get_tensors() const override;
575
+ virtual size_t num_tensors() const override;
576
+ virtual at::Tensor operator()(const at::Tensor&) const override;
577
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
578
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
579
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
580
+
581
+ protected:
582
+ virtual void set_symints(std::vector<c10::SymInt>) override;
583
+ virtual void set_tensors(std::vector<at::Tensor>) override;
584
+
585
+ private:
586
+ int64_t dim;
587
+ ::std::optional<c10::SymInt> start;
588
+ ::std::optional<c10::SymInt> end;
589
+ c10::SymInt step;
590
+ };
591
+
592
+ #define SLICE_INVERSE_VIEW_FUNC_AVAILABLE
593
+ struct SliceInverseViewFunc : public torch::autograd::ViewFunc {
594
+ SliceInverseViewFunc(const at::Tensor & src, int64_t dim, ::std::optional<c10::SymInt> start, ::std::optional<c10::SymInt> end, c10::SymInt step) : src(src), dim(dim), start(start), end(end), step(step)
595
+ {}
596
+ virtual ~SliceInverseViewFunc() override = default;
597
+ virtual std::vector<c10::SymInt> get_symints() const override;
598
+ virtual size_t num_symints() const override;
599
+ virtual std::vector<at::Tensor> get_tensors() const override;
600
+ virtual size_t num_tensors() const override;
601
+ virtual at::Tensor operator()(const at::Tensor&) const override;
602
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
603
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
604
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
605
+
606
+ protected:
607
+ virtual void set_symints(std::vector<c10::SymInt>) override;
608
+ virtual void set_tensors(std::vector<at::Tensor>) override;
609
+
610
+ private:
611
+ at::Tensor src;
612
+ int64_t dim;
613
+ ::std::optional<c10::SymInt> start;
614
+ ::std::optional<c10::SymInt> end;
615
+ c10::SymInt step;
616
+ };
617
+
618
+ #define SPLIT_TENSOR_VIEW_FUNC_AVAILABLE
619
+ struct SplitTensorViewFunc : public torch::autograd::ViewFunc {
620
+ SplitTensorViewFunc(c10::SymInt split_size, int64_t dim, int64_t view_idx) : split_size(split_size), dim(dim), view_idx(view_idx)
621
+ {}
622
+ virtual ~SplitTensorViewFunc() override = default;
623
+ virtual std::vector<c10::SymInt> get_symints() const override;
624
+ virtual size_t num_symints() const override;
625
+ virtual std::vector<at::Tensor> get_tensors() const override;
626
+ virtual size_t num_tensors() const override;
627
+ virtual at::Tensor operator()(const at::Tensor&) const override;
628
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
629
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
630
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
631
+
632
+ protected:
633
+ virtual void set_symints(std::vector<c10::SymInt>) override;
634
+ virtual void set_tensors(std::vector<at::Tensor>) override;
635
+
636
+ private:
637
+ c10::SymInt split_size;
638
+ int64_t dim;
639
+ int64_t view_idx;
640
+ };
641
+
642
+ #define SPLIT_WITH_SIZES_VIEW_FUNC_AVAILABLE
643
+ struct SplitWithSizesViewFunc : public torch::autograd::ViewFunc {
644
+ SplitWithSizesViewFunc(c10::SymIntArrayRef split_sizes, int64_t dim, int64_t view_idx) : split_sizes(split_sizes.vec()), dim(dim), view_idx(view_idx)
645
+ {}
646
+ virtual ~SplitWithSizesViewFunc() override = default;
647
+ virtual std::vector<c10::SymInt> get_symints() const override;
648
+ virtual size_t num_symints() const override;
649
+ virtual std::vector<at::Tensor> get_tensors() const override;
650
+ virtual size_t num_tensors() const override;
651
+ virtual at::Tensor operator()(const at::Tensor&) const override;
652
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
653
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
654
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
655
+
656
+ protected:
657
+ virtual void set_symints(std::vector<c10::SymInt>) override;
658
+ virtual void set_tensors(std::vector<at::Tensor>) override;
659
+
660
+ private:
661
+ ::std::vector<c10::SymInt> split_sizes;
662
+ int64_t dim;
663
+ int64_t view_idx;
664
+ };
665
+
666
+ #define SQUEEZE_VIEW_FUNC_AVAILABLE
667
+ struct SqueezeViewFunc : public torch::autograd::ViewFunc {
668
+ SqueezeViewFunc()
669
+ {}
670
+ virtual ~SqueezeViewFunc() override = default;
671
+ virtual std::vector<c10::SymInt> get_symints() const override;
672
+ virtual size_t num_symints() const override;
673
+ virtual std::vector<at::Tensor> get_tensors() const override;
674
+ virtual size_t num_tensors() const override;
675
+ virtual at::Tensor operator()(const at::Tensor&) const override;
676
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
677
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
678
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
679
+
680
+ protected:
681
+ virtual void set_symints(std::vector<c10::SymInt>) override;
682
+ virtual void set_tensors(std::vector<at::Tensor>) override;
683
+
684
+ private:
685
+
686
+ };
687
+
688
+ #define SQUEEZE_DIM_VIEW_FUNC_AVAILABLE
689
+ struct SqueezeDimViewFunc : public torch::autograd::ViewFunc {
690
+ SqueezeDimViewFunc(int64_t dim) : dim(dim)
691
+ {}
692
+ virtual ~SqueezeDimViewFunc() override = default;
693
+ virtual std::vector<c10::SymInt> get_symints() const override;
694
+ virtual size_t num_symints() const override;
695
+ virtual std::vector<at::Tensor> get_tensors() const override;
696
+ virtual size_t num_tensors() const override;
697
+ virtual at::Tensor operator()(const at::Tensor&) const override;
698
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
699
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
700
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
701
+
702
+ protected:
703
+ virtual void set_symints(std::vector<c10::SymInt>) override;
704
+ virtual void set_tensors(std::vector<at::Tensor>) override;
705
+
706
+ private:
707
+ int64_t dim;
708
+ };
709
+
710
+ #define SQUEEZE_DIMS_VIEW_FUNC_AVAILABLE
711
+ struct SqueezeDimsViewFunc : public torch::autograd::ViewFunc {
712
+ SqueezeDimsViewFunc(at::IntArrayRef dim) : dim(dim.vec())
713
+ {}
714
+ virtual ~SqueezeDimsViewFunc() override = default;
715
+ virtual std::vector<c10::SymInt> get_symints() const override;
716
+ virtual size_t num_symints() const override;
717
+ virtual std::vector<at::Tensor> get_tensors() const override;
718
+ virtual size_t num_tensors() const override;
719
+ virtual at::Tensor operator()(const at::Tensor&) const override;
720
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
721
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
722
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
723
+
724
+ protected:
725
+ virtual void set_symints(std::vector<c10::SymInt>) override;
726
+ virtual void set_tensors(std::vector<at::Tensor>) override;
727
+
728
+ private:
729
+ ::std::vector<int64_t> dim;
730
+ };
731
+
732
+ #define T_VIEW_FUNC_AVAILABLE
733
+ struct TViewFunc : public torch::autograd::ViewFunc {
734
+ TViewFunc()
735
+ {}
736
+ virtual ~TViewFunc() override = default;
737
+ virtual std::vector<c10::SymInt> get_symints() const override;
738
+ virtual size_t num_symints() const override;
739
+ virtual std::vector<at::Tensor> get_tensors() const override;
740
+ virtual size_t num_tensors() const override;
741
+ virtual at::Tensor operator()(const at::Tensor&) const override;
742
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
743
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
744
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
745
+
746
+ protected:
747
+ virtual void set_symints(std::vector<c10::SymInt>) override;
748
+ virtual void set_tensors(std::vector<at::Tensor>) override;
749
+
750
+ private:
751
+
752
+ };
753
+
754
+ #define TRANSPOSE_INT_VIEW_FUNC_AVAILABLE
755
+ struct TransposeIntViewFunc : public torch::autograd::ViewFunc {
756
+ TransposeIntViewFunc(int64_t dim0, int64_t dim1) : dim0(dim0), dim1(dim1)
757
+ {}
758
+ virtual ~TransposeIntViewFunc() override = default;
759
+ virtual std::vector<c10::SymInt> get_symints() const override;
760
+ virtual size_t num_symints() const override;
761
+ virtual std::vector<at::Tensor> get_tensors() const override;
762
+ virtual size_t num_tensors() const override;
763
+ virtual at::Tensor operator()(const at::Tensor&) const override;
764
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
765
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
766
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
767
+
768
+ protected:
769
+ virtual void set_symints(std::vector<c10::SymInt>) override;
770
+ virtual void set_tensors(std::vector<at::Tensor>) override;
771
+
772
+ private:
773
+ int64_t dim0;
774
+ int64_t dim1;
775
+ };
776
+
777
+ #define UNBIND_INT_VIEW_FUNC_AVAILABLE
778
+ struct UnbindIntViewFunc : public torch::autograd::ViewFunc {
779
+ UnbindIntViewFunc(int64_t dim, int64_t view_idx) : dim(dim), view_idx(view_idx)
780
+ {}
781
+ virtual ~UnbindIntViewFunc() override = default;
782
+ virtual std::vector<c10::SymInt> get_symints() const override;
783
+ virtual size_t num_symints() const override;
784
+ virtual std::vector<at::Tensor> get_tensors() const override;
785
+ virtual size_t num_tensors() const override;
786
+ virtual at::Tensor operator()(const at::Tensor&) const override;
787
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
788
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
789
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
790
+
791
+ protected:
792
+ virtual void set_symints(std::vector<c10::SymInt>) override;
793
+ virtual void set_tensors(std::vector<at::Tensor>) override;
794
+
795
+ private:
796
+ int64_t dim;
797
+ int64_t view_idx;
798
+ };
799
+
800
+ #define UNFOLD_VIEW_FUNC_AVAILABLE
801
+ struct UnfoldViewFunc : public torch::autograd::ViewFunc {
802
+ UnfoldViewFunc(int64_t dimension, int64_t size, int64_t step) : dimension(dimension), size(size), step(step)
803
+ {}
804
+ virtual ~UnfoldViewFunc() override = default;
805
+ virtual std::vector<c10::SymInt> get_symints() const override;
806
+ virtual size_t num_symints() const override;
807
+ virtual std::vector<at::Tensor> get_tensors() const override;
808
+ virtual size_t num_tensors() const override;
809
+ virtual at::Tensor operator()(const at::Tensor&) const override;
810
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
811
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
812
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
813
+
814
+ protected:
815
+ virtual void set_symints(std::vector<c10::SymInt>) override;
816
+ virtual void set_tensors(std::vector<at::Tensor>) override;
817
+
818
+ private:
819
+ int64_t dimension;
820
+ int64_t size;
821
+ int64_t step;
822
+ };
823
+
824
+ #define UNSQUEEZE_VIEW_FUNC_AVAILABLE
825
+ struct UnsqueezeViewFunc : public torch::autograd::ViewFunc {
826
+ UnsqueezeViewFunc(int64_t dim) : dim(dim)
827
+ {}
828
+ virtual ~UnsqueezeViewFunc() override = default;
829
+ virtual std::vector<c10::SymInt> get_symints() const override;
830
+ virtual size_t num_symints() const override;
831
+ virtual std::vector<at::Tensor> get_tensors() const override;
832
+ virtual size_t num_tensors() const override;
833
+ virtual at::Tensor operator()(const at::Tensor&) const override;
834
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
835
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
836
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
837
+
838
+ protected:
839
+ virtual void set_symints(std::vector<c10::SymInt>) override;
840
+ virtual void set_tensors(std::vector<at::Tensor>) override;
841
+
842
+ private:
843
+ int64_t dim;
844
+ };
845
+
846
+ #define VALUES_VIEW_FUNC_AVAILABLE
847
+ struct ValuesViewFunc : public torch::autograd::ViewFunc {
848
+ ValuesViewFunc()
849
+ {}
850
+ virtual ~ValuesViewFunc() override = default;
851
+ virtual std::vector<c10::SymInt> get_symints() const override;
852
+ virtual size_t num_symints() const override;
853
+ virtual std::vector<at::Tensor> get_tensors() const override;
854
+ virtual size_t num_tensors() const override;
855
+ virtual at::Tensor operator()(const at::Tensor&) const override;
856
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
857
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
858
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
859
+
860
+ protected:
861
+ virtual void set_symints(std::vector<c10::SymInt>) override;
862
+ virtual void set_tensors(std::vector<at::Tensor>) override;
863
+
864
+ private:
865
+
866
+ };
867
+
868
+ #define VIEW_VIEW_FUNC_AVAILABLE
869
+ struct ViewViewFunc : public torch::autograd::ViewFunc {
870
+ ViewViewFunc(c10::SymIntArrayRef size) : size(size.vec())
871
+ {}
872
+ virtual ~ViewViewFunc() override = default;
873
+ virtual std::vector<c10::SymInt> get_symints() const override;
874
+ virtual size_t num_symints() const override;
875
+ virtual std::vector<at::Tensor> get_tensors() const override;
876
+ virtual size_t num_tensors() const override;
877
+ virtual at::Tensor operator()(const at::Tensor&) const override;
878
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
879
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
880
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
881
+
882
+ protected:
883
+ virtual void set_symints(std::vector<c10::SymInt>) override;
884
+ virtual void set_tensors(std::vector<at::Tensor>) override;
885
+
886
+ private:
887
+ ::std::vector<c10::SymInt> size;
888
+ };
889
+
890
+ #define VIEW_DTYPE_VIEW_FUNC_AVAILABLE
891
+ struct ViewDtypeViewFunc : public torch::autograd::ViewFunc {
892
+ ViewDtypeViewFunc(at::ScalarType dtype) : dtype(dtype)
893
+ {}
894
+ virtual ~ViewDtypeViewFunc() override = default;
895
+ virtual std::vector<c10::SymInt> get_symints() const override;
896
+ virtual size_t num_symints() const override;
897
+ virtual std::vector<at::Tensor> get_tensors() const override;
898
+ virtual size_t num_tensors() const override;
899
+ virtual at::Tensor operator()(const at::Tensor&) const override;
900
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
901
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
902
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
903
+
904
+ protected:
905
+ virtual void set_symints(std::vector<c10::SymInt>) override;
906
+ virtual void set_tensors(std::vector<at::Tensor>) override;
907
+
908
+ private:
909
+ at::ScalarType dtype;
910
+ };
911
+
912
+ #define VIEW_AS_COMPLEX_VIEW_FUNC_AVAILABLE
913
+ struct ViewAsComplexViewFunc : public torch::autograd::ViewFunc {
914
+ ViewAsComplexViewFunc()
915
+ {}
916
+ virtual ~ViewAsComplexViewFunc() override = default;
917
+ virtual std::vector<c10::SymInt> get_symints() const override;
918
+ virtual size_t num_symints() const override;
919
+ virtual std::vector<at::Tensor> get_tensors() const override;
920
+ virtual size_t num_tensors() const override;
921
+ virtual at::Tensor operator()(const at::Tensor&) const override;
922
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
923
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
924
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
925
+
926
+ protected:
927
+ virtual void set_symints(std::vector<c10::SymInt>) override;
928
+ virtual void set_tensors(std::vector<at::Tensor>) override;
929
+
930
+ private:
931
+
932
+ };
933
+
934
+ #define VIEW_AS_REAL_VIEW_FUNC_AVAILABLE
935
+ struct ViewAsRealViewFunc : public torch::autograd::ViewFunc {
936
+ ViewAsRealViewFunc()
937
+ {}
938
+ virtual ~ViewAsRealViewFunc() override = default;
939
+ virtual std::vector<c10::SymInt> get_symints() const override;
940
+ virtual size_t num_symints() const override;
941
+ virtual std::vector<at::Tensor> get_tensors() const override;
942
+ virtual size_t num_tensors() const override;
943
+ virtual at::Tensor operator()(const at::Tensor&) const override;
944
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
945
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
946
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
947
+
948
+ protected:
949
+ virtual void set_symints(std::vector<c10::SymInt>) override;
950
+ virtual void set_tensors(std::vector<at::Tensor>) override;
951
+
952
+ private:
953
+
954
+ };
955
+
956
+ } // namespace torch::autograd::generated
957
+
958
+ #else
959
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
960
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_functions.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <Python.h>
5
+
6
+ // @generated from ../tools/autograd/templates/python_functions.h
7
+
8
+ // Python bindings for automatically generated autograd functions
9
+
10
+ namespace torch { namespace autograd { namespace generated {
11
+
12
+ void initialize_autogenerated_functions_0(PyObject* module);
13
+ void initialize_autogenerated_functions_1(PyObject* module);
14
+ void initialize_autogenerated_functions_2(PyObject* module);
15
+ void initialize_autogenerated_functions_3(PyObject* module);
16
+ void initialize_autogenerated_functions_4(PyObject* module);
17
+
18
+ inline void initialize_autogenerated_functions(PyObject* module) {
19
+ initialize_autogenerated_functions_0(module);
20
+ initialize_autogenerated_functions_1(module);
21
+ initialize_autogenerated_functions_2(module);
22
+ initialize_autogenerated_functions_3(module);
23
+ initialize_autogenerated_functions_4(module);
24
+ }
25
+
26
+ }}} // namespace torch::autograd::generated
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/python_return_types.h ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace torch {
5
+ namespace autograd {
6
+ namespace generated {
7
+
8
+ PyTypeObject* get__fake_quantize_per_tensor_affine_cachemask_tensor_qparams_structseq();
9
+ PyTypeObject* get__fused_moving_avg_obs_fq_helper_structseq();
10
+ PyTypeObject* get__linalg_det_structseq();
11
+ PyTypeObject* get__linalg_det_out_structseq();
12
+ PyTypeObject* get__linalg_eigh_structseq();
13
+ PyTypeObject* get__linalg_eigh_out_structseq();
14
+ PyTypeObject* get__linalg_slogdet_structseq();
15
+ PyTypeObject* get__linalg_slogdet_out_structseq();
16
+ PyTypeObject* get__linalg_solve_ex_structseq();
17
+ PyTypeObject* get__linalg_solve_ex_out_structseq();
18
+ PyTypeObject* get__linalg_svd_structseq();
19
+ PyTypeObject* get__linalg_svd_out_structseq();
20
+ PyTypeObject* get__lu_with_info_structseq();
21
+ PyTypeObject* get__scaled_dot_product_cudnn_attention_structseq();
22
+ PyTypeObject* get__scaled_dot_product_efficient_attention_structseq();
23
+ PyTypeObject* get__scaled_dot_product_flash_attention_structseq();
24
+ PyTypeObject* get__scaled_dot_product_flash_attention_for_cpu_structseq();
25
+ PyTypeObject* get__unpack_dual_structseq();
26
+ PyTypeObject* get_aminmax_structseq();
27
+ PyTypeObject* get_aminmax_out_structseq();
28
+ PyTypeObject* get_cummax_structseq();
29
+ PyTypeObject* get_cummax_out_structseq();
30
+ PyTypeObject* get_cummin_structseq();
31
+ PyTypeObject* get_cummin_out_structseq();
32
+ PyTypeObject* get_frexp_structseq();
33
+ PyTypeObject* get_frexp_out_structseq();
34
+ PyTypeObject* get_geqrf_out_structseq();
35
+ PyTypeObject* get_geqrf_structseq();
36
+ PyTypeObject* get_histogram_out_structseq();
37
+ PyTypeObject* get_histogram_structseq();
38
+ PyTypeObject* get_histogramdd_structseq();
39
+ PyTypeObject* get_kthvalue_structseq();
40
+ PyTypeObject* get_kthvalue_out_structseq();
41
+ PyTypeObject* get_linalg_cholesky_ex_structseq();
42
+ PyTypeObject* get_linalg_cholesky_ex_out_structseq();
43
+ PyTypeObject* get_linalg_eig_structseq();
44
+ PyTypeObject* get_linalg_eig_out_structseq();
45
+ PyTypeObject* get_linalg_eigh_structseq();
46
+ PyTypeObject* get_linalg_eigh_out_structseq();
47
+ PyTypeObject* get_linalg_inv_ex_structseq();
48
+ PyTypeObject* get_linalg_inv_ex_out_structseq();
49
+ PyTypeObject* get_linalg_ldl_factor_structseq();
50
+ PyTypeObject* get_linalg_ldl_factor_out_structseq();
51
+ PyTypeObject* get_linalg_ldl_factor_ex_structseq();
52
+ PyTypeObject* get_linalg_ldl_factor_ex_out_structseq();
53
+ PyTypeObject* get_linalg_lstsq_structseq();
54
+ PyTypeObject* get_linalg_lstsq_out_structseq();
55
+ PyTypeObject* get_linalg_lu_structseq();
56
+ PyTypeObject* get_linalg_lu_out_structseq();
57
+ PyTypeObject* get_linalg_lu_factor_structseq();
58
+ PyTypeObject* get_linalg_lu_factor_out_structseq();
59
+ PyTypeObject* get_linalg_lu_factor_ex_structseq();
60
+ PyTypeObject* get_linalg_lu_factor_ex_out_structseq();
61
+ PyTypeObject* get_linalg_qr_structseq();
62
+ PyTypeObject* get_linalg_qr_out_structseq();
63
+ PyTypeObject* get_linalg_slogdet_structseq();
64
+ PyTypeObject* get_linalg_slogdet_out_structseq();
65
+ PyTypeObject* get_linalg_solve_ex_structseq();
66
+ PyTypeObject* get_linalg_solve_ex_out_structseq();
67
+ PyTypeObject* get_linalg_svd_structseq();
68
+ PyTypeObject* get_linalg_svd_out_structseq();
69
+ PyTypeObject* get_lu_unpack_structseq();
70
+ PyTypeObject* get_lu_unpack_out_structseq();
71
+ PyTypeObject* get_max_structseq();
72
+ PyTypeObject* get_max_out_structseq();
73
+ PyTypeObject* get_median_structseq();
74
+ PyTypeObject* get_median_out_structseq();
75
+ PyTypeObject* get_min_structseq();
76
+ PyTypeObject* get_min_out_structseq();
77
+ PyTypeObject* get_mode_structseq();
78
+ PyTypeObject* get_mode_out_structseq();
79
+ PyTypeObject* get_nanmedian_structseq();
80
+ PyTypeObject* get_nanmedian_out_structseq();
81
+ PyTypeObject* get_qr_out_structseq();
82
+ PyTypeObject* get_qr_structseq();
83
+ PyTypeObject* get_slogdet_structseq();
84
+ PyTypeObject* get_slogdet_out_structseq();
85
+ PyTypeObject* get_sort_out_structseq();
86
+ PyTypeObject* get_sort_structseq();
87
+ PyTypeObject* get_svd_out_structseq();
88
+ PyTypeObject* get_svd_structseq();
89
+ PyTypeObject* get_topk_out_structseq();
90
+ PyTypeObject* get_topk_structseq();
91
+ PyTypeObject* get_triangular_solve_out_structseq();
92
+ PyTypeObject* get_triangular_solve_structseq();
93
+
94
+ }
95
+
96
+ void initReturnTypes(PyObject* module);
97
+
98
+ } // namespace autograd
99
+ } // namespace torch
100
+
101
+ #else
102
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
103
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/generated/variable_factories.h ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // @generated from ../tools/autograd/templates/variable_factories.h
5
+
6
+ #include <ATen/core/Tensor.h>
7
+ #include <ATen/TracerMode.h>
8
+ #include <ATen/core/grad_mode.h>
9
+ #include <c10/util/ArrayRef.h>
10
+ #include <c10/core/MemoryFormat.h>
11
+ #include <torch/csrc/api/include/torch/detail/TensorDataContainer.h>
12
+ #include <torch/csrc/autograd/variable.h>
13
+
14
+ #ifndef AT_PER_OPERATOR_HEADERS
15
+ #include <ATen/Functions.h>
16
+ #else
17
+ #include <ATen/ops/from_blob.h>
18
+ #include <ATen/ops/_make_dep_token.h>
19
+ #include <ATen/ops/_cudnn_init_dropout_state.h>
20
+ #include <ATen/ops/arange.h>
21
+ #include <ATen/ops/arange.h>
22
+ #include <ATen/ops/arange.h>
23
+ #include <ATen/ops/bartlett_window.h>
24
+ #include <ATen/ops/bartlett_window.h>
25
+ #include <ATen/ops/blackman_window.h>
26
+ #include <ATen/ops/blackman_window.h>
27
+ #include <ATen/ops/empty.h>
28
+ #include <ATen/ops/empty.h>
29
+ #include <ATen/ops/empty_permuted.h>
30
+ #include <ATen/ops/_empty_affine_quantized.h>
31
+ #include <ATen/ops/_empty_per_channel_affine_quantized.h>
32
+ #include <ATen/ops/empty_quantized.h>
33
+ #include <ATen/ops/empty_like.h>
34
+ #include <ATen/ops/empty_strided.h>
35
+ #include <ATen/ops/eye.h>
36
+ #include <ATen/ops/eye.h>
37
+ #include <ATen/ops/full.h>
38
+ #include <ATen/ops/full.h>
39
+ #include <ATen/ops/full_like.h>
40
+ #include <ATen/ops/from_file.h>
41
+ #include <ATen/ops/hann_window.h>
42
+ #include <ATen/ops/hann_window.h>
43
+ #include <ATen/ops/hamming_window.h>
44
+ #include <ATen/ops/hamming_window.h>
45
+ #include <ATen/ops/hamming_window.h>
46
+ #include <ATen/ops/hamming_window.h>
47
+ #include <ATen/ops/kaiser_window.h>
48
+ #include <ATen/ops/kaiser_window.h>
49
+ #include <ATen/ops/kaiser_window.h>
50
+ #include <ATen/ops/linspace.h>
51
+ #include <ATen/ops/linspace.h>
52
+ #include <ATen/ops/linspace.h>
53
+ #include <ATen/ops/linspace.h>
54
+ #include <ATen/ops/logspace.h>
55
+ #include <ATen/ops/logspace.h>
56
+ #include <ATen/ops/logspace.h>
57
+ #include <ATen/ops/logspace.h>
58
+ #include <ATen/ops/ones.h>
59
+ #include <ATen/ops/ones.h>
60
+ #include <ATen/ops/ones_like.h>
61
+ #include <ATen/ops/scalar_tensor.h>
62
+ #include <ATen/ops/rand.h>
63
+ #include <ATen/ops/rand.h>
64
+ #include <ATen/ops/rand.h>
65
+ #include <ATen/ops/rand.h>
66
+ #include <ATen/ops/rand_like.h>
67
+ #include <ATen/ops/rand_like.h>
68
+ #include <ATen/ops/randint.h>
69
+ #include <ATen/ops/randint.h>
70
+ #include <ATen/ops/randint.h>
71
+ #include <ATen/ops/randint.h>
72
+ #include <ATen/ops/randint_like.h>
73
+ #include <ATen/ops/randint_like.h>
74
+ #include <ATen/ops/randint_like.h>
75
+ #include <ATen/ops/randint_like.h>
76
+ #include <ATen/ops/randint_like.h>
77
+ #include <ATen/ops/randint_like.h>
78
+ #include <ATen/ops/randn.h>
79
+ #include <ATen/ops/randn.h>
80
+ #include <ATen/ops/randn.h>
81
+ #include <ATen/ops/randn.h>
82
+ #include <ATen/ops/randn_like.h>
83
+ #include <ATen/ops/randn_like.h>
84
+ #include <ATen/ops/randperm.h>
85
+ #include <ATen/ops/randperm.h>
86
+ #include <ATen/ops/range.h>
87
+ #include <ATen/ops/range.h>
88
+ #include <ATen/ops/zeros.h>
89
+ #include <ATen/ops/_efficientzerotensor.h>
90
+ #include <ATen/ops/zeros.h>
91
+ #include <ATen/ops/zeros_like.h>
92
+ #include <ATen/ops/_sparse_compressed_tensor_with_dims.h>
93
+ #include <ATen/ops/sparse_compressed_tensor.h>
94
+ #include <ATen/ops/sparse_csr_tensor.h>
95
+ #include <ATen/ops/sparse_csc_tensor.h>
96
+ #include <ATen/ops/sparse_bsr_tensor.h>
97
+ #include <ATen/ops/sparse_bsc_tensor.h>
98
+ #include <ATen/ops/sparse_compressed_tensor.h>
99
+ #include <ATen/ops/sparse_csr_tensor.h>
100
+ #include <ATen/ops/sparse_csc_tensor.h>
101
+ #include <ATen/ops/sparse_bsr_tensor.h>
102
+ #include <ATen/ops/sparse_bsc_tensor.h>
103
+ #include <ATen/ops/_sparse_compressed_tensor_unsafe.h>
104
+ #include <ATen/ops/_sparse_csr_tensor_unsafe.h>
105
+ #include <ATen/ops/_sparse_csc_tensor_unsafe.h>
106
+ #include <ATen/ops/_sparse_bsr_tensor_unsafe.h>
107
+ #include <ATen/ops/_sparse_bsc_tensor_unsafe.h>
108
+ #include <ATen/ops/sparse_coo_tensor.h>
109
+ #include <ATen/ops/sparse_coo_tensor.h>
110
+ #include <ATen/ops/sparse_coo_tensor.h>
111
+ #include <ATen/ops/_sparse_coo_tensor_unsafe.h>
112
+ #include <ATen/ops/_sparse_coo_tensor_with_dims.h>
113
+ #include <ATen/ops/_sparse_coo_tensor_with_dims_and_tensors.h>
114
+ #include <ATen/ops/_to_copy.h>
115
+ #include <ATen/ops/tril_indices.h>
116
+ #include <ATen/ops/triu_indices.h>
117
+ #include <ATen/ops/normal.h>
118
+ #include <ATen/ops/fft_fftfreq.h>
119
+ #include <ATen/ops/fft_rfftfreq.h>
120
+ #endif
121
+
122
+ #include <functional>
123
+ #include <initializer_list>
124
+ #include <utility>
125
+
126
+ namespace torch {
127
+
128
+ /// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types
129
+ /// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to
130
+ /// support it in the future by iterating over all sub-lists to find
131
+ /// the largest data type that can represent all of the elements, or by using
132
+ /// variadic templates.
133
+ ///
134
+ /// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` /
135
+ /// (nested) braced-init-list of floating-point types always produces a tensor of dtype
136
+ /// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior.
137
+ ///
138
+ /// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` /
139
+ /// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong`
140
+ /// (aka. int64_t), matching Python `torch.tensor` behavior.
141
+ ///
142
+ /// NOTE: The following dtypes are not supported by `torch::tensor` currently:
143
+ /// - `unsigned int`
144
+ /// - `unsigned long int`
145
+ /// - `unsigned long long int`
146
+ /// - `long long int`
147
+ inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) {
148
+ return autograd::make_variable(
149
+ // note: we remove the requires_grad setting from the TensorOptions because
150
+ // it is ignored anyways (and we actually have an assertion that it isn't set
151
+ // which would fail otherwise). We handle requires_grad explicitly here
152
+ // instead of passing it through to the kernel.
153
+ tensor_data_container.convert_to_tensor(options.requires_grad(::std::nullopt)),
154
+ options.requires_grad());
155
+ }
156
+
157
+ /// A generic deleter function.
158
+ using Deleter = std::function<void(void*)>;
159
+ using at::MemoryFormat;
160
+
161
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
162
+ /// original data. `sizes` should specify the shape of the tensor, `strides` the
163
+ /// stride in each dimension. The `deleter` function (a
164
+ /// `std::function<void(void*)>`) will be called on the `data` when the Tensor
165
+ /// data would normally be deallocated. The `TensorOptions` specify additional
166
+ /// configuration options for the returned tensor, such as what type to
167
+ /// interpret the `data` as.
168
+ inline at::Tensor from_blob(
169
+ void* data,
170
+ at::IntArrayRef sizes,
171
+ at::IntArrayRef strides,
172
+ const Deleter& deleter,
173
+ const at::TensorOptions& options = at::TensorOptions()) {
174
+ at::Tensor tensor = ([&]() {
175
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
176
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
177
+ return at::from_blob(data, sizes, strides, deleter, options.requires_grad(::std::nullopt));
178
+ })();
179
+ return autograd::make_variable(tensor, options.requires_grad());
180
+ }
181
+
182
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
183
+ /// original data. `sizes` should specify the shape of the tensor, `strides` the
184
+ /// stride in each dimension. The `TensorOptions`
185
+ /// specify additional configuration options for the returned tensor, such as
186
+ /// what type to interpret the `data` as.
187
+ inline at::Tensor from_blob(
188
+ void* data,
189
+ at::IntArrayRef sizes,
190
+ at::IntArrayRef strides,
191
+ const at::TensorOptions& options = at::TensorOptions()) {
192
+ at::Tensor tensor = ([&]() {
193
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
194
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
195
+ return at::from_blob(data, sizes, strides, options.requires_grad(::std::nullopt));
196
+ })();
197
+ return autograd::make_variable(tensor, options.requires_grad());
198
+ }
199
+
200
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
201
+ /// original data. `sizes` should specify the shape of the tensor. The `deleter`
202
+ /// (a `std::function<void(void*)>`) function will be called on the `data` when
203
+ /// the Tensor data would normally be deallocated. The `TensorOptions` specify
204
+ /// additional configuration options for the returned tensor, such as what type
205
+ /// to interpret the `data` as.
206
+ inline at::Tensor from_blob(
207
+ void* data,
208
+ at::IntArrayRef sizes,
209
+ const Deleter& deleter,
210
+ const at::TensorOptions& options = at::TensorOptions()) {
211
+ at::Tensor tensor = ([&]() {
212
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
213
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
214
+ return at::from_blob(data, sizes, deleter, options.requires_grad(::std::nullopt));
215
+ })();
216
+ return autograd::make_variable(tensor, options.requires_grad());
217
+ }
218
+
219
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
220
+ /// original data. `sizes` should specify the shape of the tensor. The
221
+ /// `TensorOptions` specify additional configuration options for the returned
222
+ /// tensor, such as what type to interpret the `data` as.
223
+ inline at::Tensor from_blob(
224
+ void* data,
225
+ at::IntArrayRef sizes,
226
+ const at::TensorOptions& options = at::TensorOptions()) {
227
+ at::Tensor tensor = ([&]() {
228
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
229
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
230
+ return at::from_blob(data, sizes, options.requires_grad(::std::nullopt));
231
+ })();
232
+ return autograd::make_variable(tensor, options.requires_grad());
233
+ }
234
+
235
+ inline at::Tensor _make_dep_token(at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
236
+ at::AutoDispatchBelowADInplaceOrView guard;
237
+ return autograd::make_variable(at::_make_dep_token(at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
238
+ }
239
+ inline at::Tensor _cudnn_init_dropout_state(double dropout, bool train, int64_t dropout_seed, at::TensorOptions options) {
240
+ at::AutoDispatchBelowADInplaceOrView guard;
241
+ 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());
242
+ }
243
+ inline at::Tensor arange(const at::Scalar & end, at::TensorOptions options = {}) {
244
+ at::AutoDispatchBelowADInplaceOrView guard;
245
+ return autograd::make_variable(at::arange(end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
246
+ }
247
+ inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options = {}) {
248
+ at::AutoDispatchBelowADInplaceOrView guard;
249
+ return autograd::make_variable(at::arange(start, end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
250
+ }
251
+ inline at::Tensor arange(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::TensorOptions options = {}) {
252
+ at::AutoDispatchBelowADInplaceOrView guard;
253
+ return autograd::make_variable(at::arange(start, end, step, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
254
+ }
255
+ inline at::Tensor bartlett_window(int64_t window_length, at::TensorOptions options = {}) {
256
+ at::AutoDispatchBelowADInplaceOrView guard;
257
+ return autograd::make_variable(at::bartlett_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
258
+ }
259
+ inline at::Tensor bartlett_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
260
+ at::AutoDispatchBelowADInplaceOrView guard;
261
+ return autograd::make_variable(at::bartlett_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
262
+ }
263
+ inline at::Tensor blackman_window(int64_t window_length, at::TensorOptions options = {}) {
264
+ at::AutoDispatchBelowADInplaceOrView guard;
265
+ return autograd::make_variable(at::blackman_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
266
+ }
267
+ inline at::Tensor blackman_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
268
+ at::AutoDispatchBelowADInplaceOrView guard;
269
+ return autograd::make_variable(at::blackman_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
270
+ }
271
+ inline at::Tensor empty(at::IntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
272
+ at::AutoDispatchBelowADInplaceOrView guard;
273
+ return autograd::make_variable(at::empty(size, names, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
274
+ }
275
+ inline at::Tensor empty(at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
276
+ at::AutoDispatchBelowADInplaceOrView guard;
277
+ return autograd::make_variable(at::empty(size, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
278
+ }
279
+ inline at::Tensor empty_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
280
+ at::AutoDispatchBelowADInplaceOrView guard;
281
+ return autograd::make_variable(at::empty_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
282
+ }
283
+ inline at::Tensor empty_permuted(at::IntArrayRef size, at::IntArrayRef physical_layout, at::TensorOptions options = {}) {
284
+ at::AutoDispatchBelowADInplaceOrView guard;
285
+ return autograd::make_variable(at::empty_permuted(size, physical_layout, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
286
+ }
287
+ inline at::Tensor empty_permuted_symint(c10::SymIntArrayRef size, at::IntArrayRef physical_layout, at::TensorOptions options = {}) {
288
+ at::AutoDispatchBelowADInplaceOrView guard;
289
+ return autograd::make_variable(at::empty_permuted_symint(size, physical_layout, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
290
+ }
291
+ inline at::Tensor _empty_affine_quantized(at::IntArrayRef size, at::TensorOptions options = {}, double scale = 1, int64_t zero_point = 0, ::std::optional<at::MemoryFormat> memory_format = c10::MemoryFormat::Contiguous) {
292
+ at::AutoDispatchBelowADInplaceOrView guard;
293
+ 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());
294
+ }
295
+ inline at::Tensor _empty_affine_quantized_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}, double scale = 1, int64_t zero_point = 0, ::std::optional<at::MemoryFormat> memory_format = c10::MemoryFormat::Contiguous) {
296
+ at::AutoDispatchBelowADInplaceOrView guard;
297
+ 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());
298
+ }
299
+ 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<at::MemoryFormat> memory_format = c10::MemoryFormat::Contiguous) {
300
+ at::AutoDispatchBelowADInplaceOrView guard;
301
+ 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());
302
+ }
303
+ 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<at::MemoryFormat> memory_format = c10::MemoryFormat::Contiguous) {
304
+ at::AutoDispatchBelowADInplaceOrView guard;
305
+ 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());
306
+ }
307
+ inline at::Tensor empty_quantized(at::IntArrayRef size, const at::Tensor & qtensor, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
308
+ at::AutoDispatchBelowADInplaceOrView guard;
309
+ return autograd::make_variable(at::empty_quantized(size, qtensor, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
310
+ }
311
+ inline at::Tensor empty_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
312
+ at::AutoDispatchBelowADInplaceOrView guard;
313
+ return autograd::make_variable(at::empty_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
314
+ }
315
+ inline at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options = {}) {
316
+ at::AutoDispatchBelowADInplaceOrView guard;
317
+ return autograd::make_variable(at::empty_strided(size, stride, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
318
+ }
319
+ inline at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options = {}) {
320
+ at::AutoDispatchBelowADInplaceOrView guard;
321
+ return autograd::make_variable(at::empty_strided_symint(size, stride, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
322
+ }
323
+ inline at::Tensor eye(int64_t n, at::TensorOptions options = {}) {
324
+ at::AutoDispatchBelowADInplaceOrView guard;
325
+ return autograd::make_variable(at::eye(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
326
+ }
327
+ inline at::Tensor eye_symint(c10::SymInt n, at::TensorOptions options = {}) {
328
+ at::AutoDispatchBelowADInplaceOrView guard;
329
+ return autograd::make_variable(at::eye_symint(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
330
+ }
331
+ inline at::Tensor eye(int64_t n, int64_t m, at::TensorOptions options = {}) {
332
+ at::AutoDispatchBelowADInplaceOrView guard;
333
+ return autograd::make_variable(at::eye(n, m, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
334
+ }
335
+ inline at::Tensor eye_symint(c10::SymInt n, c10::SymInt m, at::TensorOptions options = {}) {
336
+ at::AutoDispatchBelowADInplaceOrView guard;
337
+ return autograd::make_variable(at::eye_symint(n, m, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
338
+ }
339
+ inline at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
340
+ at::AutoDispatchBelowADInplaceOrView guard;
341
+ return autograd::make_variable(at::full(size, fill_value, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
342
+ }
343
+ inline at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options = {}) {
344
+ at::AutoDispatchBelowADInplaceOrView guard;
345
+ return autograd::make_variable(at::full(size, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
346
+ }
347
+ inline at::Tensor full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options = {}) {
348
+ at::AutoDispatchBelowADInplaceOrView guard;
349
+ return autograd::make_variable(at::full_symint(size, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
350
+ }
351
+ inline at::Tensor full_like(const at::Tensor & self, const at::Scalar & fill_value, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
352
+ at::AutoDispatchBelowADInplaceOrView guard;
353
+ return autograd::make_variable(at::full_like(self, fill_value, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
354
+ }
355
+ inline at::Tensor from_file(c10::string_view filename, ::std::optional<bool> shared = ::std::nullopt, ::std::optional<int64_t> size = 0, at::TensorOptions options = {}) {
356
+ at::AutoDispatchBelowADInplaceOrView guard;
357
+ return autograd::make_variable(at::from_file(filename, shared, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
358
+ }
359
+ inline at::Tensor hann_window(int64_t window_length, at::TensorOptions options = {}) {
360
+ at::AutoDispatchBelowADInplaceOrView guard;
361
+ return autograd::make_variable(at::hann_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
362
+ }
363
+ inline at::Tensor hann_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
364
+ at::AutoDispatchBelowADInplaceOrView guard;
365
+ return autograd::make_variable(at::hann_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
366
+ }
367
+ inline at::Tensor hamming_window(int64_t window_length, at::TensorOptions options = {}) {
368
+ at::AutoDispatchBelowADInplaceOrView guard;
369
+ return autograd::make_variable(at::hamming_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
370
+ }
371
+ inline at::Tensor hamming_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
372
+ at::AutoDispatchBelowADInplaceOrView guard;
373
+ return autograd::make_variable(at::hamming_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
374
+ }
375
+ inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, at::TensorOptions options = {}) {
376
+ at::AutoDispatchBelowADInplaceOrView guard;
377
+ return autograd::make_variable(at::hamming_window(window_length, periodic, alpha, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
378
+ }
379
+ inline at::Tensor hamming_window(int64_t window_length, bool periodic, double alpha, double beta, at::TensorOptions options = {}) {
380
+ at::AutoDispatchBelowADInplaceOrView guard;
381
+ return autograd::make_variable(at::hamming_window(window_length, periodic, alpha, beta, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
382
+ }
383
+ inline at::Tensor kaiser_window(int64_t window_length, at::TensorOptions options = {}) {
384
+ at::AutoDispatchBelowADInplaceOrView guard;
385
+ return autograd::make_variable(at::kaiser_window(window_length, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
386
+ }
387
+ inline at::Tensor kaiser_window(int64_t window_length, bool periodic, at::TensorOptions options = {}) {
388
+ at::AutoDispatchBelowADInplaceOrView guard;
389
+ return autograd::make_variable(at::kaiser_window(window_length, periodic, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
390
+ }
391
+ inline at::Tensor kaiser_window(int64_t window_length, bool periodic, double beta, at::TensorOptions options = {}) {
392
+ at::AutoDispatchBelowADInplaceOrView guard;
393
+ return autograd::make_variable(at::kaiser_window(window_length, periodic, beta, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
394
+ }
395
+ inline at::Tensor linspace(const at::Scalar & start, const at::Scalar & end, int64_t steps, at::TensorOptions options = {}) {
396
+ at::AutoDispatchBelowADInplaceOrView guard;
397
+ return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
398
+ }
399
+ inline at::Tensor linspace(const at::Tensor & start, const at::Tensor & end, int64_t steps, at::TensorOptions options = {}) {
400
+ at::AutoDispatchBelowADInplaceOrView guard;
401
+ return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
402
+ }
403
+ inline at::Tensor linspace(const at::Tensor & start, const at::Scalar & end, int64_t steps, at::TensorOptions options = {}) {
404
+ at::AutoDispatchBelowADInplaceOrView guard;
405
+ return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
406
+ }
407
+ inline at::Tensor linspace(const at::Scalar & start, const at::Tensor & end, int64_t steps, at::TensorOptions options = {}) {
408
+ at::AutoDispatchBelowADInplaceOrView guard;
409
+ return autograd::make_variable(at::linspace(start, end, steps, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
410
+ }
411
+ inline at::Tensor logspace(const at::Scalar & start, const at::Scalar & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
412
+ at::AutoDispatchBelowADInplaceOrView guard;
413
+ return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
414
+ }
415
+ inline at::Tensor logspace(const at::Tensor & start, const at::Tensor & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
416
+ at::AutoDispatchBelowADInplaceOrView guard;
417
+ return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
418
+ }
419
+ inline at::Tensor logspace(const at::Tensor & start, const at::Scalar & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
420
+ at::AutoDispatchBelowADInplaceOrView guard;
421
+ return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
422
+ }
423
+ inline at::Tensor logspace(const at::Scalar & start, const at::Tensor & end, int64_t steps, double base = 10.0, at::TensorOptions options = {}) {
424
+ at::AutoDispatchBelowADInplaceOrView guard;
425
+ return autograd::make_variable(at::logspace(start, end, steps, base, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
426
+ }
427
+ inline at::Tensor ones(at::IntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
428
+ at::AutoDispatchBelowADInplaceOrView guard;
429
+ return autograd::make_variable(at::ones(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
430
+ }
431
+ inline at::Tensor ones(at::IntArrayRef size, at::TensorOptions options = {}) {
432
+ at::AutoDispatchBelowADInplaceOrView guard;
433
+ return autograd::make_variable(at::ones(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
434
+ }
435
+ inline at::Tensor ones_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
436
+ at::AutoDispatchBelowADInplaceOrView guard;
437
+ return autograd::make_variable(at::ones_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
438
+ }
439
+ inline at::Tensor ones_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
440
+ at::AutoDispatchBelowADInplaceOrView guard;
441
+ return autograd::make_variable(at::ones_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
442
+ }
443
+ inline at::Tensor scalar_tensor(const at::Scalar & s, at::TensorOptions options = {}) {
444
+ at::AutoDispatchBelowADInplaceOrView guard;
445
+ return autograd::make_variable(at::scalar_tensor(s, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
446
+ }
447
+ inline at::Tensor rand(at::IntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
448
+ at::AutoDispatchBelowADInplaceOrView guard;
449
+ return autograd::make_variable(at::rand(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
450
+ }
451
+ inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
452
+ at::AutoDispatchBelowADInplaceOrView guard;
453
+ return autograd::make_variable(at::rand_symint(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
454
+ }
455
+ inline at::Tensor rand(at::IntArrayRef size, ::std::optional<at::Generator> generator, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
456
+ at::AutoDispatchBelowADInplaceOrView guard;
457
+ return autograd::make_variable(at::rand(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
458
+ }
459
+ inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional<at::Generator> generator, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
460
+ at::AutoDispatchBelowADInplaceOrView guard;
461
+ return autograd::make_variable(at::rand_symint(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
462
+ }
463
+ inline at::Tensor rand(at::IntArrayRef size, at::TensorOptions options = {}) {
464
+ at::AutoDispatchBelowADInplaceOrView guard;
465
+ return autograd::make_variable(at::rand(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
466
+ }
467
+ inline at::Tensor rand_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
468
+ at::AutoDispatchBelowADInplaceOrView guard;
469
+ return autograd::make_variable(at::rand_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
470
+ }
471
+ inline at::Tensor rand(at::IntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = {}) {
472
+ at::AutoDispatchBelowADInplaceOrView guard;
473
+ return autograd::make_variable(at::rand(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
474
+ }
475
+ inline at::Tensor rand_symint(c10::SymIntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = {}) {
476
+ at::AutoDispatchBelowADInplaceOrView guard;
477
+ return autograd::make_variable(at::rand_symint(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
478
+ }
479
+ inline at::Tensor rand_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
480
+ at::AutoDispatchBelowADInplaceOrView guard;
481
+ return autograd::make_variable(at::rand_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
482
+ }
483
+ inline at::Tensor rand_like(const at::Tensor & self, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
484
+ at::AutoDispatchBelowADInplaceOrView guard;
485
+ return autograd::make_variable(at::rand_like(self, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
486
+ }
487
+ inline at::Tensor randint(int64_t high, at::IntArrayRef size, at::TensorOptions options = at::kLong) {
488
+ at::AutoDispatchBelowADInplaceOrView guard;
489
+ return autograd::make_variable(at::randint(high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
490
+ }
491
+ inline at::Tensor randint_symint(c10::SymInt high, c10::SymIntArrayRef size, at::TensorOptions options = at::kLong) {
492
+ at::AutoDispatchBelowADInplaceOrView guard;
493
+ return autograd::make_variable(at::randint_symint(high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
494
+ }
495
+ inline at::Tensor randint(int64_t high, at::IntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = at::kLong) {
496
+ at::AutoDispatchBelowADInplaceOrView guard;
497
+ return autograd::make_variable(at::randint(high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
498
+ }
499
+ inline at::Tensor randint_symint(c10::SymInt high, c10::SymIntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = at::kLong) {
500
+ at::AutoDispatchBelowADInplaceOrView guard;
501
+ return autograd::make_variable(at::randint_symint(high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
502
+ }
503
+ inline at::Tensor randint(int64_t low, int64_t high, at::IntArrayRef size, at::TensorOptions options = at::kLong) {
504
+ at::AutoDispatchBelowADInplaceOrView guard;
505
+ return autograd::make_variable(at::randint(low, high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
506
+ }
507
+ inline at::Tensor randint_symint(c10::SymInt low, c10::SymInt high, c10::SymIntArrayRef size, at::TensorOptions options = at::kLong) {
508
+ at::AutoDispatchBelowADInplaceOrView guard;
509
+ return autograd::make_variable(at::randint_symint(low, high, size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
510
+ }
511
+ inline at::Tensor randint(int64_t low, int64_t high, at::IntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = at::kLong) {
512
+ at::AutoDispatchBelowADInplaceOrView guard;
513
+ return autograd::make_variable(at::randint(low, high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
514
+ }
515
+ inline at::Tensor randint_symint(c10::SymInt low, c10::SymInt high, c10::SymIntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = at::kLong) {
516
+ at::AutoDispatchBelowADInplaceOrView guard;
517
+ return autograd::make_variable(at::randint_symint(low, high, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
518
+ }
519
+ inline at::Tensor randint_like(const at::Tensor & self, int64_t high, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
520
+ at::AutoDispatchBelowADInplaceOrView guard;
521
+ return autograd::make_variable(at::randint_like(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
522
+ }
523
+ inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
524
+ at::AutoDispatchBelowADInplaceOrView guard;
525
+ return autograd::make_variable(at::randint_like_symint(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
526
+ }
527
+ inline at::Tensor randint_like(const at::Tensor & self, int64_t high, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
528
+ at::AutoDispatchBelowADInplaceOrView guard;
529
+ return autograd::make_variable(at::randint_like(self, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
530
+ }
531
+ inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt high, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
532
+ at::AutoDispatchBelowADInplaceOrView guard;
533
+ 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());
534
+ }
535
+ inline at::Tensor randint_like(const at::Tensor & self, const at::Tensor & high, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
536
+ at::AutoDispatchBelowADInplaceOrView guard;
537
+ return autograd::make_variable(at::randint_like(self, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
538
+ }
539
+ inline at::Tensor randint_like(const at::Tensor & self, const at::Tensor & high, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
540
+ at::AutoDispatchBelowADInplaceOrView guard;
541
+ return autograd::make_variable(at::randint_like(self, high, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
542
+ }
543
+ inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
544
+ at::AutoDispatchBelowADInplaceOrView guard;
545
+ return autograd::make_variable(at::randint_like(self, low, high, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
546
+ }
547
+ inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
548
+ at::AutoDispatchBelowADInplaceOrView guard;
549
+ 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());
550
+ }
551
+ inline at::Tensor randint_like(const at::Tensor & self, int64_t low, int64_t high, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
552
+ at::AutoDispatchBelowADInplaceOrView guard;
553
+ 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());
554
+ }
555
+ inline at::Tensor randint_like_symint(const at::Tensor & self, c10::SymInt low, c10::SymInt high, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
556
+ at::AutoDispatchBelowADInplaceOrView guard;
557
+ 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());
558
+ }
559
+ inline at::Tensor randn(at::IntArrayRef size, at::TensorOptions options = {}) {
560
+ at::AutoDispatchBelowADInplaceOrView guard;
561
+ return autograd::make_variable(at::randn(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
562
+ }
563
+ inline at::Tensor randn_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
564
+ at::AutoDispatchBelowADInplaceOrView guard;
565
+ return autograd::make_variable(at::randn_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
566
+ }
567
+ inline at::Tensor randn(at::IntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = {}) {
568
+ at::AutoDispatchBelowADInplaceOrView guard;
569
+ return autograd::make_variable(at::randn(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
570
+ }
571
+ inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional<at::Generator> generator, at::TensorOptions options = {}) {
572
+ at::AutoDispatchBelowADInplaceOrView guard;
573
+ return autograd::make_variable(at::randn_symint(size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
574
+ }
575
+ inline at::Tensor randn(at::IntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
576
+ at::AutoDispatchBelowADInplaceOrView guard;
577
+ return autograd::make_variable(at::randn(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
578
+ }
579
+ inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
580
+ at::AutoDispatchBelowADInplaceOrView guard;
581
+ return autograd::make_variable(at::randn_symint(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
582
+ }
583
+ inline at::Tensor randn(at::IntArrayRef size, ::std::optional<at::Generator> generator, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
584
+ at::AutoDispatchBelowADInplaceOrView guard;
585
+ return autograd::make_variable(at::randn(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
586
+ }
587
+ inline at::Tensor randn_symint(c10::SymIntArrayRef size, ::std::optional<at::Generator> generator, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
588
+ at::AutoDispatchBelowADInplaceOrView guard;
589
+ return autograd::make_variable(at::randn_symint(size, generator, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
590
+ }
591
+ inline at::Tensor randn_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
592
+ at::AutoDispatchBelowADInplaceOrView guard;
593
+ return autograd::make_variable(at::randn_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
594
+ }
595
+ inline at::Tensor randn_like(const at::Tensor & self, ::std::optional<at::Generator> generator, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
596
+ at::AutoDispatchBelowADInplaceOrView guard;
597
+ return autograd::make_variable(at::randn_like(self, generator, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
598
+ }
599
+ inline at::Tensor randperm(int64_t n, at::TensorOptions options = at::kLong) {
600
+ at::AutoDispatchBelowADInplaceOrView guard;
601
+ return autograd::make_variable(at::randperm(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
602
+ }
603
+ inline at::Tensor randperm_symint(c10::SymInt n, at::TensorOptions options = at::kLong) {
604
+ at::AutoDispatchBelowADInplaceOrView guard;
605
+ return autograd::make_variable(at::randperm_symint(n, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
606
+ }
607
+ inline at::Tensor randperm(int64_t n, ::std::optional<at::Generator> generator, at::TensorOptions options = at::kLong) {
608
+ at::AutoDispatchBelowADInplaceOrView guard;
609
+ return autograd::make_variable(at::randperm(n, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
610
+ }
611
+ inline at::Tensor randperm_symint(c10::SymInt n, ::std::optional<at::Generator> generator, at::TensorOptions options = at::kLong) {
612
+ at::AutoDispatchBelowADInplaceOrView guard;
613
+ return autograd::make_variable(at::randperm_symint(n, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
614
+ }
615
+ inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step = 1, at::TensorOptions options = {}) {
616
+ at::AutoDispatchBelowADInplaceOrView guard;
617
+ return autograd::make_variable(at::range(start, end, step, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
618
+ }
619
+ inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options = {}) {
620
+ at::AutoDispatchBelowADInplaceOrView guard;
621
+ return autograd::make_variable(at::range(start, end, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
622
+ }
623
+ inline at::Tensor zeros(at::IntArrayRef size, ::std::optional<at::DimnameList> names, at::TensorOptions options = {}) {
624
+ at::AutoDispatchBelowADInplaceOrView guard;
625
+ return autograd::make_variable(at::zeros(size, names, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
626
+ }
627
+ inline at::Tensor _efficientzerotensor(at::IntArrayRef size, at::TensorOptions options = {}) {
628
+ at::AutoDispatchBelowADInplaceOrView guard;
629
+ return autograd::make_variable(at::_efficientzerotensor(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
630
+ }
631
+ inline at::Tensor _efficientzerotensor_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
632
+ at::AutoDispatchBelowADInplaceOrView guard;
633
+ return autograd::make_variable(at::_efficientzerotensor_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
634
+ }
635
+ inline at::Tensor zeros(at::IntArrayRef size, at::TensorOptions options = {}) {
636
+ at::AutoDispatchBelowADInplaceOrView guard;
637
+ return autograd::make_variable(at::zeros(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
638
+ }
639
+ inline at::Tensor zeros_symint(c10::SymIntArrayRef size, at::TensorOptions options = {}) {
640
+ at::AutoDispatchBelowADInplaceOrView guard;
641
+ return autograd::make_variable(at::zeros_symint(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
642
+ }
643
+ inline at::Tensor zeros_like(const at::Tensor & self, at::TensorOptions options = {}, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
644
+ at::AutoDispatchBelowADInplaceOrView guard;
645
+ return autograd::make_variable(at::zeros_like(self, at::TensorOptions(options).requires_grad(::std::nullopt), memory_format), /*requires_grad=*/options.requires_grad());
646
+ }
647
+ 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) {
648
+ at::AutoDispatchBelowADInplaceOrView guard;
649
+ 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());
650
+ }
651
+ 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) {
652
+ at::AutoDispatchBelowADInplaceOrView guard;
653
+ 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());
654
+ }
655
+ 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) {
656
+ at::AutoDispatchBelowADInplaceOrView guard;
657
+ 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());
658
+ }
659
+ 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) {
660
+ at::AutoDispatchBelowADInplaceOrView guard;
661
+ 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());
662
+ }
663
+ 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) {
664
+ at::AutoDispatchBelowADInplaceOrView guard;
665
+ 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());
666
+ }
667
+ 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) {
668
+ at::AutoDispatchBelowADInplaceOrView guard;
669
+ 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());
670
+ }
671
+ 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) {
672
+ at::AutoDispatchBelowADInplaceOrView guard;
673
+ 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());
674
+ }
675
+ inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::TensorOptions options) {
676
+ at::AutoDispatchBelowADInplaceOrView guard;
677
+ 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());
678
+ }
679
+ inline at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options) {
680
+ at::AutoDispatchBelowADInplaceOrView guard;
681
+ 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());
682
+ }
683
+ inline at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options) {
684
+ at::AutoDispatchBelowADInplaceOrView guard;
685
+ 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());
686
+ }
687
+ inline at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options) {
688
+ at::AutoDispatchBelowADInplaceOrView guard;
689
+ 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());
690
+ }
691
+ inline at::Tensor sparse_bsc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options) {
692
+ at::AutoDispatchBelowADInplaceOrView guard;
693
+ 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());
694
+ }
695
+ 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 = {}) {
696
+ at::AutoDispatchBelowADInplaceOrView guard;
697
+ 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());
698
+ }
699
+ 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 = {}) {
700
+ at::AutoDispatchBelowADInplaceOrView guard;
701
+ 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());
702
+ }
703
+ 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 = {}) {
704
+ at::AutoDispatchBelowADInplaceOrView guard;
705
+ 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());
706
+ }
707
+ 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 = {}) {
708
+ at::AutoDispatchBelowADInplaceOrView guard;
709
+ 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());
710
+ }
711
+ 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 = {}) {
712
+ at::AutoDispatchBelowADInplaceOrView guard;
713
+ 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());
714
+ }
715
+ 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 = {}) {
716
+ at::AutoDispatchBelowADInplaceOrView guard;
717
+ 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());
718
+ }
719
+ inline at::Tensor sparse_coo_tensor(at::IntArrayRef size, at::TensorOptions options) {
720
+ at::AutoDispatchBelowADInplaceOrView guard;
721
+ return autograd::make_variable(at::sparse_coo_tensor(size, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
722
+ }
723
+ inline at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options = {}, ::std::optional<bool> is_coalesced = ::std::nullopt) {
724
+ at::AutoDispatchBelowADInplaceOrView guard;
725
+ return autograd::make_variable(at::sparse_coo_tensor(indices, values, at::TensorOptions(options).requires_grad(::std::nullopt), is_coalesced), /*requires_grad=*/options.requires_grad());
726
+ }
727
+ inline at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional<bool> is_coalesced = ::std::nullopt) {
728
+ at::AutoDispatchBelowADInplaceOrView guard;
729
+ 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());
730
+ }
731
+ inline at::Tensor _sparse_coo_tensor_unsafe(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options = {}, ::std::optional<bool> is_coalesced = ::std::nullopt) {
732
+ at::AutoDispatchBelowADInplaceOrView guard;
733
+ 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());
734
+ }
735
+ inline at::Tensor _sparse_coo_tensor_unsafe_symint(const at::Tensor & indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options = {}, ::std::optional<bool> is_coalesced = ::std::nullopt) {
736
+ at::AutoDispatchBelowADInplaceOrView guard;
737
+ 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());
738
+ }
739
+ inline at::Tensor _sparse_coo_tensor_with_dims(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, at::TensorOptions options) {
740
+ at::AutoDispatchBelowADInplaceOrView guard;
741
+ 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());
742
+ }
743
+ 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<bool> is_coalesced = ::std::nullopt) {
744
+ at::AutoDispatchBelowADInplaceOrView guard;
745
+ 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());
746
+ }
747
+ 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<bool> is_coalesced = ::std::nullopt) {
748
+ at::AutoDispatchBelowADInplaceOrView guard;
749
+ 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());
750
+ }
751
+ inline at::Tensor _to_copy(const at::Tensor & self, at::TensorOptions options = {}, bool non_blocking = false, ::std::optional<at::MemoryFormat> memory_format = ::std::nullopt) {
752
+ at::AutoDispatchBelowADInplaceOrView guard;
753
+ return autograd::make_variable(at::_to_copy(self, at::TensorOptions(options).requires_grad(::std::nullopt), non_blocking, memory_format), /*requires_grad=*/options.requires_grad());
754
+ }
755
+ inline at::Tensor tril_indices(int64_t row, int64_t col, int64_t offset = 0, at::TensorOptions options = at::kLong) {
756
+ at::AutoDispatchBelowADInplaceOrView guard;
757
+ return autograd::make_variable(at::tril_indices(row, col, offset, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
758
+ }
759
+ inline at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset = 0, at::TensorOptions options = at::kLong) {
760
+ at::AutoDispatchBelowADInplaceOrView guard;
761
+ return autograd::make_variable(at::triu_indices(row, col, offset, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
762
+ }
763
+ inline at::Tensor normal(double mean, double std, at::IntArrayRef size, ::std::optional<at::Generator> generator = ::std::nullopt, at::TensorOptions options = {}) {
764
+ at::AutoDispatchBelowADInplaceOrView guard;
765
+ return autograd::make_variable(at::normal(mean, std, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
766
+ }
767
+ inline at::Tensor normal_symint(double mean, double std, c10::SymIntArrayRef size, ::std::optional<at::Generator> generator = ::std::nullopt, at::TensorOptions options = {}) {
768
+ at::AutoDispatchBelowADInplaceOrView guard;
769
+ return autograd::make_variable(at::normal_symint(mean, std, size, generator, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
770
+ }
771
+ inline at::Tensor fft_fftfreq(int64_t n, double d = 1.0, at::TensorOptions options = {}) {
772
+ at::AutoDispatchBelowADInplaceOrView guard;
773
+ return autograd::make_variable(at::fft_fftfreq(n, d, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
774
+ }
775
+ inline at::Tensor fft_rfftfreq(int64_t n, double d = 1.0, at::TensorOptions options = {}) {
776
+ at::AutoDispatchBelowADInplaceOrView guard;
777
+ return autograd::make_variable(at::fft_rfftfreq(n, d, at::TensorOptions(options).requires_grad(::std::nullopt)), /*requires_grad=*/options.requires_grad());
778
+ }
779
+
780
+ } // namespace torch
781
+
782
+ #else
783
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
784
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/grad_mode.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/grad_mode.h>
5
+ #include <torch/csrc/Export.h>
6
+
7
+ namespace torch::autograd {
8
+
9
+ using GradMode = at::GradMode;
10
+ using AutoGradMode = at::AutoGradMode;
11
+
12
+ } // namespace torch::autograd
13
+
14
+ #else
15
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
16
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/graph_task.h ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/ThreadLocalState.h>
4
+ #include <ATen/core/Tensor.h>
5
+ #include <c10/util/ThreadLocal.h>
6
+ #include <torch/csrc/autograd/input_buffer.h>
7
+ #include <torch/csrc/autograd/utils/warnings.h>
8
+ #include <vector>
9
+
10
+ namespace torch::autograd {
11
+
12
+ using edge_list = std::vector<Edge>;
13
+ struct ReadyQueue;
14
+
15
+ static constexpr int NO_DEVICE = -2;
16
+ static constexpr int CPU_DEVICE = -1;
17
+
18
+ // GraphTask holds metadata needed for a single execution of backward()
19
+ struct GraphTask : std::enable_shared_from_this<GraphTask> {
20
+ std::atomic<uint64_t> outstanding_tasks_{0};
21
+ // Indicates if an error occurred while executing any task. When this is
22
+ // true, it signals all threads to stop executing.
23
+ std::atomic_bool has_error_{false};
24
+ std::atomic_bool future_completed_{false};
25
+ // It is safe to read keep_graph_ without synchronization
26
+ bool keep_graph_;
27
+
28
+ // To protect reads/writes to not_ready_, dependencies_, captured_vars_,
29
+ // has_error_, future_result_, cpu_ready_queue_, and leaf_streams.
30
+ std::mutex mutex_;
31
+ std::unordered_map<Node*, InputBuffer> not_ready_;
32
+ std::unordered_map<Node*, int> dependencies_;
33
+
34
+ // Records the nodes that are in the graph
35
+ std::unordered_set<Node*> nodes_in_graph_;
36
+ c10::SmallVector<Node*, 4> graph_roots_;
37
+ // Note [Exec info]
38
+ // Exec info is created for each GraphTask, which allows filtering paths on
39
+ // the graph that are not needed. It has a bit complicated semantics. If it's
40
+ // empty, it means the task is run in a "default" mode, which means that all
41
+ // next_edges we encounter should get executed. If it's not empty, only
42
+ // functions that have an entry and this entry has needed == True should be
43
+ // executed. exec_info is only empty when the graph is executed via
44
+ // .backward() and the inputs parameter is not passed. Otherwise, when
45
+ // executed through .grad(), or when inputs arg is specified for .backward(),
46
+ // exec_info will be non-empty.
47
+ //
48
+ struct ExecInfo {
49
+ struct Capture {
50
+ Capture(const Capture&) = delete;
51
+ Capture(Capture&&) = default;
52
+ Capture& operator=(const Capture&) = delete;
53
+ Capture& operator=(Capture&&) = default;
54
+ ~Capture() = default;
55
+
56
+ Capture(int input_idx, int output_idx)
57
+ : input_idx_(input_idx), output_idx_(output_idx) {}
58
+ int input_idx_; // within Node inputs
59
+ int output_idx_; // within the output vector of a GraphTask
60
+
61
+ // This hook will be executed after a grad is captured. The captured
62
+ // grad will be replaced by the return value of the hook.
63
+ struct GradCaptureHook {
64
+ virtual ~GradCaptureHook() = default;
65
+ virtual at::Tensor operator()(const at::Tensor& grad) = 0;
66
+ };
67
+ // NOTE [Deprecated capture hooks]
68
+ //
69
+ // The current status of capture hooks is that we continue to support
70
+ // the single usage of it by distributed in the dist_engine. If anyone
71
+ // else needs to use it for other purposes, they should file an issue.
72
+ //
73
+ // Capture hooks were originally created because there did not exist
74
+ // any way to register pre/post hooks to grad_fn in a way such that it
75
+ // would still be executed even if that is the grad_fn of a Tensor
76
+ // passed as input= of .grad. As far as I know, only dist_engine uses
77
+ // this hook.
78
+ //
79
+ // However, there are other alternatives today like tensor hooks that can
80
+ // replace the usage that originally motivated its creation. Also,
81
+ // Captures hooks are an outlier in terms of the types of hook that
82
+ // autograd offers in how it is registered and behaves, e.g. it is a hook
83
+ // registered not to the graph, but to a particular graph_task! This makes
84
+ // it a burden to maintain.
85
+ //
86
+ // It would be very nice to clean up/do a migration from pre/post
87
+ // hooks used in distributed to use tensor hooks, but for now we just
88
+ // mark this method as deprecated to prevent additional usage.
89
+ //
90
+ // If you still think you really need to capture hooks, please file an
91
+ // issue (and tag autograd).
92
+ const std::vector<std::unique_ptr<GradCaptureHook>>&
93
+ DO_NOT_USE_DEPRECATED_get_capture_hooks() const {
94
+ return hooks_;
95
+ }
96
+ // See NOTE [deprecated capture hooks]
97
+ void DO_NOT_USE_DEPRECATED_register_capture_hook(
98
+ std::unique_ptr<GradCaptureHook> hook) {
99
+ hooks_.push_back(std::move(hook));
100
+ }
101
+
102
+ private:
103
+ // The hooks will be called one by one in the order as they were added.
104
+ // The input grad of a hook will be the output of its preceding hook. The
105
+ // first hook will take the captured grad as the input. The output of the
106
+ // last hook will replace the captured grad.
107
+ std::vector<std::unique_ptr<GradCaptureHook>> hooks_;
108
+ };
109
+
110
+ bool should_execute() const {
111
+ return needed_ || captures_;
112
+ }
113
+
114
+ bool needed_ = false;
115
+ std::unique_ptr<std::vector<Capture>> captures_;
116
+ };
117
+ // exec_info_ is safe to read without synchronization
118
+ std::unordered_map<Node*, ExecInfo> exec_info_;
119
+ // Captures variables are grads captured that we return to the user. After
120
+ // execution of the GraphTask is completed, the captured_vars_ are moved
121
+ // out of the GraphTask and are no longer valid.
122
+ std::vector<Variable> captured_vars_;
123
+
124
+ // Note: this field is not ready to be used until the proper
125
+ // `thread_locals_.set_grad_mode()` call in the constructor.
126
+ at::ThreadLocalState thread_locals_;
127
+
128
+ std::unordered_set<c10::Stream> leaf_streams;
129
+
130
+ // Per-device current streams of the execute() that called this GraphTask.
131
+ // These will be synced with leaf_streams in exec_post_processing.
132
+ std::vector<std::optional<c10::Stream>> caller_current_streams_;
133
+
134
+ // Collects caller_current_streams_ for the accelerator device.
135
+ void stash_current_streams();
136
+
137
+ void init_to_execute(
138
+ Node& graph_root,
139
+ const edge_list& outputs,
140
+ bool accumulate_grad,
141
+ uint64_t min_topo_nr);
142
+
143
+ // The value of worker_device in the thread that created this task.
144
+ // See Note [Reentrant backwards]
145
+ // Safe to read owner_ and reentrant_depth_ without synchronization
146
+ int owner_;
147
+ // The number of parent graph tasks for this graph task
148
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
149
+ const int reentrant_depth_;
150
+
151
+ bool can_checkpoint() const {
152
+ return exec_info_.empty();
153
+ }
154
+
155
+ // check if the GraphTask is completed or not
156
+ bool completed();
157
+ // mark the graph task as completed and trigger post processing
158
+ void mark_as_completed_and_run_post_processing();
159
+
160
+ // Set an appropriate exception on this graph_task which was encountered while
161
+ // running the provided function.
162
+ void set_exception(std::exception_ptr eptr, const std::shared_ptr<Node>& fn);
163
+
164
+ // Set an appropriate exception on this graph_task which was encountered while
165
+ // running the provided function. But doesn't signal completion on
166
+ // 'future_result_' right away. The user needs to explicitly mark
167
+ // 'future_result_' completed with an appropriate exception.
168
+ void set_exception_without_signal(const std::shared_ptr<Node>& fn);
169
+
170
+ // Whether or not to stop execution for this GraphTask when an error is
171
+ // encountered. When set to true, this would cause Engine::execute() to throw
172
+ // an exception as soon as the autograd engine receives an exception.
173
+ bool exit_on_error_;
174
+
175
+ // CPU threads are dedicated to processing CPU work for the backward they
176
+ // invoked. So any given graph task maintains its own cpu_ready_queue_ where
177
+ // you should send work for it to be done. We memoize the cpu_ready_queue_ per
178
+ // GraphTask so that we know which ready queue we should push to if we are on
179
+ // device thread (i.e. GPU) and but next NodeTask should be run on CPU.
180
+ std::shared_ptr<ReadyQueue> cpu_ready_queue_;
181
+
182
+ // Future representing the completion of the graph task. Notified when all
183
+ // tasks are done.
184
+ c10::intrusive_ptr<at::ivalue::Future> future_result_;
185
+
186
+ // Final callbacks installed during execution of this GraphTask
187
+ std::vector<std::function<void()>> final_callbacks_;
188
+ // To protect reads and writes to final_callbacks_. Intentionally no reusing
189
+ // mutex_ as the two are protecting different data structures.
190
+ std::mutex final_callbacks_lock_;
191
+
192
+ utils::DelayWarningHandler warning_handler_;
193
+
194
+ uint64_t id_;
195
+
196
+ GraphTask(
197
+ bool keep_graph,
198
+ bool grad_mode,
199
+ int reentrant_depth,
200
+ std::shared_ptr<ReadyQueue> cpu_ready_queue,
201
+ c10::SmallVector<Node*, 4> graph_roots,
202
+ bool exit_on_error = false);
203
+
204
+ private:
205
+ // run GraphTask post processing
206
+ void exec_post_processing();
207
+ };
208
+
209
+ // The guard that sets and restores current_graph_task.
210
+ class GraphTaskGuard {
211
+ public:
212
+ explicit GraphTaskGuard(std::shared_ptr<GraphTask> graph_task);
213
+ ~GraphTaskGuard();
214
+
215
+ void restore_current_graph_task();
216
+
217
+ private:
218
+ std::shared_ptr<GraphTask> last_graph_task_;
219
+ };
220
+
221
+ TORCH_API const std::unordered_map<Node*, GraphTask::ExecInfo>*
222
+ get_current_graph_task_exec_info();
223
+ TORCH_API const std::unordered_set<Node*>*
224
+ get_current_graph_task_nodes_in_graph();
225
+ TORCH_API bool get_current_graph_task_keep_graph();
226
+ TORCH_API std::vector<Node*> get_current_graph_task_execution_order();
227
+ TORCH_API int get_current_graph_task_id();
228
+ void add_node_to_current_graph_task_exec_info(Node* fn);
229
+
230
+ } // namespace torch::autograd
231
+
232
+ #else
233
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
234
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_buffer.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // The InputBuffer class accumulates a list of Variables for use by a
5
+ // function. It implements logic to avoid modifying the passed
6
+ // values in-place (adding an input twice will accumulate the result).
7
+ // This behaviour is needed and used only in backward graphs.
8
+
9
+ #include <utility>
10
+ #include <vector>
11
+
12
+ #include <c10/core/Stream.h>
13
+ #include <torch/csrc/autograd/variable.h>
14
+ #include <optional>
15
+
16
+ namespace torch::autograd {
17
+
18
+ struct InputBuffer {
19
+ explicit InputBuffer(size_t size)
20
+ : buffer(size),
21
+ opt_accum_streams(size),
22
+ ready_events(size),
23
+ ready_streams(size) {}
24
+ InputBuffer(const InputBuffer& other) = delete;
25
+ InputBuffer(InputBuffer&& other) = default;
26
+ explicit InputBuffer(variable_list&& inputs) : buffer(std::move(inputs)) {}
27
+ InputBuffer& operator=(InputBuffer&& other) = default;
28
+
29
+ // Accumulates the variable at a specified index.
30
+ // The optional CUDA streams determine which stream the accumulation
31
+ // is run on and how the addition is synchronized.
32
+ TORCH_API void add(
33
+ size_t pos,
34
+ Variable&& var,
35
+ const std::optional<c10::Stream>& opt_producer_stream,
36
+ const std::optional<c10::Stream>& opt_consumer_stream,
37
+ Node* fn);
38
+
39
+ Variable operator[](size_t pos) {
40
+ return buffer[pos];
41
+ }
42
+
43
+ // Returns the inputs as a list of variables. Destroys given InputBuffer.
44
+ static std::vector<Variable> variables(InputBuffer&& g);
45
+
46
+ std::vector<Variable> buffer;
47
+ // The stream used for accumulation when a variable is used multiple times.
48
+ std::vector<std::optional<c10::Stream>> opt_accum_streams;
49
+ // The events you need to wait for to ensure the corresponding buffers
50
+ // are ready. The events are updated as we accumulate into the buffer.
51
+ std::vector<std::optional<c10::Event>> ready_events;
52
+ // The streams corresponding to the events above. This is only used to
53
+ // check if more synchronization is needed or not.
54
+ std::vector<std::optional<c10::Stream>> ready_streams;
55
+ };
56
+
57
+ } // namespace torch::autograd
58
+
59
+ #else
60
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
61
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/input_metadata.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ExpandUtils.h>
5
+ #include <ATen/NestedTensorImpl.h>
6
+ #include <ATen/core/Tensor.h>
7
+ #include <c10/core/Device.h>
8
+ #include <c10/core/DeviceType.h>
9
+ #include <c10/core/Stream.h>
10
+ #include <c10/core/SymIntArrayRef.h>
11
+ #include <c10/core/TensorImpl.h>
12
+ #include <c10/core/impl/DeviceGuardImplInterface.h>
13
+ #include <c10/util/DimVector.h>
14
+ #include <c10/util/Exception.h>
15
+ #include <c10/util/SmallVector.h>
16
+
17
+ #ifndef AT_PER_OPERATOR_HEADERS
18
+ #include <ATen/Functions.h>
19
+ #else
20
+ #include <ATen/ops/zeros.h>
21
+ #endif
22
+
23
+ namespace torch::autograd {
24
+
25
+ using SymIntSmallVec = c10::SmallVector<c10::SymInt, c10::kDimVectorStaticSize>;
26
+ using MetadataShape = std::variant<SymIntSmallVec, at::Tensor>;
27
+
28
+ /**
29
+ * Records TensorOptions, shape of the tensor, whether or not the Python
30
+ * dispatch key is set (tensor subclass), and, where applicable, the stream the
31
+ * corresponding operation took place on.
32
+ *
33
+ * If is_valid() is false, then the corresponding input is not used and may be
34
+ * an undefined tensor.
35
+ */
36
+ struct TORCH_API InputMetadata {
37
+ InputMetadata() = default;
38
+ InputMetadata(
39
+ const at::TensorOptions& options,
40
+ MetadataShape input_shape,
41
+ bool is_tensor_subclass,
42
+ bool is_nested,
43
+ std::optional<at::ScalarType> grad_dtype);
44
+ InputMetadata(const at::Tensor& t);
45
+
46
+ const at::TensorOptions& options() const {
47
+ return options_;
48
+ }
49
+
50
+ caffe2::TypeMeta dtype() const {
51
+ return options_.dtype();
52
+ }
53
+
54
+ at::Device device() const {
55
+ return options_.device();
56
+ }
57
+
58
+ at::Layout layout() const {
59
+ return options_.layout();
60
+ }
61
+
62
+ c10::Stream stream() const {
63
+ return stream_;
64
+ }
65
+
66
+ bool is_tensor_subclass() const {
67
+ return is_tensor_subclass_;
68
+ }
69
+
70
+ at::Tensor zeros_like() const;
71
+
72
+ bool is_same_shape(const at::Tensor& grad) const;
73
+
74
+ bool is_expandable_to_shape(const at::Tensor& grad) const;
75
+
76
+ at::Tensor reduce_grad(at::Tensor& grad) const;
77
+
78
+ at::Tensor maybe_reduce(
79
+ const size_t index,
80
+ at::Tensor grad,
81
+ const std::function<std::string(const std::string&)>& format_error) const;
82
+
83
+ std::stringstream incompatible_shape_error_message(
84
+ const size_t index,
85
+ const at::Tensor& grad) const;
86
+
87
+ bool was_default_constructed() const {
88
+ return was_default_constructed_;
89
+ }
90
+
91
+ bool is_cpp_nested_tensor() const;
92
+
93
+ bool is_nested_tensor() const {
94
+ return is_nested_;
95
+ }
96
+
97
+ c10::SymIntArrayRef shape_as_dim_vector() const;
98
+
99
+ // Danger: not thread safe, caller must protect with lock
100
+ SymIntSmallVec& mutable_shape_as_dim_vector();
101
+
102
+ std::optional<at::ScalarType> grad_dtype() const {
103
+ TORCH_INTERNAL_ASSERT(!was_default_constructed_);
104
+ return grad_dtype_;
105
+ }
106
+
107
+ void set_grad_dtype(const std::optional<at::ScalarType>& grad_dtype) {
108
+ TORCH_INTERNAL_ASSERT(!was_default_constructed_);
109
+ grad_dtype_ = grad_dtype;
110
+ }
111
+
112
+ private:
113
+ at::Tensor shape_as_tensor() const;
114
+ bool is_nestedness_same(const at::Tensor& grad) const;
115
+ bool maybe_expandable_to(const at::Tensor& grad) const;
116
+
117
+ // NB: The engine does not use the dtype from the options, but rather the
118
+ // grad_dtype_ field to validate grad_output dtype.
119
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
120
+ const at::TensorOptions options_;
121
+ MetadataShape shape_;
122
+ c10::Stream stream_ = c10::Stream(c10::Stream::Default::DEFAULT, device());
123
+ bool is_tensor_subclass_ = false;
124
+ bool is_nested_ = false;
125
+ bool was_default_constructed_ = true;
126
+
127
+ // The grad_dtype_ field is the dtype that the engine expects the grad to be.
128
+ // When nullopt, grad_dtype_ is allowed to be any dtype.
129
+ // This field is mutated if THPVariable_set_grad_dtype is called
130
+ // and the AccumulateGrad has already been created.
131
+ std::optional<at::ScalarType> grad_dtype_;
132
+ };
133
+ } // namespace torch::autograd
134
+
135
+ #else
136
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
137
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/jit_decomp_interface.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/core/function_schema.h>
6
+ #include <c10/macros/Export.h>
7
+
8
+ // NOTE: [Jit Decomposition Interface]
9
+ //
10
+ // For some context of why we need this at all, see NOTE: [forward-mode AD
11
+ // decompositions mechanism]
12
+ //
13
+ // Introducing that mechanism from the NOTE is problematic because:
14
+ // - it relies on TorchScript, so now VariableTypeX.cpp depends on TorchScript.
15
+ // - there exist internal builds like lite_trainer, which depend on VariableType
16
+ // but do not depend on TorchScript.
17
+ //
18
+ // For internal builds like lite_trainer builds to pass, and for OSS builds that
19
+ // do depend on TorchScript to still support the forward AD decomp mechanism, we
20
+ // implement a PImpl pattern to avoid a static dependency in favor of a dynamic
21
+ // one
22
+ // - during static initialization time, if the library is built with TorchScript
23
+ // setJitDecompImpl is called in decomposition_registry.cpp setting a global
24
+ // ptr to the impl
25
+ // - when the program is run,if getJitDecompImpl returns a non null ptr, we can
26
+ // carry on normally, otherwise we gracefully error out
27
+ //
28
+ // For extra context, see VariableHooksInterface.h, where a similar technique
29
+ // is used
30
+
31
+ namespace torch::autograd::impl {
32
+
33
+ struct TORCH_API JitDecompInterface {
34
+ virtual ~JitDecompInterface() = default;
35
+ virtual bool has_jit_decomposition(
36
+ const c10::FunctionSchema& schema) const = 0;
37
+ virtual void run_jit_decomposition(
38
+ const c10::OperatorHandle& op,
39
+ jit::Stack* stack) const = 0;
40
+ };
41
+
42
+ TORCH_API void setJitDecompImpl(JitDecompInterface* impl);
43
+ TORCH_API JitDecompInterface* getJitDecompImpl();
44
+
45
+ struct TORCH_API JitDecompRegisterer{explicit JitDecompRegisterer(
46
+ JitDecompInterface * impl){setJitDecompImpl(impl);
47
+ } // namespace torch::autograd::impl
48
+ }
49
+ ;
50
+
51
+ } // namespace torch::autograd::impl
52
+
53
+ #else
54
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
55
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/autograd/profiler_kineto.h>
5
+ #include <torch/csrc/autograd/profiler_legacy.h>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_kineto.h ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+ #include <vector>
6
+
7
+ #include <torch/csrc/profiler/api.h>
8
+ #include <torch/csrc/profiler/events.h>
9
+ #include <torch/csrc/profiler/stubs/base.h>
10
+ #include <torch/csrc/profiler/util.h>
11
+
12
+ namespace torch {
13
+
14
+ namespace profiler::impl {
15
+ struct Result;
16
+ namespace kineto {
17
+ struct ActivityTraceWrapper;
18
+ } // namespace kineto
19
+ } // namespace profiler::impl
20
+
21
+ namespace autograd::profiler {
22
+ using experimental_event_t = std::shared_ptr<torch::profiler::impl::Result>;
23
+ using extra_meta_t = std::unordered_map<std::string, std::string>;
24
+
25
+ struct TORCH_API KinetoEvent {
26
+ KinetoEvent(
27
+ const std::shared_ptr<const torch::profiler::impl::Result>& /*result*/,
28
+ const bool verbose);
29
+
30
+ uint64_t startThreadId() const;
31
+ uint64_t endThreadId() const;
32
+ uint8_t activityType() const;
33
+ uint64_t fwdThreadId() const;
34
+ bool hasShapes() const;
35
+ const c10::ArrayRef<std::vector<int64_t>> shapes() const;
36
+ bool hasTypes() const;
37
+ const c10::ArrayRef<std::string> dtypes() const;
38
+ bool hasConcreteInputs() const;
39
+ const c10::ArrayRef<c10::IValue> concreteInputs() const;
40
+ bool hasKwinputs() const;
41
+ bool isHiddenEvent() const;
42
+ const std::unordered_map<std::string, c10::IValue> kwinputs() const;
43
+ uint64_t flops() const;
44
+ int64_t sequenceNr() const;
45
+ bool hasStack() const;
46
+ const c10::ArrayRef<std::string> stack() const;
47
+ uint8_t scope() const;
48
+ bool hasModuleHierarchy() const;
49
+ const c10::ArrayRef<std::string> moduleHierarchy() const;
50
+ int64_t debugHandle() const;
51
+ std::string name() const;
52
+ std::string overload_name() const;
53
+ c10::DeviceType deviceType() const;
54
+ int deviceIndex() const;
55
+ int64_t nBytes() const;
56
+ uint64_t startNs() const;
57
+ uint64_t endNs() const;
58
+ uint64_t durationNs() const;
59
+ bool isAsync() const;
60
+ uint64_t correlationId() const;
61
+ uint64_t linkedCorrelationId() const;
62
+ int64_t deviceResourceId() const;
63
+ std::string backend() const;
64
+ bool isPythonFunction() const;
65
+ int64_t cudaElapsedUs() const;
66
+ int64_t privateuse1ElapsedUs() const;
67
+ void getPerfEventCounters(torch::profiler::perf_counters_t& /*in*/) const;
68
+ extra_meta_t extraMeta() const;
69
+ std::string metadataJson() const;
70
+
71
+ private:
72
+ torch::profiler::impl::ProfilerVoidEventStub fallbackStart() const;
73
+ torch::profiler::impl::ProfilerVoidEventStub fallbackEnd() const;
74
+
75
+ std::shared_ptr<const torch::profiler::impl::Result> result_;
76
+ std::vector<std::string> python_stack_;
77
+
78
+ // Copy fields from result so we can return ArrayRefs.
79
+ std::vector<std::vector<int64_t>> shapes_;
80
+ std::vector<std::string> dtypes_;
81
+ std::vector<c10::IValue> concrete_inputs_;
82
+ std::unordered_map<std::string, c10::IValue> kwinputs_;
83
+ };
84
+
85
+ // Consolidating events returned directly from Kineto
86
+ // with events manually created by us (e.g. start/stop marks,
87
+ // memory allocation events)
88
+ struct TORCH_API ProfilerResult {
89
+ ProfilerResult();
90
+ ProfilerResult(
91
+ uint64_t start_time,
92
+ std::vector<KinetoEvent> events,
93
+ std::unique_ptr<torch::profiler::impl::kineto::ActivityTraceWrapper>&&
94
+ trace,
95
+ std::vector<experimental_event_t>&& event_tree);
96
+ ~ProfilerResult();
97
+
98
+ uint64_t trace_start_ns() const {
99
+ return trace_start_ns_;
100
+ }
101
+
102
+ const std::vector<KinetoEvent>& events() const {
103
+ return events_;
104
+ }
105
+
106
+ const std::vector<experimental_event_t>& event_tree() const {
107
+ return event_tree_;
108
+ }
109
+
110
+ void save(const std::string& path);
111
+
112
+ private:
113
+ uint64_t trace_start_ns_ = 0;
114
+ std::vector<KinetoEvent> events_;
115
+ std::unique_ptr<torch::profiler::impl::kineto::ActivityTraceWrapper> trace_;
116
+ std::vector<experimental_event_t> event_tree_;
117
+ };
118
+
119
+ /*
120
+ * This API is used by backends to record latency of events that
121
+ * happened in the backend but were not visible to pytorch runtime.
122
+ * For example, if part of the model is lowered to a dsp backend, then
123
+ * the execution of that part of the model is delegated to the backend.
124
+ * When backend finishes execution it has an option to provide profiling
125
+ * information (latency only at the moment) corresponding to different operators
126
+ * that were executed in the backend.
127
+ * When such events are recorded by backend using this API, the event
128
+ * records will be collected by active kineto profiler. If no kineto profiler
129
+ * is active then the event is ignored.
130
+ * This provides us with a way to generate all the profiling information
131
+ * for a model regardless of where model (or part of it) executed.
132
+ * @param start_time_us: start time in us of the event
133
+ * @param end_time_us: end time in us of the event
134
+ * @param debug_handle: debug handle to correlate this event/op with
135
+ * model level module/source information
136
+ * @param scope: scope of the event, e.g. LITE_INTERPRETER, RECORD_FN etc.
137
+ * @param event_name: name of the event, e.g. op name
138
+ * @param backend_name: name of the backend where the event took place.
139
+ */
140
+ TORCH_API void reportBackendEventToActiveKinetoProfiler(
141
+ const int64_t start_time_us,
142
+ const int64_t end_time_us,
143
+ const int64_t debug_handle,
144
+ const at::RecordScope scope,
145
+ const std::string& event_name,
146
+ const std::string& backend_name);
147
+
148
+ TORCH_API void enableProfiler(
149
+ const torch::profiler::impl::ProfilerConfig& config,
150
+ const std::set<torch::profiler::impl::ActivityType>& activities,
151
+ const std::unordered_set<at::RecordScope>& scopes = {});
152
+
153
+ /*
154
+ * Same as enableProfiler but with callback to do post-processing of
155
+ * KinetoEvents.
156
+ * enableProfilerWithEventPostProcess enables profiler to capture
157
+ * specified activities, with specified RecordFunction scope, if any.
158
+ * Additionally, it takes a functor that does in-place post processing of
159
+ * events, e.g. populate stack trace or module hierarchy information lazily
160
+ * using debug_handle.
161
+ * Example usage is with lite interpreter that has recording scope of
162
+ * LITE_INTERPRETER. In this case lite interpreter runtime, records debug
163
+ * handles in RecordFunction, along with other information. Debug handles are
164
+ * eventually passed down to KinetoEvent and recorded as part of the event.
165
+ * KinetoEdgeCPUProfiler, in torch/csrc/jit/mobile/profiler_edge.cpp, enables
166
+ * profiler using post-processing callback, via
167
+ * enableProfilerWithEventPostProcess, that takes these debug handles and
168
+ * generates stack trace and module hierarchy information, once profiling is
169
+ * done.
170
+ */
171
+ using post_process_t = std::function<void(
172
+ /*debug_handle */ int64_t,
173
+ /*jit_stack */ std::vector<std::string>&,
174
+ /*jit_modules */ std::vector<std::string>&)>;
175
+ TORCH_API void enableProfilerWithEventPostProcess(
176
+ const torch::profiler::impl::ProfilerConfig& config,
177
+ const std::set<torch::profiler::impl::ActivityType>& activities,
178
+ post_process_t&& cb,
179
+ const std::unordered_set<at::RecordScope>& scopes = {});
180
+
181
+ TORCH_API std::unique_ptr<ProfilerResult> disableProfiler();
182
+
183
+ TORCH_API void prepareProfiler(
184
+ const torch::profiler::impl::ProfilerConfig& config,
185
+ const std::set<torch::profiler::impl::ActivityType>& activities);
186
+
187
+ TORCH_API void toggleCollectionDynamic(
188
+ const bool enable,
189
+ const std::set<torch::profiler::impl::ActivityType>& activities);
190
+
191
+ TORCH_API void startMemoryProfile();
192
+ TORCH_API void stopMemoryProfile();
193
+ TORCH_API void exportMemoryProfile(const std::string& path);
194
+
195
+ /**
196
+ * When a C++ thread really has no control over how the profiler was enabled,
197
+ * for example, by some unreachable Python code, it can call these functions
198
+ * to test/join/unjoin itself into the collection set of a profiler, if any.
199
+ * Without calling these functions, the symptom may be "not seeing GPU events
200
+ * from some child C++ threads". This is an example on how to use them,
201
+ *
202
+ * using namespace torch::autograd::profiler;
203
+ * bool enabled = isProfilerEnabledInMainThread();
204
+ * if (enabled != saved_enabled_state) {
205
+ * if (enabled) {
206
+ * enableProfilerInChildThread();
207
+ * } else {
208
+ * disableProfilerInChildThread();
209
+ * }
210
+ * saved_enabled_state = enabled;
211
+ * }
212
+ */
213
+ TORCH_API bool isProfilerEnabledInMainThread();
214
+ TORCH_API void enableProfilerInChildThread();
215
+ TORCH_API void disableProfilerInChildThread();
216
+
217
+ } // namespace autograd::profiler
218
+
219
+ namespace profiler::impl {
220
+
221
+ // Experimental.
222
+ TORCH_API void _reportVulkanEventToProfiler(vulkan_id_t id);
223
+
224
+ } // namespace profiler::impl
225
+
226
+ } // namespace torch
227
+
228
+ #else
229
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
230
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_legacy.h ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cstdint>
5
+ #include <iostream>
6
+ #include <memory>
7
+ #include <mutex>
8
+ #include <string>
9
+ #include <vector>
10
+
11
+ #include <torch/csrc/Export.h>
12
+ #include <torch/csrc/profiler/api.h>
13
+ #include <torch/csrc/profiler/stubs/base.h>
14
+ #include <torch/csrc/profiler/util.h>
15
+
16
+ namespace torch::autograd::profiler {
17
+
18
+ enum class C10_API_ENUM EventKind : uint16_t {
19
+ Mark,
20
+ PushRange,
21
+ PopRange,
22
+ MemoryAlloc,
23
+ };
24
+
25
+ // To be deprecated, once we switch to Kineto profiling
26
+ struct TORCH_API LegacyEvent {
27
+ LegacyEvent(
28
+ EventKind kind,
29
+ at::StringView name,
30
+ uint16_t thread_id,
31
+ bool record_cuda,
32
+ at::RecordFunctionHandle handle = 0,
33
+ std::vector<std::vector<int64_t>>&& shapes = {},
34
+ int64_t node_id = -1,
35
+ bool is_async = false)
36
+ : name_(std::move(name)),
37
+ kind_(kind),
38
+ thread_id_(thread_id),
39
+ handle_(handle),
40
+ shapes_(std::move(shapes)),
41
+ node_id_(node_id),
42
+ is_async_(is_async) {
43
+ record(record_cuda);
44
+ }
45
+
46
+ // Constructor to be used in conjunction with LegacyEvent::fromIValue.
47
+ LegacyEvent(
48
+ EventKind kind,
49
+ at::StringView name,
50
+ uint16_t thread_id,
51
+ at::RecordFunctionHandle handle,
52
+ std::vector<std::vector<int64_t>>&& shapes,
53
+ int64_t node_id,
54
+ bool is_remote,
55
+ int64_t cpu_memory_usage,
56
+ int64_t cpu_ns,
57
+ bool cuda_recorded,
58
+ int64_t cuda_memory_usage = 0,
59
+ c10::DeviceIndex device = -1,
60
+ double cuda_us = -1)
61
+ : cpu_ns_(cpu_ns),
62
+ name_(std::move(name)),
63
+ kind_(kind),
64
+ thread_id_(thread_id),
65
+ handle_(handle),
66
+ shapes_(std::move(shapes)),
67
+ cpu_memory_usage_(cpu_memory_usage),
68
+ cuda_memory_usage_(cuda_memory_usage),
69
+ device_(device),
70
+ node_id_(node_id),
71
+ is_remote_(is_remote),
72
+ cuda_us_(static_cast<int64_t>(cuda_us)) {
73
+ // Sanity check values that were deserialized
74
+ TORCH_INTERNAL_ASSERT(cpu_ns_ > 0);
75
+ if (cuda_recorded) {
76
+ TORCH_INTERNAL_ASSERT(device_ >= 0);
77
+ TORCH_INTERNAL_ASSERT(cuda_us_ >= 0);
78
+ }
79
+ }
80
+
81
+ // Returns IValues corresponding to event structure, to be used for
82
+ // serialization.
83
+ at::IValue toIValue() const;
84
+
85
+ // Reconstructs an event from IValues given by toIValue.
86
+ static LegacyEvent fromIValue(const at::IValue& eventIValue);
87
+
88
+ void record(bool record_cuda);
89
+
90
+ std::string kindStr() const {
91
+ switch (kind_) {
92
+ case EventKind::Mark:
93
+ return "mark";
94
+ case EventKind::PushRange:
95
+ return "push";
96
+ case EventKind::PopRange:
97
+ return "pop";
98
+ case EventKind::MemoryAlloc:
99
+ return "memory_alloc";
100
+ default:
101
+ TORCH_CHECK(false, "unknown event kind");
102
+ }
103
+ }
104
+
105
+ EventKind kind() const {
106
+ return kind_;
107
+ }
108
+
109
+ const char* name() const {
110
+ return name_.str();
111
+ }
112
+
113
+ uint64_t threadId() const {
114
+ return thread_id_;
115
+ }
116
+
117
+ std::vector<std::vector<int64_t>> shapes() const {
118
+ return shapes_;
119
+ }
120
+
121
+ double cpuElapsedUs(const LegacyEvent& e) const {
122
+ return static_cast<double>(e.cpu_ns_ - cpu_ns_) / 1000.0;
123
+ }
124
+
125
+ void setCpuUs(int64_t cpu_us) {
126
+ cpu_ns_ = cpu_us * 1000;
127
+ }
128
+
129
+ double cpuUs() const {
130
+ return static_cast<double>(cpu_ns_) / 1000.0;
131
+ }
132
+
133
+ double cudaElapsedUs(const LegacyEvent& e) const;
134
+
135
+ bool hasCuda() const {
136
+ return cuda_event != nullptr || (isRemote() && device_ != -1);
137
+ }
138
+
139
+ c10::DeviceIndex device() const {
140
+ return device_;
141
+ }
142
+
143
+ void updateMemoryStats(int64_t alloc_size, c10::Device device) {
144
+ if (device.is_cuda() || device.type() == c10::DeviceType::HIP) {
145
+ cuda_memory_usage_ = alloc_size;
146
+ } else if (
147
+ device.is_cpu() || device.type() == c10::DeviceType::MKLDNN ||
148
+ device.type() == c10::DeviceType::IDEEP) {
149
+ cpu_memory_usage_ = alloc_size;
150
+ } else {
151
+ LOG(WARNING) << "Unsupported memory profiling device: " << device;
152
+ }
153
+ }
154
+
155
+ int64_t cpuMemoryUsage() const {
156
+ return cpu_memory_usage_;
157
+ }
158
+
159
+ int64_t cudaMemoryUsage() const {
160
+ return cuda_memory_usage_;
161
+ }
162
+
163
+ at::RecordFunctionHandle handle() const {
164
+ return handle_;
165
+ }
166
+
167
+ // Node ID corresponding to this event.
168
+ int64_t nodeId() const {
169
+ return node_id_;
170
+ }
171
+
172
+ // Set Node ID on this event.
173
+ void setNodeId(int64_t node_id) {
174
+ node_id_ = node_id;
175
+ }
176
+
177
+ void setName(at::StringView newName_) {
178
+ name_ = std::move(newName_);
179
+ }
180
+
181
+ bool isRemote() const {
182
+ return is_remote_;
183
+ }
184
+
185
+ void setCudaUs(int64_t cuda_us) {
186
+ cuda_us_ = cuda_us;
187
+ }
188
+
189
+ void setSequenceNr(int64_t sequence_nr) {
190
+ sequence_nr_ = sequence_nr;
191
+ }
192
+
193
+ int64_t sequenceNr() const {
194
+ return sequence_nr_;
195
+ }
196
+
197
+ void setCorrelationId(uint64_t correlation_id) {
198
+ correlation_id_ = correlation_id;
199
+ }
200
+
201
+ uint64_t correlationId() const {
202
+ return correlation_id_;
203
+ }
204
+
205
+ const std::vector<std::string>& stack() const {
206
+ return stack_;
207
+ }
208
+
209
+ void setStack(const std::vector<std::string>& stack) {
210
+ stack_ = stack;
211
+ }
212
+
213
+ uint64_t fwdThreadId() const {
214
+ return fwd_thread_id_;
215
+ }
216
+
217
+ void setFwdThreadId(uint64_t fwd_thread_id) {
218
+ fwd_thread_id_ = fwd_thread_id;
219
+ }
220
+
221
+ uint8_t scope() const {
222
+ return scope_;
223
+ }
224
+
225
+ void setScope(uint8_t scope) {
226
+ scope_ = scope;
227
+ }
228
+
229
+ const std::unordered_map<std::string, c10::IValue>& extraArgs() const {
230
+ return extra_args_;
231
+ }
232
+
233
+ void setExtraArgs(std::unordered_map<std::string, c10::IValue>&& save_args) {
234
+ extra_args_ = std::move(save_args);
235
+ }
236
+
237
+ uint64_t flops() {
238
+ return flops_;
239
+ }
240
+
241
+ bool isAsync() {
242
+ return is_async_;
243
+ }
244
+
245
+ void setFlops(uint64_t flops) {
246
+ flops_ = flops;
247
+ }
248
+
249
+ private:
250
+ // signed to allow for negative intervals, initialized for safety.
251
+ int64_t cpu_ns_ = 0;
252
+ at::StringView name_;
253
+ EventKind kind_;
254
+ uint64_t thread_id_;
255
+ uint64_t fwd_thread_id_{0};
256
+ at::RecordFunctionHandle handle_{0};
257
+ std::vector<std::vector<int64_t>> shapes_;
258
+ int64_t cpu_memory_usage_ = 0;
259
+ int64_t cuda_memory_usage_ = 0;
260
+ c10::DeviceIndex device_ = -1;
261
+ torch::profiler::impl::ProfilerVoidEventStub cuda_event = nullptr;
262
+ int64_t node_id_ = 0;
263
+ bool is_remote_ = false;
264
+ int64_t cuda_us_ = -1;
265
+ int64_t sequence_nr_ = -1;
266
+ bool is_async_ = false;
267
+
268
+ std::vector<std::string> stack_;
269
+ uint8_t scope_{0};
270
+ uint64_t correlation_id_{0};
271
+ // Extra arguments for computing op flops
272
+ std::unordered_map<std::string, c10::IValue> extra_args_;
273
+ uint64_t flops_ = 0;
274
+ };
275
+
276
+ // a linked-list of fixed sized vectors, to avoid
277
+ // a std::vector resize from taking a large amount of time inside
278
+ // a profiling event
279
+ struct RangeEventList {
280
+ RangeEventList() {
281
+ events_.reserve(kReservedCapacity);
282
+ }
283
+
284
+ template <typename... Args>
285
+ void record(Args&&... args) {
286
+ std::lock_guard<std::mutex> guard(mutex_);
287
+ events_.emplace_back(std::forward<Args>(args)...);
288
+ }
289
+
290
+ std::vector<LegacyEvent> consolidate() {
291
+ std::lock_guard<std::mutex> lock(mutex_);
292
+ std::vector<LegacyEvent> result;
293
+ result.insert(
294
+ result.begin(),
295
+ std::make_move_iterator(events_.begin()),
296
+ std::make_move_iterator(events_.end()));
297
+ events_.erase(events_.begin(), events_.end());
298
+ return result;
299
+ }
300
+
301
+ size_t size() {
302
+ std::lock_guard<std::mutex> lock(mutex_);
303
+ return events_.size();
304
+ }
305
+
306
+ private:
307
+ // This mutex is used to serialize access when different threads are writing
308
+ // to the same instance of RangeEventList.
309
+ std::mutex mutex_;
310
+ std::vector<LegacyEvent> events_;
311
+
312
+ static const size_t kReservedCapacity = 1024;
313
+ };
314
+
315
+ // A struct to control settings of disableProfiler options.
316
+ struct TORCH_API ProfilerDisableOptions {
317
+ ProfilerDisableOptions() = default;
318
+ ProfilerDisableOptions(bool shouldCleanupTLSState, bool shouldConsolidate)
319
+ : cleanupTLSState(shouldCleanupTLSState),
320
+ consolidate(shouldConsolidate) {}
321
+ // Whether we should clean up profiler states that are thread local, such as
322
+ // ThreadLocalDebugInfo and thread local RecordFunction callbacks.
323
+ bool cleanupTLSState = true;
324
+ // Whether we should consolidate all currently recorded profiled events. If
325
+ // false, will not consolidate and other threads can continue to write to the
326
+ // event lists.
327
+ bool consolidate = true;
328
+ };
329
+
330
+ // NOTE: profiler mode is thread local, with automatic propagation
331
+ // across thread boundary (e.g. at::launch tasks)
332
+ TORCH_API void enableProfilerLegacy(
333
+ const torch::profiler::impl::ProfilerConfig& /*new_config*/);
334
+ using thread_event_lists = std::vector<std::vector<LegacyEvent>>;
335
+ TORCH_API thread_event_lists disableProfilerLegacy(
336
+ std::optional<ProfilerDisableOptions> profilerDisableOptions =
337
+ std::nullopt);
338
+
339
+ // adds profiledEvents to the current thread local recorded events. Each event
340
+ // will be marked with node ID given by fromNodeId.
341
+ TORCH_API void addEventList(std::vector<LegacyEvent>&& profiledEvents);
342
+ // Writes profiled events to a stream.
343
+ TORCH_API void writeProfilerEventsToStream(
344
+ std::ostream& out,
345
+ const std::vector<LegacyEvent*>& events);
346
+
347
+ // Usage:
348
+ // {
349
+ // RecordProfile guard("filename.trace");
350
+ // // code you want to profile
351
+ // }
352
+ // Then open filename.trace in chrome://tracing
353
+ struct TORCH_API RecordProfile {
354
+ RecordProfile(std::ostream& out);
355
+ RecordProfile(const std::string& filename);
356
+
357
+ ~RecordProfile();
358
+
359
+ private:
360
+ void init();
361
+ std::unique_ptr<std::ofstream> file_;
362
+ std::ostream& out_;
363
+ void processEvents(const std::vector<LegacyEvent*>& events);
364
+ };
365
+
366
+ // A guard that enables the legacy profiler, taking in an optional callback to
367
+ // process the results Usage:
368
+ // {
369
+ // TLSLegacyProfilerGuard g([](thread_event_lists profilerResults) {
370
+ // // process profilerResults
371
+ // });
372
+ // Code to profile
373
+ // }
374
+ struct TORCH_API TLSLegacyProfilerGuard {
375
+ explicit TLSLegacyProfilerGuard(
376
+ const torch::profiler::impl::ProfilerConfig& cfg,
377
+ std::optional<std::function<void(const thread_event_lists&)>>
378
+ resultCallback = std::nullopt,
379
+ std::optional<ProfilerDisableOptions> profilerDisableOptions =
380
+ std::nullopt)
381
+ : cb_(std::move(resultCallback)),
382
+ profilerDisableOptions_(profilerDisableOptions) {
383
+ enableProfilerLegacy(cfg);
384
+ }
385
+ ~TLSLegacyProfilerGuard() {
386
+ thread_event_lists event_lists =
387
+ disableProfilerLegacy(profilerDisableOptions_);
388
+ if (cb_) {
389
+ try {
390
+ (*cb_)(event_lists);
391
+ } catch (const std::exception& e) {
392
+ LOG(ERROR) << "Got error processing profiler events: " << e.what();
393
+ }
394
+ }
395
+ }
396
+
397
+ private:
398
+ std::optional<std::function<void(const thread_event_lists&)>> cb_;
399
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
400
+ const std::optional<ProfilerDisableOptions> profilerDisableOptions_;
401
+ };
402
+
403
+ } // namespace torch::autograd::profiler
404
+
405
+ #else
406
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
407
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/autograd/profiler_python.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace torch::autograd::profiler::python_tracer {
5
+
6
+ void init();
7
+
8
+ }
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)