Skip to content
n-azimiPublic

Repository files navigation

QShield: Coherence-Blind Circuits and the Adversarial Robustness of Hybrid Quantum–Classical Networks

Formerly titled: QShield: Securing Neural Networks Against Adversarial Attacks using Quantum Circuits

Google Scholar arXiv Paper Authors Python PyTorch Jupyter Notebook Platform No Maintenance Intended Media Coverage - Machine Brief Media Coverage - Quantum Zeitgeist

📚 Table of Contents

  1. 📋 Overview
  2. 🔍 The QShield Framework
  3. 💡 QShield-Net: Key Features
  4. 🏗️ Architecture & Components
  5. ⚛️ Quantum Circuits
  6. 🛢️ Datasets
  7. 🧠 Models
  8. ⚙️ Installation & Setup
  9. 🔬 Reproducing the Paper's Results
  10. 🌐 Flask Web Application
  11. 🗂️ Code Structure
  12. 📦 Libraries & Dependencies
  13. 📑 Citation
  14. 📜 License

📋 Overview

Hybrid quantum-classical neural networks are often reported to be more robust to adversarial examples than classical networks, but what the quantum circuit contributes is rarely established. We answer this question exactly for a broad family of circuits. We characterize the quantum operations whose measured statistics are blind to coherence and prove that a circuit that prepares a product encoding and then applies only such operations, including CNOT and CZ entanglers, diagonal gates, and Pauli and damping noise, has the measurement statistics of a classical probabilistic circuit, however much entanglement it creates. Inside this family, a classical sampler reproduces the quantum component exactly, so every robustness property of the hybrid model is shared by a classical model. Building on this result, we introduce QShield, an analysis-guided evaluation that derives adaptive attacks and matched classical controls from the exact analysis. On QShield-Net, a hybrid ResNet-18 inside the family, a lower attack success rate than an identically initialized CNN in 94 of 96 standard comparisons shrinks to a gain of 2.7 to 7.2 percentage points under 30 adaptive attacks. As predicted, this gain does not depend on the circuit: a CNN trained with the same Gaussian input noise is equally robust. Outside the family, a trainable re-uploading quantum head shows no gradient masking, yet training drives its contribution to near zero. These results establish when a quantum circuit can contribute to adversarial robustness.

⚠️ In the code, the hybrid model is called QNN (qnn_model, qnn_toolkit.py). QNN and QShield-Net refer to the same model.

🔍 The QShield Framework

A QShield audit compares a hybrid model with a matched classical reference that has the same backbone, initialization, and training procedure. It combines six components:

Component Question
Benchmark evaluation Does the hybrid model appear more robust under library-default attacks?
Exact analysis What does the quantum component compute: classical statistics, input dependence, randomness, gradient path, class bias?
Adaptive evaluation Does the advantage survive attacks that meet the requirements derived from the analysis?
Attribution Which component produces the surviving gain? (inference-time ablations and classical controls retrained over several seeds)
Calibration How large is the gain relative to an established defense, across budgets?
Redesign Do the design implications hold when acted on? (pre-specified experiments)

The implementation of the audit, and instructions for reproducing every result of the paper, are in supplementary_material/.

💡 QShield-Net: Key Features

  • Modular Hybrid Architecture: A ResNet-18 backbone whose class logits feed a compact quantum circuit through a forward hook, so the branch can be attached to any classifier.
  • Configurable Quantum Branch: Enhanced RX/RY/RZ angle encoding through a random orthogonal projection, with selectable entanglement topology (none, linear, star, or full) and circuit depth.
  • Noise Modeling: Simulation of quantum noise channels (depolarizing, amplitude damping, phase damping, and a mixture of the three), with optional Gaussian input-noise injection.
  • Adaptive Hybrid Fusion: An MLP computes a per-input fusion weight that combines the classical and quantum class distributions in amplitude space.
  • Benchmark Evaluation: Eight adversarial attacks (FGSM, PGD, APGD, VMI-FGSM, C&W, DeepFool, One-Pixel, and Square) on MNIST, OrganAMNIST, and CIFAR-10, with DNN and CNN baselines.
  • Device-Aware Training: Automatic CUDA/CPU device placement for training and evaluation.
  • Jupyter Notebook Integration: Ready-to-run training and evaluation pipelines with logging, dataset selection, and attack configuration.

🏗️ Architecture & Components

Fully connected DNN architectures for MNIST, OrganAMNIST, and CIFAR-10 datasets
Figure 1. Fully connected DNN baselines for MNIST, OrganAMNIST, and CIFAR-10


CNN architectures based on the ResNet-18 backbone for MNIST, OrganAMNIST, and CIFAR-10 datasets
Figure 2. CNN baselines based on the ResNet-18 backbone for MNIST, OrganAMNIST, and CIFAR-10


Schematic overview of the QShield-Net architecture
Figure 3. Schematic overview of the QShield-Net architecture

⚛️ Quantum Circuits

No entanglement quantum circuit
Figure 4. Quantum circuit without entanglement


Linear entanglement quantum circuit
Figure 5. Quantum circuit with linear entanglement


Star entanglement quantum circuit
Figure 6. Quantum circuit with star entanglement


Full entanglement quantum circuit
Figure 7. Quantum circuit with full entanglement

🛢️ Datasets

QShield-Net is evaluated on widely used benchmark datasets for general-purpose and medical image classification:

  • 📝 MNIST Handwritten digit classification dataset containing 70,000 grayscale images (28×28) across 10 classes (digits 0–9).

  • 🖼️ CIFAR-10 Natural image dataset with 60,000 color images (32×32) across 10 object classes (airplane, car, cat, dog, etc.).

  • 🫀 OrganAMNIST A medical imaging benchmark derived from abdominal CT scans, containing 11 organ classes.

All datasets can also be accessed directly through the following Hugging Face repository:

🔗 QShield Datasets on Hugging Face

🧠 Models

The trained DNN, CNN, and QShield-Net models evaluated in the paper (the "original models") are available on Hugging Face:

🔗 QShield Models on Hugging Face

⚙️ Installation & Setup (Benchmark Evaluation)

1. Environment Setup

#🔹Create a virtual environment (recommended)
python -m venv qshield

#🔹Activate the environment

# On Linux/macOS:
source qshield/bin/activate

# On Windows:
qshield\Scripts\activate

# If using Conda:
conda activate qshield
# Install dependencies
pip install -r requirements.txt
# Download datasets
python datasets.py

# (OR) Download datasets + trained models from Hugging Face
python hf.py

2. Parameters Configuration

This section lists the key options and parameters you can configure in the notebook before training and evaluation.

Device Selection
global device
device = 'cuda' if torch.cuda.is_available() else 'cpu'
Model & Dataset Settings
# Choose the quantum circuit pattern:
# Options: no_entanglement_ansatz, linear_entanglement_ansatz, full_entanglement_ansatz, star_entanglement_ansatz
global entanglement_type
entanglement_type = 'no_entanglement_ansatz'

# Choose the dataset:
# Options: MNIST, CIFAR10, OrganAMNIST
global dataset_name
dataset_name = 'OrganAMNIST'

# Choose the base neural network:
# Options: CNN-MNIST, DNN-MNIST, CNN-CIFAR10, DNN-CIFAR10, CNN-OrganAMNIST, DNN-OrganAMNIST
global NN_name
NN_name = 'DNN-OrganAMNIST'
Adversarial Attack Settings
# Adversarial attack method:
# Options: fgsm_attack, pgd_attack, apgd_attack, vnifgsm_attack, vmifgsm_attack,
#          sinifgsm_attack, cw_attack, deepfool_attack, onepixel_attack, square_attack
global adversarial_attack_name
adversarial_attack_name = 'fgsm_attack'
Training Parameters
# Number of training epochs
global num_epochs
num_epochs = 10

# Number of classes:
# 10 → MNIST / CIFAR10
# 11 → OrganAMNIST
global NUM_CLASSES
NUM_CLASSES = 11
QShield-Net (QNN) Settings
# Enable / disable QShield-Net model construction
global construct_qnn_model
construct_qnn_model = True

# QShield-Net configuration
qnn_settings = {
    "output_dim": NUM_CLASSES,                       # Number of output classes
    "circuit_depth": 1,                              # Depth of the quantum circuit
    "noise_strength": 0.005,                         # Quantum noise strength (0.0 – 1.0)
    "input_noise_injection": False,                  # Gaussian input noise (sigma = 0.01); the original models use True
    "entanglement_type": 'no_entanglement_ansatz',   # Entanglement topology of the circuit
    "use_dynamic_weights": True,                     # Input-dependent weighting for the hybrid fusion
    "encoding_method": 'enhanced_angle',             # Data encoding method: 'angle' or 'enhanced_angle'
    "noise_model": 'mixed'                           # Noise model: 'depolarizing', 'amplitude_damping',
                                                     #              'phase_damping', or 'mixed'
}

ℹ️ The original models of the paper were trained with input_noise_injection = True. Set it to True to reproduce them.

Target Model, Optimizer & Loss
# Select the target model:
# Options: dnn_model, cnn_model, qnn_model
global target_model
target_model = dnn_model

# Optimizer
optimizer = optim.Adam(target_model.parameters())

# Loss function
loss_fn = nn.NLLLoss()

🔬 Reproducing the Paper's Results

The benchmark evaluation (attack success rates, clean accuracies, and runtimes) is produced by the notebooks in this repository. Its values are collected in docs/Results.ipynb.

All other results of the paper are produced by the audit in supplementary_material/:

Folder Content
theory_checks/ Numerical checks of the exact analysis
adaptive_evaluation/ Verification and adaptive evaluation of the original models, and the inference-time attribution
retraining_experiments/ Retrained models and classical controls, adversarial training and budget sweep, convergence attacks, and the two redesign experiments, with their pre-specified analysis plans
manuscript_figure_data/ The data plotted in the paper's figures

Every analysis can be recomputed from the stored results with numpy and scipy alone, without a GPU:

cd supplementary_material/theory_checks
python verify_quantum_branch.py
python verify_extended_theory.py
cd ../adaptive_evaluation
python paired_analysis.py
python attack_suite_analysis.py
cd ../retraining_experiments
python -m analysis.make_report --plan extended

See supplementary_material/README.md for the full list of analyses, the mapping from each result of the paper to its script and stored output, and instructions for re-running the experiments.

🌐 Flask Web Application

# Download all required datasets
python datasets.py
# Launch the Flask web application
python app.py
# (Optional) Generate additional clean sample images
#    → Edit N_PER_CLASS in images.py, then run:
python images.py
# (Optional) Generate adversarial examples
#    → Open images_adversarial.py and set:
#       ADVERSARIAL_ATTACK_NAME = 'onepixel_attack'   # Options: fgsm_attack, pgd_attack, apgd_attack, vmifgsm_attack,
#                                                     #          cw_attack, deepfool_attack, onepixel_attack, square_attack
#       MODEL_TYPE = 'dnn'                            # Options: cnn, dnn, qnn
#       N_PER_CLASS = 3                               # Images per class to save
#    → Then run:
python images_adversarial.py

You can select different trained QShield-Net models by editing the .pt file paths in the LOAD ALL MODELS section of app.py:

# ==========================================================================================
# LOAD ALL MODELS
# ==========================================================================================

models_dict = {
    'mnist': {
        'cnn': load_model('clean_models/clean_model-MNIST-cnn_model.pt', CNN_Grayscale, num_classes=10),
        'dnn': load_model('clean_models/clean_model-MNIST-dnn_model.pt', DNN_Grayscale, num_classes=10),
        'qnn': load_qnn_model('clean_models/clean_model-MNIST-qnn_model-full_entanglement_ansatz.pt')
    },
    'organmnist': {
        'cnn': load_model('clean_models/clean_model-OrganAMNIST-cnn_model.pt', CNN_Grayscale, num_classes=11),
        'dnn': load_model('clean_models/clean_model-OrganAMNIST-dnn_model.pt', DNN_Grayscale, num_classes=11),
        'qnn': load_qnn_model('clean_models/clean_model-OrganAMNIST-qnn_model-full_entanglement_ansatz.pt')
    },
    'cifar10': {
        'cnn': load_model('clean_models/clean_model-CIFAR10-cnn_model.pt', CNN_CIFAR10, num_classes=10),
        'dnn': load_model('clean_models/clean_model-CIFAR10-dnn_model.pt', DNN_CIFAR10, num_classes=10),
        'qnn': load_qnn_model('clean_models/clean_model-CIFAR10-qnn_model-full_entanglement_ansatz.pt')
    }
}

🗂️ Code Structure

📁 QShield/
├── 🧠 clean_models/                                             # Trained models (downloaded from Hugging Face)
│   └── clean_model-<dataset>-<model_type>.pt
│   └── ...
├── 🛢️ data/                                                     # Datasets
│   └── CIFAR10/
│   └── MNIST/
│   └── OrganAMNIST/
├── 📚 docs/                                                     # Documentation
│   └── Adversarial Attack Parameters.md
│   └── Dataset Visualization.ipynb
│   └── Results.ipynb                                            # Values of the benchmark evaluation
├── ➕ etc/                                                      # Integrated Jupyter Notebooks
│   └── Jupyter Notebook - Adversarial Attacks.ipynb
│   └── Jupyter Notebook - Model Training & Evaluation.ipynb
├── 🖼️ img/                                                      # Figures, diagrams, and images
│   └── _DNN.png
│   └── _CNN.png
│   └── _QShield.png
│   └── ...
├── 🔬 supplementary_material/                                   # The QShield audit: code, plans, and results of the paper
│   └── README.md
│   └── theory_checks/
│   └── adaptive_evaluation/
│   └── retraining_experiments/
│   └── manuscript_figure_data/
├── 📃 templates/                                                # HTML structure for the web app
│   └── index.html
├── 🌐 app.py                                                    # Flask web app for image classification using preloaded models
├── 🗃️ datasets.py                                               # Download datasets into local ./data folders
├── ⬇️ hf.py                                                     # Download datasets and trained models from Hugging Face
├── 🌄 images.py                                                 # Save sample images from datasets into class-specific folders
├── 🌄 images_adversarial.py                                     # Generate adversarial examples, saving original and perturbed images per class
├── 📓 Jupyter Notebook.ipynb                                    # Primary Jupyter Notebook
├── 📄 LICENSE                                                   # License
├── 🌀 noise_transforms.py                                       # Optional noise transforms
├── ⚛️ qnn_toolkit.py                                            # QShield-Net (QNN) implementation
├── 📖 README.md                                                 # Primary documentation
└── 📦 requirements.txt                                          # Project dependencies

📦 Libraries & Dependencies

Package Purpose
🔥 torch Core deep learning framework (GPU-enabled, PyTorch 2.5.1 + CUDA 12.1)
🖼️ torchvision Computer vision utilities, datasets, and transforms
📊 matplotlib Visualization and plotting of results
📦 medmnist Access to MedMNIST benchmark medical image datasets
🔢 numpy Fundamental numerical computing library
📐 scipy Scientific computing and statistics
🖌 pillow Image processing (loading, saving, and transforming images)
🎯 scikit-learn Machine learning utilities for metrics, preprocessing, and models
⏳ tqdm Progress bars for loops and training
🖥 psutil System and resource monitoring (CPU/GPU/memory usage)
🛡️ torchattacks PyTorch-based adversarial attack implementations
🛡️ adversarial-robustness-toolbox Adversarial attacks and defenses (ART)
⚛️ pennylane Quantum machine learning and hybrid quantum–classical circuits
📋 tabulate Pretty-print tabular results
⚙️ pip / setuptools / wheel Python packaging and dependency management
🌐 Flask Lightweight web framework for building APIs and web apps
🤗 huggingface_hub Download and manage models and datasets from Hugging Face

The audit in supplementary_material/ lists its own pinned requirements in supplementary_material/requirements.txt.

📑 Citation

The paper associated with this work is available at the links below:

Google Scholar arXiv

If this repository or the paper has contributed to your research, please acknowledge our work by citing it:

Google Scholar

@article{azimi2026qshield,
  title={QShield: Securing Neural Networks Against Adversarial Attacks using Quantum Circuits},
  author={Azimi, Navid and Prakash, Aditya and Wang, Yao and Xiong, Li},
  journal={arXiv preprint arXiv:2604.10933},
  year={2026}
}

📜 License

This software is licensed under the GNU General Public License v3.0 (GPLv3). You are free to use, modify, and distribute this software for both personal and commercial purposes, as long as you comply with the terms of the GPLv3 license. This includes preserving the license notice and making the source code of any derivative works available under the same license.