• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // Class and associated machinery for specifying an Op's OpDef and shape
17 // inference function for Op registration.
18 
19 #ifndef TENSORFLOW_CORE_FRAMEWORK_OP_DEF_BUILDER_H_
20 #define TENSORFLOW_CORE_FRAMEWORK_OP_DEF_BUILDER_H_
21 
22 #include <string>
23 #include <vector>
24 
25 #include "tensorflow/core/framework/op_def.pb.h"
26 #include "tensorflow/core/lib/core/status.h"
27 #include "tensorflow/core/lib/core/stringpiece.h"
28 #include "tensorflow/core/platform/macros.h"
29 
30 namespace tensorflow {
31 
32 typedef std::function<Status(OpDef* c)> OpTypeConstructor;
33 
34 class FunctionDefHelper;
35 
36 namespace shape_inference {
37 class InferenceContext;
38 }
39 typedef std::function<Status(shape_inference::InferenceContext* c)>
40     OpShapeInferenceFn;
41 
42 struct OpRegistrationData {
43  public:
OpRegistrationDataOpRegistrationData44   OpRegistrationData() {}
OpRegistrationDataOpRegistrationData45   OpRegistrationData(const OpDef& def) : op_def(def) {}
46   OpRegistrationData(const OpDef& def, const OpShapeInferenceFn& fn,
47                      bool is_function = false)
op_defOpRegistrationData48       : op_def(def), shape_inference_fn(fn), is_function_op(is_function) {}
49 
50   OpDef op_def;
51   OpShapeInferenceFn shape_inference_fn;
52 
53   // Type constructor. This callable initializes the type of this op.
54   // It is provided as a programmatic mechanism for defining an op's
55   // type, as part of its registration. It is to be eventually replaced by a
56   // textual language.
57   //
58   // Important: historically, op registrations only contained partial
59   // input/output type information in non-standardized attribute declarations
60   // (e.g. typically, input types were held in a `dtype` attribute). The type
61   // constructor currently duplicates such attribute information, with the aim
62   // of entirely subsuming it, and eventually deprecating all type-related
63   // attributes.
64   //
65   // Since ops are typically parametrized, the type created by this constructor
66   // is also parametric.
67   //
68   // Example: for an op `Foo(x: T) -> Bar[T]`:
69   //
70   //  * typically, its op registration included a single attribute `T: type`;
71   //    then the respective input was defined as `x: T`; the output type `Bar`
72   //    was implied by the op name.
73   //  * the type constructor creates a FullType object containing `Bar[T]`; this
74   //    still relies on the `T` attribute which it references.
75   //  * in the future, the type constructor will create a FullType containing
76   //    `Callable[(x: T), Bar[T]]`, and the attribute `T` will be deprecated.
77   OpTypeConstructor type_ctor;
78 
79   bool is_function_op = false;
80 };
81 
82 // Builder class passed to the REGISTER_OP() macro.
83 class OpDefBuilder {
84  public:
85   // Constructs an OpDef with just the name field set.
86   explicit OpDefBuilder(std::string op_name);
87 
88   // Adds an attr to this OpDefBuilder (and returns *this). The spec has
89   // format "<name>:<type>" or "<name>:<type>=<default>"
90   // where <name> matches regexp [a-zA-Z][a-zA-Z0-9_]*
91   // (by convention only using capital letters for attrs that can be inferred)
92   // <type> can be:
93   //   "string", "int", "float", "bool", "type", "shape", or "tensor"
94   //   "numbertype", "realnumbertype", "quantizedtype"
95   //       (meaning "type" with a restriction on valid values)
96   //   "{int32,int64}" or {realnumbertype,quantizedtype,string}"
97   //       (meaning "type" with a restriction containing unions of value types)
98   //   "{\"foo\", \"bar\n baz\"}", or "{'foo', 'bar\n baz'}"
99   //       (meaning "string" with a restriction on valid values)
100   //   "list(string)", ..., "list(tensor)", "list(numbertype)", ...
101   //       (meaning lists of the above types)
102   //   "int >= 2" (meaning "int" with a restriction on valid values)
103   //   "list(string) >= 2", "list(int) >= 2"
104   //       (meaning "list(string)" / "list(int)" with length at least 2)
105   // <default>, if included, should use the Proto text format
106   // of <type>.  For lists use [a, b, c] format.
107   //
108   // Note that any attr specifying the length of an input or output will
109   // get a default minimum of 1 unless the >= # syntax is used.
110   //
111   // TODO(josh11b): Perhaps support restrictions and defaults as optional
112   // extra arguments to Attr() instead of encoding them in the spec string.
113   // TODO(josh11b): Would like to have better dtype handling for tensor attrs:
114   // * Ability to say the type of an input/output matches the type of
115   //   the tensor.
116   // * Ability to restrict the type of the tensor like the existing
117   //   restrictions for type attrs.
118   // Perhaps by linking the type of the tensor to a type attr?
119   OpDefBuilder& Attr(std::string spec);
120 
121   // Adds an input or output to this OpDefBuilder (and returns *this).
122   // The spec has form "<name>:<type-expr>" or "<name>:Ref(<type-expr>)"
123   // where <name> matches regexp [a-z][a-z0-9_]* and <type-expr> can be:
124   // * For a single tensor: <type>
125   // * For a sequence of tensors with the same type: <number>*<type>
126   // * For a sequence of tensors with different types: <type-list>
127   // Where:
128   //   <type> is either one of "float", "int32", "string", ...
129   //                 or the name of an attr (see above) with type "type".
130   //   <number> is the name of an attr with type "int".
131   //   <type-list> is the name of an attr with type "list(type)".
132   // TODO(josh11b): Indicate Ref() via an optional argument instead of
133   // in the spec?
134   // TODO(josh11b): SparseInput() and SparseOutput() matching the Python
135   // handling?
136   OpDefBuilder& Input(std::string spec);
137   OpDefBuilder& Output(std::string spec);
138 
139   // Turns on the indicated boolean flag in this OpDefBuilder (and
140   // returns *this).
141   OpDefBuilder& SetIsCommutative();
142   OpDefBuilder& SetIsAggregate();
143   OpDefBuilder& SetIsStateful();
144   OpDefBuilder& SetAllowsUninitializedInput();
145   OpDefBuilder& SetIsDistributedCommunication();
146 
147   // Deprecate the op at a certain GraphDef version.
148   OpDefBuilder& Deprecated(int version, std::string explanation);
149 
150   // Adds docs to this OpDefBuilder (and returns *this).
151   // Docs have the format:
152   //   <1-line summary>
153   //   <rest of the description>
154   //   <name>: <description of name>
155   //   <name>: <description of name>
156   //     <if long, indent the description on subsequent lines>
157   // Where <name> is the name of an attr, input, or output.  Please
158   // wrap docs at 72 columns so that it may be indented in the
159   // generated output.  For tensor inputs or outputs (not attrs), you
160   // may start the description with an "=" (like name:= <description>)
161   // to suppress the automatically-generated type documentation in
162   // generated output.
163 #ifndef TF_LEAN_BINARY
164   OpDefBuilder& Doc(std::string text);
165 #else
Doc(string text)166   OpDefBuilder& Doc(string text) { return *this; }
167 #endif
168 
169   // Sets the function to be used as type constructor. Type constructors are
170   // called just before a graph node is finalized, which also happens before
171   // shape inference.
172   OpDefBuilder& SetTypeConstructor(OpTypeConstructor c);
173 
174   // Sets the shape function to be used for shape inference.
175   //
176   // Note that currently (October 2016), python code still requires a
177   // RegisterShape call to invoke this; see call_cpp_shape_fn in
178   // python/framework/common_shapes.py
179   OpDefBuilder& SetShapeFn(OpShapeInferenceFn fn);
180 
181   // Allows the `<type>` in calls to `Attr()` to be "any".
182   // This is used by PythonAPIWrapper for pass-through parameters.
183   OpDefBuilder& AllowAttrTypeAny();
184 
185   // Sets op_reg_data->op_def to the requested OpDef and
186   // op_reg_data->shape_inference_fn to the requested shape inference function,
187   // or returns an error.
188   // Must be called after all of the above methods.
189   //
190   // Note that OpDefBuilder only reports parsing errors.  You should also
191   // call ValidateOpDef() to detect other problems.
192   Status Finalize(OpRegistrationData* op_reg_data) const;
193 
194  private:
195   friend class FunctionDefHelper;
196 
197   // Adds control output to this OpDefBuilder (and returns *this).
198   // The <name> must be a valid node name (matches regexp
199   // [a-zA-Z][a-zA-Z0-9_]*). Named control output can only exist for functions.
200   OpDefBuilder& ControlOutput(std::string name);
201 
op_def()202   OpDef* op_def() { return &op_reg_data_.op_def; }
203 
204   OpRegistrationData op_reg_data_;
205   std::vector<string> attrs_;
206   std::vector<string> inputs_;
207   std::vector<string> outputs_;
208   std::vector<string> control_outputs_;
209   std::string doc_;
210   std::vector<string> errors_;
211   bool allow_attr_type_any_ = false;
212 };
213 
214 }  // namespace tensorflow
215 
216 #endif  // TENSORFLOW_CORE_FRAMEWORK_OP_DEF_BUILDER_H_
217