empty_tensor_op.h 1.04 KB
Newer Older
eellison's avatar
eellison committed
1
2
3
4
5
6
7
8
9
#pragma once

// All pure C++ headers for the C++ frontend.
#include <torch/all.h>
// Python bindings for the C++ frontend (includes Python.h).
#include <torch/python.h>

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

19
20
21
  static torch::autograd::variable_list backward(
      torch::autograd::AutogradContext* ctx,
      torch::autograd::variable_list grad_output) {
eellison's avatar
eellison committed
22
23
24
25
26
27
28
    // 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()};
  }
};

29
at::Tensor new_empty_tensor(const at::Tensor& input, c10::List<int64_t> shape) {
eellison's avatar
eellison committed
30
31
  return NewEmptyTensorOp::apply(input, shape)[0];
}