Tensor Operation

Function Description

Vision SDK tensor operation specifies the assigned input tensor and allocates memory to the output tensor. The tensor operation API performs the operation and assigns the result to the output tensor.

For details about related APIs, see TensorOperations.

API Calling Process

Before calling the tensor operation APIs, create the input and output tensors, allocate the memory, and assign a value to the input tensor.

The input and output data types must be the same.

For four arithmetic operations and bitwise operations, the shapes of the input and output tensors must be the same. For tensor transposition, rotation, channel splitting, channel merging, cropping, and extension APIs, the shapes of the input and output tensors must comply with the corresponding operation specifications.

For details about the API functions, see TensorOperations.

The following uses Add as an example to describe the tensor operation process:

Figure 1 Process of calling APIs in tensor mode

Key steps are demonstrated as follows:

  1. Perform global initialization by calling MxInit().
  2. Initialize the tensors and allocate the memory. You need to initialize the input and output and allocate memory.
    • For the input tensor, create the tensor data and input the tensor shape and type for initialization. You can also specify the device where the tensor is located.
    • For the output tensor, input the tensor shape and type for initialization. You can also specify the device where the tensor is located, and allocate memory for the tensor by calling Tensor.Malloc().
    • For a tensor whose device is not specified during initialization, use the ToDevice(int DeviceId) method to compute the tensor on the specified device after initialization.
  3. Select the synchronous or asynchronous calling mode of the operator API based on the service requirements for tensor computing.
    • Synchronous execution

      No stream is created. The Add method is passed to the input tensor to obtain the result of tensor addition.

    • Asynchronous execution
      1. Create a stream. For details, see Asynchronous Invocation.
      2. Pass the input tensor, created stream, and other parameters to the Add method to obtain the tensor addition result.
  4. Deinitialize the initialized global resources by calling MxDeInit().

Sample Code

The following is a code example of key steps of functions and features of the tensor add API, which is for reference only and cannot be directly copied for compilation or running.