Random Numbers

Parallel codes often need random numbers for Monte Carlo methods, randomized initialization, sampling, or synthetic test data. alpaka provides random engines and distributions that can be used directly inside kernels.

Using Random Numbers in a Kernel

To avoid correlations between random numbers generated by different threads each thread should get its own deterministic engine state generated by a unique seed. The easiest way to do that is to derive the seed from the loop index. The unique engine state can then be used to generate as many random samples as needed from the chosen distribution.

alpaka supports the following distributions:

  • UniformReal<float or double> for samples in a bounded floating-point interval where all values can occur with equal probability.

  • NormalReal<float or double> for Gaussian-distributed samples with a chosen mean and standard deviation.

Uniform Random Numbers

struct UniformRandomKernel
{
    ALPAKA_FN_ACC void operator()(onAcc::concepts::Acc auto const& acc, concepts::IMdSpan auto out, uint32_t seed)
        const
    {
        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
        // globally unique seed created from a base seed and the thread index within the grid
        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);
        auto distribution = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::co};

        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{out.getExtents()}))
        {
            out[idx] = distribution(engine);
        }
    }
};

This example uses the engine rand::engine::Philox4x32x10 and the distribution rand::distribution::UniformReal<float> with the half-open interval [0, 1) interval rand::interval::co. The configuration of intervals is explained in the Intervals section. The distribution is used to create a random index per element in the output data container.

Launching the Kernel:

onHost::concepts::FrameSpec auto frameSpec = onHost::getFrameSpec(device, exec, randomBuffer.getExtents());
queue.enqueue(frameSpec, KernelBundle{UniformRandomKernel{}, randomBuffer, 1234u});

Uniform distributions are mostly used for probabilities, random offsets, randomized initialization, and rejection sampling. Normal distributions are used for noise models, perturbations around a mean value, and many Monte Carlo methods.

Normal Distribution

NormalReal generates Gaussian noise with a chosen mean and standard deviation. Unlike the uniform distribution, it keeps internal state, therefore you should not share the distribution objects between threads.

struct NormalNoiseKernel
{
    ALPAKA_FN_ACC void operator()(
        onAcc::concepts::Acc auto const& acc,
        concepts::IMdSpan auto out,
        uint32_t seed,
        float mean,
        float stdDev) const
    {
        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
        // globally unique seed created from a base seed and the thread index within the grid
        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);

        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{out.getExtents()}))
        {
            rand::distribution::NormalReal<float> normal(mean, stdDev);
            out[idx] = normal(engine);
        }
    }
};

Launching the kernel is the same as before; only the kernel logic changes.

onHost::concepts::FrameSpec auto frameSpec = onHost::getFrameSpec(device, exec, randomBuffer.getExtents());
queue.enqueue(frameSpec, KernelBundle{NormalNoiseKernel{}, randomBuffer, 2025u, 5.0f, 2.0f});

Intervals

UniformReal supports four interval tags:

  • rand::interval::co gives [a, b)

  • rand::interval::oc gives (a, b]

  • rand::interval::cc gives [a, b]

  • rand::interval::oo gives (a, b)

The following kernel shows all four forms side by side.

struct IntervalExamplesKernel
{
    ALPAKA_FN_ACC void operator()(
        onAcc::concepts::Acc auto const& acc,
        concepts::IMdSpan auto coValues,
        concepts::IMdSpan auto ocValues,
        concepts::IMdSpan auto ccValues,
        concepts::IMdSpan auto ooValues,
        uint32_t seed) const
    {
        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
        // globally unique seed created from a base seed and the thread index within the grid
        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);

        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{coValues.getExtents()}))
        {
            // 0 <= val <  1
            coValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::co}(engine);
            // 0 <  val <= 1
            ocValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::oc}(engine);
            // 0 <= val <= 1
            ccValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::cc}(engine);
            // 0 <  val <  1
            ooValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::oo}(engine);
        }
    }
};

Monte Carlo Pi

A classic example is Monte Carlo estimation of pi. Draw points in the square [0, 1) x [0, 1), count how many land inside the unit quarter circle, and estimate pi from that ratio. The half-open interval matches array-style data access and avoids awkward endpoint corner cases.

In the example each worker draws one point, writes 1 if the point falls inside the quarter circle, and then a reduction adds up all hits.

struct MonteCarloPiKernel
{
    ALPAKA_FN_ACC void operator()(onAcc::concepts::Acc auto const& acc, concepts::IMdSpan auto hits, uint32_t seed)
        const
    {
        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
        // globally unique seed created from a base seed and the thread index within the grid
        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);
        auto uniform = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::co};

        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{hits.getExtents()}))
        {
            auto x = uniform(engine);
            auto y = uniform(engine);
            hits[idx] = (x * x + y * y <= 1.0f) ? 1u : 0u;
        }
    }
};

The reduction happens on the same queue right after the kernel.

queue.enqueue(frameSpec, KernelBundle{MonteCarloPiKernel{}, hitBuffer, 2026u});
onHost::reduce(queue, exec, 0u, hitCountBuffer, std::plus{}, hitBuffer);

After copying back the single reduction result, the estimate itself is just the usual Monte Carlo formula.

auto estimatedPi = 4.0f * static_cast<float>(hostHitCount[0]) / static_cast<float>(numSamples);

Complete Source File

170_random.cpp
  1/* Copyright 2026 René Widera
  2 * SPDX-License-Identifier: ISC
  3 */
  4
  5#include "docsTest.hpp"
  6
  7#include <alpaka/alpaka.hpp>
  8
  9#include <catch2/catch_approx.hpp>
 10#include <catch2/catch_template_test_macros.hpp>
 11#include <catch2/catch_test_macros.hpp>
 12
 13#include <array>
 14#include <cmath>
 15#include <numeric>
 16
 17using namespace alpaka;
 18
 19struct UniformRandomKernel
 20{
 21    ALPAKA_FN_ACC void operator()(onAcc::concepts::Acc auto const& acc, concepts::IMdSpan auto out, uint32_t seed)
 22        const
 23    {
 24        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
 25        // globally unique seed created from a base seed and the thread index within the grid
 26        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);
 27        auto distribution = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::co};
 28
 29        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{out.getExtents()}))
 30        {
 31            out[idx] = distribution(engine);
 32        }
 33    }
 34};
 35
 36
 37struct IntervalExamplesKernel
 38{
 39    ALPAKA_FN_ACC void operator()(
 40        onAcc::concepts::Acc auto const& acc,
 41        concepts::IMdSpan auto coValues,
 42        concepts::IMdSpan auto ocValues,
 43        concepts::IMdSpan auto ccValues,
 44        concepts::IMdSpan auto ooValues,
 45        uint32_t seed) const
 46    {
 47        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
 48        // globally unique seed created from a base seed and the thread index within the grid
 49        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);
 50
 51        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{coValues.getExtents()}))
 52        {
 53            // 0 <= val <  1
 54            coValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::co}(engine);
 55            // 0 <  val <= 1
 56            ocValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::oc}(engine);
 57            // 0 <= val <= 1
 58            ccValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::cc}(engine);
 59            // 0 <  val <  1
 60            ooValues[idx] = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::oo}(engine);
 61        }
 62    }
 63};
 64
 65
 66struct NormalNoiseKernel
 67{
 68    ALPAKA_FN_ACC void operator()(
 69        onAcc::concepts::Acc auto const& acc,
 70        concepts::IMdSpan auto out,
 71        uint32_t seed,
 72        float mean,
 73        float stdDev) const
 74    {
 75        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
 76        // globally unique seed created from a base seed and the thread index within the grid
 77        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);
 78
 79        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{out.getExtents()}))
 80        {
 81            rand::distribution::NormalReal<float> normal(mean, stdDev);
 82            out[idx] = normal(engine);
 83        }
 84    }
 85};
 86
 87
 88TEMPLATE_LIST_TEST_CASE("tutorial random numbers", "[docs]", docs::test::TestBackends)
 89{
 90    auto cfg = TestType::makeDict();
 91    auto exec = alpaka::getExecutor(cfg);
 92
 93    auto selector = onHost::makeDeviceSelector(cfg);
 94    if(!selector.isAvailable())
 95        return;
 96    onHost::concepts::Device auto device = selector.makeDevice(0);
 97    onHost::Queue queue = device.makeQueue(queueKind::blocking);
 98
 99    std::array<float, 8u> hostValues{};
100    auto randomBuffer = onHost::allocLike(device, hostValues);
101
102    onHost::concepts::FrameSpec auto frameSpec = onHost::getFrameSpec(device, exec, randomBuffer.getExtents());
103    queue.enqueue(frameSpec, KernelBundle{UniformRandomKernel{}, randomBuffer, 1234u});
104
105    onHost::memcpy(queue, hostValues, randomBuffer);
106    onHost::wait(queue);
107
108    float sum = 0.0f;
109    for(auto value : hostValues)
110    {
111        CHECK(value >= 0.0f);
112        CHECK(value < 1.0f);
113        sum += value;
114    }
115
116    CHECK(sum > 0.0f);
117    CHECK(sum < 8.0f);
118}
119
120TEMPLATE_LIST_TEST_CASE("tutorial random intervals", "[docs]", docs::test::TestBackends)
121{
122    auto cfg = TestType::makeDict();
123    auto exec = alpaka::getExecutor(cfg);
124
125    auto selector = onHost::makeDeviceSelector(cfg);
126    if(!selector.isAvailable())
127        return;
128    onHost::concepts::Device auto device = selector.makeDevice(0);
129    onHost::Queue queue = device.makeQueue(queueKind::blocking);
130
131    std::array<float, 16u> hostCo{};
132    std::array<float, 16u> hostOc{};
133    std::array<float, 16u> hostCc{};
134    std::array<float, 16u> hostOo{};
135
136    auto coBuffer = onHost::allocLike(device, hostCo);
137    auto ocBuffer = onHost::allocLike(device, hostOc);
138    auto ccBuffer = onHost::allocLike(device, hostCc);
139    auto ooBuffer = onHost::allocLike(device, hostOo);
140
141    onHost::concepts::FrameSpec auto frameSpec = onHost::getFrameSpec(device, exec, coBuffer.getExtents());
142    queue.enqueue(frameSpec, KernelBundle{IntervalExamplesKernel{}, coBuffer, ocBuffer, ccBuffer, ooBuffer, 999u});
143
144    onHost::memcpy(queue, hostCo, coBuffer);
145    onHost::memcpy(queue, hostOc, ocBuffer);
146    onHost::memcpy(queue, hostCc, ccBuffer);
147    onHost::memcpy(queue, hostOo, ooBuffer);
148    onHost::wait(queue);
149
150    for(size_t i = 0; i < hostCo.size(); ++i)
151    {
152        CHECK(hostCo[i] >= 0.0f);
153        CHECK(hostCo[i] < 1.0f);
154        CHECK(hostOc[i] > 0.0f);
155        CHECK(hostOc[i] <= 1.0f);
156        CHECK(hostCc[i] >= 0.0f);
157        CHECK(hostCc[i] <= 1.0f);
158        CHECK(hostOo[i] > 0.0f);
159        CHECK(hostOo[i] < 1.0f);
160    }
161}
162
163TEMPLATE_LIST_TEST_CASE("tutorial random normal distribution", "[docs]", docs::test::TestBackends)
164{
165    auto cfg = TestType::makeDict();
166    auto exec = alpaka::getExecutor(cfg);
167
168    auto selector = onHost::makeDeviceSelector(cfg);
169    if(!selector.isAvailable())
170        return;
171    onHost::concepts::Device auto device = selector.makeDevice(0);
172    onHost::Queue queue = device.makeQueue(queueKind::blocking);
173
174    std::array<float, 64u> hostValues{};
175    auto randomBuffer = onHost::allocLike(device, hostValues);
176
177    onHost::concepts::FrameSpec auto frameSpec = onHost::getFrameSpec(device, exec, randomBuffer.getExtents());
178    queue.enqueue(frameSpec, KernelBundle{NormalNoiseKernel{}, randomBuffer, 2025u, 5.0f, 2.0f});
179
180    onHost::memcpy(queue, hostValues, randomBuffer);
181    onHost::wait(queue);
182
183    float mean = std::accumulate(hostValues.begin(), hostValues.end(), 0.0f) / static_cast<float>(hostValues.size());
184    CHECK(mean > 4.0f);
185    CHECK(mean < 6.0f);
186
187    bool foundBelowMean = false;
188    bool foundAboveMean = false;
189    for(auto value : hostValues)
190    {
191        foundBelowMean = foundBelowMean || value < 5.0f;
192        foundAboveMean = foundAboveMean || value > 5.0f;
193    }
194    CHECK(foundBelowMean);
195    CHECK(foundAboveMean);
196}
197
198struct MonteCarloPiKernel
199{
200    ALPAKA_FN_ACC void operator()(onAcc::concepts::Acc auto const& acc, concepts::IMdSpan auto hits, uint32_t seed)
201        const
202    {
203        auto const [threadIdxInGrid] = acc.getIdxWithin(alpaka::onAcc::origin::grid, alpaka::onAcc::unit::threads);
204        // globally unique seed created from a base seed and the thread index within the grid
205        rand::engine::Philox4x32x10 engine(seed + threadIdxInGrid);
206        auto uniform = rand::distribution::UniformReal{0.0f, 1.0f, rand::interval::co};
207
208        for(auto [idx] : onAcc::makeIdxMap(acc, onAcc::worker::threadsInGrid, IdxRange{hits.getExtents()}))
209        {
210            auto x = uniform(engine);
211            auto y = uniform(engine);
212            hits[idx] = (x * x + y * y <= 1.0f) ? 1u : 0u;
213        }
214    }
215};
216
217
218TEMPLATE_LIST_TEST_CASE("tutorial monte carlo pi", "[docs]", docs::test::TestBackends)
219{
220    auto cfg = TestType::makeDict();
221    auto exec = alpaka::getExecutor(cfg);
222
223    auto selector = onHost::makeDeviceSelector(cfg);
224    if(!selector.isAvailable())
225        return;
226    onHost::concepts::Device auto device = selector.makeDevice(0);
227    onHost::Queue queue = device.makeQueue(queueKind::blocking);
228
229    constexpr uint32_t numSamples = 16384u;
230    auto hitBuffer = onHost::alloc<uint32_t>(device, Vec{numSamples});
231    auto hitCountBuffer = onHost::alloc<uint32_t>(device, Vec{1u});
232    auto hostHitCount = onHost::allocHostLike(hitCountBuffer);
233
234    onHost::concepts::FrameSpec auto frameSpec = onHost::getFrameSpec(device, exec, hitBuffer.getExtents());
235
236    queue.enqueue(frameSpec, KernelBundle{MonteCarloPiKernel{}, hitBuffer, 2026u});
237    onHost::reduce(queue, exec, 0u, hitCountBuffer, std::plus{}, hitBuffer);
238
239    onHost::memcpy(queue, hostHitCount, hitCountBuffer);
240    onHost::wait(queue);
241
242    auto estimatedPi = 4.0f * static_cast<float>(hostHitCount[0]) / static_cast<float>(numSamples);
243
244    CHECK(estimatedPi == Catch::Approx(3.14159f).margin(0.15f));
245}