Sequential Quantum Gate Decomposer  v1.9.6
Powerful decomposition of general unitarias into one- and two-qubit gates gates
matrix_baseline_validation.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 """Validation: fixed-parameter matrix baseline.
3 
4 Builds the fixed-parameter matrix gate from:
5 - the emitted canonical workflow contract,
6 - the emitted end-to-end trace bundle,
7 - and the committed validation workflow baseline bundle, which already contains
8  the rich 4/6/8/10 fixed-parameter matrix evidence.
9 
10 This layer is intentionally thin:
11 - it preserves one stable exact-regime matrix identity,
12 - it rebinds matrix cases to the canonical workflow ID and version,
13 - and it fails explicitly when required matrix identity or 10-qubit anchor
14  evidence is incomplete.
15 
16 Run with:
17  python benchmarks/density_matrix/workflow_evidence/matrix_baseline_validation.py
18 """
19 
20 from __future__ import annotations
21 
22 import argparse
23 import json
24 import sys
25 from collections import Counter, defaultdict
26 from pathlib import Path
27 
28 REPO_ROOT = Path(__file__).resolve().parents[3]
29 if str(REPO_ROOT) not in sys.path:
30  sys.path.insert(0, str(REPO_ROOT))
31 
32 from benchmarks.density_matrix.workflow_evidence.workflow_contract_validation import (
33  ARTIFACT_FILENAME as WORKFLOW_CONTRACT_ARTIFACT_FILENAME,
34  CONTRACT_VERSION,
35  DEFAULT_OUTPUT_DIR as WORKFLOW_EVIDENCE_OUTPUT_DIR,
36  REFERENCE_BACKEND,
37  WORKFLOW_ID,
38  build_software_metadata,
39  get_git_revision,
40  run_validation as run_workflow_contract_validation,
41  validate_artifact_bundle as validate_workflow_contract_artifact,
42 )
43 from benchmarks.density_matrix.workflow_evidence.end_to_end_trace_validation import (
44  ARTIFACT_FILENAME as END_TO_END_TRACE_ARTIFACT_FILENAME,
45  run_validation as run_end_to_end_trace_validation,
46  validate_artifact_bundle as validate_end_to_end_trace_artifact,
47 )
48 
49 SUITE_NAME = "matrix_baseline_validation"
50 ARTIFACT_FILENAME = "matrix_baseline_bundle.json"
51 DEFAULT_OUTPUT_DIR = WORKFLOW_EVIDENCE_OUTPUT_DIR
52 WORKFLOW_CONTRACT_PATH = DEFAULT_OUTPUT_DIR / WORKFLOW_CONTRACT_ARTIFACT_FILENAME
53 END_TO_END_TRACE_BUNDLE_PATH = DEFAULT_OUTPUT_DIR / END_TO_END_TRACE_ARTIFACT_FILENAME
54 VALIDATION_WORKFLOW_BASELINE_PATH = (
55  REPO_ROOT
56  / "benchmarks"
57  / "density_matrix"
58  / "artifacts"
59  / "validation_evidence"
60  / "workflow_baseline_bundle.json"
61 )
62 MANDATORY_WORKFLOW_QUBITS = (4, 6, 8, 10)
63 PARAMETER_SET_COUNT = 10
64 ARTIFACT_CORE_FIELDS = (
65  "suite_name",
66  "status",
67  "workflow_id",
68  "contract_version",
69  "backend",
70  "reference_backend",
71  "requirements",
72  "thresholds",
73  "software",
74  "provenance",
75  "summary",
76  "required_artifacts",
77  "cases",
78 )
79 
80 
81 def _load_json(path: Path):
82  return json.loads(path.read_text(encoding="utf-8"))
83 
84 
85 def _load_workflow_contract(path: Path = WORKFLOW_CONTRACT_PATH):
86  if path.exists():
87  artifact = _load_json(path)
88  validate_workflow_contract_artifact(artifact)
89  return artifact
90  _, artifact = run_workflow_contract_validation(verbose=False)
91  return artifact
92 
93 
94 def _load_end_to_end_trace_bundle(path: Path = END_TO_END_TRACE_BUNDLE_PATH):
95  if path.exists():
96  artifact = _load_json(path)
97  validate_end_to_end_trace_artifact(artifact)
98  return artifact
99  _, _, _, artifact = run_end_to_end_trace_validation(verbose=False)
100  return artifact
101 
102 
103 def get_required_workflow_qubits(workflow_contract):
104  return tuple(workflow_contract["thresholds"]["required_workflow_qubits"])
105 
106 
107 def get_required_parameter_set_count(workflow_contract):
108  return int(workflow_contract["thresholds"]["fixed_parameter_sets_per_size"])
109 
110 
111 def get_documented_anchor_qubit(workflow_contract):
112  return int(workflow_contract["thresholds"]["documented_anchor_qubit"])
113 
114 
115 def build_requirement_metadata(validation_workflow_baseline_bundle, workflow_contract):
116  requirements = validation_workflow_baseline_bundle["requirements"]
117  return {
118  "workflow_id": workflow_contract["workflow_id"],
119  "contract_version": workflow_contract["contract_version"],
120  "mandatory_workflow_qubits": list(get_required_workflow_qubits(workflow_contract)),
121  "fixed_parameter_sets_per_size": get_required_parameter_set_count(
122  workflow_contract
123  ),
124  "mandatory_parameter_set_ids": list(requirements["mandatory_parameter_set_ids"]),
125  "required_case_names": list(requirements["mandatory_case_names"]),
126  "documented_anchor_qubit": get_documented_anchor_qubit(workflow_contract),
127  "required_bundle_sources": [
128  workflow_contract["suite_name"],
129  "end_to_end_trace_validation",
130  "workflow_baseline_validation",
131  ],
132  }
133 
134 
135 def build_threshold_metadata(workflow_contract, validation_workflow_baseline_bundle):
136  contract_thresholds = workflow_contract["thresholds"]
137  workflow_thresholds = validation_workflow_baseline_bundle["thresholds"]
138  threshold_fields = (
139  "absolute_energy_error",
140  "rho_is_valid_tol",
141  "trace_deviation",
142  "observable_imag_abs",
143  "required_pass_rate",
144  "required_workflow_qubits",
145  "fixed_parameter_sets_per_size",
146  "documented_anchor_qubit",
147  )
148  return {
149  field: contract_thresholds[field] for field in threshold_fields
150  }, all(
151  workflow_thresholds[field] == contract_thresholds[field]
152  for field in threshold_fields
153  if field in workflow_thresholds
154  )
155 
156 
158  required_fields = (
159  "case_name",
160  "status",
161  "backend",
162  "reference_backend",
163  "qbit_num",
164  "workflow_completed",
165  "parameter_set_id",
166  "absolute_energy_error",
167  "energy_pass",
168  "density_valid_pass",
169  "trace_pass",
170  "observable_pass",
171  "bridge_supported_pass",
172  "support_tier",
173  "case_purpose",
174  "counts_toward_mandatory_baseline",
175  "workflow_id",
176  "contract_version",
177  "workflow_evidence_role",
178  "required_matrix_case",
179  )
180  missing_fields = [field for field in required_fields if field not in case]
181  if missing_fields:
182  raise ValueError(
183  "Matrix baseline case is missing required fields: {}".format(
184  ", ".join(missing_fields)
185  )
186  )
187 
188 
189 def build_case_identity_summary(cases, requirements):
190  expected_case_names = set(requirements["required_case_names"])
191  expected_parameter_set_ids = set(requirements["mandatory_parameter_set_ids"])
192 
193  observed_case_names = [case["case_name"] for case in cases]
194  case_counts = Counter(observed_case_names)
195  duplicate_case_names = sorted(
196  case_name for case_name, count in case_counts.items() if count > 1
197  )
198  missing_mandatory_case_names = sorted(expected_case_names - set(observed_case_names))
199  unexpected_case_names = sorted(set(observed_case_names) - expected_case_names)
200 
201  parameter_sets_per_qbit = defaultdict(list)
202  for case in cases:
203  parameter_sets_per_qbit[case["qbit_num"]].append(case["parameter_set_id"])
204 
205  missing_parameter_set_ids_by_qbit = {}
206  duplicate_parameter_set_ids_by_qbit = {}
207  cases_per_qbit = {}
208  for qbit_num in requirements["mandatory_workflow_qubits"]:
209  observed_ids = parameter_sets_per_qbit.get(qbit_num, [])
210  counts = Counter(observed_ids)
211  duplicate_ids = sorted(
212  parameter_set_id
213  for parameter_set_id, count in counts.items()
214  if count > 1
215  )
216  missing_ids = sorted(expected_parameter_set_ids - set(observed_ids))
217  duplicate_parameter_set_ids_by_qbit[str(qbit_num)] = duplicate_ids
218  missing_parameter_set_ids_by_qbit[str(qbit_num)] = missing_ids
219  cases_per_qbit[str(qbit_num)] = len(observed_ids)
220 
221  stable_case_ids_present = (
222  not missing_mandatory_case_names
223  and not duplicate_case_names
224  and not unexpected_case_names
225  and len(observed_case_names) == len(expected_case_names)
226  )
227  stable_parameter_set_ids_present = all(
228  not missing_parameter_set_ids_by_qbit[str(qbit_num)]
229  and not duplicate_parameter_set_ids_by_qbit[str(qbit_num)]
230  for qbit_num in requirements["mandatory_workflow_qubits"]
231  )
232 
233  return {
234  "observed_case_names": observed_case_names,
235  "missing_mandatory_case_names": missing_mandatory_case_names,
236  "duplicate_case_names": duplicate_case_names,
237  "unexpected_case_names": unexpected_case_names,
238  "stable_case_ids_present": stable_case_ids_present,
239  "cases_per_qbit": cases_per_qbit,
240  "missing_parameter_set_ids_by_qbit": missing_parameter_set_ids_by_qbit,
241  "duplicate_parameter_set_ids_by_qbit": duplicate_parameter_set_ids_by_qbit,
242  "stable_parameter_set_ids_present": stable_parameter_set_ids_present,
243  }
244 
245 
246 def _enrich_case(case, workflow_contract):
247  case = dict(case)
248  case["workflow_id"] = workflow_contract["workflow_id"]
249  case["contract_version"] = workflow_contract["contract_version"]
250  case["workflow_evidence_role"] = "required_fixed_parameter_matrix"
251  case["required_matrix_case"] = True
252  return case
253 
254 
256  workflow_contract,
257  end_to_end_trace_bundle,
258  validation_workflow_baseline_bundle,
259 ):
260  requirements = build_requirement_metadata(
261  validation_workflow_baseline_bundle, workflow_contract
262  )
263  threshold_metadata, workflow_thresholds_match_contract = build_threshold_metadata(
264  workflow_contract, validation_workflow_baseline_bundle
265  )
266  cases = [
267  _enrich_case(case, workflow_contract)
268  for case in validation_workflow_baseline_bundle["cases"]
269  ]
270  for case in cases:
272 
273  case_identity = build_case_identity_summary(cases, requirements)
274  total_cases = len(cases)
275  passed_cases = sum(case["status"] == "pass" for case in cases)
276  unsupported_cases = sum(case["status"] == "unsupported" for case in cases)
277  bridge_supported_cases = sum(
278  case.get("bridge_supported_pass", False) for case in cases
279  )
280  all_cases_required = all(case["support_tier"] == "required" for case in cases)
281  all_cases_mandatory = all(
282  case["counts_toward_mandatory_baseline"] for case in cases
283  )
284  all_cases_match_contract = all(
285  case["workflow_id"] == workflow_contract["workflow_id"]
286  and case["contract_version"] == workflow_contract["contract_version"]
287  for case in cases
288  )
289  workflow_inventory_matches_contract = bool(
290  validation_workflow_baseline_bundle["requirements"]["mandatory_workflow_qubits"]
291  == requirements["mandatory_workflow_qubits"]
292  and validation_workflow_baseline_bundle["requirements"][
293  "fixed_parameter_sets_per_size"
294  ]
295  == requirements["fixed_parameter_sets_per_size"]
296  )
297  documented_10q_anchor_present = any(
298  case["qbit_num"] == requirements["documented_anchor_qubit"] for case in cases
299  )
300  matrix_gate_completed = bool(
301  workflow_contract["status"] == "pass"
302  and end_to_end_trace_bundle["status"] == "pass"
303  and validation_workflow_baseline_bundle["status"] == "pass"
304  and case_identity["stable_case_ids_present"]
305  and case_identity["stable_parameter_set_ids_present"]
306  and passed_cases == total_cases
307  and unsupported_cases == 0
308  and bridge_supported_cases == total_cases
309  and all_cases_required
310  and all_cases_mandatory
311  and all_cases_match_contract
312  and workflow_inventory_matches_contract
313  and workflow_thresholds_match_contract
314  and documented_10q_anchor_present
315  )
316 
317  bundle = {
318  "suite_name": SUITE_NAME,
319  "status": "pass" if matrix_gate_completed else "fail",
320  "workflow_id": workflow_contract["workflow_id"],
321  "contract_version": workflow_contract["contract_version"],
322  "backend": workflow_contract["backend"],
323  "reference_backend": workflow_contract["reference_backend"],
324  "requirements": requirements,
325  "thresholds": threshold_metadata,
326  "software": build_software_metadata(),
327  "provenance": {
328  "generation_command": (
329  "python benchmarks/density_matrix/"
330  "workflow_evidence/matrix_baseline_validation.py"
331  ),
332  "working_directory": str(REPO_ROOT),
333  "git_revision": get_git_revision(),
334  "workflow_contract_path": str(WORKFLOW_CONTRACT_PATH),
335  "end_to_end_trace_bundle_path": str(END_TO_END_TRACE_BUNDLE_PATH),
336  "validation_workflow_baseline_path": str(
337  VALIDATION_WORKFLOW_BASELINE_PATH
338  ),
339  },
340  "summary": {
341  "total_cases": total_cases,
342  "passed_cases": passed_cases,
343  "failed_cases": total_cases - passed_cases,
344  "unsupported_cases": unsupported_cases,
345  "bridge_supported_cases": bridge_supported_cases,
346  "required_cases": total_cases,
347  "required_passed_cases": passed_cases,
348  "required_pass_rate": (passed_cases / total_cases) if total_cases else 0.0,
349  "documented_10q_anchor_present": documented_10q_anchor_present,
350  "workflow_inventory_matches_contract": workflow_inventory_matches_contract,
351  "workflow_thresholds_match_contract": workflow_thresholds_match_contract,
352  "all_cases_required": all_cases_required,
353  "all_cases_count_toward_mandatory_baseline": all_cases_mandatory,
354  "all_cases_match_contract": all_cases_match_contract,
355  **case_identity,
356  "matrix_gate_completed": matrix_gate_completed,
357  },
358  "required_artifacts": {
359  "workflow_contract": {
360  "suite_name": workflow_contract["suite_name"],
361  "status": workflow_contract["status"],
362  "workflow_id": workflow_contract["workflow_id"],
363  "contract_version": workflow_contract["contract_version"],
364  "thresholds": workflow_contract["thresholds"],
365  "summary": workflow_contract["summary"],
366  },
367  "end_to_end_trace_reference": {
368  "suite_name": end_to_end_trace_bundle["suite_name"],
369  "status": end_to_end_trace_bundle["status"],
370  "summary": end_to_end_trace_bundle["summary"],
371  },
372  "validation_workflow_baseline_reference": {
373  "suite_name": validation_workflow_baseline_bundle["suite_name"],
374  "status": validation_workflow_baseline_bundle["status"],
375  "summary": validation_workflow_baseline_bundle["summary"],
376  },
377  },
378  "cases": cases,
379  }
381  return bundle
382 
383 
385  missing_fields = [field for field in ARTIFACT_CORE_FIELDS if field not in bundle]
386  if missing_fields:
387  raise ValueError(
388  "Matrix baseline bundle is missing required fields: {}".format(
389  ", ".join(missing_fields)
390  )
391  )
392 
393  if bundle["workflow_id"] != WORKFLOW_ID:
394  raise ValueError(
395  "Matrix baseline bundle has unexpected workflow_id '{}'".format(
396  bundle["workflow_id"]
397  )
398  )
399  if bundle["contract_version"] != CONTRACT_VERSION:
400  raise ValueError(
401  "Matrix baseline bundle has unexpected contract_version '{}'".format(
402  bundle["contract_version"]
403  )
404  )
405  if (
406  bundle["requirements"]["mandatory_workflow_qubits"]
407  != bundle["thresholds"]["required_workflow_qubits"]
408  ):
409  raise ValueError(
410  "Matrix baseline bundle has inconsistent workflow-qubit requirements"
411  )
412  if (
413  bundle["requirements"]["fixed_parameter_sets_per_size"]
414  != bundle["thresholds"]["fixed_parameter_sets_per_size"]
415  ):
416  raise ValueError(
417  "Matrix baseline bundle has inconsistent parameter-set-count requirements"
418  )
419  if (
420  bundle["requirements"]["documented_anchor_qubit"]
421  != bundle["thresholds"]["documented_anchor_qubit"]
422  ):
423  raise ValueError(
424  "Matrix baseline bundle has inconsistent documented-anchor requirements"
425  )
426  if bundle["summary"]["matrix_gate_completed"] != (bundle["status"] == "pass"):
427  raise ValueError(
428  "Matrix baseline bundle matrix_gate_completed summary is inconsistent"
429  )
430  for case in bundle["cases"]:
432  if case["workflow_id"] != bundle["workflow_id"]:
433  raise ValueError(
434  "Matrix baseline case '{}' does not match bundle workflow_id".format(
435  case["case_name"]
436  )
437  )
438  if case["contract_version"] != bundle["contract_version"]:
439  raise ValueError(
440  "Matrix baseline case '{}' does not match bundle contract_version".format(
441  case["case_name"]
442  )
443  )
444  if not bundle["summary"]["all_cases_match_contract"] and bundle["status"] == "pass":
445  raise ValueError(
446  "Matrix baseline bundle cannot pass when matrix cases do not match the canonical contract"
447  )
448  if (
449  bundle["summary"]["workflow_inventory_matches_contract"] is False
450  and bundle["status"] == "pass"
451  ):
452  raise ValueError(
453  "Matrix baseline bundle cannot pass when matrix inventory drifts from workflow-contract metadata"
454  )
455  if (
456  bundle["summary"]["workflow_thresholds_match_contract"] is False
457  and bundle["status"] == "pass"
458  ):
459  raise ValueError(
460  "Matrix baseline bundle cannot pass when matrix thresholds drift from workflow-contract metadata"
461  )
462 
463 
464 def write_artifact_bundle(output_path: Path, bundle):
466  output_path.parent.mkdir(parents=True, exist_ok=True)
467  output_path.write_text(
468  json.dumps(bundle, indent=2, sort_keys=True) + "\n", encoding="utf-8"
469  )
470 
471 
472 def run_validation(
473  *,
474  workflow_contract_path: Path = WORKFLOW_CONTRACT_PATH,
475  end_to_end_trace_bundle_path: Path = END_TO_END_TRACE_BUNDLE_PATH,
476  validation_workflow_baseline_path: Path = VALIDATION_WORKFLOW_BASELINE_PATH,
477  verbose=False,
478 ):
479  workflow_contract = _load_workflow_contract(workflow_contract_path)
480  end_to_end_trace_bundle = _load_end_to_end_trace_bundle(
481  end_to_end_trace_bundle_path
482  )
483  validation_workflow_baseline_bundle = _load_json(
484  validation_workflow_baseline_path
485  )
486  bundle = build_artifact_bundle(
487  workflow_contract,
488  end_to_end_trace_bundle,
489  validation_workflow_baseline_bundle,
490  )
491  if verbose:
492  print(
493  "{} [{}] matrix={}/{} 10q_anchor={}".format(
494  bundle["suite_name"],
495  bundle["status"],
496  bundle["summary"]["required_passed_cases"],
497  bundle["summary"]["required_cases"],
498  bundle["summary"]["documented_10q_anchor_present"],
499  )
500  )
501  return (
502  workflow_contract,
503  end_to_end_trace_bundle,
504  validation_workflow_baseline_bundle,
505  bundle,
506  )
507 
508 
510  parser = argparse.ArgumentParser(description=__doc__)
511  parser.add_argument(
512  "--output-dir",
513  type=Path,
514  default=DEFAULT_OUTPUT_DIR,
515  help="Directory for the matrix-baseline JSON artifact bundle.",
516  )
517  parser.add_argument(
518  "--workflow-contract-path",
519  type=Path,
520  default=WORKFLOW_CONTRACT_PATH,
521  help="Path to the canonical workflow-contract artifact.",
522  )
523  parser.add_argument(
524  "--end-to-end-trace-bundle-path",
525  type=Path,
526  default=END_TO_END_TRACE_BUNDLE_PATH,
527  help="Path to the end-to-end trace bundle.",
528  )
529  parser.add_argument(
530  "--validation-workflow-baseline-path",
531  type=Path,
532  default=VALIDATION_WORKFLOW_BASELINE_PATH,
533  help="Path to the committed validation workflow-baseline bundle.",
534  )
535  parser.add_argument(
536  "--quiet",
537  action="store_true",
538  help="Suppress summary output.",
539  )
540  return parser.parse_args()
541 
542 
543 def main():
544  args = parse_args()
545  _, _, _, bundle = run_validation(
546  workflow_contract_path=args.workflow_contract_path,
547  end_to_end_trace_bundle_path=args.end_to_end_trace_bundle_path,
548  validation_workflow_baseline_path=args.validation_workflow_baseline_path,
549  verbose=not args.quiet,
550  )
551  output_path = args.output_dir / ARTIFACT_FILENAME
552  write_artifact_bundle(output_path, bundle)
553  print(
554  "Wrote {} with status {} ({}/{})".format(
555  output_path,
556  bundle["status"],
557  bundle["summary"]["required_passed_cases"],
558  bundle["summary"]["required_cases"],
559  )
560  )
561  if bundle["status"] != "pass":
562  raise SystemExit(1)
563 
564 
565 if __name__ == "__main__":
566  main()
def build_artifact_bundle(workflow_contract, end_to_end_trace_bundle, validation_workflow_baseline_bundle)
def _enrich_case(case, workflow_contract)
def get_documented_anchor_qubit(workflow_contract)
def build_threshold_metadata(workflow_contract, validation_workflow_baseline_bundle)
def get_required_workflow_qubits(workflow_contract)
def build_software_metadata()
def build_case_identity_summary(cases, requirements)
def get_required_parameter_set_count(workflow_contract)
def build_requirement_metadata(validation_workflow_baseline_bundle, workflow_contract)