Ana içeriğe geç
NM-RFC-0018

Yoğunluk matrisi yürütmesi ve Kraus kanalları

Tasarım belgesi · Özgün kaynak

RFC'ler tasarım ve değişiklik kayıtlarıdır. Bir önerinin burada bulunması, özelliğin kullanıma hazır olduğu anlamına gelmez. Güncel dil desteğini incele

Özgün belgedeki durum: Öneri

Bağlı özgün kaynak · SHA-256
19c1dd4b47cff373a0caa34bd876ceff0f7d45b559cadfa95f39af7ae5c1f72a

  • Status: proposed
  • Revision: 1 (2026-08-11)
  • Target contract: 0.1.0-experimental
  • Feature flag: experimental.densityMatrixNoise=true
  • Owners: language, runtime, verification, tooling, product, security
  • Depends on: stable @target, @seed, and sample; NM-RFC-0002 exact-version package resolution
  • Does not change: stable @noise, NM-RFC-0017 composed trajectories, the five-qubit statevector ceiling, nm-target-calibration@0.1, mitigation, QEC, or hardware-provider contracts
  • Implementation gate: merging this proposal is not approval to implement it; the review record in section 19 must be completed first

1. Summary

N/M currently models noise with finite-shot statevector trajectories. Those trajectories are useful and reproducible, but they do not expose the exact mixed state produced by a quantum channel. This RFC proposes a separate, explicitly negotiated density-matrix backend:

nm
@target("browser-density-matrix");
@seed(42);

density profile relaxation {
  after H on q[0] apply amplitude_damping(0.02);
  after CNOT on q[0..1]
    apply kraus("package.community.noise@1.2.0", "thermal_pair");
}

@density_noise_profile("relaxation");

qreg q[2];
sample 1024 {
  H(q[0]);
  CNOT(q[0], q[1]);
  measure(q[0]);
  measure(q[1]);
}

The compiler resolves the complete gate plan and every channel before runtime. The runtime evolves one density operator deterministically, validates its physical invariants, publishes exact terminal probabilities, and only then uses the seed to draw the requested finite-shot histogram. Channel application does not consume randomness and therefore does not inherit trajectory RNG semantics.

The proposal is intentionally small. It is an exact local simulator for at most five qubits, not a scale, calibration, hardware-fidelity, or fault-tolerance claim.

2. Frozen decision set

Revision 1 proposes the following decisions as one reviewable unit:

  1. Density execution uses the distinct browser-density-matrix target and experimental.densityMatrixNoise=true; selection is never automatic.
  2. The workload is a bounded unitary prefix followed by terminal Z-basis measurement of every allocated qubit exactly once.
  3. Built-in channels are a closed one-qubit set. Custom channels are typed KrausChannel<1> or KrausChannel<2> exact-version package exports.
  4. Inline source matrices, URLs, runtime channel construction, and unversioned package references are not accepted.
  5. The quantum state evolves deterministically. @seed controls only the finite-shot terminal measurement stream.
  6. The public result is nm-density-matrix-run@0.1 and includes the bounded final density matrix, exact probabilities, sampled histogram, metrics, and provenance without raw source.
  7. The runtime revalidates the complete carrier and Kraus artifacts before allocating a density matrix.
  8. Calibration binding, idle time, leakage, crosstalk, pulses, and readout confusion matrices require later RFCs.

Changing any of these decisions requires a new RFC revision, not an implementation-only interpretation.

3. Goals

  • Add exact mixed-state evolution without changing the statevector fast path.
  • Define a closed, typed, package-resolved Kraus channel boundary.
  • Validate channel dimensions, complete positivity, and trace preservation.
  • Validate density-matrix Hermiticity, unit trace, and positive semidefiniteness with frozen cross-platform tolerances.
  • Keep all untrusted counts and dimensions bounded before allocation.
  • Make exact probabilities and finite-shot estimates visibly distinct.
  • Carry the same closed contract through Core, CLI, Worker, LSP, VS Code, Playground, Experiment Studio, exports, and evidence artifacts.
  • Fail closed wherever the contract cannot be preserved.

4. Non-goals

  • Raising either the density-matrix or statevector ceiling above five qubits.
  • Automatic backend selection or silently upgrading a statevector execution.
  • Leakage levels, erasure, crosstalk topology, non-Markovian memory, Lindblad solvers, pulse waveforms, idle windows, or continuous-time integration.
  • Reading provider calibration or binding nm-target-calibration@0.1.
  • Readout confusion matrices, POVM authoring, mid-circuit measurement, reset, measurement-conditioned control, or QEC correction.
  • ZNE, PEC, readout mitigation, QEC thresholds, logical error rates, device fidelity, quantum advantage, or fault-tolerance evidence.
  • Symbolic matrices, parameterized custom matrices, source-inline matrices, network loading, runtime-sized registers, or dynamic channel selection.
  • Treating a numerically valid channel as physically representative of a real device.

5. Closed source grammar

Revision 1 is line-oriented, like NM-RFC-0017. The declaration header, every channel, closing brace, and activation occupy separate logical lines. A channel may wrap only after the apply token as shown in the example; formatting does not change source order.

ebnf
density-profile      = "density" "profile" identifier "{"
                       density-channel+ "}" ;
density-channel      = "after" gate "on" register-view "apply"
                       density-channel-expression ";" ;
density-channel-expression
                     = builtin-channel | package-kraus-channel ;
builtin-channel      = "amplitude_damping" "(" probability ")"
                     | "phase_damping" "(" probability ")"
                     | "depolarizing" "(" probability ")" ;
package-kraus-channel
                     = "kraus" "(" exact-package-string ","
                       export-name-string ")" ;
register-view        = identifier "[" integer "]"
                     | identifier "[" integer ".." integer "]" ;
density-profile-use  = "@density_noise_profile" "("
                       string-literal ")" ";" ;

The package string uses NM-RFC-0002's canonical package. namespace and an exact version. Ranges, tags, workspace references, URLs, and bare or unversioned identifiers fail closed. The export-name string is an identifier, not a path.

Built-in channels resolve to KrausChannel<1>, so their register view has width one. A package channel's register view has exactly the exported arity. Register-view order is observable. For a two-qubit operator, the first scope entry is the least-significant local basis bit; rows and columns are ordered |00>, |01>, |10>, |11> in that convention. This matches N/M's existing two-qubit matrix application order.

6. Built-in channel definitions

All parameters are finite decimal source literals in the inclusive range 0..1. Expressions, percentages, NaN, Infinity, signed zero spellings, and more than nine fractional decimal digits are rejected.

For the matrices below, I, X, Y, and Z have their ordinary N/M complex-matrix definitions and |b><b| is the computational-basis projector.

6.1 Amplitude damping

For gamma in 0..1:

text
K0 = [[1, 0], [0, sqrt(1 - gamma)]]
K1 = [[0, sqrt(gamma)], [0, 0]]

6.2 Phase damping

For lambda in 0..1:

text
K0 = sqrt(1 - lambda) I
K1 = sqrt(lambda) |0><0|
K2 = sqrt(lambda) |1><1|

This convention multiplies off-diagonal density terms by 1 - lambda.

6.3 Depolarizing

For p in 0..1:

text
K0 = sqrt(1 - p) I
K1 = sqrt(p / 3) X
K2 = sqrt(p / 3) Y
K3 = sqrt(p / 3) Z

Implementations must use these definitions. They may not substitute a trajectory approximation or a differently parameterized channel under the same source spelling.

7. Typed custom Kraus artifact

A package export referenced by kraus(...) resolves at compile time to the strict artifact nm-kraus-channel@0.1. Its closed logical shape is:

text
format: "nm-kraus-channel"
version: "0.1"
identity:
  packageSpecifier: exact canonical package specifier
  exportName: source export name
  packageDigest: immutable registry digest
  arity: 1 | 2
operators:
  ordered list of row-major complex square matrices
limitations:
  localExactSimulatorOnly: true
  calibrationBound: false
integrity:
  algorithm: "fnv1a-64"
  value: canonical artifact checksum

A complex number is exactly a two-element JSON array [real, imaginary] of finite JSON numbers. Each operator has 2^arity rows and columns. The strict reader rejects unknown, inherited, accessor-backed, sparse, or duplicate fields; invalid Unicode; -0; non-canonical numbers; and future versions.

Normative artifact bounds are:

  • arity: one or two qubits;
  • operators: 1..8 in declared order;
  • serialized UTF-8 size: at most 65,536 bytes;
  • identifier/export length: at most 64 Unicode scalar values;
  • package specifier length: at most 160 ASCII bytes; and
  • total complex entries: at most 128.

The compiler resolves and embeds the validated artifact. Runtime never loads a package, file, or URL. FNV-1a-64 detects accidental or unvalidated mutation; it is not authentication, a publisher signature, or collision-resistant identity. Package trust, moderation, immutable registry digest, and signed attestation remain separate evidence and are copied without being upgraded.

8. Program bounds and static rules

  • A module contains at most four density profiles and eight channels per profile. Exactly one activation is required when a profile is present.
  • Profile names are unique. The activation names one declared profile.
  • The program declares exactly one qreg of width 1..5 and exactly one sample block with a literal shot count in 1..4096.
  • The program declares @target("browser-density-matrix") and exactly one uint32 @seed in 0..4294967295.
  • The monomorphized gate-only prefix contains at most 256 executable gates and at most 64 matched channel placements.
  • Each after gate rule matches at least one executable gate. The gate must touch every qubit in the resolved channel scope.
  • Register views are compile-time resolved, non-empty, in range, and free of duplicate physical qubits. Descending views preserve their explicit order.
  • The sample block ends with one Z-basis measurement of every allocated qubit exactly once, in any source order, followed by at most one return.
  • Gates after the first measurement, barriers, reset, non-Z measurements, feed-forward, runtime if, runtime loops, syndrome operations, allocation, calls with unresolved bodies, and executable statements outside the sample block fail closed.
  • Compile-time loops and generics are permitted only after ordinary N/M monomorphization produces a concrete plan within every bound.
  • Stable @noise, NM-RFC-0017 profiles, @mitigation, QEC experiments, and density profiles cannot coexist in contract 0.1.

All byte, collection, arity, qubit, gate, placement, and shot checks occur before matrix dimensions are multiplied and before density storage is allocated. Checked integer arithmetic is mandatory.

9. Normative execution

The initial state is rho = |0...0><0...0|. Density storage is split Float64 real/imaginary row-major storage with dimension d = 2^n and exactly d*d complex entries. Revision 1 therefore allocates at most 1,024 complex entries for the state.

The compiler carrier owns the canonical gate and placement order. For every gate in source order:

  1. apply the exact N/M unitary as rho' = U rho U†;
  2. visit matching channels in profile source order; and
  3. for each channel with ordered scope s, apply rho' = sum_i E(K_i, s) rho E(K_i, s)† in operator order.

E(K_i, s) embeds the local operator on exactly the ordered scope and identity on every other qubit. Implementations may use an equivalent local-index kernel and need not materialize the full embedded matrix, but they must preserve the same Float64 operation order and results within section 10 tolerances.

Channels are not merged, commuted, deduplicated, sampled, or replaced by one random Kraus operator. Source order is observable and part of carrier identity.

After the final channel, diagonal entries yield the exact Z-basis probability vector. Outcome strings use the existing N/M histogram convention. The runtime then creates a fresh mulberry32-v1 terminal-measurement stream from the validated seed and draws exactly the requested shots. This stream is not used for channel application and is not inherited from another simulator stream. Changing seed or shots may change the histogram but must not change the final density matrix, exact probabilities, purity, trace, or channel evidence.

10. Numerical validation

All arithmetic is IEEE-754 binary64 complex arithmetic. The normative absolute tolerance is tau = 1e-10; no relative tolerance is used in contract 0.1. Values with magnitude below tolerance are not silently rounded to make a check pass. Serialization may canonicalize an exact -0 result to 0 only after all checks succeed.

10.1 Channel validation

Before execution, each resolved channel is revalidated:

  • every component is finite;
  • every operator has the exact declared dimension;
  • maxAbs(sum_i K_i† K_i - I) <= tau (trace preservation);
  • the operator-sum form establishes complete positivity; additionally, the constructed Choi matrix must be Hermitian within tau and have no eigenvalue below -tau; and
  • built-in matrices recomputed from the source parameter match the carrier component-by-component within tau.

The runtime rejects rather than normalizes an incomplete channel. It never adds an implicit residual Kraus operator.

10.2 Density validation

The initial state, every post-channel state, and the final state must satisfy:

  • maxAbs(rho - rho†) <= tau;
  • real trace differs from 1 by at most tau and imaginary trace magnitude is at most tau;
  • no Hermitian eigenvalue is below -tau; and
  • every exact probability is in [-tau, 1 + tau] and their sum differs from 1 by at most tau.

An implementation must not symmetrize, renormalize, clamp, or project a state to make it pass. Values inside tolerance may be serialized as their canonical physical boundary value only after the unmodified value and maximum drift are recorded in evidence.

Hermitian eigenvalue checks use a deterministic Jacobi sweep with lexicographic pivot order, a maximum of 64*d*d rotations, and convergence threshold tau/10. Failure to converge is a diagnostic, not an assumed pass. Reference fixtures freeze canonical values and permitted drift on Windows and Linux under the pinned Node 22 toolchain.

11. Compiler/runtime carrier

The closed carrier includes:

  • RFC, contract, target, source identity, seed, shots, and resource bounds;
  • allocated qubits and terminal measurement-to-bit mapping;
  • canonical monomorphized gate plan with numeric parameters;
  • active profile and ordered resolved placements;
  • fully embedded built-in or package Kraus artifacts, exact package identity, export name, registry digest, trust/attestation evidence, and source lines;
  • the numeric policy and random-source version; and
  • FNV-1a-64 checksums over the complete canonical carrier and gate plan.

Raw source is not carried. Before allocation, the public runtime validates exact keys and versions, recomputes every count and checksum, derives a fresh gate plan from its gate input, and requires exact equality with the carrier. Replacing gates, targets, channels, matrices, package identity, placement, seed, shots, tolerances, or limits fails closed.

The checksum is tamper evidence, not authorization. An untrusted caller that can recompute FNV is still constrained by the strict reader, package digest, numeric validation, and fixed bounds.

12. Result and provenance

Successful execution produces nm-density-matrix-run@0.1. Its closed result contains:

  • run/carrier/source identities and implementation version;
  • requested and selected backend, target, qubits, gates, placements, shots, seed, numeric policy, and random-source version;
  • final row-major density matrix and exact basis probabilities;
  • sampled histogram with counts summing exactly to shots;
  • trace, purity Tr(rho^2), maximum Hermiticity drift, minimum eigenvalue, completeness drift, and probability-sum drift;
  • ordered per-channel source line, scope, match count, application count, built-in parameters or exact package provenance; and
  • limitations stating local exact-simulator evidence, no calibration binding, no hardware fidelity, and no mitigation or fault-tolerance claim.

The result contains no raw source and is at most 524,288 UTF-8 bytes. Its FNV-1a-64 integrity covers all fields except the integrity value itself. A strict reader revalidates the matrix, probabilities, histogram, metrics, identity, bounds, and integrity; it never trusts stored derived values.

Purity is a property of the simulated state under the supplied channel, not a claim that a device has that purity.

13. Diagnostics

Tablo 1
CodeMeaning
NM-DENSITY-001explicit experimental negotiation is absent
NM-DENSITY-002malformed, duplicate, or unresolved profile/activation
NM-DENSITY-003invalid channel grammar, built-in parameter, gate, or scope
NM-DENSITY-004byte, profile, channel, qubit, gate, placement, or shot budget exceeded
NM-DENSITY-005required density target, uint32 seed, qreg, sample, or terminal measurement contract is absent
NM-DENSITY-006incompatible directive, dynamic statement, backend, or exporter
NM-DENSITY-007package specifier/export is not exact, typed, immutable, or available offline
NM-DENSITY-008Kraus artifact shape, dimension, finite-number, version, or integrity failure
NM-DENSITY-009channel is not trace preserving or completely positive within the frozen tolerance
NM-DENSITY-010compiler/runtime carrier or gate-plan binding failure
NM-DENSITY-011density state violates Hermiticity, trace, positivity, probability, or convergence rules
NM-DENSITY-012result artifact, recomputation, or provenance validation failure

Disabled syntax is removed before ordinary parsing and reports 001. It never falls back to stable @noise, NM-RFC-0017, or an unknown-statement path.

14. Negotiation and tool surfaces

After approval, every executable surface must expose a separate opt-in:

  • Core: experimentalDensityMatrixNoise: true;
  • CLI: --experimental-density-matrix-noise;
  • Worker request: experimentalDensityMatrixNoise: true plus the closed compiler carrier;
  • LSP/VS Code: initializationOptions.nm.experimental.densityMatrixNoise=true;
  • Playground share/saved context: a new versioned densityMatrixNoise: true field, defaulting false; and
  • Experiment Studio: explicit browser-density-matrix backend selection with no automatic promotion from another lane.

The parser, analyzer, completion list, hover text, CLI, Worker, saved context, share URL, and result evidence must agree on the flag and limits. Source text alone never enables the feature.

This revision creates no runtime, flag, backend, capability-manifest entry, or interactive lab. Those are implementation work after section 19 approval.

15. Export and compatibility

N/M JSON IR may preserve the closed density carrier only after its schema and strict reader are implemented. OpenQASM 2/3, Quantikz, framework exporters, target-native lowering, quantum jobs, and provider adapters fail closed until their own versioned contracts can preserve the channel matrices, placement order, package identity, target, and numeric policy.

Stable programs and NM-RFC-0017 programs behave byte-for-byte as before while the new flag is false. browser-statevector never executes a density carrier, and browser-density-matrix never reports itself as statevector execution. This RFC does not raise any existing backend ceiling.

16. Security and resource policy

  • Parse and validate the top-level byte length before JSON decoding large artifacts where the surface permits it.
  • Reject every count and dimension before multiplication or allocation.
  • Use checked arithmetic for 2^n, d*d, matrix entry counts, and result size.
  • Never invoke getters, prototypes, user callbacks, package code, filesystem paths, URLs, WebAssembly, or dynamic imports while reading a channel.
  • Copy validated numeric arrays into owned storage; never retain caller-owned mutable buffers.
  • Cancel between gates/channels and before eigensolver sweeps. Cancellation returns no partial artifact labeled successful.
  • Enforce a five-second browser execution budget for the maximum accepted fixture; timeout is a structured failure.
  • Logs and telemetry contain identities, counts, timings, and diagnostics, not raw source or full matrices.

17. Product surface after approval

The first product surface is a bounded Density Noise Lab adjacent to the existing Noise Composer, not a replacement for it. It should show:

  • generated source and explicit density target/feature negotiation;
  • exact final probabilities beside a seeded finite-shot histogram;
  • final density matrix, trace, purity, and positivity/completeness drift;
  • ordered channel placement and typed package provenance;
  • the same circuit under the existing statevector trajectory model only when the two plans are contract-compatible; and
  • a persistent boundary explaining that no calibration, device fidelity, leakage, crosstalk, mitigation, QEC threshold, or hardware claim was made.

Experiment Studio may add a density lane only after it can preserve the same carrier and result reader. Imported calibration snapshots remain display-only; binding them to this runtime requires the later calibration-aware timing RFC.

18. Rollout and acceptance criteria

Implementation may begin only after section 19 approval. The proposed sequence is:

  1. Freeze flag-off behavior, grammar fixtures, schemas, strict readers, numeric reference fixtures, and maximum-allocation rejection tests.
  2. Implement built-in one-qubit channels and the exact density kernel behind the distinct backend.
  3. Add typed exact-version package Kraus resolution and public-runtime carrier revalidation.
  4. Add result artifact, CLI/Worker negotiation, fail-closed exporters, LSP, VS Code, Playground, and saved/share context.
  5. Add the localized lab and explicit Experiment Studio lane.
  6. Close hostile-carrier fuzz, deterministic cross-platform conformance, maximum-workload performance, browser, accessibility, security, and named review evidence.

Acceptance requires all of the following:

  • Flag-off density source reports 001 and leaves no executable residue.
  • Stable and NM-RFC-0017 programs remain unchanged.
  • Zero, oversized, future-version, unknown-field, sparse, NaN, Infinity, dimension-overflow, invalid-seed, invalid-shot, and multiple-sample inputs fail before density allocation.
  • Non-CPTP, incorrectly typed, unversioned, missing, mutated, or digest-drifted package channels fail closed.
  • Runtime gate or placement changes fail carrier binding before execution.
  • Built-in channels match the exact definitions in section 6.
  • Same source and channel artifacts produce the same density matrix and exact probabilities across seeds; the same seed and shots also produce the same histogram.
  • Reordering non-commuting channels changes carrier identity and execution.
  • Trace, Hermiticity, PSD, completeness, probability, and purity evidence is recomputed and cannot be forged by editing the result artifact.
  • The five-qubit maximum fixture stays inside the approved time and memory ratchets on Windows and Linux with pinned Node 22.
  • Core, CLI, Worker, LSP, VS Code, Playground, Experiment Studio, lab, spec catalog, EN/TR documentation, and share/save context publish identical boundaries.
  • No surface labels this result calibration-aware, hardware-faithful, mitigated, fault tolerant, or scalable.

19. Required review record

The following decisions require named approval before implementation begins:

Tablo 2
ReviewRequired decisionStatus
Language ownergrammar, exact-version export reference, conflicts, diagnosticspending
Runtime ownerbackend separation, operation order, five-qubit/gate/placement limitspending
Verification ownerCPTP, density invariants, Jacobi policy, 1e-10 tolerancepending
Security ownerstrict artifact reader, allocation order, package trust boundary, time budgetpending
Product ownerexplicit selection, evidence wording, lab/Experiment Studio boundariespending

Approval must be recorded by revising this table with reviewer identity, date, and decision reference, or by a later RFC revision that links an immutable review artifact. A merge commit, passing CI, prototype, or implementation PR is not approval. Until every row is approved, experimental.densityMatrixNoise, browser-density-matrix, nm-kraus-channel@0.1, and nm-density-matrix-run@0.1 are proposed names only and must not be advertised as implemented capabilities.