-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQelm2.py
757 lines (631 loc) · 28.4 KB
/
Qelm2.py
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
====================================================================================================
Quantum-Enhanced Language Model (QELM) - Single Thread Script (This takes a long time to train)
====================================================================================================
This script defines a Quantum-Enhanced Language Model (QELM) with the following features:
1. Gradient-Based Optimization using the Parameter Shift Rule.
2. Advanced Quantum Circuit Design with entangling gates and multiple layers.
3. Improved Synthetic Dataset resembling language data.
4. Enhanced Model Architecture with residual connections and layer normalization.
5. Robust Parameter Persistence with versioning and validation.
6. User-Friendly Command-Line Interface (CLI) for training, inference, saving, and loading.
7. Single thread - to utilize the most of your cpu or gpu you will need to update threading or use the GUI script.
Dependencies:
- qiskit
- qiskit-aer
- numpy
- scipy
- nltk
- argparse
Ensure all dependencies are installed before running the script.
Ensure Qiskit is running import correctly as they tend to change it each update.
====================================================================================================
"""
import sys
import numpy as np
import json
import argparse
import logging
from typing import List, Dict
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.circuit import Parameter
from scipy.optimize import minimize
import nltk
from nltk.tokenize import word_tokenize
from collections import defaultdict
# Initialize NLTK data (only the first time)
nltk.download('punkt', quiet=True)
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# ============================
# Utility Functions
# ============================
def normalize_vector(vec: np.ndarray) -> np.ndarray:
"""
Normalize a vector to unit length.
"""
norm = np.linalg.norm(vec)
if norm < 1e-12:
return vec
return vec / norm
# ============================
# Quantum Parameter Store
# ============================
class QuantumParameterStore:
"""
Stores parameters for quantum gates.
"""
def __init__(self, size: int, prefix: str = "theta"):
self.size = size
self.parameters = [Parameter(f"{prefix}_{i}") for i in range(size)]
self.values = np.zeros(size, dtype=float)
def set_values(self, vals: np.ndarray):
if vals.shape[0] != self.size:
sys.exit("Error: Parameter values length mismatch.")
self.values = vals
def get_values(self) -> np.ndarray:
return self.values.copy()
def to_dict(self) -> dict:
return {
"size": self.size,
"prefix": self.parameters[0].name.rsplit('_', 1)[0],
"values": self.values.tolist()
}
def from_dict(self, d: dict):
if d["size"] != self.size:
sys.exit("Error: Size mismatch when loading parameters.")
self.set_values(np.array(d["values"], dtype=float))
# ============================
# Quantum Attention Layer
# ============================
class QuantumAttentionLayer:
"""
Quantum-enhanced attention layer with advanced circuit design.
"""
def __init__(self, embed_dim: int, num_heads: int, prefix: str = "attn"):
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
if self.head_dim * num_heads != embed_dim:
sys.exit("Error: embed_dim must be divisible by num_heads.")
# Initialize parameter stores
self.query_params = QuantumParameterStore(embed_dim * embed_dim, prefix=f"{prefix}_Q")
self.key_params = QuantumParameterStore(embed_dim * embed_dim, prefix=f"{prefix}_K")
self.value_params = QuantumParameterStore(embed_dim * embed_dim, prefix=f"{prefix}_V")
self.out_params = QuantumParameterStore(embed_dim * embed_dim, prefix=f"{prefix}_O")
# Initialize quantum simulator
self.backend = AerSimulator()
def build_circuit(self, input_vector: np.ndarray, param_store: QuantumParameterStore, output_length: int) -> QuantumCircuit:
"""
Build the quantum circuit with entangling gates and multiple layers.
"""
qubits_needed = max(1, int(np.ceil(np.log2(output_length))))
circuit = QuantumCircuit(qubits_needed)
# Initialize the quantum state
state_prep_vec = np.zeros(2**qubits_needed, dtype=complex)
# Truncate or pad the input_vector to match output_length
truncated_input = input_vector[:output_length] if len(input_vector) >= output_length else np.pad(input_vector, (0, output_length - len(input_vector)), 'constant')
state_prep_vec[:output_length] = truncated_input.astype(complex)
state_prep_vec = normalize_vector(state_prep_vec)
circuit.initialize(state_prep_vec, qubits=range(qubits_needed))
# Apply parameterized rotations with entangling gates
num_layers = 2 # Multiple layers
for layer in range(num_layers):
# Parameterized RY rotations
for i in range(qubits_needed):
theta = param_store.values[layer * qubits_needed + i]
circuit.ry(theta, i)
# Entangling CNOT gates
for i in range(qubits_needed - 1):
circuit.cx(i, i+1)
# Final RY rotations
for i in range(qubits_needed):
theta = param_store.values[num_layers * qubits_needed + i]
circuit.ry(theta, i)
circuit.save_statevector()
return circuit
def forward(self, input_vector: np.ndarray, mode: str = 'query') -> np.ndarray:
"""
Perform a forward pass through the quantum attention layer.
"""
input_vector = normalize_vector(input_vector)
if mode == 'query':
output_length = self.embed_dim
circuit = self.build_circuit(input_vector, self.query_params, output_length)
elif mode == 'key':
output_length = self.embed_dim
circuit = self.build_circuit(input_vector, self.key_params, output_length)
elif mode == 'value':
output_length = self.embed_dim
circuit = self.build_circuit(input_vector, self.value_params, output_length)
elif mode == 'out':
output_length = self.embed_dim
circuit = self.build_circuit(input_vector, self.out_params, output_length)
else:
sys.exit("Error: Invalid mode for QuantumAttentionLayer.forward")
# Simulate the circuit
try:
job = self.backend.run(circuit, shots=1024)
result = job.result()
final_state = result.get_statevector(circuit)
except Exception as e:
logging.error(f"An error occurred during quantum simulation: {e}")
sys.exit(1)
# Extract and normalize the output vector
if len(final_state.data) < output_length:
logging.warning(f"Final state vector length ({len(final_state.data)}) is less than expected ({output_length}). Padding with zeros.")
output_vec = np.real(final_state.data[:len(final_state.data)]) # Use available data
output_vec = np.pad(output_vec, (0, output_length - len(output_vec)), 'constant')
else:
output_vec = np.real(final_state.data[:output_length])
return normalize_vector(output_vec)
def get_all_parameters(self) -> np.ndarray:
"""
Get all parameters as a single array.
"""
return np.concatenate([
self.query_params.get_values(),
self.key_params.get_values(),
self.value_params.get_values(),
self.out_params.get_values()
])
def set_all_parameters(self, params: np.ndarray):
"""
Set all parameters from a single array.
"""
total_size = self.query_params.size + self.key_params.size + self.value_params.size + self.out_params.size
if params.shape[0] != total_size:
sys.exit("Error: Parameter size mismatch in QuantumAttentionLayer.")
q_size = self.query_params.size
k_size = self.key_params.size
v_size = self.value_params.size
o_size = self.out_params.size
self.query_params.set_values(params[:q_size])
self.key_params.set_values(params[q_size:q_size + k_size])
self.value_params.set_values(params[q_size + k_size:q_size + k_size + v_size])
self.out_params.set_values(params[q_size + k_size + v_size:])
def to_dict(self) -> dict:
return {
"embed_dim": self.embed_dim,
"num_heads": self.num_heads,
"query_params": self.query_params.to_dict(),
"key_params": self.key_params.to_dict(),
"value_params": self.value_params.to_dict(),
"out_params": self.out_params.to_dict()
}
def from_dict(self, d: dict):
if d["embed_dim"] != self.embed_dim or d["num_heads"] != self.num_heads:
sys.exit("Error: Attention layer configuration mismatch.")
self.query_params.from_dict(d["query_params"])
self.key_params.from_dict(d["key_params"])
self.value_params.from_dict(d["value_params"])
self.out_params.from_dict(d["out_params"])
# ============================
# Quantum Feed-Forward Layer
# ============================
class QuantumFeedForwardLayer:
"""
Quantum-enhanced feed-forward layer with advanced circuit design.
"""
def __init__(self, embed_dim: int, hidden_dim: int, prefix: str = "ffn"):
self.embed_dim = embed_dim
self.hidden_dim = hidden_dim
# Initialize parameter stores
self.w1_params = QuantumParameterStore(embed_dim * hidden_dim, prefix=f"{prefix}_W1")
self.w2_params = QuantumParameterStore(hidden_dim * embed_dim, prefix=f"{prefix}_W2")
# Initialize quantum simulator
self.backend = AerSimulator()
def build_circuit(self, input_vector: np.ndarray, param_store: QuantumParameterStore, output_length: int) -> QuantumCircuit:
"""
Build the quantum circuit with entangling gates and multiple layers.
"""
qubits_needed = max(1, int(np.ceil(np.log2(output_length))))
circuit = QuantumCircuit(qubits_needed)
# Initialize the quantum state
state_prep_vec = np.zeros(2**qubits_needed, dtype=complex)
# Truncate or pad the input_vector to match output_length
truncated_input = input_vector[:output_length] if len(input_vector) >= output_length else np.pad(input_vector, (0, output_length - len(input_vector)), 'constant')
state_prep_vec[:output_length] = truncated_input.astype(complex)
state_prep_vec = normalize_vector(state_prep_vec)
circuit.initialize(state_prep_vec, qubits=range(qubits_needed))
# Apply parameterized rotations with entangling gates
num_layers = 2 # Multiple layers
for layer in range(num_layers):
# Parameterized RY rotations
for i in range(qubits_needed):
theta = param_store.values[layer * qubits_needed + i]
circuit.ry(theta, i)
# Entangling CNOT gates
for i in range(qubits_needed - 1):
circuit.cx(i, i+1)
# Final RY rotations
for i in range(qubits_needed):
theta = param_store.values[num_layers * qubits_needed + i]
circuit.ry(theta, i)
circuit.save_statevector()
return circuit
def forward(self, input_vector: np.ndarray, layer: str = 'w1') -> np.ndarray:
"""
Perform a forward pass through the quantum feed-forward layer.
"""
input_vector = normalize_vector(input_vector)
if layer == 'w1':
output_length = self.hidden_dim # 32
circuit = self.build_circuit(input_vector, self.w1_params, output_length)
elif layer == 'w2':
output_length = self.embed_dim # 16
circuit = self.build_circuit(input_vector, self.w2_params, output_length)
else:
sys.exit("Error: Invalid layer for QuantumFeedForwardLayer.forward")
# Simulate the circuit
try:
job = self.backend.run(circuit, shots=1024)
result = job.result()
final_state = result.get_statevector(circuit)
except Exception as e:
logging.error(f"An error occurred during quantum simulation: {e}")
sys.exit(1)
# Extract and normalize the output vector
if len(final_state.data) < output_length:
logging.warning(f"Final state vector length ({len(final_state.data)}) is less than expected ({output_length}). Padding with zeros.")
output_vec = np.real(final_state.data[:len(final_state.data)]) # Use available data
output_vec = np.pad(output_vec, (0, output_length - len(output_vec)), 'constant')
else:
output_vec = np.real(final_state.data[:output_length])
return normalize_vector(output_vec)
def get_all_parameters(self) -> np.ndarray:
"""
Get all parameters as a single array.
"""
return np.concatenate([
self.w1_params.get_values(),
self.w2_params.get_values()
])
def set_all_parameters(self, params: np.ndarray):
"""
Set all parameters from a single array.
"""
total_size = self.w1_params.size + self.w2_params.size
if params.shape[0] != total_size:
sys.exit("Error: Parameter size mismatch in QuantumFeedForwardLayer.")
w1_size = self.w1_params.size
self.w1_params.set_values(params[:w1_size])
self.w2_params.set_values(params[w1_size:])
def to_dict(self) -> dict:
return {
"embed_dim": self.embed_dim,
"hidden_dim": self.hidden_dim,
"w1_params": self.w1_params.to_dict(),
"w2_params": self.w2_params.to_dict()
}
def from_dict(self, d: dict):
if d["embed_dim"] != self.embed_dim or d["hidden_dim"] != self.hidden_dim:
sys.exit("Error: Feed-forward layer configuration mismatch.")
self.w1_params.from_dict(d["w1_params"])
self.w2_params.from_dict(d["w2_params"])
# ============================
# Quantum Language Model
# ============================
class QuantumLanguageModel:
"""
Quantum-Enhanced Language Model combining attention and feed-forward layers.
"""
def __init__(self, vocab_size: int, embed_dim: int, num_heads: int, hidden_dim: int):
self.vocab_size = vocab_size
self.embed_dim = embed_dim
self.num_heads = num_heads
self.hidden_dim = hidden_dim
# Initialize embeddings
self.embeddings = (np.random.randn(vocab_size, embed_dim) * 0.01).astype(np.float32)
# Initialize quantum layers
self.attn = QuantumAttentionLayer(embed_dim, num_heads, prefix="layer1_attn")
self.ffn = QuantumFeedForwardLayer(embed_dim, hidden_dim, prefix="layer1_ffn")
# Initialize quantum parameters
self._initialize_quantum_params()
def _initialize_quantum_params(self):
"""
Randomly initialize quantum parameters.
"""
scale = 0.1 # Increased scale for better parameter exploration
self.attn.query_params.set_values(np.random.randn(self.attn.query_params.size) * scale)
self.attn.key_params.set_values(np.random.randn(self.attn.key_params.size) * scale)
self.attn.value_params.set_values(np.random.randn(self.attn.value_params.size) * scale)
self.attn.out_params.set_values(np.random.randn(self.attn.out_params.size) * scale)
self.ffn.w1_params.set_values(np.random.randn(self.ffn.w1_params.size) * scale)
self.ffn.w2_params.set_values(np.random.randn(self.ffn.w2_params.size) * scale)
def forward(self, input_ids: List[int], use_residual: bool = True) -> np.ndarray:
"""
Perform a forward pass through the entire model.
"""
if not input_ids:
sys.exit("Error: input_ids list is empty.")
# Embedding lookup
try:
x = self.embeddings[input_ids[0]]
except IndexError:
sys.exit(f"Error: input_id {input_ids[0]} is out of bounds for vocabulary size {self.vocab_size}.")
# Quantum attention
attn_output = self.attn.forward(x, mode='query')
key_output = self.attn.forward(x, mode='key')
value_output = self.attn.forward(x, mode='value')
# Combine attention outputs (placeholder for actual attention mechanism)
combined_attn = attn_output + key_output + value_output
if use_residual:
x = normalize_vector(x + combined_attn) # Residual connection and normalization
else:
x = combined_attn
# Quantum feed-forward
ffn_output_w1 = self.ffn.forward(x, layer='w1') # Shape: (32,)
ffn_output_w2 = self.ffn.forward(ffn_output_w1, layer='w2') # Shape: (16,)
ffn_output = ffn_output_w2 # Shape: (16,)
if use_residual:
x = normalize_vector(x + ffn_output) # Residual connection and normalization
else:
x = ffn_output
# Output logits (linear transformation)
W_out = np.random.randn(self.vocab_size, self.embed_dim).astype(np.float32) * 0.01 # Updated shape to (256, 16)
logits = W_out @ x # Shape: (256,)
return logits
def get_all_parameters(self) -> np.ndarray:
"""
Get all quantum parameters concatenated into a single array.
"""
return np.concatenate([
self.attn.get_all_parameters(),
self.ffn.get_all_parameters()
])
def set_all_parameters(self, params: np.ndarray):
"""
Set all quantum parameters from a single array.
"""
attn_size = self.attn.query_params.size + self.attn.key_params.size + self.attn.value_params.size + self.attn.out_params.size
ffn_size = self.ffn.w1_params.size + self.ffn.w2_params.size
if params.shape[0] != attn_size + ffn_size:
sys.exit("Error: Parameter size mismatch in QuantumLanguageModel.")
self.attn.set_all_parameters(params[:attn_size])
self.ffn.set_all_parameters(params[attn_size:])
def to_dict(self) -> dict:
return {
"vocab_size": self.vocab_size,
"embed_dim": self.embed_dim,
"num_heads": self.num_heads,
"hidden_dim": self.hidden_dim,
"embeddings": self.embeddings.tolist(),
"attn": self.attn.to_dict(),
"ffn": self.ffn.to_dict()
}
def from_dict(self, d: dict):
if (d["vocab_size"] != self.vocab_size or
d["embed_dim"] != self.embed_dim or
d["num_heads"] != self.num_heads or
d["hidden_dim"] != self.hidden_dim):
sys.exit("Error: Model configuration in file does not match this QLM instance.")
self.embeddings = np.array(d["embeddings"], dtype=np.float32)
self.attn.from_dict(d["attn"])
self.ffn.from_dict(d["ffn"])
def save_model(self, save_path: str):
"""
Save model parameters (embeddings and quantum parameters) to a JSON file.
"""
model_dict = self.to_dict()
model_dict["version"] = "1.0"
try:
with open(save_path, 'w') as f:
json.dump(model_dict, f)
logging.info(f"Model saved to {save_path}")
except Exception as e:
logging.error(f"Failed to save model: {e}")
sys.exit(1)
def load_model(self, load_path: str):
"""
Load model parameters (embeddings and quantum parameters) from a JSON file.
"""
try:
with open(load_path, 'r') as f:
model_dict = json.load(f)
except FileNotFoundError:
sys.exit(f"Error: The file {load_path} does not exist.")
except json.JSONDecodeError:
sys.exit(f"Error: The file {load_path} is not a valid JSON file.")
except Exception as e:
sys.exit(f"Error reading the model file: {e}")
# Version check
if "version" not in model_dict or model_dict["version"] != "1.0":
sys.exit("Error: Unsupported model version.")
try:
self.from_dict(model_dict)
logging.info(f"Model loaded from {load_path}")
except Exception as e:
logging.error(f"Failed to load model: {e}")
sys.exit(1)
# ============================
# Synthetic Dataset
# ============================
def create_synthetic_dataset(vocab_size: int, num_samples: int = 100):
"""
Create a synthetic dataset for demonstration:
Each sample: input_id -> random token, target -> one-hot vector
"""
X = np.random.randint(0, vocab_size, size=(num_samples,))
Y = np.zeros((num_samples, vocab_size), dtype=np.float32)
for i in range(num_samples):
# Create a "target" as a random one-hot vector different from input token
target_id = np.random.randint(0, vocab_size)
Y[i, target_id] = 1.0
return X, Y
# ============================
# Real Dataset Loader (Optional)
# ============================
def load_real_dataset(file_path: str, vocab_size: int):
"""
Load and preprocess a real language dataset.
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
except FileNotFoundError:
sys.exit(f"Error: The file {file_path} does not exist.")
except Exception as e:
sys.exit(f"Error reading the dataset file: {e}")
tokens = word_tokenize(text.lower())
freq = defaultdict(int)
for token in tokens:
freq[token] += 1
# Select top vocab_size tokens
sorted_tokens = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:vocab_size]
token_to_id = {token: idx for idx, (token, _) in enumerate(sorted_tokens)}
# Convert tokens to IDs
X = []
Y = []
for i in range(len(tokens) - 1):
current_token = tokens[i]
next_token = tokens[i + 1]
if current_token in token_to_id and next_token in token_to_id:
X.append(token_to_id[current_token])
Y.append(token_to_id[next_token])
# One-hot encode targets
Y_one_hot = np.zeros((len(Y), vocab_size), dtype=np.float32)
for i, target_id in enumerate(Y):
Y_one_hot[i, target_id] = 1.0
return np.array(X), Y_one_hot, token_to_id
# ============================
# Loss Function
# ============================
def mse_loss(pred: np.ndarray, target: np.ndarray) -> float:
"""
Compute Mean Squared Error loss between prediction and target.
"""
return np.mean((pred - target)**2)
# ============================
# Training Functions
# ============================
def compute_gradients(model: QuantumLanguageModel, X: np.ndarray, Y: np.ndarray) -> np.ndarray:
"""
Compute gradients of the loss with respect to all quantum parameters using the Parameter Shift Rule.
Note: This is a simplified implementation for demonstration purposes.
"""
gradients = np.zeros_like(model.get_all_parameters())
original_params = model.get_all_parameters().copy()
for i in range(len(original_params)):
# Shift parameter positively
shifted_params_plus = original_params.copy()
shifted_params_plus[i] += np.pi / 2
model.set_all_parameters(shifted_params_plus)
loss_plus = 0.0
for x, y in zip(X, Y):
logits = model.forward([x])
loss_plus += mse_loss(logits, y)
loss_plus /= len(X)
# Shift parameter negatively
shifted_params_minus = original_params.copy()
shifted_params_minus[i] -= np.pi / 2
model.set_all_parameters(shifted_params_minus)
loss_minus = 0.0
for x, y in zip(X, Y):
logits = model.forward([x])
loss_minus += mse_loss(logits, y)
loss_minus /= len(X)
# Reset to original parameter
model.set_all_parameters(original_params)
# Compute gradient using Parameter Shift Rule
gradients[i] = (loss_plus - loss_minus) / 2
return gradients
def train_model(model: QuantumLanguageModel, X: np.ndarray, Y: np.ndarray, epochs: int = 10, lr: float = 0.1):
"""
Train the model using gradient-based optimization with the Parameter Shift Rule.
"""
for epoch in range(epochs):
logging.info(f"Starting Epoch {epoch+1}/{epochs}")
# Compute gradients
gradients = compute_gradients(model, X, Y)
# Update parameters
params = model.get_all_parameters()
params -= lr * gradients
model.set_all_parameters(params)
# Compute average loss
total_loss = 0.0
for x, y in zip(X, Y):
logits = model.forward([x])
loss = mse_loss(logits, y)
total_loss += loss
avg_loss = total_loss / len(X)
logging.info(f"Epoch {epoch+1}/{epochs}, Average Loss: {avg_loss:.6f}")
# ============================
# Parameter Persistence
# ============================
def save_model(model: QuantumLanguageModel, save_path: str):
"""
Save model parameters (embeddings and quantum parameters) to a JSON file.
"""
model.save_model(save_path)
def load_model(model: QuantumLanguageModel, load_path: str):
"""
Load model parameters (embeddings and quantum parameters) from a JSON file.
"""
model.load_model(load_path)
# ============================
# Inference Function
# ============================
def run_inference(model: QuantumLanguageModel, input_id: int):
"""
Run a forward pass of the model and print the logits.
"""
logits = model.forward([input_id])
print("Logits:", logits)
# ============================
# Main Function with CLI
# ============================
def main():
"""
Main function to initialize the model, perform training, save/load model parameters, and run inference.
"""
parser = argparse.ArgumentParser(description="Quantum-Enhanced Language Model (QELM) - Enhanced Version")
parser.add_argument('--train', action='store_true', help='Train the model')
parser.add_argument('--inference', action='store_true', help='Run inference')
parser.add_argument('--input_id', type=int, help='Input token ID for inference')
parser.add_argument('--save_path', type=str, default='quantum_llm_model_enhanced.json', help='Path to save the model')
parser.add_argument('--load_path', type=str, help='Path to load the model')
parser.add_argument('--epochs', type=int, default=10, help='Number of training epochs')
parser.add_argument('--lr', type=float, default=0.1, help='Learning rate')
parser.add_argument('--dataset_path', type=str, help='Path to real dataset file (optional)')
args = parser.parse_args()
# Check if no arguments are provided
if len(sys.argv) == 1:
parser.print_help()
sys.exit(0)
# Model parameters
vocab_size = 256
embed_dim = 16
num_heads = 2
hidden_dim = 32
epochs = args.epochs
learning_rate = args.lr
save_path = args.save_path
load_path = args.load_path
# Initialize the Quantum Language Model
model = QuantumLanguageModel(vocab_size, embed_dim, num_heads, hidden_dim)
# Load model if specified
if load_path:
load_model(model, load_path)
# Train the model
if args.train:
if args.dataset_path:
logging.info("Loading real dataset...")
X, Y, token_to_id = load_real_dataset(args.dataset_path, vocab_size)
else:
logging.info("Creating synthetic dataset...")
X, Y = create_synthetic_dataset(vocab_size, num_samples=100)
logging.info("Starting training...")
train_model(model, X, Y, epochs=epochs, lr=learning_rate)
logging.info("Training completed.")
save_model(model, save_path)
# Run inference
if args.inference:
if args.input_id is None:
sys.exit("Error: --input_id is required for inference.")
run_inference(model, args.input_id)
if __name__ == "__main__":
main()