c_runtime_api.h 17.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
tqchen committed
21
 * \file tvm/runtime/c_runtime_api.h
22 23 24 25 26 27
 * \brief TVM runtime library.
 *
 *  The philosophy of TVM project is to customize the compilation
 *  stage to generate code that can used by other projects transparently.
 *  So this is a minimum runtime code gluing, and some limited
 *  memory management code to enable quick testing.
28 29 30 31 32 33 34
 *
 *  The runtime API is independent from TVM compilation stack and can
 *  be linked via libtvm_runtime.
 *
 *  The common flow is:
 *   - Use TVMFuncListGlobalNames to get global function name
 *   - Use TVMFuncCall to call these functions.
35
 */
36 37
#ifndef TVM_RUNTIME_C_RUNTIME_API_H_
#define TVM_RUNTIME_C_RUNTIME_API_H_
38

39 40 41 42 43 44 45
// Macros to do weak linking
#ifdef _MSC_VER
#define TVM_WEAK __declspec(selectany)
#else
#define TVM_WEAK __attribute__((weak))
#endif

46 47 48 49 50 51
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#define TVM_DLL EMSCRIPTEN_KEEPALIVE
#endif

#ifndef TVM_DLL
52 53 54 55 56 57 58
#ifdef _WIN32
#ifdef TVM_EXPORTS
#define TVM_DLL __declspec(dllexport)
#else
#define TVM_DLL __declspec(dllimport)
#endif
#else
59
#define TVM_DLL __attribute__((visibility("default")))
60
#endif
61
#endif
62

63
// TVM version
64
#define TVM_VERSION "0.7.dev1"
65 66


67 68
// TVM Runtime is DLPack compatible.
#include <dlpack/dlpack.h>
69

70
#ifdef __cplusplus
71
extern "C" {
72 73 74 75
#endif
#include <stdint.h>
#include <stddef.h>

76
/*! \brief type of array index. */
77
typedef int64_t tvm_index_t;
78 79 80

/*! \brief Extension device types in TVM */
typedef enum {
81
  kDLAOCL = 5,
82
  kDLSDAccel = 6,
83
  kOpenGL = 11,
84
  kDLMicroDev = 13,
85
  kDLHexagon = 14,
86
  // AddExtraTVMType which is not in DLPack here
87 88
} TVMDeviceExtType;

89
/*!
90
 * \brief The type code in used in the TVM FFI.
91 92
 */
typedef enum {
93
  // The type code of other types are compatible with DLPack.
94 95
  // The next few fields are extension types
  // that is used by TVM API calls.
96 97 98
  kTVMOpaqueHandle = 3U,
  kTVMNullptr = 4U,
  kTVMDataType = 5U,
99
  kTVMContext = 6U,
100 101 102 103 104 105 106
  kTVMDLTensorHandle = 7U,
  kTVMObjectHandle = 8U,
  kTVMModuleHandle = 9U,
  kTVMPackedFuncHandle = 10U,
  kTVMStr = 11U,
  kTVMBytes = 12U,
  kTVMNDArrayHandle = 13U,
107
  kTVMObjectRValueRefArg = 14U,
108 109 110 111
  // Extension codes for other frameworks to integrate TVM PackedFunc.
  // To make sure each framework's id do not conflict, use first and
  // last sections to mark ranges.
  // Open an issue at the repo if you need a section of code.
112 113 114
  kTVMExtBegin = 15U,
  kTVMNNVMFirst = 16U,
  kTVMNNVMLast = 20U,
115
  // The following section of code is used for non-reserved types.
116 117
  kTVMExtReserveEnd = 64U,
  kTVMExtEnd = 128U,
118
  // The rest of the space is used for custom, user-supplied datatypes
119
  kTVMCustomBegin = 129U,
120 121 122
} TVMTypeCode;

/*!
123 124 125 126
 * \brief The Device information, abstract away common device types.
 */
typedef DLContext TVMContext;

127
/*! \brief the array handle */
128
typedef DLTensor* TVMArrayHandle;
129

130
/*!
131 132 133 134 135 136 137 138
 * \brief Union type of values
 *  being passed through API and function calls.
 */
typedef union {
  int64_t v_int64;
  double v_float64;
  void* v_handle;
  const char* v_str;
139
  DLDataType v_type;
140
  TVMContext v_ctx;
141 142 143
} TVMValue;

/*!
144
 * \brief Byte array type used to pass in byte array
145
 *  When kTVMBytes is used as data type.
146 147 148 149 150 151
 */
typedef struct {
  const char* data;
  size_t size;
} TVMByteArray;

152 153
/*! \brief Handle to TVM runtime modules. */
typedef void* TVMModuleHandle;
154
/*! \brief Handle to packed function handle. */
155
typedef void* TVMFunctionHandle;
156 157
/*! \brief Handle to hold return value. */
typedef void* TVMRetValueHandle;
158 159 160 161 162
/*!
 * \brief The stream that is specific to device
 * can be NULL, which indicates the default one.
 */
typedef void* TVMStreamHandle;
163 164
/*! \brief Handle to Object. */
typedef void* TVMObjectHandle;
165 166

/*!
167 168 169 170 171 172 173
 * \brief Used for implementing C API function.
 *  Set last error message before return.
 * \param msg The error message to be set.
 */
TVM_DLL void TVMAPISetLastError(const char* msg);

/*!
174 175
 * \brief return str message of the last error
 *  all function in this file will return 0 when success
176
 *  and -1 when an error occurred,
177 178 179 180 181 182 183
 *  TVMGetLastError can be called to retrieve the error
 *
 *  this function is threadsafe and can be called by different thread
 *  \return error info
 */
TVM_DLL const char *TVMGetLastError(void);
/*!
184 185 186 187
 * \brief Load module from file.
 * \param file_name The file name to load the module from.
 * \param format The format of the module.
 * \param out The result module
188
 *
189
 * \return 0 when success, -1 when failure happens
190 191
 * \note The resulting module do not contain import relation.
 *  It can be reconstructed by TVMModImport.
192
 */
193 194 195
TVM_DLL int TVMModLoadFromFile(const char* file_name,
                               const char* format,
                               TVMModuleHandle* out);
196 197

/*!
198 199
 * \brief Add dep to mod's dependency.
 *  This allows functions in this module to use modules.
200
 *
201 202 203
 * \param mod The module handle.
 * \param dep The dependent module to be imported.
 * \return 0 when success, -1 when failure happens
204
 */
205 206
TVM_DLL int TVMModImport(TVMModuleHandle mod,
                         TVMModuleHandle dep);
207 208

/*!
209 210 211 212 213 214
 * \brief Get function from the module.
 * \param mod The module handle.
 * \param func_name The name of the function.
 * \param query_imports Whether to query imported modules
 * \param out The result function, can be NULL if it is not available.
 * \return 0 when no error is thrown, -1 when failure happens
215
 */
216 217 218 219 220
TVM_DLL int TVMModGetFunction(TVMModuleHandle mod,
                              const char* func_name,
                              int query_imports,
                              TVMFunctionHandle *out);

221
/*!
222 223 224 225 226 227 228 229
 * \brief Free the Module
 * \param mod The module to be freed.
 *
 * \note This may not free up the module's resources.
 *  If there is active TVMFunctionHandle uses the module
 *  Or if this module is imported by another active module.
 *
 *  The all functions remains valid until TVMFuncFree is called.
230
 * \return 0 when success, -1 when failure happens
231 232 233 234
 */
TVM_DLL int TVMModFree(TVMModuleHandle mod);

/*!
235 236
 * \brief Free the function when it is no longer needed.
 * \param func The function handle
237
 * \return 0 when success, -1 when failure happens
238
 */
239
TVM_DLL int TVMFuncFree(TVMFunctionHandle func);
240 241

/*!
242
 * \brief Call a Packed TVM Function.
243
 *
244
 * \param func node handle of the function.
245
 * \param arg_values The arguments
246
 * \param type_codes The type codes of the arguments
247
 * \param num_args Number of arguments.
248
 *
249 250 251
 * \param ret_val The return value.
 * \param ret_type_code the type code of return value.
 *
252 253
 * \return 0 when success, -1 when failure happens
 * \note TVM calls always exchanges with type bits=64, lanes=1
254 255 256 257 258 259
 *
 * \note API calls always exchanges with type bits=64, lanes=1
 *   If API call returns container handles (e.g. FunctionHandle)
 *   these handles should be managed by the front-end.
 *   The front-end need to call free function (e.g. TVMFuncFree)
 *   to free these handles.
260
 */
261
TVM_DLL int TVMFuncCall(TVMFunctionHandle func,
262
                        TVMValue* arg_values,
263
                        int* type_codes,
264 265 266 267 268 269 270 271 272 273 274 275 276
                        int num_args,
                        TVMValue* ret_val,
                        int* ret_type_code);

/*!
 * \brief Set the return value of TVMPackedCFunc.
 *
 *  This function is called by TVMPackedCFunc to set the return value.
 *  When this function is not called, the function returns null by default.
 *
 * \param ret The return value handle, pass by ret in TVMPackedCFunc
 * \param value The value to be returned.
 * \param type_code The type of the value to be returned.
277
 * \param num_ret Number of return values, for now only 1 is supported.
278 279
 */
TVM_DLL int TVMCFuncSetReturn(TVMRetValueHandle ret,
280 281 282
                              TVMValue* value,
                              int* type_code,
                              int num_ret);
283 284

/*!
285 286 287 288 289 290 291 292 293
 * \brief Inplace translate callback argument value to return value.
 *  This is only needed for non-POD arguments.
 *
 * \param value The value to be translated.
 * \param code The type code to be translated.
 * \note This function will do a shallow copy when necessary.
 *
 * \return 0 when success, -1 when failure happens.
 */
294
TVM_DLL int TVMCbArgToReturn(TVMValue* value, int* code);
295 296

/*!
297 298 299 300 301
 * \brief C type of packed function.
 *
 * \param args The arguments
 * \param type_codes The type codes of the arguments
 * \param num_args Number of arguments.
302
 * \param ret The return value handle.
303
 * \param resource_handle The handle additional resouce handle from fron-end.
304
 * \return 0 if success, -1 if failure happens, set error via TVMAPISetLastError.
305
 * \sa TVMCFuncSetReturn
306
 */
307
typedef int (*TVMPackedCFunc)(
308 309 310 311 312
    TVMValue* args,
    int* type_codes,
    int num_args,
    TVMRetValueHandle ret,
    void* resource_handle);
313 314 315 316 317 318 319 320

/*!
 * \brief C callback to free the resource handle in C packed function.
 * \param resource_handle The handle additional resouce handle from fron-end.
 */
typedef void (*TVMPackedCFuncFinalizer)(void* resource_handle);

/*!
321 322 323 324 325
 * \brief Signature for extension function declarer.
 *
 *  TVM call this function to get the extension functions
 *  The declarer will call register_func to register function and their name.
 *
326
 * \param register_func_handle The register function
327 328 329 330 331
 * \return 0 if success, -1 if failure happens
 */
typedef int (*TVMExtensionFuncDeclarer)(TVMFunctionHandle register_func_handle);

/*!
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
 * \brief Wrap a TVMPackedCFunc to become a FunctionHandle.
 *
 * The resource_handle will be managed by TVM API, until the function is no longer used.
 *
 * \param func The packed C function.
 * \param resource_handle The resource handle from front-end, can be NULL.
 * \param fin The finalizer on resource handle when the FunctionHandle get freed, can be NULL
 * \param out the result function handle.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMFuncCreateFromCFunc(TVMPackedCFunc func,
                                   void* resource_handle,
                                   TVMPackedCFuncFinalizer fin,
                                   TVMFunctionHandle *out);

/*!
 * \brief Register the function to runtime's global table.
 *
 * The registered function then can be pulled by the backend by the name.
 *
 * \param name The name of the function.
 * \param f The function to be registered.
354
 * \param override Whether allow override already registered function.
355
 */
356 357
TVM_DLL int TVMFuncRegisterGlobal(
    const char* name, TVMFunctionHandle f, int override);
358 359 360 361 362

/*!
 * \brief Get a global function.
 *
 * \param name The name of the function.
363
 * \param out the result function pointer, NULL if it does not exist.
364 365 366
 *
 * \note The function handle of global function is managed by TVM runtime,
 *  So TVMFuncFree is should not be called when it get deleted.
367 368
 */
TVM_DLL int TVMFuncGetGlobal(const char* name, TVMFunctionHandle* out);
369 370 371 372 373 374 375

/*!
 * \brief List all the globally registered function name
 * \param out_size The number of functions
 * \param out_array The array of function names.
 * \return 0 when success, -1 when failure happens
 */
376
TVM_DLL int TVMFuncListGlobalNames(int* out_size,
377
                                   const char*** out_array);
378

379
// Array related apis for quick proptyping
380 381 382 383 384 385
/*!
 * \brief Allocate a nd-array's memory,
 *  including space of shape, of given spec.
 *
 * \param shape The shape of the array, the data content will be copied to out
 * \param ndim The number of dimension of the array.
386 387 388 389 390
 * \param dtype_code The type code of the dtype
 * \param dtype_bits The number of bits of dtype
 * \param dtype_lanes The number of lanes in the dtype.
 * \param device_type The device type of context
 * \param device_id The device id of context.
391 392 393 394
 * \param out The output handle.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayAlloc(const tvm_index_t* shape,
395
                          int ndim,
396 397 398 399 400
                          int dtype_code,
                          int dtype_bits,
                          int dtype_lanes,
                          int device_type,
                          int device_id,
401
                          TVMArrayHandle* out);
402

403 404 405 406 407 408 409 410
/*!
 * \brief Free the TVM Array.
 * \param handle The array handle to be freed.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayFree(TVMArrayHandle handle);

/*!
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
 * \brief Copy array data from CPU byte array.
 * \param handle The array handle.
 * \param data the data pointer
 * \param nbytes The number of bytes to copy.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayCopyFromBytes(TVMArrayHandle handle,
                                  void* data,
                                  size_t nbytes);

/*!
 * \brief Copy array data to CPU byte array.
 * \param handle The array handle.
 * \param data the data pointer
 * \param nbytes The number of bytes to copy.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayCopyToBytes(TVMArrayHandle handle,
                                void* data,
                                size_t nbytes);

/*!
433 434 435 436 437 438 439 440 441
 * \brief Copy the array, both from and to must be valid during the copy.
 * \param from The array to be copied from.
 * \param to The target space.
 * \param stream The stream where the copy happens, can be NULL.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayCopyFromTo(TVMArrayHandle from,
                               TVMArrayHandle to,
                               TVMStreamHandle stream);
442 443

/*!
eqy committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
 * \brief Produce an array from the DLManagedTensor that shares data memory
 * with the DLManagedTensor.
 * \param from The source DLManagedTensor.
 * \param out The output array handle.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayFromDLPack(DLManagedTensor* from,
                               TVMArrayHandle* out);

/*!
 * \brief Produce a DLMangedTensor from the array that shares data memory with
 * the array.
 * \param from The source array.
 * \param out The DLManagedTensor handle.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMArrayToDLPack(TVMArrayHandle from,
                             DLManagedTensor** out);

/*!
 * \brief Delete (free) a DLManagedTensor's data.
465
 * \param dltensor Pointer to the DLManagedTensor.
eqy committed
466 467 468 469
 */
TVM_DLL void TVMDLManagedTensorCallDeleter(DLManagedTensor* dltensor);

/*!
tqchen committed
470
 * \brief Create a new runtime stream.
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
 *
 * \param device_type The device type of context
 * \param device_id The device id of context
 * \param out The new stream handle
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMStreamCreate(int device_type, int device_id, TVMStreamHandle* out);

/*!
 * \brief Free a created stream handle.
 *
 * \param device_type The device type of context
 * \param device_id The device id of context
 * \param stream The stream to be freed
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMStreamFree(int device_type, int device_id, TVMStreamHandle stream);

/*!
490 491 492 493 494
 * \brief Set the runtime stream of current thread to be stream.
 *  The subsequent calls to the same device_type
 *  will use the setted stream handle.
 *  The specific type of stream is runtime device dependent.
 *
495 496
 * \param device_type The device type of context
 * \param device_id The device id of context.
497 498 499
 * \param handle The stream handle.
 * \return 0 when success, -1 when failure happens
 */
500
TVM_DLL int TVMSetStream(int device_type, int device_id, TVMStreamHandle handle);
501

502 503
/*!
 * \brief Wait until all computations on stream completes.
504 505 506
 *
 * \param device_type The device type of context
 * \param device_id The device id of context.
507 508 509
 * \param stream The stream to be synchronized.
 * \return 0 when success, -1 when failure happens
 */
510
TVM_DLL int TVMSynchronize(int device_type, int device_id, TVMStreamHandle stream);
511

512 513 514 515 516 517 518 519 520 521 522 523 524 525
/*!
 * \brief Synchronize two streams of execution.
 *
 * \param device_type The device type of context
 * \param device_id The device id of context
 * \param src The source stream to synchronize.
 * \param dst The destination stream to synchronize.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMStreamStreamSynchronize(int device_type,
                                       int device_id,
                                       TVMStreamHandle src,
                                       TVMStreamHandle dst);

526
/*!
527
 * \brief Get the type_index from an object.
528 529
 *
 * \param obj The object handle.
530
 * \param out_tindex the output type index.
531 532
 * \return 0 when success, -1 when failure happens
 */
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
TVM_DLL int TVMObjectGetTypeIndex(TVMObjectHandle obj, unsigned* out_tindex);

/*!
 * \brief Convert type key to type index.
 * \param type_key The key of the type.
 * \param out_tindex the corresponding type index.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMObjectTypeKey2Index(const char* type_key, unsigned* out_tindex);

/*!
 * \brief Free the object.
 *
 * \param obj The object handle.
 * \note Internally we decrease the reference counter of the object.
 *       The object will be freed when every reference to the object are removed.
 * \return 0 when success, -1 when failure happens
 */
TVM_DLL int TVMObjectFree(TVMObjectHandle obj);
552

553
#ifdef __cplusplus
554
}  // TVM_EXTERN_C
555
#endif
556
#endif  // TVM_RUNTIME_C_RUNTIME_API_H_