Hello Sort

Write a host program and a device kernel, then build and run it with a compiler invocation.

See Compiler for compiler options and supported language features.

Overview

This tutorial sorts independent arrays on the device. The tutorial has three steps:

  • Mark a function as a device kernel with __pxl_kernel__
  • Launch it from host code with pxl::Launcher
  • Build host + device with pxcc++ and run the result

Read PXL Key Concepts first for the task and device memory model.

1. Write the source

Create sort.cpp. The kernel and the host main() live in the same file.

#include <algorithm>
#include <cstdio>
#include "mu/mu.hpp"
#include "pxl/pxl.hpp"

// A device kernel is just a function annotated with __pxl_kernel__.
// Each parallel task sorts its own sub-array; mu::getTaskIdx() gives
// the index of the running task.
__pxl_kernel__ void sort_with_ptr(int* arr, int size)
{
    int idx = mu::getTaskIdx();
    int* base = arr + idx * size;
    std::sort(base, base + size);
}

int main()
{
    const int testCount = 2048;  // number of parallel tasks
    const int sortSize = 64;     // elements per task

    // Allocate device (CXL) memory and fill each array in descending order.
    auto* data = pxl::allocateMemory<int>(0, testCount * sortSize);
    if (!data)
    {
        printf("Allocation failed\n");
        return 1;
    }
    for (int i = 0; i < testCount; i++)
        for (int j = 0; j < sortSize; j++)
            data[i * sortSize + j] = sortSize - j;

    // Launch one kernel instance per task and wait for completion.
    auto result = pxl::Launcher()
                      .execute<sort_with_ptr>(data, sortSize)
                      .tasks(testCount)
                      .run();
    if (result.status != pxl::Result::Success)
    {
        printf("Launch failed: %s\n", result.errorMessage.c_str());
        pxl::releaseMemory(data);
        return 1;
    }
    printf("test done : %.2f us\n", result.elapsedUs);

    // Verify every array is now sorted in ascending order.
    for (int i = 0; i < testCount; i++)
        for (int j = 1; j < sortSize; j++)
            if (data[i * sortSize + j - 1] > data[i * sortSize + j])
            {
                printf("Verification failed at [%d][%d]\n", i, j);
                pxl::releaseMemory(data);
                return 1;
            }

    pxl::releaseMemory(data);
    return 0;
}

The host selects the kernel by its C++ symbol with execute<sort_with_ptr>(...).

2. Compile

A single command compiles both the host and the device code and links them into one executable:

pxcc++ sort.cpp -o sort

The same build runs from CMake:

cmake_minimum_required(VERSION 3.21)
set(CMAKE_CXX_COMPILER pxcc++)
project(sort LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(sort sort.cpp)

3. Run

sudo ./sort   # CXL device memory access requires elevated privileges

Expected output:

test done : XXXX.XX us

The elapsed time varies by hardware.

If any array is not sorted correctly, the program prints Verification failed at [i][j] (with the offending coordinates) and exits non-zero.

Declare input and output buffers

The first example sorts in place, so int* correctly uses Launcher’s legacy bidirectional synchronization. When a kernel has separate source and destination buffers, declare their directions in the kernel signature:

__pxl_kernel__ void copy_then_sort(mu::input_ptr<int> input,
                                   mu::output_ptr<int> output,
                                   int size)
{
    const int offset = mu::getTaskIdx() * size;
    const int* source = input;
    int* destination = output;

    std::copy(source + offset, source + offset + size, destination + offset);
    std::sort(destination + offset, destination + offset + size);
}

Inside main(), reuse the initialized data buffer from the first example as input and allocate a separate output buffer of the same size:

auto* input = data;
auto* output = pxl::allocateMemory<int>(testCount * sortSize);
if (!output)
{
    printf("Output allocation failed\n");
    return 1;
}

auto result = pxl::Launcher()
                  .execute<copy_then_sort>(input, output, sortSize)
                  .tasks(testCount)
                  .run();

// Check result.status and use or verify output before releasing it.
pxl::releaseMemory(output);

The host still passes the original int* values. mu::input_ptr<int> tells Launcher to skip synchronization back to the host for input, while mu::output_ptr<int> tells it to skip the ordinary pre-launch upload for output. An unmarked pointer remains bidirectional for existing kernels and in-place algorithms. See Kernel Execution for NDArray behavior and synchronization details.

Template kernels

A kernel function template generates a function for each concrete element type. For example, sort_with_ptr<int> sorts integer arrays. Launcher selects that specialization through its C++ symbol. A separate kernel binary can also contain instantiated template code, but a host that loads kernels by name needs registered entry points for the required specializations.

template <typename T>
__pxl_kernel__ void sort_with_ptr(T* arr, int size)
{
    int idx = mu::getTaskIdx();
    std::sort(arr + idx * size, arr + idx * size + size);
}

// Launch — name the kernel with a concrete type.
auto r = pxl::Launcher().execute<sort_with_ptr<int>>(data, size).tasks(testCount).run();

Explicit type only. A template kernel takes a concrete type argument at the launch, as in sort_with_ptr<int> or sort_with_ptr<FixedString>. Launch (or createModule()->createFunction<…>()) once per type you need.

Overloaded kernels

Two kernels may share one name when their parameter lists differ. pxcc compiles both of them for the device.

__pxl_kernel__ void scale(int* arr, int size)   { /* ... */ }
__pxl_kernel__ void scale(float* arr, int size) { /* ... */ }

The launch takes the kernel as a template argument, so a bare scale leaves the compiler with two candidates and no way to pick one. Declare an alias for the parameter list you want, and launch through that alias:

using ScaleFloat = void (*)(float*, int);

auto r = pxl::Launcher()
             .execute<ScaleFloat(scale)>(data, size)
             .tasks(testCount)
             .run();

The alias states one parameter list, so ScaleFloat(scale) picks the kernel that matches it.

Element types must be trivially copyable - they live in device memory and are moved/swapped by the device sort. Declare a user-defined type struct __mu_shared__ so the type and its operators are available on the device. To sort by name, use a fixed-size character buffer rather than std::string (whose layout and heap pointers differ between the host and device standard libraries):

struct __mu_shared__ FixedString       // sort by name
{
    char data[16];
    bool operator<(const FixedString& rhs) const { /* lexicographic compare */ }
};

struct __mu_shared__ Point             // sort 2-D points by distance from origin
{
    int x, y;
    int dist2() const { return x * x + y * y; }
    bool operator<(const Point& rhs) const { return dist2() < rhs.dist2(); }
};
// ... then: pxl::Launcher()
//               .execute<sort_with_ptr<FixedString>>(...)
//               .tasks(testCount)
//               .run();

A runnable version is in example/template_programming/template_programming.cpp. It selects the element type at run time with --template-type <int|string|custom_type> and sorts one type per run, verifying the device result against a host std::sort:

Build it the same way as the other bundled examples, then run one type per invocation (use sudo - the device sort touches CXL device memory):

cd example/template_programming
./build.sh
sudo ./build/template_programming --template-type int
sudo ./build/template_programming --template-type string
sudo ./build/template_programming --template-type custom_type   # custom struct (Point)

One type is sorted per process because each run issues a single kernel launch.

The examples above run on device 0 by default. Add -d <id> (or --device <id>) to target another device:

../single_source/build.sh
sudo ../single_source/build/single_source -d 1
sudo ./build/template_programming --template-type int -d 1

Next steps

  • Compiler - the annotation model (__pxl_kernel__, __mu_device__, __mu_shared__), options, device flags, and linking.
  • Troubleshooting - common build errors.