TensorBody.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. #pragma once
  2. #ifdef TORCH_ASSERT_NO_OPERATORS
  3. #error This change adds a dependency on native_functions.yaml, \
  4. meaning the file will need to be re-compiled every time an operator \
  5. is changed or added. Consider if your change would be better placed in \
  6. another file, or if a more specific header might achieve the same goal. \
  7. See NOTE: [Tensor vs. TensorBase]
  8. #endif
  9. #include <c10/core/Device.h>
  10. #include <c10/core/Layout.h>
  11. #include <c10/core/MemoryFormat.h>
  12. #include <c10/core/QScheme.h>
  13. #include <c10/core/Stream.h>
  14. #include <c10/core/Scalar.h>
  15. #include <c10/core/ScalarType.h>
  16. #include <c10/core/ScalarTypeToTypeMeta.h>
  17. #include <c10/core/Storage.h>
  18. #include <c10/core/TensorImpl.h>
  19. #include <c10/core/UndefinedTensorImpl.h>
  20. #include <c10/core/WrapDimMinimal.h>
  21. #include <c10/util/Exception.h>
  22. #include <c10/util/Deprecated.h>
  23. #include <c10/util/MaybeOwned.h>
  24. #include <c10/util/Optional.h>
  25. #include <c10/util/OptionalArrayRef.h>
  26. #include <c10/util/intrusive_ptr.h>
  27. #include <c10/macros/Export.h>
  28. #include <ATen/core/CheckMemoryFormat.h>
  29. #include <ATen/core/DeprecatedTypePropertiesRegistry.h>
  30. #include <ATen/core/DeprecatedTypeProperties.h>
  31. #include <ATen/core/NamedTensor.h>
  32. #include <ATen/core/QuantizerBase.h>
  33. #include <c10/core/SymInt.h>
  34. #include <ATen/core/TensorAccessor.h>
  35. #include <ATen/core/TensorBase.h>
  36. #include <ATen/MethodOperators.h>
  37. namespace c10{
  38. template<class T> class List;
  39. template<class T> class IListRef;
  40. }
  41. namespace at {
  42. struct Generator;
  43. struct Type;
  44. class DeprecatedTypeProperties;
  45. class Tensor;
  46. } // namespace at
  47. namespace at {
  48. namespace indexing {
  49. struct TensorIndex;
  50. } // namespace indexing
  51. } // namespace at
  52. namespace torch { namespace autograd {
  53. struct Node;
  54. }} // namespace torch::autograd
  55. namespace at {
  56. class OptionalTensorRef;
  57. class Tensor;
  58. using TensorList = ArrayRef<Tensor>;
  59. using ITensorList = c10::IListRef<Tensor>;
  60. using Stream = c10::Stream;
  61. // Tensor is a "generic" object holding a pointer to the underlying TensorImpl object, which
  62. // has an embedded reference count. In this way, Tensor is similar to boost::intrusive_ptr.
  63. //
  64. // For example:
  65. //
  66. // void func(Tensor a) {
  67. // Tensor b = a;
  68. // ...
  69. // }
  70. //
  71. // In this example, when we say Tensor b = a, we are creating a new object that points to the
  72. // same underlying TensorImpl, and bumps its reference count. When b goes out of scope, the
  73. // destructor decrements the reference count by calling release() on the TensorImpl it points to.
  74. // The existing constructors, operator overloads, etc. take care to implement the correct semantics.
  75. //
  76. // Note that Tensor can also be NULL, i.e. it is not associated with any underlying TensorImpl, and
  77. // special care must be taken to handle this.
  78. class TORCH_API Tensor: public TensorBase {
  79. protected:
  80. // Create a Tensor with a +0 reference count. Special care must be
  81. // taken to avoid decrementing this reference count at destruction
  82. // time. Intended to support MaybeOwnedTraits<Tensor>.
  83. explicit Tensor(unsafe_borrow_t, const TensorBase& rhs): TensorBase(unsafe_borrow_t{}, rhs) {}
  84. friend MaybeOwnedTraits<Tensor>;
  85. friend OptionalTensorRef;
  86. public:
  87. Tensor() = default;
  88. // This constructor should not be used by end users and is an implementation
  89. // detail invoked by autogenerated code.
  90. explicit Tensor(
  91. c10::intrusive_ptr<TensorImpl, UndefinedTensorImpl> tensor_impl)
  92. : TensorBase(std::move(tensor_impl)) {}
  93. Tensor(const Tensor &tensor) = default;
  94. Tensor(Tensor &&tensor) = default;
  95. // Implicitly move-constructible from TensorBase, but must be explicit to increase refcount
  96. explicit Tensor(const TensorBase &base): TensorBase(base) {}
  97. /*implicit*/ Tensor(TensorBase &&base): TensorBase(std::move(base)) {}
  98. // Creates a new wrapper from TensorImpl. Intentionally a free method because
  99. // it should be used with care. Checks necessary invariants
  100. static Tensor wrap_tensor_impl(
  101. c10::intrusive_ptr<TensorImpl, UndefinedTensorImpl> tensor_impl) {
  102. return TensorBase::wrap_tensor_impl(std::move(tensor_impl));
  103. }
  104. Tensor contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const {
  105. return TensorBase::contiguous(memory_format);
  106. }
  107. Tensor conj() const {
  108. if (!this->is_complex()) {
  109. return *this;
  110. }
  111. switch (this->layout()) {
  112. case at::kSparse:
  113. case at::kSparseCsr:
  114. case at::kSparseCsc:
  115. case at::kSparseBsr:
  116. case at::kSparseBsc:
  117. return this->conj_physical();
  118. default:
  119. return this->_conj();
  120. }
  121. }
  122. // Aliased by Dimname overloads, so need explicit using
  123. using TensorBase::size;
  124. using TensorBase::sym_size;
  125. using TensorBase::stride;
  126. /// Should be used if *this can reasonably be expected to be contiguous and
  127. /// performance is important.
  128. /// Compared to contiguous, it saves a reference count
  129. /// increment/decrement if *this is already contiguous, at the cost
  130. /// in all cases of an extra pointer of stack usage, an extra branch
  131. /// to access, and an extra branch at destruction time.
  132. c10::MaybeOwned<Tensor> expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const &;
  133. // Use .contiguous() instead. Trying to borrow from a prvalue Tensor
  134. // will only lead to trouble and dangling references.
  135. c10::MaybeOwned<Tensor> expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) && = delete;
  136. // The following overloads are very intruiging. Consider the following
  137. // program:
  138. //
  139. // x[1] = 3;
  140. //
  141. // We would expect that the first entry of x is written to 3. But how can we
  142. // actually achieve this? x[1] evaluates to a tensor...
  143. //
  144. // The answer is, using a ref-qualifier. x[1] is an rvalue, which cannot be
  145. // (profitably) assigned to in the traditional sense, so we overload
  146. // assignment to mean, "Actually, copy 3 into the tensor data." This is done
  147. // with an rvalue-reference ref-qualified overload (the methods with && at the
  148. // end of their type.)
  149. //
  150. // There's one more fly in the ointment: We also want
  151. //
  152. // Tensor x = y;
  153. //
  154. // to work, and we want it NOT to copy. So we need a traditional operator=
  155. // overload. But we MUST specify a mutable lvalue ref-qualifier, to
  156. // disambiguate the traditional overload from the rvalue-reference
  157. // ref-qualified overload. Otherwise, it will be ambiguous, because
  158. // a non ref-qualified method is eligible for all situations.
  159. // Unfortunately, we have to write these constructors out manually
  160. // to work around an MSVC bug:
  161. // error C2580: 'at::Tensor &at::Tensor::operator =(const at::Tensor &) &':
  162. // multiple versions of a defaulted special member functions are not allowed
  163. // Tensor& operator=(const Tensor&) & = default;
  164. // Tensor& operator=(Tensor&&) & = default;
  165. // Also MSVC will wrongly issue the following warning with the aforementioned fix
  166. // warning C4522: 'at::Tensor': multiple assignment operators specified
  167. // Let's just skip the warning.
  168. //
  169. // TODO: temporarily disabled
  170. Tensor& operator=(const TensorBase& x) & {
  171. impl_ = x.getIntrusivePtr();
  172. return *this;
  173. }
  174. Tensor& operator=(TensorBase&& x) & noexcept {
  175. impl_ = x.unsafeReleaseIntrusivePtr();
  176. return *this;
  177. }
  178. Tensor& operator=(const Tensor &x) & {
  179. return operator=(static_cast<const TensorBase&>(x));
  180. }
  181. Tensor& operator=(Tensor &&x) & noexcept {
  182. return operator=(static_cast<TensorBase&&>(x));
  183. }
  184. Tensor& operator=(const Scalar &v) && {
  185. return fill_(v);
  186. }
  187. Tensor& operator=(const Tensor &rhs) && {
  188. return copy_(rhs);
  189. }
  190. Tensor& operator=(Tensor&& rhs) && {
  191. return copy_(rhs);
  192. }
  193. C10_DEPRECATED_MESSAGE("Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device().")
  194. DeprecatedTypeProperties & type() const {
  195. return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
  196. dispatchKeyToBackend(legacyExtractDispatchKey(key_set())),
  197. scalar_type());
  198. }
  199. Tensor toType(ScalarType t) const {
  200. return to(options().dtype(t), /*non_blocking*/ false, /*copy*/ false);
  201. }
  202. // TODO: Deprecate me
  203. Tensor toBackend(Backend b) const {
  204. return to(options().device(backendToDeviceType(b)).layout(layout_from_backend(b)), /*non_blocking*/ false, /*copy*/ false);
  205. }
  206. C10_DEPRECATED_MESSAGE("Tensor.is_variable() is deprecated; everything is a variable now. (If you want to assert that variable has been appropriately handled already, use at::impl::variable_excluded_from_dispatch())")
  207. bool is_variable() const noexcept {
  208. return !at::impl::variable_excluded_from_dispatch();
  209. }
  210. template<typename T>
  211. C10_DEPRECATED_MESSAGE("Tensor.data<T>() is deprecated. Please use Tensor.data_ptr<T>() instead.")
  212. T * data() const {
  213. return data_ptr<T>();
  214. }
  215. template <typename T>
  216. T item() const;
  217. template<typename T, size_t N, template <typename U> class PtrTraits = DefaultPtrTraits, typename index_t = int64_t>
  218. C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead")
  219. GenericPackedTensorAccessor<T,N,PtrTraits,index_t> packed_accessor() const & {
  220. return generic_packed_accessor<T,N,PtrTraits,index_t>();
  221. }
  222. template<typename T, size_t N, template <typename U> class PtrTraits = DefaultPtrTraits, typename index_t = int64_t>
  223. C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead")
  224. GenericPackedTensorAccessor<T,N,PtrTraits,index_t> packed_accessor() && = delete;
  225. Tensor operator~() const {
  226. return bitwise_not();
  227. }
  228. Tensor operator-() const {
  229. return neg();
  230. }
  231. Tensor& operator+=(const Tensor & other) {
  232. return add_(other);
  233. }
  234. Tensor& operator+=(const Scalar & other) {
  235. return add_(other);
  236. }
  237. Tensor& operator-=(const Tensor & other) {
  238. return sub_(other);
  239. }
  240. Tensor& operator-=(const Scalar & other) {
  241. return sub_(other);
  242. }
  243. Tensor& operator*=(const Tensor & other) {
  244. return mul_(other);
  245. }
  246. Tensor& operator*=(const Scalar & other) {
  247. return mul_(other);
  248. }
  249. Tensor& operator/=(const Tensor & other) {
  250. return div_(other);
  251. }
  252. Tensor& operator/=(const Scalar & other) {
  253. return div_(other);
  254. }
  255. Tensor& operator&=(const Tensor & other) {
  256. return bitwise_and_(other);
  257. }
  258. Tensor& operator|=(const Tensor & other) {
  259. return bitwise_or_(other);
  260. }
  261. Tensor& operator^=(const Tensor & other) {
  262. return bitwise_xor_(other);
  263. }
  264. Tensor operator[](const Scalar & index) const {
  265. if (!index.isIntegral(false)) {
  266. TORCH_CHECK_INDEX(false, "Can only index tensors with integral scalars");
  267. }
  268. return this->operator[](index.toLong());
  269. }
  270. Tensor operator[](const Tensor & index) const {
  271. // These properties are checked in the Scalar constructor, but we already
  272. // check them here to provide more useful diagnostics for the user.
  273. if (!index.defined()) {
  274. TORCH_CHECK_INDEX(false, "Can only index with tensors that are defined");
  275. }
  276. if (index.dim() != 0) {
  277. TORCH_CHECK_INDEX(false,
  278. "Can only index with tensors that are scalars (zero-dim)");
  279. }
  280. // The Scalar(Tensor) constructor is explicit, so we need to call it.
  281. return this->operator[](index.item());
  282. }
  283. Tensor operator[](int64_t index) const {
  284. return select(0, index);
  285. }
  286. Tensor index(ArrayRef<at::indexing::TensorIndex> indices) const;
  287. Tensor index(std::initializer_list<at::indexing::TensorIndex> indices) const;
  288. Tensor & index_put_(ArrayRef<at::indexing::TensorIndex> indices, Tensor const & rhs);
  289. Tensor & index_put_(ArrayRef<at::indexing::TensorIndex> indices, const Scalar& v);
  290. Tensor & index_put_(std::initializer_list<at::indexing::TensorIndex> indices, Tensor const & rhs);
  291. Tensor & index_put_(std::initializer_list<at::indexing::TensorIndex> indices, const Scalar& v);
  292. Tensor cpu() const {
  293. return to(options().device(DeviceType::CPU), /*non_blocking*/ false, /*copy*/ false);
  294. }
  295. // TODO: The Python version also accepts arguments
  296. Tensor cuda() const {
  297. return to(options().device(DeviceType::CUDA), /*non_blocking*/ false, /*copy*/ false);
  298. }
  299. Tensor hip() const {
  300. return to(options().device(DeviceType::HIP), /*non_blocking*/ false, /*copy*/ false);
  301. }
  302. Tensor ve() const {
  303. return to(options().device(DeviceType::VE), /*non_blocking*/ false, /*copy*/ false);
  304. }
  305. Tensor vulkan() const {
  306. return to(options().device(DeviceType::Vulkan), /*non_blocking*/ false, /*copy*/ false);
  307. }
  308. Tensor metal() const {
  309. return to(options().device(DeviceType::Metal), /*non_blocking*/ false, /*copy*/ false);
  310. }
  311. Tensor meta() const {
  312. return to(options().device(DeviceType::Meta), /*non_blocking*/ false, /*copy*/ false);
  313. }
  314. // ~~~~~ Autograd API ~~~~~
  315. /// \fn bool is_leaf() const;
  316. ///
  317. /// All Tensors that have `requires_grad()` which is ``false`` will be leaf Tensors by convention.
  318. ///
  319. /// For Tensors that have `requires_grad()` which is ``true``, they will be leaf Tensors if they were
  320. /// created by the user. This means that they are not the result of an operation and so
  321. /// `grad_fn()` is `nullptr`.
  322. ///
  323. /// Only leaf Tensors will have their `grad()` populated during a call to `backward()`.
  324. /// To get `grad()` populated for non-leaf Tensors, you can use `retain_grad()`.
  325. ///
  326. /// Example:
  327. /// @code
  328. /// auto a = torch::rand(10, torch::requires_grad());
  329. /// std::cout << a.is_leaf() << std::endl; // prints `true`
  330. ///
  331. /// auto b = torch::rand(10, torch::requires_grad()).to(torch::kCUDA);
  332. /// std::cout << b.is_leaf() << std::endl; // prints `false`
  333. /// // b was created by the operation that cast a cpu Tensor into a cuda Tensor
  334. ///
  335. /// auto c = torch::rand(10, torch::requires_grad()) + 2;
  336. /// std::cout << c.is_leaf() << std::endl; // prints `false`
  337. /// // c was created by the addition operation
  338. ///
  339. /// auto d = torch::rand(10).cuda();
  340. /// std::cout << d.is_leaf() << std::endl; // prints `true`
  341. /// // d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
  342. ///
  343. /// auto e = torch::rand(10).cuda().requires_grad_();
  344. /// std::cout << e.is_leaf() << std::endl; // prints `true`
  345. /// // e requires gradients and has no operations creating it
  346. ///
  347. /// auto f = torch::rand(10, torch::device(torch::kCUDA).requires_grad(true));
  348. /// std::cout << f.is_leaf() << std::endl; // prints `true`
  349. /// // f requires grad, has no operation creating it
  350. /// @endcode
  351. /// \fn void backward(const Tensor & gradient={}, c10::optional<bool> retain_graph=c10::nullopt, bool create_graph=false, c10::optional<TensorList> inputs=c10::nullopt) const;
  352. ///
  353. /// Computes the gradient of current tensor with respect to graph leaves.
  354. ///
  355. /// The graph is differentiated using the chain rule. If the tensor is
  356. /// non-scalar (i.e. its data has more than one element) and requires
  357. /// gradient, the function additionally requires specifying ``gradient``.
  358. /// It should be a tensor of matching type and location, that contains
  359. /// the gradient of the differentiated function w.r.t. this Tensor.
  360. ///
  361. /// This function accumulates gradients in the leaves - you might need to
  362. /// zero them before calling it.
  363. ///
  364. /// \param gradient Gradient w.r.t. the
  365. /// tensor. If it is a tensor, it will be automatically converted
  366. /// to a Tensor that does not require grad unless ``create_graph`` is True.
  367. /// None values can be specified for scalar Tensors or ones that
  368. /// don't require grad. If a None value would be acceptable then
  369. /// this argument is optional.
  370. /// \param retain_graph If ``false``, the graph used to compute
  371. /// the grads will be freed. Note that in nearly all cases setting
  372. /// this option to True is not needed and often can be worked around
  373. /// in a much more efficient way. Defaults to the value of
  374. /// ``create_graph``.
  375. /// \param create_graph If ``true``, graph of the derivative will
  376. /// be constructed, allowing to compute higher order derivative
  377. /// products. Defaults to ``false``.
  378. /// \param inputs Inputs w.r.t. which the gradient will be accumulated into
  379. /// ``at::Tensor::grad``. All other Tensors will be ignored. If not
  380. /// provided, the gradient is accumulated into all the leaf Tensors
  381. /// that were used to compute the current tensor.
  382. /// When inputs are provided and a given input is not a leaf,
  383. /// the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients).
  384. /// It is an implementation detail on which the user should not rely.
  385. /// See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
  386. void backward(const Tensor & gradient={}, c10::optional<bool> retain_graph=c10::nullopt, bool create_graph=false, c10::optional<TensorList> inputs=c10::nullopt) const {
  387. // NB: Adding this wrapper to _backward here because we'd like our
  388. // 'backwards' api to accept the 'inputs' argument optionally. Since code gen
  389. // currently does not support optional of TensorList our approach is to replace
  390. // backward in native_functions.yaml with _backward and call it here instead.
  391. if (inputs.has_value()) {
  392. TORCH_CHECK(inputs.value().size() > 0, "'inputs' argument to backward cannot be empty")
  393. this->_backward(inputs.value(), gradient, retain_graph, create_graph);
  394. } else {
  395. this->_backward({}, gradient, retain_graph, create_graph);
  396. }
  397. }
  398. /// \fn Tensor detach() const;
  399. ///
  400. /// Returns a new Tensor, detached from the current graph.
  401. /// The result will never require gradient.
  402. /// \fn Tensor & detach_() const;
  403. ///
  404. /// Detaches the Tensor from the graph that created it, making it a leaf.
  405. /// Views cannot be detached in-place.
  406. /// \fn void retain_grad() const;
  407. ///
  408. /// Enables this Tensor to have their :attr:`grad` populated during
  409. /// :func:`backward`. This is a no-op for leaf tensors.
  410. /// \fn bool retains_grad() const;
  411. ///
  412. /// Is ``true`` if this Tensor is non-leaf and its :attr:`grad` is enabled to be
  413. /// populated during :func:`backward`, ``false`` otherwise.
  414. const Tensor& set_requires_grad(bool requires_grad) const {
  415. TensorBase::set_requires_grad(requires_grad);
  416. return *this;
  417. }
  418. /// Return a mutable reference to the gradient. This is conventionally
  419. /// used as `t.grad() = x` to set a gradient to a completely new tensor.
  420. /// Note that this function work with a non-const Tensor and is not
  421. /// thread safe.
  422. Tensor& mutable_grad() const {
  423. return impl_->mutable_grad();
  424. }
  425. /// This function returns an undefined tensor by default and returns a defined tensor
  426. /// the first time a call to `backward()` computes gradients for this Tensor.
  427. /// The attribute will then contain the gradients computed and future calls
  428. /// to `backward()` will accumulate (add) gradients into it.
  429. const Tensor& grad() const {
  430. const Tensor& maybe_grad = impl_->grad();
  431. if (!is_leaf() && !retains_grad() && !maybe_grad.defined()) {
  432. TORCH_WARN(
  433. "The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad "
  434. "attribute won't be populated during autograd.backward(). If you indeed want the .grad "
  435. "field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. "
  436. "If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor "
  437. "instead. See github.com/pytorch/pytorch/pull/30531 for more informations.");
  438. }
  439. return maybe_grad;
  440. }
  441. // The Forward AD API functions below are low level and are not to be used by end
  442. // users who should use the API provided in torch/csrc/autograd.h
  443. /// This function returns the forward gradient for this Tensor at the given level.
  444. const Tensor& _fw_grad(uint64_t level) const {
  445. return impl_->_fw_grad(level, *this);
  446. }
  447. /// This function can be used to set the value of the forward grad.
  448. /// Note that the given new_grad might not be used directly if it has different
  449. /// metadata (size/stride/storage offset) compared to this Tensor. In that case,
  450. /// new_grad content will be copied into a new Tensor
  451. void _set_fw_grad(const TensorBase& new_grad, uint64_t level, bool is_inplace_op) const {
  452. impl_->_set_fw_grad(new_grad, *this, level, is_inplace_op);
  453. }
  454. // STOP. Thinking of adding a method here, which only makes use
  455. // of other ATen methods? Define it in native_functions.yaml.
  456. //example
  457. //Tensor * add(Tensor & b);
  458. ${tensor_method_declarations}
  459. // Special C++ only overloads for std()-like functions (See gh-40287)
  460. // These are needed because int -> bool conversion takes precedence over int -> IntArrayRef
  461. // So, for example std(0) would select the std(unbiased=False) overload
  462. Tensor var(int dim) const {
  463. return var(IntArrayRef{dim});
  464. }
  465. Tensor std(int dim) const {
  466. return std(IntArrayRef{dim});
  467. }
  468. // We changed .dtype() to return a TypeMeta in #12766. Ideally, we want the
  469. // at::kDouble and its friends to be TypeMeta's, but that hasn't happened yet.
  470. // Before that change, we make this method to maintain BC for C++ usage like
  471. // `x.to(y.dtype)`.
  472. // TODO: remove following two after at::kDouble and its friends are TypeMeta's.
  473. inline Tensor to(caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const {
  474. return this->to(/*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy);
  475. }
  476. inline Tensor to(Device device, caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const {
  477. return this->to(device, /*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy);
  478. }
  479. template <typename F, typename... Args>
  480. decltype(auto) m(F func, Args&&... params) const {
  481. return func(*this, std::forward<Args>(params)...);
  482. }
  483. /// NOTE: This is similar to the legacy `.data()` function on `Variable`, and is intended
  484. /// to be used from functions that need to access the `Variable`'s equivalent `Tensor`
  485. /// (i.e. `Tensor` that shares the same storage and tensor metadata with the `Variable`).
  486. ///
  487. /// One notable difference with the legacy `.data()` function is that changes to the
  488. /// returned `Tensor`'s tensor metadata (e.g. sizes / strides / storage / storage_offset)
  489. /// will not update the original `Variable`, due to the fact that this function
  490. /// shallow-copies the `Variable`'s underlying TensorImpl.
  491. at::Tensor tensor_data() const {
  492. return TensorBase::tensor_data();
  493. }
  494. /// NOTE: `var.variable_data()` in C++ has the same semantics as `tensor.data`
  495. /// in Python, which create a new `Variable` that shares the same storage and
  496. /// tensor metadata with the original `Variable`, but with a completely new
  497. /// autograd history.
  498. ///
  499. /// NOTE: If we change the tensor metadata (e.g. sizes / strides /
  500. /// storage / storage_offset) of a variable created from `var.variable_data()`, those
  501. /// changes will not update the original variable `var`. In `.variable_data()`, we set
  502. /// `allow_tensor_metadata_change_` to false to make such changes explicitly illegal,
  503. /// in order to prevent users from changing metadata of `var.variable_data()`
  504. /// and expecting the original variable `var` to also be updated.
  505. at::Tensor variable_data() const {
  506. return TensorBase::variable_data();
  507. }
  508. // Hooks
  509. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  510. template <typename T>
  511. using hook_return_void_t = std::enable_if_t<std::is_void<typename c10::invoke_result_t<T&, Tensor>>::value, unsigned>;
  512. template <typename T>
  513. using hook_return_var_t = std::enable_if_t<std::is_same<typename c10::invoke_result_t<T&, Tensor>, Tensor>::value, unsigned>;
  514. /// Registers a backward hook.
  515. ///
  516. /// The hook will be called every time a gradient with respect to the Tensor is computed.
  517. /// The hook should have one of the following signature:
  518. /// ```
  519. /// hook(Tensor grad) -> Tensor
  520. /// ```
  521. /// ```
  522. /// hook(Tensor grad) -> void
  523. /// ```
  524. /// The hook should not modify its argument, but it can optionally return a new gradient
  525. /// which will be used in place of `grad`.
  526. ///
  527. /// This function returns the index of the hook in the list which can be used to remove hook.
  528. ///
  529. /// Example:
  530. /// @code
  531. /// auto v = torch::tensor({0., 0., 0.}, torch::requires_grad());
  532. /// auto h = v.register_hook([](torch::Tensor grad){ return grad * 2; }); // double the gradient
  533. /// v.backward(torch::tensor({1., 2., 3.}));
  534. /// // This prints:
  535. /// // ```
  536. /// // 2
  537. /// // 4
  538. /// // 6
  539. /// // [ CPUFloatType{3} ]
  540. /// // ```
  541. /// std::cout << v.grad() << std::endl;
  542. /// v.remove_hook(h); // removes the hook
  543. /// @endcode
  544. template <typename T>
  545. hook_return_void_t<T> register_hook(T&& hook) const;
  546. template <typename T>
  547. hook_return_var_t<T> register_hook(T&& hook) const;
  548. // Variable methods
  549. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  550. Tensor data() const {
  551. return TensorBase::data();
  552. }
  553. void _backward(TensorList inputs, const c10::optional<Tensor>& gradient, c10::optional<bool> keep_graph, bool create_graph) const;
  554. const Tensor& requires_grad_(bool _requires_grad=true) const {
  555. TensorBase::requires_grad_(_requires_grad);
  556. return *this;
  557. }
  558. };
  559. namespace detail {
  560. // Helper creator for Tensor class which doesn't requires the users to pass
  561. // in an intrusive_ptr instead it just converts the argument passed to
  562. // requested intrusive_ptr type.
  563. template <typename T, typename... Args>
  564. Tensor make_tensor(Args&&... args) {
  565. return Tensor(c10::make_intrusive<T>(std::forward<Args>(args)...));
  566. }
  567. } // namespace detail
  568. } // namespace at
  569. namespace at {
  570. ${tensor_method_definitions}
  571. } // namespace at
  572. namespace c10 {
  573. template <>
  574. struct MaybeOwnedTraits<at::Tensor> {
  575. using owned_type = at::Tensor;
  576. using borrow_type = at::Tensor;
  577. static borrow_type createBorrow(const owned_type& from) {
  578. // NOTE: this can be implemented without the special
  579. // unsafe_borrow_t Tensor constructor as
  580. //
  581. // return borrow_type(c10::intrusive_ptr<at::TensorImpl, at::UndefinedTensorImpl>::reclaim(from.unsafeGetTensorImpl()));
  582. //
  583. // but that hurts inlining due to the nullptr check in the
  584. // Tensor(c10::intrusive_ptr<...>) constructor. We already know
  585. // that from.impl_ isn't null because from is a valid Tensor, so
  586. // we needn't do the check again. (using __builtin_assume can
  587. // avoid this, but wouldn't be portable to MSVC.)
  588. return borrow_type(borrow_type::unsafe_borrow_t{}, from);
  589. }
  590. static void assignBorrow(borrow_type& lhs, const borrow_type& rhs) {
  591. lhs.unsafeReleaseTensorImpl();
  592. // See above note: this can be implemented with public API
  593. // similarly to createBorrow(), but that would hurt inlining.
  594. lhs = borrow_type(borrow_type::unsafe_borrow_t{}, rhs);
  595. }
  596. static void destroyBorrow(borrow_type& toDestroy) {
  597. toDestroy.unsafeReleaseTensorImpl(); // "leak" it, but it was already +0.
  598. }
  599. static const owned_type& referenceFromBorrow(const borrow_type& borrow) {
  600. return borrow;
  601. }
  602. static const owned_type* pointerFromBorrow(const borrow_type& borrow) {
  603. return &borrow;
  604. }
  605. static bool debugBorrowIsValid(const borrow_type& /*borrow*/) {
  606. return true;
  607. }
  608. };
  609. template <>
  610. struct ExclusivelyOwnedTraits<at::Tensor> {
  611. using repr_type = at::Tensor;
  612. using pointer_type = at::Tensor*;
  613. using const_pointer_type = const at::Tensor*;
  614. static repr_type nullRepr() {
  615. return at::Tensor();
  616. }
  617. template <class... Args>
  618. static repr_type createInPlace(Args&&... args) {
  619. return at::Tensor(std::forward<Args>(args)...);
  620. }
  621. static repr_type moveToRepr(at::Tensor&& x) {
  622. return std::move(x);
  623. }
  624. static void destroyOwned(at::Tensor& x) {
  625. return ExclusivelyOwnedTraits<at::TensorBase>::destroyOwned(x);
  626. }
  627. static at::Tensor take(at::Tensor& x) {
  628. return std::move(x);
  629. }
  630. static pointer_type getImpl(repr_type& x) {
  631. return &x;
  632. }
  633. static const_pointer_type getImpl(const repr_type& x) {
  634. return &x;
  635. }
  636. };
  637. } // namespace c10
  638. namespace at {
  639. inline c10::MaybeOwned<Tensor> borrow_from_optional_tensor(
  640. const c10::optional<Tensor>& opt) {
  641. return opt.has_value()
  642. ? c10::MaybeOwned<Tensor>::borrowed(*opt)
  643. : c10::MaybeOwned<Tensor>::owned(c10::in_place);
  644. }
  645. inline c10::MaybeOwned<Tensor> Tensor::expect_contiguous(MemoryFormat memory_format) const & {
  646. if (is_contiguous(memory_format)) {
  647. return c10::MaybeOwned<Tensor>::borrowed(*this);
  648. } else {
  649. return c10::MaybeOwned<Tensor>::owned(__dispatch_contiguous(memory_format));
  650. }
  651. }
  652. } // namespace at