tensornet-mps fp64: asymmetric Kraus channel aborts with zero norm in sample and observe (0.16.0)
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 15/100
Research direction
The failure is raised by cutensornetStateCompute at line 650 of the cuTensorNet backend, and the reproducer is the self-contained cudaq_channel_example.py in the issue, run with --target tensornet-mps --channel asymmetric on a GPU node. Start by running the asymmetric observe and sample cases, then the density-matrix-cpu control, and compare the logged zero-norm error with the expected Z0 of 0.11. Done means the asymmetric channel returns a finite expectation within the stated tolerance on tensornet-mps without aborting.
Written by the indexing model from the issue text.
Description
Required prerequisites
- Consulted the security policy; this is a simulation correctness/runtime bug report.
- Read the noise-model documentation.
- Searched the issue tracker for related reports.
- Submit a PR with a failing test (standalone tested reproducer below instead).
Describe the bug
CUDA-Q 0.16.0 tensornet-mps, explicitly selected with option="fp64", aborts when applying a trace-preserving asymmetric Kraus channel to a three-qubit GHZ circuit. This reproduces with both sample and shot-free observe. The same source passes on density-matrix-cpu; symmetric bit-flip Kraus controls pass on both targets.
Both failing processes log:
[Error][cutensornetStateCompute] exception: General channel cannot be applied to state with zero norm.
cuTensorNet error CUTENSORNET_STATUS_INTERNAL_ERROR in line 650
Both exit with code 134. There is no KrausChannel subclass, apply_noise, or application circuit adapter: the source uses cudaq.KrausChannel(matrices), cudaq.NoiseModel() and noise_model.add_channel("x", [site], channel).
The channel uses complex128 matrices, with a=0.12 and b=0.23:
K0 = diag(sqrt(1-a), sqrt(1-b))
K1 = [[0, 0], [sqrt(a), 0]]
K2 = [[0, sqrt(b)], [0, 0]]
Their completeness relation is sum(Kj† Kj)=I. The circuit prepares GHZ with H/CX/CX, then applies X to each site with one local noise channel attached to each uncontrolled X. The three X gates preserve ideal GHZ+, and channels on distinct sites commute with the other X gates. Expected Z0 after noise is b-a=0.11.
Steps to reproduce the bug
Save the exact tested source below as cudaq_channel_example.py. It is self-contained apart from CUDA-Q, NumPy and SciPy. Our cluster requires all execution, including CUDA-Q import, on allocated compute nodes; the source therefore checks SLURM_JOB_ID and rejects login hostnames. On a standalone workstation, only this cluster-specific guard would need adapting (that adaptation has not been tested here).
Activate the environment described below, then run each case in a separate process on an allocated GPU node. Output directories must not already exist:
export CUDAQ_DEFAULT_SIMULATOR=density-matrix-cpu
export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1
export CUTENSORNET_LOG_LEVEL=5
CUTENSORNET_LOG_FILE="$PWD/asymmetric-sample-cutensornet.log" timeout --signal=TERM --kill-after=10s 75s python -u cudaq_channel_example.py --target tensornet-mps --circuit ghz --channel asymmetric --method sample --shots 4096 --trajectories 4096 --seed 272008200 --output asymmetric-sample
CUTENSORNET_LOG_FILE="$PWD/asymmetric-observe-cutensornet.log" timeout --signal=TERM --kill-after=10s 75s python -u cudaq_channel_example.py --target tensornet-mps --circuit ghz --channel asymmetric --method observe --shots 4096 --trajectories 4096 --seed 272008200 --output asymmetric-observe
The observe branch actually passes shots_count=-1, num_trajectories=4096 on the GPU; the CPU branch omits the trajectory keyword. CPU controls use --target density-matrix-cpu; symmetric controls use --channel symmetric --probability .15, each with a fresh output path. The damping controls use --channel damping --probability .25.
Exact tested source (including result persistence and reference checks)
"""Small CUDA-Q matrix-list/add_channel diagnostic; run only on a compute node.
Separate from acquisition runners so channel construction can be tested without
the circuit adapter or production noise model. No subclasses or apply_noise.
Invoke once per setting under an external timeout; this script never retries.
"""
import argparse
import json
import os
from pathlib import Path
import socket
import numpy as np
def kraus_matrices(channel, a, b, probability):
"""Return complex128 operators with the tutorial's matrix-list convention."""
if not all(np.isfinite(p) and 0 <= p <= 1 for p in (a, b, probability)):
raise ValueError('Channel probabilities must be finite and in [0, 1]')
if channel == 'asymmetric':
return [np.diag(np.sqrt([1-a, 1-b])).astype(np.complex128),
np.array([[0, 0], [np.sqrt(a), 0]], dtype=np.complex128),
np.array([[0, np.sqrt(b)], [0, 0]], dtype=np.complex128)]
if channel == 'symmetric':
return [np.sqrt(1-probability) * np.eye(2, dtype=np.complex128),
np.sqrt(probability) * np.array([[0, 1], [1, 0]], dtype=np.complex128)]
if channel == 'damping':
return [np.diag([1, np.sqrt(1-probability)]).astype(np.complex128),
np.array([[0, np.sqrt(probability)], [0, 0]], dtype=np.complex128)]
raise ValueError(f'Unknown channel: {channel}')
def build(cudaq, matrices, circuit):
channel = cudaq.KrausChannel(matrices)
noise_model = cudaq.NoiseModel()
for site in range(3):
noise_model.add_channel('x', [site], channel)
kernel = cudaq.make_kernel()
q = kernel.qalloc(3)
kernel.disable_quantum_optimization()
if circuit == 'ghz':
kernel.h(q[0])
kernel.cx(q[0], q[1])
kernel.cx(q[0], q[2])
# Exactly one un-controlled X per site, each followed by its attached noise.
# X on all three sites preserves the ideal GHZ+ state. Noise on distinct
# sites commutes with the other X gates, giving terminal local noise.
for site in range(3):
kernel.x(q[site])
# sample measures implicitly; observe needs the unmeasured preparation.
return kernel, noise_model
def reference_probabilities(channel, circuit, a, b, probability):
"""Independent classical assignment map for final basis populations."""
if channel == 'symmetric':
a = b = probability
elif channel == 'damping':
a, b = 0., probability
response = np.array([[1-a, b], [a, 1-b]])
sources = [(1, 1.)] if circuit == 'ones' else [(0, .5), (1, .5)]
return np.array([sum(weight * np.prod([response[int(bit), source]
for bit in format(i, '03b')]) for source, weight in sources)
for i in range(8)])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--target', choices=('density-matrix-cpu', 'nvidia', 'tensornet-mps'),
default='density-matrix-cpu')
parser.add_argument('--channel', choices=('asymmetric', 'symmetric', 'damping'),
default='asymmetric')
parser.add_argument('--circuit', choices=('ones', 'ghz'), default='ones')
parser.add_argument('--method', choices=('sample', 'observe'), default='sample')
parser.add_argument('--a', type=float, default=.12)
parser.add_argument('--b', type=float, default=.23)
parser.add_argument('--probability', type=float, default=.15)
parser.add_argument('--shots', type=int, default=4096)
parser.add_argument('--trajectories', type=int, default=4096)
parser.add_argument('--seed', type=int, default=272008200)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if not os.environ.get('SLURM_JOB_ID') or socket.gethostname().split('.')[0].startswith('login'):
parser.error('An allocated compute node is required, including for CPU execution')
if min(args.shots, args.trajectories) < 1 or not 0 <= args.seed < 2**32:
parser.error('Require positive shots/trajectories and a seed in [0, 2**32)')
matrices = kraus_matrices(args.channel, args.a, args.b, args.probability)
args.output.mkdir(parents=True, exist_ok=False)
result = {**vars(args), 'output': str(args.output), 'complete': False,
'phase': 'import', 'diagnostic_only': True,
'family_error_probability': .01, 'family_test_budget': 128,
'matrix_real': [k.real.tolist() for k in matrices],
'matrix_imag': [k.imag.tolist() for k in matrices]}
expected = reference_probabilities(args.channel, args.circuit, args.a,
args.b, args.probability)
expected_z0 = float(expected[:4].sum() - expected[4:].sum())
result.update(expected_q0_left=expected.tolist(), expected_z0=expected_z0)
def save():
temporary = args.output / 'result.tmp'
temporary.write_text(json.dumps(result, indent=2, allow_nan=False) + '\n')
temporary.replace(args.output / 'result.json')
save()
# Select a CPU default before import, even when later selecting a GPU target.
os.environ['CUDAQ_DEFAULT_SIMULATOR'] = 'density-matrix-cpu'
os.environ.update(CUDAQ_MPS_MAX_BOND='64', CUDAQ_MPS_ABS_CUTOFF='1e-8',
CUDAQ_MPS_RELATIVE_CUTOFF='1e-8', CUDAQ_MPS_SVD_ALGO='GESVD',
CUDAQ_MPS_GAUGE='FREE')
import cudaq
if args.target == 'density-matrix-cpu':
cudaq.set_target(args.target)
else:
cudaq.set_target(args.target, option='fp64')
result.update(phase='build', active_target=str(cudaq.get_target()),
cudaq_version=cudaq.__version__,
settings={k: v for k, v in os.environ.items() if k.startswith('CUDAQ_')},
loaded_libraries=sorted({line.split()[-1]
for line in Path('/proc/self/maps').read_text().splitlines()
if '/' in line and any(name in line for name in
('libnvqir', 'libcudaq', 'libcutensornet', 'libcutensor.', 'libcudart'))}))
save()
kernel, noise_model = build(cudaq, matrices, args.circuit)
(args.output / 'kernel.mlir').write_text(str(kernel))
cudaq.set_random_seed(args.seed)
result['phase'] = args.method
save()
try:
if args.method == 'sample':
from scipy.stats import binom
counts = cudaq.sample(kernel, noise_model=noise_model, shots_count=args.shots)
result.update(phase='sample_returned', counts=dict(counts.items()))
save()
actual = np.array([result['counts'].get(format(i, '03b'), 0) for i in range(8)])
lo = binom.ppf(.01/256, args.shots, expected)
hi = binom.ppf(1-.01/256, args.shots, expected)
result['reference_check'] = bool(actual.sum() == args.shots and
np.all((actual >= lo) & (actual <= hi)))
result['bounds'] = np.column_stack((lo, hi)).tolist()
else:
options = {} if args.target == 'density-matrix-cpu' else {
'num_trajectories': args.trajectories}
value = float(cudaq.observe(kernel, cudaq.spin.z(0), noise_model=noise_model,
shots_count=-1, **options).expectation())
result.update(phase='observe_returned', expectation_z0=value)
save()
# CPU density matrix contracts directly. GPU averages bounded [-1,1]
# trajectory values: two-sided Hoeffding bound, same family budget.
tolerance = (1e-10 if args.target == 'density-matrix-cpu' else
float(np.sqrt(2*np.log(256/.01)/args.trajectories)))
result.update(reference_tolerance=tolerance,
reference_check=bool(np.isfinite(value) and
abs(value-expected_z0) <= tolerance))
save()
if not result['reference_check']:
raise ValueError('Output failed the predeclared reference check')
result.update(phase='complete', complete=True)
save()
print(json.dumps(result, allow_nan=False), flush=True)
except Exception as error:
result.update(phase='failed', error=repr(error))
save()
raise
if __name__ == '__main__':
main()
Expected behavior
The trace-preserving channel should return valid noisy counts / an expectation consistent with Z0=0.11, as the CPU density-matrix target does, without aborting.
Observed controls and limits
| Channel | CPU sample | CPU observe Z0 | GPU sample | GPU observe |
|---|---|---|---|---|
| Asymmetric | Passed | 0.1100000000000001 | Zero-norm abort, exit 134 | Zero-norm abort, exit 134 |
| Symmetric bit flip | Passed | 0 | Passed | Passed, Z0=-2.3565e-16 |
| Amplitude damping | Passed | 0.2500000000000001 | Killed, exit 137; inconclusive | Killed, exit 137; inconclusive |
Sample passes mean all eight counts passed the predeclared binomial bounds implemented above. CPU expectation tolerance is 1e-10; GPU expectation tolerance is approximately 0.07040046 under the stated trajectory assumptions.
Separate resource failure: the batch requested 7 GiB host memory, with a 75-second timeout plus 10-second kill grace per process. After the asymmetric aborts and symmetric passes, both damping cases were killed. Slurm ended the batch OUT_OF_MEMORY and reported Detected 2 oom_kill events. Neither damping case returned a numerical result. This does not establish a damping-channel numerical failure. Detailed cuTensorNet logging may affect resource use; no attribution of the memory growth is established.
Environment
- CUDA-Q:
cuda-quantum-cu12==0.16.0; runtime source identity9ceceba030d737655f8a4fb15fadbc3bdee6f30d. - Python 3.11; NumPy 2.4.6; SciPy 1.17.1; Linux cluster (exact distribution not captured in this run).
- GPU: Tesla T4; NVIDIA driver 575.57.08.
- CUDA runtime package 12.9.79; CUDA toolkit module 12.9.1.
- cuTensorNet 2.13.0; cuTensor 2.8.1; cuStateVec 1.14.0.
tensornet-mps,option="fp64".CUDAQ_MPS_MAX_BOND=64, absolute/relative cutoffs1e-8,CUDAQ_MPS_SVD_ALGO=GESVD,CUDAQ_MPS_GAUGE=FREE; quantum optimization disabled.- CPU controls completed on a CPU-only compute node. The CPU default is selected before import, then the requested target is set explicitly.
Is this a regression?
Unknown; no previously working version has been established for this exact reproducer.
Additional diagnosis / related reports
In a separate earlier asymmetric-channel diagnostic, a debugger captured three channel calls and nine uploaded matrices at the CUDA-Q/cuTensorNet boundary. Each matrix contained four complex-double entries (64 bytes). Host/device values matched exactly as printed, and expected entries within 1e-15. Calls used null strides and nine distinct device pointers, followed by the same StateCompute zero-norm error. This was a different circuit, not a buffer capture of the GHZ run above; it does not rule out later mutation or internal state handling.
I checked #5178, which concerns Python callback exceptions; this reproducer has no callback subclass. I also checked #5584, which addresses fp32 general-channel buffers; this run explicitly uses fp64, and I have not tested that PR's patch. I do not know whether the underlying cause is related.
Can you reproduce this, or identify a documented restriction or defect in general Kraus-channel evolution that explains it? Which internal state or Kraus-branch diagnostic would be most useful next? Full per-case logs, environment reports and the separate buffer capture are retained and can be supplied. No Compute Sanitizer or patched-library result is available yet.
- Dominant language
- C++
- Stars
- 1.2k
- Forks
- 508
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 100
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from NVIDIA/cuda-quantum
-
Difficulty 1/5 Under an hour Newbie friendliness 88/100
NVIDIA/cuda-quantum#6035 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 1-3 hours Newbie friendliness 77/100
NVIDIA/cuda-quantum#6034 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
NVIDIA/cuda-quantum#6033 ·
Maintainers usually reply within 1 day
-
Point the CUDA-Q Pulse research preview docs to the released cudaq-pulse packagePossibly taken @fedonman claimed this 2 days ago. Open
Difficulty 1/5 1-3 hours Newbie friendliness 88/100
NVIDIA/cuda-quantum#6031 ·
Maintainers usually reply within 1 day
-
Realtime fnv1a_hash sign-extends char, so a non-ASCII handler name gets a platform-dependent function idPossibly taken @fedonman claimed this 2 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
NVIDIA/cuda-quantum#6029 ·
Maintainers usually reply within 1 day
All issues in NVIDIA/cuda-quantum
Similar issues
-
Difficulty 1/5 Under an hour Newbie friendliness 90/100
Maintainers usually reply within 2 days
-
bug data-types
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
ClickHouse/clickhouse-cpp#645 ·
Maintainers usually reply within 1 day
-
bug compatibility difficulty:easy prio:normal
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
NatronGitHub/openfx-misc#524 ·
Maintainers usually reply within 1 day
-
documentation enhancement help wanted P0
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Awesome-Embedded-Learning-Studio/Tutorial_AwesomeModernCPP#359 ·
Maintainers usually reply within 1 day
-
Type: Bug
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
openscad/openscad#7360 · 2 comments ·
Maintainers usually reply within 1 day