c_api.h 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #ifndef TENSORFLOW_C_C_API_H_
  13. #define TENSORFLOW_C_C_API_H_
  14. #include <stddef.h>
  15. #include <stdint.h>
  16. #include "tensorflow/c/tf_attrtype.h"
  17. #include "tensorflow/c/tf_datatype.h"
  18. #include "tensorflow/c/tf_status.h"
  19. #include "tensorflow/c/tf_tensor.h"
  20. #include "tensorflow/c/tf_tstring.h"
  21. // --------------------------------------------------------------------------
  22. // C API for TensorFlow.
  23. //
  24. // The API leans towards simplicity and uniformity instead of convenience
  25. // since most usage will be by language specific wrappers.
  26. //
  27. // Conventions:
  28. // * We use the prefix TF_ for everything in the API.
  29. // * Objects are always passed around as pointers to opaque structs
  30. // and these structs are allocated/deallocated via the API.
  31. // * TF_Status holds error information. It is an object type
  32. // and therefore is passed around as a pointer to an opaque
  33. // struct as mentioned above.
  34. // * Every call that has a TF_Status* argument clears it on success
  35. // and fills it with error info on failure.
  36. // * unsigned char is used for booleans (instead of the 'bool' type).
  37. // In C++ bool is a keyword while in C99 bool is a macro defined
  38. // in stdbool.h. It is possible for the two to be inconsistent.
  39. // For example, neither the C99 nor the C++11 standard force a byte
  40. // size on the bool type, so the macro defined in stdbool.h could
  41. // be inconsistent with the bool keyword in C++. Thus, the use
  42. // of stdbool.h is avoided and unsigned char is used instead.
  43. // * size_t is used to represent byte sizes of objects that are
  44. // materialized in the address space of the calling process.
  45. // * int is used as an index into arrays.
  46. // * Deletion functions are safe to call on nullptr.
  47. //
  48. // Questions left to address:
  49. // * Might at some point need a way for callers to provide their own Env.
  50. // * Maybe add TF_TensorShape that encapsulates dimension info.
  51. //
  52. // Design decisions made:
  53. // * Backing store for tensor memory has an associated deallocation
  54. // function. This deallocation function will point to client code
  55. // for tensors populated by the client. So the client can do things
  56. // like shadowing a numpy array.
  57. // * We do not provide TF_OK since it is not strictly necessary and we
  58. // are not optimizing for convenience.
  59. // * We make assumption that one session has one graph. This should be
  60. // fine since we have the ability to run sub-graphs.
  61. // * We could allow NULL for some arguments (e.g., NULL options arg).
  62. // However since convenience is not a primary goal, we don't do this.
  63. // * Devices are not in this API. Instead, they are created/used internally
  64. // and the API just provides high level controls over the number of
  65. // devices of each type.
  66. // Macro to control visibility of exported symbols in the shared library (.so,
  67. // .dylib, .dll).
  68. // This duplicates the TF_EXPORT macro definition in
  69. // tensorflow/core/platform/macros.h in order to keep this .h file independent
  70. // of any other includes.
  71. #ifdef SWIG
  72. #define TF_CAPI_EXPORT
  73. #else
  74. #if defined(_WIN32)
  75. #ifdef TF_COMPILE_LIBRARY
  76. #define TF_CAPI_EXPORT __declspec(dllexport)
  77. #else
  78. #define TF_CAPI_EXPORT __declspec(dllimport)
  79. #endif // TF_COMPILE_LIBRARY
  80. #else
  81. #define TF_CAPI_EXPORT __attribute__((visibility("default")))
  82. #endif // _WIN32
  83. #endif // SWIG
  84. #ifdef __cplusplus
  85. extern "C" {
  86. #endif
  87. // --------------------------------------------------------------------------
  88. // TF_Version returns a string describing version information of the
  89. // TensorFlow library. TensorFlow using semantic versioning.
  90. TF_CAPI_EXPORT extern const char* TF_Version(void);
  91. // --------------------------------------------------------------------------
  92. // TF_Buffer holds a pointer to a block of data and its associated length.
  93. // Typically, the data consists of a serialized protocol buffer, but other data
  94. // may also be held in a buffer.
  95. //
  96. // By default, TF_Buffer itself does not do any memory management of the
  97. // pointed-to block. If need be, users of this struct should specify how to
  98. // deallocate the block by setting the `data_deallocator` function pointer.
  99. typedef struct TF_Buffer {
  100. const void* data;
  101. size_t length;
  102. void (*data_deallocator)(void* data, size_t length);
  103. } TF_Buffer;
  104. // Makes a copy of the input and sets an appropriate deallocator. Useful for
  105. // passing in read-only, input protobufs.
  106. TF_CAPI_EXPORT extern TF_Buffer* TF_NewBufferFromString(const void* proto,
  107. size_t proto_len);
  108. // Useful for passing *out* a protobuf.
  109. TF_CAPI_EXPORT extern TF_Buffer* TF_NewBuffer(void);
  110. TF_CAPI_EXPORT extern void TF_DeleteBuffer(TF_Buffer*);
  111. TF_CAPI_EXPORT extern TF_Buffer TF_GetBuffer(TF_Buffer* buffer);
  112. // --------------------------------------------------------------------------
  113. // Used to return strings across the C API. The caller does not take ownership
  114. // of the underlying data pointer and is not responsible for freeing it.
  115. typedef struct TF_StringView {
  116. const char* data;
  117. size_t len;
  118. } TF_StringView;
  119. // --------------------------------------------------------------------------
  120. // TF_SessionOptions holds options that can be passed during session creation.
  121. typedef struct TF_SessionOptions TF_SessionOptions;
  122. // Return a new options object.
  123. TF_CAPI_EXPORT extern TF_SessionOptions* TF_NewSessionOptions(void);
  124. // Set the target in TF_SessionOptions.options.
  125. // target can be empty, a single entry, or a comma separated list of entries.
  126. // Each entry is in one of the following formats :
  127. // "local"
  128. // ip:port
  129. // host:port
  130. TF_CAPI_EXPORT extern void TF_SetTarget(TF_SessionOptions* options,
  131. const char* target);
  132. // Set the config in TF_SessionOptions.options.
  133. // config should be a serialized tensorflow.ConfigProto proto.
  134. // If config was not parsed successfully as a ConfigProto, record the
  135. // error information in *status.
  136. TF_CAPI_EXPORT extern void TF_SetConfig(TF_SessionOptions* options,
  137. const void* proto, size_t proto_len,
  138. TF_Status* status);
  139. // Destroy an options object.
  140. TF_CAPI_EXPORT extern void TF_DeleteSessionOptions(TF_SessionOptions*);
  141. // TODO(jeff,sanjay):
  142. // - export functions to set Config fields
  143. // --------------------------------------------------------------------------
  144. // The new graph construction API, still under development.
  145. // Represents a computation graph. Graphs may be shared between sessions.
  146. // Graphs are thread-safe when used as directed below.
  147. typedef struct TF_Graph TF_Graph;
  148. // Return a new graph object.
  149. TF_CAPI_EXPORT extern TF_Graph* TF_NewGraph(void);
  150. // Destroy an options object. Graph will be deleted once no more
  151. // TFSession's are referencing it.
  152. TF_CAPI_EXPORT extern void TF_DeleteGraph(TF_Graph*);
  153. // Operation being built. The underlying graph must outlive this.
  154. typedef struct TF_OperationDescription TF_OperationDescription;
  155. // Operation that has been added to the graph. Valid until the graph is
  156. // deleted -- in particular adding a new operation to the graph does not
  157. // invalidate old TF_Operation* pointers.
  158. typedef struct TF_Operation TF_Operation;
  159. // Represents a specific input of an operation.
  160. typedef struct TF_Input {
  161. TF_Operation* oper;
  162. int index; // The index of the input within oper.
  163. } TF_Input;
  164. // Represents a specific output of an operation.
  165. typedef struct TF_Output {
  166. TF_Operation* oper;
  167. int index; // The index of the output within oper.
  168. } TF_Output;
  169. // TF_Function is a grouping of operations with defined inputs and outputs.
  170. // Once created and added to graphs, functions can be invoked by creating an
  171. // operation whose operation type matches the function name.
  172. typedef struct TF_Function TF_Function;
  173. // Function definition options. TODO(iga): Define and implement
  174. typedef struct TF_FunctionOptions TF_FunctionOptions;
  175. // Sets the shape of the Tensor referenced by `output` in `graph` to
  176. // the shape described by `dims` and `num_dims`.
  177. //
  178. // If the number of dimensions is unknown, `num_dims` must be set to
  179. // -1 and `dims` can be null. If a dimension is unknown, the
  180. // corresponding entry in the `dims` array must be -1.
  181. //
  182. // This does not overwrite the existing shape associated with `output`,
  183. // but merges the input shape with the existing shape. For example,
  184. // setting a shape of [-1, 2] with an existing shape [2, -1] would set
  185. // a final shape of [2, 2] based on shape merging semantics.
  186. //
  187. // Returns an error into `status` if:
  188. // * `output` is not in `graph`.
  189. // * An invalid shape is being set (e.g., the shape being set
  190. // is incompatible with the existing shape).
  191. TF_CAPI_EXPORT extern void TF_GraphSetTensorShape(TF_Graph* graph,
  192. TF_Output output,
  193. const int64_t* dims,
  194. const int num_dims,
  195. TF_Status* status);
  196. // Returns the number of dimensions of the Tensor referenced by `output`
  197. // in `graph`.
  198. //
  199. // If the number of dimensions in the shape is unknown, returns -1.
  200. //
  201. // Returns an error into `status` if:
  202. // * `output` is not in `graph`.
  203. TF_CAPI_EXPORT extern int TF_GraphGetTensorNumDims(TF_Graph* graph,
  204. TF_Output output,
  205. TF_Status* status);
  206. // Returns the shape of the Tensor referenced by `output` in `graph`
  207. // into `dims`. `dims` must be an array large enough to hold `num_dims`
  208. // entries (e.g., the return value of TF_GraphGetTensorNumDims).
  209. //
  210. // If the number of dimensions in the shape is unknown or the shape is
  211. // a scalar, `dims` will remain untouched. Otherwise, each element of
  212. // `dims` will be set corresponding to the size of the dimension. An
  213. // unknown dimension is represented by `-1`.
  214. //
  215. // Returns an error into `status` if:
  216. // * `output` is not in `graph`.
  217. // * `num_dims` does not match the actual number of dimensions.
  218. TF_CAPI_EXPORT extern void TF_GraphGetTensorShape(TF_Graph* graph,
  219. TF_Output output,
  220. int64_t* dims, int num_dims,
  221. TF_Status* status);
  222. // Operation will only be added to *graph when TF_FinishOperation() is
  223. // called (assuming TF_FinishOperation() does not return an error).
  224. // *graph must not be deleted until after TF_FinishOperation() is
  225. // called.
  226. TF_CAPI_EXPORT extern TF_OperationDescription* TF_NewOperation(
  227. TF_Graph* graph, const char* op_type, const char* oper_name);
  228. // Specify the device for `desc`. Defaults to empty, meaning unconstrained.
  229. TF_CAPI_EXPORT extern void TF_SetDevice(TF_OperationDescription* desc,
  230. const char* device);
  231. // The calls to TF_AddInput and TF_AddInputList must match (in number,
  232. // order, and type) the op declaration. For example, the "Concat" op
  233. // has registration:
  234. // REGISTER_OP("Concat")
  235. // .Input("concat_dim: int32")
  236. // .Input("values: N * T")
  237. // .Output("output: T")
  238. // .Attr("N: int >= 2")
  239. // .Attr("T: type");
  240. // that defines two inputs, "concat_dim" and "values" (in that order).
  241. // You must use TF_AddInput() for the first input (since it takes a
  242. // single tensor), and TF_AddInputList() for the second input (since
  243. // it takes a list, even if you were to pass a list with a single
  244. // tensor), as in:
  245. // TF_OperationDescription* desc = TF_NewOperation(graph, "Concat", "c");
  246. // TF_Output concat_dim_input = {...};
  247. // TF_AddInput(desc, concat_dim_input);
  248. // TF_Output values_inputs[5] = {{...}, ..., {...}};
  249. // TF_AddInputList(desc, values_inputs, 5);
  250. // For inputs that take a single tensor.
  251. TF_CAPI_EXPORT extern void TF_AddInput(TF_OperationDescription* desc,
  252. TF_Output input);
  253. // For inputs that take a list of tensors.
  254. // inputs must point to TF_Output[num_inputs].
  255. TF_CAPI_EXPORT extern void TF_AddInputList(TF_OperationDescription* desc,
  256. const TF_Output* inputs,
  257. int num_inputs);
  258. // Call once per control input to `desc`.
  259. TF_CAPI_EXPORT extern void TF_AddControlInput(TF_OperationDescription* desc,
  260. TF_Operation* input);
  261. // Request that `desc` be co-located on the device where `op`
  262. // is placed.
  263. //
  264. // Use of this is discouraged since the implementation of device placement is
  265. // subject to change. Primarily intended for internal libraries
  266. TF_CAPI_EXPORT extern void TF_ColocateWith(TF_OperationDescription* desc,
  267. TF_Operation* op);
  268. // Call some TF_SetAttr*() function for every attr that is not
  269. // inferred from an input and doesn't have a default value you wish to
  270. // keep.
  271. // `value` must point to a string of length `length` bytes.
  272. TF_CAPI_EXPORT extern void TF_SetAttrString(TF_OperationDescription* desc,
  273. const char* attr_name,
  274. const void* value, size_t length);
  275. // `values` and `lengths` each must have lengths `num_values`.
  276. // `values[i]` must point to a string of length `lengths[i]` bytes.
  277. TF_CAPI_EXPORT extern void TF_SetAttrStringList(TF_OperationDescription* desc,
  278. const char* attr_name,
  279. const void* const* values,
  280. const size_t* lengths,
  281. int num_values);
  282. TF_CAPI_EXPORT extern void TF_SetAttrInt(TF_OperationDescription* desc,
  283. const char* attr_name, int64_t value);
  284. TF_CAPI_EXPORT extern void TF_SetAttrIntList(TF_OperationDescription* desc,
  285. const char* attr_name,
  286. const int64_t* values,
  287. int num_values);
  288. TF_CAPI_EXPORT extern void TF_SetAttrFloat(TF_OperationDescription* desc,
  289. const char* attr_name, float value);
  290. TF_CAPI_EXPORT extern void TF_SetAttrFloatList(TF_OperationDescription* desc,
  291. const char* attr_name,
  292. const float* values,
  293. int num_values);
  294. TF_CAPI_EXPORT extern void TF_SetAttrBool(TF_OperationDescription* desc,
  295. const char* attr_name,
  296. unsigned char value);
  297. TF_CAPI_EXPORT extern void TF_SetAttrBoolList(TF_OperationDescription* desc,
  298. const char* attr_name,
  299. const unsigned char* values,
  300. int num_values);
  301. TF_CAPI_EXPORT extern void TF_SetAttrType(TF_OperationDescription* desc,
  302. const char* attr_name,
  303. TF_DataType value);
  304. TF_CAPI_EXPORT extern void TF_SetAttrTypeList(TF_OperationDescription* desc,
  305. const char* attr_name,
  306. const TF_DataType* values,
  307. int num_values);
  308. TF_CAPI_EXPORT extern void TF_SetAttrPlaceholder(TF_OperationDescription* desc,
  309. const char* attr_name,
  310. const char* placeholder);
  311. // Set a 'func' attribute to the specified name.
  312. // `value` must point to a string of length `length` bytes.
  313. TF_CAPI_EXPORT extern void TF_SetAttrFuncName(TF_OperationDescription* desc,
  314. const char* attr_name,
  315. const char* value, size_t length);
  316. // Set `num_dims` to -1 to represent "unknown rank". Otherwise,
  317. // `dims` points to an array of length `num_dims`. `dims[i]` must be
  318. // >= -1, with -1 meaning "unknown dimension".
  319. TF_CAPI_EXPORT extern void TF_SetAttrShape(TF_OperationDescription* desc,
  320. const char* attr_name,
  321. const int64_t* dims, int num_dims);
  322. // `dims` and `num_dims` must point to arrays of length `num_shapes`.
  323. // Set `num_dims[i]` to -1 to represent "unknown rank". Otherwise,
  324. // `dims[i]` points to an array of length `num_dims[i]`. `dims[i][j]`
  325. // must be >= -1, with -1 meaning "unknown dimension".
  326. TF_CAPI_EXPORT extern void TF_SetAttrShapeList(TF_OperationDescription* desc,
  327. const char* attr_name,
  328. const int64_t* const* dims,
  329. const int* num_dims,
  330. int num_shapes);
  331. // `proto` must point to an array of `proto_len` bytes representing a
  332. // binary-serialized TensorShapeProto.
  333. TF_CAPI_EXPORT extern void TF_SetAttrTensorShapeProto(
  334. TF_OperationDescription* desc, const char* attr_name, const void* proto,
  335. size_t proto_len, TF_Status* status);
  336. // `protos` and `proto_lens` must point to arrays of length `num_shapes`.
  337. // `protos[i]` must point to an array of `proto_lens[i]` bytes
  338. // representing a binary-serialized TensorShapeProto.
  339. TF_CAPI_EXPORT extern void TF_SetAttrTensorShapeProtoList(
  340. TF_OperationDescription* desc, const char* attr_name,
  341. const void* const* protos, const size_t* proto_lens, int num_shapes,
  342. TF_Status* status);
  343. TF_CAPI_EXPORT extern void TF_SetAttrTensor(TF_OperationDescription* desc,
  344. const char* attr_name,
  345. TF_Tensor* value,
  346. TF_Status* status);
  347. TF_CAPI_EXPORT extern void TF_SetAttrTensorList(TF_OperationDescription* desc,
  348. const char* attr_name,
  349. TF_Tensor* const* values,
  350. int num_values,
  351. TF_Status* status);
  352. // `proto` should point to a sequence of bytes of length `proto_len`
  353. // representing a binary serialization of an AttrValue protocol
  354. // buffer.
  355. TF_CAPI_EXPORT extern void TF_SetAttrValueProto(TF_OperationDescription* desc,
  356. const char* attr_name,
  357. const void* proto,
  358. size_t proto_len,
  359. TF_Status* status);
  360. // If this function succeeds:
  361. // * *status is set to an OK value,
  362. // * a TF_Operation is added to the graph,
  363. // * a non-null value pointing to the added operation is returned --
  364. // this value is valid until the underlying graph is deleted.
  365. // Otherwise:
  366. // * *status is set to a non-OK value,
  367. // * the graph is not modified,
  368. // * a null value is returned.
  369. // In either case, it deletes `desc`.
  370. TF_CAPI_EXPORT extern TF_Operation* TF_FinishOperation(
  371. TF_OperationDescription* desc, TF_Status* status);
  372. // TF_Operation functions. Operations are immutable once created, so
  373. // these are all query functions.
  374. TF_CAPI_EXPORT extern const char* TF_OperationName(TF_Operation* oper);
  375. TF_CAPI_EXPORT extern const char* TF_OperationOpType(TF_Operation* oper);
  376. TF_CAPI_EXPORT extern const char* TF_OperationDevice(TF_Operation* oper);
  377. TF_CAPI_EXPORT extern int TF_OperationNumOutputs(TF_Operation* oper);
  378. TF_CAPI_EXPORT extern TF_DataType TF_OperationOutputType(TF_Output oper_out);
  379. TF_CAPI_EXPORT extern int TF_OperationOutputListLength(TF_Operation* oper,
  380. const char* arg_name,
  381. TF_Status* status);
  382. TF_CAPI_EXPORT extern int TF_OperationNumInputs(TF_Operation* oper);
  383. TF_CAPI_EXPORT extern TF_DataType TF_OperationInputType(TF_Input oper_in);
  384. TF_CAPI_EXPORT extern int TF_OperationInputListLength(TF_Operation* oper,
  385. const char* arg_name,
  386. TF_Status* status);
  387. // In this code:
  388. // TF_Output producer = TF_OperationInput(consumer);
  389. // There is an edge from producer.oper's output (given by
  390. // producer.index) to consumer.oper's input (given by consumer.index).
  391. TF_CAPI_EXPORT extern TF_Output TF_OperationInput(TF_Input oper_in);
  392. // Get list of all inputs of a specific operation. `inputs` must point to
  393. // an array of length at least `max_inputs` (ideally set to
  394. // TF_OperationNumInputs(oper)). Beware that a concurrent
  395. // modification of the graph can increase the number of inputs of
  396. // an operation.
  397. TF_CAPI_EXPORT extern void TF_OperationAllInputs(TF_Operation* oper,
  398. TF_Output* inputs,
  399. int max_inputs);
  400. // Get the number of current consumers of a specific output of an
  401. // operation. Note that this number can change when new operations
  402. // are added to the graph.
  403. TF_CAPI_EXPORT extern int TF_OperationOutputNumConsumers(TF_Output oper_out);
  404. // Get list of all current consumers of a specific output of an
  405. // operation. `consumers` must point to an array of length at least
  406. // `max_consumers` (ideally set to
  407. // TF_OperationOutputNumConsumers(oper_out)). Beware that a concurrent
  408. // modification of the graph can increase the number of consumers of
  409. // an operation. Returns the number of output consumers (should match
  410. // TF_OperationOutputNumConsumers(oper_out)).
  411. TF_CAPI_EXPORT extern int TF_OperationOutputConsumers(TF_Output oper_out,
  412. TF_Input* consumers,
  413. int max_consumers);
  414. // Get the number of control inputs to an operation.
  415. TF_CAPI_EXPORT extern int TF_OperationNumControlInputs(TF_Operation* oper);
  416. // Get list of all control inputs to an operation. `control_inputs` must
  417. // point to an array of length `max_control_inputs` (ideally set to
  418. // TF_OperationNumControlInputs(oper)). Returns the number of control
  419. // inputs (should match TF_OperationNumControlInputs(oper)).
  420. TF_CAPI_EXPORT extern int TF_OperationGetControlInputs(
  421. TF_Operation* oper, TF_Operation** control_inputs, int max_control_inputs);
  422. // Get the number of operations that have `*oper` as a control input.
  423. // Note that this number can change when new operations are added to
  424. // the graph.
  425. TF_CAPI_EXPORT extern int TF_OperationNumControlOutputs(TF_Operation* oper);
  426. // Get the list of operations that have `*oper` as a control input.
  427. // `control_outputs` must point to an array of length at least
  428. // `max_control_outputs` (ideally set to
  429. // TF_OperationNumControlOutputs(oper)). Beware that a concurrent
  430. // modification of the graph can increase the number of control
  431. // outputs. Returns the number of control outputs (should match
  432. // TF_OperationNumControlOutputs(oper)).
  433. TF_CAPI_EXPORT extern int TF_OperationGetControlOutputs(
  434. TF_Operation* oper, TF_Operation** control_outputs,
  435. int max_control_outputs);
  436. // TF_AttrMetadata describes the value of an attribute on an operation.
  437. typedef struct TF_AttrMetadata {
  438. // A boolean: 1 if the attribute value is a list, 0 otherwise.
  439. unsigned char is_list;
  440. // Length of the list if is_list is true. Undefined otherwise.
  441. int64_t list_size;
  442. // Type of elements of the list if is_list != 0.
  443. // Type of the single value stored in the attribute if is_list == 0.
  444. TF_AttrType type;
  445. // Total size the attribute value.
  446. // The units of total_size depend on is_list and type.
  447. // (1) If type == TF_ATTR_STRING and is_list == 0
  448. // then total_size is the byte size of the string
  449. // valued attribute.
  450. // (2) If type == TF_ATTR_STRING and is_list == 1
  451. // then total_size is the cumulative byte size
  452. // of all the strings in the list.
  453. // (3) If type == TF_ATTR_SHAPE and is_list == 0
  454. // then total_size is the number of dimensions
  455. // of the shape valued attribute, or -1
  456. // if its rank is unknown.
  457. // (4) If type == TF_ATTR_SHAPE and is_list == 1
  458. // then total_size is the cumulative number
  459. // of dimensions of all shapes in the list.
  460. // (5) Otherwise, total_size is undefined.
  461. int64_t total_size;
  462. } TF_AttrMetadata;
  463. // Returns metadata about the value of the attribute `attr_name` of `oper`.
  464. TF_CAPI_EXPORT extern TF_AttrMetadata TF_OperationGetAttrMetadata(
  465. TF_Operation* oper, const char* attr_name, TF_Status* status);
  466. // Fills in `value` with the value of the attribute `attr_name`. `value` must
  467. // point to an array of length at least `max_length` (ideally set to
  468. // TF_AttrMetadata.total_size from TF_OperationGetAttrMetadata(oper,
  469. // attr_name)).
  470. TF_CAPI_EXPORT extern void TF_OperationGetAttrString(TF_Operation* oper,
  471. const char* attr_name,
  472. void* value,
  473. size_t max_length,
  474. TF_Status* status);
  475. // Get the list of strings in the value of the attribute `attr_name`. Fills in
  476. // `values` and `lengths`, each of which must point to an array of length at
  477. // least `max_values`.
  478. //
  479. // The elements of values will point to addresses in `storage` which must be at
  480. // least `storage_size` bytes in length. Ideally, max_values would be set to
  481. // TF_AttrMetadata.list_size and `storage` would be at least
  482. // TF_AttrMetadata.total_size, obtained from TF_OperationGetAttrMetadata(oper,
  483. // attr_name).
  484. //
  485. // Fails if storage_size is too small to hold the requested number of strings.
  486. TF_CAPI_EXPORT extern void TF_OperationGetAttrStringList(
  487. TF_Operation* oper, const char* attr_name, void** values, size_t* lengths,
  488. int max_values, void* storage, size_t storage_size, TF_Status* status);
  489. TF_CAPI_EXPORT extern void TF_OperationGetAttrInt(TF_Operation* oper,
  490. const char* attr_name,
  491. int64_t* value,
  492. TF_Status* status);
  493. // Fills in `values` with the value of the attribute `attr_name` of `oper`.
  494. // `values` must point to an array of length at least `max_values` (ideally set
  495. // TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper,
  496. // attr_name)).
  497. TF_CAPI_EXPORT extern void TF_OperationGetAttrIntList(TF_Operation* oper,
  498. const char* attr_name,
  499. int64_t* values,
  500. int max_values,
  501. TF_Status* status);
  502. TF_CAPI_EXPORT extern void TF_OperationGetAttrFloat(TF_Operation* oper,
  503. const char* attr_name,
  504. float* value,
  505. TF_Status* status);
  506. // Fills in `values` with the value of the attribute `attr_name` of `oper`.
  507. // `values` must point to an array of length at least `max_values` (ideally set
  508. // to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper,
  509. // attr_name)).
  510. TF_CAPI_EXPORT extern void TF_OperationGetAttrFloatList(TF_Operation* oper,
  511. const char* attr_name,
  512. float* values,
  513. int max_values,
  514. TF_Status* status);
  515. TF_CAPI_EXPORT extern void TF_OperationGetAttrBool(TF_Operation* oper,
  516. const char* attr_name,
  517. unsigned char* value,
  518. TF_Status* status);
  519. // Fills in `values` with the value of the attribute `attr_name` of `oper`.
  520. // `values` must point to an array of length at least `max_values` (ideally set
  521. // to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper,
  522. // attr_name)).
  523. TF_CAPI_EXPORT extern void TF_OperationGetAttrBoolList(TF_Operation* oper,
  524. const char* attr_name,
  525. unsigned char* values,
  526. int max_values,
  527. TF_Status* status);
  528. TF_CAPI_EXPORT extern void TF_OperationGetAttrType(TF_Operation* oper,
  529. const char* attr_name,
  530. TF_DataType* value,
  531. TF_Status* status);
  532. // Fills in `values` with the value of the attribute `attr_name` of `oper`.
  533. // `values` must point to an array of length at least `max_values` (ideally set
  534. // to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper,
  535. // attr_name)).
  536. TF_CAPI_EXPORT extern void TF_OperationGetAttrTypeList(TF_Operation* oper,
  537. const char* attr_name,
  538. TF_DataType* values,
  539. int max_values,
  540. TF_Status* status);
  541. // Fills in `value` with the value of the attribute `attr_name` of `oper`.
  542. // `values` must point to an array of length at least `num_dims` (ideally set to
  543. // TF_Attr_Meta.size from TF_OperationGetAttrMetadata(oper, attr_name)).
  544. TF_CAPI_EXPORT extern void TF_OperationGetAttrShape(TF_Operation* oper,
  545. const char* attr_name,
  546. int64_t* value,
  547. int num_dims,
  548. TF_Status* status);
  549. // Fills in `dims` with the list of shapes in the attribute `attr_name` of
  550. // `oper` and `num_dims` with the corresponding number of dimensions. On return,
  551. // for every i where `num_dims[i]` > 0, `dims[i]` will be an array of
  552. // `num_dims[i]` elements. A value of -1 for `num_dims[i]` indicates that the
  553. // i-th shape in the list is unknown.
  554. //
  555. // The elements of `dims` will point to addresses in `storage` which must be
  556. // large enough to hold at least `storage_size` int64_ts. Ideally, `num_shapes`
  557. // would be set to TF_AttrMetadata.list_size and `storage_size` would be set to
  558. // TF_AttrMetadata.total_size from TF_OperationGetAttrMetadata(oper,
  559. // attr_name).
  560. //
  561. // Fails if storage_size is insufficient to hold the requested shapes.
  562. TF_CAPI_EXPORT extern void TF_OperationGetAttrShapeList(
  563. TF_Operation* oper, const char* attr_name, int64_t** dims, int* num_dims,
  564. int num_shapes, int64_t* storage, int storage_size, TF_Status* status);
  565. // Sets `value` to the binary-serialized TensorShapeProto of the value of
  566. // `attr_name` attribute of `oper`'.
  567. TF_CAPI_EXPORT extern void TF_OperationGetAttrTensorShapeProto(
  568. TF_Operation* oper, const char* attr_name, TF_Buffer* value,
  569. TF_Status* status);
  570. // Fills in `values` with binary-serialized TensorShapeProto values of the
  571. // attribute `attr_name` of `oper`. `values` must point to an array of length at
  572. // least `num_values` (ideally set to TF_AttrMetadata.list_size from
  573. // TF_OperationGetAttrMetadata(oper, attr_name)).
  574. TF_CAPI_EXPORT extern void TF_OperationGetAttrTensorShapeProtoList(
  575. TF_Operation* oper, const char* attr_name, TF_Buffer** values,
  576. int max_values, TF_Status* status);
  577. // Gets the TF_Tensor valued attribute of `attr_name` of `oper`.
  578. //
  579. // Allocates a new TF_Tensor which the caller is expected to take
  580. // ownership of (and can deallocate using TF_DeleteTensor).
  581. TF_CAPI_EXPORT extern void TF_OperationGetAttrTensor(TF_Operation* oper,
  582. const char* attr_name,
  583. TF_Tensor** value,
  584. TF_Status* status);
  585. // Fills in `values` with the TF_Tensor values of the attribute `attr_name` of
  586. // `oper`. `values` must point to an array of TF_Tensor* of length at least
  587. // `max_values` (ideally set to TF_AttrMetadata.list_size from
  588. // TF_OperationGetAttrMetadata(oper, attr_name)).
  589. //
  590. // The caller takes ownership of all the non-null TF_Tensor* entries in `values`
  591. // (which can be deleted using TF_DeleteTensor(values[i])).
  592. TF_CAPI_EXPORT extern void TF_OperationGetAttrTensorList(TF_Operation* oper,
  593. const char* attr_name,
  594. TF_Tensor** values,
  595. int max_values,
  596. TF_Status* status);
  597. // Sets `output_attr_value` to the binary-serialized AttrValue proto
  598. // representation of the value of the `attr_name` attr of `oper`.
  599. TF_CAPI_EXPORT extern void TF_OperationGetAttrValueProto(
  600. TF_Operation* oper, const char* attr_name, TF_Buffer* output_attr_value,
  601. TF_Status* status);
  602. // Returns the operation in the graph with `oper_name`. Returns nullptr if
  603. // no operation found.
  604. TF_CAPI_EXPORT extern TF_Operation* TF_GraphOperationByName(
  605. TF_Graph* graph, const char* oper_name);
  606. // Iterate through the operations of a graph. To use:
  607. // size_t pos = 0;
  608. // TF_Operation* oper;
  609. // while ((oper = TF_GraphNextOperation(graph, &pos)) != nullptr) {
  610. // DoSomethingWithOperation(oper);
  611. // }
  612. TF_CAPI_EXPORT extern TF_Operation* TF_GraphNextOperation(TF_Graph* graph,
  613. size_t* pos);
  614. // Write out a serialized representation of `graph` (as a GraphDef protocol
  615. // message) to `output_graph_def` (allocated by TF_NewBuffer()).
  616. // `output_graph_def`'s underlying buffer will be freed when TF_DeleteBuffer()
  617. // is called.
  618. //
  619. // May fail on very large graphs in the future.
  620. TF_CAPI_EXPORT extern void TF_GraphToGraphDef(TF_Graph* graph,
  621. TF_Buffer* output_graph_def,
  622. TF_Status* status);
  623. // Returns the serialized OpDef proto with name `op_name`, or a bad status if no
  624. // such op exists. This can return OpDefs of functions copied into the graph.
  625. TF_CAPI_EXPORT extern void TF_GraphGetOpDef(TF_Graph* graph,
  626. const char* op_name,
  627. TF_Buffer* output_op_def,
  628. TF_Status* status);
  629. // Returns the serialized VersionDef proto for this graph.
  630. TF_CAPI_EXPORT extern void TF_GraphVersions(TF_Graph* graph,
  631. TF_Buffer* output_version_def,
  632. TF_Status* status);
  633. // TF_ImportGraphDefOptions holds options that can be passed to
  634. // TF_GraphImportGraphDef.
  635. typedef struct TF_ImportGraphDefOptions TF_ImportGraphDefOptions;
  636. TF_CAPI_EXPORT extern TF_ImportGraphDefOptions* TF_NewImportGraphDefOptions(
  637. void);
  638. TF_CAPI_EXPORT extern void TF_DeleteImportGraphDefOptions(
  639. TF_ImportGraphDefOptions* opts);
  640. // Set the prefix to be prepended to the names of nodes in `graph_def` that will
  641. // be imported into `graph`. `prefix` is copied and has no lifetime
  642. // requirements.
  643. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsSetPrefix(
  644. TF_ImportGraphDefOptions* opts, const char* prefix);
  645. // Set the execution device for nodes in `graph_def`.
  646. // Only applies to nodes where a device was not already explicitly specified.
  647. // `device` is copied and has no lifetime requirements.
  648. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsSetDefaultDevice(
  649. TF_ImportGraphDefOptions* opts, const char* device);
  650. // Set whether to uniquify imported operation names. If true, imported operation
  651. // names will be modified if their name already exists in the graph. If false,
  652. // conflicting names will be treated as an error. Note that this option has no
  653. // effect if a prefix is set, since the prefix will guarantee all names are
  654. // unique. Defaults to false.
  655. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsSetUniquifyNames(
  656. TF_ImportGraphDefOptions* opts, unsigned char uniquify_names);
  657. // If true, the specified prefix will be modified if it already exists as an
  658. // operation name or prefix in the graph. If false, a conflicting prefix will be
  659. // treated as an error. This option has no effect if no prefix is specified.
  660. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsSetUniquifyPrefix(
  661. TF_ImportGraphDefOptions* opts, unsigned char uniquify_prefix);
  662. // Set any imported nodes with input `src_name:src_index` to have that input
  663. // replaced with `dst`. `src_name` refers to a node in the graph to be imported,
  664. // `dst` references a node already existing in the graph being imported into.
  665. // `src_name` is copied and has no lifetime requirements.
  666. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsAddInputMapping(
  667. TF_ImportGraphDefOptions* opts, const char* src_name, int src_index,
  668. TF_Output dst);
  669. // Set any imported nodes with control input `src_name` to have that input
  670. // replaced with `dst`. `src_name` refers to a node in the graph to be imported,
  671. // `dst` references an operation already existing in the graph being imported
  672. // into. `src_name` is copied and has no lifetime requirements.
  673. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsRemapControlDependency(
  674. TF_ImportGraphDefOptions* opts, const char* src_name, TF_Operation* dst);
  675. // Cause the imported graph to have a control dependency on `oper`. `oper`
  676. // should exist in the graph being imported into.
  677. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsAddControlDependency(
  678. TF_ImportGraphDefOptions* opts, TF_Operation* oper);
  679. // Add an output in `graph_def` to be returned via the `return_outputs` output
  680. // parameter of TF_GraphImportGraphDef(). If the output is remapped via an input
  681. // mapping, the corresponding existing tensor in `graph` will be returned.
  682. // `oper_name` is copied and has no lifetime requirements.
  683. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsAddReturnOutput(
  684. TF_ImportGraphDefOptions* opts, const char* oper_name, int index);
  685. // Returns the number of return outputs added via
  686. // TF_ImportGraphDefOptionsAddReturnOutput().
  687. TF_CAPI_EXPORT extern int TF_ImportGraphDefOptionsNumReturnOutputs(
  688. const TF_ImportGraphDefOptions* opts);
  689. // Add an operation in `graph_def` to be returned via the `return_opers` output
  690. // parameter of TF_GraphImportGraphDef(). `oper_name` is copied and has no
  691. // lifetime requirements.
  692. TF_CAPI_EXPORT extern void TF_ImportGraphDefOptionsAddReturnOperation(
  693. TF_ImportGraphDefOptions* opts, const char* oper_name);
  694. // Returns the number of return operations added via
  695. // TF_ImportGraphDefOptionsAddReturnOperation().
  696. TF_CAPI_EXPORT extern int TF_ImportGraphDefOptionsNumReturnOperations(
  697. const TF_ImportGraphDefOptions* opts);
  698. // TF_ImportGraphDefResults holds results that are generated by
  699. // TF_GraphImportGraphDefWithResults().
  700. typedef struct TF_ImportGraphDefResults TF_ImportGraphDefResults;
  701. // Fetches the return outputs requested via
  702. // TF_ImportGraphDefOptionsAddReturnOutput(). The number of fetched outputs is
  703. // returned in `num_outputs`. The array of return outputs is returned in
  704. // `outputs`. `*outputs` is owned by and has the lifetime of `results`.
  705. TF_CAPI_EXPORT extern void TF_ImportGraphDefResultsReturnOutputs(
  706. TF_ImportGraphDefResults* results, int* num_outputs, TF_Output** outputs);
  707. // Fetches the return operations requested via
  708. // TF_ImportGraphDefOptionsAddReturnOperation(). The number of fetched
  709. // operations is returned in `num_opers`. The array of return operations is
  710. // returned in `opers`. `*opers` is owned by and has the lifetime of `results`.
  711. TF_CAPI_EXPORT extern void TF_ImportGraphDefResultsReturnOperations(
  712. TF_ImportGraphDefResults* results, int* num_opers, TF_Operation*** opers);
  713. // Fetches any input mappings requested via
  714. // TF_ImportGraphDefOptionsAddInputMapping() that didn't appear in the GraphDef
  715. // and weren't used as input to any node in the imported graph def. The number
  716. // of fetched mappings is returned in `num_missing_unused_input_mappings`. The
  717. // array of each mapping's source node name is returned in `src_names`, and the
  718. // array of each mapping's source index is returned in `src_indexes`.
  719. //
  720. // `*src_names`, `*src_indexes`, and the memory backing each string in
  721. // `src_names` are owned by and have the lifetime of `results`.
  722. TF_CAPI_EXPORT extern void TF_ImportGraphDefResultsMissingUnusedInputMappings(
  723. TF_ImportGraphDefResults* results, int* num_missing_unused_input_mappings,
  724. const char*** src_names, int** src_indexes);
  725. // Deletes a results object returned by TF_GraphImportGraphDefWithResults().
  726. TF_CAPI_EXPORT extern void TF_DeleteImportGraphDefResults(
  727. TF_ImportGraphDefResults* results);
  728. // Import the graph serialized in `graph_def` into `graph`. Returns nullptr and
  729. // a bad status on error. Otherwise, returns a populated
  730. // TF_ImportGraphDefResults instance. The returned instance must be deleted via
  731. // TF_DeleteImportGraphDefResults().
  732. TF_CAPI_EXPORT extern TF_ImportGraphDefResults*
  733. TF_GraphImportGraphDefWithResults(TF_Graph* graph, const TF_Buffer* graph_def,
  734. const TF_ImportGraphDefOptions* options,
  735. TF_Status* status);
  736. // Import the graph serialized in `graph_def` into `graph`.
  737. // Convenience function for when only return outputs are needed.
  738. //
  739. // `num_return_outputs` must be the number of return outputs added (i.e. the
  740. // result of TF_ImportGraphDefOptionsNumReturnOutputs()). If
  741. // `num_return_outputs` is non-zero, `return_outputs` must be of length
  742. // `num_return_outputs`. Otherwise it can be null.
  743. TF_CAPI_EXPORT extern void TF_GraphImportGraphDefWithReturnOutputs(
  744. TF_Graph* graph, const TF_Buffer* graph_def,
  745. const TF_ImportGraphDefOptions* options, TF_Output* return_outputs,
  746. int num_return_outputs, TF_Status* status);
  747. // Import the graph serialized in `graph_def` into `graph`.
  748. // Convenience function for when no results are needed.
  749. TF_CAPI_EXPORT extern void TF_GraphImportGraphDef(
  750. TF_Graph* graph, const TF_Buffer* graph_def,
  751. const TF_ImportGraphDefOptions* options, TF_Status* status);
  752. // Adds a copy of function `func` and optionally its gradient function `grad`
  753. // to `g`. Once `func`/`grad` is added to `g`, it can be called by creating
  754. // an operation using the function's name.
  755. // Any changes to `func`/`grad` (including deleting it) done after this method
  756. // returns, won't affect the copy of `func`/`grad` in `g`.
  757. // If `func` or `grad` are already in `g`, TF_GraphCopyFunction has no
  758. // effect on them, but can establish the function->gradient relationship
  759. // between them if `func` does not already have a gradient. If `func` already
  760. // has a gradient different from `grad`, an error is returned.
  761. //
  762. // `func` must not be null.
  763. // If `grad` is null and `func` is not in `g`, `func` is added without a
  764. // gradient.
  765. // If `grad` is null and `func` is in `g`, TF_GraphCopyFunction is a noop.
  766. // `grad` must have appropriate signature as described in the doc of
  767. // GradientDef in tensorflow/core/framework/function.proto.
  768. //
  769. // If successful, status is set to OK and `func` and `grad` are added to `g`.
  770. // Otherwise, status is set to the encountered error and `g` is unmodified.
  771. TF_CAPI_EXPORT extern void TF_GraphCopyFunction(TF_Graph* g,
  772. const TF_Function* func,
  773. const TF_Function* grad,
  774. TF_Status* status);
  775. // Returns the number of TF_Functions registered in `g`.
  776. TF_CAPI_EXPORT extern int TF_GraphNumFunctions(TF_Graph* g);
  777. // Fills in `funcs` with the TF_Function* registered in `g`.
  778. // `funcs` must point to an array of TF_Function* of length at least
  779. // `max_func`. In usual usage, max_func should be set to the result of
  780. // TF_GraphNumFunctions(g). In this case, all the functions registered in
  781. // `g` will be returned. Else, an unspecified subset.
  782. //
  783. // If successful, returns the number of TF_Function* successfully set in
  784. // `funcs` and sets status to OK. The caller takes ownership of
  785. // all the returned TF_Functions. They must be deleted with TF_DeleteFunction.
  786. // On error, returns 0, sets status to the encountered error, and the contents
  787. // of funcs will be undefined.
  788. TF_CAPI_EXPORT extern int TF_GraphGetFunctions(TF_Graph* g, TF_Function** funcs,
  789. int max_func, TF_Status* status);
  790. // Note: The following function may fail on very large protos in the future.
  791. TF_CAPI_EXPORT extern void TF_OperationToNodeDef(TF_Operation* oper,
  792. TF_Buffer* output_node_def,
  793. TF_Status* status);
  794. typedef struct TF_WhileParams {
  795. // The number of inputs to the while loop, i.e. the number of loop variables.
  796. // This is the size of cond_inputs, body_inputs, and body_outputs.
  797. const int ninputs;
  798. // The while condition graph. The inputs are the current values of the loop
  799. // variables. The output should be a scalar boolean.
  800. TF_Graph* const cond_graph;
  801. const TF_Output* const cond_inputs;
  802. TF_Output cond_output;
  803. // The loop body graph. The inputs are the current values of the loop
  804. // variables. The outputs are the updated values of the loop variables.
  805. TF_Graph* const body_graph;
  806. const TF_Output* const body_inputs;
  807. TF_Output* const body_outputs;
  808. // Unique null-terminated name for this while loop. This is used as a prefix
  809. // for created operations.
  810. const char* name;
  811. } TF_WhileParams;
  812. // Creates a TF_WhileParams for creating a while loop in `g`. `inputs` are
  813. // outputs that already exist in `g` used as initial values for the loop
  814. // variables.
  815. //
  816. // The returned TF_WhileParams will have all fields initialized except
  817. // `cond_output`, `body_outputs`, and `name`. The `body_outputs` buffer will be
  818. // allocated to size `ninputs`. The caller should build `cond_graph` and
  819. // `body_graph` starting from the inputs, and store the final outputs in
  820. // `cond_output` and `body_outputs`.
  821. //
  822. // If `status` is OK, the caller must call either TF_FinishWhile or
  823. // TF_AbortWhile on the returned TF_WhileParams. If `status` isn't OK, the
  824. // returned TF_WhileParams is not valid, and the caller should not call
  825. // TF_FinishWhile() or TF_AbortWhile().
  826. //
  827. // Missing functionality (TODO):
  828. // - Gradients
  829. // - Reference-type inputs
  830. // - Directly referencing external tensors from the cond/body graphs (this is
  831. // possible in the Python API)
  832. TF_CAPI_EXPORT extern TF_WhileParams TF_NewWhile(TF_Graph* g, TF_Output* inputs,
  833. int ninputs,
  834. TF_Status* status);
  835. // Builds the while loop specified by `params` and returns the output tensors of
  836. // the while loop in `outputs`. `outputs` should be allocated to size
  837. // `params.ninputs`.
  838. //
  839. // `params` is no longer valid once this returns.
  840. //
  841. // Either this or TF_AbortWhile() must be called after a successful
  842. // TF_NewWhile() call.
  843. TF_CAPI_EXPORT extern void TF_FinishWhile(const TF_WhileParams* params,
  844. TF_Status* status,
  845. TF_Output* outputs);
  846. // Frees `params`s resources without building a while loop. `params` is no
  847. // longer valid after this returns. Either this or TF_FinishWhile() must be
  848. // called after a successful TF_NewWhile() call.
  849. TF_CAPI_EXPORT extern void TF_AbortWhile(const TF_WhileParams* params);
  850. // Adds operations to compute the partial derivatives of sum of `y`s w.r.t `x`s,
  851. // i.e., d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2...
  852. //
  853. // `dx` are used as initial gradients (which represent the symbolic partial
  854. // derivatives of some loss function `L` w.r.t. `y`).
  855. // `dx` must be nullptr or have size `ny`.
  856. // If `dx` is nullptr, the implementation will use dx of `OnesLike` for all
  857. // shapes in `y`.
  858. // The partial derivatives are returned in `dy`. `dy` should be allocated to
  859. // size `nx`.
  860. //
  861. // Gradient nodes are automatically named under the "gradients/" prefix. To
  862. // guarantee name uniqueness, subsequent calls to the same graph will
  863. // append an incremental tag to the prefix: "gradients_1/", "gradients_2/", ...
  864. // See TF_AddGradientsWithPrefix, which provides a means to specify a custom
  865. // name prefix for operations added to a graph to compute the gradients.
  866. //
  867. // WARNING: This function does not yet support all the gradients that python
  868. // supports. See
  869. // https://www.tensorflow.org/code/tensorflow/cc/gradients/README.md
  870. // for instructions on how to add C++ more gradients.
  871. TF_CAPI_EXPORT void TF_AddGradients(TF_Graph* g, TF_Output* y, int ny,
  872. TF_Output* x, int nx, TF_Output* dx,
  873. TF_Status* status, TF_Output* dy);
  874. // Adds operations to compute the partial derivatives of sum of `y`s w.r.t `x`s,
  875. // i.e., d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2...
  876. // This is a variant of TF_AddGradients that allows to caller to pass a custom
  877. // name prefix to the operations added to a graph to compute the gradients.
  878. //
  879. // `dx` are used as initial gradients (which represent the symbolic partial
  880. // derivatives of some loss function `L` w.r.t. `y`).
  881. // `dx` must be nullptr or have size `ny`.
  882. // If `dx` is nullptr, the implementation will use dx of `OnesLike` for all
  883. // shapes in `y`.
  884. // The partial derivatives are returned in `dy`. `dy` should be allocated to
  885. // size `nx`.
  886. // `prefix` names the scope into which all gradients operations are being added.
  887. // `prefix` must be unique within the provided graph otherwise this operation
  888. // will fail. If `prefix` is nullptr, the default prefixing behaviour takes
  889. // place, see TF_AddGradients for more details.
  890. //
  891. // WARNING: This function does not yet support all the gradients that python
  892. // supports. See
  893. // https://www.tensorflow.org/code/tensorflow/cc/gradients/README.md
  894. // for instructions on how to add C++ more gradients.
  895. TF_CAPI_EXPORT void TF_AddGradientsWithPrefix(TF_Graph* g, const char* prefix,
  896. TF_Output* y, int ny,
  897. TF_Output* x, int nx,
  898. TF_Output* dx, TF_Status* status,
  899. TF_Output* dy);
  900. // Create a TF_Function from a TF_Graph
  901. //
  902. // Params:
  903. // fn_body - the graph whose operations (or subset of whose operations) will be
  904. // converted to TF_Function.
  905. // fn_name - the name of the new TF_Function. Should match the operation
  906. // name (OpDef.name) regexp [A-Z][A-Za-z0-9_.\\-/]*.
  907. // If `append_hash_to_fn_name` is false, `fn_name` must be distinct
  908. // from other function and operation names (at least those
  909. // registered in graphs where this function will be used).
  910. // append_hash_to_fn_name - Must be 0 or 1. If set to 1, the actual name
  911. // of the function will be `fn_name` appended with
  912. // '_<hash_of_this_function's_definition>'.
  913. // If set to 0, the function's name will be `fn_name`.
  914. // num_opers - `num_opers` contains the number of elements in the `opers` array
  915. // or a special value of -1 meaning that no array is given.
  916. // The distinction between an empty array of operations and no
  917. // array of operations is necessary to distinguish the case of
  918. // creating a function with no body (e.g. identity or permutation)
  919. // and the case of creating a function whose body contains all
  920. // the nodes in the graph (except for the automatic skipping, see
  921. // below).
  922. // opers - Array of operations to become the body of the function or null.
  923. // - If no array is given (`num_opers` = -1), all the
  924. // operations in `fn_body` will become part of the function
  925. // except operations referenced in `inputs`. These operations
  926. // must have a single output (these operations are typically
  927. // placeholders created for the sole purpose of representing
  928. // an input. We can relax this constraint if there are
  929. // compelling use cases).
  930. // - If an array is given (`num_opers` >= 0), all operations
  931. // in it will become part of the function. In particular, no
  932. // automatic skipping of dummy input operations is performed.
  933. // ninputs - number of elements in `inputs` array
  934. // inputs - array of TF_Outputs that specify the inputs to the function.
  935. // If `ninputs` is zero (the function takes no inputs), `inputs`
  936. // can be null. The names used for function inputs are normalized
  937. // names of the operations (usually placeholders) pointed to by
  938. // `inputs`. These operation names should start with a letter.
  939. // Normalization will convert all letters to lowercase and
  940. // non-alphanumeric characters to '_' to make resulting names match
  941. // the "[a-z][a-z0-9_]*" pattern for operation argument names.
  942. // `inputs` cannot contain the same tensor twice.
  943. // noutputs - number of elements in `outputs` array
  944. // outputs - array of TF_Outputs that specify the outputs of the function.
  945. // If `noutputs` is zero (the function returns no outputs), `outputs`
  946. // can be null. `outputs` can contain the same tensor more than once.
  947. // output_names - The names of the function's outputs. `output_names` array
  948. // must either have the same length as `outputs`
  949. // (i.e. `noutputs`) or be null. In the former case,
  950. // the names should match the regular expression for ArgDef
  951. // names - "[a-z][a-z0-9_]*". In the latter case,
  952. // names for outputs will be generated automatically.
  953. // opts - various options for the function, e.g. XLA's inlining control.
  954. // description - optional human-readable description of this function.
  955. // status - Set to OK on success and an appropriate error on failure.
  956. //
  957. // Note that when the same TF_Output is listed as both an input and an output,
  958. // the corresponding function's output will equal to this input,
  959. // instead of the original node's output.
  960. //
  961. // Callers must also satisfy the following constraints:
  962. // - `inputs` cannot refer to TF_Outputs within a control flow context. For
  963. // example, one cannot use the output of "switch" node as input.
  964. // - `inputs` and `outputs` cannot have reference types. Reference types are
  965. // not exposed through C API and are being replaced with Resources. We support
  966. // reference types inside function's body to support legacy code. Do not
  967. // use them in new code.
  968. // - Every node in the function's body must have all of its inputs (including
  969. // control inputs). In other words, for every node in the body, each input
  970. // must be either listed in `inputs` or must come from another node in
  971. // the body. In particular, it is an error to have a control edge going from
  972. // a node outside of the body into a node in the body. This applies to control
  973. // edges going from nodes referenced in `inputs` to nodes in the body when
  974. // the former nodes are not in the body (automatically skipped or not
  975. // included in explicitly specified body).
  976. //
  977. // Returns:
  978. // On success, a newly created TF_Function instance. It must be deleted by
  979. // calling TF_DeleteFunction.
  980. //
  981. // On failure, null.
  982. TF_CAPI_EXPORT extern TF_Function* TF_GraphToFunction(
  983. const TF_Graph* fn_body, const char* fn_name,
  984. unsigned char append_hash_to_fn_name, int num_opers,
  985. const TF_Operation* const* opers, int ninputs, const TF_Output* inputs,
  986. int noutputs, const TF_Output* outputs, const char* const* output_names,
  987. const TF_FunctionOptions* opts, const char* description, TF_Status* status);
  988. // Similar to TF_GraphToFunction but allows specifying control outputs of the
  989. // function.
  990. //
  991. // The arguments of TF_GraphToFunction have the same meaning, but the new
  992. // arguments are as follows:
  993. //
  994. // ncontrol_outputs: Number of control outputs of the function.
  995. // control_outputs: vector of TF_Operation objects to be marked as control
  996. // outputs of the function. Operations marked as control outputs are
  997. // guaranteed to execute.
  998. // control_output_names: Optional. If not nullptr, vector of strings, one
  999. // per control output, with their names to be added to the function's
  1000. // OpDef.
  1001. TF_CAPI_EXPORT extern TF_Function* TF_GraphToFunctionWithControlOutputs(
  1002. const TF_Graph* fn_body, const char* fn_name,
  1003. unsigned char append_hash_to_fn_name, int num_opers,
  1004. const TF_Operation* const* opers, int ninputs, const TF_Output* inputs,
  1005. int noutputs, const TF_Output* outputs, const char* const* output_names,
  1006. int ncontrol_outputs, const TF_Operation* const* control_outputs,
  1007. const char* const* control_output_names, const TF_FunctionOptions* opts,
  1008. const char* description, TF_Status* status);
  1009. // Returns the name of the graph function.
  1010. // The return value points to memory that is only usable until the next
  1011. // mutation to *func.
  1012. TF_CAPI_EXPORT extern const char* TF_FunctionName(TF_Function* func);
  1013. // Write out a serialized representation of `func` (as a FunctionDef protocol
  1014. // message) to `output_func_def` (allocated by TF_NewBuffer()).
  1015. // `output_func_def`'s underlying buffer will be freed when TF_DeleteBuffer()
  1016. // is called.
  1017. //
  1018. // May fail on very large graphs in the future.
  1019. TF_CAPI_EXPORT extern void TF_FunctionToFunctionDef(TF_Function* func,
  1020. TF_Buffer* output_func_def,
  1021. TF_Status* status);
  1022. // Construct and return the function whose FunctionDef representation is
  1023. // serialized in `proto`. `proto_len` must equal the number of bytes
  1024. // pointed to by `proto`.
  1025. // Returns:
  1026. // On success, a newly created TF_Function instance. It must be deleted by
  1027. // calling TF_DeleteFunction.
  1028. //
  1029. // On failure, null.
  1030. TF_CAPI_EXPORT extern TF_Function* TF_FunctionImportFunctionDef(
  1031. const void* proto, size_t proto_len, TF_Status* status);
  1032. // Sets function attribute named `attr_name` to value stored in `proto`.
  1033. // If this attribute is already set to another value, it is overridden.
  1034. // `proto` should point to a sequence of bytes of length `proto_len`
  1035. // representing a binary serialization of an AttrValue protocol
  1036. // buffer.
  1037. TF_CAPI_EXPORT extern void TF_FunctionSetAttrValueProto(TF_Function* func,
  1038. const char* attr_name,
  1039. const void* proto,
  1040. size_t proto_len,
  1041. TF_Status* status);
  1042. // Sets `output_attr_value` to the binary-serialized AttrValue proto
  1043. // representation of the value of the `attr_name` attr of `func`.
  1044. // If `attr_name` attribute is not present, status is set to an error.
  1045. TF_CAPI_EXPORT extern void TF_FunctionGetAttrValueProto(
  1046. TF_Function* func, const char* attr_name, TF_Buffer* output_attr_value,
  1047. TF_Status* status);
  1048. // Frees the memory used by the `func` struct.
  1049. // TF_DeleteFunction is a noop if `func` is null.
  1050. // Deleting a function does not remove it from any graphs it was copied to.
  1051. TF_CAPI_EXPORT extern void TF_DeleteFunction(TF_Function* func);
  1052. // Attempts to evaluate `output`. This will only be possible if `output` doesn't
  1053. // depend on any graph inputs (this function is safe to call if this isn't the
  1054. // case though).
  1055. //
  1056. // If the evaluation is successful, this function returns true and `output`s
  1057. // value is returned in `result`. Otherwise returns false. An error status is
  1058. // returned if something is wrong with the graph or input. Note that this may
  1059. // return false even if no error status is set.
  1060. TF_CAPI_EXPORT extern unsigned char TF_TryEvaluateConstant(TF_Graph* graph,
  1061. TF_Output output,
  1062. TF_Tensor** result,
  1063. TF_Status* status);
  1064. // TODO(josh11b): Register OpDef, available to all operations added
  1065. // to this graph.
  1066. // --------------------------------------------------------------------------
  1067. // API for driving Graph execution.
  1068. typedef struct TF_Session TF_Session;
  1069. // Return a new execution session with the associated graph, or NULL on
  1070. // error. Does not take ownership of any input parameters.
  1071. //
  1072. // *`graph` must be a valid graph (not deleted or nullptr). `graph` will be
  1073. // kept alive for the lifetime of the returned TF_Session. New nodes can still
  1074. // be added to `graph` after this call.
  1075. TF_CAPI_EXPORT extern TF_Session* TF_NewSession(TF_Graph* graph,
  1076. const TF_SessionOptions* opts,
  1077. TF_Status* status);
  1078. // This function creates a new TF_Session (which is created on success) using
  1079. // `session_options`, and then initializes state (restoring tensors and other
  1080. // assets) using `run_options`.
  1081. //
  1082. // Any NULL and non-NULL value combinations for (`run_options, `meta_graph_def`)
  1083. // are valid.
  1084. //
  1085. // - `export_dir` must be set to the path of the exported SavedModel.
  1086. // - `tags` must include the set of tags used to identify one MetaGraphDef in
  1087. // the SavedModel.
  1088. // - `graph` must be a graph newly allocated with TF_NewGraph().
  1089. //
  1090. // If successful, populates `graph` with the contents of the Graph and
  1091. // `meta_graph_def` with the MetaGraphDef of the loaded model.
  1092. TF_CAPI_EXPORT extern TF_Session* TF_LoadSessionFromSavedModel(
  1093. const TF_SessionOptions* session_options, const TF_Buffer* run_options,
  1094. const char* export_dir, const char* const* tags, int tags_len,
  1095. TF_Graph* graph, TF_Buffer* meta_graph_def, TF_Status* status);
  1096. // Close a session.
  1097. //
  1098. // Contacts any other processes associated with the session, if applicable.
  1099. // May not be called after TF_DeleteSession().
  1100. TF_CAPI_EXPORT extern void TF_CloseSession(TF_Session*, TF_Status* status);
  1101. // Destroy a session object.
  1102. //
  1103. // Even if error information is recorded in *status, this call discards all
  1104. // local resources associated with the session. The session may not be used
  1105. // during or after this call (and the session drops its reference to the
  1106. // corresponding graph).
  1107. TF_CAPI_EXPORT extern void TF_DeleteSession(TF_Session*, TF_Status* status);
  1108. // Run the graph associated with the session starting with the supplied inputs
  1109. // (inputs[0,ninputs-1] with corresponding values in input_values[0,ninputs-1]).
  1110. //
  1111. // Any NULL and non-NULL value combinations for (`run_options`,
  1112. // `run_metadata`) are valid.
  1113. //
  1114. // - `run_options` may be NULL, in which case it will be ignored; or
  1115. // non-NULL, in which case it must point to a `TF_Buffer` containing the
  1116. // serialized representation of a `RunOptions` protocol buffer.
  1117. // - `run_metadata` may be NULL, in which case it will be ignored; or
  1118. // non-NULL, in which case it must point to an empty, freshly allocated
  1119. // `TF_Buffer` that may be updated to contain the serialized representation
  1120. // of a `RunMetadata` protocol buffer.
  1121. //
  1122. // The caller retains ownership of `input_values` (which can be deleted using
  1123. // TF_DeleteTensor). The caller also retains ownership of `run_options` and/or
  1124. // `run_metadata` (when not NULL) and should manually call TF_DeleteBuffer on
  1125. // them.
  1126. //
  1127. // On success, the tensors corresponding to outputs[0,noutputs-1] are placed in
  1128. // output_values[]. Ownership of the elements of output_values[] is transferred
  1129. // to the caller, which must eventually call TF_DeleteTensor on them.
  1130. //
  1131. // On failure, output_values[] contains NULLs.
  1132. TF_CAPI_EXPORT extern void TF_SessionRun(
  1133. TF_Session* session,
  1134. // RunOptions
  1135. const TF_Buffer* run_options,
  1136. // Input tensors
  1137. const TF_Output* inputs, TF_Tensor* const* input_values, int ninputs,
  1138. // Output tensors
  1139. const TF_Output* outputs, TF_Tensor** output_values, int noutputs,
  1140. // Target operations
  1141. const TF_Operation* const* target_opers, int ntargets,
  1142. // RunMetadata
  1143. TF_Buffer* run_metadata,
  1144. // Output status
  1145. TF_Status*);
  1146. // Set up the graph with the intended feeds (inputs) and fetches (outputs) for a
  1147. // sequence of partial run calls.
  1148. //
  1149. // On success, returns a handle that is used for subsequent PRun calls. The
  1150. // handle should be deleted with TF_DeletePRunHandle when it is no longer
  1151. // needed.
  1152. //
  1153. // On failure, out_status contains a tensorflow::Status with an error
  1154. // message. *handle is set to nullptr.
  1155. TF_CAPI_EXPORT extern void TF_SessionPRunSetup(
  1156. TF_Session*,
  1157. // Input names
  1158. const TF_Output* inputs, int ninputs,
  1159. // Output names
  1160. const TF_Output* outputs, int noutputs,
  1161. // Target operations
  1162. const TF_Operation* const* target_opers, int ntargets,
  1163. // Output handle
  1164. const char** handle,
  1165. // Output status
  1166. TF_Status*);
  1167. // Continue to run the graph with additional feeds and fetches. The
  1168. // execution state is uniquely identified by the handle.
  1169. TF_CAPI_EXPORT extern void TF_SessionPRun(
  1170. TF_Session*, const char* handle,
  1171. // Input tensors
  1172. const TF_Output* inputs, TF_Tensor* const* input_values, int ninputs,
  1173. // Output tensors
  1174. const TF_Output* outputs, TF_Tensor** output_values, int noutputs,
  1175. // Target operations
  1176. const TF_Operation* const* target_opers, int ntargets,
  1177. // Output status
  1178. TF_Status*);
  1179. // Deletes a handle allocated by TF_SessionPRunSetup.
  1180. // Once called, no more calls to TF_SessionPRun should be made.
  1181. TF_CAPI_EXPORT extern void TF_DeletePRunHandle(const char* handle);
  1182. // --------------------------------------------------------------------------
  1183. // The deprecated session API. Please switch to the above instead of
  1184. // TF_ExtendGraph(). This deprecated API can be removed at any time without
  1185. // notice.
  1186. typedef struct TF_DeprecatedSession TF_DeprecatedSession;
  1187. TF_CAPI_EXPORT extern TF_DeprecatedSession* TF_NewDeprecatedSession(
  1188. const TF_SessionOptions*, TF_Status* status);
  1189. TF_CAPI_EXPORT extern void TF_CloseDeprecatedSession(TF_DeprecatedSession*,
  1190. TF_Status* status);
  1191. TF_CAPI_EXPORT extern void TF_DeleteDeprecatedSession(TF_DeprecatedSession*,
  1192. TF_Status* status);
  1193. TF_CAPI_EXPORT extern void TF_Reset(const TF_SessionOptions* opt,
  1194. const char** containers, int ncontainers,
  1195. TF_Status* status);
  1196. // Treat the bytes proto[0,proto_len-1] as a serialized GraphDef and
  1197. // add the nodes in that GraphDef to the graph for the session.
  1198. //
  1199. // Prefer use of TF_Session and TF_GraphImportGraphDef over this.
  1200. TF_CAPI_EXPORT extern void TF_ExtendGraph(TF_DeprecatedSession*,
  1201. const void* proto, size_t proto_len,
  1202. TF_Status*);
  1203. // See TF_SessionRun() above.
  1204. TF_CAPI_EXPORT extern void TF_Run(TF_DeprecatedSession*,
  1205. const TF_Buffer* run_options,
  1206. const char** input_names, TF_Tensor** inputs,
  1207. int ninputs, const char** output_names,
  1208. TF_Tensor** outputs, int noutputs,
  1209. const char** target_oper_names, int ntargets,
  1210. TF_Buffer* run_metadata, TF_Status*);
  1211. // See TF_SessionPRunSetup() above.
  1212. TF_CAPI_EXPORT extern void TF_PRunSetup(TF_DeprecatedSession*,
  1213. const char** input_names, int ninputs,
  1214. const char** output_names, int noutputs,
  1215. const char** target_oper_names,
  1216. int ntargets, const char** handle,
  1217. TF_Status*);
  1218. // See TF_SessionPRun above.
  1219. TF_CAPI_EXPORT extern void TF_PRun(TF_DeprecatedSession*, const char* handle,
  1220. const char** input_names, TF_Tensor** inputs,
  1221. int ninputs, const char** output_names,
  1222. TF_Tensor** outputs, int noutputs,
  1223. const char** target_oper_names, int ntargets,
  1224. TF_Status*);
  1225. typedef struct TF_DeviceList TF_DeviceList;
  1226. // Lists all devices in a TF_Session.
  1227. //
  1228. // Caller takes ownership of the returned TF_DeviceList* which must eventually
  1229. // be freed with a call to TF_DeleteDeviceList.
  1230. TF_CAPI_EXPORT extern TF_DeviceList* TF_SessionListDevices(TF_Session* session,
  1231. TF_Status* status);
  1232. // Lists all devices in a TF_Session.
  1233. //
  1234. // Caller takes ownership of the returned TF_DeviceList* which must eventually
  1235. // be freed with a call to TF_DeleteDeviceList.
  1236. TF_CAPI_EXPORT extern TF_DeviceList* TF_DeprecatedSessionListDevices(
  1237. TF_DeprecatedSession* session, TF_Status* status);
  1238. // Deallocates the device list.
  1239. TF_CAPI_EXPORT extern void TF_DeleteDeviceList(TF_DeviceList* list);
  1240. // Counts the number of elements in the device list.
  1241. TF_CAPI_EXPORT extern int TF_DeviceListCount(const TF_DeviceList* list);
  1242. // Retrieves the full name of the device (e.g. /job:worker/replica:0/...)
  1243. // The return value will be a pointer to a null terminated string. The caller
  1244. // must not modify or delete the string. It will be deallocated upon a call to
  1245. // TF_DeleteDeviceList.
  1246. //
  1247. // If index is out of bounds, an error code will be set in the status object,
  1248. // and a null pointer will be returned.
  1249. TF_CAPI_EXPORT extern const char* TF_DeviceListName(const TF_DeviceList* list,
  1250. int index,
  1251. TF_Status* status);
  1252. // Retrieves the type of the device at the given index.
  1253. //
  1254. // The caller must not modify or delete the string. It will be deallocated upon
  1255. // a call to TF_DeleteDeviceList.
  1256. //
  1257. // If index is out of bounds, an error code will be set in the status object,
  1258. // and a null pointer will be returned.
  1259. TF_CAPI_EXPORT extern const char* TF_DeviceListType(const TF_DeviceList* list,
  1260. int index,
  1261. TF_Status* status);
  1262. // Retrieve the amount of memory associated with a given device.
  1263. //
  1264. // If index is out of bounds, an error code will be set in the status object,
  1265. // and -1 will be returned.
  1266. TF_CAPI_EXPORT extern int64_t TF_DeviceListMemoryBytes(
  1267. const TF_DeviceList* list, int index, TF_Status* status);
  1268. // Retrieve the incarnation number of a given device.
  1269. //
  1270. // If index is out of bounds, an error code will be set in the status object,
  1271. // and 0 will be returned.
  1272. TF_CAPI_EXPORT extern uint64_t TF_DeviceListIncarnation(
  1273. const TF_DeviceList* list, int index, TF_Status* status);
  1274. // --------------------------------------------------------------------------
  1275. // Load plugins containing custom ops and kernels
  1276. // TF_Library holds information about dynamically loaded TensorFlow plugins.
  1277. typedef struct TF_Library TF_Library;
  1278. // Load the library specified by library_filename and register the ops and
  1279. // kernels present in that library.
  1280. //
  1281. // Pass "library_filename" to a platform-specific mechanism for dynamically
  1282. // loading a library. The rules for determining the exact location of the
  1283. // library are platform-specific and are not documented here.
  1284. //
  1285. // On success, place OK in status and return the newly created library handle.
  1286. // The caller owns the library handle.
  1287. //
  1288. // On failure, place an error status in status and return NULL.
  1289. TF_CAPI_EXPORT extern TF_Library* TF_LoadLibrary(const char* library_filename,
  1290. TF_Status* status);
  1291. // Get the OpList of OpDefs defined in the library pointed by lib_handle.
  1292. //
  1293. // Returns a TF_Buffer. The memory pointed to by the result is owned by
  1294. // lib_handle. The data in the buffer will be the serialized OpList proto for
  1295. // ops defined in the library.
  1296. TF_CAPI_EXPORT extern TF_Buffer TF_GetOpList(TF_Library* lib_handle);
  1297. // Frees the memory associated with the library handle.
  1298. // Does NOT unload the library.
  1299. TF_CAPI_EXPORT extern void TF_DeleteLibraryHandle(TF_Library* lib_handle);
  1300. // Get the OpList of all OpDefs defined in this address space.
  1301. // Returns a TF_Buffer, ownership of which is transferred to the caller
  1302. // (and can be freed using TF_DeleteBuffer).
  1303. //
  1304. // The data in the buffer will be the serialized OpList proto for ops registered
  1305. // in this address space.
  1306. TF_CAPI_EXPORT extern TF_Buffer* TF_GetAllOpList(void);
  1307. // TF_ApiDefMap encapsulates a collection of API definitions for an operation.
  1308. //
  1309. // This object maps the name of a TensorFlow operation to a description of the
  1310. // API to generate for it, as defined by the ApiDef protocol buffer (
  1311. // https://www.tensorflow.org/code/tensorflow/core/framework/api_def.proto)
  1312. //
  1313. // The ApiDef messages are typically used to generate convenience wrapper
  1314. // functions for TensorFlow operations in various language bindings.
  1315. typedef struct TF_ApiDefMap TF_ApiDefMap;
  1316. // Creates a new TF_ApiDefMap instance.
  1317. //
  1318. // Params:
  1319. // op_list_buffer - TF_Buffer instance containing serialized OpList
  1320. // protocol buffer. (See
  1321. // https://www.tensorflow.org/code/tensorflow/core/framework/op_def.proto
  1322. // for the OpList proto definition).
  1323. // status - Set to OK on success and an appropriate error on failure.
  1324. TF_CAPI_EXPORT extern TF_ApiDefMap* TF_NewApiDefMap(TF_Buffer* op_list_buffer,
  1325. TF_Status* status);
  1326. // Deallocates a TF_ApiDefMap.
  1327. TF_CAPI_EXPORT extern void TF_DeleteApiDefMap(TF_ApiDefMap* apimap);
  1328. // Add ApiDefs to the map.
  1329. //
  1330. // `text` corresponds to a text representation of an ApiDefs protocol message.
  1331. // (https://www.tensorflow.org/code/tensorflow/core/framework/api_def.proto).
  1332. //
  1333. // The provided ApiDefs will be merged with existing ones in the map, with
  1334. // precedence given to the newly added version in case of conflicts with
  1335. // previous calls to TF_ApiDefMapPut.
  1336. TF_CAPI_EXPORT extern void TF_ApiDefMapPut(TF_ApiDefMap* api_def_map,
  1337. const char* text, size_t text_len,
  1338. TF_Status* status);
  1339. // Returns a serialized ApiDef protocol buffer for the TensorFlow operation
  1340. // named `name`.
  1341. TF_CAPI_EXPORT extern TF_Buffer* TF_ApiDefMapGet(TF_ApiDefMap* api_def_map,
  1342. const char* name,
  1343. size_t name_len,
  1344. TF_Status* status);
  1345. // --------------------------------------------------------------------------
  1346. // Kernel definition information.
  1347. // Returns a serialized KernelList protocol buffer containing KernelDefs for all
  1348. // registered kernels.
  1349. TF_CAPI_EXPORT extern TF_Buffer* TF_GetAllRegisteredKernels(TF_Status* status);
  1350. // Returns a serialized KernelList protocol buffer containing KernelDefs for all
  1351. // kernels registered for the operation named `name`.
  1352. TF_CAPI_EXPORT extern TF_Buffer* TF_GetRegisteredKernelsForOp(
  1353. const char* name, TF_Status* status);
  1354. // Update edge, switch input/ output in a node
  1355. TF_CAPI_EXPORT extern void TF_UpdateEdge(TF_Graph* graph, TF_Output new_src,
  1356. TF_Input dst, TF_Status* status);
  1357. // --------------------------------------------------------------------------
  1358. // In-process TensorFlow server functionality, for use in distributed training.
  1359. // A Server instance encapsulates a set of devices and a Session target that
  1360. // can participate in distributed training. A server belongs to a cluster
  1361. // (specified by a ClusterSpec), and corresponds to a particular task in a
  1362. // named job. The server can communicate with any other server in the same
  1363. // cluster.
  1364. // In-process TensorFlow server.
  1365. typedef struct TF_Server TF_Server;
  1366. // Creates a new in-process TensorFlow server configured using a serialized
  1367. // ServerDef protocol buffer provided via `proto` and `proto_len`.
  1368. //
  1369. // The server will not serve any requests until TF_ServerStart is invoked.
  1370. // The server will stop serving requests once TF_ServerStop or
  1371. // TF_DeleteServer is invoked.
  1372. TF_CAPI_EXPORT extern TF_Server* TF_NewServer(const void* proto,
  1373. size_t proto_len,
  1374. TF_Status* status);
  1375. // Starts an in-process TensorFlow server.
  1376. TF_CAPI_EXPORT extern void TF_ServerStart(TF_Server* server, TF_Status* status);
  1377. // Stops an in-process TensorFlow server.
  1378. TF_CAPI_EXPORT extern void TF_ServerStop(TF_Server* server, TF_Status* status);
  1379. // Blocks until the server has been successfully stopped (via TF_ServerStop or
  1380. // TF_ServerClose).
  1381. TF_CAPI_EXPORT extern void TF_ServerJoin(TF_Server* server, TF_Status* status);
  1382. // Returns the target string that can be provided to TF_SetTarget() to connect
  1383. // a TF_Session to `server`.
  1384. //
  1385. // The returned string is valid only until TF_DeleteServer is invoked.
  1386. TF_CAPI_EXPORT extern const char* TF_ServerTarget(TF_Server* server);
  1387. // Destroy an in-process TensorFlow server, frees memory. If server is running
  1388. // it will be stopped and joined.
  1389. TF_CAPI_EXPORT extern void TF_DeleteServer(TF_Server* server);
  1390. // Register a listener method that processes printed messages.
  1391. //
  1392. // If any listeners are registered, the print operator will call all listeners
  1393. // with the printed messages and immediately return without writing to the
  1394. // logs.
  1395. TF_CAPI_EXPORT extern void TF_RegisterLogListener(
  1396. void (*listener)(const char*));
  1397. // Register a FileSystem plugin from filename `plugin_filename`.
  1398. //
  1399. // On success, place OK in status.
  1400. // On failure, place an error status in status.
  1401. TF_CAPI_EXPORT extern void TF_RegisterFilesystemPlugin(
  1402. const char* plugin_filename, TF_Status* status);
  1403. #ifdef __cplusplus
  1404. } /* end extern "C" */
  1405. #endif
  1406. #endif // TENSORFLOW_C_C_API_H_
粤ICP备19079148号