> ## Documentation Index
> Fetch the complete documentation index at: https://bloqade.quera.com/tsim/llms.txt
> Use this file to discover all available pages before exploring further.

# tsim

> A GPU-accelerated quantum circuit sampler based on ZX-calculus stabilizer rank decomposition.

A GPU-accelerated quantum circuit sampler based on ZX-calculus stabilizer rank decomposition.
tsim feels just like [Stim](https://github.com/quantumlib/Stim), but supports non-Clifford gates.

A detailed description of tsim is given in [arXiv:2604.01059](https://arxiv.org/abs/2604.01059).

## Quick start

An introductory tutorial is available [here](/tsim/tsim/tutorials/encoding_demo). For many existing scripts, replacing `stim` with `tsim` should just work. tsim mirrors the Stim API and supports all [Stim instructions](https://github.com/quantumlib/Stim/wiki/Stim-v1.13-Gate-Reference).

Additionally, tsim supports the instructions `T`, `T_DAG`, `R_Z`, `R_X`, `R_Y`, `U3`, `TPP`, `TPP_DAG`, `R_XX`, `R_YY`, `R_ZZ`, `R_PAULI`, `CCZ`, and `CCX`.

```python theme={null}
import tsim

c = tsim.Circuit(
    """
    RX 0
    R 1
    T 0
    PAULI_CHANNEL_1(0.1, 0.1, 0.2) 0 1
    H 0
    CNOT 0 1
    DEPOLARIZE2(0.01) 0 1
    M 0 1
    DETECTOR rec[-1] rec[-2]
    """
)

detector_sampler = c.compile_detector_sampler()
samples = detector_sampler.sample(shots=100)
```

## Installation

```bash theme={null}
uv add bloqade-tsim
```

For GPU acceleration, use

```bash theme={null}
uv add "bloqade-tsim[cuda13]"
```

See [Installation](/tsim/tsim/install) for more options.

## Architecture

<img src="https://mintcdn.com/tsim/ix3kddKGdX7JucGG/tsim/architecture.svg?fit=max&auto=format&n=ix3kddKGdX7JucGG&q=85&s=ef1c2addcc26ed40f1986661e474f110" alt="tsim architecture diagram" width="577" height="225" data-path="tsim/architecture.svg" />

Quantum programs are translated into ZX diagrams in which Pauli noise channels appear as parameterized vertices with binary variables $e_i$.
ZX simplification factors the diagram into a classical part that represents the Tanner graph and a quantum part containing the observable circuit. Both parts define a new basis of *error mechanisms* $f_i = \bigoplus_j T_{ij}\,e_j$.
The observable diagram is used to compute marginal probabilities for autoregressive sampling. Here, each diagram is decomposed into a sum of Clifford terms via stabilizer rank decomposition, following [Sutcliffe and Kissinger (2024)](https://arxiv.org/abs/2403.06777), and compiled into binary JAX tensors $g_{tki}$.
At sampling time, JIT-compiled XLA kernels contract $g_{tki}$ with batched noise configurations $f_i^{s}$ to evaluate marginal probabilities and autoregressively sample detector and observable bits.

## Differences from Stim

tsim supports non-deterministic detectors and observables. An important consequence is that
tsim will simulate actual detector samples, whereas Stim only reports detection flips (i.e. detection samples XORed with
a noiseless reference sample). Concretely,

```python theme={null}
c = tsim.Circuit(
    """
    X 0
    M 0
    DETECTOR rec[-1]
    """
)
sampler = c.compile_detector_sampler()
samples = sampler.sample(shots=100)
print(samples)
```

will report `True` values, whereas the same circuit would result in `False` values in Stim. To reproduce the behavior of Stim, you can use the following:

```python theme={null}
samples = sampler.sample(
    shots=100,
    use_detector_reference_sample=True,
    use_observable_reference_sample=True,
)
```

When set to `True`, a noiseless reference sample is computed and XORed with the
results, so that output values represent deviations from the noiseless baseline.
Note that this feature should be used carefully. If detectors or observables are not deterministic, this may lead to incorrect statistics.

## Postselected simulations

For postselected QEC experiments, pass a boolean mask to
`CompiledDetectorSampler.sample`. The mask has length `num_detectors`; a shot is
*discarded* when any masked detector fires.

```python theme={null}
import numpy as np

c = tsim.Circuit(
    """
    X_ERROR(0.01) 0 1
    M 0 1
    DETECTOR rec[-2]
    DETECTOR rec[-1] rec[-2]
    OBSERVABLE_INCLUDE(0) rec[-1]
    """
)
sampler = c.compile_detector_sampler()
mask = np.array([True, False])  # postselect on detector 0

samples = sampler.sample(
    shots=10_000,
    postselection_mask=mask,
    append_observables=True,
)
keep = ~np.any(samples[:, : c.num_detectors] & mask, axis=1)
survivors = samples[keep]
```

`sample` always returns exactly `shots` rows. Shots discarded by a **direct**
postselected detector skip the expensive JAX autoregressive loop; their direct
detector columns are still correct, and all other columns are filled with
`False`. Re-apply the mask to the detector columns (as above) to recover the
surviving shots. Detectors that live inside a JAX component cannot be evaluated
without running JAX, so those shots are always computed in full.

This is independent of `prepend_observables`, `append_observables`,
`separate_observables`, and `bit_packed`. When combined with
`use_detector_reference_sample`, the reference XOR is applied before the
postselection discard check. On surviving rows it is applied to every detector
column; on direct-discarded partial rows it is applied only to direct detector
columns (component columns stay `False`). When combined with
`use_observable_reference_sample`, the reference XOR is applied to every row
that ran JAX; direct-discarded partial rows are left unchanged.

## Benchmarks

With GPU acceleration, tsim can achieve sampling throughput for low-magic circuits that approaches the throughput of Stim on Clifford circuits of the same size. The figure below shows a comparison for [distillation circuits](https://arxiv.org/html/2412.15165v1) (35 and 85 qubits), [cultivation circuits](https://arxiv.org/abs/2409.17595), and rotated surface code circuits.
tsim can be five orders of magnitude faster than [quizx](https://github.com/zxcalc/quizx).

<img src="https://mintcdn.com/tsim/ix3kddKGdX7JucGG/tsim/benchmarks.svg?fit=max&auto=format&n=ix3kddKGdX7JucGG&q=85&s=c6b7bc26f87e7df04fa1d1f4ee343c6d" alt="Sampling throughput benchmark comparing tsim against Stim and quizx" width="586" height="288" data-path="tsim/benchmarks.svg" />

## Citing tsim

If you use tsim, please consider citing the paper describing the core simulation approach:

```
@article{tsim2026,
  title={Tsim: Fast Universal Simulator for Quantum Error Correction},
  author={Haenel, Rafael and Luo, Xiuzhe and Zhao, Chen},
  journal={arXiv preprint arXiv:2604.01059},
  year={2026}
}
```
