Skip to content

Commit

Permalink
Update Qelm-Quantum.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Inserian authored Dec 22, 2024
1 parent 1c7cb96 commit 5a4c477
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions Quantum/Qelm-Quantum.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
from tkinter import ttk
import multiprocessing # Added import

# Ensure Qiskit is installed correctly
# Ensure Qiskit is called correctly
try:
from qiskit import QuantumCircuit
from qiskit import QuantumCircuit, transpile # Added transpile import
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService # Removed Sampler import
from qiskit.quantum_info import SparsePauliOp
Expand Down Expand Up @@ -168,8 +168,6 @@ def simulate(self, circuit: QuantumCircuit) -> np.ndarray:
raise ValueError("Service is not initialized.")

backend_name = self.initialize_backend()

# Retrieve the backend object
backend = self.service.backend(backend_name)

# Initialize BackendSamplerV2 with the backend
Expand All @@ -182,15 +180,18 @@ def simulate(self, circuit: QuantumCircuit) -> np.ndarray:
if self.enable_logging:
logging.info(f"QuantumLayerBase: Running sampler on backend '{backend_name}'.")

# **Fix**: Transpile the circuit before running to ensure supported instructions for qubit cross instructions to qpu's
transpiled_circuit = transpile(circuit, backend=backend)

# Run the sampler
result = sampler.run([circuit]) # Fixed: Pass circuits as positional arguments
job_result = result.result() # Retrieve the result object
result = sampler.run([transpiled_circuit])
job_result = result.result()
counts = job_result.quasi_dists[0].get_counts()

# Convert counts to probability distribution
total = sum(counts.values())
probabilities = np.array([
counts.get(format(i, f'0{int(np.ceil(np.log2(len(counts))) or 1)}b'), 0)
counts.get(format(i, f'0{int(np.ceil(np.log2(len(counts))) or 1)}b'), 0)
for i in range(len(counts))
])
probabilities = probabilities / total
Expand Down Expand Up @@ -393,8 +394,8 @@ def set_all_parameters(self, params: np.ndarray):
"""
attn_size = self.attn.get_all_parameters().size
ffn_size = self.ffn.get_all_parameters().size
proj_size = self.embed_dim * self.hidden_dim # e.g., (256 * 512) = 131072
out_size = self.vocab_size * self.embed_dim # e.g., (10000 * 256) = 2560000
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:
Expand Down Expand Up @@ -805,7 +806,7 @@ def __init__(self, master):
try:
self.master = master
master.title("QELM Trainer - Enhanced")
master.geometry("1600x1000") # Increased window size for better layout
master.geometry("1600x1000") # Increased window size for better layout *edit based on your screen size*
master.resizable(False, False)

# Default Model parameters
Expand All @@ -815,7 +816,7 @@ def __init__(self, master):
self.hidden_dim = 512 # Default hidden dimension
self.sim_method = 'simulator'
self.num_threads = min(8, multiprocessing.cpu_count()) # Adjusted for higher model complexity
self.api_token = "" # Initialize API token as empty string
self.api_token = "" # Initialize API token as empty string (Don't store your API here, pop it in the box and let it remain hidden).

self.model = QuantumLanguageModel(
self.vocab_size,
Expand Down Expand Up @@ -846,7 +847,7 @@ def __init__(self, master):
else:
self.process = None

# Configure GUI appearance
# Configure GUI appearance to whatever suits your mood (Please keep gradio away from my code).
self.master.configure(bg="#2C3E50")
style = ttk.Style(self.master)
style.theme_use('clam')
Expand Down Expand Up @@ -1184,7 +1185,7 @@ def train_model(self):
messagebox.showerror("Invalid Input", "Please enter valid positive integers for model parameters and epochs, and a positive float for learning rate.")
return

sim_method = self.backend_var.get() # Updated line
sim_method = self.backend_var.get()
num_threads = self.num_threads_var.get()
max_threads = multiprocessing.cpu_count()
if num_threads > max_threads:
Expand Down Expand Up @@ -1218,7 +1219,7 @@ def train_model(self):
messagebox.showerror("Dataset Load Error", err_msg)
return
else:
X, Y = create_synthetic_dataset(vocab_size, num_samples=500) # Increased samples for better training
X, Y = create_synthetic_dataset(vocab_size, num_samples=500) # Can be changed but utilizing a real dataset is best
self.X = X
self.Y = Y
self.log_train("Using synthetic dataset for training.\n")
Expand All @@ -1233,7 +1234,7 @@ def train_model(self):
sim_method=sim_method,
num_threads=num_threads,
enable_logging=True,
api_token=self.api_token # Pass the API token
api_token=self.api_token
)
self.optimizer = AdamOptimizer(self.model.get_all_parameters(), lr=lr)
self.log_train("Model re-initialized with new parameters.\n")
Expand Down Expand Up @@ -1349,7 +1350,7 @@ def save_model(self):
"""
try:
save_path = filedialog.asksaveasfilename(title="Save Model", defaultextension=".qelm",
filetypes=[("QELM Files", "*.qelm"), ("All Files", "*.*")])
filetypes=[("QELM Files", "*.qelm", "*.qlm"), ("All Files", "*.*")])
if save_path:
self.model.save_model(save_path)
if self.token_to_id:
Expand All @@ -1369,7 +1370,7 @@ def load_model(self):
"""
try:
load_path = filedialog.askopenfilename(title="Load Model",
filetypes=[("QELM Files", "*.qelm"), ("All Files", "*.*")])
filetypes=[("QELM Files", "*.qelm", "*.qlm"), ("All Files", "*.*")])
if load_path:
self.model.load_model(load_path)
token_map_path = load_path.replace(".qelm", "_token_map.json")
Expand Down

0 comments on commit 5a4c477

Please sign in to comment.