### Example: Getting Started with the NVIDIA QLDPC Decoder Source: https://nvidia.github.io/cudaqx/api/qec/python_api.html Provides a basic usage example for the NVIDIA Quantum Low-Density Parity-Check (QLDPC) decoder. This involves initializing the decoder with a code and applying it to a syndrome. ```python import cudaq # Assume 'code' is an instance of a cudaq.qec.code subclass code = cudaq.qec.steane_code() # Example: Steane code # Initialize the NVIDIA QLDPC decoder nvidia_decoder = cudaq.qec.nvidia_qldpc_decoder(code) # Example syndrome (must match the code's properties) syndrome = [0, 1, 0, 1, 0, 1, 0] # Example for Steane code # Decode the syndrome corrected_syndrome = nvidia_decoder.decode(syndrome) print(f"Original syndrome: {syndrome}") print(f"Corrected syndrome: {corrected_syndrome}") ``` -------------------------------- ### Example: Getting Started with NVIDIA QLDPC Decoder Source: https://nvidia.github.io/cudaqx/index.html Provides a basic usage example for the NVIDIA Quantum Low-Density Parity-Check (QLDPC) decoder. This snippet shows how to initialize and use the decoder with a given QEC code. ```python import cudaq # Define a QEC code (e.g., Surface Code) code = cudaq.qec.SurfaceCode(distance=3) # Initialize the NVIDIA QLDPC decoder qldpc_decoder = cudaq.qec.NVIDIAQLDPCDecoder(code) # Example syndrome measurement syndrome = [0, 1, 0, 1, 1, 0, 0, 1] # Decode the syndrome error_vector = qldpc_decoder.decode(syndrome) print(f"Decoded error vector: {error_vector}\n") ``` -------------------------------- ### Getting Started with the NVIDIA QLDPC Decoder Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_predecoder_pymatching.html This example shows how to initialize and use the NVIDIA QLDPC (Quantum Low-Density Parity-Check) decoder. It requires a parity check matrix as input. ```python import numpy as np import cudaq from cudaq.qec import decoder # Assume parity_matrix is a pre-generated numpy array # Example: parity_matrix = np.array([[1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1]]) def get_nvidia_qldpc_decoder(parity_matrix: np.ndarray) -> decoder: """Initializes the NVIDIA QLDPC decoder.""" # The actual implementation might involve specific parameters or classes # This is a conceptual representation. # Replace 'NvidiaQldpcDecoder' with the actual class name if available # For now, we'll simulate by returning a placeholder. print("Initializing NVIDIA QLDPC Decoder...") # Example: return NvidiaQldpcDecoder(parity_matrix) class MockDecoder: def __init__(self, matrix): self.matrix = matrix print("Mock QLDPC Decoder initialized.") def decode(self, syndrome): print(f"Decoding syndrome: {syndrome}") # Placeholder for decoding logic return [0] * len(syndrome) return MockDecoder(parity_matrix) # Example usage: # Generate a dummy parity matrix for demonstration num_qubits = 5 num_checks = 3 parity_matrix = np.random.randint(2, size=(num_checks, num_qubits)) nvidia_decoder = get_nvidia_qldpc_decoder(parity_matrix) # Example syndrome syndrome = [1, 0, 1] corrected_errors = nvidia_decoder.decode(syndrome) print(f"Corrected errors: {corrected_errors}") ``` -------------------------------- ### Getting Started with NVIDIA QLDPC Decoder Source: https://nvidia.github.io/cudaqx/examples_rst/qec/circuit_level_noise.html Provides an example of how to initialize and use the NVIDIA Low-Density Parity-Check (LDPC) decoder. This involves specifying the code and potentially belief propagation parameters. ```python import cudaq # Assume 'code' is an instance of a cudaq.qec.code class # For example, a surface code code = cudaq.qec.surface_code(5) # 5x5 surface code # Initialize the NVIDIA QLDPC decoder # This might involve specifying parameters like max iterations or belief propagation method # qldpc_decoder = cudaq.qec.qldpc_decoder(code, belief_propagation_method='sum_product') # Example usage of the decoder (requires a syndrome) # syndrome = [0, 1, 0, 1, ...] # error_chain = qldpc_decoder.decode(syndrome) print("Placeholder for initializing and using the NVIDIA QLDPC decoder.") ``` -------------------------------- ### Example: Full CUDA-Q Build (CI Test + Hololink) Source: https://nvidia.github.io/cudaqx/examples_rst/solvers/adapt.html Shows a comprehensive build command for CUDA-Q that includes CI tests and Hololink bridge/playback tools. This is for a more complete development or testing setup. ```bash cmake -B build -DCUDAQ_BUILD_TESTS=ON -DCUDAQ_BUILD_PYTHON=ON -DCUDAQ_BUILD_JAVA=ON -DCUDAQ_BUILD_EXAMPLES=ON -DCUDAQ_BUILD_TOOLS=ON -DCUDAQ_USE_HOLOLINK=ON cmake --build build ``` -------------------------------- ### Example: Building CUDA-Q Application with Full Workflow Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_decoding.html Illustrates a complete workflow example for building and running a CUDA-Q application, potentially involving compilation and execution steps. ```bash # Step 1: Compile C++ code (if applicable) nvcc main.cpp -o main_app -lstdc++ -lcudaq # Step 2: Run the application ./main_app # Or, if using Python: # python main_script.py ``` -------------------------------- ### Example: Full CUDA-Q Build Source: https://nvidia.github.io/cudaqx/examples_rst/solvers/qaoa.html Command to perform a full build of CUDA-Q, including CI tests and Hololink bridge/playback tools. This is for a complete development or deployment setup. ```bash make full_build ``` -------------------------------- ### Run ADAPT-VQE Source: https://nvidia.github.io/cudaqx/components/solvers/introduction.html Demonstrates the basic setup and execution of the ADAPT-VQE algorithm for molecular systems. ```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}") ``` ```C++ #include "cudaq/solvers/adapt.h" #include "cudaq/solvers/operators.h" // compile with // nvq++ adaptEx.cpp --enable-mlir -lcudaq-solvers // ./a.out int main() { // Define initial state preparation auto initial_state = [](cudaq::qvector<>& q) __qpu__ { for (std::size_t i = 0; i < 2; ++i) x(q[i]); }; // Create Hamiltonian (H2 molecule example) cudaq::solvers::molecular_geometry geometry{{"H", {0., 0., 0.}}, {"H", {0., 0., .7474}}}; auto molecule = cudaq::solvers::create_molecule( geometry, "sto-3g", 0, 0, {.casci = true, .verbose = true}); auto h = molecule.hamiltonian; // Generate operator pool auto operators = cudaq::solvers::get_operator_pool( "spin_complement_gsd", { {"num-orbitals", h.num_qubits() / 2} }); // Run ADAPT-VQE auto [energy, parameters, selected_ops] = cudaq::solvers::adapt_vqe( initial_state, h, operators, { {"grad_norm_tolerance", 1e-3}, {"verbose", true} } ); } ``` -------------------------------- ### Example: AI Predecoder with FPGA Data Injection Source: https://nvidia.github.io/cudaqx/examples_rst/solvers/adapt.html Shows the command to run the AI Predecoder with FPGA data injection enabled. This requires specific hardware and setup. ```bash build/bin/ai_predecider_fpga --gpu-id 0 --network-sanity-check --data-dir /path/to/fpga/data --output-dir /path/to/output ``` -------------------------------- ### Example: Building CUDA-Q AI Predecoder Source: https://nvidia.github.io/cudaqx/examples_rst/qec/decoders.html Provides instructions or an example command for building the AI Predecoder component of CUDA-Q. This typically involves using a build system like CMake. ```bash # Navigate to the source directory of the AI Predecoder component. # cd /path/to/cudaq/ai-predecoder-source # Create a build directory and navigate into it. # mkdir build # cd build # Configure the build using CMake, specifying installation prefix if needed. # cmake .. -DCMAKE_INSTALL_PREFIX=/path/to/install # Build the project. # make -j$(nproc) # Use multiple cores for faster compilation # Optionally, install the built components. # make install print("Example build process for CUDA-Q AI Predecoder using CMake.") print("Ensure all prerequisites (dependencies, compilers) are met before building.") ``` -------------------------------- ### Example: Running AI Predecoder with FPGA Data Injection Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_decoding.html Demonstrates running the AI predecoder with FPGA data injection. This example includes options for GPU selection and network sanity checks. ```bash python run_fpga_injection.py \ --mode fpga_test \ --action run \ --gpu_id 0 \ --network_interface eth0 \ --config_file fpga_config.yaml ``` -------------------------------- ### Example: Running AI Predecoder with CUDA-Q Realtime Source: https://nvidia.github.io/cudaqx/api/qec/cpp_api.html Illustrates how to run the AI predecoder component with CUDA-Q for real-time quantum error correction. This example shows the command-line execution with positional arguments. ```bash python -m cudaq.qec.ai_predecoder /path/to/data/directory /path/to/config.json --model /path/to/model.onnx ``` -------------------------------- ### Example: Running FPGA End-to-End Test for Relay BP Decoding Source: https://nvidia.github.io/cudaqx/api/solvers/gqe_api.html Executes an end-to-end test for Relay BP decoding using FPGA acceleration. This requires specific hardware setup and configuration. ```bash ./your_relay_bp_test_executable --fpga --gpu-id 0 --network-sanity-check # Ensure the correct GPU is selected and network sanity check is performed if needed. ``` -------------------------------- ### Install CUDA-Q Solvers with GQE Algorithm via Pip Source: https://nvidia.github.io/cudaqx/quickstart/installation.html Install the CUDA-Q Solvers library with the optional GQE algorithm component using pip. ```bash # Install the GQE algorithm from the Solvers library pip install cudaq-solvers[gqe] ``` -------------------------------- ### Example Usage of CUDA-Q Solvers Library Source: https://nvidia.github.io/cudaqx/api/qec/sliding_window_api.html Demonstrates basic usage of the CUDA-Q Solvers library, focusing on operator infrastructure. This example shows how to create and manipulate molecular Hamiltonians. ```python import cudaq # Define a molecular Hamiltonian using a simple basis # This is a placeholder; actual Hamiltonian construction can be complex. # Example: H2 molecule at a specific bond length (simplified representation) # Define basis orbitals (e.g., STO-3G basis) # For simplicity, let's assume we have pre-defined molecular orbitals and integrals. # Example: Creating a Hamiltonian from a list of terms (Pauli strings and coefficients) # This represents a simplified Hamiltonian, e.g., for H2 in a minimal basis. hamiltonian_terms = [ ("I0", 0.5), # Identity term (constant energy offset) ("Z0", -0.5), # Electron repulsion term ("Z1", -0.5), # Electron repulsion term ("Z0Z1", 0.1657) ] # Create a CUDA-Q Hamiltonian object # Note: The exact API for creating Hamiltonians might vary based on library version. # This is a conceptual example. # hamiltonian = cudaq.spin.PauliHamiltonian(hamiltonian_terms) # Example of using a pre-defined molecular Hamiltonian (if available in the library) # For instance, generating the Hamiltonian for H2 at a specific bond length. # try: # h2_hamiltonian = cudaq.chemistry.MolecularHamiltonian("H2", bond_length=0.74) # print("H2 Hamiltonian generated successfully.") # print(f"Number of terms: {h2_hamiltonian.num_terms()}") # except Exception as e: # print(f"Could not generate H2 Hamiltonian: {e}") # Placeholder for demonstrating operator infrastructure usage print("CUDA-Q Solvers Operator Infrastructure Example") print("This section demonstrates how to work with operators, such as molecular Hamiltonians.") print("Refer to the official documentation for specific API details and advanced usage.") ``` -------------------------------- ### Example: AI Predecoder with CUDA-Q Realtime - Running Source: https://nvidia.github.io/cudaqx/index.html Illustrates how to run the AI Predecoder with CUDA-Q Realtime. This example covers the command-line arguments, including positional and named flags, for executing the predecoder pipeline. ```bash # Example usage with positional arguments and named flags ./run_predecoder.sh \ --data_dir /path/to/data \ --config_file pipeline.json \ --model_path /path/to/model.onnx \ --num_gpus 1 \ --log_level INFO \ /path/to/input/file.qsim \ /path/to/output/directory ``` -------------------------------- ### Example: Complete CUDA-Q Workflow Source: https://nvidia.github.io/cudaqx/api/qec/python_api.html Illustrates a complete workflow in CUDA-Q, from defining a quantum kernel to executing it and retrieving results. This example might involve a simple algorithm like creating a Bell state. ```python import cudaq # Define the quantum kernel @cudaq.kernel def create_bell_state(): qubit = cudaq.get_qureg(2) qubit[0] | H qubit[0] | CNOT(qubit[0], qubit[1]) return cudaq.sample(qubit) # Execute the kernel counts = create_bell_state() # Print the results print(counts) ``` -------------------------------- ### Example: Usage of CUDA-Q Solvers Library for Molecular Hamiltonians Source: https://nvidia.github.io/cudaqx/api/qec/python_api.html Demonstrates how to generate and use molecular Hamiltonians within the CUDA-Q Solvers library. This example shows the creation of a Hamiltonian from molecular orbitals. ```python import cudaq from cudaq import spin # Define molecular orbitals (example) mo = [ spin.Matrix([[1.0, 0.0], [0.0, -1.0]]), spin.Matrix([[0.0, 1.0], [1.0, 0.0]]) ] # Create a molecular Hamiltonian ham = cudaq.chemistry.MolecularHamiltonian(mo) # Use the Hamiltonian in a quantum algorithm (e.g., VQE) # ... (rest of the VQE implementation) ``` -------------------------------- ### Example: Surface Code Implementation in Python Source: https://nvidia.github.io/cudaqx/api/qec/sliding_window_api.html Illustrates how to use the pre-built Surface code in Python with the CUDA-Q QEC library. This example shows basic instantiation and property retrieval. ```python import cudaq # Instantiate the pre-built Surface code with a 2x2 grid surface_code = cudaq.qec.codes.surface(rows=2, cols=2) # Print information about the Surface code print(f"Surface Code (rows={surface_code.rows}, cols={surface_code.cols}):") print(f" Stabilizers: {surface_code.get_stabilizers()}") print(f" Logical Operators: {surface_code.get_logical_operators()}") ``` -------------------------------- ### Usage Example for CUDA-Q QEC Decoder Framework Source: https://nvidia.github.io/cudaqx/api/solvers/gqe_api.html Provides a basic example of how to use the CUDA-Q QEC decoder framework. This snippet shows how to initialize a decoder and potentially use it, though specific decoder logic is omitted. ```python from cudaq import qec # Assume a pre-built decoder or a custom implementation exists # For example, using a hypothetical LookupTableDecoder # decoder = qec.decoder.LookupTableDecoder(...) # Placeholder for decoder usage # print("Decoder initialized and ready for use.") # Example of how a decoder might be used with syndromes: # syndromes = [0, 1, 0, 1] # Example syndromes # corrected_errors = decoder.decode(syndromes) # print(f"Corrected errors: {corrected_errors}") ``` -------------------------------- ### Example: Running Emulated End-to-End Test for Relay BP Decoding Source: https://nvidia.github.io/cudaqx/examples_rst/qec/decoders.html Provides an example command for running an emulated end-to-end test for the Relay BP decoding component. This test simulates the full workflow without requiring hardware. ```bash # Ensure the Relay BP decoding component is built. # Navigate to the build directory or use the orchestration script. # cd /path/to/relay-bp-decoding-source/build # Run the emulated end-to-end test. # ctest --verbose # If using CTest # Or using the orchestration script: # ../scripts/orchestration.sh run --mode emulated_e2e # Example command with specific options: # ../scripts/orchestration.sh run --mode emulated_e2e --num-gpus 1 --data-dir /path/to/test/data print("Example command for running emulated end-to-end tests for Relay BP Decoding.") print("This verifies the decoding pipeline in a simulated environment.") ``` -------------------------------- ### Example: Real-Time Decoding Configuration - Step 3: Load Configuration Source: https://nvidia.github.io/cudaqx/api/qec/python_api.html Demonstrates how to load a previously saved real-time decoder configuration. This allows the decoder to be readily available for use in quantum kernels without re-configuration. ```python import cudaq # Load the decoder configuration from a file config_filename = "my_decoder_config.json" loaded_decoder = cudaq.qec.load_decoder_config(config_filename) print("Decoder configuration loaded successfully.") # The 'loaded_decoder' can now be used for decoding. ``` -------------------------------- ### Example: Building CUDA-Q with CI Unit Tests Source: https://nvidia.github.io/cudaqx/examples_rst/solvers/adapt.html Demonstrates the build process for CUDA-Q specifically for running CI unit tests. This is a minimal build focused on testing infrastructure. ```bash cmake -B build -DCUDAQ_BUILD_TESTS=ON -DCUDAQ_BUILD_PYTHON=OFF -DCUDAQ_BUILD_JAVA=OFF -DCUDAQ_BUILD_EXAMPLES=OFF -DCUDAQ_BUILD_TOOLS=OFF cmake --build build --target test ``` -------------------------------- ### Usage Example for CUDA-Q QEC Decoder Framework Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_decoding.html Illustrates how to use the CUDA-Q QEC decoder framework in C++. This example shows basic setup and usage of a decoder. ```cpp #include #include #include int main() { // Assume a code and stabilizers are defined elsewhere // For demonstration, let's create a dummy code and stabilizers class DummyCode : public cudaq::qec::code { public: DummyCode(int n_qubits) : cudaq::qec::code(n_qubits) {} std::vector get_stabilizers() override { return {cudaq::qec::Pauli("XX"), cudaq::qec::Pauli("ZZ")}; } std::vector get_logical_operators() override { return {cudaq::qec::Pauli("X"), cudaq::qec::Pauli("Z")}; } }; DummyCode code(2); cudaq::qec::decoder decoder(code); // Example syndrome measurement (replace with actual measurements) std::vector syndrome = {0, 1}; // Apply the decoder to correct errors decoder.apply(syndrome); std::cout << "Decoder applied successfully." << std::endl; return 0; } ``` -------------------------------- ### Basic VQE Usage Example Source: https://nvidia.github.io/cudaqx/api/qec/python_realtime_decoding_api.html A fundamental example demonstrating the Variational Quantum Eigensolver (VQE) using the CUDA-Q Solvers library. This snippet shows the basic setup for finding the ground state energy of a molecule. ```python from cudaq import solvers from cudaq.optimization import Adam # Define Hamiltonian options and create Hamiltonian ham_opts = solvers.MolecularHamiltonianOptions() ham_opts.geometry = "H 0.0 0.0 0.0\n H 0.0 0.0 0.74 " ham_opts.basis = "sto-3g" hamiltonian = solvers.MolecularHamiltonian(ham_opts) # Initialize VQE with a basic ansatz and optimizer vqe = solvers.VQE(ansatz=solvers.ansatz.HardwareEfficient(num_qubits=hamiltonian.qubits), optimizer=Adam(max_iterations=100)) # Run VQE result = vqe.run(hamiltonian) print(f"Ground state energy: {result.energy:.5f}") ``` -------------------------------- ### Compilation and Execution Commands Source: https://nvidia.github.io/cudaqx/examples_rst/qec/code_capacity_noise.html Commands to compile and run the C++ CUDA-QEC example. Ensure you have the necessary compiler and libraries installed. ```bash nvq++ --enable-mlir --target=stim -lcudaq-qec code_capacity_noise.cpp -o code_capacity_noise ./code_capacity_noise ``` -------------------------------- ### Decoder Instantiation (C++) Source: https://nvidia.github.io/cudaqx/api/qec/cpp_api.html Example of how to get a decoder instance using the C++ API, supporting default values for parameters. ```APIDOC ## get(name, H, param_map) ### Description This `get` overload supports default values for parameters. ### Method `static std::unique_ptr get` ### Parameters - **name** (const std::string &) - The name of the decoder. - **H** (const cudaqx::tensor &) - The parity-check matrix. - **param_map** (const cudaqx::heterogeneous_map &) - Optional map of decoder parameters. Defaults to an empty map. ``` -------------------------------- ### Decoder Instantiation (Python) Source: https://nvidia.github.io/cudaqx/api/qec/cpp_api.html Example of how to get a decoder instance using the Python API, including specifying the parity-check matrix and options. ```APIDOC ## get_decoder (Python Example) ### Description Instantiates a decoder using the CUDA-QX extension points API. ### Method `qec.get_decoder` ### Parameters - **H** (numpy.ndarray) - The parity-check matrix (PCM) in row-major order (e.g., `order='C'`). - **opts** (dict) - A dictionary of decoder options. ### Request Example ```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 ``` ``` -------------------------------- ### Example: Building CUDA-Q Relay BP Decoding (Full Build) Source: https://nvidia.github.io/cudaqx/index.html Provides instructions for performing a full build of the CUDA-Q Relay BP Decoding components, including CI tests and Hololink bridge/playback tools. This is necessary for full functionality. ```bash # Perform a full build including Hololink tools make -j $(nproc) \ BUILD_HOLOLINK_TOOLS=ON \ BUILD_CI_TESTS=ON ``` -------------------------------- ### Real-Time Decoding Configuration Example Source: https://nvidia.github.io/cudaqx/examples_rst/solvers/vqe.html Shows the steps involved in configuring and saving a decoder for real-time use with CUDA-Q. This includes generating a detector error model and saving the decoder configuration. ```bash # Step 1: Generate Detector Error Model (Conceptual) # cudaq-qec generate-dem --code SteaneCode --output steane_dem.json # Step 2: Configure and Save Decoder (Conceptual) # cudaq-qec configure-decoder --dem steane_dem.json --decoder NVIDIALDPCDecoder --output steane_decoder.json # Step 3: Load Configuration (Conceptual) # decoder_config = cudaq.qec.load_decoder_config("steane_decoder.json") # Step 4: Use in Quantum Kernels (Conceptual) # @cudaq.kernel # def my_kernel(): # # ... quantum circuit ... # syndrome = cudaq.qec.measure_syndrome(...) # corrected_error = cudaq.qec.apply_decoder(syndrome, decoder_config) # # ... continue ... print("Conceptual steps for real-time decoding configuration.") ``` -------------------------------- ### Example: Real-Time Decoding Configuration - Step 2: Configure and Save Decoder Source: https://nvidia.github.io/cudaqx/api/qec/python_api.html This step focuses on configuring a specific decoder (e.g., NVIDIA QLDPC) with the generated detector error model and saving this configuration for later use. ```python import cudaq # Assume 'code' and 'dem' are already defined code = cudaq.qec.surface_code(5) dem = cudaq.qec.generate_detector_error_model(code) # Initialize a decoder (e.g., NVIDIA QLDPC) decoder_config = cudaq.qec.nvidia_qldpc_decoder_config(code, dem) # Save the decoder configuration to a file config_filename = "my_decoder_config.json" decoder_config.save(config_filename) print(f"Decoder configuration saved to {config_filename}") ``` -------------------------------- ### Python Execution Example for CUDA-Q Source: https://nvidia.github.io/cudaqx/api/solvers/gqe_api.html Shows how to execute a CUDA-Q Python script. This typically involves running the script using the Python interpreter, assuming CUDA-Q is installed correctly. ```bash python my_cudaq_script.py # Ensure that the 'cudaq' Python package is installed in your environment. ``` -------------------------------- ### Use Python QEC Implementation Source: https://nvidia.github.io/cudaqx/components/qec/introduction.html Demonstrates how to instantiate and use the custom QEC code. ```python import cudaq_qec as qec # Either import your code directly (e.g. "import my_steane", assuming # your my_steane.py file is in the same directory), or you can paste the # above code here without importing the file. import my_steane # Create instance of your code code = qec.get_code('py-steane-example') # Use the code for various numerical experiments ``` -------------------------------- ### Configuration: Step 3 - Load Configuration Source: https://nvidia.github.io/cudaqx/api/qec/python_realtime_decoding_api.html Demonstrates loading a previously saved decoder configuration. This is essential for using a pre-configured decoder in quantum kernels. ```python from cudaq import qec # Load the decoder configuration from a file loaded_config = qec.DecoderConfiguration.load("my_decoder_config.json") # The loaded_config object can now be used to access the decoder and its settings print(f"Loaded decoder configuration. Decoder type: {type(loaded_config.decoder).__name__}") ``` -------------------------------- ### Complete Workflow Example Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_decoding.html Multi-phase workflow for generating DEMs and running real-time decoding in C++ and Python. ```bash # Phase 1: Generate Detector Error Model (DEM) # This is done once per code/distance/noise configuration ## C++ ./surface_code-1 --distance 3 --num_shots 1000 --p_spam 0.01 \ --save_dem config_d3.yaml --num_rounds 12 --decoder_window 6 ## Python python surface_code-1.py --distance 3 --num_shots 1000 --p_spam 0.01 \ --save_dem config_d3.yaml --num_rounds 12 --decoder_window 6 # Phase 2: Run with Real-Time Decoding # Use the saved DEM configuration ## Simulation ./surface_code-1 --distance 3 --num_shots 1000 --load_dem config_d3.yaml \ --num_rounds 12 --decoder_window 6 ## Quantinuum Emulation ./surface_code-1-quantinuum-emulate --distance 3 --num_shots 1000 --load_dem config_d3.yaml \ --num_rounds 12 --decoder_window 6 ``` -------------------------------- ### Install gfortran on Debian-based Systems Source: https://nvidia.github.io/cudaqx/quickstart/installation.html If CUDA-Q Solvers requires `libgfortran` and it's not installed, use this command on Debian-based systems to install it via apt-get. ```bash apt-get install gfortran ``` -------------------------------- ### Configure and Run GQE Algorithm Source: https://nvidia.github.io/cudaqx/examples_rst/solvers/gqe.html Sets up the configuration for the GQE algorithm, including logging and verbosity settings, and then executes the algorithm to find the ground state energy. ```python from lightning.fabric.loggers import CSVLogger cfg = get_default_config() cfg.use_fabric_logging = False logger = CSVLogger("gqe_h2_logs/gqe.csv") cfg.fabric_logger = logger cfg.save_trajectory = False cfg.verbose = True minE, best_ops = solvers.gqe(cost, op_pool, max_iters=25, ngates=10, config=cfg) ``` -------------------------------- ### Install CUDA-Q Solvers Library via Pip Source: https://nvidia.github.io/cudaqx/quickstart/installation.html Use this command to install the CUDA-Q Solvers library using pip. This is the simplest installation method for the Solvers component. ```bash # Install Solvers library pip install cudaq-solvers ``` -------------------------------- ### Initialize nv-qldpc-decoder with various BP methods Source: https://nvidia.github.io/cudaqx/examples_rst/qec/decoders.html Demonstrates the configuration of different BP methods using the qec.get_decoder interface. Requires a parity check matrix H and appropriate parameters for the chosen method. ```python # Simple 3x7 parity check matrix for demonstration 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.array(H_list, dtype=np.uint8) print("=" * 60) print("Demonstrating BP Methods in nv-qldpc-decoder") print("=" * 60) # Method 0: Sum-Product BP (default) print("\n1. Sum-Product BP (bp_method=0, default):") try: decoder_sp = qec.get_decoder("nv-qldpc-decoder", H, bp_method=0, max_iterations=30) except Exception as e: print( 'The nv-qldpc-decoder is not available with your current CUDA-Q ' + 'QEC installation.') exit(0) print(" Created decoder with sum-product BP") # Method 1: Min-Sum BP print("\n2. Min-Sum BP (bp_method=1):") decoder_ms = qec.get_decoder("nv-qldpc-decoder", H, bp_method=1, max_iterations=30, scale_factor=1.0) print(" Created decoder with min-sum BP") # Method 2: Min-Sum with uniform Memory (Mem-BP) print("\n3. Mem-BP (bp_method=2, uniform memory strength):") decoder_mem = qec.get_decoder("nv-qldpc-decoder", H, bp_method=2, max_iterations=30, use_sparsity=True, gamma0=0.5) print(" Created decoder with Mem-BP (gamma0=0.5)") # Method 3: Min-Sum with Disordered Memory (DMem-BP) print("\n4. DMem-BP (bp_method=3, disordered memory strength):") # Option A: Using gamma_dist (random gammas in range) decoder_dmem = qec.get_decoder("nv-qldpc-decoder", H, bp_method=3, max_iterations=30, use_sparsity=True, gamma_dist=[0.1, 0.5], bp_seed=42) print(" Created decoder with DMem-BP (gamma_dist=[0.1, 0.5])") # Option B: Using explicit_gammas (specify exact gamma for each variable) block_size = H.shape[1] explicit_gammas = [[0.1 + 0.05 * i for i in range(block_size)]] decoder_dmem_explicit = qec.get_decoder("nv-qldpc-decoder", H, bp_method=3, max_iterations=30, use_sparsity=True, explicit_gammas=explicit_gammas) print(" Created decoder with DMem-BP (explicit gammas)") # Method 4: Sequential Relay BP (composition=1) print("\n5. Sequential Relay BP (composition=1):") print(" Requires bp_method=3 and srelay_config") # Configure relay parameters srelay_config = { 'pre_iter': 5, # Run 5 iterations with gamma0 before relay legs 'num_sets': 3, # Use 3 relay legs 'stopping_criterion': 'FirstConv' # Stop after first convergence } # Option A: Using gamma_dist for relay legs decoder_relay = qec.get_decoder("nv-qldpc-decoder", H, bp_method=3, composition=1, max_iterations=50, use_sparsity=True, gamma0=0.3, gamma_dist=[0.1, 0.5], srelay_config=srelay_config, bp_seed=42) print(" Created decoder with Relay-BP (gamma_dist, FirstConv stopping)") # Option B: Using explicit gammas for each relay leg num_relay_legs = 3 explicit_relay_gammas = [ [0.1 + 0.02 * i for i in range(block_size)], # First relay leg [0.2 + 0.03 * i for i in range(block_size)], # Second relay leg [0.3 + 0.04 * i for i in range(block_size)] # Third relay leg ] srelay_config_all = { 'pre_iter': 10, 'num_sets': 3, 'stopping_criterion': 'All' # Run all relay legs } decoder_relay_explicit = qec.get_decoder( "nv-qldpc-decoder", H, bp_method=3, composition=1, max_iterations=50, use_sparsity=True, gamma0=0.3, explicit_gammas=explicit_relay_gammas, srelay_config=srelay_config_all) print(" Created decoder with Relay-BP (explicit gammas, All legs)") ``` -------------------------------- ### Install CUDA-Q QEC Library via Pip Source: https://nvidia.github.io/cudaqx/quickstart/installation.html Use this command to install the CUDA-Q QEC library using pip. This is the simplest installation method for the QEC component. ```bash # Install QEC library pip install cudaq-qec ``` -------------------------------- ### Step 3: Load Configuration for Real-Time Decoding Source: https://nvidia.github.io/cudaqx/api/qec/sliding_window_api.html Demonstrates how to load a previously saved decoder configuration for use in real-time quantum error correction with CUDA-Q. This allows quick deployment of decoders. ```python import cudaq # Define the path to the saved decoder configuration file config_path = "./my_decoder_config.json" # Load the decoder configuration # This function typically returns a decoder object ready for use. # loaded_decoder = cudaq.qec.load_decoder_configuration(config_path) print("Step 3: Load Configuration for Real-Time Decoding") print(f"This step loads the decoder configuration from {config_path}.") print("The loaded decoder is now ready to process syndromes in real-time.") print("Refer to CUDA-Q documentation for the exact loading function.") ``` -------------------------------- ### Install PyTorch directly Source: https://nvidia.github.io/cudaqx/quickstart/installation.html Installs the standard PyTorch package independently of CUDA-QX components. ```bash pip install torch ``` -------------------------------- ### Example: Real-Time Decoding Configuration - Step 4: Use in Quantum Kernels Source: https://nvidia.github.io/cudaqx/api/qec/python_api.html Shows how to integrate a loaded real-time decoder into a CUDA-Q quantum kernel for live error correction during quantum computation. ```python import cudaq # Assume 'loaded_decoder' is already loaded from a configuration file # loaded_decoder = cudaq.qec.load_decoder_config("my_decoder_config.json") @cudaq.kernel def my_quantum_kernel(decoder: cudaq.qec.decoder): q = cudaq.get_qureg(5) # ... perform quantum operations ... syndrome = cudaq.qec.measure_syndrome(q, code) # Assuming 'code' is accessible corrected_syndrome = decoder.decode(syndrome) # ... continue computation with corrected syndrome ... # Example of how to pass the loaded decoder to the kernel # Note: The actual 'code' object needs to be accessible or passed appropriately # For simplicity, assume 'code' is globally available or part of the kernel context # my_quantum_kernel(loaded_decoder) ``` -------------------------------- ### Install PyTorch via CUDA-QX optional components Source: https://nvidia.github.io/cudaqx/quickstart/installation.html Installs PyTorch as a dependency when setting up the QEC or Solvers libraries. ```bash # Installs PyTorch as a dependency pip install cudaq-qec[tensor-network-decoder] pip install cudaq-solvers[gqe] ``` -------------------------------- ### Install CUDA-Q with pip Source: https://nvidia.github.io/cudaqx/api/qec/nv_qldpc_decoder_api.html Install the CUDA-Q Python package using pip. Ensure you have a compatible Python environment. ```bash pip install cudaq ``` -------------------------------- ### Example: Running AI Predecoder with CUDA-Q Realtime Source: https://nvidia.github.io/cudaqx/api/solvers/gqe_api.html Demonstrates how to run the AI predecoder, specifying positional arguments and named flags. This is crucial for setting up the predecoder pipeline for real-time quantum error correction. ```bash ./your_predecoder_executable \ --data-dir /path/to/data \ --model /path/to/model.onnx \ --num-gpus 1 \ --pipeline-config config.json # Replace placeholders with actual paths and configuration details. ``` -------------------------------- ### hololink_qldpc_graph_decoder_test.sh - FPGA Mode Example Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_relay_bp.html Example of running the decoder test script in FPGA mode with specific network and device configurations. ```APIDOC ## Running in FPGA Mode ### Description This section demonstrates how to run the `hololink_qldpc_graph_decoder_test.sh` script in FPGA mode, specifying various parameters for network interfaces, devices, and GPU selection. ### Method Shell Script Execution ### Endpoint `./libs/qec/unittests/utils/hololink_qldpc_graph_decoder_test.sh` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Command Example ```bash ./libs/qec/unittests/utils/hololink_qldpc_graph_decoder_test.sh \ --build \ --setup-network \ --device mlx5_5 \ --bridge-ip 192.168.0.1 \ --fpga-ip 192.168.0.2 \ --gpu 2 \ --page-size 512 \ --hsb-dir /path/to/holoscan-sensor-bridge ``` ### Key Parameters for FPGA Mode | Parameter | Description | |-------------------|---------------------------------------------------| | `--device` | ConnectX IB device name (e.g., `mlx5_5`) | | `--bridge-ip` | IP address assigned to the ConnectX interface | | `--fpga-ip` | FPGA’s IP address | | `--gpu` | GPU device ID (choose NUMA-local GPU for lowest latency) | | `--page-size` | Ring buffer slot size in bytes (use `512` on GB200 for alignment) | | `--spacing` | Inter-shot spacing in microseconds | ### Note on `--spacing` The `--spacing` value should be set to at least the per-shot decode time to avoid overrunning the input ring buffer. If syndromes arrive faster than the decoder can process them, the buffer fills up and messages are lost. Use a `--spacing` value at or above the observed decode time for sustained operation. ### GPU Selection For lowest latency, choose a GPU that is NUMA-local to the ConnectX NIC. For example, on a GB200 system where `mlx5_5` is on NUMA node 1, use `--gpu 2` or `--gpu 3`. Check NUMA locality with: ```bash cat /sys/class/infiniband//device/numa_node ``` ### Network Sanity Check Before running, verify that the bridge IP is assigned to exactly one interface: ```bash ip addr show | grep 192.168.0.1 ``` If multiple interfaces show the same IP, remove the duplicate to avoid routing ambiguity that silently drops RDMA packets. ``` -------------------------------- ### Build FPGA Demo and Realtime Tools Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_predecoder_fpga.html Provides the sequence of commands to clone, configure, and build the cuda-quantum realtime components and the holoscan-sensor-bridge dependency. ```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 ../../.. ``` -------------------------------- ### Install Both CUDA-Q QEC and Solvers Libraries via Pip Source: https://nvidia.github.io/cudaqx/quickstart/installation.html Install both the CUDA-Q QEC and Solvers libraries simultaneously using a single pip command. ```bash # Install both libraries pip install cudaq-qec cudaq-solvers ``` -------------------------------- ### C++ Compilation Example Source: https://nvidia.github.io/cudaqx/api/qec/python_realtime_decoding_api.html Provides a basic example of how to compile a CUDA-Q C++ application. This typically involves using nvcc and linking against CUDA-Q libraries. ```bash nvcc my_cudaq_app.cpp -o my_cudaq_app -l:libcudaq.so -L/path/to/cudaq/lib -I/path/to/cudaq/include ``` -------------------------------- ### Step 3: Load Configuration Source: https://nvidia.github.io/cudaqx/api/qec/tensor_network_decoder_api.html Explains how to load a previously saved decoder configuration. This is necessary to utilize a pre-trained or pre-configured decoder within a quantum kernel or simulation. ```python import cudaq # Conceptual function to load a decoder configuration def load_decoder_configuration(config_path): print(f"Loading decoder configuration from: {config_path}") # This function would read the configuration file and instantiate # the appropriate decoder object with its trained parameters. # loaded_decoder = cudaq.qec.load_decoder(config_path) # return loaded_decoder return "loaded_decoder_object" # Placeholder # Example usage: # decoder_config_path = "./my_qldpc_decoder.config" # my_decoder = load_decoder_configuration(decoder_config_path) # print(f"Decoder loaded: {my_decoder}") ``` -------------------------------- ### AI Predecoder Example Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_predecoder_pymatching.html This example demonstrates the usage of an AI-based predecoder with CUDA-Q Realtime. It outlines the necessary prerequisites, data directory layout, and how to run the predecoder. ```bash # Example command to run the AI predecoder # python run_predecoder.py \ # --data_dir /path/to/your/data \ # --model_path /path/to/your/model.onnx \ # --num_qubits 4 \ # --num_rounds 10 \ # --threshold 0.05 # Positional Arguments: # data_dir: Path to the directory containing simulation data. # model_path: Path to the ONNX model file for the predecoder. # Named Flags: # --num_qubits: Number of qubits in the quantum system. # --num_rounds: Number of QEC rounds to simulate. # --threshold: Error rate threshold for decoding. ``` -------------------------------- ### Basic VQE Example in CUDA-Q Source: https://nvidia.github.io/cudaqx/examples_rst/qec/realtime_predecoder_fpga.html A fundamental example showcasing the Variational Quantum Eigensolver (VQE) implementation in CUDA-Q, suitable for basic quantum chemistry calculations. ```python import cudaq from cudaq import spin # Define the Hamiltonian (e.g., from a molecular model) hamiltonian = spin.FermionicModel.from_qiskit_hamiltonian(...) # Define the ansatz circuit ansatz = cudaq.qiskit.circuit.QuantumCircuit(hamiltonian.num_qubits) # ... add gates to ansatz ... # Run VQE result = cudaq.minimize(ansatz, hamiltonian=hamiltonian, optimizer=cudaq.optimizers.Adam(50), sampler=cudaq.SampleResult()) print(f"Minimum energy found: {result.optimal_value}") ```