From PTO to Output Code

Overview

This document uses an A3 vec add kernel throughout the compilation and running process: the two input vectors a and b and the output vector c each contain 1024 consecutive float32 elements, computing c[i] = a[i] + b[i] (0 <= i < 1024). The kernel represents each vector as a 1 x 1024 tile and uses one block to complete the computation.

For users, a complete pipeline typically consists of 5 steps:

  1. Write the .pto file
  2. Use ptoas to generate the kernel C++.
  3. Prepare launch.cpp to expose the kernel entry as a host-callable wrapper.
  4. Use the CCE compiler to compile the kernel C++ and launch.cpp into a host-linkable fatobj.
  5. Allocate memory in the host program, call the launch wrapper, and run it through Ascend Computing Language (AscendCL or ACL for short).

If your generated code needs to call the PTO instruction API, it will do so through the unified entry header file provided by pto-isa:

#include <pto/pto-inst.hpp>

For usage of pto-isa, see:

In this document, the pto-isa header file is uniformly written as #include <pto/pto-inst.hpp> (the unified entry header form recommended by pto-isa); the header files provided by CANN are written as #include "acl/acl.h" following CANN conventions. Note that the C++ generated by ptoas itself outputs the quoted form #include "pto/pto-inst.hpp". Both forms point to the same header file and can be used interchangeably.

Step 1: Generating Kernel C++ Using ptoas

The complete input file is vec_add.pto. Apart from the file header comments, its content is as follows and can be saved directly as vec_add.pto:

!vec_tile = !pto.tile_buf<vec, 1x1024xf32>

module attributes {pto.target_arch = "a3"} {
  func.func @vec_add(%a: !pto.ptr<f32>, %b: !pto.ptr<f32>, %c: !pto.ptr<f32>)
      attributes {pto.entry, pto.kernel_kind = #pto.kernel_kind<vector>} {
    %c0 = arith.constant 0 : index
    %c1 = arith.constant 1 : index
    %c1024 = arith.constant 1024 : index

    %a_view = pto.make_tensor_view %a, shape = [%c1, %c1024], strides = [%c1024, %c1]
        : !pto.tensor_view<?x?xf32>
    %b_view = pto.make_tensor_view %b, shape = [%c1, %c1024], strides = [%c1024, %c1]
        : !pto.tensor_view<?x?xf32>
    %c_view = pto.make_tensor_view %c, shape = [%c1, %c1024], strides = [%c1024, %c1]
        : !pto.tensor_view<?x?xf32>

    %a_part = pto.partition_view %a_view, offsets = [%c0, %c0], sizes = [%c1, %c1024]
        : !pto.tensor_view<?x?xf32> -> !pto.partition_tensor_view<1x1024xf32>
    %b_part = pto.partition_view %b_view, offsets = [%c0, %c0], sizes = [%c1, %c1024]
        : !pto.tensor_view<?x?xf32> -> !pto.partition_tensor_view<1x1024xf32>
    %c_part = pto.partition_view %c_view, offsets = [%c0, %c0], sizes = [%c1, %c1024]
        : !pto.tensor_view<?x?xf32> -> !pto.partition_tensor_view<1x1024xf32>

    %a_tile = pto.alloc_tile : !vec_tile
    %b_tile = pto.alloc_tile : !vec_tile
    %c_tile = pto.alloc_tile : !vec_tile

    pto.tload ins(%a_part : !pto.partition_tensor_view<1x1024xf32>) outs(%a_tile : !vec_tile)
    pto.tload ins(%b_part : !pto.partition_tensor_view<1x1024xf32>) outs(%b_tile : !vec_tile)
    pto.tadd ins(%a_tile, %b_tile : !vec_tile, !vec_tile) outs(%c_tile : !vec_tile)
    pto.tstore ins(%c_tile : !vec_tile) outs(%c_part : !pto.partition_tensor_view<1x1024xf32>)
    return
  }
}

shape, sizes, and strides are all in units of elements; strides = [1024, 1] indicates contiguous row-major storage. !vec_tile is a type alias within this file, representing 1 x 1024 f32 elements stored in the vector computation storage area, with the entire tile participating in the computation.

pto.entry marks vec_add as a kernel entry that can be launched from the host; pto.kernel_kind = #pto.kernel_kind<vector> specifies that it performs vector computation.

Run the following command in the directory where vec_add.pto is located:

ptoas vec_add.pto --pto-arch=a3 --pto-backend=emitc \
  --enable-insert-sync -o vec_add_kernel.cpp

Common parameters include:

  • --pto-arch=a3|a5: specifies the target generation.
  • --pto-backend=emitc: generates C++ that calls the PTO instruction APIs, for use in the CCE compilation process described in this document.
  • --enable-insert-sync: inserts the necessary synchronization for input transfer, vector computation, and output transfer; this option must be retained for the example in this document.

Step 2: How Generated Code Integrates with pto-isa

The C++ generated by ptoas typically includes the PTO instruction header files directly and maps the operations in the PTO ISA to PTO instruction APIs.

The following shows the main PTO API calls for vec add. To highlight the data flow, the illustrative code omits address binding and automatic synchronization; the complete vec_add_kernel.cpp generated in step 1 is used for the actual build.

#include <pto/pto-inst.hpp>
using namespace pto;

extern "C" __global__ AICORE void vec_add(__gm__ float* a, __gm__ float* b, __gm__ float* c) {
  using VecTile = Tile<TileType::Vec, float, 1, 1024, BLayout::RowMajor, 1, 1024>;
  using VecShape = Shape<1, 1, 1, 1, 1024>;
  using VecStride = Stride<1024, 1024, 1024, 1024, 1>;
  using VecTensor = GlobalTensor<float, VecShape, VecStride>;

  VecTile tileA;
  VecTile tileB;
  VecTile tileC;
  VecTensor gA(a);
  VecTensor gB(b);
  VecTensor gC(c);

  // The complete generated code binds storage addresses for the tile.
  TLOAD(tileA, gA);
  TLOAD(tileB, gB);
  // The complete generated code waits for the input transfer to finish before computation.
  TADD(tileC, tileA, tileB);
  // The complete generated code waits for the computation to finish before writing back.
  TSTORE(gC, tileC);
}

The integration relationship here can be summarized as follows:

  • PTO ISA describes tile-level semantics.
  • ptoas translates these semantics into PTO instruction API calls.
  • pto-isa provides the type system, instruction declarations, and target-specific implementations corresponding to these APIs.

From the user's perspective, after ptoas generates the code, the next step is not to manually write the tile instruction body again, but to let the CCE compiler continue compiling these C++ files that already call the PTO instruction APIs.

Step 3: Preparing launch.cpp

launch.cpp wraps the device-side kernel entry into a callable function on the host side. The minimal form is as follows:

#include <pto/pto-inst.hpp>
#include "acl/acl.h"

extern "C" __global__ AICORE void vec_add(__gm__ float* a, __gm__ float* b, __gm__ float* c);

void LaunchVecAdd(float *a, float *b, float *c, aclrtStream stream) {
  vec_add<<<1, nullptr, stream>>>(a, b, c);
}

Here, one block is launched, which is consistent with the convention in .pto of processing an entire 1 x 1024 tile. a, b, and c must be device addresses pointing to three independent buffers, each of which is at least 1024 * sizeof(float), that is, 4096 bytes.

The extern "C" in the kernel declaration is consistent with the entry generated by pto.entry, so that launch.cpp can correctly link to vec_add.

Step 4: Generating fatobj Using the CCE Compiler

Role of fatobj

Here, fatobj can be understood as:

  • Linkable to the host.
  • Carrying the device binary internally.
  • Directly linkable by a host-executable program or shared library

Therefore, what users ultimately link is usually not a bare device target, but a host-linkable artifact that carries the device image.

Typical Compilation Method

Prepare the CANN environment, point PTO_ISA_ROOT to the pto-isa source directory, and confirm that ASCEND_HOME_PATH points to the CANN installation directory. Save the code from step 3 as launch.cpp, and then compile it together with the generated kernel C++:

bisheng -std=c++17 -shared -fPIC \
  -xcce \
  --cce-aicore-arch=dav-c220-vec \
  --cce-fatobj-link \
  vec_add_kernel.cpp launch.cpp \
  -I"${PTO_ISA_ROOT}/include" \
  -I"${ASCEND_HOME_PATH}/include" \
  -I"${ASCEND_HOME_PATH}/pkg_inc" \
  -o libvec_add_kernel.so

This document uses vector computation, so the dav-c220-vec compilation target corresponding to A3 is selected.

In CMake, the most critical item is usually the following:

target_link_options(vec_add_kernel PRIVATE --cce-fatobj-link)

Step 5: How the Host Program Runs the fatobj

The basic process of the host program is as follows:

  1. Call aclInit.
  2. Call aclrtSetDevice.
  3. Call aclrtCreateStream.
  4. Allocate host/device memory.
  5. Copy the input from the host to the device.
  6. Call LaunchVecAdd(devA, devB, devC, stream).
  7. Call aclrtSynchronizeStream.
  8. Copy the output from the device back to the host.
  9. Compare hostC[i] with hostA[i] + hostB[i] element by element.
  10. Release the host/device memory, destroy the stream, reset the device, and call aclFinalize.

The following is the call snippet for steps 6 and 7, which can be placed in main.cpp. Before the call, complete ACL initialization, stream creation, allocation of the three device buffers, and input copy. After the call, check the return value, and then copy the 4096-byte output back to the host for comparison. A complete host program also needs to check the return value of each ACL call and release the allocated resources before exiting.

#include "acl/acl.h"

void LaunchVecAdd(float *a, float *b, float *c, aclrtStream stream);

aclError RunVecAdd(float *devA, float *devB, float *devC, aclrtStream stream) {
  LaunchVecAdd(devA, devB, devC, stream);
  return aclrtSynchronizeStream(stream);
}

For example, if hostA[i] = float(i) and hostB[i] = 1.0f is configured, then the expected result is hostC[i] = float(i) + 1.0f. For general floating-point inputs, set the comparison tolerance according to the required precision.

For a single sample, the following structure is recommended:

vec_add_example/
├── vec_add.pto
├── vec_add_kernel.cpp
├── launch.cpp
├── main.cpp
└── CMakeLists.txt

Where:

  • vec_add.pto: complete PTO ISA input. See the accompanying file.
  • vec_add_kernel.cpp: output of ptoas.
  • launch.cpp: kernel wrapper.
  • main.cpp: host-side entry point.
  • CMakeLists.txt: calls bisheng to generate the fatobj and link the host program.

Common Notes

--pto-arch Must Match the Target Generation

If a .pto file targets A5 but is compiled for A3, the common results are as follows:

  • Type or operation constraint mismatch.
  • Some ops are not supported by the target.

Keeping the Kernel Parameter Order Consistent

The function parameter order in .pto, the generated kernel formal parameter order, the launch.cpp wrapper parameter order, and the host-side call order must be consistent.

Keeping Input Length Consistent with Launch Scale

This example processes only 1024 elements and does not include logic for dividing data by block or handling tail blocks. Shortening the buffer causes out-of-bounds access, and increasing the number of blocks causes multiple blocks to write repeatedly to the same output region. When changing the length or parallelism scale, you must also modify the views and tiles in the .pto file, the launch configuration, and the host memory allocation.

Compilation Passes Does Not Mean Correct Execution

Successful compilation by ptoas and bisheng only indicates that:

  • The PTO ISA structure is basically valid.
  • The generated PTO instruction call form is basically valid.

Whether the result meets expectations still requires you to further check the execution result on the board according to your own scenario.