BoltzmannEntropy commited on
Commit
5ebbc77
·
1 Parent(s): 41e6c53
Files changed (9) hide show
  1. .gitattributes +0 -35
  2. .gitignore +4 -0
  3. Dockerfile +3 -21
  4. Q_app_llm_pairs_gen.py +199 -0
  5. Q_llm_prompts.py +726 -0
  6. Q_quantum_utils.py +625 -0
  7. README.md +88 -7
  8. app.py +0 -255
  9. qlmmi-detailed-flowchart.jpg +0 -0
.gitattributes DELETED
@@ -1,35 +0,0 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ archive
2
+ __pycache__
3
+ *.duckdb
4
+ *.parquet
Dockerfile CHANGED
@@ -1,10 +1,3 @@
1
- # Dockerfile customized for deployment on HuggingFace Spaces platform
2
-
3
- # -- The Dockerfile has been tailored specifically for use on HuggingFace.
4
- # -- It implies that certain modifications or optimizations have been made with HuggingFace's environment in mind.
5
- # -- It uses "HuggingFace Spaces" to be more specific about the target platform.
6
-
7
- # FROM pytorch/pytorch:2.2.1-cuda12.1-cudnn8-devel
8
  FROM pytorch/pytorch:2.4.0-cuda12.1-cudnn9-devel
9
  # FOR HF
10
 
@@ -38,7 +31,6 @@ ENV TZ=Asia/Dubai
38
  RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
39
 
40
 
41
-
42
  RUN useradd -m -u 1000 user
43
 
44
  RUN apt-get update && apt-get install -y sudo && \
@@ -49,7 +41,6 @@ ENV HOME=/home/user \
49
  PATH=/home/user/.local/bin:$PATH
50
 
51
  RUN mkdir $HOME/app
52
- RUN mkdir $HOME/app/test_images
53
 
54
  # WORKDIR $HOME/app
55
 
@@ -58,31 +49,20 @@ RUN chown -R user:user $HOME/app
58
  USER user
59
  WORKDIR $HOME/app
60
 
61
- RUN python -m pip install qwen-vl-utils
62
- RUN python -m pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu122 mlc-ai-nightly-cu122
63
- #python -m pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cpu mlc-ai-nightly-cpu
64
 
65
  RUN python3 -m pip install chromadb db-sqlite3 auto-gptq exllama sqlalchemy
66
  WORKDIR $HOME/app
67
- RUN git clone https://github.com/casper-hansen/AutoAWQ
68
- WORKDIR $HOME/app/AutoAWQ/
69
- RUN python3 -m pip install -e .
70
- WORKDIR $HOME/app
71
  # ENV FLASH_ATTENTION_FORCE_BUILD=TRUE
72
  RUN python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
73
  RUN python -m pip install accelerate diffusers datasets timm flash-attn==2.6.1 gradio
74
 
75
  RUN python3 -m pip install --no-deps optimum
76
- RUN python3 -m pip install --no-deps autoawq>=0.1.8
77
 
78
  #This seems to be a must : Intel Extension for PyTorch 2.4 needs to work with PyTorch 2.4.*, but PyTorch 2.2.2 is
79
  RUN python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
80
- RUN python3 -m pip install -U accelerate
81
  RUN python3 -m pip install -U git+https://github.com/huggingface/transformers
82
 
83
- WORKDIR $HOME/app
84
- COPY --chown=user:user app.py .
85
- # COPY --chown=user:user test_images /home/user/app/test_images
86
 
87
  ENV PYTHONUNBUFFERED=1 GRADIO_ALLOW_FLAGGING=never GRADIO_NUM_PORTS=1 GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860 SYSTEM=spaces
88
  RUN python3 -m pip install pennylane sympy pennylane-qiskit duckdb qutip qutip-qip
@@ -91,3 +71,5 @@ WORKDIR $HOME/app
91
  EXPOSE 8097 7842 8501 8000 6666 7860
92
 
93
  CMD ["python", "app.py"]
 
 
 
 
 
 
 
 
 
 
1
  FROM pytorch/pytorch:2.4.0-cuda12.1-cudnn9-devel
2
  # FOR HF
3
 
 
31
  RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
32
 
33
 
 
34
  RUN useradd -m -u 1000 user
35
 
36
  RUN apt-get update && apt-get install -y sudo && \
 
41
  PATH=/home/user/.local/bin:$PATH
42
 
43
  RUN mkdir $HOME/app
 
44
 
45
  # WORKDIR $HOME/app
46
 
 
49
  USER user
50
  WORKDIR $HOME/app
51
 
 
 
 
52
 
53
  RUN python3 -m pip install chromadb db-sqlite3 auto-gptq exllama sqlalchemy
54
  WORKDIR $HOME/app
 
 
 
 
55
  # ENV FLASH_ATTENTION_FORCE_BUILD=TRUE
56
  RUN python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
57
  RUN python -m pip install accelerate diffusers datasets timm flash-attn==2.6.1 gradio
58
 
59
  RUN python3 -m pip install --no-deps optimum
 
60
 
61
  #This seems to be a must : Intel Extension for PyTorch 2.4 needs to work with PyTorch 2.4.*, but PyTorch 2.2.2 is
62
  RUN python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
63
+ RUN python3 -m pip install -U accelerate bitsandbytes
64
  RUN python3 -m pip install -U git+https://github.com/huggingface/transformers
65
 
 
 
 
66
 
67
  ENV PYTHONUNBUFFERED=1 GRADIO_ALLOW_FLAGGING=never GRADIO_NUM_PORTS=1 GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860 SYSTEM=spaces
68
  RUN python3 -m pip install pennylane sympy pennylane-qiskit duckdb qutip qutip-qip
 
71
  EXPOSE 8097 7842 8501 8000 6666 7860
72
 
73
  CMD ["python", "app.py"]
74
+
75
+ # mlc-llm server HF://mlc-ai/Llama-3.2-1B-Instruct-q4f16_1-MLC
Q_app_llm_pairs_gen.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Quantum Physics Problem Generator
3
+ Shlomo Kashani
4
+
5
+ Description:
6
+ ------------
7
+ This module is part of the QuantumLLMInstruct system, designed to generate and solve quantum physics problems
8
+ using advanced Large Language Models (LLMs). It utilizes a multi-stage pipeline for problem generation,
9
+ solution generation, and database management.
10
+
11
+ Core Functionalities:
12
+ ---------------------
13
+ 1. **Problem Generation**:
14
+ - Generates quantum physics problems in LaTeX format using LLMs.
15
+ - Supports domain-specific problem generation across multiple quantum fields.
16
+
17
+ 2. **Solution Generation**:
18
+ - Provides step-by-step LaTeX solutions for the generated problems using a second LLM.
19
+
20
+ 3. **Data Management**:
21
+ - Stores generated problems and solutions in DuckDB and Parquet files.
22
+ - Enables exporting data in Parquet format for scalability and compatibility.
23
+
24
+ 4. **Gradio Interface**:
25
+ - A user-friendly interface to interact with the system, including problem generation,
26
+ solution generation, and database exploration.
27
+
28
+ 5. **Hugging Face Integration**:
29
+ - Supports visualization and interaction with the dataset on the Hugging Face platform.
30
+
31
+ Main Components:
32
+ ----------------
33
+ - **initialize_duckdb() / initialize_parquet()**: Initializes the database schema.
34
+ - **generate_multiple_problems()**: Generates multiple problems for the selected quantum domains.
35
+ - **generate_solutions()**: Solves unsolved problems in the database.
36
+ - **export_parquet()**: Exports the database to a Parquet file for external use.
37
+
38
+ Dependencies:
39
+ -------------
40
+ - Python 3.7+
41
+ - Transformers: `transformers`
42
+ - DuckDB: `duckdb`
43
+ - Gradio: `gradio`
44
+ - Pandas: `pandas`
45
+ """
46
+ import gradio as gr
47
+
48
+ from Q_llm_prompts import *
49
+ from Q_quantum_utils import *
50
+
51
+ initialize_duckdb()
52
+
53
+ description = """
54
+ This demo showcases **[QuantumLLMInstruct](https://huggingface.co/datasets/BoltzmannEntropy/QuantumLLMInstruct/)**
55
+ <img src="https://huggingface.co/datasets/BoltzmannEntropy/QuantumLLMInstruct/resolve/main/qlmmi-detailed-flowchart.jpg" alt="The Pipeline" width="70%" align="center" />
56
+ ## 🚀 Pipeline:
57
+ 1. **📝 Problem Generation:** The Qwen model generates a user instruction.
58
+ 2. **💬 Solution Generation:** The Qwen model generates a response to this instruction.
59
+ """
60
+
61
+ # Gradio app
62
+ with gr.Blocks() as app:
63
+ """
64
+ Main Gradio application block defining the QuantumLLMInstruct pipeline.
65
+ Provides tabs for viewing datasets, generating problems, generating solutions,
66
+ and exporting the database.
67
+ """
68
+ gr.Markdown("# QuantumLLMInstruct: A 500k LLM Instruction-Tuning Dataset with Problem-Solution Pairs for Quantum Computing.")
69
+
70
+ with gr.Tab("View HF DB"):
71
+ """
72
+ Tab for displaying the Hugging Face QuantumLLMInstruct dataset.
73
+ Embeds a viewer for exploring the dataset hosted on Hugging Face.
74
+ """
75
+ gr.Markdown("### Generated Dataset")
76
+ gr.HTML("""<iframe
77
+ src="https://huggingface.co/datasets/BoltzmannEntropy/QuantumLLMInstruct/embed/viewer"
78
+ frameborder="0"
79
+ width="100%"
80
+ height="560px"
81
+ ></iframe>""")
82
+
83
+ with gr.Tab("LLM stage 1 model: Generate Problems"):
84
+ """
85
+ Tab for generating quantum physics problems using the Qwen model.
86
+ Allows users to select models, choose domains, and specify the number of problems to generate.
87
+ """
88
+ model_selector = gr.Dropdown(
89
+ choices=model_options,
90
+ value=model_options[0],
91
+ label="Select Qwen Model"
92
+ )
93
+ reload_button = gr.Button("Reload Model")
94
+ reload_status = gr.Textbox(label="Model Status", interactive=False)
95
+
96
+ generate_button = gr.Button("🚀 Generate Instructions For the Pair")
97
+ result_output = gr.Textbox(label="Generated Problems", interactive=False)
98
+ num_pairs = gr.Radio(choices=[1, 5, 50, 200, 2000, 20000, 200000], value=5, label="Number of Problems")
99
+
100
+ domain_selector = gr.CheckboxGroup(
101
+ choices=list(quantum_problem_domains.keys()),
102
+ value=list(quantum_problem_domains.keys()),
103
+ label="Select Domain Types"
104
+ )
105
+
106
+ reload_button.click(
107
+ reload_model,
108
+ inputs=[model_selector],
109
+ outputs=[reload_status]
110
+ )
111
+
112
+ def generate_and_display(num_pairs, selected_domains):
113
+ """
114
+ Generates multiple quantum problems based on user inputs.
115
+
116
+ Args:
117
+ num_pairs (int): Number of problems to generate.
118
+ selected_domains (list): Selected quantum domains for problem generation.
119
+
120
+ Returns:
121
+ str: Status message confirming successful problem generation.
122
+ """
123
+ generate_multiple_problems(num_pairs, selected_domains)
124
+ return "Problems generated successfully."
125
+
126
+ generate_button.click(
127
+ generate_and_display,
128
+ inputs=[num_pairs, domain_selector],
129
+ outputs=[result_output]
130
+ )
131
+
132
+ with gr.Tab("LLM Stage 2: Generate Solutions"):
133
+ """
134
+ Tab for generating solutions to the quantum problems using the Qwen solution models.
135
+ """
136
+ generate_solutions_button = gr.Button("🚀 Generate Responses for the Pair")
137
+ solutions_status = gr.Textbox(label="Solution Generation Status", interactive=False)
138
+
139
+ solutions_model_selector = gr.Dropdown(
140
+ choices=solutions_model_options,
141
+ value=solutions_model_options[4],
142
+ label="Select Solution Model"
143
+ )
144
+
145
+ generate_solutions_button.click(
146
+ generate_solutions,
147
+ inputs=[solutions_model_selector],
148
+ outputs=[solutions_status]
149
+ )
150
+
151
+ with gr.Tab("View instruction-pairs DB"):
152
+ """
153
+ Tab for viewing data stored in the DuckDB database.
154
+ Provides an HTML table viewer for summarized and detailed data exploration.
155
+ """
156
+ summary_output = gr.HTML()
157
+ view_button = gr.Button("View Data")
158
+ db_output_display = gr.HTML()
159
+
160
+ view_button.click(load_summary_from_duckdb, inputs=None, outputs=summary_output)
161
+
162
+ def view_db_data():
163
+ """
164
+ Loads and formats problems stored in the DuckDB database for display.
165
+
166
+ Returns:
167
+ str: HTML representation of the database content or a message indicating no data.
168
+ """
169
+ df = load_problems_from_duckdb()
170
+ if df.empty:
171
+ return "<p>No data found in the DuckDB database.</p>"
172
+ html_table = df.to_html(index=False, escape=False)
173
+ return html_table
174
+
175
+ view_button.click(
176
+ view_db_data,
177
+ inputs=None,
178
+ outputs=[db_output_display]
179
+ )
180
+
181
+ with gr.Tab("Export Parquet"):
182
+ """
183
+ Tab for exporting the DuckDB database into a Parquet file format.
184
+ Enables efficient data sharing and downstream analysis.
185
+ """
186
+ gr.Markdown("### Export DuckDB Data to Parquet Format")
187
+ db_file_input = gr.Textbox(label="Database File Path", value="quantum_problems.duckdb")
188
+ export_button = gr.Button("Export Data")
189
+ export_status = gr.Textbox(label="Export Status", interactive=False)
190
+
191
+ export_button.click(
192
+ export_parquet,
193
+ inputs=[db_file_input],
194
+ outputs=[export_status]
195
+ )
196
+
197
+ gr.Markdown(description)
198
+
199
+ app.launch()
Q_llm_prompts.py ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+
3
+ quantum_problem_domains = {
4
+ "QASM Generation": {
5
+ "description": "Generate a quantum physics problem involving generating executable QASM code in OpenQASM for a given quantum circuit.",
6
+ "template": """{Problem:} Design a quantum circuit that prepares the Bell state \\( |\\phi^+\\rangle = \\frac{1}{\\sqrt{2}}(|00\\rangle + |11\\rangle) \\) and generate the corresponding QASM code.
7
+ {Domain:} QASM GENERATION"""
8
+ },
9
+ "Quantum Hamiltonians": {
10
+ "description": "Generate a quantum physics problem such as Hamiltonian time evolution and ground-state energy calculations.",
11
+ "template": """{Problem:} Given a three-qubit system with the Hamiltonian:
12
+ \\[
13
+ H = J (\\sigma_1^z \\sigma_2^z + \\sigma_2^z \\sigma_3^z) - h \\sum_{i=1}^3 \\sigma_i^x
14
+ \\]
15
+ where \\( J = 1.5 \\) and \\( h = 0.8 \\), determine the ground-state energy.
16
+ {Domain:} QUANTUM HAMILTONIANS"""
17
+ },
18
+ "Yang-Baxter Solvability": {
19
+ "description": "Generate a quantum physics problem focused on determining if a quantum model is Yang-Baxter solvable.",
20
+ "template": """{Problem:} Verify whether the following 2x2 R-matrix satisfies the Yang-Baxter equation:
21
+ \\[
22
+ R = \\begin{bmatrix}
23
+ 1 & 0 & 0 & 0 \\\\
24
+ 0 & 0 & 1 & 0 \\\\
25
+ 0 & 1 & 0 & 0 \\\\
26
+ 0 & 0 & 0 & 1
27
+ \\end{bmatrix}.
28
+ \\]
29
+ {Domain:} YANG-BAXTER SOLVABILITY"""
30
+ },
31
+ "Trotter-Suzuki Decomposition": {
32
+ "description": "Generate a quantum physics problem involving the Trotter-Suzuki decomposition of Hamiltonians.",
33
+ "template": """{Problem:} Perform a first-order Trotter-Suzuki decomposition for the Hamiltonian:
34
+ \\[
35
+ H = H_A + H_B, \\quad H_A = \\sigma_1^x \\sigma_2^x, \\quad H_B = \\sigma_1^z \\sigma_2^z.
36
+ \\]
37
+ Write the decomposition for \\( e^{-iHt} \\) up to time \\( t = 1 \\).
38
+ {Domain:} TROTTER-SUZUKI DECOMPOSITION"""
39
+ },
40
+ "Lindblad Dynamics": {
41
+ "description": "Generate a quantum physics problem related to simulating the dynamics of a qubit interacting with a thermal bath using the Lindblad equation.",
42
+ "template": """{Problem:} Simulate the time evolution of a single qubit under the Lindblad master equation:
43
+ \\[
44
+ \\frac{d\\rho}{dt} = -i[H, \\rho] + \\sum_k \\left(L_k \\rho L_k^\\dagger - \\frac{1}{2} \\{L_k^\\dagger L_k, \\rho\\}\\right),
45
+ \\]
46
+ where \\( H = \\frac{\\omega}{2} \\sigma^z \\) and \\( L_k = \\sqrt{\\gamma} \\sigma^- \\). Calculate \\( \\rho(t) \\) for \\( t = 1 \\).
47
+ {Domain:} LINDBLAD DYNAMICS"""
48
+ },
49
+ "Randomized Circuits Optimization": {
50
+ "description": "Generate a quantum physics problem that requires the optimization of a randomized quantum circuit to minimize error rates.",
51
+ "template": """{Problem:} Design a randomized quantum circuit of 5 qubits with a depth of 10, and propose a cost function to optimize the fidelity of the output state.
52
+ {Domain:} RANDOMIZED CIRCUITS OPTIMIZATION"""
53
+ },
54
+ "Quantum Phase Estimation": {
55
+ "description": "Generate a quantum physics problem involving the implementation of quantum phase estimation for an eigenvalue calculation.",
56
+ "template": """{Problem:} Design a quantum phase estimation circuit to determine the eigenvalue \\( \\phi \\) of a unitary operator \\( U \\) for \\( U |\\psi\\rangle = e^{2\\pi i \\phi} |\\psi\\rangle \\). Provide an example with \\( U = \\text{diag}(1, e^{2\\pi i / 4}) \\).
57
+ {Domain:} QUANTUM PHASE ESTIMATION"""
58
+ },
59
+ "Cluster States Verification": {
60
+ "description": "Generate a quantum physics problem focusing on the preparation and verification of cluster states for measurement-based quantum computation.",
61
+ "template": """{Problem:} Prepare a four-qubit cluster state using Hadamard gates and controlled-Z operations. Verify the entanglement of the state using stabilizer measurements.
62
+ {Domain:} CLUSTER STATES VERIFICATION"""
63
+ },
64
+ "VQE Analysis": {
65
+ "description": "Generate a quantum physics problem involving the construction and evaluation of a variational quantum eigensolver (VQE) Ansatz for a specific molecular Hamiltonian.",
66
+ "template": """{Problem:} Construct a variational quantum eigensolver (VQE) Ansatz to approximate the ground-state energy of the H2 molecule. Use the Hamiltonian:
67
+ \\[
68
+ H = g (\\sigma_1^z \\sigma_2^z) + J (\\sigma_1^x + \\sigma_2^x),
69
+ \\]
70
+ where \\( g = 1.0 \\) and \\( J = 0.5 \\). Describe the optimization process.
71
+ {Domain:} VQE ANALYSIS"""
72
+ },
73
+ "Quantum Algorithm Development": {
74
+ "description": "Develop a quantum algorithm to solve a complex problem, such as integer factorization or database search, using principles of quantum computing.",
75
+ "template": """{Problem:} Develop a quantum algorithm using Grover's search to find a marked item in an unsorted database of size 8. Provide the circuit and explain the amplification steps.
76
+ {Domain:} QUANTUM ALGORITHM DEVELOPMENT"""
77
+ },
78
+ "Entanglement and Quantum Information Theory": {
79
+ "description": "Generate a quantum physics problem that explores the properties and applications of entangled states within quantum information theory frameworks.",
80
+ "template": """{Problem:} Demonstrate the violation of Bell's inequality using the CHSH game. Compute the quantum value for the CHSH parameter given a maximally entangled state.
81
+ {Domain:} ENTANGLEMENT AND QUANTUM INFORMATION THEORY"""
82
+ },
83
+ "Quantum Error Correction": {
84
+ "description": "Create a quantum physics problem centered on designing and implementing error correction codes to protect qubits from decoherence and other quantum noise sources.",
85
+ "template": """{Problem:} Design a quantum error correction scheme using the Shor code to protect against arbitrary single-qubit errors. Show the encoding and decoding procedures.
86
+ {Domain:} QUANTUM ERROR CORRECTION"""
87
+ },
88
+ "Semiclassical Quantum Simulation": {
89
+ "description": "Generate a quantum physics problem that involves simulating the dynamics of a quantum system using semiclassical methods, where some degrees of freedom are treated classically while others are treated quantum mechanically.",
90
+ "template": """{Problem:} Simulate a particle in a double-well potential using semiclassical methods, treating position classically and momentum quantum mechanically. Compute the tunneling rate.
91
+ {Domain:} SEMICLASSICAL QUANTUM SIMULATION"""
92
+ },
93
+ "Quantum Communication Protocols": {
94
+ "description": "Develop a quantum physics problem related to the implementation and evaluation of secure communication protocols such as Quantum Key Distribution (QKD) or superdense coding.",
95
+ "template": """{Problem:} Implement the BB84 protocol for quantum key distribution. Describe the process for generating and verifying the shared secret key.
96
+ {Domain:} QUANTUM COMMUNICATION PROTOCOLS"""
97
+ },
98
+ "Topological Quantum Computing": {
99
+ "description": "Generate a quantum physics problem involving the study of topological quantum computing, focusing on braiding operations in anyonic quasiparticles to achieve fault-tolerant computation.",
100
+ "template": """{Problem:} Illustrate how to braid anyons in a topological quantum computing model to implement a CNOT gate. Explain the fault tolerance of this operation.
101
+ {Domain:} TOPOLOGICAL QUANTUM COMPUTING"""
102
+ },
103
+ "Quantum Complexity Classes": {
104
+ "description": "Formulate a quantum physics problem that investigates the classification of computational problems based on their solvability by quantum algorithms and the complexity of these solutions.",
105
+ "template": """{Problem:} Explain why the factoring problem belongs to the class BQP and discuss the implications of Shor's algorithm in computational complexity theory.
106
+ {Domain:} QUANTUM COMPLEXITY CLASSES"""
107
+ },
108
+ "Quantum Thermodynamics": {
109
+ "description": "Create a quantum physics problem that involves analyzing thermodynamic quantities, such as entropy or work extraction, in isolated or open quantum systems.",
110
+ "template": """{Problem:} Calculate the entropy of a two-qubit thermal state described by the density matrix:
111
+ \\[
112
+ \\rho = \\frac{e^{-\\beta H}}{Z},
113
+ \\]
114
+ where \\( H = \\sigma_1^z \\sigma_2^z \\) and \\( \\beta = 1 \\).
115
+ {Domain:} QUANTUM THERMODYNAMICS"""
116
+ },
117
+ "Interacting Quantum Systems": {
118
+ "description": "Generate a quantum physics problem that studies the dynamics and correlations of interacting quantum systems, potentially including many-body localized phases or critical behavior near phase transitions.",
119
+ "template": """{Problem:} Analyze the dynamics of a three-qubit system governed by the Hamiltonian:
120
+ \\[
121
+ H = J \\sigma_1^z \\sigma_2^z + h (\\sigma_2^x + \\sigma_3^x),
122
+ \\]
123
+ where \\( J = 1.0 \\) and \\( h = 0.5 \\). Determine the time evolution of the initial state \\( |101\\rangle \\).
124
+ {Domain:} INTERACTING QUANTUM SYSTEMS"""
125
+ },
126
+ "Quantum Cryptography": {
127
+ "description": "Generate a quantum physics problem exploring quantum cryptographic protocols like quantum key distribution (QKD) and secure communication methods.",
128
+ "template": """{Problem:} Propose a quantum cryptography protocol for superdense coding to send two classical bits using one qubit. Explain the encoding and decoding processes.
129
+ {Domain:} QUANTUM CRYPTOGRAPHY"""
130
+ },
131
+ "Quantum Channels": {
132
+ "description": "Generate a quantum physics problem that involves the mathematical and physical properties of quantum channels for information transfer.",
133
+ "template": """{Problem:} Analyze the action of the amplitude-damping channel on a single-qubit state. Compute the output state for \\( \\rho = |1\\rangle\\langle 1| \\) with damping probability \\( p = 0.2 \\).
134
+ {Domain:} QUANTUM CHANNELS"""
135
+ },
136
+ "Quantum Fourier Transform": {
137
+ "description": "Develop a problem exploring the implementation and use of the quantum Fourier transform in quantum algorithms.",
138
+ "template": """{Problem:} Implement the quantum Fourier transform for a 3-qubit system. Show the transformation of the computational basis state \\( |101\\rangle \\).
139
+ {Domain:} QUANTUM FOURIER TRANSFORM"""
140
+ },
141
+ "Quantum Machine Learning": {
142
+ "description": "Generate a problem that focuses on the application of quantum circuits to machine learning tasks such as classification or regression.",
143
+ "template": """{Problem:} Design a variational quantum classifier to separate linearly non-separable data points in a 2D space. Describe the Ansatz and the cost function used.
144
+ {Domain:} QUANTUM MACHINE LEARNING"""
145
+ },
146
+ "Quantum State Tomography": {
147
+ "description": "Create a problem requiring the reconstruction of quantum states using measurement data and tomography techniques.",
148
+ "template": """{Problem:} Perform quantum state tomography to reconstruct the density matrix of a two-qubit state given measurement outcomes in the \\( \\sigma^x \\), \\( \\sigma^y \\), and \\( \\sigma^z \\) bases.
149
+ {Domain:} QUANTUM STATE TOMOGRAPHY"""
150
+ },
151
+ "Bell Inequalities and Nonlocality": {
152
+ "description": "Formulate a quantum problem centered on testing Bell inequalities and analyzing quantum nonlocality through experiments.",
153
+ "template": """{Problem:} Test the violation of Bell's inequality using a singlet state \\( |\\psi\\rangle = \\frac{1}{\\sqrt{2}}(|01\\rangle - |10\\rangle) \\). Compute the expected CHSH parameter.
154
+ {Domain:} BELL INEQUALITIES AND NONLOCALITY"""
155
+ },
156
+
157
+ "Diagonalization of Two-Spin Hamiltonian": {
158
+ "description": "Find the eigenvalues of a Hamiltonian for a two-spin system without using a computer.",
159
+ "template": """{Problem:} Consider a Hamiltonian for two spin-1/2s:
160
+ \\[
161
+ H = A \\sigma_1^z \\otimes I_2 + B (\\sigma_1^x \\otimes \\sigma_2^x + \\sigma_1^y \\otimes \\sigma_2^y).
162
+ \\]
163
+ Find all the eigenvalues of \\( H \\) without using a computer.
164
+ {Domain:} DIAGONALIZATION"""
165
+ },
166
+ "Energy Eigenvalues via Perturbation Theory": {
167
+ "description": "Calculate the exact energy eigenvalues of a given Hamiltonian via diagonalization and compare with first-order perturbation theory.",
168
+ "template": """{Problem:} Calculate the exact energy eigenvalues for the Hamiltonian:
169
+ \\[
170
+ H = \\omega_o \\sigma_z + \\omega \\sigma_x.
171
+ \\]
172
+ Perform diagonalization and compare with the results obtained via first-order perturbation theory.
173
+ {Domain:} PERTURBATION THEORY"""
174
+ },
175
+ "Measurement in Plus-Minus Basis": {
176
+ "description": "Explore the measurement probabilities and post-measurement states in the |+⟩, |-⟩ basis.",
177
+ "template": """{Problem:} Consider the state \\( |+\\rangle = \\frac{1}{\\sqrt{2}}(|0\\rangle + |1\\rangle) \\).
178
+ If measured in the \\( |+\\rangle, |−\\rangle \\) basis (where \\( |−\\rangle = \\frac{1}{\\sqrt{2}}(|0\\rangle − |1\\rangle) \\)), calculate the probability of each outcome. Derive the resulting post-measurement state.
179
+ {Domain:} MEASUREMENT BASIS"""
180
+ },
181
+ "Pauli Spin Matrices Analysis": {
182
+ "description": "Analyze properties of Pauli matrices, find linear combinations, and diagonalize matrices.",
183
+ "template": """{Problem:} The Pauli spin matrices are:
184
+ \\[
185
+ \\sigma_1 = \\begin{bmatrix} 0 & 1 \\\\ 1 & 0 \\end{bmatrix}, \\quad
186
+ \\sigma_2 = \\begin{bmatrix} 0 & -i \\\\ i & 0 \\end{bmatrix}, \\quad
187
+ \\sigma_3 = \\begin{bmatrix} 1 & 0 \\\\ 0 & -1 \\end{bmatrix}.
188
+ \\]
189
+ (a) Show that \\( \\sigma_i \\sigma_j = i \\epsilon_{ijk} \\sigma_k \\) (cyclic permutation property). \\\\
190
+ (b) Express the matrix \\( A = \\begin{bmatrix} 5 & 2 + 3i \\\\ 2 - 3i & -3 \\end{bmatrix} \\) as a linear combination of the Pauli matrices and the identity matrix. \\\\
191
+ (c) Diagonalize each of the Pauli matrices and specify the eigenvalues and normalized eigenvectors.
192
+ {Domain:} PAULI MATRICES"""
193
+ },
194
+ "Born's Rule and State Measurement": {
195
+ "description": "Use Born's rule to calculate measurement probabilities and post-measurement states.",
196
+ "template": """{Problem:} For the state:
197
+ \\[
198
+ |\\psi\\rangle = \\frac{1}{\\sqrt{2}} |00\\rangle + \\frac{1}{2} |10\\rangle − \\frac{1}{2} |11\\rangle,
199
+ \\]
200
+ calculate the probability of measuring the second qubit in the state \\( |0\\rangle \\). Use the projective measurement operator \\( M = I \\otimes |0\\rangle \\langle 0| \\). Determine the resulting post-measurement state.
201
+ {Domain:} BORN'S RULE"""
202
+ },
203
+
204
+ "Quantum Hamiltonians": {
205
+ "description": "Generate a quantum physics problem such as Hamiltonian time evolution and ground-state energy calculations.",
206
+ "example": """{Problem:} Calculate the exact energy eigenvalues for the Hamiltonian \\( H = \\omega_o \\sigma_z + \\omega \\sigma_x \\) via diagonalization. Compare with the results from first-order perturbation theory.
207
+ {Domain:} QUANTUM HAMILTONIANS"""
208
+ },
209
+ "Measurement in Qubit Basis": {
210
+ "description": "Generate a problem focusing on the quantum measurement principle in various bases.",
211
+ "example": """{Problem:} Consider the quantum state \\( |\\psi\\rangle = \\frac{1}{\\sqrt{2}} |0\\rangle + \\frac{e^{i\\theta}}{\\sqrt{2}} |1\\rangle \\). Compute the probability of measuring \\( |+\\rangle \\) and \\( |-\\rangle \\) in the \\( \\{|+\\rangle, |-\\rangle\\} \\) basis.
212
+ {Domain:} MEASUREMENT PRINCIPLE"""
213
+ },
214
+ "Density Matrix Analysis": {
215
+ "description": "Generate a problem focusing on density matrix representation and tracing out subsystems.",
216
+ "example": """{Problem:} For the quantum state \\( |\\psi\\rangle = \\frac{|00\\rangle + |11\\rangle}{\\sqrt{2}} \\), compute the density matrix \\( \\rho \\). Trace out the second qubit to determine the reduced density matrix of the first qubit.
217
+ {Domain:} DENSITY MATRIX ANALYSIS"""
218
+ },
219
+ "Spin Chains": {
220
+ "description": "Generate a quantum physics problem on integrable spin chains, such as the Heisenberg or Ising model.",
221
+ "example": """{Problem:} Consider the Heisenberg spin chain with the Hamiltonian:
222
+ \\[
223
+ H = J \\sum_{i} \\sigma_i^z \\sigma_{i+1}^z + h \\sum_i \\sigma_i^x
224
+ \\]
225
+ where \\( J = 1 \\) and \\( h = 0.5 \\). Determine the ground state energy and eigenvalues.
226
+ {Domain:} SPIN CHAINS"""
227
+ },
228
+ "Bell State and Concurrence": {
229
+ "description": "Generate a problem on the preparation and analysis of Bell states and concurrence.",
230
+ "example": """{Problem:} Alice and Bob prepare two qubits in the Bell state \\( |\\psi\\rangle = \\frac{3}{7}|00\\rangle + \\frac{6}{7}|01\\rangle + \\frac{2}{7}|10\\rangle \\). Calculate the concurrence of \\( |\\psi\\rangle \\) and determine the expectation value of \\( \\sigma_z \\) for qubit B.
231
+ {Domain:} BELL STATES"""
232
+ },
233
+ "Quantum Probability Calculations": {
234
+ "description": "Generate a problem involving calculation of quantum probabilities.",
235
+ "example": """{Problem:} Given the final quantum state:
236
+ \\[
237
+ |\\psi\\rangle = \\frac{1}{2}\\begin{pmatrix} 1 + e^{i\\phi} \\\\ 1 - e^{i\\phi} \\end{pmatrix}
238
+ \\]
239
+ calculate the probability of finding the system in state \\( |1\\rangle \\).
240
+ {Domain:} QUANTUM PROBABILITY"""
241
+ },
242
+ "Quantum Phase Estimation": {
243
+ "description": "Generate a problem involving quantum phase estimation techniques.",
244
+ "example": """{Problem:} Consider the quantum state \\( |\\psi\\rangle = \\frac{1}{\\sqrt{2}}(|0\\rangle + e^{i\\theta}|1\\rangle) \\). Perform a measurement in the \\( \\{|+\\rangle, |-\\rangle\\} \\) basis and compute the probabilities for each outcome as a function of \\( \\theta \\).
245
+ {Domain:} QUANTUM PHASE ESTIMATION"""
246
+ },
247
+
248
+ "Quantum Paradoxes": {
249
+ "description": "Generate a quantum physics problem focusing on Hardy's paradox or other quantum paradoxes illustrating non-classical phenomena.",
250
+ "template": """{Problem:} Hardy's paradox is a thought experiment that demonstrates non-classical correlations without probabilities adding up to one in certain measurement scenarios.
251
+ (a) Explain Hardy's paradox for a two-particle quantum system.
252
+ (b) Design a quantum circuit to reproduce the experimental setup for Hardy's paradox.
253
+ {Domain:} QUANTUM PARADOXES"""
254
+ },
255
+
256
+ "PennyLane Quantum Circuits": {
257
+ "description": "Generate a quantum physics problem involving the implementation of a quantum circuit using the PennyLane framework.",
258
+ "template": """{Problem:} Implement a quantum circuit in PennyLane that prepares the Bell state \\( |\\phi^+\\rangle = \\frac{1}{\\sqrt{2}}(|00\\rangle + |11\\rangle) \\) and measures the expectation value of \\( \\sigma_z \\otimes \\sigma_z \\).
259
+ {Domain:} PENNYLANE QUANTUM CIRCUITS"""
260
+ },
261
+
262
+ "PennyLane Circuit Analysis": {
263
+ "description":"Analyze a given PennyLane program and its corresponding quantum circuit diagram to describe its functionality.",
264
+ "template": """{Problem:} Given the following PennyLane program:}
265
+ ```python
266
+ import pennylane as qml
267
+ import numpy as np
268
+ dev = qml.device('default.qubit', wires=2)
269
+
270
+ @qml.qnode(dev)
271
+ def circuit(theta):
272
+ qml.Hadamard(wires=0)
273
+ qml.CNOT(wires=[0, 1])
274
+ qml.RZ(theta, wires=1)
275
+ return qml.expval(qml.PauliZ(1)) ```
276
+ Describe the quantum operations performed by this circuit. (b) Generate the corresponding quantum circuit diagram.
277
+ {Domain:} PENNYLANE CIRCUIT ANALYSIS"""
278
+ },
279
+ "Building Molecular Hamiltonian": {
280
+ "description": "Generate a quantum physics problem that involves constructing a molecular Hamiltonian for a given molecule using second quantization and quantum chemistry principles.",
281
+ "template": """{Problem:} Build the molecular Hamiltonian for a water molecule (H2O) using second quantization. Include both one-electron and two-electron integrals. Represent the Hamiltonian in matrix form.
282
+ {Domain:} BUILDING MOLECULAR HAMILTONIAN"""
283
+ },
284
+ "Variational Quantum Eigensolver (VQE)": {
285
+ "description": "Generate a quantum physics problem that focuses on implementing and optimizing the variational quantum eigensolver (VQE) for a specific Hamiltonian.",
286
+ "template": """{Problem:} Implement a variational quantum eigensolver (VQE) to find the ground-state energy of the Hamiltonian:
287
+ \\[
288
+ H = -J \\sigma_1^z \\sigma_2^z + h (\\sigma_1^x + \\sigma_2^x),
289
+ \\]
290
+ where \\( J = 1.0 \\) and \\( h = 0.5 \\). Use a hardware-efficient Ansatz and evaluate its performance.
291
+ {Domain:} VARIATIONAL QUANTUM EIGENSOLVER"""
292
+ },
293
+ "Subspace Search-Quantum Variational Quantum Eigensolver (SSVQE)": {
294
+ "description": "Generate a quantum physics problem that involves applying the subspace search quantum variational quantum eigensolver (SSVQE) to find multiple eigenstates of a Hamiltonian.",
295
+ "template": """{Problem:} Use the SSVQE approach to find the first three eigenstates of the Hamiltonian:
296
+ \\[
297
+ H = - \\sum_{i=1}^{N-1} J \\sigma_i^z \\sigma_{i+1}^z + h \\sum_{i=1}^N \\sigma_i^x,
298
+ \\]
299
+ where \\( J = 1.0 \\), \\( h = 0.5 \\), and \\( N = 4 \\). Design the Ansatz and cost function to achieve this.
300
+ {Domain:} SUBSPACE SSVQE"""
301
+ },
302
+ "Variational Quantum State Diagonalization (VQSD)": {
303
+ "description": "Generate a quantum physics problem involving variational quantum state diagonalization (VQSD) to diagonalize a given quantum state or density matrix.",
304
+ "template": """{Problem:} Apply VQSD to diagonalize the density matrix \\( \\rho \\) of a two-qubit quantum system:
305
+ \\[
306
+ \\rho = \\frac{1}{2} \\begin{bmatrix}
307
+ 1 & 0.3 \\\\
308
+ 0.3 & 0.7
309
+ \\end{bmatrix}.
310
+ \\]
311
+ Describe the Ansatz and optimization process required.
312
+ {Domain:} VARIATIONAL QUANTUM STATE DIAGONALIZATION"""
313
+ },
314
+ "Gibbs State Preparation": {
315
+ "description": "Generate a quantum physics problem that focuses on preparing a Gibbs state for a given Hamiltonian and temperature.",
316
+ "template": """{Problem:} Prepare the Gibbs state for the Hamiltonian:
317
+ \\[
318
+ H = \\sigma^z + 0.5 \\sigma^x,
319
+ \\]
320
+ at a temperature \\( T = 0.5 \\). Use variational methods to approximate the state.
321
+ {Domain:} GIBBS STATE PREPARATION"""
322
+ },
323
+ "The Classical Shadow of Unknown Quantum States": {
324
+ "description": "Generate a quantum physics problem involving the use of classical shadows to approximate properties of unknown quantum states.",
325
+ "template": """{Problem:} Use the classical shadow method to estimate the expectation value of the observable \\( \\sigma^z \\) for an unknown quantum state \\( |\\psi\\rangle \\). Explain the protocol and compute the sample complexity.
326
+ {Domain:} CLASSICAL SHADOWS"""
327
+ },
328
+ "Estimation of Quantum State Properties Based on the Classical Shadow": {
329
+ "description": "Generate a quantum physics problem that involves estimating properties of quantum states using classical shadows.",
330
+ "template": """{Problem:} Estimate the purity \\( \\text{Tr}(\\rho^2) \\) of a quantum state \\( \\rho \\) using classical shadow techniques. Describe the measurement protocol and necessary post-processing.
331
+ {Domain:} QUANTUM STATE PROPERTY ESTIMATION"""
332
+ },
333
+ "Hamiltonian Simulation with Product Formula": {
334
+ "description": "Generate a quantum physics problem that involves simulating the dynamics of a Hamiltonian using the product formula method.",
335
+ "template": """{Problem:} Simulate the time evolution of the Hamiltonian:
336
+ \\[
337
+ H = \\sigma^z + 0.5 \\sigma^x,
338
+ \\]
339
+ for time \\( t = 1.0 \\) using the first-order Trotter product formula. Calculate the approximation error.
340
+ {Domain:} PRODUCT FORMULA SIMULATION"""
341
+ },
342
+ "Simulate the Spin Dynamics on a Heisenberg Chain": {
343
+ "description": "Generate a quantum physics problem focusing on simulating spin dynamics in a Heisenberg chain.",
344
+ "template": """{Problem:} Simulate the spin dynamics of a three-qubit Heisenberg chain with the Hamiltonian:
345
+ \\[
346
+ H = J \\sum_{i=1}^{2} (\\sigma_i^x \\sigma_{i+1}^x + \\sigma_i^y \\sigma_{i+1}^y + \\sigma_i^z \\sigma_{i+1}^z),
347
+ \\]
348
+ where \\( J = 1.0 \\). Calculate the time evolution of the initial state \\( |\\uparrow \\downarrow \\uparrow\\rangle \\).
349
+ {Domain:} HEISENBERG CHAIN SIMULATION"""
350
+ },
351
+ "Distributed Variational Quantum Eigensolver Based on Schmidt Decomposition": {
352
+ "description": "Generate a quantum physics problem involving distributed VQE using Schmidt decomposition.",
353
+ "template": """{Problem:} Implement a distributed VQE algorithm to find the ground state of a bipartite system with the Hamiltonian:
354
+ \\[
355
+ H = \\sigma^z \\otimes \\sigma^z + 0.5 (\\sigma^x \\otimes I + I \\otimes \\sigma^x).
356
+ \\]
357
+ Use Schmidt decomposition to partition the system.
358
+ {Domain:} DISTRIBUTED VQE"""
359
+ },
360
+ "Quantum Signal Processing and Quantum Singular Value Transformation": {
361
+ "description": "Generate a quantum physics problem involving quantum signal processing and singular value transformation.",
362
+ "template": """{Problem:} Design a quantum circuit to implement the quantum singular value transformation (QSVT) for the operator:
363
+ \\[
364
+ U = e^{-i H t},
365
+ \\]
366
+ where \\( H = \\sigma^z \\) and \\( t = 1.0 \\). Explain how QSVT can be used for Hamiltonian simulation.
367
+ {Domain:} QSVT AND SIGNAL PROCESSING"""
368
+ },
369
+ "Hamiltonian Simulation with qDRIFT": {
370
+ "description": "Generate a quantum physics problem that involves simulating Hamiltonian dynamics using the qDRIFT method.",
371
+ "template": """{Problem:} Simulate the time evolution of the Hamiltonian:
372
+ \\[
373
+ H = \\sigma^z + 0.5 \\sigma^x,
374
+ \\]
375
+ for time \\( t = 2.0 \\) using the qDRIFT method. Estimate the sampling error and number of terms required.
376
+ {Domain:} QDRIFT SIMULATION"""
377
+ },
378
+ "Quantum Phase Processing": {
379
+ "description": "Generate a quantum physics problem that focuses on quantum phase processing techniques.",
380
+ "template": """{Problem:} Apply quantum phase processing to amplify the signal of the eigenvalue \\( \\lambda = 0.5 \\) of the operator:
381
+ \\[
382
+ H = \\sigma^z.
383
+ \\]
384
+ Design a quantum circuit for the amplification.
385
+ {Domain:} QUANTUM PHASE PROCESSING"""
386
+ },
387
+ "Variational Quantum Metrology": {
388
+ "description": "Generate a quantum physics problem involving variational quantum metrology to optimize quantum sensing.",
389
+ "template": """{Problem:} Use variational quantum metrology to estimate the parameter \\( \\theta \\) in the state:
390
+ \\[
391
+ |\\psi(\\theta)\\rangle = \\cos(\\theta/2)|0\\rangle + \\sin(\\theta/2)|1\\rangle.
392
+ \\]
393
+ Optimize the measurement settings to minimize the estimation error.
394
+ {Domain:} VARIATIONAL QUANTUM METROLOGY"""
395
+ },
396
+ "Encoding Classical Data into Quantum States": {
397
+ "description": "Generate a quantum physics problem focusing on encoding classical data into quantum states for quantum computation.",
398
+ "template": """{Problem:} Encode the classical data vector \\( [1, 0, -1] \\) into a quantum state using amplitude encoding. Explain the process and construct the required quantum circuit.
399
+ {Domain:} DATA ENCODING"""
400
+ },
401
+ "Quantum Classifier": {
402
+ "description": "Generate a quantum physics problem involving the implementation and optimization of a quantum classifier for machine learning tasks.",
403
+ "template": """{Problem:} Design a quantum classifier to distinguish between the quantum states \\( |0\\rangle \\) and \\( |1\\rangle \\) based on a variational Ansatz. Optimize the parameters to maximize classification accuracy.
404
+ {Domain:} QUANTUM CLASSIFIER"""
405
+ },
406
+ "Variational Shadow Quantum Learning (VSQL)": {
407
+ "description": "Generate a quantum physics problem involving variational shadow quantum learning to approximate quantum state properties.",
408
+ "template": """{Problem:} Use the VSQL method to approximate the trace of the operator \\( H = \\sigma^z \\otimes \\sigma^z \\) for a two-qubit state. Explain the variational Ansatz and optimization process.
409
+ {Domain:} VSQL"""
410
+ },
411
+ "Quantum Kernel Methods": {
412
+ "description": "Generate a quantum physics problem exploring the use of quantum kernel methods in machine learning.",
413
+ "template": """{Problem:} Develop a quantum kernel function to compute the similarity between the classical data points \\( x_1 = [1, 0] \\) and \\( x_2 = [0, 1] \\). Construct the quantum circuit for kernel evaluation and calculate the kernel value.
414
+ {Domain:} QUANTUM KERNELS"""
415
+ },
416
+ "Quantum Autoencoder": {
417
+ "description": "Generate a quantum physics problem focusing on designing and training a quantum autoencoder to compress quantum data.",
418
+ "template": """{Problem:} Design a quantum autoencoder to compress a two-qubit quantum state \\( |\\psi\\rangle = \\frac{1}{\\sqrt{2}} (|00\\rangle + |11\\rangle) \\) into a single qubit. Describe the training process and Ansatz used.
419
+ {Domain:} QUANTUM AUTOENCODER"""
420
+ },
421
+ "Quantum GAN": {
422
+ "description": "Generate a quantum physics problem that involves implementing a quantum generative adversarial network (GAN) for quantum data generation.",
423
+ "template": """{Problem:} Implement a quantum GAN to generate the quantum state \\( |\\psi\\rangle = \\frac{1}{\\sqrt{2}} (|0\\rangle + |1\\rangle) \\). Describe the architecture of the generator and discriminator circuits and the training process.
424
+ {Domain:} QUANTUM GAN"""
425
+ },
426
+ "Variational Quantum Singular Value Decomposition (VQSVD)": {
427
+ "description": "Generate a quantum physics problem that involves using VQSVD to approximate the singular value decomposition of a quantum operator.",
428
+ "template": """{Problem:} Apply VQSVD to find the singular value decomposition of the operator \\( A = \\begin{bmatrix} 1 & 0 \\\\ 0 & -1 \\end{bmatrix} \\). Construct the variational Ansatz and describe the optimization process.
429
+ {Domain:} VQSVD"""
430
+ },
431
+ "Data Encoding Analysis": {
432
+ "description": "Generate a quantum physics problem focusing on analyzing the efficiency and fidelity of different data encoding methods in quantum computation.",
433
+ "template": """{Problem:} Compare amplitude encoding and basis encoding for the classical vector \\( [1, 0, 1, 0] \\). Analyze the circuit depth and fidelity of each method.
434
+ {Domain:} DATA ENCODING ANALYSIS"""
435
+ },
436
+ "Quantum Neural Network Approximating Functions": {
437
+ "description": "Generate a quantum physics problem involving a quantum neural network approximating a given function.",
438
+ "template": """{Problem:} Construct a quantum neural network to approximate the function \\( f(x) = \\sin(x) \\) for \\( x \\in [0, \\pi] \\). Use a variational Ansatz and optimize the parameters to minimize the error.
439
+ {Domain:} QUANTUM NEURAL NETWORK"""
440
+ },
441
+ "Variational Quantum Amplitude Estimation": {
442
+ "description": "Generate a quantum physics problem that involves variational quantum amplitude estimation for a given probability distribution.",
443
+ "template": """{Problem:} Use variational quantum amplitude estimation to estimate the amplitude \\( \\alpha \\) in the state \\( \\sqrt{\\alpha}|0\\rangle + \\sqrt{1-\\alpha}|1\\rangle \\). Design the Ansatz and describe the optimization process.
444
+ {Domain:} VARIATIONAL AMPLITUDE ESTIMATION"""
445
+ },
446
+ "Quantum Approximation Optimization Algorithm (QAOA)": {
447
+ "description": "Generate a quantum physics problem focusing on implementing the Quantum Approximation Optimization Algorithm (QAOA) to solve combinatorial optimization problems.",
448
+ "template": """{Problem:} Implement QAOA to find the ground state of the cost Hamiltonian \\( H_C = Z_1 Z_2 + Z_2 Z_3 \\) for a three-qubit system. Describe the Ansatz and the optimization of the variational parameters \\( \\gamma \\) and \\( \\beta \\).
449
+ {Domain:} QAOA"""
450
+ },
451
+ "Solving Max-Cut Problem with QAOA": {
452
+ "description": "Generate a quantum physics problem that uses QAOA to solve the Max-Cut problem on a given graph.",
453
+ "template": """{Problem:} Solve the Max-Cut problem for a graph with three vertices and two edges \\( (1, 2), (2, 3) \\) using QAOA. Construct the cost Hamiltonian \\( H_C \\), prepare the initial state, and describe the variational optimization process.
454
+ {Domain:} MAX-CUT QAOA"""
455
+ },
456
+ "Large-scale QAOA via Divide-and-Conquer": {
457
+ "description": "Generate a quantum physics problem exploring the application of divide-and-conquer techniques to scale QAOA for large problem instances.",
458
+ "template": """{Problem:} Apply the divide-and-conquer approach to solve a Max-Cut problem on a graph with six vertices. Decompose the graph into two smaller subgraphs, solve them individually using QAOA, and combine the solutions to find the global Max-Cut.
459
+ {Domain:} LARGE-SCALE QAOA"""
460
+ },
461
+ "Travelling Salesman Problem": {
462
+ "description": "Generate a quantum physics problem involving the application of quantum algorithms, such as QAOA or Grover's search, to solve the Travelling Salesman Problem.",
463
+ "template": """{Problem:} Solve the Travelling Salesman Problem (TSP) for four cities \\( A, B, C, D \\) with the distance matrix:
464
+ \\[
465
+ \\begin{bmatrix}
466
+ 0 & 2 & 9 & 10 \\\\
467
+ 1 & 0 & 6 & 4 \\\\
468
+ 15 & 7 & 0 & 8 \\\\
469
+ 6 & 3 & 12 & 0
470
+ \\end{bmatrix}
471
+ \\]
472
+ Use QAOA to minimize the total travel distance. Construct the cost Hamiltonian and describe the optimization of variational parameters.
473
+ {Domain:} TSP QAOA"""
474
+ },
475
+ "Jordan-Wigner Transformations": {
476
+ "description": "Design problems using Jordan-Wigner transformations to map spin models to fermionic systems.",
477
+ "template": """{Problem:} Jordan-Wigner transformations are used to transform spin models into fermionic representations.
478
+ (a) Derive the Jordan-Wigner transformation for a 1D XXZ spin chain.
479
+ (b) Discuss the implications of non-locality introduced by string operators in the transformation.
480
+ {Domain:} SPIN-FERMION MAPPINGS"""
481
+ },
482
+ "Bethe Ansatz Application": {
483
+ "description": "Problems on solving the Heisenberg spin chain spectrum using the Bethe Ansatz.",
484
+ "template": """{Problem:} The Bethe Ansatz is a key method for solving the spectrum of the Heisenberg spin chain.
485
+ (a) Derive the energy spectrum for the XXZ spin chain using the Bethe Ansatz for a system with periodic boundary conditions.
486
+ (b) Discuss the implications of magnon scattering phases in determining the chain's spectrum.
487
+ {Domain:} INTEGRABLE SYSTEMS"""
488
+ },
489
+ "Generalized Spin Chain Compression": {
490
+ "description": "Design problems related to compressing quantum circuits using the Yang-Baxter equation for various spin chain models, including the generalized XYZ Heisenberg model and its variations.",
491
+ "template": """{Problem:} Generalized spin chain models, such as the XYZ Heisenberg model, include interactions along all spatial directions, often coupled with external fields or anisotropic interactions. These features present unique challenges for compressing quantum circuits using the Yang-Baxter equation.
492
+ (a) Analyze the conditions under which a generalized spin chain model (e.g., XYZ or XXZ with external fields) resists compression using the Yang-Baxter equation.
493
+ (b) Explore potential modifications to the Hamiltonian or circuit representation (e.g., introducing symmetries or reparametrizing coupling constants) that might render the model compressible.
494
+ (c) Evaluate the computational trade-offs introduced by these modifications in terms of circuit depth and fidelity.
495
+ {Domain:} SPIN CHAIN MODELS"""
496
+ },
497
+ "Wave-Particle Duality": {
498
+ "description": "Generate a quantum mechanics problem illustrating the dual nature of particles and waves, focusing on the photoelectric effect and Compton scattering.",
499
+ "template": """{Problem:} Discuss how the photoelectric effect supports the particle nature of light.
500
+ (a) Calculate the maximum kinetic energy of emitted electrons when light of frequency f strikes a metallic surface with work function W.
501
+ (b) Derive the Compton wavelength shift formula for photons scattering off free electrons.
502
+ {Domain:} WAVE-PARTICLE DUALITY"""
503
+ },
504
+ "Uncertainty Principle": {
505
+ "description": "Develop a problem involving Heisenberg's uncertainty principle and its implications for the ground state energy of quantum systems.",
506
+ "template": """{Problem:} Using the uncertainty principle, derive an expression for the minimum energy of a particle confined in a one-dimensional infinite potential well of width L.
507
+ (a) Calculate the ground-state energy for an electron in such a well with L = 1 nm.
508
+ (b) Discuss the implications for quantum confinement in nanoscale devices.
509
+ {Domain:} UNCERTAINTY PRINCIPLE"""
510
+ },
511
+ "Perturbation Theory": {
512
+ "description": "Formulate a problem using time-independent perturbation theory to analyze the correction of energy levels in a perturbed quantum harmonic oscillator.",
513
+ "template": """{Problem:} A quantum harmonic oscillator is subjected to a perturbation V(x) = λx^4.
514
+ (a) Using first-order perturbation theory, calculate the energy correction to the ground state.
515
+ (b) Discuss the physical implications of the perturbation on the potential shape.
516
+ {Domain:} PERTURBATION THEORY"""
517
+ },
518
+ "Angular Momentum": {
519
+ "description": "Create a problem exploring angular momentum eigenstates and their addition rules in quantum systems.",
520
+ "template": """{Problem:} Two particles have spins S1 = 1 and S2 = 1/2.
521
+ (a) Determine the possible total spin states using the addition of angular momentum.
522
+ (b) Write down the Clebsch-Gordan coefficients for these states.
523
+ {Domain:} ANGULAR MOMENTUM"""
524
+ },
525
+ "Hydrogen Atom": {
526
+ "description": "Design a problem focusing on the quantization of energy levels in the hydrogen atom and transitions between them.",
527
+ "template": """{Problem:} Calculate the wavelength of the photon emitted during a transition from n=3 to n=2 in a hydrogen atom.
528
+ (a) Use the Rydberg formula for hydrogen to verify the Balmer series.
529
+ (b) Discuss the physical significance of this transition in spectroscopy.
530
+ {Domain:} HYDROGEN ATOM"""
531
+ },
532
+ "Scattering Theory": {
533
+ "description": "Develop a problem involving quantum scattering and phase shifts using the Born approximation.",
534
+ "template": """{Problem:} A particle of mass m and energy E scatters off a potential V(r) = V0 exp(-r/a).
535
+ (a) Use the Born approximation to calculate the scattering amplitude.
536
+ (b) Discuss the physical interpretation of the phase shift in the low-energy limit.
537
+ {Domain:} SCATTERING THEORY"""
538
+ },
539
+ "Quantum Tunneling": {
540
+ "description": "Create a problem analyzing tunneling phenomena through potential barriers using the WKB approximation.",
541
+ "template": """{Problem:} Derive the tunneling probability for a particle encountering a potential barrier of height V0 and width d using the WKB approximation.
542
+ (a) Apply the formula to an electron with E = 5 eV tunneling through a barrier with V0 = 10 eV and d = 1 nm.
543
+ (b) Explain the implications of this for alpha decay in nuclear physics.
544
+ {Domain:} QUANTUM TUNNELING"""
545
+ },
546
+ "Entanglement": {
547
+ "description": "Formulate a problem on the concept of quantum entanglement and its applications in quantum communication.",
548
+ "template": """{Problem:} Two qubits are entangled in the state |ψ⟩ = (|00⟩ + |11⟩)/√2.
549
+ (a) Calculate the reduced density matrix for one qubit.
550
+ (b) Discuss the significance of the von Neumann entropy for this state.
551
+ {Domain:} QUANTUM ENTANGLEMENT"""
552
+ },
553
+ "Time Evolution": {
554
+ "description": "Generate a problem analyzing time evolution in quantum mechanics using the Schrödinger equation.",
555
+ "template": """{Problem:} A particle is initially in a superposition state |ψ(0)⟩ = (|1⟩ + |2⟩)/√2, where |1⟩ and |2⟩ are energy eigenstates with energies E1 and E2.
556
+ (a) Derive the time-evolved state |ψ(t)⟩.
557
+ (b) Calculate the probability of measuring the particle in state |1⟩ at time t.
558
+ {Domain:} TIME EVOLUTION"""
559
+ },
560
+ "Quantum Measurement": {
561
+ "description": "Develop a problem focusing on quantum measurement theory and wavefunction collapse.",
562
+ "template": """{Problem:} A spin-1/2 particle is prepared in the state |ψ⟩ = α|↑⟩ + β|↓⟩.
563
+ (a) If a measurement of Sz is performed, calculate the probabilities of outcomes ±ħ/2.
564
+ (b) Discuss the implications of wavefunction collapse in the context of this measurement.
565
+ {Domain:} QUANTUM MEASUREMENT"""
566
+ },
567
+ "Quantum Harmonic Oscillator": {
568
+ "description": "Generate a problem analyzing the energy eigenvalues and wavefunctions of the quantum harmonic oscillator.",
569
+ "template": """{Problem:} Solve the Schrödinger equation for the quantum harmonic oscillator and derive the energy eigenvalues.
570
+ (a) Show that the ground state wavefunction is a Gaussian.
571
+ (b) Calculate the expectation value of the position operator in the first excited state.
572
+ {Domain:} QUANTUM HARMONIC OSCILLATOR"""
573
+ },
574
+ "Spin-Orbit Coupling": {
575
+ "description": "Develop a problem exploring the spin-orbit interaction in atomic systems.",
576
+ "template": """{Problem:} Derive the form of the spin-orbit coupling term in the hydrogen atom.
577
+ (a) Calculate the energy shift caused by spin-orbit coupling for the n=2 level.
578
+ (b) Discuss its significance in the fine structure of spectral lines.
579
+ {Domain:} SPIN-ORBIT COUPLING"""
580
+ },
581
+ "Quantum Zeno Effect": {
582
+ "description": "Create a problem that demonstrates the quantum Zeno effect and its experimental implications.",
583
+ "template": """{Problem:} A quantum system is prepared in a superposition state and repeatedly measured at time intervals Δt.
584
+ (a) Derive the probability of finding the system in its initial state after n measurements.
585
+ (b) Discuss the implications of the quantum Zeno effect on the decay of unstable systems.
586
+ {Domain:} QUANTUM ZENO EFFECT"""
587
+ },
588
+ "Quantum Gates": {
589
+ "description": "Formulate a problem involving quantum gates and their implementation in quantum circuits.",
590
+ "template": """{Problem:} Construct a quantum circuit using Hadamard and CNOT gates to create a Bell state.
591
+ (a) Write the unitary matrix representation of this circuit.
592
+ (b) Explain the significance of this state in quantum communication protocols.
593
+ {Domain:} QUANTUM GATES"""
594
+ },
595
+ "Adiabatic Theorem": {
596
+ "description": "Design a problem demonstrating the adiabatic theorem and its application to quantum systems.",
597
+ "template": """{Problem:} A particle is in the ground state of a slowly varying potential V(x, t).
598
+ (a) Use the adiabatic theorem to argue why the system remains in the instantaneous ground state.
599
+ (b) Discuss the breakdown of the adiabatic approximation for rapid changes in V(x, t).
600
+ {Domain:} ADIABATIC THEOREM"""
601
+ },
602
+ "Bell Inequalities": {
603
+ "description": "Generate a problem testing Bell inequalities in quantum mechanics.",
604
+ "template": """{Problem:} Consider a system of two entangled spin-1/2 particles. Derive the CHSH inequality for the system.
605
+ (a) Show how quantum mechanics predicts a violation of this inequality.
606
+ (b) Discuss the implications for local hidden variable theories.
607
+ {Domain:} BELL INEQUALITIES"""
608
+ },
609
+ "Superposition Principle": {
610
+ "description": "Create a problem exploring the principle of superposition in quantum mechanics.",
611
+ "template": """{Problem:} A particle in a 1D infinite potential well is in a superposition of the first two energy eigenstates.
612
+ (a) Write the time-dependent wavefunction of the system.
613
+ (b) Calculate the probability density and discuss its periodicity.
614
+ {Domain:} SUPERPOSITION PRINCIPLE"""
615
+ },
616
+ "Quantum Decoherence": {
617
+ "description": "Formulate a problem examining quantum decoherence and its effects on quantum systems.",
618
+ "template": """{Problem:} A qubit interacts with its environment modeled as a thermal bath.
619
+ (a) Derive the master equation governing the reduced density matrix of the qubit.
620
+ (b) Discuss the loss of coherence in the off-diagonal elements of the density matrix.
621
+ {Domain:} QUANTUM DECOHERENCE"""
622
+ },
623
+ "Topological Quantum States": {
624
+ "description": "Develop a problem on topological quantum states and their robustness against local perturbations.",
625
+ "template": """{Problem:} Consider a quantum system with a non-trivial topological phase.
626
+ (a) Calculate the Chern number for a 2D electron gas in a magnetic field.
627
+ (b) Discuss the physical significance of topologically protected edge states.
628
+ {Domain:} TOPOLOGICAL QUANTUM STATES"""
629
+ },
630
+ "Quantum Cryptography": {
631
+ "description": "Generate a problem analyzing the principles of quantum cryptography.",
632
+ "template": """{Problem:} Explain the BB84 protocol for quantum key distribution.
633
+ (a) Calculate the error rate threshold for secure communication in the presence of an eavesdropper.
634
+ (b) Discuss the role of entanglement in quantum cryptographic protocols.
635
+ {Domain:} QUANTUM CRYPTOGRAPHY"""
636
+ },
637
+ "Quantum Eraser": {
638
+ "description": "Design a problem on the quantum eraser experiment and its implications for wave-particle duality.",
639
+ "template": """{Problem:} In a double-slit experiment with a quantum eraser, analyze the interference pattern.
640
+ (a) Derive the conditions under which interference fringes are observed.
641
+ (b) Discuss the delayed-choice quantum eraser and its implications for causality.
642
+ {Domain:} QUANTUM ERASER"""
643
+ },
644
+ "Quantum Teleportation": {
645
+ "description": "Formulate a problem demonstrating the principles of quantum teleportation.",
646
+ "template": """{Problem:} Alice and Bob share an entangled pair of qubits. Alice wishes to teleport an unknown quantum state to Bob.
647
+ (a) Write down the quantum circuit for the teleportation protocol.
648
+ (b) Discuss the role of classical communication in completing the protocol.
649
+ {Domain:} QUANTUM TELEPORTATION"""
650
+ },
651
+ "Path Integral Formulation": {
652
+ "description": "Create a problem utilizing the path integral formulation of quantum mechanics.",
653
+ "template": """{Problem:} Derive the propagator for a free particle using the path integral approach.
654
+ (a) Discuss the significance of the classical action in the path integral formulation.
655
+ (b) Compare the result with the propagator derived from the Schrödinger equation.
656
+ {Domain:} PATH INTEGRAL FORMULATION"""
657
+ },
658
+ "Quantum Annealing": {
659
+ "description": "Generate a problem analyzing the principles of quantum annealing for optimization problems.",
660
+ "template": """{Problem:} Describe the quantum annealing process for solving the Ising model.
661
+ (a) Derive the time-dependent Hamiltonian used in quantum annealing.
662
+ (b) Discuss the role of tunneling in escaping local minima during the annealing process.
663
+ {Domain:} QUANTUM ANNEALING"""
664
+ },
665
+ "Berry Phase": {
666
+ "description": "Develop a problem on the geometric phase in quantum systems.",
667
+ "template": """{Problem:} A quantum system evolves adiabatically around a closed loop in parameter space.
668
+ (a) Derive the expression for the Berry phase acquired by the system.
669
+ (b) Discuss an example where the Berry phase has observable consequences.
670
+ {Domain:} BERRY PHASE"""
671
+ },
672
+ "Quantum Cloning": {
673
+ "description": "Formulate a problem exploring the no-cloning theorem in quantum mechanics.",
674
+ "template": """{Problem:} Prove the no-cloning theorem for arbitrary quantum states.
675
+ (a) Discuss why cloning is forbidden in the context of the linearity of quantum mechanics.
676
+ (b) Explore the implications of this theorem for quantum communication.
677
+ {Domain:} QUANTUM CLONING"""
678
+ },
679
+ "Density Matrix Formalism": {
680
+ "description": "Create a problem utilizing the density matrix formalism to describe mixed states.",
681
+ "template": """{Problem:} A two-level quantum system is described by the density matrix ρ.
682
+ (a) Calculate the purity of the state and interpret its physical meaning.
683
+ (b) Discuss the evolution of ρ under a unitary transformation.
684
+ {Domain:} DENSITY MATRIX FORMALISM"""
685
+ },
686
+ "Quantum Computation": {
687
+ "description": "Generate a problem involving basic concepts of quantum computation.",
688
+ "template": """{Problem:} Implement the Deutsch-Jozsa algorithm for a quantum oracle.
689
+ (a) Write down the steps of the algorithm and the required quantum circuit.
690
+ (b) Discuss the computational advantage over classical methods.
691
+ {Domain:} QUANTUM COMPUTATION"""
692
+ },
693
+ "Relativistic Quantum Mechanics": {
694
+ "description": "Develop a problem on the Klein-Gordon or Dirac equations.",
695
+ "template": """{Problem:} Solve the Klein-Gordon equation for a free particle.
696
+ (a) Derive the relativistic energy-momentum relation from the equation.
697
+ (b) Discuss the significance of negative energy solutions.
698
+ {Domain:} RELATIVISTIC QUANTUM MECHANICS"""
699
+ },
700
+ "Quantum Field Theory": {
701
+ "description": "Create a problem introducing basic concepts of quantum field theory.",
702
+ "template": """{Problem:} Quantize the scalar field and derive the commutation relations for the field operators.
703
+ (a) Discuss the role of creation and annihilation operators.
704
+ (b) Explain the physical interpretation of the vacuum state.
705
+ {Domain:} QUANTUM FIELD THEORY"""
706
+ }
707
+ }
708
+
709
+
710
+
711
+
712
+ stage3_prompt = ("You are a math-solving assistant. You will be presented with a math problem and a proposed solution. Your task is to determine if the provided solution is correct. "
713
+ "If the solution is correct, confirm it with a detailed explanation. If the solution is incorrect, identify the errors and provide a full corrected solution using the "
714
+ "TORA framework: Think—understand and restate the problem, identifying key details; Organize—break it into manageable steps; Reason—solve systematically, showing all "
715
+ "intermediate steps and calculations; and Answer—present the final solution clearly and concisely. Always use Chain of Thought reasoning to ensure logical progression "
716
+ "and clarity. Here is an example: \n\n"
717
+ "Problem: A train travels 120 miles in 2 hours. What is its average speed?\n"
718
+ "Proposed Solution: The average speed is 70 mph.\n"
719
+ "Analysis: The solution is incorrect. Think: Speed is distance divided by time. The distance is 120 miles, and the time is 2 hours. Organize: Write the formula "
720
+ "Speed = Distance / Time. Reason: Substitute the values, Speed = 120 / 2 = 60 mph. Answer: The correct average speed is 60 mph.\n\n"
721
+ "Now analyze the following problem and solution:\n\n"
722
+ "Problem: [Insert Problem Here]\n"
723
+ "Proposed Solution: [Insert Proposed Solution Here]")
724
+
725
+
726
+
Q_quantum_utils.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Quantum Physics Problem Generator
3
+ Shlomo Kashani
4
+
5
+ Description:
6
+ ------------
7
+ This module is part of the QuantumLLMInstruct system, designed to generate and solve quantum physics problems
8
+ using advanced Large Language Models (LLMs). It utilizes a multi-stage pipeline for problem generation,
9
+ solution generation, and database management.
10
+
11
+ Core Functionalities:
12
+ ---------------------
13
+ 1. **Problem Generation**:
14
+ - Generates quantum physics problems in LaTeX format using LLMs.
15
+ - Supports domain-specific problem generation across multiple quantum fields.
16
+
17
+ 2. **Solution Generation**:
18
+ - Provides step-by-step LaTeX solutions for the generated problems using a second LLM.
19
+
20
+ 3. **Data Management**:
21
+ - Stores generated problems and solutions in DuckDB and Parquet files.
22
+ - Enables exporting data in Parquet format for scalability and compatibility.
23
+
24
+ 4. **Gradio Interface**:
25
+ - A user-friendly interface to interact with the system, including problem generation,
26
+ solution generation, and database exploration.
27
+
28
+ 5. **Hugging Face Integration**:
29
+ - Supports visualization and interaction with the dataset on the Hugging Face platform.
30
+
31
+ Main Components:
32
+ ----------------
33
+ - **initialize_duckdb() / initialize_parquet()**: Initializes the database schema.
34
+ - **generate_multiple_problems()**: Generates multiple problems for the selected quantum domains.
35
+ - **generate_solutions()**: Solves unsolved problems in the database.
36
+ - **export_parquet()**: Exports the database to a Parquet file for external use.
37
+
38
+ Dependencies:
39
+ -------------
40
+ - Python 3.7+
41
+ - Transformers: `transformers`
42
+ - DuckDB: `duckdb`
43
+ - Gradio: `gradio`
44
+ - Pandas: `pandas`
45
+ """
46
+
47
+ import numpy as np
48
+ import random
49
+ import io
50
+ import duckdb
51
+ import math
52
+ from datetime import datetime
53
+ import PIL
54
+ from PIL import Image
55
+ import pennylane as qml
56
+ import base64
57
+ import platform
58
+ from math import pi
59
+ import pandas as pd
60
+ import os
61
+ from transformers import AutoModelForCausalLM, AutoTokenizer
62
+ import tqdm
63
+ import duckdb
64
+ from tqdm import tqdm
65
+ import uuid
66
+ import random
67
+ import sympy
68
+ from datetime import datetime
69
+
70
+ from Q_llm_prompts import *
71
+
72
+ # Predefined Qwen models
73
+ # Qwen2.5 offers multiple model sizes, including 72B, 32B, 14B, 7B, 3B, 1.5B, 0.5B, etc.
74
+ # You can choose the appropriate model based on your needs and GPU memory size
75
+ model_options = [
76
+ "Qwen/Qwen2.5-Coder-1.5B-Instruct",
77
+ "Qwen/Qwen2.5-Coder-3B-Instruct",
78
+ "Qwen/Qwen2.5-Coder-7B-Instruct",
79
+ "Qwen/Qwen2.5-Math-7B-Instruct",
80
+ "Qwen/Qwen2.5-Coder-32B-Instruct",
81
+ "meta-llama/Llama-3.2-3B-Instruct"
82
+ # "unsloth/Qwen2.5-Math-7B-Instruct",
83
+ # "unsloth/Llama-3.2-3B-Instruct-bnb-4bit",
84
+ # "nvidia/OpenMath-CodeLlama-7b-Python-hf" tokenizer.chat_template is not set and no template argument was passed!
85
+ ]
86
+
87
+ solutions_model_options = model_options
88
+
89
+ # Load default model and tokenizer
90
+ selected_model = model_options[0]
91
+ model = AutoModelForCausalLM.from_pretrained(
92
+ selected_model,
93
+ torch_dtype="auto",
94
+ device_map="auto"
95
+ )
96
+ tokenizer = AutoTokenizer.from_pretrained(selected_model)
97
+ solution_model = selected_model
98
+ solution_tokenizer =tokenizer
99
+ solution_model_instance =model
100
+
101
+ # Function to reload the model when selection changes
102
+ def reload_model(model_name):
103
+ global model, tokenizer
104
+ model = AutoModelForCausalLM.from_pretrained(
105
+ model_name,
106
+ torch_dtype="auto",
107
+ device_map="auto"
108
+ )
109
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
110
+ return f"Model loaded: {model_name}"
111
+
112
+
113
+
114
+ # Define a Pennylane device
115
+ dev = qml.device('default.qubit', wires=10)
116
+
117
+ # Detect platform-specific device
118
+ def is_mac_os():
119
+ return platform.system() == 'Darwin'
120
+
121
+ device = 'cpu' if is_mac_os() else 'cuda'
122
+
123
+ RESPONSE_SOLUTION_LLM_SYS_PROMPT = "You are an expert in quantum physics and provide detailed solutions in plain text. All mathematical equations and symbols must strictly be in LaTeX."
124
+ RESPONSE_SOLUTION_LLM_USR_PROMPT = """
125
+ Provide a complete solution to the following quantum physics problem in plain text format:
126
+ {problem}
127
+ """
128
+
129
+ # Parquet file setup
130
+ PARQUET_FILE = 'quantum_problems.parquet'
131
+
132
+ def initialize_parquet():
133
+ """Initialize Parquet file with the required schema if it doesn't exist."""
134
+ if not os.path.exists(PARQUET_FILE):
135
+ data = {
136
+ "uuid": [],
137
+ "timestamp": [],
138
+ "problem": [],
139
+ "sub_domain": [],
140
+ "main_domain": [],
141
+ "model_name": [],
142
+ "solution": [],
143
+ "solution_model_name": []
144
+ }
145
+ df = pd.DataFrame(data)
146
+ df.to_parquet(PARQUET_FILE, index=False)
147
+ print("Initialized Parquet file with schema.")
148
+
149
+ def load_parquet():
150
+ """Load data from the Parquet file."""
151
+ if os.path.exists(PARQUET_FILE):
152
+ return pd.read_parquet(PARQUET_FILE)
153
+ else:
154
+ initialize_parquet()
155
+ return pd.read_parquet(PARQUET_FILE)
156
+
157
+ def save_parquet(df):
158
+ """Save DataFrame to Parquet file."""
159
+ df.to_parquet(PARQUET_FILE, index=False)
160
+
161
+ def insert_problem_pqt(uuid, timestamp, problem, main_domain, sub_domain, model_name, solution=None, solution_model_name=None):
162
+ """Insert a new problem into the Parquet file."""
163
+ df = load_parquet()
164
+ new_row = {
165
+ "uuid": uuid,
166
+ "timestamp": timestamp,
167
+ "problem": problem,
168
+ "sub_domain": sub_domain,
169
+ "main_domain": main_domain,
170
+ "model_name": model_name,
171
+ "solution": solution,
172
+ "solution_model_name": solution_model_name
173
+ }
174
+ df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
175
+ save_parquet(df)
176
+
177
+ def update_solution_pqt(uuid, solution, solution_model_name):
178
+ """Update the solution for a given problem UUID."""
179
+ df = load_parquet()
180
+ df.loc[df["uuid"] == uuid, ["solution", "solution_model_name"]] = solution, solution_model_name
181
+ save_parquet(df)
182
+
183
+
184
+ # DuckDB setup
185
+ DB_FILE = 'quantum_problems.duckdb'
186
+
187
+ def initialize_duckdb():
188
+ conn = duckdb.connect(database=DB_FILE)
189
+
190
+ conn.execute("""
191
+ CREATE TABLE IF NOT EXISTS problems (
192
+ uuid TEXT UNIQUE NOT NULL,
193
+ timestamp TEXT,
194
+ problem TEXT,
195
+ sub_domain TEXT,
196
+ main_domain TEXT,
197
+ model_name TEXT,
198
+ solution TEXT,
199
+ solution_model_name TEXT
200
+ )
201
+ """)
202
+ # print ("Created schema")
203
+ # df = conn.execute("SELECT * FROM problems").df()
204
+ # print (df.count)
205
+ conn.close()
206
+
207
+ # Function to buffer the plot and return as PIL image
208
+ def buffer_plot_and_get(fig):
209
+ buf = io.BytesIO()
210
+ fig.savefig(buf, format='png')
211
+ buf.seek(0)
212
+ return PIL.Image.open(buf)
213
+
214
+ # Store image in bytes for DuckDB
215
+ def pil_image_to_bytes(image):
216
+ img_byte_arr = io.BytesIO()
217
+ image.save(img_byte_arr, format='PNG')
218
+ return img_byte_arr.getvalue()
219
+
220
+ # Encode the image in base64 to display in HTML
221
+ def encode_image_from_blob(blob):
222
+ img_buffer = io.BytesIO(blob)
223
+ image = Image.open(img_buffer)
224
+ img_str = base64.b64encode(img_buffer.getvalue()).decode("utf-8")
225
+ return f'<img src="data:image/png;base64,{img_str}" style="max-width:500px;"/>'
226
+
227
+ # Function to generate a random Hamiltonian
228
+ def generate_random_hamiltonian(num_qubits):
229
+ terms = []
230
+ for _ in range(random.randint(1, 5)):
231
+ coeff = round(random.uniform(-1, 1), 2)
232
+ pauli_ops = [random.choice(['I', 'X', 'Y', 'Z']) for _ in range(num_qubits)]
233
+ term = f"{coeff} * {' '.join(pauli_ops)}"
234
+ terms.append(term)
235
+ return " + ".join(terms)
236
+
237
+ # Function to convert Hamiltonian to QASM code
238
+ def hamiltonian_to_qasm(hamiltonian, num_qubits):
239
+ qasm_code = f"OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[{num_qubits}];\n"
240
+ rotations = {i: 0.0 for i in range(num_qubits)}
241
+ terms = hamiltonian.split(" + ")
242
+
243
+ for term in terms:
244
+ coeff, paulis = term.split(" * ")
245
+ paulis = paulis.split()
246
+ coeff = float(coeff)
247
+
248
+ for i, pauli in enumerate(paulis):
249
+ if pauli == "X":
250
+ qasm_code += f"x q[{i}];\n"
251
+ elif pauli == "Y":
252
+ qasm_code += f"ry(pi/2) q[{i}];\n"
253
+ elif pauli == "Z":
254
+ rotations[i] += coeff
255
+
256
+ for i, angle in rotations.items():
257
+ if angle != 0:
258
+ angle_degrees = round(angle * 180 / math.pi, 2)
259
+ qasm_code += f"rz({angle_degrees}) q[{i}];\n"
260
+
261
+ return qasm_code
262
+
263
+ # Function to parse QASM code and create Pennylane circuit
264
+ def qasm_to_pennylane(qasm_code):
265
+ qasm_lines = qasm_code.split("\n")
266
+ num_qubits = int(qasm_lines[2].split('[')[1].split(']')[0]) # Extract number of qubits from QASM
267
+
268
+ @qml.qnode(dev)
269
+ def circuit():
270
+ for line in qasm_lines:
271
+ if "x" in line:
272
+ qml.PauliX(int(line.split('q[')[1].split(']')[0]))
273
+ elif "rz" in line:
274
+ angle = float(line.split('(')[1].split(')')[0])
275
+ qml.RZ(angle, int(line.split('q[')[1].split(']')[0]))
276
+ elif "ry" in line:
277
+ qml.RY(pi / 2, int(line.split('q[')[1].split(']')[0]))
278
+ return qml.state()
279
+
280
+ return circuit
281
+
282
+ # # Store data in DuckDB
283
+ # def store_in_duckdb(data, db_file='quantum_hamiltonians.duckdb'):
284
+ # conn = duckdb.connect(database=db_file)
285
+ # conn.execute("""CREATE TABLE IF NOT EXISTS hamiltonians (
286
+ # id INTEGER,
287
+ # plot BLOB,
288
+ # hamiltonian VARCHAR,
289
+ # qasm_code VARCHAR,
290
+ # trotter_code VARCHAR,
291
+ # num_qubits INTEGER,
292
+ # trotter_order INTEGER,
293
+ # timestamp TIMESTAMP
294
+ # )""")
295
+ # conn.executemany("""INSERT INTO hamiltonians (id, plot, hamiltonian, qasm_code, trotter_code, num_qubits, trotter_order, timestamp)
296
+ # VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", data)
297
+ # conn.close()
298
+
299
+ # Function to load results from DuckDB
300
+ def load_from_duckdb(db_file='quantum_hamiltonians.duckdb'):
301
+ conn = duckdb.connect(database=db_file)
302
+ df = conn.execute("SELECT * FROM hamiltonians").df()
303
+ conn.close()
304
+
305
+ # Convert results to HTML with images
306
+ html_content = []
307
+ for index, row in df.iterrows():
308
+ plot_blob = row['plot']
309
+ encoded_img = encode_image_from_blob(plot_blob)
310
+
311
+ html_content.append(f"""
312
+ <table style='width: 100%; border-collapse: collapse; margin: 10px;'>
313
+ <tr>
314
+ <td style='width: 30%; text-align: center;'>
315
+ <h3>Circuit {index + 1}</h3>
316
+ {encoded_img} <!-- Display the image -->
317
+ </td>
318
+ <td style='padding: 10px;'>
319
+ <table style='width: 100%; border-collapse: collapse;'>
320
+ <tr>
321
+ <td><strong>Hamiltonian:</strong></td><td>{row['hamiltonian']}</td>
322
+ </tr>
323
+ <tr>
324
+ <td><strong>QASM Representation:</strong></td><td>{row['qasm_code']}</td>
325
+ </tr>
326
+ <tr>
327
+ <td><strong>Trotter Decomposition:</strong></td><td>{row['trotter_code']}</td>
328
+ </tr>
329
+ <tr>
330
+ <td><strong>Number of Qubits:</strong></td><td>{row['num_qubits']}</td>
331
+ </tr>
332
+ <tr>
333
+ <td><strong>Trotter Order:</strong></td><td>{row['trotter_order']}</td>
334
+ </tr>
335
+ <tr>
336
+ <td><strong>Timestamp:</strong></td><td>{row['timestamp']}</td>
337
+ </tr>
338
+ </table>
339
+ </td>
340
+ </tr>
341
+ </table>
342
+ """)
343
+
344
+ return "".join(html_content)
345
+
346
+ # Function to generate Hamiltonians
347
+ def generate_hamiltonians(num_hamiltonians, selected_qubits, selected_order):
348
+ results_table = []
349
+ timestamp = str(datetime.now())
350
+
351
+ for i in range(num_hamiltonians):
352
+ num_qubits = random.choice(selected_qubits)
353
+ order = selected_order
354
+ hamiltonian = generate_random_hamiltonian(num_qubits)
355
+ qasm_code = hamiltonian_to_qasm(hamiltonian, num_qubits)
356
+ trotter_code = trotter_decomposition(hamiltonian, order)
357
+
358
+ # Generate Pennylane circuit from QASM code
359
+ circuit = qasm_to_pennylane(qasm_code)
360
+
361
+ # Draw the Pennylane circuit and save as an image
362
+ fig, ax = qml.draw_mpl(circuit)()
363
+ circuit_plot_image = buffer_plot_and_get(fig)
364
+ circuit_plot_bytes = pil_image_to_bytes(circuit_plot_image)
365
+
366
+ # Append data to results table
367
+ results_table.append((i + 1, circuit_plot_bytes, hamiltonian, qasm_code, trotter_code, num_qubits, order, timestamp))
368
+
369
+
370
+ # Function for Trotter decomposition
371
+ def trotter_decomposition(hamiltonian, order):
372
+ terms = hamiltonian.split(" + ")
373
+ trotter_steps = []
374
+
375
+ for term in terms:
376
+ coeff, *pauli_ops = term.split(" * ")
377
+ coeff = float(coeff)
378
+ for _ in range(order):
379
+ trotter_steps.append(f"exp({coeff / order}) * ({' * '.join(pauli_ops)})")
380
+ for _ in range(order):
381
+ trotter_steps.append(f"exp({-coeff / order}) * ({' * '.join(pauli_ops)})")
382
+
383
+ return " + ".join(trotter_steps)
384
+
385
+ # def export_parquet(db_file):
386
+ # """Export DuckDB table to a Parquet file using COPY."""
387
+ # try:
388
+ # conn = duckdb.connect(database=db_file)
389
+ # parquet_file = f"quantum_problems_{datetime.now().strftime('%Y%m%d_%H%M%S')}.parquet"
390
+ # conn.execute(f"COPY problems TO '{parquet_file}' (FORMAT PARQUET);")
391
+ # conn.close()
392
+ # return f"Data successfully exported to Parquet file: {parquet_file}"
393
+ # except Exception as e:
394
+ # return f"Error exporting to Parquet: {e}"
395
+
396
+ def export_parquet(db_file):
397
+ """Export DuckDB table to a Parquet file using COPY."""
398
+ try:
399
+ conn = duckdb.connect(database=db_file)
400
+ parquet_file = f"quantum_problems_{datetime.now().strftime('%Y%m%d_%H%M%S')}.parquet"
401
+ conn.execute(f"""
402
+ COPY (
403
+ SELECT
404
+ uuid,
405
+ CAST(timestamp AS VARCHAR) AS timestamp,
406
+ problem,
407
+ sub_domain,
408
+ main_domain,
409
+ model_name,
410
+ solution,
411
+ solution_model_name
412
+ FROM problems
413
+ ) TO '{parquet_file}' (FORMAT PARQUET);
414
+ """)
415
+ conn.close()
416
+ df = pd.read_parquet(parquet_file)
417
+ df['timestamp'] = df['timestamp'].astype(str)
418
+ df.to_parquet(parquet_file, index=False)
419
+
420
+ return f"Data successfully exported to Parquet file: {parquet_file}"
421
+ except Exception as e:
422
+ return f"Error exporting to Parquet: {e}"
423
+
424
+ def generate_dynamic_prompt(selected_domains):
425
+ if not selected_domains:
426
+ raise ValueError("No domains selected. Please select at least one domain.")
427
+ # Select a single domain randomly
428
+ selected_domain = random.choice(selected_domains)
429
+ print("Selected Domain:", selected_domain)
430
+ # Retrieve the description and template
431
+ domain_details = quantum_problem_domains[selected_domain]
432
+ domain_description = domain_details["description"]
433
+ example_output = domain_details["template"]
434
+ RESPONSE_INSTRUCTION_LLM_PROMPT = f"""
435
+ Generate a single detailed quantum physics problem for an exam in LaTeX format. Do not solve the problem.
436
+ Do not include additional explanations or comments outside of LaTeX, and avoid unnecessary LaTeX imports (e.g., \\documentclass{{}}, \\usepackage{{}}, or \\begin{{document}}).
437
+ All mathematical equations and symbols must strictly be in LaTeX.
438
+ Your response must strictly follow this provided format:
439
+ 1) {{Problem:}} Clearly define the quantum physics problem here, using mathematical precision and LaTeX formatting. Provide any equations or detailed descriptions necessary for students to understand and solve the problem.
440
+ 2) {{Domain:}} Provide a concise two-word domain description in CAPS such as "ISING HAMILTONIAN".
441
+ Do not solve the problem!. The problem must strictly adhere to one and only one of the following domain types:
442
+ {domain_description}
443
+ Example Response Output:
444
+ {example_output}
445
+ """
446
+ return RESPONSE_INSTRUCTION_LLM_PROMPT, selected_domain
447
+
448
+ # Function to generate a quantum physics problem
449
+ def generate_problem(pair_id, model_name, selected_domains):
450
+ try:
451
+ prompt, selected_domain = generate_dynamic_prompt(selected_domains)
452
+
453
+ messages = [
454
+ {"role": "system", "content": "You are a quantum physics professor and an expert in quantum computing."},
455
+ {"role": "user", "content": prompt}
456
+ ]
457
+ text = tokenizer.apply_chat_template(
458
+ messages,
459
+ tokenize=False,
460
+ add_generation_prompt=True
461
+ )
462
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
463
+
464
+ generated_ids = model.generate(
465
+ **model_inputs,
466
+ max_new_tokens=10024
467
+ )
468
+ generated_ids = [
469
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
470
+ ]
471
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
472
+
473
+ if "{Problem:}" not in response or "{Domain:}" not in response:
474
+ raise ValueError(f"Generated problem does not match the expected format. Response:\n{response}")
475
+
476
+ problem = response.split("{Problem:}")[1].split("{Domain:}")[0].strip()
477
+ sub_domain = response.split("{Domain:}")[1].strip()
478
+
479
+ # Insert the problem into DuckDB
480
+ conn = duckdb.connect(database=DB_FILE)
481
+ conn.execute("""
482
+ INSERT INTO problems (uuid, timestamp, problem, main_domain, sub_domain, model_name)
483
+ VALUES (?, ?, ?, ?, ?, ?)
484
+ """, (str(uuid.uuid4()), datetime.now().isoformat(), problem, selected_domain, sub_domain, model_name.split("/")[-1]))
485
+ conn.close()
486
+
487
+ # print(response)
488
+ return response
489
+ except Exception as e:
490
+ print(f"Error generating problem {pair_id}: {e}")
491
+ return None
492
+
493
+ # Generate multiple problems with progress
494
+ def generate_multiple_problems(num_pairs, selected_domains):
495
+ if not selected_domains:
496
+ return "Please select at least one domain type."
497
+
498
+ conn = duckdb.connect(database=DB_FILE)
499
+ current_count = conn.execute("SELECT COUNT(*) FROM problems").fetchone()[0]
500
+ conn.close()
501
+
502
+ responses = []
503
+ with tqdm(total=num_pairs, desc="Generating Problems", unit="problem") as pbar:
504
+ for i in range(num_pairs):
505
+ response = generate_problem(current_count + i + 1, selected_model, selected_domains)
506
+ if response:
507
+ responses.append(response)
508
+ pbar.update(1)
509
+ return "\n\n".join(responses)
510
+
511
+ def generate_solutions_pqt(solution_model_name):
512
+ df = load_parquet()
513
+ unsolved_problems = df[df["solution"].isna()]
514
+
515
+ if unsolved_problems.empty:
516
+ return "No unsolved problems found in the database."
517
+
518
+ with tqdm(total=len(unsolved_problems), desc="Generating Solutions", unit="solution") as pbar:
519
+ for _, row in unsolved_problems.iterrows():
520
+ try:
521
+ solution_prompt = RESPONSE_SOLUTION_LLM_USR_PROMPT.format(problem=row["problem"])
522
+
523
+ messages = [
524
+ {"role": "system", "content": RESPONSE_SOLUTION_LLM_SYS_PROMPT},
525
+ {"role": "user", "content": solution_prompt}
526
+ ]
527
+ text = solution_tokenizer.apply_chat_template(
528
+ messages,
529
+ tokenize=False,
530
+ add_generation_prompt=True
531
+ )
532
+ model_inputs = solution_tokenizer([text], return_tensors="pt").to(solution_model_instance.device)
533
+
534
+ generated_ids = solution_model_instance.generate(
535
+ **model_inputs,
536
+ max_new_tokens=10024
537
+ )
538
+ generated_ids = [
539
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
540
+ ]
541
+ solution = solution_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
542
+
543
+ # Update solution in Parquet
544
+ update_solution_pqt(row["uuid"], solution, solution_model_name.split("/")[-1])
545
+ except Exception as e:
546
+ print(f"Error generating solution for problem {row['uuid']}: {e}")
547
+ pbar.update(1)
548
+ return "Solutions generated successfully!"
549
+
550
+ # Function to generate solutions for unsolved problems
551
+ def generate_solutions(solution_model_name):
552
+ conn = duckdb.connect(database=DB_FILE)
553
+ problems = conn.execute("SELECT uuid, problem FROM problems WHERE solution IS NULL").fetchall()
554
+
555
+ if not problems:
556
+ return "No unsolved problems found in the database."
557
+
558
+ with tqdm(total=len(problems), desc="Generating Solutions", unit="solution") as pbar:
559
+ for problem_id, problem_text in problems:
560
+ try:
561
+ solution_prompt = RESPONSE_SOLUTION_LLM_USR_PROMPT.format(problem=problem_text)
562
+
563
+ messages = [
564
+ {"role": "system", "content": RESPONSE_SOLUTION_LLM_SYS_PROMPT},
565
+ {"role": "user", "content": solution_prompt}
566
+ ]
567
+ text = solution_tokenizer.apply_chat_template(
568
+ messages,
569
+ tokenize=False,
570
+ add_generation_prompt=True
571
+ )
572
+ model_inputs = solution_tokenizer([text], return_tensors="pt").to(solution_model_instance.device)
573
+
574
+ generated_ids = solution_model_instance.generate(
575
+ **model_inputs,
576
+ max_new_tokens=10024
577
+ )
578
+ generated_ids = [
579
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
580
+ ]
581
+ solution = solution_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
582
+
583
+ conn.execute("""
584
+ UPDATE problems
585
+ SET solution = ?, solution_model_name = ?
586
+ WHERE uuid = ?
587
+ """, (solution, solution_model_name.split("/")[-1], problem_id))
588
+ except Exception as e:
589
+ print(f"Error generating solution for problem {problem_id}: {e}")
590
+ pbar.update(1)
591
+ conn.close()
592
+ return "Solutions generated successfully!"
593
+
594
+ # Load problems from DuckDB
595
+ def load_problems_from_duckdb():
596
+ """Load all problems and solutions from the DuckDB database."""
597
+ conn = duckdb.connect(database=DB_FILE)
598
+ df = conn.execute("SELECT * FROM problems").df()
599
+ conn.close()
600
+ return df
601
+
602
+ # Load summary from DuckDB
603
+ def load_summary_from_duckdb():
604
+ conn = duckdb.connect(database=DB_FILE)
605
+
606
+ # Total number of problems
607
+ total_problems = conn.execute("SELECT COUNT(*) FROM problems").fetchone()[0]
608
+
609
+ # Count of distinct domains
610
+ distinct_domains_count = conn.execute("SELECT COUNT(DISTINCT main_domain) FROM problems").fetchone()[0]
611
+
612
+ # Problems by model
613
+ problems_by_model = conn.execute("SELECT model_name, COUNT(*) as count FROM problems GROUP BY model_name").fetchall()
614
+ conn.close()
615
+
616
+ # Build the summary
617
+ summary = f"<h3>Total Problems: {total_problems}</h3>"
618
+ summary += f"<h4>Distinct Domains: {distinct_domains_count}</h4>"
619
+
620
+ summary += "<h4>Problems by Model:</h4><ul>"
621
+ for model_name, count in problems_by_model:
622
+ summary += f"<li>{model_name}: {count}</li>"
623
+ summary += "</ul>"
624
+
625
+ return summary
README.md CHANGED
@@ -1,11 +1,92 @@
1
  ---
2
- title: QuantumLLMInstruct
3
- emoji: 🦀
4
- colorFrom: green
5
- colorTo: indigo
6
- sdk: docker
7
- pinned: false
8
- short_description: 'An open-source dataset designed to assess whether solutions '
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  ---
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+
6
+ ---
7
+
8
+ # QuantumLLMInstruct: A 500k LLM Instruction-Tuning Dataset with Problem-Solution Pairs for Quantum Computing
9
+
10
+ ### Dataset Overview
11
+
12
+ **QuantumLLMInstruct (QLMMI)** is a groundbreaking dataset designed to fine-tune and evaluate Large Language Models (LLMs) in the domain of quantum computing. This dataset spans **90 primary quantum computing domains** and contains over **500,000 rigorously curated instruction-following problem-solution pairs**.
13
+
14
+ The dataset focuses on enhancing reasoning capabilities in LLMs for quantum-specific tasks, including Hamiltonian dynamics, quantum circuit optimization, and Yang-Baxter solvability.
15
+
16
+ Each entry consists of:
17
+ - A **quantum computing problem** expressed in natural language and/or LaTeX.
18
+ - A detailed **step-by-step solution**, designed for precision and clarity.
19
+ - Domain-specific metadata, such as the problem's **main domain**, **sub-domain**, and associated tags.
20
+
21
+ ![QuantumLLMInstruct Workflow](qlmmi-detailed-flowchart.jpg)
22
  ---
23
 
24
+ ### Data Sources
25
+
26
+ The dataset leverages cutting-edge methodologies to generate problems and solutions:
27
+ 1. **Predefined Templates**: Problems crafted using robust templates to ensure domain specificity and mathematical rigor.
28
+ 2. **LLM-Generated Problems**: Models such as `Qwen-2.5-Coder` autonomously generate complex problems across diverse quantum topics, including:
29
+ - Synthetic Hamiltonians
30
+ - QASM code
31
+ - Jordan-Wigner transformations
32
+ - Trotter-Suzuki decompositions
33
+ - Quantum phase estimation
34
+ - Variational Quantum Eigensolvers (VQE)
35
+ - Gibbs state preparation
36
+ 3. **Advanced Reasoning Techniques**: Leveraging Chain-of-Thought (CoT) and Task-Oriented Reasoning and Action (ToRA) frameworks to refine problem-solution pairs.
37
+
38
+ ---
39
+
40
+ ### Structure
41
+
42
+ The dataset contains the following fields:
43
+ - `images`: Optional multimodal inputs, such as visualizations of quantum circuits or spin models.
44
+ - `problem_text`: The quantum computing problem, formatted in plain text or LaTeX.
45
+ - `solution`: A detailed solution generated by state-of-the-art LLMs.
46
+ - `main_domain`: The primary quantum domain, e.g., "Quantum Spin Chains" or "Hamiltonian Dynamics."
47
+ - `sub_domain`: Specific subtopics, e.g., "Ising Models" or "Trotterization."
48
+ - `tags`: Relevant tags for classification and retrieval.
49
+ - `model_name`: The name of the model used to generate the problem or solution.
50
+ - `timestamp`: The date and time of creation.
51
+
52
+ ---
53
+
54
+ ### Key Features
55
+
56
+ - **Comprehensive Coverage**: Spanning 90 primary domains and hundreds of subdomains.
57
+ - **High Quality**: Problems and solutions validated through advanced reasoning frameworks and Judge LLMs.
58
+ - **Open Access**: Designed to support researchers, educators, and developers in the field of quantum computing.
59
+ - **Scalable Infrastructure**: Metadata and structure optimized for efficient querying and usage.
60
+
61
+ ---
62
+
63
+ ### Example Domains
64
+
65
+ Some of the key domains covered in the dataset include:
66
+ - Synthetic Hamiltonians: Energy computations and time evolution.
67
+ - Quantum Spin Chains: Ising, Heisenberg, and advanced integrable models.
68
+ - Yang-Baxter Solvability: Solving for quantum integrable models.
69
+ - Trotter-Suzuki Decompositions: Efficient simulation of Hamiltonian dynamics.
70
+ - Quantum Phase Estimation: Foundational in quantum algorithms.
71
+ - Variational Quantum Eigensolvers (VQE): Optimization for quantum chemistry.
72
+ - Randomized Circuit Optimization: Enhancing algorithm robustness in noisy conditions.
73
+ - Quantum Thermodynamics: Gibbs state preparation and entropy calculations.
74
+
75
+ ---
76
+
77
+ ### Contributions
78
+
79
+ This dataset represents a collaborative effort to advance quantum computing research through the use of large-scale LLMs. It offers:
80
+ 1. A scalable and comprehensive dataset for fine-tuning LLMs.
81
+ 2. Rigorous methodologies for generating and validating quantum problem-solving tasks.
82
+ 3. Open-access resources to foster collaboration and innovation in the quantum computing community.
83
+
84
+ ---
85
 
86
+ Cite:
87
+ @dataset{quantumllm_instruct,
88
+ title={QuantumLLMInstruct: A 500k LLM Instruction-Tuning Dataset with Problem-Solution Pairs for Quantum Computing},
89
+ author={Shlomo Kashani},
90
+ year={2025},
91
+ url={https://huggingface.co/datasets/QuantumLLMInstruct}
92
+ }
app.py DELETED
@@ -1,255 +0,0 @@
1
- import numpy as np
2
- import random
3
- import io
4
- import duckdb
5
- import gradio as gr
6
- import math
7
- from datetime import datetime
8
- import PIL
9
- import matplotlib.pyplot as plt
10
- from PIL import Image
11
- import pennylane as qml
12
- import base64
13
- from qutip import *
14
- from qutip.qip.operations import *
15
- from qutip.qip.circuit import QubitCircuit, Gate
16
- import pennylane as qml
17
- from math import pi
18
-
19
- # Define a Pennylane device
20
- dev = qml.device('default.qubit', wires=10)
21
-
22
- # Hugging Face and DuckDB function placeholders
23
- def store_in_hf_dataset(data):
24
- pass
25
-
26
- def load_from_hf_dataset():
27
- return []
28
-
29
- # Function to buffer the plot and return as PIL image
30
- def buffer_plot_and_get(fig):
31
- buf = io.BytesIO()
32
- fig.savefig(buf, format='png')
33
- buf.seek(0)
34
- return PIL.Image.open(buf)
35
-
36
- # Store image in bytes for DuckDB
37
- def pil_image_to_bytes(image):
38
- img_byte_arr = io.BytesIO()
39
- image.save(img_byte_arr, format='PNG')
40
- return img_byte_arr.getvalue()
41
-
42
- # Encode the image in base64 to display in HTML
43
- def encode_image_from_blob(blob):
44
- img_buffer = io.BytesIO(blob)
45
- image = Image.open(img_buffer)
46
- img_str = base64.b64encode(img_buffer.getvalue()).decode("utf-8")
47
- return f'<img src="data:image/png;base64,{img_str}" style="max-width:500px;"/>'
48
-
49
- # Function to generate a random Hamiltonian
50
- def generate_random_hamiltonian(num_qubits):
51
- terms = []
52
- for _ in range(random.randint(1, 5)):
53
- coeff = round(random.uniform(-1, 1), 2)
54
- pauli_ops = [random.choice(['I', 'X', 'Y', 'Z']) for _ in range(num_qubits)]
55
- term = f"{coeff} * {' '.join(pauli_ops)}"
56
- terms.append(term)
57
- return " + ".join(terms)
58
-
59
- # Function to convert Hamiltonian to QASM code
60
- def hamiltonian_to_qasm(hamiltonian, num_qubits):
61
- qasm_code = f"OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[{num_qubits}];\n"
62
- rotations = {i: 0.0 for i in range(num_qubits)}
63
- terms = hamiltonian.split(" + ")
64
-
65
- for term in terms:
66
- coeff, paulis = term.split(" * ")
67
- paulis = paulis.split()
68
- coeff = float(coeff)
69
-
70
- for i, pauli in enumerate(paulis):
71
- if pauli == "X":
72
- qasm_code += f"x q[{i}];\n"
73
- elif pauli == "Y":
74
- qasm_code += f"ry(pi/2) q[{i}];\n"
75
- elif pauli == "Z":
76
- rotations[i] += coeff
77
-
78
- for i, angle in rotations.items():
79
- if angle != 0:
80
- angle_degrees = round(angle * 180 / math.pi, 2)
81
- qasm_code += f"rz({angle_degrees}) q[{i}];\n"
82
-
83
- return qasm_code
84
-
85
- # Function to parse QASM code and create Pennylane circuit
86
- def qasm_to_pennylane(qasm_code):
87
- qasm_lines = qasm_code.split("\n")
88
- num_qubits = int(qasm_lines[2].split('[')[1].split(']')[0]) # Extract number of qubits from QASM
89
-
90
- @qml.qnode(dev)
91
- def circuit():
92
- for line in qasm_lines:
93
- if "x" in line:
94
- qml.PauliX(int(line.split('q[')[1].split(']')[0]))
95
- elif "rz" in line:
96
- angle = float(line.split('(')[1].split(')')[0])
97
- qml.RZ(angle, int(line.split('q[')[1].split(']')[0]))
98
- elif "ry" in line:
99
- qml.RY(pi / 2, int(line.split('q[')[1].split(']')[0]))
100
- return qml.state()
101
-
102
- return circuit
103
-
104
- # Store data in DuckDB
105
- def store_in_duckdb(data, db_file='quantum_hamiltonians.duckdb'):
106
- conn = duckdb.connect(database=db_file)
107
- conn.execute("""CREATE TABLE IF NOT EXISTS hamiltonians (
108
- id INTEGER,
109
- plot BLOB,
110
- hamiltonian VARCHAR,
111
- qasm_code VARCHAR,
112
- trotter_code VARCHAR,
113
- num_qubits INTEGER,
114
- trotter_order INTEGER,
115
- timestamp TIMESTAMP
116
- )""")
117
- conn.executemany("""INSERT INTO hamiltonians (id, plot, hamiltonian, qasm_code, trotter_code, num_qubits, trotter_order, timestamp)
118
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", data)
119
- conn.close()
120
-
121
- # Function to load results from DuckDB
122
- def load_from_duckdb(db_file='quantum_hamiltonians.duckdb'):
123
- conn = duckdb.connect(database=db_file)
124
- df = conn.execute("SELECT * FROM hamiltonians").df()
125
- conn.close()
126
-
127
- # Convert results to HTML with images
128
- html_content = []
129
- for index, row in df.iterrows():
130
- plot_blob = row['plot']
131
- encoded_img = encode_image_from_blob(plot_blob)
132
-
133
- html_content.append(f"""
134
- <table style='width: 100%; border-collapse: collapse; margin: 10px;'>
135
- <tr>
136
- <td style='width: 30%; text-align: center;'>
137
- <h3>Circuit {index + 1}</h3>
138
- {encoded_img} <!-- Display the image -->
139
- </td>
140
- <td style='padding: 10px;'>
141
- <table style='width: 100%; border-collapse: collapse;'>
142
- <tr>
143
- <td><strong>Hamiltonian:</strong></td><td>{row['hamiltonian']}</td>
144
- </tr>
145
- <tr>
146
- <td><strong>QASM Representation:</strong></td><td>{row['qasm_code']}</td>
147
- </tr>
148
- <tr>
149
- <td><strong>Trotter Decomposition:</strong></td><td>{row['trotter_code']}</td>
150
- </tr>
151
- <tr>
152
- <td><strong>Number of Qubits:</strong></td><td>{row['num_qubits']}</td>
153
- </tr>
154
- <tr>
155
- <td><strong>Trotter Order:</strong></td><td>{row['trotter_order']}</td>
156
- </tr>
157
- <tr>
158
- <td><strong>Timestamp:</strong></td><td>{row['timestamp']}</td>
159
- </tr>
160
- </table>
161
- </td>
162
- </tr>
163
- </table>
164
- """)
165
-
166
- return "".join(html_content)
167
-
168
- # Function to generate Hamiltonians
169
- def generate_hamiltonians(num_hamiltonians, selected_qubits, selected_order, write_to_hf, write_to_duckdb):
170
- results_table = []
171
- timestamp = datetime.now()
172
-
173
- for i in range(num_hamiltonians):
174
- num_qubits = random.choice(selected_qubits)
175
- order = selected_order
176
- hamiltonian = generate_random_hamiltonian(num_qubits)
177
- qasm_code = hamiltonian_to_qasm(hamiltonian, num_qubits)
178
- trotter_code = trotter_decomposition(hamiltonian, order)
179
-
180
- # Generate Pennylane circuit from QASM code
181
- circuit = qasm_to_pennylane(qasm_code)
182
-
183
- # Draw the Pennylane circuit and save as an image
184
- fig, ax = qml.draw_mpl(circuit)()
185
- circuit_plot_image = buffer_plot_and_get(fig)
186
- circuit_plot_bytes = pil_image_to_bytes(circuit_plot_image)
187
-
188
- # Append data to results table
189
- results_table.append((i + 1, circuit_plot_bytes, hamiltonian, qasm_code, trotter_code, num_qubits, order, timestamp))
190
-
191
- # Write data to Hugging Face dataset if selected
192
- if write_to_hf:
193
- store_in_hf_dataset(results_table)
194
-
195
- # Write data to DuckDB if selected
196
- if write_to_duckdb:
197
- store_in_duckdb(results_table)
198
-
199
- # Function to load results from either DuckDB or Hugging Face dataset
200
- def load_results(load_from_hf, load_from_duckdb1):
201
- if load_from_hf:
202
- return load_from_hf_dataset()
203
- if load_from_duckdb1:
204
- return load_from_duckdb()
205
-
206
- # Function for Trotter decomposition
207
- def trotter_decomposition(hamiltonian, order):
208
- terms = hamiltonian.split(" + ")
209
- trotter_steps = []
210
-
211
- for term in terms:
212
- coeff, *pauli_ops = term.split(" * ")
213
- coeff = float(coeff)
214
- for _ in range(order):
215
- trotter_steps.append(f"exp({coeff / order}) * ({' * '.join(pauli_ops)})")
216
- for _ in range(order):
217
- trotter_steps.append(f"exp({-coeff / order}) * ({' * '.join(pauli_ops)})")
218
-
219
- return " + ".join(trotter_steps)
220
-
221
-
222
- # Gradio app
223
- with gr.Blocks() as app:
224
- gr.Markdown("# Quantum Hamiltonian Generator")
225
-
226
- with gr.Tab("Generate Hamiltonians"):
227
- num_hamiltonians = gr.Dropdown(label="Select number of Hamiltonians to generate", choices=[1, 10, 20, 100], value=20)
228
- qubit_choices = [1, 2, 3, 4, 5, 6]
229
- selected_qubits = gr.CheckboxGroup(label="Select number of qubits", choices=qubit_choices, value=[1])
230
- order_choices = [1, 2, 3, 4, 5]
231
- selected_order = gr.Dropdown(label="Select Trotter order", choices=order_choices, value=1)
232
-
233
- # Checkboxes for writing to HF dataset and DuckDB
234
- write_to_hf = gr.Checkbox(label="Write to Hugging Face dataset", value=False)
235
- write_to_duckdb = gr.Checkbox(label="Write to DuckDB", value=True)
236
-
237
- generate_button = gr.Button("Generate Hamiltonians")
238
- status = gr.Markdown("Click 'Generate Hamiltonians' to start the process.")
239
-
240
- def update_status(num, qubits, order, write_hf, write_duckdb):
241
- generate_hamiltonians(num, qubits, order, write_hf, write_duckdb)
242
- return "Data stored as per selection."
243
-
244
- generate_button.click(update_status, inputs=[num_hamiltonians, selected_qubits, selected_order, write_to_hf, write_to_duckdb], outputs=status)
245
-
246
- with gr.Tab("View Results"):
247
- load_from_hf = gr.Checkbox(label="Load from Hugging Face dataset", value=False)
248
- load_from_duckdb1 = gr.Checkbox(label="Load from DuckDB", value=True)
249
-
250
- load_button = gr.Button("Load Results")
251
- output_display = gr.HTML()
252
-
253
- load_button.click(load_results, inputs=[load_from_hf, load_from_duckdb1], outputs=output_display)
254
-
255
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
qlmmi-detailed-flowchart.jpg ADDED