Dvirmor100 commited on
Commit
8f5c845
·
1 Parent(s): e027689

feat(llm): create basic llm methods for error mitigation technics

Browse files
src/models/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+
3
+ class ModelName(Enum):
4
+ PHI4 = "phi4"
5
+ QWEN2_5_14B = "qwen2.5:14b"
6
+
7
+ # Example usage
8
+ print(ModelName.PHI4.value) # Output: phi4
9
+ print(ModelName.QWEN2_5_14B.value) # Output: qwen2.5:14b
src/models/jinja_templates/qasm.j2 ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a quantum computing expert specializing in error mitigation and noise-aware quantum circuit optimization. Your objective is to transform the given quantum circuit into an optimized version that minimizes the impact of noise while ensuring that the circuit still produces the correct results in a noisy environment.
2
+
3
+ ### **Optimization Strategy:**
4
+ 1. **Analyze Noise Sources:**
5
+ - Examine the input QASM circuit and identify potential noise-prone components.
6
+ - Review the provided noisy operation information to determine which gates or operations have the highest error rates.
7
+
8
+ 2. **Error Mitigation and Noise Reduction:**
9
+ - **Substitute High-Noise Gates:** Replace high-error-rate gates with equivalent, more robust alternatives that introduce less decoherence.
10
+ - **Circuit Depth Optimization:** Reduce circuit depth and gate count where possible to minimize accumulated noise.
11
+ - **Redundancy Reduction:** Identify and eliminate unnecessary operations while preserving the circuit's logical function.
12
+ - **Gate Compilation and Reordering:** Optimize gate sequences to leverage noise resilience while maintaining computational integrity.
13
+ - **Qubit Connectivity Awareness:** Adjust qubit mapping to minimize long-range interactions that introduce errors.
14
+ - **Error-Correcting Encodings:** Consider encoding techniques (e.g., repetition encoding, decoherence-free subspaces) to improve result fidelity.
15
+
16
+ 3. **Validation & Result Accuracy Enhancement:**
17
+ - Implement techniques such as **readout error mitigation**, **virtual Z-gate corrections**, and **dynamical decoupling** where applicable.
18
+ - If the circuit includes measurements, suggest strategies to improve measurement accuracy and post-processing corrections.
19
+
20
+ ### **Input:**
21
+ #### **Original QASM Circuit:**
22
+ {{ original_qasm }}
23
+
24
+ #### **Noisy Operations and Their Error Rates:**
25
+ {% for op in noisy_operations %}
26
+ - **{{ op.operation }}**:
27
+ - Probability of error: **{{ op.probability }}**
28
+ - Affected Qubits: **{{ op.wires }}**
29
+ {% endfor %}
30
+
31
+ #### **Noisy Results from the Original Circuit:**
32
+ {{ noisy_results }}
33
+
34
+ #### **Excepted Results from the Original Circuit:**
35
+ {{ results }}
36
+
37
+ ### **Output Specification:**
38
+ Your output must be enclosed by `<QASM START>` and `<QASM END>` as follows:
39
+
40
+ <QASM START>
41
+ [Your optimized OPENQASM 2.0 circuit here]
42
+ <QASM END>
43
+
44
+ ### **Key Considerations:**
45
+ - The optimized circuit **must** maintain the original circuit’s logical function while significantly improving result accuracy under noisy conditions.
46
+ - Prioritize practical noise mitigation techniques that are feasible on real quantum hardware.
47
+ - Do not add measurements and comments in the output optimized QASM circuit.
48
+ - Explain the modifications made and how they contribute to **reducing errors and enhancing output correctness**.
src/models/llm_interface.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+
3
+ def chat_completion(user_prompt: str,
4
+ model_name: str = "phi4",
5
+ temperature: float = 0.01,
6
+ top_p: float = 0.99):
7
+ client = OpenAI(
8
+ base_url='http://localhost:11434/v1',
9
+ api_key='ollama', # Required but ignored
10
+ )
11
+
12
+ response = client.chat.completions.create(
13
+ messages=[
14
+ {"role": "system", "content": "You are a quantum computing expert."},
15
+ {
16
+ 'role': 'user',
17
+ 'content': user_prompt,
18
+ }
19
+ ],
20
+ temperature=temperature,
21
+ top_p=top_p,
22
+ model=model_name,
23
+ stream=True # Stream for prevent connection timeout for long response requests
24
+ )
25
+
26
+ final_answer = ""
27
+ for chunk in response:
28
+ if chunk.choices and chunk.choices[0].delta:
29
+ final_answer += chunk.choices[0].delta.content
30
+
31
+ return final_answer
32
+
33
+ if __name__ == '__main__':
34
+ print(chat_completion(user_prompt="Who are you in a sentence", model_name="phi4"))
35
+ print(chat_completion(user_prompt="Who are you in sentence", model_name="qwen2.5:14b"))
src/models/llm_prompt_utils.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from pathlib import Path
3
+ from models.llm_interface import chat_completion
4
+ from quantum_circuits.noisy_qasm_runner import NoisyQASMRunner
5
+ from jinja2 import Environment, FileSystemLoader
6
+ from openai import OpenAI
7
+ from utils.qasm_utils import extract_qasm_from_llm_output
8
+ import logging
9
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
+ logger = logging.getLogger(__name__)
11
+
12
+ def create_prompt(data_dict, refine=False):
13
+ template_name = "qasm.j2"
14
+ if refine:
15
+ template_name = "refine_qasm.j2"
16
+ env = Environment(loader=FileSystemLoader(Path(__file__).parent / "jinja_templates"))
17
+ template = env.get_template(template_name)
18
+ rendered_template = template.render(data_dict)
19
+
20
+ return rendered_template
21
+
22
+ def create_qasm_with_llm(user_prompt: str):
23
+ client = OpenAI(
24
+ base_url='http://localhost:11434/v1',
25
+ api_key='ollama', # Required but ignored
26
+ )
27
+
28
+ response = client.chat.completions.create(
29
+ messages=[
30
+ {"role": "system", "content": "You are a quantum computing expert."},
31
+ {
32
+ 'role': 'user',
33
+ 'content': user_prompt,
34
+ }
35
+ ],
36
+ temperature=0.01,
37
+ top_p=0.99,
38
+ model='phi4',
39
+ stream=True
40
+ )
41
+
42
+ final_answer = ""
43
+ for chunk in response:
44
+ if chunk.choices and chunk.choices[0].delta:
45
+ final_answer += chunk.choices[0].delta.content
46
+
47
+ return extract_qasm_from_llm_output(final_answer)
48
+
49
+ def create_and_run_circuit_by_llm(qasm_circuit, noise_data, noisy_result, noiseless_result):
50
+ circuit_data = {
51
+ "original_qasm": qasm_circuit,
52
+ "noisy_operations": noise_data,
53
+ "noisy_results": noisy_result,
54
+ "results": noiseless_result
55
+ }
56
+
57
+ logger.info("Calling LLM to create circuit #%d", i + 1)
58
+ prompt = create_prompt(circuit_data)
59
+ model_qasm_result = create_qasm_with_llm(prompt)
60
+
61
+ logger.info("Running the circuits on noisy system")
62
+ logger.info("Original Circuit Running:")
63
+ runner = NoisyQASMRunner(model_qasm_result, noise_data)
64
+ original_results = runner.run()
65
+
66
+
67
+ def generate_qasm_with_llm(circuit_data, is_refine=False, model="phi4"):
68
+ prompt = create_prompt(circuit_data, is_refine)
69
+ llm_result = chat_completion(prompt, model_name=model)
70
+ generated_qasm = extract_qasm_from_llm_output(llm_result)
71
+ return generated_qasm
72
+
73
+ def run_noisy_qasm(qasm_circuit, noise_data) -> List[float]:
74
+ runner = NoisyQASMRunner(qasm_circuit, noise_data)
75
+ expectation_values = runner.run()
76
+ return [float(val) for val in expectation_values]
77
+
src/utils/__init__.py ADDED
File without changes