### Host Path Wiring Example Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/cudaq_realtime_host_api.md This example demonstrates the end-to-end setup for the host dispatch path, including memory allocation, CUDA graph capture, dispatcher configuration, and communication setup. It requires careful management of pinned memory, ring buffers, and function tables. ```cpp constexpr size_t num_slots = 2; constexpr size_t slot_size = 256; // 1. Allocate pinned ring buffers (host + device views of the same memory) volatile uint64_t *rx_flags_host, *rx_flags_dev; uint8_t *rx_data_host, *rx_data_dev; volatile uint64_t *tx_flags_host, *tx_flags_dev; uint8_t *tx_data_host, *tx_data_dev; cudaHostAlloc(&rx_flags_host, num_slots * sizeof(uint64_t), cudaHostAllocMapped); cudaHostGetDevicePointer((void**)&rx_flags_dev, (void*)rx_flags_host, 0); cudaHostAlloc(&rx_data_host, num_slots * slot_size, cudaHostAllocMapped); cudaHostGetDevicePointer((void**)&rx_data_dev, rx_data_host, 0); // ... same for tx_flags and tx_data ... // 2. Allocate pinned mailbox (one void* per GRAPH_LAUNCH worker) void **h_mailbox_bank, **d_mailbox_bank; cudaHostAlloc(&h_mailbox_bank, sizeof(void*), cudaHostAllocMapped); cudaHostGetDevicePointer((void**)&d_mailbox_bank, h_mailbox_bank, 0); // 3. Capture a CUDA graph with d_mailbox_bank baked into the kernel args. // At runtime the kernel reads *d_mailbox_bank to find the current slot. cudaGraph_t graph; cudaGraphExec_t graph_exec; cudaStream_t capture_stream; cudaStreamCreate(&capture_stream); cudaStreamBeginCapture(capture_stream, cudaStreamCaptureModeGlobal); my_decode_kernel<<<1, 128, 0, capture_stream>>>(d_mailbox_bank); cudaStreamEndCapture(capture_stream, &graph); cudaGraphInstantiateWithFlags(&graph_exec, graph, cudaGraphInstantiateFlagDeviceLaunch); cudaGraphUpload(graph_exec, capture_stream); cudaStreamSynchronize(capture_stream); cudaStreamDestroy(capture_stream); // 4. Build function table (host-side, one GRAPH_LAUNCH entry) cudaq_function_entry_t host_table[1] = {}; host_table[0].function_id = MY_DECODE_FUNCTION_ID; host_table[0].dispatch_mode = CUDAQ_DISPATCH_GRAPH_LAUNCH; host_table[0].handler.graph_exec = graph_exec; // 5. Wire: manager, dispatcher, ringbuffer, function table, control, mailbox cudaq_dispatch_manager_t *manager; cudaq_dispatch_manager_create(&manager); cudaq_dispatcher_config_t config{}; config.device_id = 0; config.num_slots = num_slots; config.slot_size = slot_size; config.dispatch_path = CUDAQ_DISPATCH_PATH_HOST; cudaq_dispatcher_t *dispatcher; cudaq_dispatcher_create(manager, &config, &dispatcher); cudaq_ringbuffer_t ringbuffer{}; ringbuffer.rx_flags = rx_flags_dev; ringbuffer.tx_flags = tx_flags_dev; ringbuffer.rx_data = rx_data_dev; ringbuffer.tx_data = rx_data_dev; // shared: response written in-place ringbuffer.rx_stride_sz = slot_size; ringbuffer.tx_stride_sz = slot_size; ringbuffer.rx_flags_host = rx_flags_host; ringbuffer.tx_flags_host = tx_flags_host; ringbuffer.rx_data_host = rx_data_host; ringbuffer.tx_data_host = rx_data_host; // shared cudaq_dispatcher_set_ringbuffer(dispatcher, &ringbuffer); cudaq_function_table_t table{}; table.entries = host_table; table.count = 1; cudaq_dispatcher_set_function_table(dispatcher, &table); volatile int shutdown_flag = 0; uint64_t stats = 0; cudaq_dispatcher_set_control(dispatcher, &shutdown_flag, &stats); cudaq_dispatcher_set_mailbox(dispatcher, h_mailbox_bank); // 6. Start the host dispatcher (spawns the monitor thread) cudaq_dispatcher_start(dispatcher); // 7. Write an RPC request into slot 0 const uint8_t payload[] = {0, 1, 2, 3}; cudaq_host_ringbuffer_write_rpc_request( &ringbuffer, 0, MY_DECODE_FUNCTION_ID, payload, 4, /*request_id=*/0, /*ptp_timestamp=*/0); // 8. Signal the slot cudaq_host_ringbuffer_signal_slot(&ringbuffer, 0); // 9. Poll for the response cudaq_tx_status_t st; int cuda_err; do { usleep(200); st = cudaq_host_ringbuffer_poll_tx_flag(&ringbuffer, 0, &cuda_err); } while (st == CUDAQ_TX_EMPTY); // st == CUDAQ_TX_READY on success, CUDAQ_TX_ERROR on failure // 10. Sync and read the response cudaDeviceSynchronize(); RPCResponse *resp = reinterpret_cast(rx_data_host); // resp->magic == RPC_MAGIC_RESPONSE, resp->status == 0, etc. uint8_t *result = rx_data_host + sizeof(RPCResponse); // Teardown cudaq_host_ringbuffer_clear_slot(&ringbuffer, 0); shutdown_flag = 1; __sync_synchronize(); cudaq_dispatcher_stop(dispatcher); cudaq_dispatcher_destroy(dispatcher); cudaq_dispatch_manager_destroy(manager); cudaGraphExecDestroy(graph_exec); cudaGraphDestroy(graph); cudaFreeHost(h_mailbox_bank); ``` -------------------------------- ### Setup Kernel and Hamiltonian Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/examples/python/optimizers_gradients.ipynb Initializes the CUDA-Q kernel, Hamiltonian, and parameters for optimization examples. Requires importing cudaq, spin, and numpy. ```python import cudaq from cudaq import spin import numpy as np hamiltonian = 5.907 - 2.1433 * spin.x(0) * spin.x(1) - 2.1433 * spin.y( 0) * spin.y(1) + .21829 * spin.z(0) - 6.125 * spin.z(1) @cudaq.kernel def kernel(angles: list[float]): qubits = cudaq.qvector(2) x(qubits[0]) ry(angles[0], qubits[1]) x.ctrl(qubits[1], qubits[0]) initial_params = np.random.normal(0, np.pi, 1) ``` -------------------------------- ### Testing cpu_roce with Compiler-Driven Proof Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/realtime/device_call.md Example script execution for a compiler-driven proof of concept using a two-port RoCE loopback. This setup involves configuring network devices and running the application in '--app' mode. ```bash cpu_roce_device_call_test.sh \ --channel-device --channel-ip 10.0.0.1 \ --daemon-device --daemon-ip 10.0.0.2 \ --setup-network --app ``` -------------------------------- ### Graph Handler Setup Example Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/cudaq_realtime_host_api.md An example of how to initialize a function table entry for a CUDA graph handler, specifying the graph execution handle, function ID, and dispatch mode. ```APIDOC ### Graph Handler Setup Example ```cpp /// @brief Initialize function table with CUDA graph handler __global__ void init_function_table_graph(cudaq_function_entry_t* entries) { if (threadIdx.x == 0 && blockIdx.x == 0) { entries[0].handler.graph_exec = /* pre-captured cudaGraphExec_t */; entries[0].function_id = DECODE_FUNCTION_ID; entries[0].dispatch_mode = CUDAQ_DISPATCH_GRAPH_LAUNCH; // Schema: same as device call mode entries[0].schema.num_args = 1; entries[0].schema.args[0] = {TYPE_BIT_PACKED, {0}, 16, 128}; entries[0].schema.num_results = 1; entries[0].schema.results[0] = {TYPE_UINT8, {0}, 1, 1}; } } ``` ``` -------------------------------- ### Install Qbraid Server Helper Library Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/cudaq/platform/default/rest/helpers/qbraid/CMakeLists.txt Installs the 'cudaq-serverhelper-qbraid' shared library to the 'lib' directory. ```cmake install(TARGETS cudaq-serverhelper-qbraid DESTINATION lib) ``` -------------------------------- ### Graph Handler Setup Example Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/cudaq_realtime_host_api.md This example demonstrates how to initialize a function table entry to use CUDA graph dispatch. It sets the handler's graph execution, function ID, and dispatch mode, along with schema details for arguments and results. ```cuda __global__ void init_function_table_graph(cudaq_function_entry_t* entries) { if (threadIdx.x == 0 && blockIdx.x == 0) { entries[0].handler.graph_exec = /* pre-captured cudaGraphExec_t */; entries[0].function_id = DECODE_FUNCTION_ID; entries[0].dispatch_mode = CUDAQ_DISPATCH_GRAPH_LAUNCH; // Schema: same as device call mode entries[0].schema.num_args = 1; entries[0].schema.args[0] = {TYPE_BIT_PACKED, {0}, 16, 128}; entries[0].schema.num_results = 1; entries[0].schema.results[0] = {TYPE_UINT8, {0}, 1, 1}; } } ``` -------------------------------- ### Install CUDA Runtime Libraries (RHEL 8 Example) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Installs the necessary CUDA runtime libraries for GPU acceleration on RHEL 8 systems when using pre-built CUDA-Quantum binaries. This snippet is part of a larger script for configuring the build environment. ```bash #!/bin/bash # Install CUDA runtime libraries for RHEL 8 # This is a minimal example and may require adjustments based on specific needs. # Set CUDA version (example: 12.0) CUDA_VERSION="12.0" # Install CUDA runtime packages using dnf sudo dnf install -y cuda-cudart-${CUDA_VERSION} sudo dnf install -y cuda-libraries-${CUDA_VERSION} # Optional: Install other related packages if needed # sudo dnf install -y cuda-nvtx-${CUDA_VERSION} echo "CUDA runtime libraries installed successfully." ``` -------------------------------- ### Install IQM Server Helper Library Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/cudaq/platform/default/rest/helpers/iqm/CMakeLists.txt Installs the 'cudaq-serverhelper-iqm' shared library into the 'lib' directory of the installation prefix. This makes the library available for use by other projects or the runtime environment. ```cmake install(TARGETS cudaq-serverhelper-iqm DESTINATION lib) ``` -------------------------------- ### Install CUDA-Q (Bash) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/quick_start.rst Installs CUDA-Q using a pre-built binary. Use `sudo` for system-wide installation or specify a custom path. Ensure your shell environment is updated after installation. ```bash sudo -E bash install_cuda_quantum*.$(uname -m) --accept . /etc/profile ``` ```bash bash install_cuda_quantum*.$(uname -m) --accept -- --installpath $HOME/.cudaq ``` ```bash source /opt/nvidia/cudaq/set_env.sh ``` -------------------------------- ### Install CUDA-Quantum Executable Source: https://github.com/nvidia/cuda-quantum/blob/main/cudaq/tools/cudaq-quake/CMakeLists.txt Installs the compiled 'cudaq-quake' executable to the 'bin' directory in the installation prefix. This makes the tool available in the system's PATH after installation. ```cmake install(TARGETS cudaq-quake DESTINATION bin) ``` -------------------------------- ### Install LSP Server Executable Source: https://github.com/nvidia/cuda-quantum/blob/main/cudaq/tools/cudaq-lsp-server/CMakeLists.txt Installs the compiled `cudaq-lsp-server` executable to the `bin` directory in the installation prefix. This makes the server available in the system's PATH. ```cmake install(TARGETS cudaq-lsp-server DESTINATION bin) ``` -------------------------------- ### Install FermioniQ Server Helper Library Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/cudaq/platform/fermioniq/helpers/CMakeLists.txt Installs the built cudaq-serverhelper-fermioniq target to the 'lib' directory within the installation prefix. This makes the library accessible after installation. ```cmake install(TARGETS cudaq-serverhelper-fermioniq DESTINATION lib) ``` -------------------------------- ### Install Executable Source: https://github.com/nvidia/cuda-quantum/blob/main/cudaq/tools/cudaq-translate/CMakeLists.txt Installs the built cudaq-translate executable to the bin directory. ```cmake install(TARGETS ${TOOL_NAME} DESTINATION bin) ``` -------------------------------- ### Install Chemistry Library Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/cudaq/domains/chemistry/CMakeLists.txt Installs the chemistry library to the 'lib' directory. ```cmake install(TARGETS cudaq-chemistry DESTINATION lib) ``` -------------------------------- ### Install Braket Server Helper Library Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/cudaq/platform/default/rest/helpers/braket/CMakeLists.txt Installs the `cudaq-serverhelper-braket` shared library to the 'lib' destination. ```cmake install(TARGETS cudaq-serverhelper-braket DESTINATION lib) ``` -------------------------------- ### Install CMake and Ninja with Homebrew Source: https://github.com/nvidia/cuda-quantum/blob/main/Dev_Setup.md Installs CMake and Ninja build system using Homebrew. These tools are recommended for managing the build process. If not using Homebrew, they will be installed in `~/.local/bin`. ```bash brew install cmake ninja ``` -------------------------------- ### Install CUDA-Q Python API Prerequisites and Package Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Installs necessary prerequisites for the CUDA-Q Python API and then installs the package using pip. This is typically used when building from source in the GitHub repository. ```console bash scripts/install_prerequisites.sh pip install . --user ``` -------------------------------- ### Add QAOA Builder Example Test Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/CMakeLists.txt Adds a test for the 'qaoa_maxcut_builder.cpp' example, compiling and running it with `nvq++`. ```cmake add_nvqpp_test(QAOABuilder examples/cpp/other/builder/qaoa_maxcut_builder.cpp) ``` -------------------------------- ### Install CUDA-Quantum Headers (CMake) Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/CMakeLists.txt Installs header files into the include directory. This command specifies which directories to install, destination paths, and uses file matching patterns to include or exclude specific files. ```cmake install (DIRECTORY cudaq DESTINATION include FILES_MATCHING PATTERN "*.h" PATTERN "nlopt-src" EXCLUDE) ``` ```cmake install (DIRECTORY include/cudaq DESTINATION include FILES_MATCHING PATTERN "*.h") ``` ```cmake install (DIRECTORY common DESTINATION include FILES_MATCHING PATTERN "*.h") ``` ```cmake install (FILES nvqir/AnalysisScope.h nvqir/CircuitSimulator.h nvqir/Gates.h nvqir/QIRTypes.h DESTINATION include/nvqir) ``` ```cmake install (FILES nvqir/resourcecounter/ResourceCounterScope.h DESTINATION include/nvqir/resourcecounter) ``` ```cmake install (FILES nvqir/dem/DemScope.h DESTINATION include/nvqir/dem) ``` ```cmake install (FILES cudaq.h DESTINATION include) ``` -------------------------------- ### Add Basic C++ Example Test Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/CMakeLists.txt Adds a test for the 'static_kernel.cpp' example, compiling and running it with `nvq++`. ```cmake add_nvqpp_test(GHZ examples/cpp/basics/static_kernel.cpp) ``` -------------------------------- ### Set Installation and Path Variables Source: https://github.com/nvidia/cuda-quantum/blob/main/Building.md Configure the installation prefix and update PATH and PYTHONPATH environment variables to use the built CUDA-Q binaries and libraries. This is necessary when working outside the development container or customizing the installation location. ```bash export PATH="${CUDAQ_INSTALL_PREFIX}/bin:${PATH}" export PYTHONPATH="${CUDAQ_INSTALL_PREFIX}:${PYTHONPATH}" ``` -------------------------------- ### Compile and Run C++ Dynamics Examples Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/dynamics_examples.rst This command compiles and runs C++ dynamics examples. Ensure you have nvq++ installed and in your PATH. ```bash nvq++ --target dynamics .cpp -o a.out && ./a.out ``` -------------------------------- ### Install CUDA Runtime Libraries Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/data_center_install.rst Installs necessary CUDA runtime libraries for GPU acceleration. The version must match the build version. This example shows package installation for AlmaLinux 8. ```bash # CUDARTInstall # This section is for installing CUDA runtime libraries. # Example commands for AlmaLinux 8: # dnf install -y cuda-cudart-11-0 # dnf install -y cuda-libraries-11-0 # Placeholder for actual package installation commands # Ensure the version matches your CUDA-Q build # End CUDARTInstall ``` -------------------------------- ### Setup Evolution Simulation (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/dynamics.rst Sets up a quantum system time-evolution simulation using cudaq.evolve. Requires the system Hamiltonian, dimensionality, initial state, time schedule, and observables. ```python import cudaq import numpy as np # Assume H is defined as in the previous snippet # H = 0.5 * omega_z * ScalarOperator("sigmaz") + omega_x * ScalarOperator(lambda t: np.cos(omega_d * t), "sigmax") # Define the initial state (e.g., ground state |0>) initial_state = cudaq.State.zero(1) # For a single qubit system # Define the time schedule (e.g., 100 steps from 0 to 10) time_schedule = np.linspace(0, 10, 100) # Define an observable (e.g., sigma_x) observable = cudaq.operators.sigmax() # Simulate the time evolution # The 'dynamics' backend is implicitly used for performance when available result = cudaq.evolve(H, initial_state, time_schedule, observable) ``` -------------------------------- ### Install JSON Forward Header Source: https://github.com/nvidia/cuda-quantum/blob/main/CMakeLists.txt Installs the JSON forward header file to the project's include directory. This is part of the JSON library setup. ```cmake install(FILES tpls/json/single_include_fwd/nlohmann/json_fwd.hpp DESTINATION include/nlohmann) ``` -------------------------------- ### Setup Evolution Simulation (C++) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/dynamics.rst Sets up a quantum system time-evolution simulation using cudaq::evolve. Requires the system Hamiltonian, dimensionality, initial state, time schedule, and observables. ```cpp #include #include // Assume H is defined as in the previous snippet // auto H = 0.5 * omega_z * cudaq::operators::sigmaz() + // omega_x * cudaq::operators::sigmax( [omega_d](double t){ return std::cos(omega_d * t); } ); // Define the initial state (e.g., ground state |0>) auto initial_state = cudaq::get_state("|0>"); // Define the time schedule (e.g., 100 steps from 0 to 10) std::vector time_schedule; for (int i = 0; i < 100; ++i) { time_schedule.push_back(i * 10.0 / 99.0); } // Define an observable (e.g., sigma_x) auto observable = cudaq::operators::sigmax(); // Simulate the time evolution // The 'dynamics' backend is implicitly used for performance when available auto result = cudaq::evolve(H, initial_state, time_schedule, observable); ``` -------------------------------- ### Execute Photonics Kernel with Sample Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/backends/sims/photonics.rst Demonstrates executing a photonic kernel using the 'sample' command on the 'orca-photonics' simulator. This is useful for generating statistics about the quantum state. ```python import cudaq import numpy as np qumode_count = 2 # Define the simulation target. cudaq.set_target("orca-photonics") # Define a quantum kernel function. @cudaq.kernel def kernel(qumode_count: int): level = qumode_count + 1 qumodes = [qudit(level) for _ in range(qumode_count)] # Apply the create gate to the qumodes. for i in range(qumode_count): create(qumodes[i]) # |00⟩ -> |11⟩ # Apply the beam_splitter gate to the qumodes. beam_splitter(qumodes[0], qumodes[1], np.pi / 6) # measure all qumodes mz(qumodes) result = cudaq.sample(kernel, qumode_count, shots_count=1000) print(result) ``` -------------------------------- ### GetStateAsyncOutput Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/executing_kernels.rst Demonstrates how to get the asynchronous output of a kernel execution, specifically the state vector. ```python async def GetStateAsyncOutput(kernel: Kernel): """Get the asynchronous output of a kernel execution, specifically the state vector.""" # Get the state vector from the kernel result = await kernel.run_async() return result.get_state() ``` -------------------------------- ### QuEra Computing C++ Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates running kernels on QuEra's backends using C++. ```cpp #include #include "cuda_runtime.h" #include "quera_basic.hpp" int main() { // Initialize QuEra backend QueraBackend quera_backend; // Define a simple quantum kernel (e.g., a Hadamard gate) auto kernel = [](auto& qreg) { qreg.apply_hadamard(0); }; // Execute the kernel on the backend auto result = quera_backend.run_kernel(kernel); // Process the result (e.g., print measurement outcomes) std::cout << "QuEra kernel executed successfully." << std::endl; return 0; } ``` -------------------------------- ### Python Example for Setting Target and Running a Circuit Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/extending/backend.rst Demonstrates how to set a specific provider as the target in CUDA Quantum and then define and run a quantum circuit using Python. Ensure the provider name, API key, and device are correctly specified. ```python import cudaq # Set the target to your provider cudaq.set_target('', api_key='your_api_key', device='your_device') # Create and run a circuit @cudaq.kernel def bell(): qubits = cudaq.qvector(2) h(qubits[0]) x.ctrl(qubits[0], qubits[1]) mz(qubits) # Run the circuit counts = cudaq.sample(bell) print(counts) ``` -------------------------------- ### Hello World - Simple Bell State (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/specification/cudaq/examples.rst Illustrates Bell state preparation and measurement in Python using CUDA-Quantum. This version includes an assertion to verify the correctness of the results. ```python import cudaq @cudaq.kernel() def bell(num_iters : int) -> int: q = cudaq.qvector(2) nCorrect = 0 for i in range(num_iters): h(q[0]) x.ctrl(q[0], q[1]) results = mz(q) if results[0] == results[1]: nCorrect = nCorrect + 1 reset(q) return nCorrect counts = bell(100) print(f'N Correct = {counts}') assert counts == 100 ``` -------------------------------- ### CMake Target Include Directories Source: https://github.com/nvidia/cuda-quantum/blob/main/CppAPICodingStyle.md Example CMake configuration for setting include directories for internal modules, differentiating between build and install environments using INSTALL_INTERFACE and BUILD_INTERFACE. ```cmake target_include_directories(cudaq-mlir-runtime PUBLIC $ $ PRIVATE .) ``` -------------------------------- ### Run QV Procedure Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/applications/python/quantum_volume.ipynb Example of running the Quantum Volume calculation procedure for 100 four-qubit circuits with a 10% chance of error. This demonstrates how to use the `calc_qv` function. ```python n = 4 calc_qv(100, n, .1) ``` -------------------------------- ### Run Kernels on OQC Backends (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates how to run kernels on OQC's backends using Python. Ensure the OQC SDK is installed and configured. ```python import cudaq # Load a quantum kernel @cuda.kernel def bell_state(): qubit = cudaq.make_kernel() q = qubit.qalloc(2) qubit.h(q[0]) qubit.cx(q[0], q[1]) qubit.observe(q[0]) qubit.observe(q[1]) return qubit # Get the kernel kernel = bell_state() # Execute on OQC result = cudaq.execute(kernel, target="oqc") print(result) ``` -------------------------------- ### Build, Install, and Use NVQIR Backend Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/extending/nvqir_simulator.rst Commands to build, install, and use a custom NVQIR simulation backend. This involves setting environment variables, configuring CMake, and compiling CUDA-Q source files. ```bash export CUDA_QUANTUM_PATH=/path/to/cuda_quantum/install mkdir build && cd build cmake .. -G Ninja -DNVQIR_DIR="$CUDA_QUANTUM_PATH/lib/cmake/nvqir" ninja install ``` ```bash nvq++ file.cpp --target MySimulator ./a.out ``` -------------------------------- ### Setup VS Code Tunnel Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Execute this command within a running CUDA-Q container to set up a remote tunnel for VS Code. This enables connecting either a local VS Code installation or the VS Code Web UI to the container. ```console vscode-setup tunnel --name cuda-quantum-remote --accept-server-license-terms ``` -------------------------------- ### Emulate IQM with QPU Architecture File (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/backends/hardware/backend_iqm.rst Specify a QPU architecture file using 'mapping_file' for emulation, eliminating the need for a server URL. The 'emulate' flag must be set to True. ```python cudaq.set_target('iqm', emulate=True, mapping_file="") ``` -------------------------------- ### Launch and SSH into CUDA-Quantum Docker Container Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Launches a CUDA-Quantum Docker container with GPU access, installs an SSH server, configures it, copies your SSH public key, starts the SSH server, and connects to it. This allows for development with IDEs like VS Code. ```console docker run -itd --gpus all --name cuda-quantum -p 2222:22 nvcr.io/nvidia/nightly/cuda-quantum:cu12-latest ``` ```console docker exec cuda-quantum bash -c "sudo apt-get install -y --no-install-recommends openssh-server" ``` ```console docker exec cuda-quantum bash -c "sudo sed -i -E \"s/#?\s*UsePAM\s+.+/UsePAM yes/g\" /etc/ssh/sshd_config" ``` ```console docker cp ~/.ssh/id_rsa.pub cuda-quantum:/home/cudaq/.ssh/authorized_keys ``` ```console docker exec -d cuda-quantum bash -c "sudo -E /usr/sbin/sshd -D" ``` ```console ssh cudaq@localhost -p 2222 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o GlobalKnownHostsFile=/dev/null ``` -------------------------------- ### Run Kernels on IQM Backends (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates how to run kernels on IQM's backends using Python. Ensure the IQM SDK is installed and configured. ```python import cudaq # Load a quantum kernel @cuda.kernel def bell_state(): qubit = cudaq.make_kernel() q = qubit.qalloc(2) qubit.h(q[0]) qubit.cx(q[0], q[1]) qubit.observe(q[0]) qubit.observe(q[1]) return qubit # Get the kernel kernel = bell_state() # Execute on IQM result = cudaq.execute(kernel, target="iqm") print(result) ``` -------------------------------- ### Install cudaq-opt Executable Source: https://github.com/nvidia/cuda-quantum/blob/main/cudaq/tools/cudaq-opt/CMakeLists.txt Installs the 'cudaq-opt' executable to the 'bin' directory of the installation prefix. This makes the tool available in the system's PATH after installation. ```cmake install(TARGETS cudaq-opt DESTINATION bin) ``` -------------------------------- ### Run Kernels on Quantum Circuits, Inc. Backends (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates how to run kernels on Quantum Circuits, Inc.'s backends using Python. Ensure the QCI SDK is installed and configured. ```python import cudaq # Load a quantum kernel @cuda.kernel def bell_state(): qubit = cudaq.make_kernel() q = qubit.qalloc(2) qubit.h(q[0]) qubit.cx(q[0], q[1]) qubit.observe(q[0]) qubit.observe(q[1]) return qubit # Get the kernel kernel = bell_state() # Execute on QCI result = cudaq.execute(kernel, target="qci") print(result) ``` -------------------------------- ### TII C++ Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates running kernels on TII's backends using C++. ```cpp #include #include "cuda_runtime.h" #include "tii.hpp" int main() { // Initialize TII backend TIIBackend tii_backend; // Define a simple quantum kernel (e.g., a Hadamard gate) auto kernel = [](auto& qreg) { qreg.apply_hadamard(0); }; // Execute the kernel on the backend auto result = tii_backend.run_kernel(kernel); // Process the result (e.g., print measurement outcomes) std::cout << "TII kernel executed successfully." << std::endl; return 0; } ``` -------------------------------- ### QuEra Computing Python Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates running kernels on QuEra's backends using Python. ```python from cuda_quantum.quera_basic import QueraBackend # Initialize QuEra backend quera_backend = QueraBackend() # Define a simple quantum kernel (e.g., a Hadamard gate) def kernel(qreg): qreg.apply_hadamard(0) # Execute the kernel on the backend result = quera_backend.run_kernel(kernel) # Process the result (e.g., print measurement outcomes) print("QuEra kernel executed successfully.") ``` -------------------------------- ### Install Visualization Tools Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/examples/python/visualization.ipynb Installs the necessary libraries (QuTiP and Matplotlib) for visualization. Ensure you restart your kernel after installation. ```python # install `qutip` in the current Python kernel. Skip this if `qutip` is already installed. # `matplotlib` is required for all visualization tasks. # Make sure to restart your kernel if you execute this! # In a Jupyter notebook, go to the menu bar > Kernel > Restart Kernel. # In VSCode, click on the Restart button in the Jupyter toolbar. # The '\' before the '>' operator is so that the shell does not misunderstand # the '>' qualifier for the bash pipe operation. import sys try: import matplotlib.pyplot as plt import qutip except ImportError: print("Tools not found, please install and restart your kernel after this is done.") #!{sys.executable} -m pip install qutip\>5 matplotlib\>=3.5 ``` -------------------------------- ### Install Hololink Bridge Executable Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/unittests/utils/CMakeLists.txt Installs the hololink_bridge executable to the designated binary directory during the installation phase. It is associated with the 'hololink-tools' component. ```cmake install(TARGETS hololink_bridge DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT hololink-tools) ``` -------------------------------- ### TII Python Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates running kernels on TII's backends using Python. ```python from cuda_quantum.tii import TIIBackend # Initialize TII backend tii_backend = TIIBackend() # Define a simple quantum kernel (e.g., a Hadamard gate) def kernel(qreg): qreg.apply_hadamard(0) # Execute the kernel on the backend result = tii_backend.run_kernel(kernel) # Process the result (e.g., print measurement outcomes) print("TII kernel executed successfully.") ``` -------------------------------- ### Scaleway C++ Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates running kernels on Scaleway's backends using C++. ```cpp #include #include "cuda_runtime.h" #include "scaleway.hpp" int main() { // Initialize Scaleway backend ScalewayBackend scaleway_backend; // Define a simple quantum kernel (e.g., a Hadamard gate) auto kernel = [](auto& qreg) { qreg.apply_hadamard(0); }; // Execute the kernel on the backend auto result = scaleway_backend.run_kernel(kernel); // Process the result (e.g., print measurement outcomes) std::cout << "Scaleway kernel executed successfully." << std::endl; return 0; } ``` -------------------------------- ### Disable Build with Install RPATH Source: https://github.com/nvidia/cuda-quantum/blob/main/unittests/CMakeLists.txt Disables the CMake setting for building with install RPATH, which affects how shared libraries are linked during installation. ```cmake SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) ``` -------------------------------- ### Build CUDA-Q Realtime Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/building.md Steps to configure, build, and install the CUDA-Q Realtime library from source. Ensure you are in the 'realtime' directory of the forked repository. ```bash mkdir build && cd build cmake -G Ninja .. -DCUDAQ_REALTIME_BUILD_TESTS=ON # Build ninja # Install ninja install ``` -------------------------------- ### Install REST QPU Target Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/cudaq/platform/default/rest/CMakeLists.txt Installs the built REST QPU shared library to the designated lib directory during the installation process. ```cmake install(TARGETS cudaq-rest-qpu DESTINATION lib) ``` -------------------------------- ### Set up CUDA Quantum Environment Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/applications/python/ptsbe.ipynb Initializes the CUDA Quantum environment and sets the target backend. Also sets a random seed for reproducibility. ```python import cudaq cudaq.set_target("nvidia") cudaq.set_random_seed(42) ``` -------------------------------- ### Build Installer Script Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/data_center_install.rst This script is used to prepare assets for building a self-extracting installer archive. It organizes necessary files for the installation package. ```bash #!/bin/bash -e # CUDAQuantumAssets # This section is for building the installer assets. # It should copy all necessary files into the cuda_quantum_assets directory. # Example: cp -r ../../path/to/files/* cuda_quantum_assets/ # Placeholder for actual asset copying commands # Ensure this directory is created if it doesn't exist mkdir -p cuda_quantum_assets/cudaq # Example: Copying a license file # cp ../../cuda_quantum_assets/cudaq/LICENSE cuda_quantum_assets/cudaq/LICENSE # End CUDAQuantumAssets ``` -------------------------------- ### Reset Specific Install Prefix Path Source: https://github.com/nvidia/cuda-quantum/blob/main/Building.md Remove a specific installation directory for a prerequisite. Use with caution to avoid removing system-wide installations. ```bash rm - /usr/local/llvm ``` -------------------------------- ### YAML Configuration File Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/extending/backend.rst Example structure for a YAML configuration file used to define the target for a custom backend. This file specifies connection details and other backend-specific parameters. ```yaml backend: name: url: "http://localhost:8080" shots: 1024 ``` -------------------------------- ### Hello World - Simple Bell State (C++) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/specification/cudaq/examples.rst Demonstrates the creation and measurement of a Bell state using C++ in CUDA-Quantum. It includes a loop for multiple iterations and error checking. ```cpp #include struct bell { int operator()(int num_iters) __qpu__ { cudaq::qarray<2> q; int nCorrect = 0; for (int i = 0; i < num_iters; i++) { h(q[0]); x(q[0], q[1]); auto results = mz(q); if (results[0] == results[1]) nCorrect++; reset(q[0]); reset(q[1]); } return nCorrect; } }; int main() { printf("N Correct = %d\n", bell{}(100)); } ``` -------------------------------- ### Set Linux Install RPATH Source: https://github.com/nvidia/cuda-quantum/blob/main/CMakeLists.txt Defines the installation RPATH for Linux, specifying dynamic library search paths relative to the executable and installation origin. ```cmake SET(CMAKE_INSTALL_RPATH "$ORIGIN:$ORIGIN/lib:$ORIGIN/lib/plugins:$ORIGIN/../lib:$ORIGIN/../lib/plugins:$ORIGIN/../cudaq/mlir/_mlir_libs:$ORIGIN/../python/cudaq/mlir/_mlir_libs") ``` -------------------------------- ### Build Simple CUDA-Q Kernel Dynamically Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/specification/cudaq/dynamic_kernels.rst Demonstrates building a simple quantum kernel dynamically using cudaq::make_kernel, qalloc, and basic quantum operations like H and X gates. ```cpp auto kernel = cudaq::make_kernel(); auto qubits = kernel.qalloc(2); kernel.h(qubits[0]); kernel.x(qubits[0], qubits[1]); kernel.mz(qubits); // See algorithmic primitives section for more on sample auto counts = cudaq::sample(kernel); ``` ```python kernel = cudaq.make_kernel() qubits = kernel.qalloc(2) kernel.h(qubits[0]) kernel.cx(qubits[0], qubits[1]) kernel.mz(qubits) ``` -------------------------------- ### Install Qudit Execution Manager Library Source: https://github.com/nvidia/cuda-quantum/blob/main/unittests/nvqpp/qudit/simple_qudit/CMakeLists.txt Installs the built qudit execution manager library to the 'lib' directory. This ensures the library is available after installation. ```cmake install(TARGETS ${LIBRARY_NAME} DESTINATION lib) ``` -------------------------------- ### C++: Simple Conditional Logic Example (Sample) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/sample_vs_run.rst A C++ kernel with mid-circuit measurement and conditional logic, originally intended for `cudaq::sample`. This demonstrates the kernel structure before migration. ```cpp auto kernel_example1 = []() __qpu__ { cudaq::qvector q(2); h(q[0]); auto r = mz(q[0]); if (r) { x(q[1]); } return mz(q[1]); }; ``` -------------------------------- ### Verify CUDA-Enabled Torch Installation Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/dynamics.rst This command verifies if your Torch installation supports CUDA. If the output is 'None', you need to install a CUDA-enabled Torch package. ```bash python3 -c "import torch; print(torch.version.cuda)" ``` -------------------------------- ### Set up Simulation Parameters Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/examples/python/dynamics/dynamics_intro_2.ipynb Configures the simulation environment by defining system dimensions, initial state, and the time steps for evolution. The initial state is set to the ground state [1.0, 0.0]. ```python # Dimensions of sub-system. We only have a single degree of freedom of dimension 2 (two-level system). dimensions = {0: 2} # Initial state of the system (ground state) psi0 = cudaq.State.from_data(cp.array([1.0, 0.0], dtype=cp.complex128)) # Schedule of time steps (simulating a long time range) steps = np.linspace(-2.0, 2.0, 5000) schedule = Schedule(steps, ["t"]) ``` -------------------------------- ### Run Bernstein-Vazirani Example (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Execute the Bernstein-Vazirani algorithm example using Python. This command runs the program on the default simulator, utilizing GPU acceleration if available. ```console python examples/python/bernstein_vazirani.py --size 5 ``` -------------------------------- ### Install Homebrew Package Manager Source: https://github.com/nvidia/cuda-quantum/blob/main/Dev_Setup.md Installs Homebrew, a package manager for macOS, used to install core development dependencies. This script should be run directly in your terminal. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/nvidia/cuda-quantum/blob/main/Dev_Setup.md Installs the necessary command-line developer tools for macOS. Verify installation with `xcode-select -p` and `clang --version`. ```bash xcode-select --install ``` -------------------------------- ### Install CUDA-Q to Default Location (Linux) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Execute this command to install CUDA-Q to the default location (/opt/nvidia/cudaq) on Linux systems. Ensure you have bash, tar, and gzip installed. ```bash sudo bash install_cuda_quantum_cu12.x86_64 --accept ``` -------------------------------- ### Create IQM Tokens File Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/backends/hardware/backend_iqm.rst Manually create a tokens file for IQM authentication and set the environment variable. Ensure the token file has restricted access. ```bash echo '{ "access_token": "" }' > resonance-token.json export IQM_TOKENS_FILE="path/to/resonance-token.json" ``` -------------------------------- ### Setting Install RPATH for cuTensorNet and cuTensor Source: https://github.com/nvidia/cuda-quantum/blob/main/runtime/nvqir/cutensornet/CMakeLists.txt This code configures the installation RPATH to include the directories of the cuTensorNet and cuTensor libraries. This ensures that the libraries are found at runtime after installation. ```cmake get_target_property(_cutn_loc cuTensorNet::cuTensorNet IMPORTED_LOCATION) get_target_property(_cut_loc cuTensor::cuTensor IMPORTED_LOCATION) if(_cutn_loc) get_filename_component(_cutn_dir "${_cutn_loc}" DIRECTORY) set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_RPATH}:${_cutn_dir}") endif() if(_cut_loc) get_filename_component(_cut_dir "${_cut_loc}" DIRECTORY) set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_RPATH}:${_cut_dir}") endif() ``` -------------------------------- ### Build and Enter CUDA-Q Realtime Docker Environment Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/user_guide.md Use this script to build a containerized environment with necessary dependencies for CUDA-Q Realtime and transfer your local installation into it. ```bash bash /opt/nvidia/cudaq/realtime/demo.sh ``` -------------------------------- ### Install CUDA-Q Python Wheel Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/data_center_install.rst Installs the CUDA-Q Python wheel package using pip. This is the recommended method for installing CUDA-Q with Python support on the host system. ```bash pip install cuda_quantum*.whl ``` -------------------------------- ### Initialize and Configure Realtime Dispatcher Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/cudaq_realtime_host_api.md This snippet demonstrates the essential steps for initializing and configuring the CUDA Quantum realtime dispatcher. It covers creating the dispatcher, setting its configuration, defining the ring buffer, initializing the function table on the device, and setting control parameters. ```cpp // Host API wiring ASSERT_EQ(cudaq_dispatch_manager_create(&manager_), CUDAQ_OK); cudaq_dispatcher_config_t config{}; config.device_id = 0; config.num_blocks = 1; config.threads_per_block = 32; config.num_slots = static_cast(num_slots_); config.slot_size = static_cast(slot_size_); config.vp_id = 0; config.kernel_type = CUDAQ_KERNEL_REGULAR; config.dispatch_mode = CUDAQ_DISPATCH_DEVICE_CALL; ASSERT_EQ(cudaq_dispatcher_create(manager_, &config, &dispatcher_), CUDAQ_OK); cudaq_ringbuffer_t ringbuffer{}; ringbuffer.rx_flags = rx_flags_; ringbuffer.tx_flags = tx_flags_; ringbuffer.rx_data = rx_data_; ringbuffer.tx_data = tx_data_; ringbuffer.rx_stride_sz = slot_size_; ringbuffer.tx_stride_sz = slot_size_; ASSERT_EQ(cudaq_dispatcher_set_ringbuffer(dispatcher_, &ringbuffer), CUDAQ_OK); // Allocate and initialize function table entries cudaq_function_entry_t* d_entries; cudaMalloc(&d_entries, func_count_ * sizeof(cudaq_function_entry_t)); // Initialize entries on device (including schemas) init_function_table<<<1, 1>>>(d_entries); cudaDeviceSynchronize(); cudaq_function_table_t table{}; table.entries = d_entries; table.count = func_count_; ASSERT_EQ(cudaq_dispatcher_set_function_table(dispatcher_, &table), CUDAQ_OK); ASSERT_EQ(cudaq_dispatcher_set_control(dispatcher_, d_shutdown_flag_, d_stats_), CUDAQ_OK); ASSERT_EQ(cudaq_dispatcher_set_launch_fn( dispatcher_, &cudaq::qec::realtime::mock_decode_launch_dispatch_kernel), CUDAQ_OK); ASSERT_EQ(cudaq_dispatcher_start(dispatcher_), CUDAQ_OK); ``` -------------------------------- ### Run Kernels on Quantinuum Backends (Python) Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates how to run kernels on Quantinuum's backends using Python. Ensure the Quantinuum SDK is installed and configured. ```python import cudaq # Load a quantum kernel @cuda.kernel def bell_state(): qubit = cudaq.make_kernel() q = qubit.qalloc(2) qubit.h(q[0]) qubit.cx(q[0], q[1]) qubit.observe(q[0]) qubit.observe(q[1]) return qubit # Get the kernel kernel = bell_state() # Execute on Quantinuum result = cudaq.execute(kernel, target="quantinuum") print(result) ``` -------------------------------- ### Scaleway Python Example Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/examples/hardware_providers.rst Illustrates running kernels on Scaleway's backends using Python. ```python from cuda_quantum.scaleway import ScalewayBackend # Initialize Scaleway backend scaleway_backend = ScalewayBackend() # Define a simple quantum kernel (e.g., a Hadamard gate) def kernel(qreg): qreg.apply_hadamard(0) # Execute the kernel on the backend result = scaleway_backend.run_kernel(kernel) # Process the result (e.g., print measurement outcomes) print("Scaleway kernel executed successfully.") ``` -------------------------------- ### Install OpenFermionPySCF Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/applications/python/qsci.ipynb Installs the OpenFermionPySCF package, which is required for molecular simulations. ```python !pip install --quiet --break-system-packages openfermionpyscf==0.5 ``` -------------------------------- ### Build and Run Demo Docker Container Source: https://github.com/nvidia/cuda-quantum/blob/main/realtime/docs/nvqlink_latency_demo.md Builds and runs the demo Docker container. Use --dgpu for discrete GPUs or --igpu for integrated GPUs. ```shell sudo sh ./docker/build.sh --dgpu sudo sh ./docker/demo.sh ``` -------------------------------- ### Install CuPy for CUDA 12 Source: https://github.com/nvidia/cuda-quantum/blob/main/docs/sphinx/using/install/local_installation.rst Install the CuPy library for CUDA 12 after the CUDA toolkit has been installed within the container. This command ensures GPU-accelerated Python packages can be used. ```bash python3 -m pip install cupy-cuda12x ```