eager_properties.cc 12.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
// disable numpy compile error
#include <Python.h>

#include <string>
#include <vector>

17
#include "paddle/fluid/eager/accumulation/accumulation_node.h"
18
#include "paddle/fluid/eager/api/all.h"
19
#include "paddle/fluid/eager/api/utils/tensor_utils.h"
20 21 22 23 24 25 26 27
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/utils.h"
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/pybind/eager.h"
#include "paddle/fluid/pybind/eager_utils.h"
#include "paddle/fluid/pybind/exception.h"
28 29 30
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
31 32 33 34 35
#pragma GCC diagnostic ignored "-Wwrite-strings"

namespace paddle {
namespace pybind {

36
extern PyTypeObject* p_tensor_type;
37

38 39
PyObject* tensor_properties_get_name(TensorObject* self, void* closure) {
  EAGER_TRY
40 41
  // NOTE(dev): [why not use egr::Controller::Instance::GernerateUniqueName()?]
  // Beacause Controller must holder a tracer, but 'tensor.name' maybe called
42 43
  // everywhere such as static graph mode in @to_static, which means tracer is
  // None.
44 45 46 47
  static egr::UniqueNameGenerator name_generator;
  if (self->tensor.name().empty()) {
    self->tensor.set_name(name_generator.Generate());
  }
48
  return ToPyObject(self->tensor.name());
49 50 51
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

52 53
PyObject* tensor_properties_get_type(TensorObject* self, void* closure) {
  EAGER_TRY
54 55 56 57
  if (!self->tensor.defined()) {
    // be same to old dygraph
    return ToPyObject(paddle::framework::proto::VarType::LOD_TENSOR);
  }
58
  if (self->tensor.is_dense_tensor()) {
59
    return ToPyObject(paddle::framework::proto::VarType::LOD_TENSOR);
60 61
  } else if (self->tensor.is_selected_rows()) {
    return ToPyObject(paddle::framework::proto::VarType::SELECTED_ROWS);
62 63 64 65
  } else if (egr::IsVariableCompatTensor(self->tensor)) {
    return ToPyObject(static_cast<paddle::framework::proto::VarType::Type>(
        static_cast<const egr::VariableCompatTensor*>(self->tensor.impl().get())
            ->Type()));
66
  } else {
67
    RETURN_PY_NONE
68 69 70 71
  }
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
72 73 74 75 76 77
PyObject* tensor_properties_is_leaf(TensorObject* self, void* closure) {
  EAGER_TRY
  return ToPyObject(egr::egr_utils_api::IsLeafTensor(self->tensor));
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

78 79
int tensor_properties_set_name(TensorObject* self,
                               PyObject* value,
80 81
                               void* closure) {
  EAGER_TRY
82
  self->tensor.set_name(CastPyArg2AttrString(value, 0));
83
  return 0;
0
0x45f 已提交
84
  EAGER_CATCH_AND_THROW_RETURN_NEG
85 86
}

87 88 89
PyObject* tensor_properties_get_stop_gradient(TensorObject* self,
                                              void* closure) {
  EAGER_TRY
90
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
91 92 93 94
  return ToPyObject(meta->StopGradient());
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

95 96
PyObject* tensor_properties_get_grad(TensorObject* self, void* closure) {
  EAGER_TRY
97 98
  VLOG(6) << "Get grad for tensor: " << self->tensor.name();
  auto meta = egr::EagerUtils::nullable_autograd_meta(self->tensor);
99
  VLOG(6) << meta << " initialized: " << meta->Grad().initialized();
100
  if (meta && meta->Grad().initialized()) {
101
    return ToPyObject(meta->Grad());
102
  } else {
103
    RETURN_PY_NONE
104
  }
105 106 107
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

108 109
int tensor_properties_set_grad(TensorObject* self,
                               PyObject* value,
110 111
                               void* closure) {
  EAGER_TRY
112
  auto src = CastPyArg2Tensor(value, 0);
113
  PADDLE_ENFORCE(
114
      egr::egr_utils_api::IsLeafTensor(self->tensor),
115
      paddle::platform::errors::Fatal("Only leaf Tensor can be set grad."));
116 117 118 119 120 121 122 123

  paddle::experimental::Tensor* grad =
      egr::EagerUtils::mutable_grad(self->tensor);
  PADDLE_ENFORCE(grad != nullptr,
                 paddle::platform::errors::Fatal(
                     "Detected NULL grad"
                     "Please check if you have manually cleared"
                     "the grad inside autograd_meta"));
C
Chen Weihang 已提交
124
  grad->copy_(src, self->tensor.place(), true);
125
  return 0;
0
0x45f 已提交
126
  EAGER_CATCH_AND_THROW_RETURN_NEG
127 128
}

129 130
int tensor_properties_set_stop_gradient(TensorObject* self,
                                        PyObject* value,
131 132
                                        void* closure) {
  EAGER_TRY
133
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
134
  meta->SetStopGradient(CastPyArg2AttrBoolean(value, 0));
135 136 137
  if (!meta->GradNode()) {
    meta->SetGradNode(std::make_shared<egr::GradNodeAccumulation>(meta));
  }
138
  return 0;
0
0x45f 已提交
139
  EAGER_CATCH_AND_THROW_RETURN_NEG
140 141
}

142 143
PyObject* tensor_properties_get_persistable(TensorObject* self, void* closure) {
  EAGER_TRY
144
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
145 146 147 148
  return ToPyObject(meta->Persistable());
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

149 150
int tensor_properties_set_persistable(TensorObject* self,
                                      PyObject* value,
151 152
                                      void* closure) {
  EAGER_TRY
153
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
154 155
  meta->SetPersistable(CastPyArg2AttrBoolean(value, 0));
  return 0;
0
0x45f 已提交
156
  EAGER_CATCH_AND_THROW_RETURN_NEG
157 158
}

159 160
PyObject* tensor_properties_get_shape(TensorObject* self, void* closure) {
  EAGER_TRY
161
  std::vector<int64_t> value;
162 163 164
  if (!self->tensor.defined()) {
    return ToPyObject(value);
  }
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  if (egr::IsVariableCompatTensor(self->tensor)) {
    auto* var_tensor = static_cast<const egr::VariableCompatTensor*>(
        self->tensor.impl().get());
    if (var_tensor->IsType<paddle::framework::Vocab>()) {
      value.emplace_back(static_cast<int64_t>(
          var_tensor->Get<paddle::framework::Vocab>().size()));
    } else if (var_tensor->IsType<paddle::framework::Strings>()) {
      value.emplace_back(static_cast<int64_t>(
          var_tensor->Get<paddle::framework::Strings>().size()));
    } else {
      PADDLE_THROW(paddle::platform::errors::Unavailable(
          "VariableCompatTensor only support get shape from Vocab or "
          "Strings."));
    }
  } else {
    auto ddim = self->tensor.shape();
    size_t rank = static_cast<size_t>(ddim.size());
    value.resize(rank);
    for (size_t i = 0; i < rank; i++) {
      value[i] = ddim[i];
    }
186 187
  }

188 189 190 191 192 193 194 195 196 197 198 199 200
  auto desired_layout =
      paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
  auto default_layout =
      paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
  bool change_dim =
      (desired_layout != default_layout &&
       self->tensor.layout() == desired_layout && value.size() == 4);
  VLOG(6) << "eager_properties 'Shape' method, layout autotune "
          << " desired_layout: " << desired_layout
          << " default_layout: " << default_layout
          << " tensor layout: " << self->tensor.layout()
          << " tensor's shape size is : " << value.size();
  std::vector<int64_t> dims = value;
201
  if (change_dim && phi::DataLayoutToString(desired_layout) == "NCHW") {
202 203 204 205 206 207 208 209
    // NCHW -> NHWC
    VLOG(6) << "layout autotune get Shape from NCHW -> NHWC " << value[0] << " "
            << value[1] << " " << value[2] << " " << value[3] << " to "
            << dims[0] << " " << dims[2] << " " << dims[3] << " " << dims[1];
    value[0] = dims[0];
    value[1] = dims[2];
    value[2] = dims[3];
    value[3] = dims[1];
210
  } else if (change_dim && phi::DataLayoutToString(desired_layout) == "NHWC") {
211 212 213 214 215 216 217 218 219 220 221
    // NHWC -> NCHW
    VLOG(6) << "layout autotune get Shape from NHWC -> NCHW " << value[0] << " "
            << value[1] << " " << value[2] << " " << value[3] << " to "
            << dims[0] << " " << dims[3] << " " << dims[1] << " " << dims[2]
            << " " << dims[1];
    value[0] = dims[0];
    value[1] = dims[3];
    value[2] = dims[1];
    value[3] = dims[2];
  }

222 223 224 225
  return ToPyObject(value);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

226 227 228 229 230 231 232 233 234 235 236
PyObject* tensor_properties_get_layout(TensorObject* self, void* closure) {
  EAGER_TRY
  std::string layout = "";
  if (!self->tensor.defined()) {
    return ToPyObject(layout);
  }

  if (egr::IsVariableCompatTensor(self->tensor)) {
    VLOG(3) << "VariableCompatTensor does not support `layout` method.";
    return ToPyObject(layout);
  } else {
237
    return ToPyObject(phi::DataLayoutToString(self->tensor.layout()));
238 239 240 241 242 243
  }

  return ToPyObject(layout);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

244 245
PyObject* tensor_properties_get_place(TensorObject* self, void* closure) {
  EAGER_TRY
C
Chen Weihang 已提交
246
  return ToPyObject(self->tensor.place());
247 248 249
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

250 251
PyObject* tensor_properties_get_place_str(TensorObject* self, void* closure) {
  EAGER_TRY
252
  std::stringstream ostr;
C
Chen Weihang 已提交
253
  ostr << self->tensor.place();
254 255 256 257
  return ToPyObject(ostr.str());
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

258 259
PyObject* tensor_properties_get_dtype(TensorObject* self, void* closure) {
  EAGER_TRY
260 261 262 263
  if (!self->tensor.defined()) {
    // be same to old dygraph
    return ToPyObject(framework::proto::VarType::FP32);
  }
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  if (egr::IsVariableCompatTensor(self->tensor)) {
    auto* var_tensor = static_cast<const egr::VariableCompatTensor*>(
        self->tensor.impl().get());
    if (var_tensor->IsType<paddle::framework::Vocab>()) {
      return ToPyObject(framework::proto::VarType::RAW);
    } else if (var_tensor->IsType<paddle::framework::Strings>()) {
      return ToPyObject(framework::proto::VarType::STRING);
    } else {
      PADDLE_THROW(paddle::platform::errors::Unavailable(
          "VariableCompatTensor only support get shape from Vocab or "
          "Strings."));
    }
  } else {
    return ToPyObject(
        paddle::framework::TransToProtoVarType(self->tensor.type()));
  }
280 281 282 283
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

struct PyGetSetDef variable_properties[] = {
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    {"grad",
     (getter)tensor_properties_get_grad,
     (setter)tensor_properties_set_grad,
     nullptr,
     nullptr},
    {"name",
     (getter)tensor_properties_get_name,
     (setter)tensor_properties_set_name,
     nullptr,
     nullptr},
    {"stop_gradient",
     (getter)tensor_properties_get_stop_gradient,
     (setter)tensor_properties_set_stop_gradient,
     nullptr,
     nullptr},
    {"persistable",
     (getter)tensor_properties_get_persistable,
     (setter)tensor_properties_set_persistable,
     nullptr,
     nullptr},
304
    {"shape", (getter)tensor_properties_get_shape, nullptr, nullptr, nullptr},
305
    {"layout", (getter)tensor_properties_get_layout, nullptr, nullptr, nullptr},
306
    // {"is_leaf", (getter)tensor_properties_get_is_leaf, nullptr,
307 308
    // nullptr,
    //  nullptr},
309
    {"place", (getter)tensor_properties_get_place, nullptr, nullptr, nullptr},
310 311 312 313
    {"_place_str",
     (getter)tensor_properties_get_place_str,
     nullptr,
     nullptr,
314
     nullptr},
315 316
    {"dtype", (getter)tensor_properties_get_dtype, nullptr, nullptr, nullptr},
    {"type", (getter)tensor_properties_get_type, nullptr, nullptr, nullptr},
W
wanghuancoder 已提交
317
    {"is_leaf", (getter)tensor_properties_is_leaf, nullptr, nullptr, nullptr},
318 319
    {nullptr, nullptr, nullptr, nullptr, nullptr}};

J
Jack Zhou 已提交
320 321
// variable_properties for core.eager.StringTensor
struct PyGetSetDef string_tensor_variable_properties[] = {
322 323 324 325 326
    {"name",
     (getter)tensor_properties_get_name,
     (setter)tensor_properties_set_name,
     nullptr,
     nullptr},
J
Jack Zhou 已提交
327
    {"shape", (getter)tensor_properties_get_shape, nullptr, nullptr, nullptr},
328
    {"layout", (getter)tensor_properties_get_layout, nullptr, nullptr, nullptr},
J
Jack Zhou 已提交
329
    {"place", (getter)tensor_properties_get_place, nullptr, nullptr, nullptr},
330 331 332 333
    {"_place_str",
     (getter)tensor_properties_get_place_str,
     nullptr,
     nullptr,
J
Jack Zhou 已提交
334 335 336
     nullptr},
    {nullptr, nullptr, nullptr, nullptr, nullptr}};

337 338
}  // namespace pybind
}  // namespace paddle