q8s.runtime 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Qubernetes contributors]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: q8s.runtime
3
+ Version: 0.1.0
4
+ Summary: A runtime library for q8s workloads
5
+ Author-email: Vlad Stirbu <vstirbu@gmail.com>
6
+ Classifier: Development Status :: 4 - Beta
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: Natural Language :: English
10
+ Classifier: Operating System :: MacOS
11
+ Classifier: Operating System :: Microsoft :: Windows
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ License-File: LICENSE
24
+ Requires-Dist: mlflow-skinny
25
+ Requires-Dist: dataclasses-json
26
+ Provides-Extra: matplotlib
27
+ Requires-Dist: matplotlib; extra == "matplotlib"
28
+ Provides-Extra: test
29
+ Requires-Dist: mqt.bench; extra == "test"
30
+ Requires-Dist: qiskit<2.2; extra == "test"
31
+ Requires-Dist: mlflow; extra == "test"
32
+ Requires-Dist: iqm-client[qiskit]; extra == "test"
33
+ Dynamic: license-file
@@ -0,0 +1,50 @@
1
+ # q8s.runtime
2
+
3
+ A runtime library for q8s workloads.
4
+
5
+ ## Installation
6
+
7
+ You can install the q8s.runtime library using pip:
8
+
9
+ ```bash
10
+ pip install q8s.runtime
11
+ ```
12
+
13
+ ## Features
14
+
15
+ ### Qiskit autologging to MLflow
16
+
17
+ ```python
18
+ import mlflow
19
+ from mqt.bench import BenchmarkLevel, get_benchmark
20
+ from q8s.runtime.mlflow.qiskit import autolog
21
+
22
+ autolog()
23
+
24
+ from iqm.qiskit_iqm.fake_backends.fake_aphrodite import IQMFakeAphrodite
25
+ from qiskit.transpiler import generate_preset_pass_manager
26
+
27
+ mlflow.set_experiment("qiskit-transpilation")
28
+
29
+
30
+ with mlflow.start_run():
31
+ qc = get_benchmark(
32
+ benchmark="qft",
33
+ level=BenchmarkLevel.ALG,
34
+ circuit_size=30,
35
+ )
36
+
37
+ backend = IQMFakeAphrodite()
38
+
39
+ manager = generate_preset_pass_manager(
40
+ optimization_level=3, backend=backend, seed_transpiler=42
41
+ )
42
+
43
+ tqc = manager.run(qc)
44
+
45
+ job = backend.run(tqc, shots=1024, memory=True)
46
+
47
+ result = job.result()
48
+
49
+ result.get_counts()
50
+ ```
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "q8s.runtime"
3
+ version = "0.1.0"
4
+ authors = [{ name = "Vlad Stirbu", email = "vstirbu@gmail.com" }]
5
+ description = "A runtime library for q8s workloads"
6
+ requires-python = ">=3.10"
7
+ classifiers = [
8
+ "Development Status :: 4 - Beta",
9
+ "Intended Audience :: Developers",
10
+ "Intended Audience :: Science/Research",
11
+ "Natural Language :: English",
12
+ "Operating System :: MacOS",
13
+ "Operating System :: Microsoft :: Windows",
14
+ "Operating System :: POSIX :: Linux",
15
+ "Programming Language :: Python",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ dependencies = ["mlflow-skinny", "dataclasses-json"]
27
+
28
+ [project.optional-dependencies]
29
+ matplotlib = ["matplotlib"]
30
+
31
+ test = ["mqt.bench", "qiskit<2.2", "mlflow", "iqm-client[qiskit]"]
32
+ [build-system]
33
+ requires = ["setuptools >= 61.0"]
34
+ build-backend = "setuptools.build_meta"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version("q8s.runtime")
@@ -0,0 +1,44 @@
1
+ import base64
2
+ import io
3
+
4
+ import matplotlib.backend_bases
5
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
6
+
7
+
8
+ class Q8SLoggerBackend(FigureCanvasAgg):
9
+ """Custom Matplotlib backend that logs images as base64-encoded strings."""
10
+
11
+ def print_png(self, filename_or_obj, *args, **kwargs):
12
+ """Override the PNG printing to log Base64 instead of saving to a file."""
13
+ buf = io.BytesIO()
14
+ super().print_png(buf, *args, **kwargs)
15
+
16
+ # Convert to base64
17
+ buf.seek(0)
18
+ encoded_image = base64.b64encode(buf.getvalue()).decode("utf-8")
19
+
20
+ # Log to console
21
+ print(f"data:image/png;base64,{encoded_image}\n")
22
+
23
+
24
+ FigureCanvas = Q8SLoggerBackend
25
+ # Register the backend
26
+
27
+
28
+ # Fix: Override `show()` to manually trigger rendering
29
+ def show():
30
+ """Manually process all figures and log their base64 images."""
31
+ import matplotlib._pylab_helpers
32
+
33
+ # Get all active figures
34
+ figures = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()
35
+
36
+ for manager in figures:
37
+ figure = manager.canvas.figure
38
+ canvas = Q8SLoggerBackend(figure)
39
+ canvas.draw() # Render the figure
40
+ canvas.print_png(None) # Trigger our Base64 logging
41
+
42
+
43
+ # Register the custom show function
44
+ matplotlib.backend_bases.show = show
@@ -0,0 +1 @@
1
+ from q8s.runtime.mlflow.qiskit.autologging import autolog
@@ -0,0 +1,290 @@
1
+ import contextvars
2
+ import tempfile
3
+ import time
4
+ from pathlib import Path
5
+
6
+ from mlflow.tracking.fluent import ActiveRun
7
+ import qiskit
8
+ from qiskit.circuit import QuantumCircuit
9
+ from qiskit.transpiler import StagedPassManager
10
+ from qiskit_aer import AerSimulator
11
+
12
+ from mlflow.utils.autologging_utils import autologging_integration, safe_patch
13
+
14
+ from q8s.runtime.mlflow.qiskit.transpiler import (
15
+ find_stage_by_id,
16
+ process_staged_pass_manager,
17
+ )
18
+ from q8s.runtime.qprov.graphs import plot_transpilation_timeline
19
+ from q8s.runtime.qprov.record import (
20
+ CompilationProvenance,
21
+ QProvRecord,
22
+ QuantumCircuitProvenance,
23
+ QuantumComputerProvenance,
24
+ )
25
+
26
+ CONTEXT_NAME = "qiskit_mlflow_autologging_context"
27
+
28
+ _current_context: contextvars.ContextVar[QProvRecord] = contextvars.ContextVar(
29
+ CONTEXT_NAME,
30
+ default=QProvRecord(
31
+ compilation=CompilationProvenance(
32
+ compiler="qiskit", compiler_version=qiskit.version.VERSION
33
+ )
34
+ ),
35
+ )
36
+
37
+
38
+ def get_context() -> QProvRecord:
39
+ ctx = _current_context.get()
40
+ if ctx is None:
41
+ raise RuntimeError("No active autolog context")
42
+ return ctx
43
+
44
+
45
+ @autologging_integration("qiskit")
46
+ def autolog(
47
+ # log_passes=True,
48
+ disable=False,
49
+ silent=False,
50
+ extra_tags=None,
51
+ ) -> None:
52
+ """
53
+ Enables the Qiskit autologging integration.
54
+
55
+ This function is idempotent and can be called multiple times. The integration will only be enabled once.
56
+ """
57
+
58
+ def patched_staged_pass_manager_run(
59
+ original: StagedPassManager.run, # type: ignore[no-untyped-def]
60
+ instance: StagedPassManager,
61
+ *args,
62
+ **kwargs,
63
+ ):
64
+ if disable:
65
+ return original(*args, **kwargs)
66
+
67
+ print("Qiskit autologging integration is enabled for StagedPassManager.run.")
68
+
69
+ start = time.perf_counter()
70
+
71
+ circuit: QuantumCircuit = args[0]
72
+
73
+ ctx = _current_context.get()
74
+
75
+ ctx.circuit = QuantumCircuitProvenance(
76
+ circuit_id=str(id(circuit)),
77
+ name=circuit.name,
78
+ num_qubits=circuit.num_qubits,
79
+ depth=circuit.depth(),
80
+ width=circuit.width(),
81
+ size=circuit.size(),
82
+ gate_counts=dict(circuit.count_ops()),
83
+ )
84
+
85
+ if ctx is None or not isinstance(ctx, QProvRecord):
86
+ raise RuntimeError(
87
+ "No active autolog context. Please call transpile() first."
88
+ )
89
+
90
+ if not silent:
91
+ print("Logging Qiskit transpilation run to MLflow.")
92
+
93
+ kwargs["callback"] = callback
94
+
95
+ ctx.compilation.metadata["stages_pass_info"] = process_staged_pass_manager(
96
+ instance
97
+ )
98
+
99
+ history = original(instance, *args, **kwargs)
100
+
101
+ ctx.compilation.duration_s = time.perf_counter() - start
102
+
103
+ return history
104
+
105
+ safe_patch(
106
+ "qiskit",
107
+ qiskit.transpiler.StagedPassManager,
108
+ "run",
109
+ patched_staged_pass_manager_run,
110
+ manage_run=False,
111
+ extra_tags=extra_tags,
112
+ )
113
+
114
+ def patched_generate_preset_pass_manager(
115
+ original, # type: ignore[no-untyped-def]
116
+ *args,
117
+ **kwargs,
118
+ ):
119
+ """
120
+ Patch the generate_preset_pass_manager function to log the backend information to the QProvRecord.
121
+ """
122
+ print(
123
+ "Qiskit autologging integration is enabled for generate_preset_pass_manager."
124
+ )
125
+
126
+ ctx = _current_context.get()
127
+
128
+ if ctx is None or not isinstance(ctx, QProvRecord):
129
+ raise RuntimeError(
130
+ "No active autolog context. Please call transpile() first."
131
+ )
132
+
133
+ optimization_level = kwargs.get("optimization_level", None)
134
+
135
+ if optimization_level is not None:
136
+ ctx.compilation.optimization_level = optimization_level
137
+ mlflow.log_param("optimization_level", optimization_level)
138
+
139
+ seed_transpiler = kwargs.get("seed_transpiler", None)
140
+
141
+ if seed_transpiler is not None:
142
+ ctx.compilation.seed_transpiler = seed_transpiler
143
+ mlflow.log_param("seed_transpiler", seed_transpiler)
144
+
145
+ backend = kwargs.get("backend", None)
146
+
147
+ if backend is not None:
148
+ ctx.quantum_computer = QuantumComputerProvenance(
149
+ provider="IQM",
150
+ backend_name=backend.name,
151
+ num_qubits=getattr(backend, "num_qubits", None),
152
+ )
153
+ mlflow.log_param("backend_name", backend.name)
154
+
155
+ return original(*args, **kwargs)
156
+
157
+ safe_patch(
158
+ "qiskit",
159
+ qiskit.transpiler,
160
+ "generate_preset_pass_manager",
161
+ patched_generate_preset_pass_manager,
162
+ manage_run=False,
163
+ extra_tags=extra_tags,
164
+ )
165
+
166
+ def patched_backend_run(original, self, *args, **kwargs):
167
+ job = original(self, *args, **kwargs)
168
+
169
+ job_cls = job.__class__
170
+
171
+ def patched_result(original_result, job_self, *r_args, **r_kwargs):
172
+ result = original_result(job_self, *r_args, **r_kwargs)
173
+
174
+ # log result here
175
+ try:
176
+ counts = result.get_counts()
177
+ # print("counts:", counts)
178
+ # mlflow.log_dict(counts, "qiskit/result_counts.json")
179
+ except Exception:
180
+ pass
181
+
182
+ return result
183
+
184
+ safe_patch(
185
+ "qiskit",
186
+ job_cls,
187
+ "result",
188
+ patched_result,
189
+ )
190
+
191
+ return job
192
+
193
+ safe_patch(
194
+ "qiskit",
195
+ AerSimulator,
196
+ "run",
197
+ patched_backend_run,
198
+ )
199
+
200
+ def patched_activerun_exit(original, *args, **kwargs):
201
+ """
202
+ Patch the __exit__ method of ActiveRun to log the QProvRecord to MLflow when the run ends.
203
+ """
204
+ ctx = _current_context.get()
205
+
206
+ if ctx is None or not isinstance(ctx, QProvRecord):
207
+ raise RuntimeError(
208
+ "No active autolog context. Please call transpile() first."
209
+ )
210
+
211
+ log_to_mlflow(ctx)
212
+
213
+ return original(*args, **kwargs)
214
+
215
+ safe_patch(
216
+ "qiskit",
217
+ ActiveRun,
218
+ "__exit__",
219
+ patched_activerun_exit,
220
+ manage_run=False,
221
+ extra_tags=extra_tags,
222
+ )
223
+
224
+
225
+ def callback(pass_, dag, time, property_set, count):
226
+ """
227
+ Callback function for logging pass information during transpilation.
228
+ """
229
+ name = pass_.__class__.__name__
230
+
231
+ ctx = _current_context.get()
232
+
233
+ if ctx is None or not isinstance(ctx, QProvRecord):
234
+ raise RuntimeError("No active autolog context. Please call transpile() first.")
235
+
236
+ pass_metadata = {
237
+ "depth": dag.depth(),
238
+ "size": dag.size(),
239
+ "stage": find_stage_by_id(
240
+ ctx.compilation.metadata["stages_pass_info"], id(pass_)
241
+ ),
242
+ }
243
+
244
+ ctx.compilation.add_pass(
245
+ pass_name=name,
246
+ pass_index=count,
247
+ pass_duration_s=time,
248
+ pass_metadata=pass_metadata,
249
+ )
250
+
251
+
252
+ def log_to_mlflow(record: QProvRecord):
253
+ """
254
+ Logs the QProvRecord to MLflow.
255
+ """
256
+ import mlflow
257
+
258
+ with tempfile.TemporaryDirectory() as tmpdir:
259
+ tmp = Path(tmpdir)
260
+ transpilation_timeline = tmp / "transpilation_timeline.png"
261
+
262
+ qprov_file = tmp / "qprov_record.json"
263
+ qprov_file.write_text(record.to_json(indent=2, sort_keys=True))
264
+
265
+ fig = plot_transpilation_timeline(list(record.compilation.passes))
266
+ fig.savefig(transpilation_timeline, bbox_inches="tight")
267
+
268
+ run = mlflow.active_run()
269
+ if run is None:
270
+ raise RuntimeError("No active MLflow run. Please start a run first.")
271
+
272
+ ctx = _current_context.get()
273
+
274
+ if ctx is None or not isinstance(ctx, QProvRecord):
275
+ raise RuntimeError(
276
+ "No active autolog context. Please call transpile() first."
277
+ )
278
+
279
+ passes = sorted(ctx.compilation.passes, key=lambda p: p.pass_index)
280
+
281
+ mlflow.log_metric("passes_count", len(passes))
282
+ mlflow.log_metric("transpilation_duration", ctx.compilation.duration_s)
283
+ mlflow.log_metric(
284
+ "circuit_depth", passes[-1].pass_metadata.get("depth", 0) if passes else 0
285
+ )
286
+ mlflow.log_metric(
287
+ "circuit_size", passes[-1].pass_metadata.get("size", 0) if passes else 0
288
+ )
289
+
290
+ mlflow.log_artifacts(tmp)
@@ -0,0 +1,70 @@
1
+ from qiskit.transpiler import (
2
+ ConditionalController,
3
+ DoWhileController,
4
+ StagedPassManager,
5
+ )
6
+ from qiskit.passmanager import FlowControllerLinear, GenericPass
7
+
8
+
9
+ def process_pass(
10
+ task: (
11
+ GenericPass | ConditionalController | DoWhileController | FlowControllerLinear
12
+ ),
13
+ stage_info: list[int],
14
+ ):
15
+ """
16
+ Recursively process a pass or controller and collect the IDs of all passes in the stage_info list.
17
+ Args:
18
+ task: The pass or controller to process.
19
+ stage_info: A list to collect the IDs of all passes.
20
+ Returns:
21
+ The updated stage_info list containing the IDs of all passes."""
22
+ if (
23
+ isinstance(task, ConditionalController)
24
+ or isinstance(task, DoWhileController)
25
+ or isinstance(task, FlowControllerLinear)
26
+ ):
27
+ for sub_pass in task.tasks:
28
+ process_pass(sub_pass, stage_info)
29
+ elif isinstance(task, GenericPass):
30
+ if id(task) not in stage_info:
31
+ stage_info.append(id(task))
32
+ else:
33
+ raise ValueError(f"Unknown task type: {type(task)}")
34
+
35
+ return stage_info
36
+
37
+
38
+ def process_staged_pass_manager(manager: StagedPassManager) -> dict[str, list[int]]:
39
+ """
40
+ Process a StagedPassManager and return a dictionary containing the stage names and their corresponding pass IDs.
41
+ Args:
42
+ manager (StagedPassManager): The StagedPassManager to process.
43
+ Returns:
44
+ dict: A dictionary mapping stage names to lists of pass IDs.
45
+ """
46
+ stages_pass_info = {}
47
+
48
+ for stage in manager.expanded_stages:
49
+ stage_pm = getattr(manager, stage, None)
50
+ if stage_pm is None:
51
+ continue
52
+
53
+ stages_pass_info[stage] = process_pass(stage_pm.to_flow_controller(), [])
54
+
55
+ return stages_pass_info
56
+
57
+
58
+ def find_stage_by_id(stage_pass_info: dict[str, list[int]], pass_id: int) -> str | None:
59
+ """
60
+ Find the stage name corresponding to a given pass ID in the staged pass manager.
61
+ Args:
62
+ stage_pass_info (dict): A dictionary mapping stage names to lists of pass IDs.
63
+ pass_id (int): The ID of the pass to find.
64
+ Returns:
65
+ str | None: The name of the stage containing the pass ID, or None if not found.
66
+ """
67
+ for stage, pass_ids in stage_pass_info.items():
68
+ if pass_id in pass_ids:
69
+ return stage
70
+ return None
@@ -0,0 +1,135 @@
1
+ import matplotlib.pyplot as plt
2
+ from matplotlib import colormaps
3
+
4
+
5
+ def plot_transpilation_timeline(passes, figsize=(16, 8)):
6
+ """
7
+ Plot a transpilation timeline.
8
+
9
+ Parameters
10
+ ----------
11
+ passes : list[dict]
12
+ List of pass execution records, e.g.
13
+
14
+ {
15
+ "pass_duration_s": 0.000285,
16
+ "pass_index": 2,
17
+ "pass_metadata": {
18
+ "depth": 14,
19
+ "size": 25,
20
+ "stage": "init"
21
+ },
22
+ "pass_name": "HighLevelSynthesis",
23
+ "pass_type": None
24
+ }
25
+ """
26
+
27
+ passes = sorted(passes, key=lambda p: p.pass_index)
28
+
29
+ labels = [f"{p.pass_index:03d}: {p.pass_name}" for p in passes]
30
+ times = [p.pass_duration_s * 1000 for p in passes]
31
+ depths = [p.pass_metadata.get("depth") for p in passes]
32
+ sizes = [p.pass_metadata.get("size") for p in passes]
33
+ stages = [p.pass_metadata.get("stage", "unknown") for p in passes]
34
+
35
+ x = range(len(passes))
36
+
37
+ fig, ax_time = plt.subplots(figsize=figsize)
38
+
39
+ # Stage background bands
40
+ unique_stages = list(dict.fromkeys(stages))
41
+
42
+ cmap = colormaps["Pastel1"].resampled(max(len(unique_stages), 1))
43
+
44
+ stage_colors = {stage: cmap(i) for i, stage in enumerate(unique_stages)}
45
+
46
+ if stages:
47
+ stage_start = 0
48
+ current_stage = stages[0]
49
+
50
+ for i, stage in enumerate(stages + [None]):
51
+ if stage != current_stage:
52
+ stage_end = i - 1
53
+
54
+ ax_time.axvspan(
55
+ stage_start - 0.5,
56
+ stage_end + 0.5,
57
+ color=stage_colors[current_stage],
58
+ alpha=0.35,
59
+ zorder=0,
60
+ )
61
+
62
+ ax_time.axvline(
63
+ stage_start - 0.5,
64
+ color="gray",
65
+ linestyle="--",
66
+ linewidth=0.8,
67
+ alpha=0.6,
68
+ zorder=1,
69
+ )
70
+
71
+ ax_time.text(
72
+ (stage_start + stage_end) / 2,
73
+ 1.02,
74
+ current_stage,
75
+ transform=ax_time.get_xaxis_transform(),
76
+ ha="center",
77
+ va="bottom",
78
+ fontsize=9,
79
+ fontweight="bold",
80
+ )
81
+
82
+ stage_start = i
83
+ current_stage = stage
84
+
85
+ # Runtime bars
86
+ bars = ax_time.bar(
87
+ x,
88
+ times,
89
+ alpha=0.7,
90
+ label="Runtime",
91
+ zorder=2,
92
+ )
93
+
94
+ ax_time.set_ylabel("Runtime (ms)")
95
+ ax_time.set_xlabel("Transpiler pass")
96
+ ax_time.set_xticks(list(x))
97
+ ax_time.set_xticklabels(labels, rotation=60, ha="right", fontsize=8)
98
+ ax_time.grid(axis="y", linestyle="--", alpha=0.4, zorder=1)
99
+
100
+ # Depth
101
+ ax_depth = ax_time.twinx()
102
+ depth_line = ax_depth.plot(
103
+ list(x),
104
+ depths,
105
+ marker="o",
106
+ linewidth=2,
107
+ label="Depth",
108
+ zorder=3,
109
+ )
110
+ ax_depth.set_ylabel("Circuit depth")
111
+
112
+ # Size
113
+ ax_size = ax_time.twinx()
114
+ ax_size.spines["right"].set_position(("outward", 60))
115
+
116
+ size_line = ax_size.plot(
117
+ list(x),
118
+ sizes,
119
+ marker="s",
120
+ linewidth=2,
121
+ label="Size",
122
+ zorder=3,
123
+ )
124
+ ax_size.set_ylabel("Circuit size")
125
+
126
+ # Combined legend
127
+ handles = [bars] + depth_line + size_line
128
+ legend_labels = ["Runtime (ms)", "Depth", "Size"]
129
+ ax_time.legend(handles, legend_labels, loc="upper left")
130
+
131
+ ax_time.set_title("Transpilation Pass Timeline", pad=20)
132
+
133
+ plt.tight_layout(rect=(0, 0.12, 1, 0.95))
134
+
135
+ return fig
@@ -0,0 +1,124 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field, asdict
4
+ from datetime import datetime, timezone
5
+ from typing import Any
6
+ from uuid import uuid4
7
+
8
+ from dataclasses_json import dataclass_json
9
+
10
+
11
+ @dataclass
12
+ class QuantumCircuitProvenance:
13
+ circuit_id: str
14
+ name: str | None = None
15
+ num_qubits: int | None = None
16
+ depth: int | None = None
17
+ width: int | None = None
18
+ size: int | None = None
19
+ gate_counts: dict[str, int] = field(default_factory=dict)
20
+ qasm: str | None = None
21
+ source: str | None = None
22
+ metadata: dict[str, Any] = field(default_factory=dict)
23
+
24
+
25
+ @dataclass
26
+ class QuantumComputerProvenance:
27
+ provider: str
28
+ backend_name: str
29
+ backend_version: str | None = None
30
+ num_qubits: int | None = None
31
+ basis_gates: list[str] = field(default_factory=list)
32
+ coupling_map: list[tuple[int, int]] = field(default_factory=list)
33
+ simulator: bool | None = None
34
+ calibration_timestamp: datetime | None = None
35
+ qubit_properties: dict[str, Any] = field(default_factory=dict)
36
+ gate_errors: dict[str, Any] = field(default_factory=dict)
37
+ readout_errors: dict[str, Any] = field(default_factory=dict)
38
+ metadata: dict[str, Any] = field(default_factory=dict)
39
+
40
+
41
+ @dataclass
42
+ class PassProvenance:
43
+ pass_name: str
44
+ pass_index: int
45
+ pass_type: str | None = None
46
+ pass_duration_s: float | None = None
47
+ pass_metadata: dict[str, Any] = field(default_factory=dict)
48
+
49
+
50
+ @dataclass
51
+ class CompilationProvenance:
52
+ compiler: str = "qiskit"
53
+ compiler_version: str | None = None
54
+ optimization_level: int | None = None
55
+ initial_layout: Any | None = None
56
+ final_layout: Any | None = None
57
+ routing_method: str | None = None
58
+ translation_method: str | None = None
59
+ scheduling_method: str | None = None
60
+ seed_transpiler: int | None = None
61
+ input_depth: int | None = None
62
+ output_depth: int | None = None
63
+ input_gate_counts: dict[str, int] = field(default_factory=dict)
64
+ output_gate_counts: dict[str, int] = field(default_factory=dict)
65
+ duration_s: float | None = None
66
+ passes: list[PassProvenance] = field(default_factory=list)
67
+ metadata: dict[str, Any] = field(default_factory=dict)
68
+
69
+ def add_pass(
70
+ self,
71
+ pass_name: str,
72
+ pass_index: int,
73
+ pass_type: str | None = None,
74
+ pass_duration_s: float | None = None,
75
+ pass_metadata: dict[str, Any] | None = None,
76
+ ):
77
+ if pass_metadata is None:
78
+ pass_metadata = {}
79
+ self.passes.append(
80
+ PassProvenance(
81
+ pass_name=pass_name,
82
+ pass_index=pass_index,
83
+ pass_type=pass_type,
84
+ pass_duration_s=pass_duration_s,
85
+ pass_metadata=pass_metadata,
86
+ )
87
+ )
88
+
89
+
90
+ @dataclass_json
91
+ @dataclass
92
+ class ExecutionProvenance:
93
+ execution_id: str = field(default_factory=lambda: str(uuid4()))
94
+ job_id: str | None = None
95
+ shots: int | None = None
96
+ status: str | None = None
97
+ submit_time: datetime | None = None
98
+ start_time: datetime | None = None
99
+ end_time: datetime | None = None
100
+ queue_time_s: float | None = None
101
+ execution_time_s: float | None = None
102
+ counts: dict[str, int] = field(default_factory=dict)
103
+ result_metadata: dict[str, Any] = field(default_factory=dict)
104
+
105
+
106
+ @dataclass_json
107
+ @dataclass
108
+ class QProvRecord:
109
+ circuit: QuantumCircuitProvenance | None = None
110
+ quantum_computer: QuantumComputerProvenance | None = None
111
+ compilation: CompilationProvenance | None = None
112
+ execution: ExecutionProvenance | None = None
113
+ created_at: datetime = field(
114
+ default_factory=lambda: datetime.now(timezone.utc),
115
+ metadata={"dataclasses_json": {"encoder": lambda dt: dt.isoformat()}},
116
+ )
117
+ record_id: str = field(default_factory=lambda: str(uuid4()))
118
+ metadata: dict[str, Any] = field(default_factory=dict)
119
+
120
+ def to_dict(self) -> dict[str, Any]:
121
+ return asdict(self)
122
+
123
+ def to_json(self, **kwargs) -> str:
124
+ return dataclass_json.dumps(self, **kwargs)
@@ -0,0 +1,133 @@
1
+ import time
2
+ import json
3
+ import tempfile
4
+ from pathlib import Path
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import mlflow
9
+ from qiskit import QuantumCircuit
10
+ from qiskit.transpiler import StagedPassManager, generate_preset_pass_manager
11
+
12
+ from q8s.runtime.mlflow.qiskit.autologging import get_context
13
+
14
+
15
+ @dataclass
16
+ class MLflowTranspilationManager:
17
+ experiment_name: str = "qiskit-transpilation"
18
+ optimization_level: int = 1
19
+ backend: Any | None = None
20
+ basis_gates: list[str] | None = None
21
+ coupling_map: Any | None = None
22
+
23
+ def __post_init__(self):
24
+ mlflow.set_experiment(self.experiment_name)
25
+
26
+ def transpile(
27
+ self, circuit: QuantumCircuit, run_name: str | None = None
28
+ ) -> QuantumCircuit:
29
+ with mlflow.start_run(run_name=run_name):
30
+ self._log_input(circuit)
31
+
32
+ mlflow.log_params(
33
+ {
34
+ "optimization_level": self.optimization_level,
35
+ "backend": getattr(self.backend, "name", None) or str(self.backend),
36
+ "basis_gates": json.dumps(self.basis_gates),
37
+ "num_qubits_input": circuit.num_qubits,
38
+ }
39
+ )
40
+
41
+ pass_manager: StagedPassManager = generate_preset_pass_manager(
42
+ optimization_level=self.optimization_level,
43
+ backend=self.backend,
44
+ basis_gates=self.basis_gates,
45
+ coupling_map=self.coupling_map,
46
+ )
47
+
48
+ start = time.perf_counter()
49
+ transpiled = pass_manager.run(circuit)
50
+ elapsed = time.perf_counter() - start
51
+
52
+ self._log_output(circuit, transpiled, elapsed)
53
+ self._log_artifacts(circuit, transpiled)
54
+
55
+ return transpiled
56
+
57
+ def _log_input(self, circuit: QuantumCircuit):
58
+ mlflow.log_metrics(
59
+ {
60
+ "input_depth": circuit.depth(),
61
+ "input_size": circuit.size(),
62
+ "input_width": circuit.width(),
63
+ "input_num_qubits": circuit.num_qubits,
64
+ "input_num_clbits": circuit.num_clbits,
65
+ }
66
+ )
67
+
68
+ for gate, count in circuit.count_ops().items():
69
+ mlflow.log_metric(f"input_gate_{gate}", count)
70
+
71
+ def _log_output(
72
+ self,
73
+ original: QuantumCircuit,
74
+ transpiled: QuantumCircuit,
75
+ elapsed: float,
76
+ ):
77
+ mlflow.log_metrics(
78
+ {
79
+ "transpilation_time_s": elapsed,
80
+ "output_depth": transpiled.depth(),
81
+ "output_size": transpiled.size(),
82
+ "output_width": transpiled.width(),
83
+ "output_num_qubits": transpiled.num_qubits,
84
+ "output_num_clbits": transpiled.num_clbits,
85
+ "depth_delta": transpiled.depth() - original.depth(),
86
+ "size_delta": transpiled.size() - original.size(),
87
+ }
88
+ )
89
+
90
+ for gate, count in transpiled.count_ops().items():
91
+ mlflow.log_metric(f"output_gate_{gate}", count)
92
+
93
+ def _log_artifacts(self, original: QuantumCircuit, transpiled: QuantumCircuit):
94
+ with tempfile.TemporaryDirectory() as tmpdir:
95
+ tmp = Path(tmpdir)
96
+
97
+ input_qasm = tmp / "input_circuit.qasm"
98
+ output_qasm = tmp / "transpiled_circuit.qasm"
99
+ summary = tmp / "transpilation_summary.json"
100
+ qprov = tmp / "qprov_record.json"
101
+
102
+ try:
103
+ input_qasm.write_text(original.qasm())
104
+ output_qasm.write_text(transpiled.qasm())
105
+ except AttributeError as e:
106
+ from qiskit.qasm3 import dumps
107
+
108
+ input_qasm.write_text(dumps(original))
109
+ output_qasm.write_text(dumps(transpiled))
110
+
111
+ summary.write_text(
112
+ json.dumps(
113
+ {
114
+ "input": {
115
+ "depth": original.depth(),
116
+ "size": original.size(),
117
+ "count_ops": dict(original.count_ops()),
118
+ },
119
+ "output": {
120
+ "depth": transpiled.depth(),
121
+ "size": transpiled.size(),
122
+ "count_ops": dict(transpiled.count_ops()),
123
+ },
124
+ },
125
+ indent=2,
126
+ )
127
+ )
128
+
129
+ ctx = get_context()
130
+
131
+ qprov.write_text(ctx.to_json(indent=2, sort_keys=True))
132
+
133
+ mlflow.log_artifacts(tmp)
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: q8s.runtime
3
+ Version: 0.1.0
4
+ Summary: A runtime library for q8s workloads
5
+ Author-email: Vlad Stirbu <vstirbu@gmail.com>
6
+ Classifier: Development Status :: 4 - Beta
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: Natural Language :: English
10
+ Classifier: Operating System :: MacOS
11
+ Classifier: Operating System :: Microsoft :: Windows
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ License-File: LICENSE
24
+ Requires-Dist: mlflow-skinny
25
+ Requires-Dist: dataclasses-json
26
+ Provides-Extra: matplotlib
27
+ Requires-Dist: matplotlib; extra == "matplotlib"
28
+ Provides-Extra: test
29
+ Requires-Dist: mqt.bench; extra == "test"
30
+ Requires-Dist: qiskit<2.2; extra == "test"
31
+ Requires-Dist: mlflow; extra == "test"
32
+ Requires-Dist: iqm-client[qiskit]; extra == "test"
33
+ Dynamic: license-file
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/q8s.runtime.egg-info/PKG-INFO
5
+ src/q8s.runtime.egg-info/SOURCES.txt
6
+ src/q8s.runtime.egg-info/dependency_links.txt
7
+ src/q8s.runtime.egg-info/requires.txt
8
+ src/q8s.runtime.egg-info/top_level.txt
9
+ src/q8s/runtime/__init__.py
10
+ src/q8s/runtime/tracking.py
11
+ src/q8s/runtime/matplotlib/backend.py
12
+ src/q8s/runtime/mlflow/qiskit/__init__.py
13
+ src/q8s/runtime/mlflow/qiskit/autologging.py
14
+ src/q8s/runtime/mlflow/qiskit/transpiler.py
15
+ src/q8s/runtime/qprov/graphs.py
16
+ src/q8s/runtime/qprov/record.py
@@ -0,0 +1,11 @@
1
+ mlflow-skinny
2
+ dataclasses-json
3
+
4
+ [matplotlib]
5
+ matplotlib
6
+
7
+ [test]
8
+ mqt.bench
9
+ qiskit<2.2
10
+ mlflow
11
+ iqm-client[qiskit]