An open API service indexing awesome lists of open source software.

https://github.com/yucelz/q-store-examples

A database architecture that leverages quantum mechanical properties—superposition, entanglement, decoherence, and tunneling—as **core features** for exponential performance advantages in vector similarity search, relationship management, and pattern discovery.
https://github.com/yucelz/q-store-examples

q-store quantum-computing quatum-database

Last synced: about 1 month ago
JSON representation

A database architecture that leverages quantum mechanical properties—superposition, entanglement, decoherence, and tunneling—as **core features** for exponential performance advantages in vector similarity search, relationship management, and pattern discovery.

Awesome Lists containing this project

README

          

# Q-Store Examples

Standalone example projects demonstrating Q-Store 3.4.3 quantum database capabilities for ML training, financial applications, and more.

**Note**: This is a standalone examples repository. Q-Store 3.4.3 is installed via pip or from a local wheel file.

📖 **For detailed setup instructions and troubleshooting, see [SETUP.md](SETUP.md)**

## 🚀 Quick Start

### Prerequisites

- Python 3.8 or higher
- pip or conda package manager
- API keys (see [API Keys](#api-keys) section)

### Installation

#### Option 1: Editable Install (Recommended for Development)

```bash
# 1. Clone this repository
git clone https://github.com/yucelz/q-store-examples.git
cd q-store-examples

# 2. Install package in editable mode (changes are immediately reflected)
pip install -e .

# Or with optional ML dependencies
pip install -e ".[ml,data,dev]"

# 3. Set up environment variables
cp .env.example .env
# Edit .env and add your API keys

# 4. Verify installation
python scripts/verify_installation.py
```

#### Option 2: Using requirements.txt

```bash
# 1. Clone this repository
git clone https://github.com/yucelz/q-store-examples.git
cd q-store-examples

# 2. Install Q-Store 3.4.3 and dependencies
pip install -r requirements.txt

# 3. Install the package (required for imports to work)
pip install -e .

# 4. Set up environment variables
cp .env.example .env
# Edit .env and add your API keys

# 5. Verify installation
python scripts/verify_installation.py
```

#### Option 3: Using conda

```bash
# 1. Clone this repository
git clone https://github.com/yucelz/q-store-examples.git
cd q-store-examples

# 2. Create conda environment
conda create -n q-store-examples python=3.11
conda activate q-store-examples

# 3. Install the package
pip install -e .

# 4. Set up environment variables
cp .env.example .env
# Edit .env and add your API keys

# 5. Verify installation
python scripts/verify_installation.py
```

#### Option 4: Using Local Wheel File

If you have the Q-Store wheel file:

```bash
# 1. Clone this repository
git clone https://github.com/yucelz/q-store-examples.git
cd q-store-examples

# 2. Copy the wheel file to this directory
cp /path/to/q_store-3.4.3-cp313-cp313-manylinux_2_17_x86_64.whl .

# 3. Install using make
make install-wheel

# Or install manually:
# pip install q_store-3.4.3-cp313-cp313-manylinux_2_17_x86_64.whl
# pip install -r requirements.txt --no-deps

# 4. Set up environment variables
cp .env.example .env
# Edit .env and add your API keys

# 5. Verify installation
python scripts/verify_installation.py
```

#### Option 4: Using Local Wheel File

If you have the Q-Store wheel file:

```bash
# 1. Clone this repository
git clone https://github.com/yucelz/q-store-examples.git
cd q-store-examples

# 2. Copy the wheel file to this directory
cp /path/to/q_store-3.4.3-cp313-cp313-manylinux_2_17_x86_64.whl .

# 3. Install using make
make install-wheel

# Or install manually:
# pip install q_store-3.4.3-cp313-cp313-manylinux_2_17_x86_64.whl
# pip install -e .

# 4. Set up environment variables
cp .env.example .env
# Edit .env and add your API keys

# 5. Verify installation
python scripts/verify_installation.py
```

#### Option 5: Minimal Installation (No ML Dependencies)

```bash
# Clone and navigate to repository
git clone https://github.com/yucelz/q-store-examples.git
cd q-store-examples

# Install only core dependencies (includes q-store==3.4.3)
pip install -r requirements-minimal.txt

# This allows running:
# - basic_example.py
# - financial_example.py
# - quantum_db_quickstart.py
```

## 🔑 API Keys

### Required

- **Pinecone API Key**: Required for all examples
- Get it from: https://www.pinecone.io/
- Free tier available (100K vectors)

### Optional

- **IonQ API Key**: Optional, enables quantum simulation features
- Get it from: https://ionq.com/
- Free credits available for new users

- **Hugging Face Token**: Optional, only for gated models
- Get it from: https://huggingface.co/settings/tokens

### Configuration

```bash
# Copy the example file
cp .env.example .env

# Edit with your favorite editor
nano .env # or vim, code, etc.

# Add your keys:
PINECONE_API_KEY=your_actual_key_here
PINECONE_ENVIRONMENT=us-east-1
IONQ_API_KEY=your_ionq_key_here # Optional

# Verify configuration
python show_config.py
```

The `show_config.py` script will display your current configuration and guide you on next steps.

## 📚 Available Examples

### 1. Basic Example (`basic_example.py`)

Demonstrates core Q-Store functionality:
- Inserting vectors with quantum contexts
- Querying with superposition
- Creating entangled groups
- Quantum tunneling for exploration

```bash
python basic_example.py
```

### 2. Financial Example (`financial_example.py`)

Financial data analysis with quantum features:
- Portfolio optimization
- Risk correlation analysis
- Market regime detection
- Anomaly detection

```bash
python financial_example.py
```

### 3. Quantum Database Quickstart (`quantum_db_quickstart.py`)

Comprehensive tutorial covering:
- Database initialization
- All query modes (PRECISE, BALANCED, EXPLORATORY)
- Advanced quantum features
- Performance optimization

```bash
python quantum_db_quickstart.py
```

### 4. V3.2 ML Training Examples (`src/q_store_examples/examples_v3_2.py`)

Complete quantum ML training demonstrations:
- Basic quantum neural network training
- Quantum data encoding strategies
- Transfer learning with quantum models
- Multiple backend comparison
- Database-ML integration
- Quantum autoencoder

```bash
# Run with mock backends (no API keys needed)
python src/q_store_examples/examples_v3_2.py

# Run with real Pinecone and IonQ backends
# Option 1: Using .env file (recommended)
# Make sure your .env file has PINECONE_API_KEY and IONQ_API_KEY set
python src/q_store_examples/examples_v3_2.py --no-mock

# Option 2: Using environment variables
export PINECONE_API_KEY="your-pinecone-key"
export IONQ_API_KEY="your-ionq-key"
export PINECONE_ENVIRONMENT="us-east-1"
export IONQ_TARGET="simulator"

python src/q_store_examples/examples_v3_2.py --no-mock

# Option 3: Using command-line arguments (overrides .env)
python src/q_store_examples/examples_v3_2.py --no-mock \
--pinecone-api-key YOUR_PINECONE_KEY \
--pinecone-env us-east-1 \
--ionq-api-key YOUR_IONQ_KEY \
--ionq-target simulator

# Available IonQ targets:
# - simulator (free, default)
# - ionq_simulator
# - qpu.aria-1 (requires credits)
# - qpu.forte-1 (requires credits)
```

**Priority Order:** Command-line args → Environment variables → .env file → Defaults

### 5. V3.3 High-Performance ML Training Examples (`src/q_store_examples/examples_v3_3.py`)

**NEW** - 24-48x faster training with algorithmic optimization:
- SPSA gradient estimation (2 circuits instead of 96)
- Hardware-efficient quantum layers (33% fewer parameters)
- Adaptive gradient optimization
- Circuit caching and batching
- Performance tracking and comparison
- Real-time speedup analysis

```bash
# With mock backends (default - for testing)
python src/q_store_examples/examples_v3_3.py

# With real IonQ/Pinecone backends
python src/q_store_examples/examples_v3_3.py --no-mock

# With specific credentials
python src/q_store_examples/examples_v3_3.py --no-mock \
--ionq-api-key YOUR_KEY \
--pinecone-api-key YOUR_KEY

# See all options
python src/q_store_examples/examples_v3_3.py --help
```

**Performance Improvements:**
- 🚀 **48x fewer circuits** with SPSA (2 vs 96 per batch)
- ⚡ **33% fewer parameters** with hardware-efficient ansatz
- 💾 **Circuit caching** eliminates redundant compilations
- 🔄 **Batch execution** enables parallel quantum jobs
- 📊 **Performance tracking** shows real-time speedup metrics

**Priority Order:** Command-line args → Environment variables → .env file → Defaults

### 6. V3.4 Performance-Optimized ML Training Examples (`src/q_store_examples/examples_v3_4.py`)

**LATEST** - 8-10x faster than v3.3.1 through true parallelization:
- **IonQBatchClient**: Single API call for all circuits (12x faster submission)
- **IonQNativeGateCompiler**: GPi/GPi2/MS native gates (30% faster execution)
- **SmartCircuitCache**: Template-based caching (10x faster preparation)
- **CircuitBatchManagerV34**: Orchestrates all optimizations together
- Production training workflow with full v3.4 features
- Configuration guide and performance evolution analysis

```bash
# ============================================================================
# BASIC USAGE
# ============================================================================

# 1. Mock mode (default - safe testing, no API calls needed)
python src/q_store_examples/examples_v3_4.py

# 2. Real IonQ/Pinecone backends (uses .env file)
python src/q_store_examples/examples_v3_4.py --no-mock

# ============================================================================
# CONFIGURATION OPTIONS
# ============================================================================

# Option 1: Using .env file (RECOMMENDED)
# Make sure your .env file has:
# PINECONE_API_KEY=your-pinecone-key
# IONQ_API_KEY=your-ionq-key
# PINECONE_ENVIRONMENT=us-east-1
# IONQ_TARGET=simulator

python src/q_store_examples/examples_v3_4.py --no-mock

# Option 2: Using environment variables
export PINECONE_API_KEY="your-pinecone-key"
export IONQ_API_KEY="your-ionq-key"
export PINECONE_ENVIRONMENT="us-east-1"
export IONQ_TARGET="simulator"

python src/q_store_examples/examples_v3_4.py --no-mock

# Option 3: Using command-line arguments (overrides .env and env vars)
python src/q_store_examples/examples_v3_4.py --no-mock \
--pinecone-api-key YOUR_PINECONE_KEY \
--pinecone-env us-east-1 \
--ionq-api-key YOUR_IONQ_KEY \
--ionq-target simulator

# ============================================================================
# IONQ TARGET OPTIONS
# ============================================================================

# Simulator (free, default)
python src/q_store_examples/examples_v3_4.py --no-mock --ionq-target simulator

# IonQ Harmony QPU (requires credits)
python src/q_store_examples/examples_v3_4.py --no-mock --ionq-target qpu.harmony

# IonQ Aria QPU (requires credits)
python src/q_store_examples/examples_v3_4.py --no-mock --ionq-target qpu.aria-1

# ============================================================================
# ADVANCED USAGE
# ============================================================================

# Show all available options
python src/q_store_examples/examples_v3_4.py --help

# Full example with all parameters
python src/q_store_examples/examples_v3_4.py \
--no-mock \
--pinecone-api-key pk-xxxxx \
--pinecone-env us-east-1 \
--ionq-api-key xxxxxxxx \
--ionq-target simulator
```

**What Each Example Demonstrates:**

| Example | Focus | Key Feature |
|---------|-------|-------------|
| **Example 1** | IonQBatchClient | True batch submission (1 API call vs 20) |
| **Example 2** | IonQNativeGateCompiler | Native gate compilation (GPi/GPi2/MS) |
| **Example 3** | SmartCircuitCache | Template-based circuit caching |
| **Example 4** | CircuitBatchManagerV34 | All optimizations integrated |
| **Example 5** | Production Training | Complete training workflow with v3.4 |
| **Example 6** | Configuration Guide | 4 config scenarios for different use cases |
| **Example 7** | Performance Evolution | v3.2 → v3.3 → v3.3.1 → v3.4 comparison |

**Performance Targets:**
- 📊 **Batch time**: 35s (v3.3.1) → 4s (v3.4) = **8.75x faster**
- ⚡ **Circuits/sec**: 0.57 (v3.3.1) → 5.0 (v3.4) = **8.8x throughput**
- 🚀 **Training time**: 29.6 min (v3.3.1) → 3.75 min (v3.4) = **7.9x faster**

**Key Innovations:**
```
Batch API: 20 circuits → 1 API call = 12x faster submission
Native Gates: GPi/GPi2/MS gates = 30% faster execution
Smart Cache: Template reuse = 10x faster preparation
─────────────────────────────────────────────────────────────────────
Combined: All optimizations together = 8-10x overall speedup
```

**Migration from v3.3.1:**
```python
# Just add one line to your existing config:
config = TrainingConfig(
# ... all your existing v3.3.1 settings ...
enable_all_v34_features=True # 🔥 Enable v3.4 optimizations
)
# That's it! Fully backward compatible.
```

**Priority Order:** Command-line args → Environment variables → .env file → Defaults

### 7. ML Training Example (`ml_training_example.py`)

Machine learning integration:
- Model embedding storage
- Training data selection
- Curriculum learning
- Hard negative mining

```bash
python ml_training_example.py
```

### 8. Connection Tests

Verify Pinecone and IonQ connections:

```bash
# Option 1: Using .env file (recommended)
# Ensure your .env has PINECONE_API_KEY and IONQ_API_KEY set
python test_pinecone_ionq_connection.py
python test_cirq_adapter_fix.py

# Option 2: Set environment variables explicitly
export PINECONE_API_KEY="your-key"
export IONQ_API_KEY="your-key"

python test_pinecone_ionq_connection.py
python test_cirq_adapter_fix.py
```

These tests will:
- ✅ Initialize Pinecone client and create test indexes
- ✅ Configure IonQ backend (simulator and QPU)
- ✅ Execute quantum circuits on IonQ
- ✅ Run small training session with real backends
- ✅ Verify Pinecone index creation during training

### 9. TinyLlama React Training (`tinyllama_react_training.py`)

Complete LLM fine-tuning workflow:
- React code dataset generation
- Quantum-enhanced data sampling
- LoRA fine-tuning
- Curriculum learning

```bash
# Option 1: Automated workflow
./run_react_training.sh

# Option 2: Step-by-step
python react_dataset_generator.py
python tinyllama_react_training.py

# See REACT_QUICK_REFERENCE.md for details
```

## 📖 Documentation

| Document | Description |
|----------|-------------|
| **REACT_QUICK_REFERENCE.md** | Quick start for React training |
| **REACT_TRAINING_WORKFLOW.md** | Detailed React training guide |
| **TINYLLAMA_TRAINING_README.md** | TinyLlama fine-tuning guide |
| **IMPROVEMENTS_SUMMARY.md** | Code improvements and comparisons |

## 🔧 Configuration

### Environment Variables

All configuration is done through `.env` file:

```bash
# Required
PINECONE_API_KEY=your_key
PINECONE_ENVIRONMENT=us-east-1

# Optional
IONQ_API_KEY=your_ionq_key
IONQ_TARGET=simulator

# ML Training (optional)
HUGGING_FACE_TOKEN=your_token
OUTPUT_DIR=./models
```

### Custom Settings

Edit configuration in each example file:

```python
# Example: tinyllama_react_training.py
config = TrainingConfig(
max_samples=1000,
num_train_epochs=3,
use_quantum_sampling=True,
use_curriculum_learning=True
)
```

## 🧪 Testing

### Verify Installation

```bash
# Test Q-Store installation
python verify_installation.py

# Check your configuration (.env file)
python show_config.py

# Test React integration
python verify_react_integration.py

# Test TinyLlama setup
python verify_tinyllama_example.py

# Verify v3.2 components
cd ..
python verify_v3_2.py
cd examples
```

### Test Quantum Backends

```bash
# Quick Cirq adapter test
python test_cirq_adapter_fix.py

# Comprehensive Pinecone + IonQ test
python test_pinecone_ionq_connection.py
```

### Run Unit Tests

```bash
# Install dev dependencies
pip install pytest pytest-cov black isort flake8 mypy

# Run tests
pytest

# With coverage
pytest --cov=. --cov-report=html
```

## 💡 Usage Tips

### GPU Support

For CUDA GPU support:

```bash
# Install PyTorch with CUDA
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

# Verify GPU availability
python -c "import torch; print('GPU Available:', torch.cuda.is_available())"
```

### Memory Management

For large datasets or limited RAM:

```python
# Reduce batch size
config = TrainingConfig(
per_device_train_batch_size=1, # Smaller batches
gradient_accumulation_steps=16, # Accumulate gradients
max_samples=500 # Limit dataset size
)
```

### Development Mode

For development with the latest Q-Store:

```bash
# If you have Q-Store source code, install in editable mode
cd /path/to/q-store
pip install -e .

# Or use the latest from PyPI
pip install --upgrade q-store

# Now run examples with the updated version
```

## 🐛 Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| `ModuleNotFoundError: q_store` | Install Q-Store: `pip install q-store==3.4.3` |
| `PINECONE_API_KEY not found` | Create `.env` file with your API key |
| `ImportError: transformers` | Install ML dependencies: `pip install -r requirements.txt` |
| `CUDA out of memory` | Reduce batch size or use CPU |
| `Dataset file not found` | Run dataset generator first |
| `'list' object has no attribute 'measurements'` | Fixed in latest version - Cirq adapter updated |
| `Pinecone index not created` | Ensure API key is valid, check `--no-mock` flag |

### Debug Mode

Enable verbose logging:

```bash
# Set environment variable
export LOG_LEVEL=DEBUG

# Or in .env file
echo "LOG_LEVEL=DEBUG" >> .env
```

### Getting Help

1. Check the documentation files in this directory
2. Review the parent [Q-Store README](../README.md)
3. Open an issue on GitHub
4. Review existing issues and discussions

## 🎯 Next Steps

1. **Run Basic Example**: Start with `basic_example.py`
2. **Try React Training**: Use the automated workflow
3. **Experiment**: Modify configs and try different strategies
4. **Build Your Own**: Use examples as templates
5. **Contribute**: Share improvements and new examples

## 📊 Performance Benchmarks

### Dataset Sizes

- **Minimal**: 500-1,000 samples (fast, for testing)
- **Medium**: 1,000-5,000 samples (balanced)
- **Large**: 5,000-10,000+ samples (best results)

### Training Times (approximate)

- **Dataset Generation**: 10-30 seconds
- **Database Loading**: 1-3 minutes
- **Quantum Sampling Demo**: 30 seconds
- **Full Training**: 30-90 minutes (with GPU)

## 🤝 Contributing

Contributions are welcome! To add new examples:

1. Follow the existing code structure
2. Add documentation
3. Include requirements
4. Test thoroughly
5. Submit a pull request

## 📄 License

MIT License - see parent repository for details

## 🔗 Related Resources

- [Q-Store Main Repository](https://github.com/yucelz/q-store)
- [Quantum Database Design](../quantum_db_design_v2.md)
- [Pinecone Documentation](https://docs.pinecone.io/)
- [IonQ Documentation](https://ionq.com/docs/)
- [Transformers Documentation](https://huggingface.co/docs/transformers/)

## 📞 Support

- GitHub Issues: [q-store/issues](https://github.com/yucelz/q-store/issues)
- Documentation: [examples/](https://github.com/yucelz/q-store/tree/main/examples)

---

**Ready to start?** Check your configuration:

```bash
python show_config.py
```

If all checks pass, you're ready to explore quantum-enhanced machine learning! 🚀

**Quick Start:**
```bash
# V3.2 - Standard quantum ML training
# With mock backends (safe, no API calls)
python src/q_store_examples/examples_v3_2.py

# With real Pinecone + IonQ (uses your .env configuration)
python src/q_store_examples/examples_v3_2.py --no-mock

# V3.3 - High-performance quantum ML training (24-48x faster!)
# With mock backends (safe, no API calls)
python src/q_store_examples/examples_v3_3.py

# With real Pinecone + IonQ (uses your .env configuration)
python src/q_store_examples/examples_v3_3.py --no-mock

# V3.3.1 - Corrected batch gradient training (True SPSA parallelization)
# With mock backends (safe, no API calls)
python src/q_store_examples/examples_v3_3_1.py

# With real Pinecone + IonQ (uses your .env configuration)
python src/q_store_examples/examples_v3_3_1.py --no-mock

# V3.4 - Performance optimized (8-10x faster than v3.3.1!) ⚡ RECOMMENDED
# With mock backends (safe, no API calls)
python src/q_store_examples/examples_v3_4.py

# With real Pinecone + IonQ (uses your .env configuration)
python src/q_store_examples/examples_v3_4.py --no-mock

# With specific API keys (overrides .env)
python src/q_store_examples/examples_v3_4.py --no-mock \
--pinecone-api-key YOUR_PINECONE_KEY \
--ionq-api-key YOUR_IONQ_KEY

# ============================================================================
# PERFORMANCE COMPARISON
# ============================================================================
# v3.2: Parameter Shift (960 circuits/batch) - Baseline
# v3.3: SPSA (20 circuits/batch) - 48x fewer circuits
# v3.3.1: Parallel SPSA (20 circuits/batch, parallel) - Correct implementation
# v3.4: Batch API + Native Gates + Caching - 8-10x faster than v3.3.1!
#
# Recommended: Start with v3.4 for best performance! 🚀
# ============================================================================
```
**docs/sphinx**

```bash
# Install documentation dependencies
pip install sphinx sphinx-rtd-theme
cd docs/sphinx
sphinx-build -b html . _build/html
```