### Realtime Pipeline Setup and Usage Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/host_side_dispatcher_design.md This C++ snippet demonstrates the basic setup and usage of the `realtime_pipeline` class. It involves configuring the pipeline with callbacks for GPU and CPU stages, creating an injector, starting the pipeline, submitting tasks, and finally stopping the pipeline. ```cpp realtime_pipeline pipeline(config); pipeline.set_gpu_stage([&](int worker_id) -> gpu_worker_resources { ... }); pipeline.set_cpu_stage([&](const cpu_stage_context& ctx) -> size_t { ... }); pipeline.set_completion_handler([&](const completion& c) { ... }); auto injector = pipeline.create_injector(); pipeline.start(); injector.submit(function_id, payload, payload_size, request_id); // ... pipeline.stop(); ``` -------------------------------- ### Python Memory Experiment Example Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/qec/introduction.rst A complete Python example demonstrating the setup and execution of a memory experiment, including noise configuration and using the prep0 operation. ```python import cudaq import cudaq_qec as qec # Use the stim backend for performance in QEC settings cudaq.set_target("stim") # Create code and decoder code = qec.get_code('steane') decoder = qec.get_decoder('single_error_lut', code.get_parity()) # Configure noise noise = cudaq.NoiseModel() noise.add_all_qubit_channel("x", cudaq.Depolarization2(0.01), 1) # Run memory experiment syndromes, measurements = qec.sample_memory_circuit( code, op=qec.operation.prep0, numShots=1000, ``` -------------------------------- ### Install CUDA-QX Components via Pip Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/quickstart/installation.rst Use pip to install the QEC library, Solvers library, or both. Ensure you have pip installed. ```bash pip install cudaq-qec ``` ```bash pip install cudaq-solvers ``` ```bash pip install cudaq-qec cudaq-solvers ``` -------------------------------- ### Compile and Run C++ QAOA Example Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/solvers/qaoa.rst Instructions for compiling and running the C++ QAOA molecular docking example using nvq++. ```bash nvq++ -lcudaq-solvers molecular_docking_qaoa.cpp -o molecular_docking_qaoa ./molecular_docking_qaoa ``` -------------------------------- ### Install PyTorch Directly Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/quickstart/installation.rst Install PyTorch using pip. This is an alternative to installing it as a dependency for optional CUDA-QX components. ```bash pip install torch ``` -------------------------------- ### Install Library Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/simulation/CMakeLists.txt Specifies the installation rules for the simulation library, including component and destination directory. ```cmake install(TARGETS cudaq-qec-realtime-decoding-simulation COMPONENT qec-lib LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ) ``` -------------------------------- ### Example Usage Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/api/qec/tensor_network_decoder_api.rst Example of how to create and use the Tensor Network Decoder. ```APIDOC ## Example Usage .. code-block:: python import cudaq_qec as qec import numpy as np # Example: [3,1] repetition code H = np.array([[1, 1, 0], [0, 1, 1]], dtype=np.uint8) logical_obs = np.array([[1, 1, 1]], dtype=np.uint8) noise_model = [0.1, 0.1, 0.1] decoder = qec.get_decoder("tensor_network_decoder", H, logical_obs=logical_obs, noise_model=noise_model) syndrome = [0.0, 1.0] result = decoder.decode(syndrome) ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/unittests/decoders/trt_decoder/ONNX_TEST_README.md Installs PyTorch and Stim for model training and data generation. ```bash pip install torch stim ``` -------------------------------- ### Build and Test CUDA-QX Source: https://github.com/nvidia/cudaqx/blob/main/Building.md Commands to clone the repository, configure the build environment, install the project, and execute the test suite. ```bash # Then inside the container export CUDAQ_INSTALL_PREFIX=/usr/local/cudaq export CUDAQX_INSTALL_PREFIX=~/.cudaqx cd /workspaces # Get latest source code git clone https://github.com/NVIDIA/cudaqx.git cd cudaqx mkdir build && cd build # Configure your build (adjust as necessary) cmake -G Ninja -S .. \ -DCUDAQ_INSTALL_DIR=$CUDAQ_INSTALL_PREFIX \ -DCMAKE_INSTALL_PREFIX=${CUDAQX_INSTALL_PREFIX} \ -DCUDAQ_DIR=${CUDAQ_INSTALL_PREFIX}/lib/cmake/cudaq \ -DCMAKE_BUILD_TYPE=Release # Install your build ninja install # Perform tests just to prove that it is running export PYTHONPATH=${CUDAQ_INSTALL_PREFIX}:${CUDAQX_INSTALL_PREFIX} export PATH="${CUDAQ_INSTALL_PREFIX}/bin:${CUDAQX_INSTALL_PREFIX}/bin:${PATH}" ctest # Run the python tests # The --ignore option is to bypass tests that require additional packages not contained in # the standard docker container cd .. python3 -m pytest -v libs/qec/python/tests --ignore libs/qec/python/tests/test_tensor_network_decoder.py python3 -m pytest -v libs/solvers/python/tests --ignore libs/solvers/python/tests/test_gqe.py ``` -------------------------------- ### Instantiating a QEC Code in Python Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/qec/introduction.rst Example of creating an instance of an implemented QEC code in Python. ```python # Create a code instance ``` -------------------------------- ### Install Quantinuum Realtime Decoding Library Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/quantinuum/CMakeLists.txt Installs the Quantinuum realtime decoding shared library to the specified library destination within the installation prefix. ```cmake install(TARGETS cudaq-qec-realtime-decoding-quantinuum COMPONENT qec-lib LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) ``` -------------------------------- ### Usage Example: Steane Code with LUT Decoder (C++) Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/qec/introduction.rst Demonstrates how to get a quantum code, instantiate a pre-built 'single_error_lut' decoder with the code's parity matrix, and run stabilizer measurements. The decoding step is shown conceptually. ```cpp using namespace cudaq; // Get a code instance auto code = qec::get_code("steane"); // Create decoder with code's parity matrix auto decoder = qec::get_decoder("single_error_lut", code->get_parity()); // Run stabilizer measurements auto [syndromes, dataQubitResults] = qec::sample_memory_circuit(*code, /*numShots*/numShots, /*numRounds*/ 1); // Decode syndrome auto result = decoder->decode(syndromes[0]); ``` -------------------------------- ### Compile and Run C++ VQE Example Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/solvers/vqe.rst Command to compile and run the C++ UCCSD VQE example using nvq++ and linking the cudaq-solvers library. ```bash nvq++ -lcudaq-solvers uccsd_vqe.cpp -o uccsd_vqe ./uccsd_vqe ``` -------------------------------- ### Install Optional CUDA-QX Components via Pip Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/quickstart/installation.rst Install optional components like the Tensor Network Decoder for QEC or the GQE algorithm for Solvers. These may install PyTorch as a dependency. ```bash pip install cudaq-qec[tensor-network-decoder] ``` ```bash pip install cudaq-solvers[gqe] ``` -------------------------------- ### Set installation directories for wheel builds Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/CMakeLists.txt Configures installation directories for binary, include, and library files when building wheels using scikit-build. ```cmake if (SKBUILD) # When building with scikit, i.e., building wheels, we want all the install # to be on the package directory. set(CMAKE_INSTALL_BINDIR cudaq_qec/bin) set(CMAKE_INSTALL_INCLUDEDIR cudaq_qec/include) set(CMAKE_INSTALL_LIBDIR cudaq_qec/lib) endif() ``` -------------------------------- ### Usage Example: Steane Code with LUT Decoder (Python) Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/qec/introduction.rst Demonstrates how to get a quantum code, instantiate a pre-built 'single_error_lut' decoder with the code's parity matrix, run stabilizer measurements, and decode a syndrome. This example assumes no noise model is applied. ```python import cudaq_qec as qec # Get a code instance steane = qec.get_code("steane") # Create decoder with code's parity matrix decoder = qec.get_decoder('single_error_lut', steane.get_parity()) # Run stabilizer measurements syndromes, dataQubitResults = qec.sample_memory_circuit(steane, numShots=1, numRounds=1) # Decode a syndrome result = decoder.decode(syndromes[0]) if result.converged: print("Error locations:", [i for i,p in enumerate(result.result) if p > 0.5]) # No errors as we did not include a noise model and # thus prints: # Error locations: [] ``` -------------------------------- ### Configure Installation Directories for Wheels Source: https://github.com/nvidia/cudaqx/blob/main/libs/solvers/CMakeLists.txt Sets installation directories for binaries, includes, and libraries when building wheels with scikit-build. ```cmake if (SKBUILD) # When building with scikit, i.e., building wheels, we want all the install # to be on the package directory. set(CMAKE_INSTALL_BINDIR cudaq_solvers/bin) set(CMAKE_INSTALL_INCLUDEDIR cudaq_solvers/include) set(CMAKE_INSTALL_LIBDIR cudaq_solvers/lib) endif() ``` -------------------------------- ### Install CUDA-Q Stubs Library Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/quantinuum/CMakeLists.txt Installs the CUDA-Q stubs shared library to the specified library destination within the installation prefix, intended for the Quantinuum GPU Server. ```cmake install(TARGETS cudaq-qec-realtime-decoding-cudaq-stubs COMPONENT qec-lib LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) ``` -------------------------------- ### Real-time Pre-decoder Test Execution Source: https://github.com/nvidia/cudaqx/blob/main/docs/hybrid_ai_predecoder_pipeline.md Command-line examples for running the real-time pre-decoder test with different pipeline configurations. Optional arguments specify rate and duration. ```bash ./test_realtime_predecoder_w_pymatching d7 # default ./test_realtime_predecoder_w_pymatching d13 ./test_realtime_predecoder_w_pymatching d13_r104 104 20 # 104 µs rate, 20 sec ./test_realtime_predecoder_w_pymatching d21 ./test_realtime_predecoder_w_pymatching d31 ``` -------------------------------- ### Install CUDA-QEC Header Files Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/CMakeLists.txt Installs the CUDA-QEC header files into the installation's include directory, matching files ending with '.h' within the specified source directory. ```cmake install(DIRECTORY ${CUDAQX_QEC_INCLUDE_DIR}/cudaq COMPONENT qec-headers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h") ``` -------------------------------- ### Install CUDA-QEC Library Target Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/CMakeLists.txt Installs the main CUDA-QEC library target to the specified installation directory for the 'qec-lib' component. ```cmake install(TARGETS ${LIBRARY_NAME} COMPONENT qec-lib LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) ``` -------------------------------- ### ADAPT-VQE Example in C++ Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/solvers/adapt.rst Demonstrates the execution of the ADAPT-VQE algorithm using the CUDA-Q Solvers library in C++. This snippet is for users who prefer C++ for quantum algorithm implementation. ```cpp #include #include #include // Begin Documentation __qpu__ void adapt_kernel(int n_qubits, int n_steps) { // Initialize ansatz with a simple parameterized gate auto ansatz = cudaq::ansatz(n_qubits); ansatz.append([](auto q) __qpu__ { spin::ry(0.1, q[0]); }); // Define the Hamiltonian for H2 molecule auto hamiltonian = cudaq::spin::qubitize_operator( "-0.24274247651571757 * I0 " "- 0.16049770801017877 * Z0 " "+ 0.12071259179300581 * Z1 " "+ 0.16049770801017877 * Z0*Z1 " "+ 0.1777127119470687 * X0*X1 " "- 0.2257534910570753 * Y0*Y1 " ); // Initialize the ADAPT-VQE algorithm auto solver = cudaq::ADAPT(hamiltonian, ansatz); // Run the ADAPT-VQE algorithm for a specified number of steps auto energy = solver.vqe(ansatz, n_steps); std::cout << "The calculated ground state energy is: " << energy << std::endl; } ``` -------------------------------- ### Benchmark Output Metrics Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_predecoder_pymatching.rst Example output formats for throughput, latency, decoding time, syndrome density, and correctness verification. ```text Submitted: 60001 Completed: 60001 Throughput: 500.0 req/s Backpressure stalls: 0 ``` ```text Latency (us) [steady-state, 59981 requests after 20 warmup] min = 154.8 p50 = 203.9 mean = 215.5 p99 = 363.4 ``` ```text PyMatching decode: 75.6 us ``` ```text Input: 931.0 / 17472 (0.0533) Output: 16.0 / 17472 (0.0009) Reduction: 98.3% ``` ```text Pipeline (pred+pymatch) mismatches: 108 LER: 0.0018 ``` -------------------------------- ### Real-time Pre-decoder Test with Data Directory Source: https://github.com/nvidia/cudaqx/blob/main/docs/hybrid_ai_predecoder_pipeline.md Example of running the real-time pre-decoder test with an optional flag to specify a data directory for correctness verification. ```bash ./test_realtime_predecoder_w_pymatching --data-dir /path/to/stim/data ``` -------------------------------- ### Run Emulated End-to-End Test Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_predecoder_fpga.rst Commands to execute the emulated test script, with an option to perform initial network setup. ```bash ./libs/qec/unittests/realtime/hololink_predecoder_test.sh \ --emulate \ --setup-network \ --cuda-quantum-dir /path/to/cuda-quantum \ --cuda-qx-dir /path/to/cudaqx \ --data-dir /path/to/syndrome_data ``` ```bash ./libs/qec/unittests/realtime/hololink_predecoder_test.sh \ --emulate \ --cuda-quantum-dir /path/to/cuda-quantum \ --cuda-qx-dir /path/to/cudaqx \ --data-dir /path/to/syndrome_data ``` -------------------------------- ### Configure Include Directories Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/quantinuum/CMakeLists.txt Sets public include directories for the Quantinuum realtime decoding library, differentiating between build and install interfaces. ```cmake target_include_directories(cudaq-qec-realtime-decoding-quantinuum PUBLIC $ $ $) ``` -------------------------------- ### Run Emulated End-to-End Test (Subsequent Runs) Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_relay_bp.rst Simplified command for subsequent runs of the emulated end-to-end test after initial setup. This omits the --build and --setup-network flags. ```bash ./libs/qec/unittests/utils/hololink_qldpc_graph_decoder_test.sh --emulate ``` -------------------------------- ### Real-time QLDPC Graph Decoding Test Output Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_relay_bp.rst Example output from running the realtime_qldpc_graph_decoding unittests. This shows the test suite execution and results. ```text [==========] Running 1 test from 1 test suite. [----------] 1 test from RealtimeQLDPCGraphDecodingTest [ RUN ] RealtimeQLDPCGraphDecodingTest.DispatchHostLoopAllShots ... [ OK ] RealtimeQLDPCGraphDecodingTest.DispatchHostLoopAllShots (XXX ms) [==========] 1 test from 1 test suite ran. [ PASSED ] 1 test. ``` -------------------------------- ### Pull and Run CUDA-QX Development Container Source: https://github.com/nvidia/cudaqx/blob/main/Building.md Use these commands to pull the appropriate Docker image for your system and start the development container with GPU support. ```bash docker pull docker run -it --gpus all --name cudaqx-dev ``` -------------------------------- ### Compilation and Execution Command Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/solvers/adapt.rst Provides the necessary bash commands to compile and run the C++ ADAPT-VQE example. Ensure the CUDA-Q Solvers library is linked during compilation. ```bash nvq++ -lcudaq-solvers adapt_h2.cpp -o adapt_h2 ./adapt_h2 ``` -------------------------------- ### ADAPT-VQE Example in Python Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/solvers/adapt.rst Demonstrates the execution of the ADAPT-VQE algorithm using the CUDA-Q Solvers library in Python. This snippet is intended for users looking to apply adaptive ansatz construction for quantum chemistry problems. ```python import cudaq from cudaq import spin # Begin Documentation @cudaq.kernel def adapt_kernel(n_qubits: int, n_steps: int): # Initialize ansatz with a simple parameterized gate ansatz = cudaq.Ansatz(n_qubits) ansatz.append(lambda q: spin.ry(0.1, q[0])) # Define the Hamiltonian for H2 molecule hamiltonian = spin.qubitize_operator( "-0.24274247651571757 * I0 " "- 0.16049770801017877 * Z0 " "+ 0.12071259179300581 * Z1 " "+ 0.16049770801017877 * Z0*Z1 " "+ 0.1777127119470687 * X0*X1 " "- 0.2257534910570753 * Y0*Y1 " ) # Initialize the ADAPT-VQE algorithm solver = cudaq.ADAPT(hamiltonian, ansatz) # Run the ADAPT-VQE algorithm for a specified number of steps energy = solver.vqe(ansatz, n_steps=n_steps) print(f"The calculated ground state energy is: {energy}") # Example usage: n_qubits = 2 n_steps = 5 adapt_kernel(n_qubits, n_steps) ``` -------------------------------- ### Build libcudaq-realtime for CI Unit Test Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_relay_bp.rst Build the libcudaq-realtime library for CI unit tests. This involves cloning the CUDA Quantum repository, checking out a specific release, configuring with CMake, and installing. ```bash # 1. Build libcudaq-realtime git clone https://github.com/NVIDIA/cuda-quantum.git cudaq-realtime-src cd cudaq-realtime-src git checkout releases/v0.14.1 cd realtime && mkdir -p build && cd build cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/tmp/cudaq-realtime .. ninja && ninja install cd ../../.. # 2. Build cudaqx with the nv-qldpc-decoder test cmake -S cudaqx -B cudaqx/build \ -DCMAKE_BUILD_TYPE=Release \ -DCUDAQ_DIR=/path/to/cudaq-install/lib/cmake/cudaq/ \ -DCUDAQ_REALTIME_ROOT=/tmp/cudaq-realtime \ -DCUDAQX_ENABLE_LIBS="qec" \ -DCUDAQX_INCLUDE_TESTS=ON cmake --build cudaqx/build --target test_realtime_qldpc_graph_decoding ``` -------------------------------- ### Running ADAPT-VQE Solver Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/solvers/introduction.rst This snippet demonstrates how to initiate the ADAPT-VQE algorithm with specified initial state, Hamiltonian, and operators. It includes common configuration parameters for convergence and simulation. ```python energy, parameters, operators = solvers.adapt_vqe( initial_state, hamiltonian, operators, grad_norm_tolerance=1e-3, max_iterations=20, verbose=True, shots=10000 ) ``` -------------------------------- ### Get NV-QLDPC Decoder in Python Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/qec/introduction.rst Instantiates the NV-QLDPC decoder using a parity check matrix defined as a NumPy array. Ensure `cudaq_qec` and `numpy` are installed. ```python import cudaq_qec as qec import numpy as np H_list = [ [1, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 1] ] H_np = np.array(H_list, dtype=np.uint8) decoder = qec.get_decoder("nv-qldpc-decoder", H_np) ``` -------------------------------- ### Build FPGA Demo Components Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_predecoder_fpga.rst Commands to clone and build the necessary dependencies and the cudaqx project with Hololink tools enabled. ```bash # 1. Clone cuda-quantum (realtime) git clone --filter=blob:none --no-checkout \ https://github.com/NVIDIA/cuda-quantum.git cudaq-realtime-src cd cudaq-realtime-src git sparse-checkout init --cone git sparse-checkout set realtime git checkout releases/v0.14.1 cd .. # 2. Build holoscan-sensor-bridge (tag 2.6.0-EA2) # Requires cmake >= 3.30.4 git clone --branch 2.6.0-EA2 \ https://github.com/nvidia-holoscan/holoscan-sensor-bridge.git cd holoscan-sensor-bridge # Strip operators we don't need to avoid configure failures sed -i '/add_subdirectory(audio_packetizer)/d; /add_subdirectory(compute_crc)/d; /add_subdirectory(csi_to_bayer)/d; /add_subdirectory(image_processor)/d; /add_subdirectory(iq_dec)/d; /add_subdirectory(iq_enc)/d; /add_subdirectory(linux_coe_receiver)/d; /add_subdirectory(linux_receiver)/d; /add_subdirectory(packed_format_converter)/d; /add_subdirectory(sub_frame_combiner)/d; /add_subdirectory(udp_transmitter)/d; /add_subdirectory(emulator)/d; /add_subdirectory(sig_gen)/d; /add_subdirectory(sig_viewer)/d' \ src/hololink/operators/CMakeLists.txt mkdir -p build && cd build cmake -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DHOLOLINK_BUILD_ONLY_NATIVE=OFF \ -DHOLOLINK_BUILD_PYTHON=OFF \ -DHOLOLINK_BUILD_TESTS=OFF \ -DHOLOLINK_BUILD_TOOLS=OFF \ -DHOLOLINK_BUILD_EXAMPLES=OFF \ -DHOLOLINK_BUILD_EMULATOR=OFF .. cmake --build . --target gpu_roce_transceiver hololink_core cd ../.. # 3. Build libcudaq-realtime with Hololink tools enabled cd cudaq-realtime-src/realtime && mkdir -p build && cd build cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/tmp/cudaq-realtime \ -DCUDAQ_REALTIME_ENABLE_HOLOLINK_TOOLS=ON \ -DHOLOSCAN_SENSOR_BRIDGE_SOURCE_DIR=../../holoscan-sensor-bridge \ -DHOLOSCAN_SENSOR_BRIDGE_BUILD_DIR=../../holoscan-sensor-bridge/build \ .. ninja && ninja install cd ../../.. # 4. Build cudaqx with Hololink tools enabled cmake -S cudaqx -B cudaqx/build \ -DCMAKE_BUILD_TYPE=Release \ -DCUDAQ_DIR=/path/to/cudaq-install/lib/cmake/cudaq/ \ -DCUDAQ_REALTIME_ROOT=/tmp/cudaq-realtime \ -DCUDAQ_QEC_BUILD_TRT_DECODER=ON \ -DCUDAQX_ENABLE_LIBS="qec" \ -DCUDAQX_INCLUDE_TESTS=ON \ -DCUDAQX_QEC_ENABLE_HOLOLINK_TOOLS=ON \ -DHOLOSCAN_SENSOR_BRIDGE_SOURCE_DIR=/path/to/holoscan-sensor-bridge \ -DHOLOSCAN_SENSOR_BRIDGE_BUILD_DIR=/path/to/holoscan-sensor-bridge/build cmake --build cudaqx/build --target \ hololink_predecoder_bridge \ hololink_fpga_syndrome_playback \ cudaq-qec-pymatching ``` -------------------------------- ### Graph-Based Dispatch Setup (sm_90+) Source: https://github.com/nvidia/cudaqx/blob/main/docs/autonomous_decoder_guide.md Set up graph-based dispatch by creating a CUDA graph, instantiating it with device launch flags, uploading it to the device, and then configuring a function table entry on the host with the graph handle. This method is required for device-side graph launches. ```cpp // 1. Create CUDA graph with your decoder kernel cudaStream_t capture_stream; cudaStreamCreate(&capture_stream); // Allocate buffer pointer for pointer indirection pattern void** d_buffer_ptr; cudaMalloc(&d_buffer_ptr, sizeof(void*)); cudaMemset(d_buffer_ptr, 0, sizeof(void*)); // Capture the graph cudaStreamBeginCapture(capture_stream, cudaStreamCaptureModeGlobal); my_decode_graph_kernel<<<1, 1, 0, capture_stream>>>(d_buffer_ptr); cudaStreamEndCapture(capture_stream, &graph); // Instantiate with device launch flag (required for device-side graph launch) cudaGraphExec_t graph_exec; cudaGraphInstantiateWithFlags(&graph_exec, graph, cudaGraphInstantiateFlagDeviceLaunch); // Upload graph to device cudaGraphUpload(graph_exec, capture_stream); cudaStreamSynchronize(capture_stream); cudaStreamDestroy(capture_stream); // 2. Set up function table entry on HOST (graph_exec is a host handle) cudaq_function_entry_t* d_function_entries; cudaMalloc(&d_function_entries, sizeof(cudaq_function_entry_t)); cudaq_function_entry_t host_entry{}; host_entry.handler.graph_exec = graph_exec; // Host-side graph handle host_entry.function_id = MY_DECODE_FUNCTION_ID; host_entry.dispatch_mode = CUDAQ_DISPATCH_GRAPH_LAUNCH; host_entry.reserved[0] = 0; host_entry.reserved[1] = 0; host_entry.reserved[2] = 0; // Schema: same as device call mode host_entry.schema.num_args = 1; host_entry.schema.num_results = 1; host_entry.schema.reserved = 0; host_entry.schema.args[0].type_id = CUDAQ_TYPE_BIT_PACKED; host_entry.schema.args[0].reserved[0] = 0; host_entry.schema.args[0].reserved[1] = 0; host_entry.schema.args[0].reserved[2] = 0; host_entry.schema.args[0].size_bytes = 16; host_entry.schema.args[0].num_elements = 128; host_entry.schema.results[0].type_id = CUDAQ_TYPE_UINT8; host_entry.schema.results[0].reserved[0] = 0; host_entry.schema.results[0].reserved[1] = 0; host_entry.schema.results[0].reserved[2] = 0; host_entry.schema.results[0].size_bytes = 1; host_entry.schema.results[0].num_elements = 1; // Copy to device cudaMemcpy(d_function_entries, &host_entry, sizeof(cudaq_function_entry_t), cudaMemcpyHostToDevice); // 3. Register with dispatcher using graph-based dispatch API cudaq_function_table_t table; table.entries = d_function_entries; table.count = 1; cudaq_dispatcher_set_function_table(dispatcher, &table); ``` -------------------------------- ### Run ADAPT-VQE (Python) Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/solvers/introduction.rst Demonstrates the basic usage of ADAPT-VQE in Python, including creating a molecule, generating an operator pool, defining an initial state, and running the solver. Requires 'cudaq' and 'cudaq_solvers'. ```python import cudaq import cudaq_solvers as solvers # Define molecular geometry geometry = [ ('H', (0., 0., 0.)), ('H', (0., 0., 0.7474)) ] # Create molecular Hamiltonian molecule = solvers.create_molecule( geometry, 'sto-3g', spin=0, charge=0, casci=True ) # Generate operator pool operators = solvers.get_operator_pool( "spin_complement_gsd", num_orbitals=molecule.n_orbitals ) numElectrons = molecule.n_electrons # Define initial state preparation @cudaq.kernel def initial_state(q: cudaq.qview): for i in range(numElectrons): x(q[i]) # Run ADAPT-VQE energy, parameters, operators = solvers.adapt_vqe( initial_state, molecule.hamiltonian, operators, verbose=True ) print(f"Ground state energy: {energy}") ``` -------------------------------- ### Create Custom Target to Zip Installed Files Source: https://github.com/nvidia/cudaqx/blob/main/CMakeLists.txt Defines a custom target 'zip_installed_files' that creates a zip archive of all installed files. This archive can be used to overlay CUDA-QX files into an existing CUDA-Q installation. ```cmake set(ZIP_OUTPUT "${CMAKE_BINARY_DIR}/installed_files.zip") # Custom target to zip up installed files. The resulting zip file can be used to # overlay CUDA-QX files into a separate (already existing) CUDA-Q install # directory. add_custom_target(zip_installed_files COMMAND bash -c "sed 's#^${CMAKE_INSTALL_PREFIX}/##' ${CMAKE_BINARY_DIR}/install_manifest.txt | zip -@ '${ZIP_OUTPUT}'" WORKING_DIRECTORY "${CMAKE_INSTALL_PREFIX}" COMMENT "Creating zip archive of installed files" VERBATIM ) ``` -------------------------------- ### Unit Test Setup for MyDecoder Source: https://github.com/nvidia/cudaqx/blob/main/docs/autonomous_decoder_guide.md Initialize a device context and decoder for unit testing. This involves allocating memory on the device, setting up the context with test parameters, and then initializing the decoder kernel. Ensure to set the global decoder instance. ```cpp // In: unittests/decoders/realtime/test_my_decoder.cu #include #include "cudaq/qec/realtime/my_decoder.cuh" class MyDecoderTest : public ::testing::Test { protected: void SetUp() override { // Allocate device context cudaMalloc(&d_ctx_, sizeof(cudaq::qec::realtime::my_decoder_context)); // Initialize context with test data cudaq::qec::realtime::my_decoder_context ctx; ctx.num_measurements = 128; ctx.num_observables = 1; // ... set up matrices, buffers, etc. cudaMemcpy(d_ctx_, &ctx, sizeof(ctx), cudaMemcpyHostToDevice); // Allocate and initialize decoder cudaMalloc(&d_decoder_, sizeof(cudaq::qec::realtime::my_decoder)); init_decoder_kernel<<<1, 1>>>(d_decoder_, d_ctx_); cudaDeviceSynchronize(); // Set global decoder cudaq::qec::realtime::set_my_decoder(d_decoder_); } void TearDown() override { if (d_decoder_) cudaFree(d_decoder_); if (d_ctx_) cudaFree(d_ctx_); } cudaq::qec::realtime::my_decoder_context* d_ctx_ = nullptr; cudaq::qec::realtime::my_decoder* d_decoder_ = nullptr; }; ``` -------------------------------- ### Install Git Hooks Source: https://github.com/nvidia/cudaqx/blob/main/CMakeLists.txt Checks for and attempts to install a pre-push Git hook if one exists in the repository. ```cmake # Hooks setup. If the repo contains a custom pre-push hook, attempt to install # it. If the user has a different one installed, then warn them but do not fail # configuration. # ============================================================================== # No actual code snippet provided for hook installation, only a comment. ``` -------------------------------- ### Initialize Sliding Window Decoder Components in Python Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/components/qec/introduction.rst Sets up a surface code and a noise model, preparing for the instantiation of a sliding window decoder. This example shows the initial steps before configuring the window and inner decoder. ```python import cudaq import cudaq_qec as qec import numpy as np cudaq.set_target('stim') num_rounds = 5 code = qec.get_code('surface_code', distance=num_rounds) noise = cudaq.NoiseModel() noise.add_all_qubit_channel("x", cudaq.Depolarization2(0.001), 1) statePrep = qec.operation.prep0 ``` -------------------------------- ### Class Initialization Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/_templates/autosummary/dataclass.rst Documentation for the constructor method of the specified CUDA-Q class. ```APIDOC ## __init__ ### Description Initializes a new instance of the specified class within the CUDA-Q module. ### Method Constructor ### Parameters - **args** (variadic) - Optional - Positional arguments for class initialization. - **kwargs** (dictionary) - Optional - Keyword arguments for class initialization. ``` -------------------------------- ### Set Install RPATH for Dynamic Loading Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/quantinuum/CMakeLists.txt Configures the runtime search path (RPATH) for the installed library to '$ORIGIN', allowing it to find dependent libraries in the same directory. ```cmake set_target_properties(cudaq-qec-realtime-decoding-quantinuum PROPERTIES INSTALL_RPATH "$ORIGIN" ) ``` -------------------------------- ### Initialize QLDPC Decoder Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/api/qec/nv_qldpc_decoder_api.rst Instantiate the nv-qldpc-decoder using the get_decoder API in Python and C++. ```python import cudaq_qec as qec import numpy as np H = np.array([[1, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 1]], dtype=np.uint8) # sample 3x7 PCM opts = dict() # see below for options # Note: H must be in row-major order. If you use # `scipy.sparse.csr_matrix.todense()` to get the parity check # matrix, you must specify todense(order='C') to get a row-major # matrix. nvdec = qec.get_decoder('nv-qldpc-decoder', H, **opts) ``` ```cpp std::size_t block_size = 7; std::size_t syndrome_size = 3; cudaqx::tensor H; std::vector H_vec = {1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1}; H.copy(H_vec.data(), {syndrome_size, block_size}); cudaqx::heterogeneous_map nv_custom_args; nv_custom_args.insert("use_osd", true); // See below for options auto nvdec = cudaq::qec::get_decoder("nv-qldpc-decoder", H, nv_custom_args); ``` -------------------------------- ### Install Git Pre-Push Hook Source: https://github.com/nvidia/cudaqx/blob/main/CMakeLists.txt This snippet checks for an existing pre-push hook and installs a new one if none exists or if the existing one differs. It warns if a hook already exists and is not being overwritten. ```cmake set(SRC_HOOK_PRE_PUSH "${CMAKE_SOURCE_DIR}/.githooks/pre-push") if(EXISTS "${SRC_HOOK_PRE_PUSH}") # Get the Git hooks directory from the Git configuration execute_process( COMMAND git config --get core.hooksPath WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" OUTPUT_VARIABLE GIT_HOOKS_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) # Determine the target hooks directory if(GIT_HOOKS_DIR) set(TARGET_HOOKS_DIR "${GIT_HOOKS_DIR}") else() set(TARGET_HOOKS_DIR "${CMAKE_SOURCE_DIR}/.git/hooks") endif() set(DST_HOOK_PRE_PUSH "${TARGET_HOOKS_DIR}/pre-push") if(EXISTS "${DST_HOOK_PRE_PUSH}") # Compare the contents of the src and dst hook. execute_process( COMMAND git hash-object "${DST_HOOK_PRE_PUSH}" OUTPUT_VARIABLE SHA_DST OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND git hash-object "${SRC_HOOK_PRE_PUSH}" OUTPUT_VARIABLE SHA_SRC OUTPUT_STRIP_TRAILING_WHITESPACE ) if(NOT SHA_SRC STREQUAL SHA_DST) message(WARNING "You already have a ${DST_HOOK_PRE_PUSH} script installed. " "This configuration script will not overwrite it despite the fact that " "it is strongly recommended to use ${SRC_HOOK_PRE_PUSH} in your environment." "\nProceed with caution!") endif() else() if(EXISTS "${TARGET_HOOKS_DIR}") file(COPY "${SRC_HOOK_PRE_PUSH}" DESTINATION "${TARGET_HOOKS_DIR}" FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) message(STATUS "Git pre-push hook installed to ${TARGET_HOOKS_DIR}") else() message(WARNING "The Git hooks directory does not exist: ${TARGET_HOOKS_DIR}\n" "Are you sure this is a Git repository? Hook cannot be installed." ) endif() endif() endif() ``` -------------------------------- ### Configure Simulation Backend Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_decoding.rst Use the simulation backend for local development and testing of decoder configurations. ```python import cudaq import cudaq_qec as qec cudaq.set_target("stim") # Or other simulator qec.configure_decoders_from_file("config.yaml") # Run circuit with noise model results = cudaq.run(my_circuit, shots_count=100, noise_model=cudaq.NoiseModel()) ``` -------------------------------- ### cudaq_qec.get_sorted_pcm_column_indices Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/api/qec/python_api.rst Gets the sorted column indices for a parity check matrix (PCM). ```APIDOC ## Function: cudaq_qec.get_sorted_pcm_column_indices ### Description Gets the sorted column indices for a parity check matrix (PCM). ### Parameters (Parameters not detailed in source) ### Returns (Return type not detailed in source) ``` -------------------------------- ### Link Directories for CUDA-QEC Stim Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/unittests/backend-specific/stim/CMakeLists.txt Specifies the installation directory for libraries to be linked against the `test_qec_stim` target. ```cmake target_link_directories(test_qec_stim PRIVATE ${CUDAQ_INSTALL_DIR}/lib) ``` -------------------------------- ### Link Directories and Definitions Source: https://github.com/nvidia/cudaqx/blob/main/CMakeLists.txt Sets the library search path and adds preprocessor definitions from LLVM. ```cmake link_directories(${LLVM_BUILD_LIBRARY_DIR}) add_definitions(${LLVM_DEFINITIONS}) ``` -------------------------------- ### Configure Include Directories Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/lib/realtime/simulation/CMakeLists.txt Specifies public include directories for the target, differentiating between build and install interfaces. ```cmake target_include_directories(cudaq-qec-realtime-decoding-simulation PUBLIC $ $ $ ) ``` -------------------------------- ### View TRT Decoder Validation Summary Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/unittests/decoders/trt_decoder/ONNX_TEST_README.md Example output format for the TRT decoder validation process. ```text === TRT Decoder Validation Summary === Total test cases: 100 Passed: 100 Failed: 0 Max error: 0.000087 Average error: 0.000023 ==================================== ``` -------------------------------- ### Include Google Test Module Source: https://github.com/nvidia/cudaqx/blob/main/libs/qec/unittests/decoders/pymatching/CMakeLists.txt Includes the Google Test CMake module to enable its functionalities, such as test discovery and setup. ```cmake include(GoogleTest) ``` -------------------------------- ### Build Hololink Bridge and Playback Tools Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_relay_bp.rst Build the Hololink bridge and playback tools, which are necessary for emulated or FPGA testing. This process involves cloning multiple repositories, configuring CMake with specific options, and building targets like gpu_roce_transceiver and hololink_core. ```bash # 1. Clone cuda-quantum (realtime) git clone --filter=blob:none --no-checkout \ https://github.com/NVIDIA/cuda-quantum.git cudaq-realtime-src cd cudaq-realtime-src git sparse-checkout init --cone git sparse-checkout set realtime git checkout releases/v0.14.1 cd .. # 2. Build holoscan-sensor-bridge (tag 2.6.0-EA2) # Requires cmake >= 3.30.4 (HSB -> find_package(holoscan) -> rapids_logger). # If your system cmake is older: pip install cmake git clone --branch 2.6.0-EA2 \ https://github.com/nvidia-holoscan/holoscan-sensor-bridge.git cd holoscan-sensor-bridge # Strip operators we don't need to avoid configure failures from missing deps sed -i '/add_subdirectory(audio_packetizer)/d; /add_subdirectory(compute_crc)/d; /add_subdirectory(csi_to_bayer)/d; /add_subdirectory(image_processor)/d; /add_subdirectory(iq_dec)/d; /add_subdirectory(iq_enc)/d; /add_subdirectory(linux_coe_receiver)/d; /add_subdirectory(linux_receiver)/d; /add_subdirectory(packed_format_converter)/d; /add_subdirectory(sub_frame_combiner)/d; /add_subdirectory(udp_transmitter)/d; /add_subdirectory(emulator)/d; /add_subdirectory(sig_gen)/d; /add_subdirectory(sig_viewer)/d' \ src/hololink/operators/CMakeLists.txt mkdir -p build && cd build cmake -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DHOLOLINK_BUILD_ONLY_NATIVE=OFF \ -DHOLOLINK_BUILD_PYTHON=OFF \ -DHOLOLINK_BUILD_TESTS=OFF \ -DHOLOLINK_BUILD_TOOLS=OFF \ -DHOLOLINK_BUILD_EXAMPLES=OFF \ -DHOLOLINK_BUILD_EMULATOR=OFF .. cmake --build . --target gpu_roce_transceiver hololink_core cd ../.. # 3. Build libcudaq-realtime with Hololink tools enabled # This produces libcudaq-realtime-bridge-hololink.so (needed by the bridge # tool) as well as the FPGA emulator. cd cudaq-realtime-src/realtime && mkdir -p build && cd build cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/tmp/cudaq-realtime \ -DCUDAQ_REALTIME_ENABLE_HOLOLINK_TOOLS=ON \ -DHOLOSCAN_SENSOR_BRIDGE_SOURCE_DIR=../../holoscan-sensor-bridge \ -DHOLOSCAN_SENSOR_BRIDGE_BUILD_DIR=../../holoscan-sensor-bridge/build \ .. ninja && ninja install cd ../../.. # 4. Build cudaqx with Hololink tools enabled cmake -S cudaqx -B cudaqx/build \ -DCMAKE_BUILD_TYPE=Release \ -DCUDAQ_DIR=/path/to/cudaq-install/lib/cmake/cudaq/ \ -DCUDAQ_REALTIME_ROOT=/tmp/cudaq-realtime \ -DCUDAQX_ENABLE_LIBS="qec" \ -DCUDAQX_INCLUDE_TESTS=ON \ -DCUDAQX_QEC_ENABLE_HOLOLINK_TOOLS=ON \ -DHOLOSCAN_SENSOR_BRIDGE_SOURCE_DIR=/path/to/holoscan-sensor-bridge \ -DHOLOSCAN_SENSOR_BRIDGE_BUILD_DIR=/path/to/holoscan-sensor-bridge/build cmake --build cudaqx/build --target \ test_realtime_qldpc_graph_decoding \ hololink_qldpc_graph_decoder_bridge \ hololink_fpga_syndrome_playback ``` -------------------------------- ### Compile Simulation Backend Source: https://github.com/nvidia/cudaqx/blob/main/docs/sphinx/examples_rst/qec/realtime_decoding.rst Compile C++ code with simulation support for local QEC testing. ```bash # Compile with simulation support nvq++ -std=c++20 my_circuit.cpp -lcudaq-qec \ -lcudaq-qec-realtime-decoding \ -lcudaq-qec-realtime-decoding-simulation ./a.out ```