-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQelmGUI.py
1979 lines (1695 loc) · 85.7 KB
/
QelmGUI.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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
====================================================================================================
Quantum-Enhanced Language Model (QELM) - Trainer with multi thread support. *CPU/GPU*
====================================================================================================
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. Support for both Synthetic and Real Datasets resembling language data.
4. Enhanced Model Architecture with residual connections and layer normalization.
5. Robust Parameter Persistence with versioning and validation using a custom .qelm file extension.
6. User-Friendly Graphical User Interface (GUI) using Tkinter for training, inference, saving, loading, and exploring token mappings.
7. Added ansatz and circuit building blocks.
Dependencies:
- qiskit
- qiskit-aer
- numpy
- scipy
- nltk
- tkinter
- tensorflow
- psutil (optional for resource monitoring)
Ensure all dependencies are installed before running the script.
Check with Qiskit to ensure calls are correct. They have a tendency to change them with updates.
*New* Use Quanta to figure out spin variables and gates, this information will help with inputs.
GPU currently isn't working for certain gpu instances.
*New* version releases soon.
====================================================================================================
"""
import sys
import os
# =====================
# Set Environment Variables
# =====================
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' # Disable oneDNN custom operations
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow INFO and WARNING messages
import json
import time
import logging
import traceback
import threading
import multiprocessing
import concurrent.futures
from collections import defaultdict
from typing import List, Dict, Tuple, Optional
import queue
import subprocess
import numpy as np
import nltk
from nltk.tokenize import word_tokenize
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.circuit import Parameter
import tensorflow as tf # TensorFlow import after setting environment variables
from tensorflow import keras
from tensorflow.keras.utils import plot_model
try:
import psutil
except ImportError:
psutil = None
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext, ttk
# Initialize NLTK quietly
nltk.download('punkt', quiet=True)
# =====================
# Logging Configuration (No I will not remove this)
# =====================
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
def normalize_vector(vec: np.ndarray) -> np.ndarray:
"""
Normalize a vector to have unit length.
"""
norm = np.linalg.norm(vec)
if norm < 1e-12:
return vec.copy()
return vec / norm
class QuantumParameterStore:
"""
Stores quantum parameters with utilities for setting and retrieving values.
"""
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:
raise ValueError("Parameter size mismatch.")
self.values = vals.copy()
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:
raise ValueError("Parameter size mismatch when loading parameters.")
self.set_values(np.array(d["values"], dtype=float))
class QuantumLayerBase:
"""
Base class for quantum layers that sets up simulators and provides circuit building utilities.
Optional advanced ansatz, data reuploading, and ring entanglement are supported.
"""
def __init__(self,
sim_method: str = 'cpu',
num_threads: int = 1,
enable_logging: bool = True,
use_advanced_ansatz: bool = False,
use_data_reuploading: bool = False):
self.sim_method = sim_method
self.num_threads = num_threads
self.enable_logging = enable_logging
self.use_advanced_ansatz = use_advanced_ansatz
self.use_data_reuploading = use_data_reuploading
self.backend = self.initialize_simulator()
def initialize_simulator(self):
if self.sim_method == 'gpu':
backend = AerSimulator(method='statevector', device='GPU', max_parallel_threads=self.num_threads)
if self.enable_logging:
logging.info(f"{self.__class__.__name__}: Using GPU.")
elif self.sim_method == 'both':
backend = AerSimulator(method='statevector', device='GPU', max_parallel_threads=self.num_threads)
if self.enable_logging:
logging.info(f"{self.__class__.__name__}: Using Both CPU and GPU.")
elif self.sim_method == 'simulation':
# Simulation mode: skip actual quantum circuit execution if desired
# This will still construct the circuit but won't run it through a real simulator.
backend = None
if self.enable_logging:
logging.info(f"{self.__class__.__name__}: Using pure simulation mode (no circuit execution).")
else:
backend = AerSimulator(method='statevector', max_parallel_threads=self.num_threads)
if self.enable_logging:
logging.info(f"{self.__class__.__name__}: Using CPU.")
return backend
def build_circuit(self, input_vector: np.ndarray, param_store: QuantumParameterStore) -> QuantumCircuit:
"""
Builds the quantum circuit. Switches between a simple circuit or an advanced one
based on self.use_advanced_ansatz. Data reuploading can be applied if specified.
"""
if self.use_advanced_ansatz:
circuit = self.build_advanced_circuit(input_vector, param_store)
else:
circuit = self.build_simple_circuit(input_vector, param_store)
return circuit
def build_simple_circuit(self, input_vector: np.ndarray, param_store: QuantumParameterStore) -> QuantumCircuit:
"""
Original simple parameterized ansatz with repeated RY and linear CNOT.
"""
qubits_needed = max(1, int(np.ceil(np.log2(len(input_vector)))))
circuit = QuantumCircuit(qubits_needed)
# Prepare the state
state_prep_vec = np.zeros(2**qubits_needed, dtype=complex)
state_prep_vec[:len(input_vector)] = input_vector.astype(complex)
state_prep_vec = normalize_vector(state_prep_vec)
circuit.initialize(state_prep_vec, qubits=range(qubits_needed))
# Simple parameterized ansatz
num_layers = 2
for layer in range(num_layers):
for i in range(qubits_needed):
theta = param_store.values[layer * qubits_needed + i]
circuit.ry(theta, i)
for i in range(qubits_needed - 1):
circuit.cx(i, i + 1)
# Final RY layer
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 build_advanced_circuit(self, input_vector: np.ndarray, param_store: QuantumParameterStore) -> QuantumCircuit:
"""
More sophisticated ansatz using RY, RZ, ring entanglement, and optional
data reuploading. Preserves the original approach but expands it for
increased expressivity.
"""
qubits_needed = max(1, int(np.ceil(np.log2(len(input_vector)))))
circuit = QuantumCircuit(qubits_needed)
# Data initialization
state_prep_vec = np.zeros(2**qubits_needed, dtype=complex)
state_prep_vec[:len(input_vector)] = input_vector.astype(complex)
state_prep_vec = normalize_vector(state_prep_vec)
circuit.initialize(state_prep_vec, qubits=range(qubits_needed))
layers = 2 # number of repeated big layers
offset = 0
for l in range(layers):
for i in range(qubits_needed):
# RY param
theta_ry = param_store.values[offset]
offset += 1
circuit.ry(theta_ry, i)
# RZ param
theta_rz = param_store.values[offset] if offset < param_store.size else 0
offset += 1
circuit.rz(theta_rz, i)
if self.use_data_reuploading:
# Simple data reupload: rotate by scaled input value
# to re-introduce classical data into the circuit.
scaled_angle = float(input_vector[i % len(input_vector)]) * 0.1
circuit.rx(scaled_angle, i)
# Ring entanglement
for i in range(qubits_needed):
next_qubit = (i + 1) % qubits_needed
circuit.cx(i, next_qubit)
circuit.save_statevector()
return circuit
def simulate(self, circuit: QuantumCircuit) -> np.ndarray:
"""
Runs the circuit on the specified backend or returns a default
state if in 'simulation' mode without real circuit execution.
"""
if self.sim_method == 'simulation' or self.backend is None:
# Skip real execution, return the last 'initialize' state (just as a fallback).
# This is purely for demonstration of "simulation" mode.
# In practice, you might do a classical approximation or no-op.
data = circuit.data
# We'll return the original initialized state from the circuit, if possible.
# If it can't be extracted, just return the initial vector of length 2^qubits.
qubits_needed = circuit.num_qubits
if len(data) > 0 and data[0].operation.name == 'initialize':
init_vec = data[0].operation.params[0]
return init_vec
else:
return np.zeros(2**qubits_needed, dtype=complex)
else:
job = self.backend.run(circuit, shots=1)
result = job.result()
final_state = result.get_statevector(circuit)
return final_state.data
class QuantumAttentionLayer(QuantumLayerBase):
"""
Quantum Attention Layer for the language model.
Implements parameter sharing to reduce total parameters.
"""
def __init__(self, embed_dim: int, num_heads: int,
sim_method: str = 'cpu', num_threads: int = 1,
prefix: str = "attn", enable_logging: bool = True,
use_advanced_ansatz: bool = False,
use_data_reuploading: bool = False):
super().__init__(sim_method=sim_method,
num_threads=num_threads,
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading)
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:
raise ValueError("embed_dim must be divisible by num_heads.")
shared_size = (embed_dim * embed_dim) // num_heads
self.query_params = QuantumParameterStore(shared_size, prefix=f"{prefix}_Q")
self.key_params = QuantumParameterStore(shared_size, prefix=f"{prefix}_K")
self.value_params = QuantumParameterStore(shared_size, prefix=f"{prefix}_V")
self.out_params = QuantumParameterStore(shared_size, prefix=f"{prefix}_O")
def forward(self, input_vector: np.ndarray, mode: str = 'query') -> np.ndarray:
input_vector = normalize_vector(input_vector)
if mode == 'query':
param_store = self.query_params
elif mode == 'key':
param_store = self.key_params
elif mode == 'value':
param_store = self.value_params
elif mode == 'out':
param_store = self.out_params
else:
raise ValueError("Invalid mode for Attention forward.")
circuit = self.build_circuit(input_vector, param_store)
final_state = self.simulate(circuit)
output_length = self.embed_dim
if len(final_state) < output_length:
output_vec = np.real(final_state[:len(final_state)])
output_vec = np.pad(output_vec, (0, output_length - len(output_vec)), 'constant')
else:
output_vec = np.real(final_state[:output_length])
return normalize_vector(output_vec)
def get_all_parameters(self) -> np.ndarray:
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):
attn_size = (self.query_params.size + self.key_params.size +
self.value_params.size + self.out_params.size)
if params.shape[0] != attn_size:
raise ValueError("Param size mismatch in Attention.")
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(),
"sim_method": self.sim_method,
"num_threads": self.num_threads,
"use_advanced_ansatz": self.use_advanced_ansatz,
"use_data_reuploading": self.use_data_reuploading
}
def from_dict(self, d: dict):
if d["embed_dim"] != self.embed_dim or d["num_heads"] != self.num_heads:
raise ValueError("Attention config 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"])
self.sim_method = d.get("sim_method", "cpu")
self.num_threads = d.get("num_threads", 1)
self.use_advanced_ansatz = d.get("use_advanced_ansatz", False)
self.use_data_reuploading = d.get("use_data_reuploading", False)
self.backend = self.initialize_simulator()
class QuantumFeedForwardLayer(QuantumLayerBase):
"""
Quantum Feed-Forward Layer for the language model.
Implements parameter sharing to reduce total parameters.
"""
def __init__(self, embed_dim: int, hidden_dim: int,
sim_method: str = 'cpu', num_threads: int = 1,
prefix: str = "ffn", enable_logging: bool = True,
use_advanced_ansatz: bool = False,
use_data_reuploading: bool = False):
super().__init__(sim_method=sim_method,
num_threads=num_threads,
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading)
self.embed_dim = embed_dim
self.hidden_dim = hidden_dim
shared_size = (embed_dim * hidden_dim) // 2
self.w1_params = QuantumParameterStore(shared_size, prefix=f"{prefix}_W1")
self.w2_params = QuantumParameterStore(shared_size, prefix=f"{prefix}_W2")
def forward(self, input_vector: np.ndarray, layer: str = 'w1') -> np.ndarray:
input_vector = normalize_vector(input_vector)
if layer == 'w1':
param_store = self.w1_params
output_length = self.hidden_dim
elif layer == 'w2':
param_store = self.w2_params
output_length = self.embed_dim
else:
raise ValueError("Invalid layer in FFN forward.")
circuit = self.build_circuit(input_vector, param_store)
final_state = self.simulate(circuit)
if len(final_state) < output_length:
output_vec = np.real(final_state[:len(final_state)])
output_vec = np.pad(output_vec, (0, output_length - len(output_vec)), 'constant')
else:
output_vec = np.real(final_state[:output_length])
return normalize_vector(output_vec)
def get_all_parameters(self) -> np.ndarray:
return np.concatenate([self.w1_params.get_values(), self.w2_params.get_values()])
def set_all_parameters(self, params: np.ndarray):
ffn_size = self.w1_params.size + self.w2_params.size
if params.shape[0] != ffn_size:
raise ValueError("FFN param size mismatch.")
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(),
"sim_method": self.sim_method,
"num_threads": self.num_threads,
"use_advanced_ansatz": self.use_advanced_ansatz,
"use_data_reuploading": self.use_data_reuploading
}
def from_dict(self, d: dict):
if d["embed_dim"] != self.embed_dim or d["hidden_dim"] != self.hidden_dim:
raise ValueError("FFN config mismatch.")
self.w1_params.from_dict(d["w1_params"])
self.w2_params.from_dict(d["w2_params"])
self.sim_method = d.get("sim_method", "cpu")
self.num_threads = d.get("num_threads", 1)
self.use_advanced_ansatz = d.get("use_advanced_ansatz", False)
self.use_data_reuploading = d.get("use_data_reuploading", False)
self.backend = self.initialize_simulator()
class AdamOptimizer:
"""
Adam Optimizer for parameter updates.
"""
def __init__(self, parameters: np.ndarray, lr: float = 0.001,
betas: Tuple[float, float] = (0.9, 0.999), eps: float = 1e-8):
self.parameters = parameters
self.lr = lr
self.betas = betas
self.eps = eps
self.m = np.zeros_like(self.parameters)
self.v = np.zeros_like(self.parameters)
self.t = 0
def step(self, gradients: np.ndarray):
self.t += 1
self.m = self.betas[0] * self.m + (1 - self.betas[0]) * gradients
self.v = self.betas[1] * self.v + (1 - self.betas[1]) * (gradients ** 2)
m_hat = self.m / (1 - self.betas[0] ** self.t)
v_hat = self.v / (1 - self.betas[1] ** self.t)
update = self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
self.parameters -= update
return self.parameters
class QuantumTransformerBlock:
"""
A block that contains one quantum attention layer and one quantum feed-forward layer,
optionally with residual connections. This is for multi-block expansions.
This will most likely be replaced soon.
"""
def __init__(self,
embed_dim: int,
num_heads: int,
hidden_dim: int,
sim_method: str = 'cpu',
num_threads: int = 1,
block_prefix: str = "block",
enable_logging: bool = True,
use_advanced_ansatz: bool = False,
use_data_reuploading: bool = False):
self.attn = QuantumAttentionLayer(
embed_dim, num_heads,
sim_method=sim_method,
num_threads=num_threads,
prefix=f"{block_prefix}_attn",
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading
)
self.ffn = QuantumFeedForwardLayer(
embed_dim, hidden_dim,
sim_method=sim_method,
num_threads=num_threads,
prefix=f"{block_prefix}_ffn",
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading
)
self.embed_dim = embed_dim
self.hidden_dim = hidden_dim
self.num_heads = num_heads
def forward(self, x: np.ndarray, use_residual: bool = True) -> np.ndarray:
"""
Forward pass of the block with a standard attention->FFN approach.
"""
attn_output_query = self.attn.forward(x, mode='query')
attn_output_key = self.attn.forward(x, mode='key')
attn_output_value = self.attn.forward(x, mode='value')
attn_output_out = self.attn.forward(x, mode='out')
attn_output = attn_output_query + attn_output_key + attn_output_value + attn_output_out
if use_residual:
x = normalize_vector(x + attn_output)
else:
x = attn_output
ffn_output_w1 = self.ffn.forward(x, layer='w1')
ffn_output_w2 = self.ffn.forward(ffn_output_w1, layer='w2')
if use_residual:
x = normalize_vector(x + ffn_output_w2)
else:
x = ffn_output_w2
return x
def get_all_parameters(self) -> np.ndarray:
return np.concatenate([
self.attn.get_all_parameters(),
self.ffn.get_all_parameters()
])
def set_all_parameters(self, params: np.ndarray):
attn_size = len(self.attn.get_all_parameters())
ffn_size = len(self.ffn.get_all_parameters())
if params.shape[0] != attn_size + ffn_size:
raise ValueError("Parameter mismatch in QuantumTransformerBlock.")
self.attn.set_all_parameters(params[:attn_size])
self.ffn.set_all_parameters(params[attn_size:])
def to_dict(self) -> dict:
return {
"attn": self.attn.to_dict(),
"ffn": self.ffn.to_dict()
}
def from_dict(self, d: dict):
self.attn.from_dict(d["attn"])
self.ffn.from_dict(d["ffn"])
class QuantumLanguageModel:
"""
The main Quantum Language Model integrating one or multiple blocks of
attention and feed-forward layers.
"""
def __init__(self,
vocab_size: int,
embed_dim: int,
num_heads: int,
hidden_dim: int,
sim_method: str = 'cpu',
num_threads: int = 1,
enable_logging: bool = True,
use_advanced_ansatz: bool = False,
use_data_reuploading: bool = False,
num_blocks: int = 1):
self.vocab_size = vocab_size
self.embed_dim = embed_dim
self.num_heads = num_heads
self.hidden_dim = hidden_dim
self.embeddings = (np.random.randn(vocab_size, embed_dim) * 0.01).astype(np.float32)
# If multiple blocks are specified, build them in a list.
self.blocks = []
if num_blocks > 1:
for b in range(num_blocks):
block_prefix = f"layer{b+1}"
block = QuantumTransformerBlock(
embed_dim=embed_dim,
num_heads=num_heads,
hidden_dim=hidden_dim,
sim_method=sim_method,
num_threads=num_threads,
block_prefix=block_prefix,
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading
)
self.blocks.append(block)
else:
# Original single attention and single feed-forward layers for
# backward compatibility.
self.attn = QuantumAttentionLayer(
embed_dim, num_heads,
sim_method=sim_method,
num_threads=num_threads,
prefix="layer1_attn",
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading
)
self.ffn = QuantumFeedForwardLayer(
embed_dim, hidden_dim,
sim_method=sim_method,
num_threads=num_threads,
prefix="layer1_ffn",
enable_logging=enable_logging,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading
)
self.W_proj = (np.random.randn(embed_dim, hidden_dim) * 0.01).astype(np.float32)
self.W_out = (np.random.randn(vocab_size, embed_dim) * 0.01).astype(np.float32)
self._initialize_quantum_params()
self.num_blocks = num_blocks
def _initialize_quantum_params(self):
scale = 0.1
if self.blocks:
# Multi-block approach
for block in self.blocks:
# We'll randomly initialize each block's parameters
block.attn.query_params.set_values(np.random.randn(block.attn.query_params.size) * scale)
block.attn.key_params.set_values(np.random.randn(block.attn.key_params.size) * scale)
block.attn.value_params.set_values(np.random.randn(block.attn.value_params.size) * scale)
block.attn.out_params.set_values(np.random.randn(block.attn.out_params.size) * scale)
block.ffn.w1_params.set_values(np.random.randn(block.ffn.w1_params.size) * scale)
block.ffn.w2_params.set_values(np.random.randn(block.ffn.w2_params.size) * scale)
else:
# Single block approach
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:
if not input_ids:
raise ValueError("input_ids is empty.")
for idx in input_ids:
if idx < 0 or idx >= self.vocab_size:
raise ValueError(f"Input id {idx} out of range.")
# For language modeling, let's just consider the last token embedding.
x = self.embeddings[input_ids[-1]]
if self.blocks:
# Multi-block approach
for block in self.blocks:
x = block.forward(x, use_residual=use_residual)
else:
# Single-block approach
attn_output_query = self.attn.forward(x, mode='query')
attn_output_key = self.attn.forward(x, mode='key')
attn_output_value = self.attn.forward(x, mode='value')
attn_output_out = self.attn.forward(x, mode='out')
attn_output = attn_output_query + attn_output_key + attn_output_value + attn_output_out
if use_residual:
x = normalize_vector(x + attn_output)
else:
x = attn_output
ffn_output_w1 = self.ffn.forward(x, layer='w1')
ffn_output_w2 = self.ffn.forward(ffn_output_w1, layer='w2')
if use_residual:
x = normalize_vector(x + ffn_output_w2)
else:
x = ffn_output_w2
logits = self.W_out @ x
return logits
def get_all_parameters(self) -> np.ndarray:
if self.blocks:
# Multi-block approach
block_params = []
for block in self.blocks:
block_params.append(block.get_all_parameters())
stacked_block_params = np.concatenate(block_params)
else:
stacked_block_params = np.concatenate([
self.attn.get_all_parameters(),
self.ffn.get_all_parameters()
])
return np.concatenate([
stacked_block_params,
self.W_proj.flatten(),
self.W_out.flatten()
])
def set_all_parameters(self, params: np.ndarray):
# Compute expected sizes
if self.blocks:
# Multi-block approach
total_block_params = 0
block_sizes = []
for block in self.blocks:
size_block = len(block.get_all_parameters())
block_sizes.append(size_block)
total_block_params += size_block
proj_size = self.embed_dim * self.hidden_dim
out_size = self.vocab_size * self.embed_dim
expected = total_block_params + proj_size + out_size
if params.shape[0] != expected:
raise ValueError(f"Parameter mismatch. Expected {expected}, got {params.shape[0]}.")
# Assign block parameters
offset = 0
for i, block in enumerate(self.blocks):
block_param_size = block_sizes[i]
block_params = params[offset: offset + block_param_size]
block.set_all_parameters(block_params)
offset += block_param_size
# Remainder for W_proj and W_out
self.W_proj = params[offset: offset + proj_size].reshape(self.embed_dim, self.hidden_dim)
offset += proj_size
self.W_out = params[offset: offset + out_size].reshape(self.vocab_size, self.embed_dim)
else:
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
proj_size = self.embed_dim * self.hidden_dim
out_size = self.vocab_size * self.embed_dim
expected = attn_size + ffn_size + proj_size + out_size
if params.shape[0] != expected:
raise ValueError(f"Parameter mismatch. Expected {expected}, got {params.shape[0]}.")
self.attn.set_all_parameters(params[:attn_size])
self.ffn.set_all_parameters(params[attn_size:attn_size+ffn_size])
self.W_proj = params[attn_size+ffn_size:attn_size+ffn_size+proj_size].reshape(self.embed_dim, self.hidden_dim)
self.W_out = params[attn_size+ffn_size+proj_size:].reshape(self.vocab_size, self.embed_dim)
def to_dict(self) -> dict:
model_dict = {
"vocab_size": self.vocab_size,
"embed_dim": self.embed_dim,
"num_heads": self.num_heads,
"hidden_dim": self.hidden_dim,
"embeddings": self.embeddings.tolist(),
"W_proj": self.W_proj.tolist(),
"W_out": self.W_out.tolist(),
"version": "4.0",
"num_blocks": self.num_blocks
}
if self.blocks:
# Multi-block approach
block_dicts = []
for block in self.blocks:
block_dicts.append(block.to_dict())
model_dict["blocks"] = block_dicts
else:
# Single-block approach
model_dict["attn"] = self.attn.to_dict()
model_dict["ffn"] = self.ffn.to_dict()
return model_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):
raise ValueError("Model config mismatch.")
self.embeddings = np.array(d["embeddings"], dtype=np.float32)
self.W_proj = np.array(d["W_proj"], dtype=np.float32)
self.W_out = np.array(d["W_out"], dtype=np.float32)
self.num_blocks = d.get("num_blocks", 1)
# If multi-block data is present, rebuild blocks
if self.num_blocks > 1 and "blocks" in d:
self.blocks = []
for i, block_info in enumerate(d["blocks"]):
block_prefix = f"layer{i+1}"
new_block = QuantumTransformerBlock(
embed_dim=self.embed_dim,
num_heads=self.num_heads,
hidden_dim=self.hidden_dim,
sim_method='cpu', # can set or load from the saved dict if needed
num_threads=1,
block_prefix=block_prefix,
enable_logging=False
)
new_block.from_dict(block_info)
self.blocks.append(new_block)
else:
# Single-block approach
self.attn.from_dict(d["attn"])
self.ffn.from_dict(d["ffn"])
def save_model(self, save_path: str):
model_dict = self.to_dict()
with open(save_path, 'w') as f:
json.dump(model_dict, f)
logging.info(f"Model saved to {save_path}")
def load_model(self, load_path: str):
if not os.path.exists(load_path):
raise FileNotFoundError(f"File {load_path} does not exist.")
with open(load_path, 'r') as f:
model_dict = json.load(f)
if "version" not in model_dict or model_dict["version"] != "4.0":
raise ValueError("Unsupported model version.")
self.from_dict(model_dict)
logging.info(f"Model loaded from {load_path}")
def shift_parameter(self, param_index: int, shift: float):
shifted_params = self.get_all_parameters()
shifted_params[param_index] += shift
self.set_all_parameters(shifted_params)
def unshift_parameter(self, param_index: int, shift: float):
self.shift_parameter(param_index, -shift)
def create_synthetic_dataset(vocab_size: int, num_samples: int = 500) -> Tuple[np.ndarray, np.ndarray]:
X = np.random.randint(4, vocab_size, size=(num_samples,))
Y = np.random.randint(4, vocab_size, size=(num_samples,))
return X, Y
def load_real_dataset(file_path: str, vocab_size: int) -> Tuple[np.ndarray, np.ndarray, Dict[str, int]]:
if not os.path.exists(file_path):
raise FileNotFoundError(f"File {file_path} does not exist.")
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
tokens = word_tokenize(text.lower())
freq = defaultdict(int)
for token in tokens:
freq[token] += 1
special_tokens = ["<PAD>", "<START>", "<END>", "<UNK>"]
sorted_tokens = sorted(freq.items(), key=lambda x: x[1], reverse=True)
token_to_id = {token: idx for idx, token in enumerate(special_tokens)}
for token, _ in sorted_tokens:
if len(token_to_id) >= vocab_size:
break
if token not in token_to_id:
token_to_id[token] = len(token_to_id)
id_to_token = {idx: token for token, idx in token_to_id.items()}
X, Y_ids = [], []
for i in range(len(tokens)-1):
current_token = tokens[i]
next_token = tokens[i+1]
X.append(token_to_id.get(current_token, token_to_id["<UNK>"]))
Y_ids.append(token_to_id.get(next_token, token_to_id["<UNK>"]))
Y = np.array(Y_ids, dtype=np.int32)
return np.array(X), Y, token_to_id
def cross_entropy_loss(logits: np.ndarray, target: int) -> float:
logits = logits - np.max(logits)
softmax = np.exp(logits) / np.sum(np.exp(logits))
softmax = np.clip(softmax, 1e-12, 1.0)
return -np.log(softmax[target])
def perplexity(logits: np.ndarray, target: int) -> float:
ce_loss = cross_entropy_loss(logits, target)
return np.exp(ce_loss)
def bleu_score(reference: List[str], hypothesis: List[str], max_n: int = 4) -> float:
from collections import Counter
import math
weights = [1.0 / max_n] * max_n
reference_counts = [Counter([tuple(reference[i:i+n]) for i in range(len(reference)-n+1)]) for n in range(1, max_n+1)]
hypothesis_counts = [Counter([tuple(hypothesis[i:i+n]) for i in range(len(hypothesis)-n+1)]) for n in range(1, max_n+1)]
precisions = []
for ref_count, hyp_count in zip(reference_counts, hypothesis_counts):
overlap = hyp_count & ref_count
precision = sum(overlap.values()) / max(sum(hyp_count.values()), 1e-12)
precisions.append(precision)
ref_length = len(reference)
hyp_length = len(hypothesis)
if hyp_length == 0:
bp = 0
elif hyp_length > ref_length:
bp = 1
else:
bp = math.exp(1 - ref_length / hyp_length)
if min(precisions) > 0:
log_precisions = [w * math.log(p) for w, p in zip(weights, precisions)]
geo_mean = math.exp(sum(log_precisions))
else:
geo_mean = 0
return bp * geo_mean
def compute_gradient_for_parameter(args):
(vocab_size, embed_dim, num_heads, hidden_dim,
sim_method, num_threads, X, Y, original_params, i,
use_advanced_ansatz, use_data_reuploading, num_blocks) = args
try:
model = QuantumLanguageModel(
vocab_size=vocab_size,
embed_dim=embed_dim,
num_heads=num_heads,
hidden_dim=hidden_dim,
sim_method=sim_method,
num_threads=num_threads,
enable_logging=False,
use_advanced_ansatz=use_advanced_ansatz,
use_data_reuploading=use_data_reuploading,
num_blocks=num_blocks
)
model.set_all_parameters(original_params)
shift = np.pi / 2
model.shift_parameter(i, shift)
loss_plus = np.mean([cross_entropy_loss(model.forward([x], use_residual=True), y) for x, y in zip(X, Y)])
model.unshift_parameter(i, shift)
model.shift_parameter(i, -shift)
loss_minus = np.mean([cross_entropy_loss(model.forward([x], use_residual=True), y) for x, y in zip(X, Y)])
model.unshift_parameter(i, -shift)
gradient = (loss_plus - loss_minus) / 2.0
return i, gradient
except Exception:
traceback.print_exc()
return i, 0.0
def compute_gradients_parallel(model: QuantumLanguageModel,
X: np.ndarray,
Y: np.ndarray,
num_processes: int = 1,
progress_callback=None,
batch_shifts: bool = False) -> np.ndarray:
"""
Computes gradients in parallel using parameter-shift rule.
If batch_shifts=True, an advanced mechanism could be implemented here
for simultaneously shifting parameters. Currently, we keep the
default single-parameter shift approach for compatibility.
"""
gradients = np.zeros_like(model.get_all_parameters())
original_params = model.get_all_parameters().copy()
total_params = len(original_params)
block_size = 100 # Reduced block size for more frequent updates
if batch_shifts:
# Placeholder for advanced parallel shift approach (not implemented here):
pass
args_list = [
(
model.vocab_size,
model.embed_dim,
model.num_heads,
model.hidden_dim,
model.attn.sim_method if not model.blocks else model.blocks[0].attn.sim_method,
model.attn.num_threads if not model.blocks else model.blocks[0].attn.num_threads,