Table of Contents

Quantum Machine Learning

Quantum machine learning (QML) uses quantum circuits as neural networks trained on classical data. CUDA-Q integrates with ML frameworks for end-to-end training.

#include "cudaq.h"
#include "cudaq/gradients.h"
#include <vector>
#include <cmath>
 
// Quantum layer: parameterized circuit
struct QuantumLayer {
  void operator()(std::vector<double> params) __qpu__ {
    int n = params.size();
    cudaq::qvector q(n);
 
    // Encoding layer: encode classical data as rotations
    for (int i = 0; i < n; i++) {
      ry(params[i], q[i]);
    }
 
    // Trainable layer
    for (int i = 0; i < n; i++) {
      // Would add learned parameters here
      h(q[i]);
    }
 
    // Entangling layer
    for (int i = 0; i < n - 1; i++) {
      cx(q[i], q[i+1]);
    }
 
    mz(q);
  }
};
 
// QML workflow
int main() {
  // Training data
  std::vector<std::vector<double>> X_train = {
      {0.1, 0.2},
      {0.3, 0.4},
      {0.5, 0.6}
  };
  std::vector<int> y_train = {0, 1, 1};
 
  // Initialize quantum weights
  std::vector<double> weights(4, 0.1);
 
  // Training loop
  for (int epoch = 0; epoch < 10; epoch++) {
    double loss = 0.0;
 
    for (size_t i = 0; i < X_train.size(); i++) {
      // Forward pass: quantum circuit predicts label
      auto result = cudaq::sample<QuantumLayer>(100, X_train[i]);
      double pred = result.probability("1");
 
      // Compute loss (cross-entropy)
      loss += (y_train[i] - pred) * (y_train[i] - pred);
    }
 
    printf("Epoch %d, Loss: %.6f\n", epoch, loss / X_train.size());
 
    // Gradient update (would use cudaq gradients in practice)
    weights[0] -= 0.01;  // Simple update
  }
 
  return 0;
}

QML leverages quantum entanglement for feature extraction. CUDA-Q provides the quantum-classical interface; combine with PyTorch/TensorFlow for full ML pipelines.