Sequential Quantum Gate Decomposer  v1.9.6
Powerful decomposition of general unitarias into one- and two-qubit gates gates
noisy_runtime_core.py
Go to the documentation of this file.
1 from __future__ import annotations
2 
3 import resource
4 import time
5 from dataclasses import dataclass, field
6 from typing import Any, Iterable, Literal, Mapping
7 
8 import numpy as np
9 
10 from squander.density_matrix import DensityMatrix, NoisyCircuit
11 from squander.partitioning.noisy_descriptor import (
12  descriptor_partition_to_dict,
13  validate_partition_descriptor_set,
14 )
15 from squander.partitioning.noisy_runtime_errors import runtime_validation_error
16 from squander.partitioning.noisy_types import (
17  PARTITIONED_DENSITY_MODE,
18  PLANNER_OP_KIND_GATE,
19  PLANNER_OP_KIND_NOISE,
20  SUPPORTED_GATE_NAMES,
21  SUPPORTED_NOISE_NAMES,
22  NoisyPartitionDescriptor,
23  NoisyPartitionDescriptorMember,
24  NoisyPartitionDescriptorSet,
25 )
26 
27 PHASE3_RUNTIME_PATH_BASELINE = "partitioned_density_descriptor_baseline"
28 PHASE3_RUNTIME_PATH_FUSED_UNITARY_ISLANDS = (
29  "partitioned_density_descriptor_fused_unitary_islands"
30 )
31 PHASE3_RUNTIME_PATH_SEQUENTIAL_REFERENCE = "sequential_density_descriptor_reference"
32 PHASE3_RUNTIME_VALIDITY_TOL = 1e-10
33 
34 PHASE31_RUNTIME_PATH_CHANNEL_NATIVE = "phase31_channel_native"
35 PHASE31_RUNTIME_PATH_CHANNEL_NATIVE_HYBRID = "phase31_channel_native_hybrid"
36 PHASE31_FUSION_KIND_CHANNEL_NATIVE_MOTIF = "channel_native_motif"
37 
38 PHASE3_FUSION_KIND_UNITARY_ISLAND = "unitary_island"
39 PHASE3_FUSION_KIND_NOISE_BOUNDARY = "noise_boundary"
40 
41 PHASE3_FUSION_CLASS_FUSED = "actually_fused"
42 PHASE3_FUSION_CLASS_SUPPORTED_UNFUSED = "supported_but_unfused"
43 PHASE3_FUSION_CLASS_DEFERRED = "deferred_or_unsupported_candidate"
44 
45 # Unitary gates lowered both to NoisyCircuit and to fused kernels (subset of SUPPORTED_GATE_NAMES).
46 _PHASE3_LOWERABLE_UNITARY_GATE_NAMES = frozenset({"U3", "CNOT"})
47 
48 
49 @dataclass(frozen=True)
51  partition_index: int
52  runtime_circuit_qbit_num: int
53  runtime_circuit_parameter_count: int
54  partition_runtime_class: str | None = None
55  partition_route_reason: str | None = None
56 
57  def to_dict(self, descriptor_set: NoisyPartitionDescriptorSet) -> dict[str, Any]:
58  return runtime_partition_audit_dict(descriptor_set, self)
59 
60 
62  descriptor_set: NoisyPartitionDescriptorSet,
63  record: NoisyRuntimePartitionRecord,
64 ) -> dict[str, Any]:
65  partition = descriptor_set.partitions[record.partition_index]
66  payload = descriptor_partition_to_dict(descriptor_set, partition)
67  payload["operation_names"] = [
68  descriptor_set.operations[m.canonical_operation_index].name
69  for m in partition.members
70  ]
71  payload["operation_kinds"] = [
72  descriptor_set.operations[m.canonical_operation_index].kind
73  for m in partition.members
74  ]
75  payload["runtime_circuit_qbit_num"] = record.runtime_circuit_qbit_num
76  payload["runtime_circuit_parameter_count"] = record.runtime_circuit_parameter_count
77  if record.partition_runtime_class is not None:
78  payload["partition_runtime_class"] = record.partition_runtime_class
79  if record.partition_route_reason is not None:
80  payload["partition_route_reason"] = record.partition_route_reason
81  return payload
82 
83 
84 @dataclass(frozen=True)
86  partition_index: int
87  candidate_kind: str
88  classification: str
89  reason: str
90  partition_member_indices: tuple[int, ...]
91  canonical_operation_indices: tuple[int, ...]
92  operation_names: tuple[str, ...]
93  global_target_qbits: tuple[int, ...]
94  local_target_qbits: tuple[int, ...]
95  member_count: int
96  gate_count: int
97 
98  def to_dict(self) -> dict[str, Any]:
99  return {
100  "partition_index": self.partition_index,
101  "candidate_kind": self.candidate_kind,
102  "classification": self.classification,
103  "reason": self.reason,
104  "partition_member_indices": list(self.partition_member_indices),
105  "canonical_operation_indices": list(self.canonical_operation_indices),
106  "operation_names": list(self.operation_names),
107  "global_target_qbits": list(self.global_target_qbits),
108  "local_target_qbits": list(self.local_target_qbits),
109  "member_count": self.member_count,
110  "gate_count": self.gate_count,
111  }
112 
113 
114 @dataclass(frozen=True)
116  """Partitioned runtime outcome. runtime_path is realized (may downgrade to baseline)."""
117 
118  requested_mode: str
119  source_type: str
120  workload_id: str
121  qbit_num: int
122  parameter_count: int
123  runtime_path: str
124  requested_runtime_path: str
125  exact_output_present: bool
126  density_matrix: DensityMatrix
127  descriptor_set: NoisyPartitionDescriptorSet = field(repr=False)
128  partitions: tuple[NoisyRuntimePartitionRecord, ...]
129  fused_regions: tuple[NoisyRuntimeFusedRegionRecord, ...]
130  runtime_ms: float
131  peak_rss_kb: int
132 
133  @property
134  def provenance(self) -> dict[str, Any]:
135  return {
136  "source_type": self.source_type,
137  "workload_id": self.workload_id,
138  }
139 
140  @property
141  def partition_count(self) -> int:
142  return len(self.partitions)
143 
144  @property
145  def descriptor_member_count(self) -> int:
146  return self.descriptor_set.descriptor_member_count
147 
148  @property
149  def gate_count(self) -> int:
150  return self.descriptor_set.gate_count
151 
152  @property
153  def noise_count(self) -> int:
154  return self.descriptor_set.noise_count
155 
156  @property
157  def max_partition_span(self) -> int:
158  return self.descriptor_set.max_partition_span
159 
160  @property
161  def partition_member_counts(self) -> tuple[int, ...]:
162  return self.descriptor_set.partition_member_counts
163 
164  @property
165  def remapped_partition_count(self) -> int:
166  return sum(
167  self.descriptor_set.partitions[rec.partition_index].requires_remap
168  for rec in self.partitions
169  )
170 
171  @property
173  return sum(
174  len(self.descriptor_set.partition_parameter_routing(p))
175  for p in self.descriptor_set.partitions
176  )
177 
178  @property
179  def fused_region_count(self) -> int:
180  return sum(
181  region.classification == PHASE3_FUSION_CLASS_FUSED
182  for region in self.fused_regions
183  )
184 
185  @property
187  return sum(
188  region.classification == PHASE3_FUSION_CLASS_SUPPORTED_UNFUSED
189  for region in self.fused_regions
190  )
191 
192  @property
193  def deferred_region_count(self) -> int:
194  return sum(
195  region.classification == PHASE3_FUSION_CLASS_DEFERRED
196  for region in self.fused_regions
197  )
198 
199  @property
200  def fused_gate_count(self) -> int:
201  return sum(
202  region.gate_count
203  for region in self.fused_regions
204  if region.classification == PHASE3_FUSION_CLASS_FUSED
205  )
206 
207  @property
209  return sum(
210  region.gate_count
211  for region in self.fused_regions
212  if region.classification == PHASE3_FUSION_CLASS_SUPPORTED_UNFUSED
213  )
214 
215  @property
216  def actual_fused_execution(self) -> bool:
217  return self.fused_region_count > 0
218 
219  @property
220  def trace(self) -> complex:
221  return complex(self.density_matrix.trace())
222 
223  @property
224  def trace_deviation(self) -> float:
225  return float(abs(self.trace - 1.0))
226 
227  @property
228  def rho_is_valid(self) -> bool:
229  return bool(self.density_matrix.is_valid(tol=PHASE3_RUNTIME_VALIDITY_TOL))
230 
231  @property
232  def purity(self) -> float:
233  return float(self.density_matrix.purity())
234 
235  def density_matrix_numpy(self) -> np.ndarray:
236  return np.asarray(self.density_matrix.to_numpy())
237 
239  self, *, include_density_matrix: bool = False
240  ) -> dict[str, Any]:
241  record = {
242  "matrix_included": include_density_matrix,
243  "shape": [self.density_matrix.dim, self.density_matrix.dim],
244  "trace_real": float(np.real(self.trace)),
245  "trace_imag": float(np.imag(self.trace)),
246  "trace_deviation": self.trace_deviation,
247  "rho_is_valid": self.rho_is_valid,
248  "rho_is_valid_tol": PHASE3_RUNTIME_VALIDITY_TOL,
249  "purity": self.purity,
250  "density_real": None,
251  "density_imag": None,
252  }
253  if include_density_matrix:
254  rho_np = self.density_matrix_numpy()
255  record["density_real"] = np.real(rho_np).tolist()
256  record["density_imag"] = np.imag(rho_np).tolist()
257  return record
258 
259  def to_dict(self, *, include_density_matrix: bool = False) -> dict[str, Any]:
260  return {
261  "requested_mode": self.requested_mode,
262  "source_type": self.source_type,
263  "workload_id": self.workload_id,
264  "provenance": self.provenance,
265  "qbit_num": self.qbit_num,
266  "parameter_count": self.parameter_count,
267  "runtime_path": self.runtime_path,
268  "requested_runtime_path": self.requested_runtime_path,
269  "summary": {
270  "exact_output_present": self.exact_output_present,
271  "partition_count": self.partition_count,
272  "descriptor_member_count": self.descriptor_member_count,
273  "gate_count": self.gate_count,
274  "noise_count": self.noise_count,
275  "max_partition_span": self.max_partition_span,
276  "partition_member_counts": list(self.partition_member_counts),
277  "remapped_partition_count": self.remapped_partition_count,
278  "parameter_routing_segment_count": self.parameter_routing_segment_count,
279  "fused_region_count": self.fused_region_count,
280  "supported_unfused_region_count": self.supported_unfused_region_count,
281  "deferred_region_count": self.deferred_region_count,
282  "fused_gate_count": self.fused_gate_count,
283  "supported_unfused_gate_count": self.supported_unfused_gate_count,
284  "actual_fused_execution": self.actual_fused_execution,
285  "runtime_ms": self.runtime_ms,
286  "peak_rss_kb": self.peak_rss_kb,
287  "density_trace_real": float(np.real(self.trace)),
288  "density_trace_imag": float(np.imag(self.trace)),
289  "trace_deviation": self.trace_deviation,
290  "rho_is_valid": self.rho_is_valid,
291  "rho_is_valid_tol": PHASE3_RUNTIME_VALIDITY_TOL,
292  "purity": self.purity,
293  },
294  "exact_output": self.build_exact_output_record(
295  include_density_matrix=include_density_matrix
296  ),
297  "partitions": [rec.to_dict(self.descriptor_set) for rec in self.partitions],
298  "fused_regions": [region.to_dict() for region in self.fused_regions],
299  }
300 
301 
303  descriptor_set: NoisyPartitionDescriptorSet,
304  parameters: Iterable[float],
305  *,
306  runtime_path: str,
307 ) -> np.ndarray:
308  parameter_vector = np.asarray(list(parameters), dtype=np.float64)
309  if parameter_vector.ndim != 1:
311  descriptor_set,
312  category="runtime_request",
313  first_unsupported_condition="parameter_vector",
314  failure_stage="runtime_preflight",
315  runtime_path=runtime_path,
316  reason="Partitioned runtime requires a one-dimensional parameter vector",
317  )
318  if parameter_vector.size != descriptor_set.parameter_count:
320  descriptor_set,
321  category="runtime_request",
322  first_unsupported_condition="parameter_count",
323  failure_stage="runtime_preflight",
324  runtime_path=runtime_path,
325  reason=(
326  "Partitioned runtime workload '{}' requires {} parameters, got {}".format(
327  descriptor_set.workload_id,
328  descriptor_set.parameter_count,
329  parameter_vector.size,
330  )
331  ),
332  )
333  return parameter_vector
334 
335 
337  descriptor_set: NoisyPartitionDescriptorSet,
338  member: NoisyPartitionDescriptorMember,
339  *,
340  runtime_path: str,
341 ) -> None:
342  op = descriptor_set.canonical_operation_for(member)
343  if op.kind == PLANNER_OP_KIND_GATE:
344  if op.name not in SUPPORTED_GATE_NAMES:
345  unsupported_gate_condition = (
346  "channel_native_support_surface"
347  if runtime_path == PHASE31_RUNTIME_PATH_CHANNEL_NATIVE
348  else "gate_name"
349  )
351  descriptor_set,
352  category="unsupported_runtime_operation",
353  first_unsupported_condition=unsupported_gate_condition,
354  failure_stage="runtime_preflight",
355  runtime_path=runtime_path,
356  reason=(
357  "Partitioned runtime supports only gate families {}, got '{}'".format(
358  sorted(SUPPORTED_GATE_NAMES), op.name
359  )
360  ),
361  )
362  if op.name == "U3" and op.target_qbit is None:
364  descriptor_set,
365  category="descriptor_to_runtime_mismatch",
366  first_unsupported_condition="target_qbit",
367  failure_stage="runtime_preflight",
368  runtime_path=runtime_path,
369  reason="Partitioned runtime requires target_qbit for U3 operations",
370  )
371  if op.name == "CNOT" and (op.target_qbit is None or op.control_qbit is None):
373  descriptor_set,
374  category="descriptor_to_runtime_mismatch",
375  first_unsupported_condition="control_qbit",
376  failure_stage="runtime_preflight",
377  runtime_path=runtime_path,
378  reason="Partitioned runtime requires both target_qbit and control_qbit for CNOT",
379  )
380  if op.fixed_value is not None:
382  descriptor_set,
383  category="descriptor_to_runtime_mismatch",
384  first_unsupported_condition="fixed_value",
385  failure_stage="runtime_preflight",
386  runtime_path=runtime_path,
387  reason="Partitioned runtime gate members must not carry fixed_value payloads",
388  )
389  return
390 
391  if op.kind == PLANNER_OP_KIND_NOISE:
392  if op.name not in SUPPORTED_NOISE_NAMES:
393  unsupported_noise_condition = (
394  "channel_native_support_surface"
395  if runtime_path == PHASE31_RUNTIME_PATH_CHANNEL_NATIVE
396  else "noise_name"
397  )
399  descriptor_set,
400  category="unsupported_runtime_operation",
401  first_unsupported_condition=unsupported_noise_condition,
402  failure_stage="runtime_preflight",
403  runtime_path=runtime_path,
404  reason=(
405  "Partitioned runtime supports only local-noise families {}, got '{}'".format(
406  sorted(SUPPORTED_NOISE_NAMES), op.name
407  )
408  ),
409  )
410  if op.target_qbit is None:
412  descriptor_set,
413  category="descriptor_to_runtime_mismatch",
414  first_unsupported_condition="target_qbit",
415  failure_stage="runtime_preflight",
416  runtime_path=runtime_path,
417  reason="Partitioned runtime requires target_qbit for local noise operations",
418  )
419  if op.param_count == 0 and op.fixed_value is None:
421  descriptor_set,
422  category="descriptor_to_runtime_mismatch",
423  first_unsupported_condition="fixed_value",
424  failure_stage="runtime_preflight",
425  runtime_path=runtime_path,
426  reason=(
427  "Partitioned runtime requires fixed_value on zero-parameter noise "
428  "operations for workload '{}'".format(descriptor_set.workload_id)
429  ),
430  )
431  return
432 
434  descriptor_set,
435  category="unsupported_runtime_operation",
436  first_unsupported_condition="operation_kind",
437  failure_stage="runtime_preflight",
438  runtime_path=runtime_path,
439  reason="Partitioned runtime does not support descriptor kind '{}'".format(
440  op.kind
441  ),
442  )
443 
444 
445 
452  descriptor_set: NoisyPartitionDescriptorSet,
453  parameters: Iterable[float],
454  *,
455  runtime_path: str = PHASE3_RUNTIME_PATH_BASELINE,
456 ) -> tuple[NoisyPartitionDescriptorSet, np.ndarray]:
457  validated_descriptor_set = validate_partition_descriptor_set(descriptor_set)
458  parameter_vector = _coerce_parameter_vector(
459  validated_descriptor_set, parameters, runtime_path=runtime_path
460  )
461  if validated_descriptor_set.requested_mode != PARTITIONED_DENSITY_MODE:
463  validated_descriptor_set,
464  category="runtime_request",
465  first_unsupported_condition="requested_mode",
466  failure_stage="runtime_preflight",
467  runtime_path=runtime_path,
468  reason=(
469  "Partitioned runtime supports only '{}' requests, got '{}'".format(
470  PARTITIONED_DENSITY_MODE, validated_descriptor_set.requested_mode
471  )
472  ),
473  )
474  for partition in validated_descriptor_set.partitions:
475  for member in partition.members:
477  validated_descriptor_set, member, runtime_path=runtime_path
478  )
479  return validated_descriptor_set, parameter_vector
480 
481 
483  circuit: NoisyCircuit,
484  member: NoisyPartitionDescriptorMember,
485  *,
486  op,
487 ) -> None:
488  """Append U3 or CNOT. Caller must ensure member is a supported unitary gate."""
489  if op.name == "U3":
490  circuit.add_U3(op.target_qbit)
491  return
492  # NoisyCircuit.add_CNOT(target_qbit, control_qbit) matches descriptor field order.
493  circuit.add_CNOT(op.target_qbit, op.control_qbit)
494 
495 
497  descriptor_set: NoisyPartitionDescriptorSet,
498  circuit: NoisyCircuit,
499  member: NoisyPartitionDescriptorMember,
500  *,
501  runtime_path: str,
502 ) -> None:
503  """Lower one member; members must already satisfy validate_runtime_request."""
504  op = descriptor_set.canonical_operation_for(member)
505  if op.kind == PLANNER_OP_KIND_GATE:
506  if op.name in _PHASE3_LOWERABLE_UNITARY_GATE_NAMES:
507  _append_lowered_unitary_gate(circuit, member, op=op)
508  return
509  elif op.kind == PLANNER_OP_KIND_NOISE:
510  if op.name == "local_depolarizing":
511  if op.param_count == 0:
512  circuit.add_local_depolarizing(op.target_qbit, op.fixed_value)
513  else:
514  circuit.add_local_depolarizing(op.target_qbit)
515  return
516  if op.name == "amplitude_damping":
517  if op.param_count == 0:
518  circuit.add_amplitude_damping(op.target_qbit, op.fixed_value)
519  else:
520  circuit.add_amplitude_damping(op.target_qbit)
521  return
522  if op.name == "phase_damping":
523  if op.param_count == 0:
524  circuit.add_phase_damping(op.target_qbit, op.fixed_value)
525  else:
526  circuit.add_phase_damping(op.target_qbit)
527  return
529  descriptor_set,
530  category="unsupported_runtime_operation",
531  first_unsupported_condition="operation_name",
532  failure_stage="runtime_preflight",
533  runtime_path=runtime_path,
534  reason="Partitioned runtime cannot lower operation '{}'".format(op.name),
535  )
536 
537 
539  descriptor_set: NoisyPartitionDescriptorSet,
540  members: Iterable[NoisyPartitionDescriptorMember],
541  *,
542  qbit_num: int,
543  runtime_path: str,
544 ) -> tuple[NoisyCircuit, tuple[NoisyPartitionDescriptorMember, ...]]:
545  """Build a circuit from members already validated by validate_runtime_request (or a slice thereof)."""
546  ordered_members = tuple(members)
547  circuit = NoisyCircuit(qbit_num)
548  for member in ordered_members:
550  descriptor_set, circuit, member, runtime_path=runtime_path
551  )
552  return circuit, ordered_members
553 
554 
555 def _normalize_runtime_operation_name(name: str) -> str:
556  aliases = {
557  "LocalDepolarizing": "local_depolarizing",
558  "AmplitudeDamping": "amplitude_damping",
559  "PhaseDamping": "phase_damping",
560  }
561  return aliases.get(name, name)
562 
563 
565  descriptor_set: NoisyPartitionDescriptorSet,
566  circuit: NoisyCircuit,
567  members: tuple[NoisyPartitionDescriptorMember, ...],
568  *,
569  runtime_path: str,
570  member_sequence_kind: Literal["descriptor", "segment"],
571  param_start_policy: Literal["from_member_attr", "segment_accumulated"],
572  param_start_attr: str | None = None,
573 ) -> None:
574  if param_start_policy == "from_member_attr" and param_start_attr is None:
575  raise ValueError(
576  "param_start_attr is required when param_start_policy is from_member_attr"
577  )
578 
579  if member_sequence_kind == "descriptor":
580  count_suffix = "descriptor members contain {}"
581  diverged_operation = (
582  "Partitioned runtime operation info diverged from the descriptor "
583  "contract for workload '{}' at canonical operation {}"
584  )
585  param_mismatch = (
586  "Partitioned runtime circuit expected {} parameters but built {}"
587  )
588  else:
589  count_suffix = "segment members contain {}"
590  diverged_operation = (
591  "Partitioned runtime segment diverged from the descriptor contract "
592  "for workload '{}' at canonical operation {}"
593  )
594  param_mismatch = (
595  "Partitioned runtime segment expected {} parameters but built {}"
596  )
597 
598  operation_info = list(circuit.get_operation_info())
599  if len(operation_info) != len(members):
601  descriptor_set,
602  category="descriptor_to_runtime_mismatch",
603  first_unsupported_condition="operation_count",
604  failure_stage="runtime_preflight",
605  runtime_path=runtime_path,
606  reason=(
607  "Partitioned runtime built {} operations for workload '{}' but the "
608  + count_suffix
609  ).format(len(operation_info), descriptor_set.workload_id, len(members)),
610  )
611 
612  running_segment_param = 0
613  for info, member in zip(operation_info, members):
614  op = descriptor_set.canonical_operation_for(member)
615  if param_start_policy == "from_member_attr":
616  if hasattr(member, param_start_attr):
617  expected_param_start = getattr(member, param_start_attr) # type: ignore[arg-type]
618  else:
619  expected_param_start = getattr(op, param_start_attr)
620  else:
621  expected_param_start = running_segment_param
622  if (
623  _normalize_runtime_operation_name(info.name) != op.name
624  or info.is_unitary != op.is_unitary
625  or info.param_count != op.param_count
626  or info.param_start != expected_param_start
627  ):
629  descriptor_set,
630  category="descriptor_to_runtime_mismatch",
631  first_unsupported_condition="operation_info",
632  failure_stage="runtime_preflight",
633  runtime_path=runtime_path,
634  reason=diverged_operation.format(
635  descriptor_set.workload_id, member.canonical_operation_index
636  ),
637  )
638  if param_start_policy == "segment_accumulated":
639  running_segment_param += op.param_count
640 
641  if param_start_policy == "from_member_attr":
642  expected_parameter_total = sum(
643  descriptor_set.canonical_operation_for(m).param_count for m in members
644  )
645  else:
646  expected_parameter_total = running_segment_param
647 
648  if circuit.parameter_num != expected_parameter_total:
650  descriptor_set,
651  category="descriptor_to_runtime_mismatch",
652  first_unsupported_condition="runtime_parameter_count",
653  failure_stage="runtime_preflight",
654  runtime_path=runtime_path,
655  reason=param_mismatch.format(
656  expected_parameter_total, circuit.parameter_num
657  ),
658  )
659 
660 
662  descriptor_set: NoisyPartitionDescriptorSet,
663  partition: NoisyPartitionDescriptor,
664  parameter_vector: np.ndarray,
665  *,
666  runtime_path: str,
667 ) -> np.ndarray:
668  local_parameter_vector = np.zeros(
669  descriptor_set.partition_parameter_count(partition), dtype=np.float64
670  )
671  for (
672  global_param_start,
673  local_param_start,
674  param_count,
675  ) in descriptor_set.partition_parameter_routing(partition):
676  global_stop = global_param_start + param_count
677  local_stop = local_param_start + param_count
678  if (
679  global_stop > parameter_vector.size
680  or local_stop > local_parameter_vector.size
681  ):
683  descriptor_set,
684  category="descriptor_to_runtime_mismatch",
685  first_unsupported_condition="parameter_routing",
686  failure_stage="runtime_preflight",
687  runtime_path=runtime_path,
688  reason=(
689  "Partitioned runtime partition {} has out-of-range parameter_routing".format(
690  partition.partition_index
691  )
692  ),
693  )
694  local_parameter_vector[local_param_start:local_stop] = parameter_vector[
695  global_param_start:global_stop
696  ]
697  return local_parameter_vector
698 
699 
701  partition: NoisyPartitionDescriptor,
702  *,
703  runtime_circuit: NoisyCircuit,
704  partition_runtime_class: str | None = None,
705  partition_route_reason: str | None = None,
706 ) -> NoisyRuntimePartitionRecord:
708  partition_index=partition.partition_index,
709  runtime_circuit_qbit_num=runtime_circuit.qbit_num,
710  runtime_circuit_parameter_count=runtime_circuit.parameter_num,
711  partition_runtime_class=partition_runtime_class,
712  partition_route_reason=partition_route_reason,
713  )
714 
715 
717  regions: tuple[NoisyRuntimeFusedRegionRecord, ...],
718  partition_index: int,
719 ) -> str:
720  for region in regions:
721  if region.partition_index != partition_index:
722  continue
723  if region.classification == PHASE3_FUSION_CLASS_FUSED:
724  return "phase3_unitary_island_fused"
725  return "phase3_supported_unfused"
726 
727 
729  descriptor_set: NoisyPartitionDescriptorSet,
730  members: tuple[NoisyPartitionDescriptorMember, ...],
731  local_parameter_vector: np.ndarray,
732  *,
733  runtime_path: str,
734 ) -> np.ndarray:
735  segment_parameter_count = sum(
736  descriptor_set.canonical_operation_for(m).param_count for m in members
737  )
738  segment_parameters = np.zeros(segment_parameter_count, dtype=np.float64)
739  cursor = 0
740  for member in members:
741  op = descriptor_set.canonical_operation_for(member)
742  local_start = member.local_param_start
743  local_stop = local_start + op.param_count
744  if local_stop > local_parameter_vector.size:
746  descriptor_set,
747  category="descriptor_to_runtime_mismatch",
748  first_unsupported_condition="parameter_routing",
749  failure_stage="runtime_preflight",
750  runtime_path=runtime_path,
751  reason=(
752  "Partitioned runtime segment for workload '{}' references "
753  "out-of-range local parameters at canonical operation {}".format(
754  descriptor_set.workload_id, member.canonical_operation_index
755  )
756  ),
757  )
758  if op.param_count:
759  segment_parameters[cursor : cursor + op.param_count] = (
760  local_parameter_vector[local_start:local_stop]
761  )
762  cursor += op.param_count
763  return segment_parameters
764 
765 
767  descriptor_set: NoisyPartitionDescriptorSet,
768  members: tuple[NoisyPartitionDescriptorMember, ...],
769  local_parameter_vector: np.ndarray,
770  rho: DensityMatrix,
771  *,
772  runtime_path: str,
773 ) -> None:
774  if not members:
775  return
776  segment_circuit, ordered_members = _build_runtime_circuit(
777  descriptor_set,
778  members,
779  qbit_num=descriptor_set.qbit_num,
780  runtime_path=runtime_path,
781  )
783  descriptor_set,
784  segment_circuit,
785  ordered_members,
786  runtime_path=runtime_path,
787  member_sequence_kind="segment",
788  param_start_policy="segment_accumulated",
789  )
790  segment_parameters = _segment_parameter_vector(
791  descriptor_set,
792  ordered_members,
793  local_parameter_vector,
794  runtime_path=runtime_path,
795  )
796  try:
797  segment_circuit.apply_to(segment_parameters, rho)
798  except Exception as exc:
800  descriptor_set,
801  category="unsupported_runtime_execution",
802  first_unsupported_condition="segment_execution",
803  failure_stage="runtime_execution",
804  runtime_path=runtime_path,
805  reason=(
806  "Partitioned runtime failed while executing a member segment of workload "
807  "'{}': {}".format(descriptor_set.workload_id, exc)
808  ),
809  ) from exc
810 
811 
812 def _peak_rss_kb() -> int:
813  return int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
814 
815 
817  descriptor_set: NoisyPartitionDescriptorSet,
818  parameters: Iterable[float],
819  *,
820  runtime_path: str = PHASE3_RUNTIME_PATH_BASELINE,
821  allow_fusion: bool = False,
822 ) -> NoisyRuntimeExecutionResult:
823  from squander.partitioning.noisy_runtime_channel_native import (
824  classify_partition_channel_native_route,
825  execute_partition_channel_native,
826  )
827  from squander.partitioning.noisy_runtime_fusion import (
828  _execute_partition_with_optional_fusion,
829  )
830 
831  requested_runtime_path = runtime_path
832  if allow_fusion and requested_runtime_path == PHASE3_RUNTIME_PATH_BASELINE:
833  requested_runtime_path = PHASE3_RUNTIME_PATH_FUSED_UNITARY_ISLANDS
834  channel_native_path = requested_runtime_path == PHASE31_RUNTIME_PATH_CHANNEL_NATIVE
835  channel_native_hybrid_path = (
836  requested_runtime_path == PHASE31_RUNTIME_PATH_CHANNEL_NATIVE_HYBRID
837  )
838  hybrid_allow_fusion = allow_fusion or channel_native_hybrid_path
839  validated_descriptor_set, parameter_vector = validate_runtime_request(
840  descriptor_set, parameters, runtime_path=requested_runtime_path
841  )
842  result_start = time.perf_counter()
843  rho = DensityMatrix(validated_descriptor_set.qbit_num)
844  partition_records: list[NoisyRuntimePartitionRecord] = []
845  fused_regions: list[NoisyRuntimeFusedRegionRecord] = []
846  for partition in validated_descriptor_set.partitions:
847  partition_circuit, ordered_members = _build_runtime_circuit(
848  validated_descriptor_set,
849  partition.members,
850  qbit_num=validated_descriptor_set.qbit_num,
851  runtime_path=requested_runtime_path,
852  )
854  validated_descriptor_set,
855  partition_circuit,
856  ordered_members,
857  runtime_path=requested_runtime_path,
858  member_sequence_kind="descriptor",
859  param_start_policy="from_member_attr",
860  param_start_attr="local_param_start",
861  )
862  local_parameter_vector = _build_partition_parameter_vector(
863  validated_descriptor_set,
864  partition,
865  parameter_vector,
866  runtime_path=requested_runtime_path,
867  )
868  if channel_native_path:
870  validated_descriptor_set,
871  partition,
872  local_parameter_vector,
873  rho,
874  runtime_path=requested_runtime_path,
875  )
876  fused_regions.extend(recs)
877  partition_records.append(
878  _build_partition_record(partition, runtime_circuit=partition_circuit)
879  )
880  elif channel_native_hybrid_path:
881  eligible, _local_support, route_reason = classify_partition_channel_native_route(
882  validated_descriptor_set,
883  partition,
884  runtime_path=requested_runtime_path,
885  )
886  if eligible:
888  validated_descriptor_set,
889  partition,
890  local_parameter_vector,
891  rho,
892  runtime_path=requested_runtime_path,
893  )
894  fused_regions.extend(recs)
895  partition_records.append(
897  partition,
898  runtime_circuit=partition_circuit,
899  partition_runtime_class="phase31_channel_native",
900  partition_route_reason="eligible_channel_native_motif",
901  )
902  )
903  else:
905  validated_descriptor_set,
906  partition,
907  local_parameter_vector,
908  rho,
909  runtime_path=requested_runtime_path,
910  allow_fusion=hybrid_allow_fusion,
911  )
912  fused_regions.extend(phase3_recs)
913  partition_records.append(
915  partition,
916  runtime_circuit=partition_circuit,
917  partition_runtime_class=_hybrid_phase3_partition_runtime_class(
918  phase3_recs, partition.partition_index
919  ),
920  partition_route_reason=route_reason,
921  )
922  )
923  else:
924  fused_regions.extend(
926  validated_descriptor_set,
927  partition,
928  local_parameter_vector,
929  rho,
930  runtime_path=requested_runtime_path,
931  allow_fusion=allow_fusion,
932  )
933  )
934  partition_records.append(
935  _build_partition_record(partition, runtime_circuit=partition_circuit)
936  )
937  if channel_native_path:
938  actual_runtime_path = PHASE31_RUNTIME_PATH_CHANNEL_NATIVE
939  elif channel_native_hybrid_path:
940  actual_runtime_path = PHASE31_RUNTIME_PATH_CHANNEL_NATIVE_HYBRID
941  else:
942  actual_runtime_path = (
943  requested_runtime_path
944  if any(
945  region.classification == PHASE3_FUSION_CLASS_FUSED
946  for region in fused_regions
947  )
948  else PHASE3_RUNTIME_PATH_BASELINE
949  )
951  requested_mode=validated_descriptor_set.requested_mode,
952  source_type=validated_descriptor_set.source_type,
953  workload_id=validated_descriptor_set.workload_id,
954  qbit_num=validated_descriptor_set.qbit_num,
955  parameter_count=validated_descriptor_set.parameter_count,
956  runtime_path=actual_runtime_path,
957  requested_runtime_path=requested_runtime_path,
958  exact_output_present=True,
959  density_matrix=rho.clone(),
960  descriptor_set=validated_descriptor_set,
961  partitions=tuple(partition_records),
962  fused_regions=tuple(fused_regions),
963  runtime_ms=(time.perf_counter() - result_start) * 1000.0,
964  peak_rss_kb=_peak_rss_kb(),
965  )
966 
967 
969  descriptor_set: NoisyPartitionDescriptorSet,
970  parameters: Iterable[float],
971 ) -> NoisyRuntimeExecutionResult:
973  descriptor_set,
974  parameters,
975  runtime_path=PHASE3_RUNTIME_PATH_FUSED_UNITARY_ISLANDS,
976  allow_fusion=True,
977  )
978 
979 
981  descriptor_set: NoisyPartitionDescriptorSet,
982  parameters: Iterable[float],
983 ) -> NoisyRuntimeExecutionResult:
985  descriptor_set,
986  parameters,
987  runtime_path=PHASE31_RUNTIME_PATH_CHANNEL_NATIVE,
988  allow_fusion=False,
989  )
990 
991 
993  descriptor_set: NoisyPartitionDescriptorSet,
994  parameters: Iterable[float],
995 ) -> NoisyRuntimeExecutionResult:
997  descriptor_set,
998  parameters,
999  runtime_path=PHASE31_RUNTIME_PATH_CHANNEL_NATIVE_HYBRID,
1000  allow_fusion=True,
1001  )
1002 
1003 
1004 
1012  descriptor_set: NoisyPartitionDescriptorSet,
1013  parameters: Iterable[float],
1014  *,
1015  runtime_path: str = PHASE3_RUNTIME_PATH_SEQUENTIAL_REFERENCE,
1016 ) -> DensityMatrix:
1017  validated_descriptor_set, parameter_vector = validate_runtime_request(
1018  descriptor_set, parameters, runtime_path=runtime_path
1019  )
1020  flattened_members = tuple(
1021  member
1022  for partition in validated_descriptor_set.partitions
1023  for member in partition.members
1024  )
1025  circuit, ordered_members = _build_runtime_circuit(
1026  validated_descriptor_set,
1027  flattened_members,
1028  qbit_num=validated_descriptor_set.qbit_num,
1029  runtime_path=runtime_path,
1030  )
1032  validated_descriptor_set,
1033  circuit,
1034  ordered_members,
1035  runtime_path=runtime_path,
1036  member_sequence_kind="descriptor",
1037  param_start_policy="from_member_attr",
1038  param_start_attr="param_start",
1039  )
1040  rho = DensityMatrix(validated_descriptor_set.qbit_num)
1041  try:
1042  circuit.apply_to(parameter_vector, rho)
1043  except Exception as exc:
1045  validated_descriptor_set,
1046  category="unsupported_runtime_execution",
1047  first_unsupported_condition="sequential_reference_execution",
1048  failure_stage="runtime_execution",
1049  runtime_path=runtime_path,
1050  reason=(
1051  "Sequential reference execution failed for workload '{}': {}".format(
1052  validated_descriptor_set.workload_id,
1053  exc,
1054  )
1055  ),
1056  ) from exc
1057  return rho
1058 
1059 
1061  result: NoisyRuntimeExecutionResult,
1062  *,
1063  metadata: Mapping[str, Any] | None = None,
1064 ) -> dict[str, Any]:
1065  payload = result.to_dict(include_density_matrix=False)
1066  return {
1067  "requested_mode": payload["requested_mode"],
1068  "runtime_path": payload["runtime_path"],
1069  "requested_runtime_path": payload["requested_runtime_path"],
1070  "qbit_num": payload["qbit_num"],
1071  "parameter_count": payload["parameter_count"],
1072  "provenance": payload["provenance"],
1073  "summary": payload["summary"],
1074  "exact_output": payload["exact_output"],
1075  "partitions": payload["partitions"],
1076  "fused_regions": payload["fused_regions"],
1077  "metadata": dict(metadata) if metadata is not None else {},
1078  }
def execute_partitioned_density_channel_native_hybrid
def execute_sequential_density_reference
Execute a sequential density reference.
def execute_partitioned_density_channel_native
def validate_runtime_request
Validate a runtime request.
def validate_partition_descriptor_set
def _execute_partition_with_optional_fusion
: execute a partition with optional fusion explain: this function is used to execute a partition with...