new_empty_tensor_op.cpp 1.08 KB
Newer Older
1
2
3
4
5
6
7
#include "new_empty_tensor_op.h"
#include <torch/extension.h>

namespace vision {
namespace ops {

namespace {
eellison's avatar
eellison committed
8
9
10

class NewEmptyTensorOp : public torch::autograd::Function<NewEmptyTensorOp> {
 public:
11
12
  static torch::autograd::variable_list forward(
      torch::autograd::AutogradContext* ctx,
13
14
      const torch::autograd::Variable& input,
      const c10::List<int64_t>& new_shape) {
eellison's avatar
eellison committed
15
16
    ctx->saved_data["shape"] = input.sizes();
    std::vector<int64_t> shape(new_shape.begin(), new_shape.end());
17
    return {input.new_empty(shape, at::TensorOptions())};
eellison's avatar
eellison committed
18
19
  }

20
21
  static torch::autograd::variable_list backward(
      torch::autograd::AutogradContext* ctx,
22
      const torch::autograd::variable_list& grad_output) {
eellison's avatar
eellison committed
23
24
25
26
27
28
29
    // Use data saved in forward
    auto shape = ctx->saved_data["shape"].toIntList();
    auto out = forward(ctx, grad_output[0], shape);
    return {out[0], at::Tensor()};
  }
};

30
31
32
33
34
} // namespace

at::Tensor new_empty_tensor(
    const at::Tensor& input,
    const c10::List<int64_t>& shape) {
eellison's avatar
eellison committed
35
36
  return NewEmptyTensorOp::apply(input, shape)[0];
}
37
38
39

} // namespace ops
} // namespace vision