Stream-ordered memory allocator#

The Stream-ordered memory allocator (SOMA) is part of the HIP runtime API. SOMA provides an asynchronous memory allocation mechanism with stream-ordering semantics. You can use SOMA to allocate and free memory in stream order, which ensures that all asynchronous accesses occur between the stream executions of allocation and deallocation. Compliance with stream order prevents use-before-allocation or use-after-free errors, which helps to avoid an undefined behavior.

Advantages of SOMA:

  • Efficient reuse: Enables efficient memory reuse across streams, which reduces unnecessary allocation overhead.

  • Fine-grained control: Allows you to set attributes and control caching behavior for memory pools.

  • Inter-process sharing: Enables secure sharing of allocations between processes.

  • Optimizations: Allows driver to optimize based on its awareness of SOMA and other stream management APIs.

Disadvantages of SOMA:

  • Temporal constraints: Requires you to adhere strictly to stream order to avoid errors.

  • Complexity: Involves memory management in stream order, which can be intricate.

  • Learning curve: Requires you to put additional efforts to understand and utilize SOMA effectively.

Using SOMA#

You can allocate memory using hipMallocAsync() with stream-ordered semantics. This restricts the asynchronous access to the memory between the stream executions of the allocation and deallocation. Accessing memory if the compliant memory accesses won’t overlap temporally. hipFreeAsync() frees memory from the pool with stream-ordered semantics.

Here is how to use stream-ordered memory allocation:

#include <hip/hip_runtime.h>

#include <cstddef>
#include <cstdlib>
#include <iostream>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

// Kernel to perform some computation on allocated memory.
__global__ void myKernel(int* data, std::size_t numElements)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    if (tid < numElements)
    {
        data[tid] = tid * 2;
    }
}

int main()
{
    // Stream 0.
    constexpr hipStream_t streamId = 0;

    // Allocate memory with stream ordered semantics.
    constexpr std::size_t numElements = 1024;
    int* devData;
    HIP_CHECK(hipMallocAsync(reinterpret_cast<void**>(&devData), numElements * sizeof(*devData), streamId));

    // Launch the kernel to perform computation.
    dim3 blockSize(256);
    dim3 gridSize((numElements + blockSize.x - 1) / blockSize.x);
    myKernel<<<gridSize, blockSize>>>(devData, numElements);

    // Copy data back to host.
    int* hostData = new int[numElements];
    HIP_CHECK(hipMemcpy(hostData, devData, numElements * sizeof(*devData), hipMemcpyDeviceToHost));

    // Print the array.
    for (std::size_t i = 0; i < numElements; ++i)
        std::cout << "Element " << i << ": " << hostData[i] << std::endl;

    // Free memory with stream ordered semantics.
    HIP_CHECK(hipFreeAsync(devData, streamId));
    delete[] hostData;

    // Synchronize to ensure completion.
    HIP_CHECK(hipDeviceSynchronize());

    return EXIT_SUCCESS;
}
#include <hip/hip_runtime.h>

#include <cstddef>
#include <iostream>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

// Kernel to perform some computation on allocated memory.
__global__ void myKernel(int* data, std::size_t numElements)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    if (tid < numElements)
    {
        data[tid] = tid * 2;
    }
}

int main()
{
    // Allocate memory.
    constexpr std::size_t numElements = 1024;
    int* devData;
    HIP_CHECK(hipMalloc(&devData, numElements * sizeof(*devData)));

    // Launch the kernel to perform computation.
    dim3 blockSize(256);
    dim3 gridSize((numElements + blockSize.x - 1) / blockSize.x);
    myKernel<<<gridSize, blockSize>>>(devData, numElements);

    // Copy data back to host.
    int* hostData = new int[numElements];
    HIP_CHECK(hipMemcpy(hostData, devData, numElements * sizeof(*devData), hipMemcpyDeviceToHost));

    // Print the array.
    for (std::size_t i = 0; i < numElements; ++i)
        std::cout << "Element " << i << ": " << hostData[i] << std::endl;

    // Free memory.
    HIP_CHECK(hipFree(devData));
    delete[] hostData;

    // Synchronize to ensure completion.
    HIP_CHECK(hipDeviceSynchronize());

    return EXIT_SUCCESS;
}

For more details, see Stream ordered memory allocator.

Memory pools#

Memory pools provide a way to manage memory with stream-ordered behavior while ensuring proper synchronization and avoiding memory access errors. Division of a single memory system into separate pools facilitates querying the access path properties for each partition. Memory pools are used for host memory, device memory, and unified memory.

Set pools#

The hipMallocAsync() function uses the current memory pool and also provides the opportunity to create and access different pools using hipMemPoolCreate() and hipMallocFromPoolAsync() functions respectively.

Unlike NVIDIA CUDA, where stream-ordered memory allocation can be implicit, ROCm HIP is explicit. This requires managing memory allocation for each stream in HIP while ensuring precise control over memory usage and synchronization.

#include <hip/hip_runtime.h>

#include <cstddef>
#include <iostream>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

// Kernel to perform some computation on allocated memory.
__global__ void myKernel(int* data, std::size_t numElements)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    if (tid < numElements)
    {
        data[tid] = tid * 2;
    }
}

int main()
{
    // Create a stream.
    hipStream_t stream;
    HIP_CHECK(hipStreamCreate(&stream));

    // Create a memory pool with default properties.
    hipMemPoolProps poolProps = {};
    poolProps.allocType = hipMemAllocationTypePinned;
    poolProps.handleTypes = hipMemHandleTypePosixFileDescriptor;
    poolProps.location.type = hipMemLocationTypeDevice;
    poolProps.location.id = 0; // Assuming device 0.

    hipMemPool_t memPool;
    HIP_CHECK(hipMemPoolCreate(&memPool, &poolProps));

    // Allocate memory from the pool asynchronously.
    constexpr std::size_t numElements = 1024;
    int* devData = nullptr;
    HIP_CHECK(hipMallocFromPoolAsync(reinterpret_cast<void**>(&devData),
                                     numElements * sizeof(*devData),
                                     memPool,
                                     stream));

    // Define grid and block sizes.
    dim3 blockSize(256);
    dim3 gridSize((numElements + blockSize.x - 1) / blockSize.x);

    // Launch the kernel to perform computation.
    myKernel<<<gridSize, blockSize, 0, stream>>>(devData, numElements);

    // Synchronize the stream.
    HIP_CHECK(hipStreamSynchronize(stream));

    // Copy data back to host.
    int* hostData = new int[numElements];
    HIP_CHECK(hipMemcpy(hostData, devData, numElements * sizeof(*devData), hipMemcpyDeviceToHost));

    // Print the array.
    for (std::size_t i = 0; i < numElements; ++i)
        std::cout << "Element " << i << ": " << hostData[i] << std::endl;

    // Free the allocated memory.
    HIP_CHECK(hipFreeAsync(devData, stream));

    // Synchronize the stream again to ensure all operations are complete.
    HIP_CHECK(hipStreamSynchronize(stream));

    // Destroy the memory pool and stream.
    HIP_CHECK(hipMemPoolDestroy(memPool));
    HIP_CHECK(hipStreamDestroy(stream));

    // Free host memory.
    delete[] hostData;

    return EXIT_SUCCESS;
}

Trim pools#

The memory allocator allows you to allocate and free memory in stream order. To control memory usage, set the release threshold attribute using hipMemPoolAttrReleaseThreshold. This threshold specifies the amount of reserved memory in bytes to hold onto.

    std::uint64_t threshold = std::numeric_limits<std::uint64_t>::max();
    HIP_CHECK(hipMemPoolSetAttribute(memPool, hipMemPoolAttrReleaseThreshold, &threshold));

When the amount of memory held in the memory pool exceeds the threshold, the allocator tries to release memory back to the operating system during the next call to stream, event, or context synchronization.

To improve performance, it is a good practice to adjust the memory pool size using hipMemPoolTrimTo(). It helps to reclaim memory from an excessive memory pool, which optimizes memory usage for your application.

#include <hip/hip_runtime.h>

#include <cstddef>
#include <cstdlib>
#include <iostream>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

int main()
{
    hipMemPool_t memPool;
    hipDevice_t device = 0; // Specify the device index.

    // Initialize the device.
    HIP_CHECK(hipSetDevice(device));

    // Get the default memory pool for the device.
    HIP_CHECK(hipDeviceGetDefaultMemPool(&memPool, device));

    // Allocate memory from the pool (e.g., 1 MB).
    std::size_t allocSize = 1 * 1024 * 1024;
    void* ptr;
    HIP_CHECK(hipMalloc(&ptr, allocSize));

    // Free the allocated memory.
    HIP_CHECK(hipFree(ptr));

    // Trim the memory pool to a specific size (e.g., 512 KB).
    std::size_t newSize = 512 * 1024;
    HIP_CHECK(hipMemPoolTrimTo(memPool, newSize));

    std::cout << "Memory pool trimmed to " << newSize << " bytes." << std::endl;
    return EXIT_SUCCESS;
}

Resource usage statistics#

Resource usage statistics help in optimization. Here is the list of pool attributes used to query memory usage:

  • hipMemPoolAttrReservedMemCurrent: Returns the total physical GPU memory currently held in the pool.

  • hipMemPoolAttrUsedMemCurrent: Returns the total size of all the memory allocated from the pool.

  • hipMemPoolAttrReservedMemHigh: Returns the total physical GPU memory held in the pool since the last reset.

  • hipMemPoolAttrUsedMemHigh: Returns the total size of all the memory allocated from the pool since the last reset.

To reset these attributes to the current value, use hipMemPoolSetAttribute().

#include <hip/hip_runtime.h>

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

// Sample helper functions for getting the usage statistics in bulk.
struct usageStatistics
{
    std::uint64_t reservedMemCurrent;
    std::uint64_t reservedMemHigh;
    std::uint64_t usedMemCurrent;
    std::uint64_t usedMemHigh;
};

void getUsageStatistics(hipMemPool_t memPool, struct usageStatistics *statistics)
{
    HIP_CHECK(hipMemPoolGetAttribute(memPool, hipMemPoolAttrReservedMemCurrent, &statistics->reservedMemCurrent));
    HIP_CHECK(hipMemPoolGetAttribute(memPool, hipMemPoolAttrReservedMemHigh, &statistics->reservedMemHigh));
    HIP_CHECK(hipMemPoolGetAttribute(memPool, hipMemPoolAttrUsedMemCurrent, &statistics->usedMemCurrent));
    HIP_CHECK(hipMemPoolGetAttribute(memPool, hipMemPoolAttrUsedMemHigh, &statistics->usedMemHigh));
}

// Resetting the watermarks resets them to the current value.
void resetStatistics(hipMemPool_t memPool)
{
    std::uint64_t value = 0;
    HIP_CHECK(hipMemPoolSetAttribute(memPool, hipMemPoolAttrReservedMemHigh, &value));
    HIP_CHECK(hipMemPoolSetAttribute(memPool, hipMemPoolAttrUsedMemHigh, &value));
}

int main()
{
    hipMemPool_t memPool;
    hipDevice_t device = 0; // Specify the device index.

    // Initialize the device.
    HIP_CHECK(hipSetDevice(device));

    // Get the default memory pool for the device.
    HIP_CHECK(hipDeviceGetDefaultMemPool(&memPool, device));

    // Allocate memory from the pool (e.g., 1 MB).
    std::size_t allocSize = 1 * 1024 * 1024;
    void* ptr;
    HIP_CHECK(hipMalloc(&ptr, allocSize));

    // Free the allocated memory.
    HIP_CHECK(hipFree(ptr));

    // Trim the memory pool to a specific size (e.g., 512 KB).
    std::size_t newSize = 512 * 1024;
    HIP_CHECK(hipMemPoolTrimTo(memPool, newSize));

    // Get and print usage statistics before resetting.
    usageStatistics statsBefore;
    getUsageStatistics(memPool, &statsBefore);
    std::cout << "Before resetting statistics:" << std::endl;
    std::cout << "Reserved Memory Current: " << statsBefore.reservedMemCurrent << " bytes" << std::endl;
    std::cout << "Reserved Memory High: " << statsBefore.reservedMemHigh << " bytes" << std::endl;
    std::cout << "Used Memory Current: " << statsBefore.usedMemCurrent << " bytes" << std::endl;
    std::cout << "Used Memory High: " << statsBefore.usedMemHigh << " bytes" << std::endl;

    // Reset the statistics.
    resetStatistics(memPool);

    // Get and print usage statistics after resetting.
    usageStatistics statsAfter;
    getUsageStatistics(memPool, &statsAfter);
    std::cout << "After resetting statistics:" << std::endl;
    std::cout << "Reserved Memory Current: " << statsAfter.reservedMemCurrent << " bytes" << std::endl;
    std::cout << "Reserved Memory High: " << statsAfter.reservedMemHigh << " bytes" << std::endl;
    std::cout << "Used Memory Current: " << statsAfter.usedMemCurrent << " bytes" << std::endl;
    std::cout << "Used Memory High: " << statsAfter.usedMemHigh << " bytes" << std::endl;

    return EXIT_SUCCESS;
}

Memory reuse policies#

The allocator might reallocate memory as long as the compliant memory accesses will not to overlap temporally. To optimize the memory usage, disable or enable the following memory pool reuse policy attribute flags:

  • hipMemPoolReuseFollowEventDependencies: Checks event dependencies before allocating additional GPU memory.

  • hipMemPoolReuseAllowOpportunistic: Checks freed allocations to determine if the stream order semantic indicated by the free operation has been met.

  • hipMemPoolReuseAllowInternalDependencies: Manages reuse based on internal dependencies in runtime. If the driver fails to allocate and map additional physical memory, it searches for memory waiting for another stream’s progress and reuses it.

Device accessibility for multi-GPU support#

Allocations are initially accessible from the device where they reside.

Interprocess memory handling#

Attention

IPC API calls are only supported on systems with an active amdgpu-dkms driver. Please refer to the AMDGPU documentation for information on how to install amdgpu-dkms.

Interprocess capable (IPC) memory pools facilitate efficient and secure sharing of GPU memory between processes.

To achieve interprocess memory sharing, you can use either a device pointer or a shareable handle. Both provide allocator (export) and consumer (import) interfaces. Use a device pointer to share a specific allocation; use a shareable handle when the importing process needs to allocate from the shared pool independently.

Device pointer#

To export a memory pool allocation for access by another process, use hipMemPoolExportPointer(). It produces a serializable hipMemPoolPtrExportData struct that can be written to any IPC channel, such as a named pipe (FIFO), and then read by the importing process.

Here is the exporter:

#include <hip/hip_runtime.h>

#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

constexpr std::size_t numElements  = 1024;
constexpr const char* fifoPath     = "/tmp/hip_ipc_devptr_fifo";
constexpr const char* doneFifoPath = "/tmp/hip_ipc_devptr_done_fifo";

__global__ void fillKernel(int* data, std::size_t n)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    if (tid < static_cast<int>(n))
        data[tid] = tid * 2;
}

void runExporter()
{
    // Allocate memory from an IPC-capable pool.
    hipMemPoolProps poolProps = {};
    poolProps.allocType       = hipMemAllocationTypePinned;
    poolProps.handleTypes     = hipMemHandleTypePosixFileDescriptor;
    poolProps.location.type   = hipMemLocationTypeDevice;
    poolProps.location.id     = 0;

    hipMemPool_t memPool;
    HIP_CHECK(hipMemPoolCreate(&memPool, &poolProps));

    hipStream_t stream;
    HIP_CHECK(hipStreamCreate(&stream));

    int* devPtr = nullptr;
    HIP_CHECK(hipMallocFromPoolAsync(reinterpret_cast<void**>(&devPtr),
                                     numElements * sizeof(*devPtr),
                                     memPool,
                                     stream));

    dim3 blockSize(256);
    dim3 gridSize((numElements + blockSize.x - 1) / blockSize.x);
    fillKernel<<<gridSize, blockSize, 0, stream>>>(devPtr, numElements);
    HIP_CHECK(hipStreamSynchronize(stream));

    // Export the memory pool pointer.
    hipMemPoolPtrExportData exportData;
    HIP_CHECK(hipMemPoolExportPointer(&exportData, devPtr));

    // Write the exported data to the named pipe.
    mkfifo(fifoPath, 0666);
    std::ofstream fifoStream(fifoPath, std::ios::out | std::ios::binary);
    fifoStream.write(reinterpret_cast<char*>(&exportData), sizeof(exportData));
    fifoStream.close();

    // Wait for the importer to signal completion before freeing.
    mkfifo(doneFifoPath, 0666);
    char ack;
    std::ifstream doneStream(doneFifoPath, std::ios::in | std::ios::binary);
    doneStream.read(&ack, 1);
    doneStream.close();

    HIP_CHECK(hipFreeAsync(devPtr, stream));
    HIP_CHECK(hipStreamSynchronize(stream));
    HIP_CHECK(hipMemPoolDestroy(memPool));
    HIP_CHECK(hipStreamDestroy(stream));
    unlink(fifoPath);
    unlink(doneFifoPath);
    std::cout << "Exporter: done." << std::endl;
}

To import a memory pool pointer from another process, use hipMemPoolImportPointer().

Here is the importer:

void runImporter()
{
    // Read the exported data from the named pipe.
    hipMemPoolPtrExportData importData;
    std::ifstream fifoStream(fifoPath, std::ios::in | std::ios::binary);
    fifoStream.read(reinterpret_cast<char*>(&importData), sizeof(importData));
    fifoStream.close();

    // Create a memory pool with matching IPC-capable properties.
    hipMemPoolProps poolProps = {};
    poolProps.allocType       = hipMemAllocationTypePinned;
    poolProps.handleTypes     = hipMemHandleTypePosixFileDescriptor;
    poolProps.location.type   = hipMemLocationTypeDevice;
    poolProps.location.id     = 0;

    hipMemPool_t memPool;
    HIP_CHECK(hipMemPoolCreate(&memPool, &poolProps));

    // Import the device pointer from the exporter's pool.
    int* importedDevPtr = nullptr;
    HIP_CHECK(hipMemPoolImportPointer(reinterpret_cast<void**>(&importedDevPtr),
                                      memPool,
                                      &importData));

    // Verify the values written by the exporter's kernel.
    int* hostData = new int[numElements];
    HIP_CHECK(hipMemcpy(hostData,
                        importedDevPtr,
                        numElements * sizeof(*hostData),
                        hipMemcpyDeviceToHost));

    bool passed = true;
    for (std::size_t i = 0; i < numElements; ++i)
    {
        if (hostData[i] != static_cast<int>(i * 2))
        {
            std::cerr << "Mismatch at [" << i << "]: expected " << i * 2
                      << ", got " << hostData[i] << std::endl;
            passed = false;
            break;
        }
    }
    delete[] hostData;

    // Signal the exporter that this process has finished.
    char ack = 1;
    std::ofstream doneStream(doneFifoPath, std::ios::out | std::ios::binary);
    doneStream.write(&ack, 1);
    doneStream.close();

    HIP_CHECK(hipFree(importedDevPtr));
    HIP_CHECK(hipMemPoolDestroy(memPool));

    std::cout << "Importer: " << (passed ? "PASS" : "FAIL") << std::endl;
    std::exit(passed ? EXIT_SUCCESS : EXIT_FAILURE);
}

Shareable handle#

To export a memory pool as a shareable handle, use hipMemPoolExportToShareableHandle(). The handle is a POSIX file descriptor, which is process-local and cannot be transferred by writing its integer value to a pipe. Instead, use SCM_RIGHTS over a Unix domain socket to duplicate the file description into the receiving process.

Here is the exporter:

#include <hip/hip_runtime.h>

#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>

#define HIP_CHECK(expression)                        \
{                                                    \
    const hipError_t status = expression;            \
    if (status != hipSuccess)                        \
    {                                                \
        std::cerr << "HIP error " << status          \
                << ": " << hipGetErrorString(status) \
                << " at " << __FILE__ << ":"         \
                << __LINE__ << std::endl;            \
        std::exit(EXIT_FAILURE);                     \
    }                                                \
}

constexpr std::size_t numElements  = 1024;
constexpr const char* sockPath     = "/tmp/hip_ipc_handle.sock";
constexpr const char* doneFifoPath = "/tmp/hip_ipc_handle_done_fifo";

__global__ void fillKernel(int* data, std::size_t n)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    if (tid < static_cast<int>(n))
        data[tid] = tid * 2;
}

// Sends an open file descriptor to another process via SCM_RIGHTS.
// A POSIX file descriptor is process-local: its integer value has no meaning
// in another process's fd table. SCM_RIGHTS is the POSIX mechanism that
// duplicates the underlying kernel file description into the receiving process.
static void sendFd(int fdToSend)
{
    unlink(sockPath);
    int listenSock = socket(AF_UNIX, SOCK_STREAM, 0);

    sockaddr_un addr = {};
    addr.sun_family  = AF_UNIX;
    strncpy(addr.sun_path, sockPath, sizeof(addr.sun_path) - 1);
    bind(listenSock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
    listen(listenSock, 1);

    std::cout << "Exporter: waiting for importer to connect..." << std::endl;
    int conn = accept(listenSock, nullptr, nullptr);

    char buf[1]              = {0};
    iovec iov                = {buf, sizeof(buf)};
    char cmsgBuf[CMSG_SPACE(sizeof(int))];
    msghdr msg               = {};
    msg.msg_iov              = &iov;
    msg.msg_iovlen           = 1;
    msg.msg_control          = cmsgBuf;
    msg.msg_controllen       = sizeof(cmsgBuf);

    cmsghdr* cmsg            = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level         = SOL_SOCKET;
    cmsg->cmsg_type          = SCM_RIGHTS;
    cmsg->cmsg_len           = CMSG_LEN(sizeof(int));
    memcpy(CMSG_DATA(cmsg), &fdToSend, sizeof(int));

    sendmsg(conn, &msg, 0);
    std::cout << "Exporter: handle sent via SCM_RIGHTS." << std::endl;

    // Wait for importer's ack before closing the connection.
    char ack;
    recv(conn, &ack, 1, 0);
    close(conn);
    close(listenSock);
    unlink(sockPath);
}

void runExporter()
{
    // Create an IPC-capable memory pool and export its handle before
    // any allocation so the importer can independently allocate from it.
    hipMemPoolProps poolProps = {};
    poolProps.allocType       = hipMemAllocationTypePinned;
    poolProps.handleTypes     = hipMemHandleTypePosixFileDescriptor;
    poolProps.location.type   = hipMemLocationTypeDevice;
    poolProps.location.id     = 0;

    hipMemPool_t memPool;
    HIP_CHECK(hipMemPoolCreate(&memPool, &poolProps));

    int descriptor = -1;
    HIP_CHECK(hipMemPoolExportToShareableHandle(reinterpret_cast<void*>(&descriptor),
                                                memPool,
                                                hipMemHandleTypePosixFileDescriptor,
                                                0));

    // Transfer the file descriptor to the importer via SCM_RIGHTS.
    sendFd(descriptor);

    // Keep the pool alive until the importer signals completion.
    mkfifo(doneFifoPath, 0666);
    char ack;
    std::ifstream doneStream(doneFifoPath, std::ios::in | std::ios::binary);
    doneStream.read(&ack, 1);
    doneStream.close();

    HIP_CHECK(hipMemPoolDestroy(memPool));
    ::close(descriptor);
    unlink(doneFifoPath);
    std::cout << "Exporter: done." << std::endl;
}

To import a memory pool from a shareable handle received via SCM_RIGHTS, use hipMemPoolImportFromShareableHandle(). The importing process can then allocate GPU memory from the imported pool independently.

Here is the importer:

void runImporter()
{
    // Receive the pool's file descriptor via SCM_RIGHTS and import the pool.
    std::cout << "Importer: connecting to exporter..." << std::endl;
    int descriptor = recvFd();

    hipMemPool_t memPool;
    void* handleValue = reinterpret_cast<void*>(static_cast<intptr_t>(descriptor));
    HIP_CHECK(hipMemPoolImportFromShareableHandle(&memPool,
                                                  handleValue,
                                                  hipMemHandleTypePosixFileDescriptor,
                                                  0));

    // Allocate from the imported pool and run a kernel to verify GPU access.
    hipStream_t stream;
    HIP_CHECK(hipStreamCreate(&stream));

    int* devPtr = nullptr;
    HIP_CHECK(hipMallocFromPoolAsync(reinterpret_cast<void**>(&devPtr),
                                     numElements * sizeof(*devPtr),
                                     memPool,
                                     stream));

    dim3 blockSize(256);
    dim3 gridSize((numElements + blockSize.x - 1) / blockSize.x);
    fillKernel<<<gridSize, blockSize, 0, stream>>>(devPtr, numElements);
    HIP_CHECK(hipStreamSynchronize(stream));

    int* hostData = new int[numElements];
    HIP_CHECK(hipMemcpy(hostData,
                        devPtr,
                        numElements * sizeof(*hostData),
                        hipMemcpyDeviceToHost));

    bool passed = true;
    for(std::size_t i = 0; i < numElements; ++i)
    {
        if(hostData[i] != static_cast<int>(i * 2))
        {
            std::cerr << "Mismatch at [" << i << "]: expected " << i * 2
                      << ", got " << hostData[i] << std::endl;
            passed = false;
            break;
        }
    }
    delete[] hostData;

    // Signal the exporter that this process has finished.
    char ack = 1;
    std::ofstream doneStream(doneFifoPath, std::ios::out | std::ios::binary);
    doneStream.write(&ack, 1);
    doneStream.close();

    HIP_CHECK(hipFreeAsync(devPtr, stream));
    HIP_CHECK(hipStreamSynchronize(stream));
    HIP_CHECK(hipMemPoolDestroy(memPool));
    HIP_CHECK(hipStreamDestroy(stream));
    ::close(descriptor);

    std::cout << "Importer: " << (passed ? "PASS" : "FAIL") << std::endl;
    std::exit(passed ? EXIT_SUCCESS : EXIT_FAILURE);
}