operator_utils.c.j2 19.2 KB
Newer Older
1
{# ----------------------------- op maker ----------------------------------- #}
2 3 4
{% macro op_maker(op) %}
  {% set op_name = op["op_name"] %}
class {{op_name | to_pascal_case}}OpMaker : public framework::OpProtoAndCheckerMaker {
5 6 7
 public:
  void Make() override {
  {% filter indent(4, True) %}
8 9
    {% for input in op["inputs"] %}
{{add_input(loop.index0, input, op_name)}};
10
    {% endfor %}
11 12
    {% for output in op["outputs"] %}
{{add_output(loop.index0, output, op_name)}};
13
    {% endfor %}
14 15 16
    {% for attr in op["attrs"] %}
      {% if attr["name"] in op["kernel"]["param"] %}
{{add_attr(loop.index0, attr, op_name)}};
17 18 19 20
      {% endif %}
    {% endfor %}
  {% endfilter %}
    AddComment(R"DOC(
21
TODO: Documentation of {{op_name}} op.
22 23 24 25 26 27 28 29 30 31 32
)DOC");
  }
};
{% endmacro %}


{# add input, it could be duplicable or dispensable #}
{% macro add_input(i, input, op_name) %}{# inline #}
  {% set name = input["name"] %}
  {% set typename = input["typename"] %}
AddInput({{name| to_opmaker_name}}, "({{typename}}), input {{i}} of {{op_name}} op.")
33 34
  {%- if typename is vec %}

35 36
    .AsDuplicable()
  {%- endif %}
37 38
  {%- if input["optional"] %}

39 40 41 42 43 44 45 46 47 48
    .AsDispensable()
  {%- endif %}
{%- endmacro %}

{# add output, it could be duplicable or intermediate, however, optional output is not supported #}
{% macro add_output(i, output, op_name) %}{# inline #}
  {% set name = output["name"] %}
  {% set typename = output["typename"] %}
  {% set is_intermediate = output["intermediate"] %}
AddOutput({{name | to_opmaker_name}}, "({{typename}}), output {{i}} of {{op_name}} op.")
49 50
  {%- if typename is vec %}

51 52
    .AsDuplicable()
  {%- endif %}
53 54
  {%- if is_intermediate %}

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    .AsIntermediate()
  {%- endif %}
{%- endmacro %}

{# add attribute, and process default value if needed #}
{% macro add_attr(i, attr, op_name) %}{# inline #}
  {% set name = attr["name"] %}
  {% set typename = attr["typename"] %}
  {% if typename is scalar %}
AddInput("{{name | to_pascal_case}}Tensor", "attribute {{i}} for {{op_name}} op from 0D Tensor.")
    .AsDispensable();
  {% elif typename == "IntArray" %}{# the type has been renamed #}
AddInput("{{name | to_pascal_case}}Tensor", "attribute {{i}} for {{op_name}} op from 1D integer Tensor.")
    .AsDispensable();
AddInput("{{name | to_pascal_case}}TensorList", "attribute {{i}} for {{op_name}} op from list fo 0D integer Tensors.")
    .AsDuplicable()
    .AsDispensable();
  {% endif %}
AddAttr<{{typename | to_op_attr_type}}>("{{name}}", "({{typename | to_op_attr_type}}), attribute {{i}} for {{op_name}} op.")
74
  {% if "default_value" in attr %}
75 76 77 78
    .SetDefault({{process_default_value(attr)}})
  {%- endif %}
{%- endmacro %}

79
{# process default value for attributes, some attribute has different types and different default values in op & opmaker #}
80 81 82 83
{% macro process_default_value(attr) %}{# inline #}
  {% set default_value = attr["default_value"] %}
  {% set typename = attr["typename"] %}
  {% if typename == "DataType" %}{# convert back to VarType #}
84 85 86
    {% if default_value == "DataType::UNDEFINED" %}
-1
    {%- else %}
87
static_cast<int>(framework::TransToProtoVarType(experimental::{{default_value}}))
88
    {%- endif %}
89 90 91 92 93 94 95 96 97 98 99
  {%- elif typename == "DataLayout" %} {# does DataLayout need any processing?#}
static_cast<int>(experimental::{{default_value}})
  {%- elif typename == "Place" %}{# construct a Place to get the type #}
static_cast<int>(phi::Place({{"phi::" if not default_value is initializer_list}}{{default_value}}).GetType())
  {%- else %}{# pass through as-is #}
{{default_value}}
  {%- endif %}
{%- endmacro %}


{# --------------------------------------- name mapping ---------------------------------------------- #}
100 101 102 103
{% macro name_map(op) %}
KernelSignature {{op["op_name"] | to_pascal_case }}OpArgumentMapping(const ArgumentMappingContext& ctx) {
  {% set kernel_args = op["kernel"]["param"] %}
  {{get_input_list(op["inputs"], kernel_args)}};
104
  paddle::small_vector<const char*> attrs;
105
  {% for attr in op["attrs"]%}
106 107 108 109
  {% filter indent(2)%}
  {{get_an_attr(attr)}};
  {% endfilter %}
  {% endfor %}
110 111 112
  {{get_output_list(op["outputs"], kernel_args)}};
  {% if op["kernel"]["func"] | length == 1 %}
  KernelSignature sig("{{op["kernel"]["func"][0]}}", std::move(inputs), std::move(attrs), std::move(outputs));
113 114
  return sig;
  {% else %}{# it has kernel for selected rows #}
115
  const char* kernel_name = ctx.IsSelectedRowsInput({{kernel_args[0] | to_opmaker_name_cstr}}) ? "{{op["kernel"]["func"][1]}}" : "{{op["kernel"]["func"][0]}}";
116 117 118
  KernelSignature sig (kernel_name, std::move(inputs), std::move(attrs), std::move(outputs));
  return sig;
  {%endif%}
119
}
120 121 122 123

/*
******************************************************************
NOTE: The following codes are for 'get_compat_kernel_signature.py'
124
All possible KernelSignatures returned by {{op["name"] | to_pascal_case }}OpArgumentMapping:
125

126
{{op | cartesian_prod_mapping}}
127 128
******************************************************************
*/
129 130
{% endmacro %}

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
{% macro get_kernel_dispatch(inputs, kernel_config) %}{# inline #}
{%- for kernel_func in kernel_config["func"] %}
  {% set input_idx = namespace(idx=0) %}
  {% set kernel_in_type_list = kernel_config["dispatch"][kernel_func][0] %}

  if ( {%- for input in inputs %}
    {%- if input["name"] in kernel_config["param"] %}
      {%- if kernel_in_type_list[input_idx.idx] == "dense" %}
ctx.IsDenseTensorInput("{{input["name"]}}"){{" && " if not loop.last}}
      {%- elif kernel_in_type_list[input_idx.idx] == "selected_rows" %}
ctx.IsSelectedRowsInput("{{input["name"]}}"){{" && " if not loop.last}}
      {%- elif kernel_in_type_list[input_idx.idx] == "sparse_coo" %}
ctx.IsSparseCooTensorInput("{{input["name"]}}"){{" && " if not loop.last}}
      {%- elif kernel_in_type_list[input_idx.idx] == "sparse_csr" %}
ctx.IsSparseCsrTensorInput("{{input["name"]}}"){{" && " if not loop.last}}
      {%- endif %}
      {% set input_idx.idx = input_idx.idx + 1 %}
    {%- endif %}
  {%- endfor %}) {
    kernel_name = "{{kernel_func}}";
  }
{%- endfor %}
{%- endmacro %}

155 156 157 158
{% macro sparse_op_name_map(op) %}
KernelSignature {{op["op_name"] | to_pascal_case }}OpArgumentMapping(const ArgumentMappingContext& ctx) {
  {% set kernel_args = op["kernel"]["param"] %}
  {{get_input_list(op["inputs"], kernel_args)}};
159
  paddle::small_vector<const char*> attrs;
160
  {% for attr in op["attrs"]%}
161 162 163 164
  {% filter indent(2)%}
  {{get_an_attr(attr)}};
  {% endfilter %}
  {% endfor %}
165
  {{get_output_list(op["outputs"], kernel_args)}};
166 167

  const char* kernel_name = "unregistered";
168
{{get_kernel_dispatch(op["inputs"], op["kernel"])}}
169 170 171 172 173 174 175
  KernelSignature sig (kernel_name, std::move(inputs), std::move(attrs), std::move(outputs));
  return sig;
}

/*
******************************************************************
NOTE: The following codes are for 'get_compat_kernel_signature.py'
176
All possible KernelSignatures returned by {{op["name"] | to_pascal_case }}OpArgumentMapping:
177

178
{{op | cartesian_prod_mapping}}
179 180 181 182
******************************************************************
*/
{% endmacro %}

183 184
{% macro register_base_kernel_name(op) %}
PD_REGISTER_BASE_KERNEL_NAME({{op["op_name"]}}, {{op["name"]}});
185
{%- endmacro %}
186

187 188
{% macro register_name_map(op) %}
PD_REGISTER_ARG_MAPPING_FN({{op["op_name"]}}, phi::{{op["op_name"] | to_pascal_case}}OpArgumentMapping);
189 190 191 192 193
{%- endmacro %}

{% macro get_input_list(inputs, kernel_args) %}{# inline #}
paddle::small_vector<const char*> inputs {
{%- for input in inputs %}
194
{%- if input["name"] in kernel_args %}
195
{{input["name"] | to_opmaker_name_cstr}}{{", " if not loop.last}}
196
{%- endif %}
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
{%- endfor %}
}
{%- endmacro %}

{% macro get_an_attr(attr) %}{# inline #}
{% set typename = attr["typename"] %}
{% set name = attr["name"] %}
{% if typename is scalar %}{# scalar correspond to a dispensable input and an attr in opmaker #}
attrs.emplace_back(
  ctx.HasInput("{{name | to_pascal_case}}")
  ? "{{name | to_pascal_case}}Tensor"
  : "{{name}}"
)
{%- elif typename == "IntArray" %}
attrs.emplace_back(
  ctx.HasInput("{{name | to_pascal_case}}Tensor")
  ? "{{name | to_pascal_case}}Tensor"
  : ctx.InputSize("{{name | to_pascal_case}}TensorList") > 0
    ? "{{name | to_pascal_case}}TensorList"
    : "{{name}}"
)
{%- else %}
attrs.emplace_back("{{name}}")
{%- endif %}
{%- endmacro %}

{% macro get_output_list(outputs, kernel_args) %}{# inline #}
paddle::small_vector<const char*> outputs {
{%- for output in outputs %}
{{output["name"] | to_opmaker_name_cstr}}{{", " if not loop.last}}
{%- endfor %}
}
{%- endmacro %}

231 232
{% macro get_expected_kernel(op) %}
{% set kernel = op["kernel"] %}
233 234 235 236 237
framework::OpKernelType GetExpectedKernelType(
    const framework::ExecutionContext& ctx) const override {
{%if kernel["data_type"] is not none %}{# data type ---------------------------------#}
  {% if kernel["data_type"]["candidates"] | length == 1 %}
    {% set data_type_arg = kernel["data_type"]["candidates"][0] %}
238
    {% set inputs = op["inputs"] | map(attribute="name") | list %}
239 240 241 242 243 244 245 246 247 248 249 250 251
    {% if data_type_arg in inputs %}
  auto data_type = framework::OperatorWithKernel::IndicateVarDataType(ctx, {{data_type_arg | to_opmaker_name}});
    {% else %}{# it is an attribute and probably named dtype#}
  auto data_type = framework::proto::VarType::Type(ctx.Attr<int>("{{data_type_arg}}"));
    {% endif %}
  {% elif kernel["data_type"]["candidates"] | length == 2 %}
    {% set data_type_args = kernel["data_type"]["candidates"] %}
  auto data_type = framework::proto::VarType::Type(ctx.Attr<int>("{{data_type_args[0]}}");
  if (data_type == static_cast<proto::VarType::Type>(-1)) {
    data_type = framework::OperatorWithKernel::IndicateVarDataType(ctx, {{data_type_args[1] | to_opmaker_name}});
  }
  {% endif %}
{% endif %}
252
  return framework::OpKernelType(data_type, ctx.GetPlace());
253 254 255
}
{% endmacro %}

256
{# --------------------------------------- operator  ---------------------------------------------- #}
257 258
{% macro operator(op) %}
class {{op["op_name"] | to_pascal_case}}Op : public framework::OperatorWithKernel {
259 260
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
261
  {# ----------- get expected kernel type function -------------------------- #}
262
  {% set kernel = op["kernel"] %}
263 264 265
  {% if kernel["data_type"] is not none %}
 protected:
  {% filter indent(2, True)%}
266
{{get_expected_kernel(op)}}
267 268
  {% endfilter %}
  {% endif %}
269 270
};

271 272
DECLARE_INFER_SHAPE_FUNCTOR({{op["op_name"]}}, {{op["op_name"] | to_pascal_case}}InferShapeFunctor,
                            PD_INFER_META(phi::{{op["infer_meta"]["func"]}}));
273
{# inplace inferer #}
274
{% if op["inplace"] is not none %}
275
  {% set inplace_map %}
276
  {% for source, target in op["inplace"].items() %}
277
{{"{"}}{{target | to_opmaker_name}}, {{source | to_opmaker_name}}{{"}"}}{{", " if not loop.last}}
278 279
  {%- endfor %}
  {%- endset %}
280
DECLARE_INPLACE_OP_INFERER({{op["op_name"] | to_pascal_case}}InplaceInferer,
281 282 283 284
                           {{inplace_map}});
{% endif %}

{# no_need_buffer inferer #}
285 286 287
{% if op["no_need_buffer"] is not none %}
DECLARE_NO_NEED_BUFFER_VARS_INFERER({{op["op_name"] | to_pascal_case}}NoNeedBufferVarInferer,
                                    {{op["no_need_buffer"] | map("to_opmaker_name") | join(", ")}});
288 289 290
{% endif %}
{% endmacro%}

291 292
{% macro register_op_with_components(op) %}
{% set name = op["op_name"] %}
293
REGISTER_OPERATOR({{name}}, ops::{{name | to_pascal_case}}Op,
294
{% if not "forward" in op %}{# it is a forward op #}
295 296
                  ops::{{name | to_pascal_case}}OpMaker,
{% endif %}
297 298
{% if "backward" in op and op["backward"] is not none %}{# backward #}
  {% set backward_name = op["backward"] %}
299 300
                  ops::{{backward_name | to_pascal_case}}OpMaker<paddle::framework::OpDesc>,
                  ops::{{backward_name | to_pascal_case}}OpMaker<paddle::imperative::OpBase>,
301 302 303
{% else %}
                  paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
                  paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
304
{% endif %}
305
{% if op is supports_inplace %}{# inplace#}
306 307
                  ops::{{name | to_pascal_case}}InplaceInferer,
{% endif %}
308
{% if op is supports_no_need_buffer %}{# no_need_buffer #}
309 310 311 312 313
                  ops::{{name | to_pascal_case}}NoNeedBufferVarInferer,
{% endif %}
                  ops::{{name | to_pascal_case}}InferShapeFunctor);
{% endmacro %}

314 315 316
{% macro register_op_version(op) %}
{% if "version" in op %}
{% set name = op["op_name"] %}
317
REGISTER_OP_VERSION({{name}})
318
  {% for checkpoint in op["version"]%}
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  .AddCheckpoint(
    R"ROC({{checkpoint["checkpoint"]}})ROC",
      paddle::framework::compatible::OpVersionDesc()
    {% for action in checkpoint["action"]%}
      {% if "add_input" in action %}
        .NewInput("{{action["add_input"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "delete_input" in action %}
        .DeleteInput("{{action["delete_input"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "modify_input" in action %}
        .ModifyInput("{{action["modify_input"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "add_output" in action %}
        .NewOutput("{{action["add_output"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "delete_output" in action %}
        .DeleteOutput("{{action["delete_output"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "modify_output" in action %}
        .ModifyOutput("{{action["modify_output"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "add_attr" in action %}
        .NewAttr("{{action["add_attr"]}}", "{{action["comment"]}}", {{action["default"]}}){{")" if loop.last}}
      {% endif %}
      {% if "delete_attr" in action %}
        .DeleteAttr("{{action["delete_attr"]}}", "{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
      {% if "fix_bug" in action %}
        .BugfixWithBehaviorChanged("{{action["comment"]}}"){{")" if loop.last}}
      {% endif %}
    {% endfor %}
  {% endfor %};
{% endif %}
{% endmacro %}

355 356

{# --------------------------------------- backward op maker ---------------------------------------------- #}
357 358 359 360 361 362 363 364
{% macro backward_op_maker(op, forward_op ) %}
  {% set name = op["op_name"] %}
  {% set forward_input_names = op["forward"]["inputs"] | map(attribute="name") | list %}
  {% set forward_output_names = op["forward"]["outputs"] | map(attribute="name") | list %}
  {% set forward_attr_names = op["forward"]["attrs"] | map(attribute="name") | list %}
  {% set forward_input_orig_names = forward_op["inputs"] | map(attribute="name") | list %}
  {% set forward_output_orig_names = forward_op["outputs"] | map(attribute="name") | list %}
  {% set forward_attr_orig_names = forward_op["attrs"] | map(attribute="name") | list %}
365 366 367 368 369 370 371 372 373
template <typename T>
class {{name | to_pascal_case}}OpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> grad_op) const override {
    grad_op->SetType("{{name}}");

374
  {% for input in op["inputs"] %}
375
    grad_op->SetInput({{input["name"] | to_opmaker_name}}, this->{{extract_input_from_forward(
376 377
      input["name"],
      forward_input_names,
378 379 380 381 382
      forward_output_names,
      forward_input_orig_names,
      forward_output_orig_names)}});
  {% endfor %}

383
  {% for output in op["outputs"] %}
384
    grad_op->SetOutput({{output["name"] | to_opmaker_name}}, this->{{extract_output_from_forward(
385 386
      output["name"],
      forward_input_names,
387 388 389 390 391
      forward_output_names,
      forward_input_orig_names,
      forward_output_orig_names)}});
  {% endfor %}

392
    grad_op->SetAttrMap(this->Attrs());
393
  {% for attr in op["attrs"] %}
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    {% set attr_name = attr["name"] %}
    {% if attr_name in forward_attr_names %}
      {% if attr["typename"] == "IntArray" %}
    grad_op->SetInput("{{attr_name | to_pascal_case}}Tensor", this->Input("{{attr_name | to_pascal_case}}Tensor"));
    grad_op->SetInput("{{attr_name | to_pascal_case}}TensorList", this->Input("{{attr_name | to_pascal_case}}TensorList"));
      {% elif attr["typename"] == "Scalar" %}
    grad_op->SetInput("{{attr_name | to_pascal_case}}Tensor", this->Input("{{attr_name | to_pascal_case}}Tensor"));
      {% endif %}
    {% else %}{# maybe something wrong: backward op has more attrs than the forward one#}
    grad_op->SetAttr("{{attr_name}}", {{process_default_value(attr)}});
    {% endif %}
  {% endfor %}
  }
};
{% endmacro %}

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
{% macro backward_op_reused_maker(bw_op, forward_op, invoke_op) %}
  {% set name = bw_op["op_name"] %}
  {% set forward_input_names = bw_op["forward"]["inputs"] | map(attribute="name") | list %}
  {% set forward_output_names = bw_op["forward"]["outputs"] | map(attribute="name") | list %}
  {% set forward_attr_names = bw_op["forward"]["attrs"] | map(attribute="name") | list %}
  {% set forward_input_orig_names = forward_op["inputs"] | map(attribute="name") | list %}
  {% set forward_output_orig_names = forward_op["outputs"] | map(attribute="name") | list %}
  {% set forward_attr_orig_names = forward_op["attrs"] | map(attribute="name") | list %}
template <typename T>
class {{name | to_pascal_case}}OpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> grad_op) const override {
    grad_op->SetType("{{invoke_op["func"]}}");

  {% for input in invoke_op["inputs"] %}
    grad_op->SetInput({{input["name"] | to_opmaker_name}}, this->{{extract_input_from_forward(
      input["value"],
      forward_input_names,
      forward_output_names,
      forward_input_orig_names,
      forward_output_orig_names)}});
  {% endfor %}

  {% for output in invoke_op["outputs"] %}
    grad_op->SetOutput({{output["name"] | to_opmaker_name}}, this->{{extract_output_from_forward(
      output["value"],
      forward_input_names,
      forward_output_names,
      forward_input_orig_names,
      forward_output_orig_names)}});
  {% endfor %}

  {% for attr in invoke_op["attrs"] %}
    grad_op->SetAttr("{{attr["name"]}}", {{attr["value"]}});
  {% endfor %}
  }
};
{% endmacro %}

452

453 454
{% macro extract_input_from_forward(name,
  input_names, output_names,
455 456 457
  input_orig_names, output_orig_names) %}{# inline #}
  {% if name in input_names %}
    {% set name_in_forward_orig = input_orig_names[input_names.index(name)]%}
458
Input({{name_in_forward_orig | to_opmaker_name}})
459 460
  {%- elif name in output_names %}
    {% set name_in_forward_orig = output_orig_names[output_names.index(name)]%}
461
Output({{name_in_forward_orig | to_opmaker_name}})
462
  {%- elif name.endswith("_grad") %}{# output grad#}
463
    {% set name_in_forward = name[:-5] %}
464 465
    {% if name_in_forward in output_names %}
      {% set name_in_forward_orig = output_orig_names[output_names.index(name_in_forward)] %}
466
OutputGrad({{name_in_forward_orig | to_opmaker_name}})
467 468 469 470 471 472
    {%- endif %}
  {%- endif %}
{%- endmacro %}

{% macro extract_output_from_forward(name, input_names, output_names,
  input_orig_names, output_orig_names) %}{# inline #}
473 474
  {% if name[:-5] in input_names %}
    {% set name_in_forward = name[:-5] %}
475
    {% set name_in_forward_orig = input_orig_names[input_names.index(name_in_forward)]%}
476
InputGrad({{name_in_forward_orig | to_opmaker_name}})
477 478 479
  {%- elif (name | to_input_name) in input_names %}
    {% set name_in_forward = name | to_input_name %}
    {% set name_in_forward_orig = input_orig_names[input_names.index(name_in_forward)]%}
480
InputGrad({{name | to_input_name | to_opmaker_name}})
481 482 483 484 485 486
  {%- endif %}
{%- endmacro %}

{% macro extract_attr_from_forward(name, attr_names, attr_origin_names) %}
this->GetAttr("{{name}}")
{%- endmacro %}