### Build Examples Option Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Controls whether to build the examples during the installation of Alpaka. ```markdown ``alpaka_EXAMPLES`` .. code-block:: markdown Build the examples. ``` -------------------------------- ### Create Directory for FetchContent Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/CMakeLists.txt Creates a dedicated build directory for the fetchContent example. This isolates the example's build environment. ```cmake file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/docs/snippets/fetchContent/) ``` -------------------------------- ### Complete Source File Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/queue.rst The complete C++ source file for the queue tutorial, including all examples and necessary includes. ```cpp #include int main() { // BEGIN-TUTORIAL-blockingQueue alpaka::Queue blockingQueue; // END-TUTORIAL-blockingQueue // BEGIN-TUTORIAL-nonBlockingQueue alpaka::Queue nonBlockingQueue; // END-TUTORIAL-nonBlockingQueue return 0; } ``` -------------------------------- ### Build and Run Scan Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/scan/README.md Instructions for building the scan example from source and running the executable. This process includes configuration, compilation, and execution. ```bash $ mkdir build && cd build $ ccmake .. # configure your backends, configure and generate (make sure to enable examples) $ cmake --build . --target=scan -j $ ./example/scan/scan ``` -------------------------------- ### Enable Examples Source: https://github.com/alpaka-group/alpaka3/blob/dev/CMakeLists.txt Enables the compilation and execution of project examples by enabling testing and adding the 'example' subdirectory if the 'alpaka_EXAMPLES' option is set. This is useful for demonstrating project usage. ```cmake if(alpaka_EXAMPLES) enable_testing() add_subdirectory("${_alpaka_ROOT_DIR}/example") endif() ``` -------------------------------- ### Set up Python Environment and Install Dependencies for Sphinx Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/contribution/sphinx.rst This snippet demonstrates how to create a virtual Python environment, activate it, install Sphinx dependencies from requirements.txt, and install Doxygen for API documentation generation. ```bash python3 -m venv alpaka-doc-env # activate environment source alpaka-doc-env/bin/activate cd docs # install dependencies pip3 install -r requirements.txt # install doxygen curl https://www.doxygen.nl/files/doxygen-1.16.0.linux.bin.tar.gz -o /tmp/doxygen.tar.gz tar -xf /tmp/doxygen.tar.gz -C /tmp/ cp /tmp/doxygen-1.16.0/bin/doxygen $VIRTUAL_ENV/bin ``` -------------------------------- ### Example main.cpp for FetchContent Integration Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Example C++ source file (main.cpp) that utilizes Alpaka, designed to be used with the FetchContent CMake integration method. ```cpp #include #include int main() { // Get the device specification from CMake cache // For example: cmake .. -DmyApp_DEVICE_SPEC="cuda:nvidiaGpu" // If not provided, it defaults to host:cpu std::string device_spec; try { device_spec = alpaka::getDeviceSpecification(/* default: "host:cpu" */); } catch (const std::exception& e) { std::cerr << "Error getting device specification: " << e.what() << std::endl; return 1; } std::cout << "Using device specification: " << device_spec << std::endl; // Example of using Alpaka (replace with your actual kernel logic) // alpaka::TaskKernel kernel; // alpaka::enqueue(kernel); return 0; } ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/alpaka-group/alpaka3/blob/dev/CONTRIBUTING.md Install the pre-commit executable and set up the git hooks for the project. This ensures code style consistency before commits. ```bash # if not yet done, install the pre-commit executable following https://pre-commit.com cd /path/to/alpaka-working-clone pre-commit install ``` -------------------------------- ### Build and Run Alpaka Examples with CMake Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Compile and run Alpaka examples by configuring CMake with the -Dalpaka_EXAMPLES=ON flag. Assumes a build directory adjacent to the Alpaka source directory. ```bash # In a directory beside the alpaka source directory (for example in "build-alpaka3") # ├── alpaka3 # └── build-alpaka3 # .. cmake ../alpaka3 -Dalpaka_EXAMPLES=ON cmake --build . --parallel -t vectorAdd ./example/vectorAdd/vectorAdd # execution ``` -------------------------------- ### Build and Run Application with FetchContent Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Steps to build and run an application integrated with Alpaka using FetchContent, starting from an empty directory. ```bash mkdir build && cd build cmake .. cmake --build . --parallel ./fetchContentExample ``` -------------------------------- ### Install CMake Configuration Files Source: https://github.com/alpaka-group/alpaka3/blob/dev/CMakeLists.txt Installs various CMake helper files, including configuration scripts and the generated package version file, to the appropriate CMake installation directory. This enables other projects to find and use the installed Alpaka package. ```cmake install( FILES "${_alpaka_ROOT_DIR}/cmake/finalize.cmake" "${_alpaka_ROOT_DIR}/cmake/alpakaCommon.cmake" "${_alpaka_ROOT_DIR}/cmake/alpakaCuda.cmake" "${_alpaka_ROOT_DIR}/cmake/alpakaHip.cmake" "${_alpaka_ROOT_DIR}/cmake/alpakaOneApi.cmake" "${_alpaka_ROOT_DIR}/cmake/alpakaHwloc.cmake" "${_alpaka_ROOT_DIR}/cmake/buildDependencies.cmake" "${_alpaka_ROOT_DIR}/cmake/common.cmake" "${_alpaka_ROOT_DIR}/cmake/alpakaCompilePedantic.cmake" "${PROJECT_BINARY_DIR}/alpakaConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/alpaka ) ``` -------------------------------- ### Add Test for FetchContent Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/CMakeLists.txt Adds a test named 'fetchContent' that runs the compiled fetchContent example. This verifies the example's functionality in a clean environment. ```cmake add_test(NAME fetchContent COMMAND ${CMAKE_BINARY_DIR}/docs/snippets/fetchContent/fetchContentExample) ``` -------------------------------- ### CMake Build and Run Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/example.rst Instructions for configuring, building, and running an Alpaka project using CMake. This example shows how to enable CUDA support during the CMake configuration phase. ```bash cd mkdir build && cd build cmake .. -Dalpaka_DEP_CUDA=ON cmake --build . ./vectorAdd ``` -------------------------------- ### CVec Example 0 Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/vector.rst Demonstrates the basic usage of CVec, highlighting its compile-time component storage. ```cpp #include // BEGIN-TUTORIAL-CVec0 using Vec = alpaka::Vec; using CVec = alpaka::CVec; int main() { CVec c_vec(1, 2, 3); static_assert(c_vec.size() == 3, "CVec size must be 3"); static_assert(c_vec[0] == 1, "CVec component 0 must be 1"); static_assert(c_vec[1] == 2, "CVec component 1 must be 2"); static_assert(c_vec[2] == 3, "CVec component 2 must be 3"); // END-TUTORIAL-CVec0 } ``` -------------------------------- ### Install Test Directory Source: https://github.com/alpaka-group/alpaka3/blob/dev/CMakeLists.txt Installs the entire directory containing tests to the installation destination. This is useful for deploying all test cases with the installed package. ```cmake install(DIRECTORY ${_alpaka_TESTS_DIR} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR} USE_SOURCE_PERMISSIONS) ``` -------------------------------- ### Define Executable and Link Alpaka Library Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/dataStorage/CMakeLists.txt Defines an executable for a data storage example and links it with the Alpaka library. This is a standard setup for Alpaka applications. ```cmake add_executable(docs_terms_extents terms_extents.cpp) target_link_libraries(docs_terms_extents PRIVATE alpaka::alpaka) alpaka_finalize(docs_terms_extents) ``` ```cmake add_executable(docs_datastorage_interface datastorage_interface.cpp) target_link_libraries(docs_datastorage_interface PRIVATE alpaka::alpaka) alpaka_finalize(docs_datastorage_interface) ``` ```cmake add_executable(docs_datastorage_writeable_datasource datastorage_writeable_datasource.cpp) target_link_libraries(docs_datastorage_writeable_datasource PRIVATE alpaka::alpaka) alpaka_finalize(docs_datastorage_writeable_datasource) ``` -------------------------------- ### CMakeLists.txt Example using FetchContent Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst A complete CMakeLists.txt file demonstrating how to use CMake's FetchContent module to automatically download and integrate Alpaka into your project. ```cmake include(FetchContent) FetchContent_Declare( alpaka GIT_REPOSITORY https://github.com/alpaka-group/alpaka3.git GIT_TAG main # or a specific tag/commit ) FetchContent_MakeAvailable(alpaka) # Add your executable and link against alpaka add_executable(fetchContentExample main.cpp) target_link_libraries(fetchContentExample PRIVATE alpaka::alpaka) alpaka_finalize(fetchContentExample) ``` -------------------------------- ### Kernel Launch Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/kernel.rst This C++ snippet demonstrates how to create a FrameSpec and launch a kernel using onAcc::makeIdxMap. It shows how to set up the thread specification based on device capabilities. ```cpp #include #include int main() { using Host_Platform = alpaka::Platform(hostAcc); // Create a FrameSpec for the device const auto devFrameSpec = alpaka::onHost::getFrameSpec(devAcc); // Example: FrameSpec with dimensions {10, 32} // On GPU, thread_spec could be {10, 32} (blocks, threads) // On CPU, thread_spec could be {10, 1} (blocks, threads) // Launch a kernel with the host FrameSpec auto hostIdxMap = alpaka::onAcc::makeIdxMap(hostFrameSpec); // Launch a kernel with the device FrameSpec auto devIdxMap = alpaka::onAcc::makeIdxMap(devFrameSpec); std::cout << "Host FrameSpec: " << hostFrameSpec << std::endl; std::cout << "Device FrameSpec: " << devFrameSpec << std::endl; return EXIT_SUCCESS; } ``` -------------------------------- ### CVec Example 1 Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/vector.rst Further illustrates CVec's compile-time capabilities with static_assert. ```cpp // BEGIN-TUTORIAL-CVec1 Vec vec(4, 5, 6); static_assert(vec.size() == 3, "Vec size must be 3"); static_assert(vec[0] == 4, "Vec component 0 must be 4"); static_assert(vec[1] == 5, "Vec component 1 must be 5"); static_assert(vec[2] == 6, "Vec component 2 must be 6"); // END-TUTORIAL-CVec1 ``` -------------------------------- ### Build Sphinx Documentation Locally Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/contribution/sphinx.rst This snippet shows how to activate the previously set up Python environment and build the HTML documentation using Sphinx's make command. It also includes an example of opening the generated index file in a browser. ```bash # activate environment source alpaka-doc-env/bin/activate cd docs # build documentation make html # chromium and other browser also works firefox ./build/html/index.html ``` -------------------------------- ### Clone and Install Alpaka Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Clones the Alpaka repository from GitHub and installs it using CMake. Assumes a specific folder structure for the build process. ```bash # Clone alpaka from github.com git clone --branch dev https://github.com/alpaka-group/alpaka3.git mkdir build && cd build # assumed folder structure # # # if not set, the default is CMAKE_INSTALL_PREFIX=/usr/local cmake -DCMAKE_INSTALL_PREFIX=/install/alpaka3 .. cmake --install . ``` -------------------------------- ### Install Generated Package Configuration File Source: https://github.com/alpaka-group/alpaka3/blob/dev/CMakeLists.txt Installs the generated 'alpakaConfig.cmake' file to the installation directory. This makes the package discoverable by CMake's find_package command. ```cmake install(FILES ${CMAKE_CURRENT_BINARY_DIR}/alpakaConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/alpaka) ``` -------------------------------- ### Load Spack Dependencies for Examples Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Load necessary Spack packages, including a specific GCC compiler and CMake version, before compiling Alpaka examples. ```bash spack load gcc@14.1.0 spack load cmake@3.29.1 ``` -------------------------------- ### Install Feature Test Files Source: https://github.com/alpaka-group/alpaka3/blob/dev/CMakeLists.txt Installs specific C++ files used for testing optional features like std::atomic_ref and std::simd. These are placed in a dedicated tests subdirectory within the installation's library directory. ```cmake install(FILES "${_alpaka_FEATURE_TESTS_DIR}/StdAtomicRef.cpp" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/alpaka/tests) ``` ```cmake install(FILES "${_alpaka_FEATURE_TESTS_DIR}/StdSimd.cpp" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/alpaka/tests) ``` -------------------------------- ### Build Testing Tree Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Enable the `alpaka_TESTS` option to build the testing tree. This can be activated during installation or when using an already installed alpaka version. ```markdown Build the testing tree with the current environment. This option is available during the installation of alpaka. Additionally this option can be activated at the moment where an already installed alpaka version is used within your project, since the environment can be different to the one used during the installation of alpaka. ``` -------------------------------- ### Use Alpaka from Source with CMake Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Demonstrates how to use Alpaka directly from its source code directory within a CMake project without performing a formal installation. ```bash ``` -------------------------------- ### Install Alpaka Include Directory Source: https://github.com/alpaka-group/alpaka3/blob/dev/CMakeLists.txt Installs the Alpaka include directory to the system's standard include path. This makes Alpaka headers available for external projects. ```cmake install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) ``` -------------------------------- ### CMakeLists.txt Configuration for Vector Addition Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/vectorAdd/CMakeLists.txt This snippet shows the main CMakeLists.txt file for the vector addition example. It sets up the project, finds the Alpaka library, and builds the executable. ```cmake # # Copyright 2023 Benjamin Worpitz, Jan Stephan # SPDX-License-Identifier: ISC # ################################################################################ # Required CMake version. cmake_minimum_required(VERSION 3.25) set_property(GLOBAL PROPERTY USE_FOLDERS ON) ################################################################################ # Project. set(_TARGET_NAME vectorAdd) project(${_TARGET_NAME} LANGUAGES CXX) #------------------------------------------------------------------------------- # Find alpaka. if(NOT TARGET alpaka::alpaka) option(alpaka_USE_SOURCE_TREE "Use alpaka's source tree instead of an alpaka installation" OFF) if(alpaka_USE_SOURCE_TREE) # Don't build the examples recursively set(alpaka_BUILD_EXAMPLES OFF) add_subdirectory("${CMAKE_CURRENT_LIST_DIR}/../.." "${CMAKE_BINARY_DIR}/alpaka") else() find_package(alpaka REQUIRED) endif() endif() #------------------------------------------------------------------------------- # Add executable. add_executable(${_TARGET_NAME} src/vectorAdd.cpp) target_link_libraries(${_TARGET_NAME} PUBLIC alpaka::alpaka) alpaka_finalize(${_TARGET_NAME}) set_target_properties(${_TARGET_NAME} PROPERTIES FOLDER example) add_test(NAME ${_TARGET_NAME} COMMAND ${_TARGET_NAME}) ``` -------------------------------- ### Initialize View Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/cheatsheet.rst Initializes an Alpaka view, potentially setting up its dimensions, extents, and other properties. This is a general-purpose snippet for view setup. ```cpp #include // ... // View initialization, etc. alpaka::initView(view, extents, pitches); ``` -------------------------------- ### Build Benchmarks Option Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Controls whether to build the benchmarks during the installation of Alpaka. ```markdown ``alpaka_BENCHMARKS`` .. code-block:: markdown Build the benchmarks. ``` -------------------------------- ### Install Catch2 Testing Framework Source: https://github.com/alpaka-group/alpaka3/blob/dev/test/CMakeLists.txt Installs the Catch2 testing framework, making it available for use in test targets. This function is assumed to be defined elsewhere in the Alpaka build system. ```cmake alpaka_install_catch2() ``` -------------------------------- ### Run Inclusive Scan Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/scan/README.md Execute the scan example to perform an inclusive scan operation. Use this command to test the default inclusive scan functionality. ```bash $ ./scan -t 0 ``` -------------------------------- ### Build Application with CMake and Prepend CMAKE_PREFIX_PATH Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Builds your application using CMake, assuming the CMAKE_PREFIX_PATH environment variable has been set to include the Alpaka installation directory. ```bash cmake cmake --build . --parallel ``` -------------------------------- ### Integrate Installed Alpaka with CMake Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Shows how to find and link the installed Alpaka library in your CMake project. Ensures Alpaka's finalization steps are applied. ```cmake find_package(alpaka REQUIRED) # ... add_executable(myTarget src/my.cpp) target_link_libraries(myTarget PUBLIC alpaka::alpaka) alpaka_finalize(myTarget) # ... ``` -------------------------------- ### Configure FetchContent Subproject Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/CMakeLists.txt Configures the fetchContent example as a separate CMake project, simulating user integration via FetchContent. It passes the C++ compiler to the subproject. ```cmake execute_process( COMMAND ${CMAKE_COMMAND} -S ${CMAKE_CURRENT_SOURCE_DIR}/fetchContent -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/docs/snippets/fetchContent RESULT_VARIABLE SUBPROJECT_CONFIGURE_RESULT OUTPUT_VARIABLE SUBPROJECT_CONFIGURE_OUTPUT ERROR_VARIABLE SUBPROJECT_CONFIGURE_ERROR ) ``` -------------------------------- ### Launching a Hierarchical Kernel Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/kernelParallelism.rst Demonstrates how to launch a hierarchical kernel with a 2D frame specification. This setup is suitable for processing 2D data structures like images. ```cpp // BEGIN-TUTORIAL-hierarchyLaunch // Define the kernel using hierarchyKernel_t = alpaka::kernel::Kernel; // Define the frame specification for the kernel launch // This example assumes a 2D grid of blocks, where each block has a 2D grid of threads. // The total number of blocks in the grid and threads in each block are determined by the device and kernel configuration. // For a 2D image of size 1024x1024, and a block size of 16x16: // const auto frameSpec = alpaka::kernel::FrameSpec, alpaka::BlockSize<16u, 16u>>(1024u, 1024u); // Launch the kernel on the device // alpaka::kernel::launch(device, frameSpec, hierarchyKernel_t{}, data); // END-TUTORIAL-hierarchyLaunch ``` -------------------------------- ### Add Executable and Link Libraries Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/randomInit/CMakeLists.txt Adds the main executable for the example, specifies its source files, includes directories, and links it with the Alpaka library. Finalizes target properties and adds a test. ```cmake add_executable(${_TARGET_NAME} src/randomInit.cpp) target_include_directories(${_TARGET_NAME} PRIVATE src) target_link_libraries(${_TARGET_NAME} PUBLIC alpaka::alpaka) alpaka_finalize(${_TARGET_NAME}) set_target_properties(${_TARGET_NAME} PROPERTIES FOLDER example) add_test(NAME ${_TARGET_NAME} COMMAND ${_TARGET_NAME}) ``` -------------------------------- ### Header Checks Option Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Validates headers to ensure all necessary includes are present during installation. ```markdown ``alpaka_HEADERCHECKS`` .. code-block:: markdown Validate headers to ensure that all necessary includes are present. ``` -------------------------------- ### C++ Memory Allocation Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/memoryAllocation.rst Demonstrates basic memory allocation and deallocation for a generic device using Alpaka's C++ API. Ensure you have the necessary Alpaka headers included. ```cpp #include #include int main() { // Define the device type (e.g., CPU, GPU) using Device = alpaka::dev::Dev; Device dev; // Define the data type and size using DataType = int; const size_t N = 1024; // Allocate memory on the device auto buf = alpaka::alloc::malloc(dev, N); // Check if allocation was successful if (!buf) { std::cerr << "Memory allocation failed!\n"; return 1; } std::cout << "Memory allocated successfully.\n"; // Access and modify data (example: fill with zeros) // Note: For actual data manipulation, you would typically use alpaka::kernel::Kernel or similar constructs. // This is a simplified example to show allocation. alpaka::mem::memset(dev, buf.get(), 0, N * sizeof(DataType)); std::cout << "Memory zeroed out.\n"; // Deallocate memory (automatic via RAII when 'buf' goes out of scope) // alpaka::mem::free(dev, buf); std::cout << "Memory will be deallocated automatically.\n"; return 0; } ``` -------------------------------- ### Build Documentation Snippets Option Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Controls whether to build documentation code snippets during the installation of Alpaka. ```markdown ``alpaka_DOCS`` .. code-block:: markdown Build documentation code snippets. ``` -------------------------------- ### Element-wise Multiplication Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/example.rst Demonstrates element-wise multiplication using Alpaka. Compile with C++20 and optimization flags. For vectorization, set appropriate march flags like -march=haswell. ```cpp #include int main() { // BEGIN-EXAMPLE-elementWiseMultiplication using Pltf = alpaka::Plattform; using Dev = alpaka::Device; using Acc = alpaka::Accelerator; Acc acc; // create host vectors std::vector h_a(1000); std::vector h_b(1000); std::vector h_c(1000); // initialize host vectors std::fill(h_a.begin(), h_a.end(), 1); std::fill(h_b.begin(), h_b.end(), 2); // create device vectors alpaka::Vec workGroupSize(1000); alpaka::Vec workGroupCount(1); auto d_a = alpaka::alloc(acc, workGroupSize.at(0)); auto d_b = alpaka::alloc(acc, workGroupSize.at(0)); auto d_c = alpaka::alloc(acc, workGroupSize.at(0)); // copy host vectors to device vectors alpaka::copy(acc, d_a, h_a.data(), workGroupSize.at(0)); alpaka::copy(acc, d_b, h_b.data(), workGroupSize.at(0)); // create kernel auto kernel = [=](auto &a, auto &b, auto &c) { // get global id auto idx = alpaka::getGlobalId(acc); // multiply elements c[idx] = a[idx] * b[idx]; }; // apply kernel alpaka::kernel(kernel, acc, d_a, d_b, d_c); // copy result back to host vector alpaka::copy(acc, h_c.data(), d_c, workGroupSize.at(0)); // END-EXAMPLE-elementWiseMultiplication return 0; } ``` -------------------------------- ### Add Executable and Link Libraries Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/boundaryIter/CMakeLists.txt Globally finds all C++ source files for the boundaryIter example, adds an executable for each, links the alpaka library, sets folder properties, specifies C++20 standard, finalizes the target, and adds a test. ```cmake file(GLOB_RECURSE boundaryIterSource "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") foreach(boundaryIterFile ${boundaryIterSource}) get_filename_component(boundaryIterFileName ${boundaryIterFile} NAME) string(REPLACE ".cpp" "" boundaryIterName ${boundaryIterFileName}) add_executable(${boundaryIterName} ${boundaryIterFile}) target_link_libraries(${boundaryIterName} PUBLIC alpaka::alpaka) set_target_properties(${boundaryIterName} PROPERTIES FOLDER tutorial) target_compile_features(${boundaryIterName} PRIVATE cxx_std_20) alpaka_finalize(${boundaryIterName}) add_test(NAME ${boundaryIterName} COMMAND ${boundaryIterName}) endforeach() ``` -------------------------------- ### Handle FetchContent Subproject Configuration Errors Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/CMakeLists.txt Checks the result of the subproject configuration and prints status or fatal errors. This ensures the fetchContent example is configured correctly. ```cmake if(NOT SUBPROJECT_CONFIGURE_RESULT EQUAL 0) message(STATUS "Subproject result:\n${SUBPROJECT_CONFIGURE_RESULT}") message(STATUS "Subproject configuration failed:\n${SUBPROJECT_CONFIGURE_OUTPUT}") message(FATAL_ERROR "Subproject configuration error:\n${SUBPROJECT_CONFIGURE_ERROR}") endif() ``` -------------------------------- ### Create Custom Target for FetchContent Build Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/CMakeLists.txt Defines a custom target 'fetchContent_build' to build the fetchContent example. This target is added to the main project's ALL target. ```cmake add_custom_target( fetchContent_build ALL COMMAND ${CMAKE_COMMAND} --build . WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/docs/snippets/fetchContent COMMENT "Building fetchContent snippet..." VERBATIM ) ``` -------------------------------- ### Run N-Body Simulation with Options Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/nBody/README.md Executes the N-Body simulation with specified parameters for particle count, time steps, and time delta. Enables PNG output if the PNGWriter is installed. ```bash ./example/nBody/nBody -n 8192 -t 2000 -d 0.0001 -p ``` -------------------------------- ### Vector Add Example with Alpaka Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/example.rst A small vector add example written with Alpaka that can be run on different processors. This example is intended to be integrated into a project using CMake. ```C++ #include #include #include int main() { // Define the platform and device (e.g., CPU) using Pltf = alpaka::Plattform; using Dev = alpaka::Device; using Acc = alpaka::Accelerator; Acc acc; // Define vector size const auto vecSize = 1000000; // Create host vectors std::vector h_a(vecSize); std::vector h_b(vecSize); std::vector h_c(vecSize); // Initialize host vectors std::fill(h_a.begin(), h_a.end(), 1.0f); std::fill(h_b.begin(), h_b.end(), 2.0f); // Create device vectors auto d_a = alpaka::alloc(acc, vecSize); auto d_b = alpaka::alloc(acc, vecSize); auto d_c = alpaka::alloc(acc, vecSize); // Copy host vectors to device vectors alpaka::copy(acc, d_a, h_a.data(), vecSize); alpaka::copy(acc, d_b, h_b.data(), vecSize); // Define the kernel for vector addition auto kernel = [=](auto &a, auto &b, auto &c) { auto idx = alpaka::getGlobalId(acc); c[idx] = a[idx] + b[idx]; }; // Apply the kernel alpaka::kernel(kernel, acc, d_a, d_b, d_c); // Copy the result back to the host vector alpaka::copy(acc, h_c.data(), d_c, vecSize); // Optional: Verify the result (e.g., check a few elements) // for (size_t i = 0; i < 10; ++i) { // std::cout << h_c[i] << " "; // } // std::cout << std::endl; return 0; } ``` -------------------------------- ### Add Tutorial Executables Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/tutorial/CMakeLists.txt Dynamically finds all C++ source files in the 'src' directory and creates an executable for each. It links against Alpaka and sets up tests. ```cmake file(GLOB_RECURSE tutorialSource "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") foreach(tutExampleFile ${tutorialSource}) get_filename_component(tutFileName ${tutExampleFile} NAME) string(REPLACE ".cpp" "" tutName ${tutFileName}) add_executable(${tutName} ${tutExampleFile}) target_include_directories(${tutName} PRIVATE src) target_link_libraries(${tutName} PUBLIC alpaka::alpaka) alpaka_finalize(${tutName}) set_target_properties(${tutName} PROPERTIES FOLDER tutorial) target_compile_features(${tutName} PRIVATE cxx_std_20) add_test(NAME ${tutName} COMMAND ${tutName}) endforeach() ``` -------------------------------- ### Install CMake on Linux Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/install.rst Installs CMake on Linux systems using either the DNF (RPM) or APT (DEB) package managers. ```bash # RPM sudo dnf install cmake # DEB sudo apt install cmake ``` -------------------------------- ### Find Alpaka Library Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/boundaryIter/CMakeLists.txt Locates the alpaka library, either from an installation or the source tree. Requires alpaka to be installed or available in the source tree. ```cmake if(NOT TARGET alpaka::alpaka) option(alpaka_USE_SOURCE_TREE "Use alpaka's source tree instead of an alpaka installation" OFF) if(alpaka_USE_SOURCE_TREE) # Don't build the examples recursively set(alpaka_BUILD_EXAMPLES OFF) add_subdirectory("${CMAKE_CURRENT_LIST_DIR}/../.." "${CMAKE_BINARY_DIR}/alpaka") else() find_package(alpaka REQUIRED) endif() endif() ``` -------------------------------- ### Create Device Selector and Select Device by Index Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/cheatsheet.rst Shows how to create a device selector and then use it to select a specific device based on its index. ```c++ using Api = alpaka::api::cuda; using DeviceKind = alpaka::deviceKind::nvidiaGpu; auto selector = alpaka::createSelector(Api{}, DeviceKind{}); auto device = alpaka::getDevice(selector, 0u); ``` -------------------------------- ### Select a Host Device Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/device.rst Demonstrates how to select a 'host' device using the 'cpu' device kind. This code snippet is useful for initializing device selection logic. ```cpp #include int main() { // Select a device of the device kind "cpu" using the "host" api. // This device kind is always available. using Device = alpaka::Device, alpaka::DevCpu>; Device device = alpaka::getDevice, alpaka::DevCpu>(); // ... return 0; } ``` -------------------------------- ### Configure, Build, and Test with CMake Presets Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Use these commands to configure a specific CMake preset, build the project using that preset, and then run tests associated with it. ```bash cmake --preset rel-host-cpu-gcc -DCMAKE_CXX_COMPILER=clang++ cmake --build --preset rel-host-cpu-gcc ctest --preset rel-host-cpu-gcc ``` -------------------------------- ### Create a Queue for a Device Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/cheatsheet.rst Demonstrates the creation of a queue associated with a specific Alpaka device, used for managing task execution. ```c++ using Api = alpaka::api::cuda; using DeviceKind = alpaka::deviceKind::nvidiaGpu; auto selector = alpaka::createSelector(Api{}, DeviceKind{}); auto device = alpaka::getDevice(selector, 0u); auto queue = alpaka::makeQueue(device); ``` -------------------------------- ### Launch a Shared-Memory Kernel Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/sharedMemory.rst Demonstrates how to launch a kernel that utilizes shared memory. This involves defining the kernel, creating the accelerator, and enqueuing the kernel with appropriate arguments and work divisions. ```cpp #include #include int main() { // BEGIN-TUTORIAL-sharedLaunch // Define accelerator and memory type using Acc = alpaka::cuda::DevAcc; using Mem = alpaka::cuda::DevMem; // Create accelerator Acc acc; // Define extents for the kernel launch const auto frameExtent = alpaka::dim3(100); const auto chunkExtent = alpaka::vec(10); // Allocate host memory for output std::vector hostOutput(frameExtent[0]); // Allocate device memory for output auto deviceOutput = alpaka::alloc(acc, frameExtent[0]); // Define work division const auto workDiv = alpaka::workDivMap(acc, frameExtent, alpaka::itemsPerThread(1)); // Launch the kernel alpaka::kernel)>(acc, workDiv, sharedKernel, deviceOutput.get(), frameExtent, chunkExtent); // Copy result back to host alpaka::memcpy(acc, hostOutput.data(), deviceOutput.get(), frameExtent[0]); // Print a few values to verify for (int i = 0; i < 10; ++i) { std::cout << hostOutput[i] << " "; } std::cout << std::endl; // END-TUTORIAL-sharedLaunch return 0; } ``` -------------------------------- ### Get Dynamic Shared Memory Pool Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/cheatsheet.rst Get a dynamic shared memory pool. This requires the kernel to have a data member with the size in bytes, or a specialized trait for the kernel. ```cpp auto sharedMem = acc.getSharedMem(...); ``` -------------------------------- ### Complete Source File: 150_atomics.cpp Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/atomics.rst This is the complete source file for the atomics tutorial, including includes, kernel definition, and host-side code for launching the kernel and managing data. ```cpp #include #include #include template void atomicKernel(Acc acc, T* data, const T* input, const T* bins, const T num_bins) { // BEGIN-TUTORIAL-atomicKernel // This kernel increments the histogram bin corresponding to the input value. // It uses alpaka::onAcc::atomicAdd to ensure thread-safe updates to the bins array. // The scope is set to device, meaning the atomic operation is coherent across the entire device. alpaka::onAcc::atomicAdd(acc, &bins[data[alpaka::this_work_item::global_id::x()], 1); // END-TUTORIAL-atomicKernel } int main() { // BEGIN-TUTORIAL-atomicLaunch // Define the accelerator and its properties. using Acc = alpaka::cuda::DevAcc; // Get the default accelerator. Acc acc; // Define the dimensions of the data and the number of bins for the histogram. const auto data_dim = alpaka::dim3(1000u); const auto bins_dim = alpaka::dim3(100u); // Define the work division for the kernel. const auto work_div = alpaka::workdiv3d(acc, data_dim); // Allocate host memory for input data and histogram bins. alpaka::mem::host::alloc host_data(data_dim.x); alpaka::mem::host::alloc host_bins(bins_dim.x); // Initialize host data with some example values. for (uint32_t i = 0; i < data_dim.x; ++i) { host_data[i] = static_cast(i % bins_dim.x); } // Allocate device memory for input data and histogram bins. alpaka::mem::dev::alloc dev_data(acc, data_dim); alpaka::mem::dev::alloc dev_bins(acc, bins_dim); // Copy input data from host to device. alpaka::mem::copy(acc, dev_data, host_data, data_dim); // Initialize device bins to zero. alpaka::mem::set(acc, dev_bins, 0.0f, bins_dim); // Launch the atomic kernel. alpaka::kernel), decltype(work_div)>(acc, atomicKernel, dev_data.get(), dev_data.get(), dev_bins.get(), bins_dim.x); // Copy the resulting histogram bins from device to host. alpaka::mem::copy(acc, host_bins, dev_bins, bins_dim); // END-TUTORIAL-atomicLaunch // Optional: Print the histogram bins to verify the result. std::cout << "Histogram bins:" << std::endl; for (uint32_t i = 0; i < bins_dim.x; ++i) { std::cout << host_bins[i] << " "; if ((i + 1) % 10 == 0) { std::cout << std::endl; } } std::cout << std::endl; return 0; } ``` -------------------------------- ### Define Executable with Catch2 and Link Alpaka Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/snippets/dataStorage/CMakeLists.txt Defines an executable for a data storage example that includes Catch2 for testing. It links against both Catch2 and the Alpaka library. Use this for examples that require unit testing with Catch2. ```cmake add_executable(docs_datastorage_pitch datastorage_pitch.cpp) target_link_libraries(docs_datastorage_pitch PRIVATE Catch2::Catch2WithMain alpaka::alpaka) alpaka_finalize(docs_datastorage_pitch) catch_discover_tests(docs_datastorage_pitch) ``` -------------------------------- ### Instantiate Kernel with Arguments Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/cheatsheet.rst Creates an instance of a kernel with specified arguments, without launching it immediately. The `acc` parameter is handled automatically by Alpaka. ```cpp #include // ... // Instantiate a kernel (does not launch it yet) auto kernel = alpaka::createKernelWithArg(arg1, arg2); ``` -------------------------------- ### CVec Operator Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/vector.rst Shows how operators on CVec result in Vec, losing compile-time availability. ```cpp // BEGIN-TUTORIAL-CVecOp auto sum = c_vec + vec; static_assert(sum.size() == 3, "Sum size must be 3"); static_assert(sum[0] == 5, "Sum component 0 must be 5"); static_assert(sum[1] == 7, "Sum component 1 must be 7"); static_assert(sum[2] == 9, "Sum component 2 must be 9"); // END-TUTORIAL-CVecOp } ``` -------------------------------- ### CMakeLists.txt for Alpaka Project Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/example.rst A minimal CMakeLists.txt file for integrating Alpaka into your project using add_subdirectory. This method does not require Alpaka to be installed separately. ```cmake cmake_minimum_required(VERSION 3.25) project("vectorAdd" CXX) add_subdirectory("" "${CMAKE_BINARY_DIR}/alpaka") add_executable(${PROJECT_NAME} vectorAdd.cpp) target_link_libraries(${PROJECT_NAME} PUBLIC alpaka::alpaka) alpaka_finalize(${PROJECT_NAME}) ``` -------------------------------- ### List Available CMake Presets Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst Use this command to see all defined CMake presets in your project. This helps in understanding the available build configurations. ```bash cd cmake --list-presets ``` -------------------------------- ### Run Exclusive Scan Source: https://github.com/alpaka-group/alpaka3/blob/dev/example/scan/README.md Execute the scan example to perform an exclusive scan operation. Use this command to test the exclusive scan functionality. ```bash $ ./scan -t 1 ``` -------------------------------- ### Get Device Properties Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/device.rst Retrieves and prints properties of a specific device, such as its name and warp size. This helps in understanding the capabilities of the selected device. ```cpp // Get the properties of the device with the index 0. // The properties include the name of the device and the warp size. const auto deviceProperties = alpaka::getDeviceProperties, alpaka::DevCpu>(0u); std::cout << "Device name: " << deviceProperties.name << std::endl; std::cout << "Warp size: " << deviceProperties.warpSize << std::endl; ``` -------------------------------- ### Define In-Kernel Thread Indexing Type Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/basic/cheatsheet.rst Defines the type used for indexing threads within a kernel. This is a fundamental setup for parallel execution. ```c++ using Index = alpaka::idx_t; using BlockSize = alpaka::dim_t; using GridSize = alpaka::dim_t; using ThreadIdx = alpaka::dim_t; using BlockIdx = alpaka::dim_t; using GridIdx = alpaka::dim_t; using WorkDiv = alpaka::workdiv_t; using HostOrDevice = alpaka::HostOrDevice; using Host = alpaka::Host; using Device = alpaka::Device; using HostOrDeviceIdx = alpaka::idx_t; using HostOrDeviceDim = alpaka::dim_t; using HostOrDeviceWorkDiv = alpaka::workdiv_t; using HostOrDeviceBlockIdx = alpaka::dim_t; using HostOrDeviceBlockSize = alpaka::dim_t; using HostOrDeviceGridIdx = alpaka::dim_t; using HostOrDeviceGridSize = alpaka::dim_t; using HostOrDeviceThreadIdx = alpaka::dim_t; ``` -------------------------------- ### Launching the Atomic Kernel Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/tutorial/atomics.rst This C++ code snippet shows how to launch the atomic kernel. It sets up the necessary data structures and defines the work division for parallel execution. ```cpp // BEGIN-TUTORIAL-atomicLaunch // Define the accelerator and its properties. using Acc = alpaka::cuda::DevAcc; // Get the default accelerator. Acc acc; // Define the dimensions of the data and the number of bins for the histogram. const auto data_dim = alpaka::dim3(1000u); const auto bins_dim = alpaka::dim3(100u); // Define the work division for the kernel. const auto work_div = alpaka::workdiv3d(acc, data_dim); // Allocate host memory for input data and histogram bins. alpaka::mem::host::alloc host_data(data_dim.x); alpaka::mem::host::alloc host_bins(bins_dim.x); // Initialize host data with some example values. for (uint32_t i = 0; i < data_dim.x; ++i) { host_data[i] = static_cast(i % bins_dim.x); } // Allocate device memory for input data and histogram bins. alpaka::mem::dev::alloc dev_data(acc, data_dim); alpaka::mem::dev::alloc dev_bins(acc, bins_dim); // Copy input data from host to device. alpaka::mem::copy(acc, dev_data, host_data, data_dim); // Initialize device bins to zero. alpaka::mem::set(acc, dev_bins, 0.0f, bins_dim); // Launch the atomic kernel. alpaka::kernel), decltype(work_div)>(acc, atomicKernel, dev_data.get(), dev_data.get(), dev_bins.get(), bins_dim.x); // Copy the resulting histogram bins from device to host. alpaka::mem::copy(acc, host_bins, dev_bins, bins_dim); // END-TUTORIAL-atomicLaunch ``` -------------------------------- ### Fetch and Configure Catch2 Source: https://github.com/alpaka-group/alpaka3/blob/dev/headerCheck/CMakeLists.txt Fetches and configures the Catch2 testing framework if it's not already available. ```cmake # fetch catch2 if(NOT TARGET Catch2::Catch2WithMain) alpaka_install_catch2() endif() ``` -------------------------------- ### Logging Function Scope Example Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/dev/logging.rst Use ALPAKA_LOG_FUNCTION at the beginning of a function to log its entry and exit. This macro is scope-aware and automatically logs when the scope ends. ```c++ void foo() { ALPAKA_LOG_FUNCTION(onHost::logger::device); // very complex code } ``` -------------------------------- ### Build with a Specific CMake Preset Source: https://github.com/alpaka-group/alpaka3/blob/dev/docs/source/advanced/cmake.rst After configuration, use this command to build the project using the selected CMake preset. This compiles the code according to the configured settings. ```bash cd # build the preset cmake --build --preset rel-host-cpu-gcc ```