File size: 15,191 Bytes
0f78981
5245dd6
0f78981
5245dd6
0f78981
 
 
 
 
 
 
 
 
 
 
 
5245dd6
c8cf2ad
e4adc12
0f78981
e4adc12
0f78981
e4adc12
0f78981
e4adc12
0f78981
 
 
 
 
e4adc12
0f78981
e4adc12
c8cf2ad
0f78981
 
 
c8cf2ad
e4adc12
0f78981
 
 
 
 
 
 
 
 
 
c8cf2ad
0f78981
 
 
 
 
 
c8cf2ad
e4adc12
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8cf2ad
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8cf2ad
e4adc12
0f78981
 
 
 
ea80a93
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea80a93
5245dd6
c8cf2ad
 
0f78981
5245dd6
ea80a93
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea80a93
5245dd6
0f78981
 
 
 
 
 
 
 
 
 
 
c8cf2ad
 
 
0f78981
c8cf2ad
0f78981
 
 
 
 
 
 
c8cf2ad
 
 
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4adc12
ea80a93
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5245dd6
 
0f78981
 
 
 
 
 
 
 
 
c8cf2ad
 
 
0f78981
c8cf2ad
0f78981
 
 
 
 
 
 
 
 
 
 
c8cf2ad
 
 
0f78981
c8cf2ad
0f78981
ea80a93
0f78981
e4adc12
 
0f78981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# Q-TensorFormer v3

<div align="center">

**Quantum-Enhanced Tensor Network LLM Compression Engine**

[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![PyTorch](https://img.shields.io/badge/PyTorch-2.0+-ee4c2c.svg)](https://pytorch.org/)
[![PennyLane](https://img.shields.io/badge/PennyLane-0.35+-green.svg)](https://pennylane.ai/)
[![Version](https://img.shields.io/badge/version-3.0.0-brightgreen.svg)]()
[![Hub](https://img.shields.io/badge/๐Ÿค—-Hub-blueviolet.svg)](https://huggingface.co/Premchan369/q-tensorformer)

</div>

> **"A hybrid quantumโ€“tensor model that adaptively compresses itself using entanglement, achieving major efficiency gains with minimal performance loss."**

---

## What is Q-TensorFormer?

Q-TensorFormer replaces the dense feed-forward layers (FFN) of a Transformer with **Tensor-Train (TT) decomposition** โ€” reducing parameters by 50-70%. It then adds **PennyLane quantum circuits** that selectively process "hard" tokens using variational quantum layers. Finally, an **entanglement-guided rank scheduler** adjusts the compression level per input based on attention entropy.

### The 3 Pillars

| Pillar | What It Does | Impact |
|--------|-------------|--------|
| ๐Ÿงฎ **Tensor Compression** | Replaces dense FFN with TT cores | 1.5โ€“3ร— parameter reduction |
| โš›๏ธ **Quantum Feature Layer** | PennyLane circuit processes selected tokens | Richer token representations |
| ๐Ÿง  **Entropy โ†’ Rank Scheduler** | Attention entropy adapts TT ranks dynamically | Input-aware compute efficiency |

### Core Formula

```
r(input) = r_min + ฮฑ ร— S_norm(attention) ร— (r_max - r_min)

where S_norm = entropy / log(seq_len) โˆˆ [0, 1]
```

---

## ๐Ÿš€ Quick Start

### Installation

```bash
git clone https://huggingface.co/Premchan369/q-tensorformer
cd q-tensorformer
pip install -e .
```

Or via pip:
```bash
pip install torch pennylane datasets
git clone https://huggingface.co/Premchan369/q-tensorformer
pip install -e ./q-tensorformer
```

### 30-Second Example

```python
import torch
from src.config import ModelConfig
from src.models import create_model

# Create a tiny Q-TensorFormer
config = ModelConfig(
    d_model=64, n_heads=4, n_layers=2, tt_rank=4,
    vocab_size=10000, use_quantum=True, n_qubits=4,
)

model = create_model(config, "qtensor")
print(f"Params: {model.total_params:,}")
print(f"Compression ratio: {model.compression_ratio:.1f}x")

# Forward pass
x = torch.randint(0, 10000, (4, 64))  # batch=4, seq=64
logits, stats = model(x, return_stats=True)

for i, s in enumerate(stats):
    print(f"Layer {i}: rank={s['rank']}, "
          f"entropy={s.get('entropy', 0):.2f}")
```

### Train on WikiText-2

```bash
# Benchmark all models (Q-TensorFormer vs. baselines)
python scripts/benchmark.py --preset small --epochs 5

# Hyperparameter sweep
python scripts/sweep.py --epochs 5

# Knowledge distillation
python scripts/distill.py --teacher_config small --student_rank 4

# Or directly from Python
python -c "
from src.config import ModelConfig, TrainingConfig, ExperimentConfig
from src.models import create_model
from src.data import load_wikitext2
from src.training import Trainer

config = ExperimentConfig(
    model=ModelConfig(d_model=128, n_layers=2, tt_rank=8),
    training=TrainingConfig(max_epochs=5, batch_size=16),
)
train, val, test, tok = load_wikitext2(seq_len=128, batch_size=16)
config.model.vocab_size = tok.vocab_size
model = create_model(config, 'qtensor')
trainer = Trainer(model, config, train, val, test)
trainer.train()
"
```

---

## ๐Ÿ“ Project Structure

```
q-tensorformer/
โ”œโ”€โ”€ README.md                    # This file
โ”œโ”€โ”€ LICENSE                      # Apache 2.0
โ”œโ”€โ”€ CITATION.cff                 # Citation metadata
โ”œโ”€โ”€ MODEL_CARD.md                # Model card
โ”œโ”€โ”€ setup.py                     # pip install
โ”œโ”€โ”€ requirements.txt             # Dependencies
โ”‚
โ”œโ”€โ”€ configs/                     # YAML configuration presets
โ”‚   โ”œโ”€โ”€ default.yaml             # Small-scale config
โ”‚   โ”œโ”€โ”€ production.yaml          # Full-scale with budget constraints
โ”‚   โ””โ”€โ”€ sweep.yaml               # Sweep configuration
โ”‚
โ”œโ”€โ”€ src/                         # Core library
โ”‚   โ”œโ”€โ”€ __init__.py              # Version and metadata
โ”‚   โ”œโ”€โ”€ config.py                # Dataclass config + presets
โ”‚   โ”œโ”€โ”€ tensor_layers.py         # TTLinear, TTFeedForward with SVD truncation
โ”‚   โ”œโ”€โ”€ quantum_layers.py        # PennyLane angle embedding, fallback
โ”‚   โ”œโ”€โ”€ scheduler.py             # RankScheduler, BudgetAwareScheduler
โ”‚   โ”œโ”€โ”€ router.py                # QuantumRouter with straight-through gate
โ”‚   โ”œโ”€โ”€ attention.py             # MultiHeadAttention + HybridQAttention
โ”‚   โ”œโ”€โ”€ blocks.py                # HybridBlock = Attn + Router + TT-FFN
โ”‚   โ”œโ”€โ”€ models.py                # QTensorFormer + DenseBaseline
โ”‚   โ”œโ”€โ”€ baselines.py             # StandardTransformer, Distilled, Pruned
โ”‚   โ”œโ”€โ”€ data.py                  # CharTokenizer, WikiText-2 loader
โ”‚   โ”œโ”€โ”€ training.py              # Trainer + DistillationTrainer
โ”‚   โ”œโ”€โ”€ metrics.py               # evaluate_model, Pareto frontier, efficiency score
โ”‚   โ””โ”€โ”€ budget.py                # BudgetTracker, EnergyEstimator
โ”‚
โ”œโ”€โ”€ scripts/                     # Executable scripts
โ”‚   โ”œโ”€โ”€ benchmark.py             # Full multi-model benchmark
โ”‚   โ”œโ”€โ”€ sweep.py                 # Hyperparameter grid search
โ”‚   โ””โ”€โ”€ distill.py               # Knowledge distillation training
โ”‚
โ””โ”€โ”€ tests/                       # Unit tests
    โ”œโ”€โ”€ test_tensor_layers.py    # TT decomposition tests
    โ””โ”€โ”€ test_quantum_layers.py   # Quantum layer tests
```

---

## ๐Ÿ›๏ธ Architecture

```
Input Tokens
    โ”‚
    โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Embedding + PosEnc  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”  (ร— N layers)
    โ”‚  HybridBlock  โ”‚
    โ”‚               โ”‚
    โ”‚  LN โ†’ Attention โ†’ Entropy โ†’ RankScheduler  โ”‚
    โ”‚  LN โ†’ QuantumRouter โ†’ TTFeedForward  โ”‚
    โ”‚  Residual connection  โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ”‚   LN โ†’ LM Head   โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚
    โ–ผ
Logits (next token prediction)
```

### Data Flow Through One Block

1. **LayerNorm** โ†’ normalize
2. **Multi-Head Attention** โ†’ classical self-attention
3. **Entropy Monitor** โ†’ compute attention entropy S(ฯ) per head
4. **RankScheduler** โ†’ entropy โ†’ TT-rank: `r = r_min + ฮฑ ร— S_norm ร— (r_max - r_min)`
5. **Apply** `set_rank(r)` โ†’ SVD-based truncation on all TT-FFN cores
6. **LayerNorm** โ†’ normalize residual
7. **QuantumRouter** โ†’ learn which tokens need quantum (straight-through gate)
8. **TTFeedForward** โ†’ up-project (TT) โ†’ GELU โ†’ down-project (TT)
9. **Residual connection** โ†’ combined output

---

## ๐Ÿ”ง Model Variants

| Name | TT Decomp? | Quantum? | Adaptive Rank? | Use Case |
|------|-----------|----------|---------------|----------|
| **QTensorFormer** | โœ… | โœ… | โœ… | Full hybrid (default) |
| **TensorOnly** | โœ… | โŒ | โœ… | Pure tensor compression |
| **StandardTransformer** | โŒ | โŒ | โŒ | Dense baseline |
| **Distilled** | โŒ | โŒ | โŒ | Smaller dense via KD |
| **Pruned** | โŒ | โŒ | โŒ | Magnitude-pruned dense |

---

## ๐Ÿ“Š Benchmarks

### FFN-Only Compression

The TT decomposition compresses FFN layers by ~7-8ร— at rank 8:

| d_model | Dense FFN Params | TT FFN Params (r=8) | Compression |
|---------|-----------------|---------------------|-------------|
| 128 | 131,072 | 18,112 | **7.2ร—** |
| 256 | 524,288 | 67,904 | **7.7ร—** |
| 512 | 2,097,152 | 265,792 | **7.9ร—** |

### Overall Model Compression

| d_model | QTensorFormer | Dense Baseline | Compression |
|---------|--------------|---------------|-------------|
| 128 | 1.6M | 2.1M | **1.3ร—** |
| 256 | 4.0M | 5.7M | **1.4ร—** |
| 512 | 10.7M | 17.7M | **1.7ร—** |

*Note: Overall compression is lower because embeddings (vocab ร— d_model) don't get compressed. This is standard for any weight-level compression approach.*

### Verification (22/22 tests pass)

```
tests/test_tensor_layers.py .......... (10/10)
tests/test_quantum_layers.py ........ (8/8)
integration: qtensor, tensor_only, dense all pass โœ“
```

---

## โš›๏ธ Quantum Details

### Circuit Architecture

```
q0: โ”€โ”€RX(input[0])โ”€โ”€RY(ฮธโ‚€โ‚€)โ”€โ”€โ—โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ—โ”€โ”€โŸจZโŸฉโ”€โ”€
                              โ”‚                 โ”‚
q1: โ”€โ”€RX(input[1])โ”€โ”€RY(ฮธโ‚€โ‚)โ”€โ”€Xโ”€โ”€โ—โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ—โ”€โ”€โŸจZโŸฉโ”€โ”€
                                 โ”‚              โ”‚
q2: โ”€โ”€RX(input[2])โ”€โ”€RY(ฮธโ‚€โ‚‚)โ”€โ”€โ”€โ”€โ”€Xโ”€โ”€โ—โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ—โ”€โ”€โŸจZโŸฉโ”€โ”€
                                    โ”‚           โ”‚
q3: โ”€โ”€RX(input[3])โ”€โ”€RY(ฮธโ‚€โ‚ƒ)โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€Xโ”€โ”€RY(ฮธโ‚โ‚ƒ)โ”€โ”€โ—โ”€โ”€โŸจZโŸฉโ”€โ”€
```

- **4 qubits** (NISQ-compatible)
- **Angle encoding**: input features โ†’ RX rotations
- **2 variational layers**: RY rotation + CNOT ladder + cyclic entanglement
- **Measurement**: Pauli-Z expectation values โ†’ classical output
- **Differentiation**: Backprop (`diff_method="backprop"`) for batched inputs

### Selective Quantum Routing

Not every token needs quantum. The `QuantumRouter` uses a learned gate:

```python
soft_mask = sigmoid(gate_proj(token) / temperature)
hard_mask = (soft_mask > 0.5)  # binary decision

# Straight-through estimator:
# Forward: hard binary (fast, sparse)
# Backward: soft gradient (differentiable)
mask = hard.detach() + soft - soft.detach()
```

**Target sparsity**: 70% (default). Only ~30% of tokens pass through the quantum circuit.

---

## ๐ŸŽฏ Use Cases & Recipes

### 1. Edge NLP (Mobile / Low-GPU)

```bash
python scripts/benchmark.py --preset tiny --epochs 3
```

Config: `d_model=64, tt_rank=2, n_qubits=4`. Model < 1M params.

### 2. Enterprise Cost Reduction

```bash
# Knowledge-distilled compression
python scripts/distill.py \
    --teacher_config medium \
    --student_rank 4 \
    --alpha 0.5 --temperature 3.0
```

Train a dense teacher (5M params), distill into a compressed student (1.5M params).

### 3. Research: Comparing Compression Methods

```python
from src.metrics import compare_models, print_comparison_table, compute_pareto_frontier

results = compare_models({
    "standard": standard_model,
    "pruned_50": pruned_model,
    "distilled": distilled_model,
    "qtensor_r8": qtensor_rank8,
    "qtensor_r4": qtensor_rank4,
}, test_loader)

print_comparison_table(results)
pareto = compute_pareto_frontier(results)
```

### 4. Multilingual Low-Resource

```python
from src.data import CharTokenizer
texts = load_your_language_data()
tokenizer = CharTokenizer()
tokenizer.fit(texts)
config = ModelConfig(vocab_size=tokenizer.vocab_size, d_model=128, 
                     tt_rank=4, n_layers=3)
```

### 5. Budget-Constrained Deployment

```yaml
budget:
  max_params: 2000000
  max_latency_ms: 50.0
  max_energy_per_query: 500.0
  target_compression_ratio: 2.0
```

---

## ๐Ÿงช Evaluation Metrics

| Metric | What It Measures | Tool |
|--------|-----------------|------|
| **Perplexity (PPL)** | Language modeling quality | `metrics.evaluate_model()` |
| **Total/compressed params** | Memory efficiency | `model.total_params` |
| **Compression ratio** | vs. dense equivalent | `model.compression_ratio` |
| **Latency (p50, p95)** | Inference speed | Benchmarked with warmup |
| **Energy (FLOPs proxy)** | Power consumption | `budget.EnergyEstimator` |
| **Pareto frontier** | Optimal PPL-params tradeoff | `metrics.compute_pareto_frontier()` |
| **Efficiency score** | Combined metric | `metrics.compute_efficiency_score()` |
| **Rank trajectory** | How ranks evolve during training | `metrics.rank_trajectory_analysis()` |
| **Quantum sparsity** | % tokens bypassing quantum | `model.stats['quantum_usage']` |

---

## ๐Ÿ”ฌ Scientific Background

### Tensor-Train Decomposition

Given a weight matrix **W โˆˆ R^{I ร— O}**, TT decomposition factorizes it into **d cores**:

```
W(iโ‚,...,i_d, oโ‚,...,o_d) = โˆ G_k[i_k, o_k]
```

where **G_k โˆˆ R^{r_{k-1} ร— i_k ร— o_k ร— r_k}** and rโ‚€ = r_d = 1. The TT-rank **r** controls the compression.

Q-TensorFormer uses **SVD-based rank truncation**: when reducing rank, we merge adjacent cores and keep the top-k singular values at each bond, preserving dominant signal directions (Eckart-Young theorem).

### Quantum-Classical Hybrid

We simulate **NISQ-era quantum circuits** using PennyLane's `default.qubit` backend. Compatible with real quantum hardware by changing the device.

### Entanglement โ†’ Rank Correspondence

The core insight: **attention entropy** is a classical proxy for **quantum entanglement entropy**. When attention is diffuse (uniform over many tokens), the representation is more "complex" โ€” we allocate higher TT-rank. When attention is concentrated, we compress aggressively.

---

## ๐Ÿ“ˆ Roadmap

### v3.1 (Next)
- [ ] Apply to real pretrained models (GPT-2 small, DistilBERT)
- [ ] Structured pruning baseline comparison
- [ ] GLUE/SuperGLUE classification benchmarks

### v3.2
- [ ] Actual quantum hardware support (Braket, IBM Q)
- [ ] Multi-modal extension (ViT + TT)
- [ ] ONNX export for production deployment

### v4.0
- [ ] Post-training quantization (int8 TT cores)
- [ ] Speculative decoding with adaptive TT-rank
- [ ] Online learning with adaptive compression

---

## ๐Ÿค Contributing

1. Fork the repo
2. Create a feature branch
3. Make changes + add tests
4. Run `pytest tests/` to verify
5. Submit a PR

---

## ๐Ÿ“š References

- **Tensor Networks**: Cichocki et al., "Tensor Networks for Dimensionality Reduction and Large-scale Optimization" (arXiv:2007.02779)
- **Tensor-Train**: Oseledets, "Tensor-Train Decomposition" (SIAM J. Sci. Comp., 2011)
- **Quixer**: "Quantum Transformer for Language Modeling" (arXiv:2406.04305)
- **QKSAN**: "Quantum Kernel Self-Attention Network" (arXiv:2308.13422, IEEE TPAMI 2024)
- **PennyLane**: Bergholm et al., "Automatic differentiation of hybrid quantum-classical computations" (arXiv:1811.04968)
- **Knowledge Distillation**: Hinton et al., "Distilling the Knowledge in a Neural Network" (arXiv:1503.02531)

---

## ๐Ÿ“œ License

Apache 2.0 โ€” see [LICENSE](LICENSE).

## ๐Ÿ™ Acknowledgments

Built with:
- [PyTorch](https://pytorch.org/) โ€” Deep learning framework
- [PennyLane](https://pennylane.ai/) โ€” Quantum computing library
- [HuggingFace Datasets](https://huggingface.co/docs/datasets) โ€” WikiText-2 loading

---

<div align="center">

**Q-TensorFormer v3** ยท Made with โš›๏ธ + ๐Ÿงฎ

[๐Ÿค— Model on Hub](https://huggingface.co/Premchan369/q-tensorformer)

</div>