forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tensor.h
94 lines (76 loc) · 2.17 KB
/
Tensor.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#pragma once
#include <ATen/core/TensorBody.h>
#include <c10/util/Exception.h>
namespace at {
class TORCH_API OptionalTensorRef {
public:
OptionalTensorRef() = default;
~OptionalTensorRef() {
ref_.unsafeReleaseTensorImpl();
}
OptionalTensorRef(const TensorBase& src)
: ref_(Tensor::unsafe_borrow_t{}, src) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src.defined());
}
OptionalTensorRef(const OptionalTensorRef& rhs)
: ref_(Tensor::unsafe_borrow_t{}, rhs.ref_) {}
OptionalTensorRef& operator=(OptionalTensorRef rhs) {
std::swap(ref_, rhs.ref_);
return *this;
}
bool has_value() const {
return ref_.defined();
}
const Tensor& getTensorRef() const & {
return ref_;
}
const Tensor& operator*() const & {
return ref_;
}
const Tensor* operator->() const & {
return &ref_;
}
operator bool() const {
return ref_.defined();
}
private:
Tensor ref_;
};
// Use to convert a TensorBase (that may be undefined) to an at::Tensor
// without bumping refcount.
class TORCH_API TensorRef {
public:
~TensorRef() {
ref_.unsafeReleaseTensorImpl();
}
TensorRef(const TensorBase& src)
: ref_(Tensor::unsafe_borrow_t{}, src) {}
const Tensor& operator*() const & {
return ref_;
}
private:
Tensor ref_;
};
template <typename T>
// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
auto Tensor::register_hook(T&& hook) const -> Tensor::hook_return_void_t<T> {
// Return the grad argument in case of a hook with void return type to have an
// std::function with Tensor return type
static_assert(std::is_same<decltype(hook(Tensor())), void>::value,
"Expected hook to return void");
return _register_hook([fn=std::forward<T>(hook)](const TensorBase& grad_base) {
TensorRef grad(grad_base);
fn(*grad);
return Tensor();
});
}
template <typename T>
// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
auto Tensor::register_hook(T&& hook) const -> Tensor::hook_return_var_t<T> {
return _register_hook([fn=std::forward<T>(hook)](const TensorBase& grad_base) {
TensorRef grad(grad_base);
Tensor ret = fn(*grad);
return TensorBase(std::move(ret));
});
}
} // namespace at