Skip to content

Commit f198248

Browse files
Merge branch 'master' into beta
2 parents bcb7571 + 43a8bba commit f198248

File tree

20 files changed

+348
-39
lines changed

20 files changed

+348
-39
lines changed

CHANGELOG.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@
22

33
## Unreleased
44

5+
### Added
6+
7+
- Add jax jitted function load/save utilities in experimental module
8+
9+
- Add `circuit.to_openqasm_file` function for compatibility of qiskit>1
10+
11+
## 1.0.2
12+
13+
### Added
14+
15+
- Add `jittable` option in `c.sample()` method, friendly to switch off for large scale sample
16+
17+
### Changed
18+
19+
- Downgrading some logger warning to info
20+
21+
### Fixed
22+
23+
- Fix quafu provider
24+
25+
- Raise ValueError for `FGSSimulator` when traced out sites correspond the full system
26+
527
## 1.0.1
628

729
### Fixed

README.md

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,23 @@
2525

2626
<p align="center"> English | <a href="README_cn.md"> 简体中文 </a></p>
2727

28-
TensorCircuit-NG is a high performance quantum software framework, supporting for automatic differentiation, just-in-time compiling, hardware acceleration, and vectorized parallelism, providing unified infrastructures and interfaces for quantum programming.
28+
TensorCircuit-NG is an open-source high-performance quantum software framework, supporting for automatic differentiation, just-in-time compiling, hardware acceleration, and vectorized parallelism, providing unified infrastructures and interfaces for quantum programming. It can compose quantum circuits, neural networks and tensor networks seamlessly with high simulation efficiency and flexibility.
2929

30-
TensorCircuit-NG is built on top of modern machine learning frameworks: Jax, TensorFlow, and PyTorch. It is specifically suitable for highly efficient simulations of quantum-classical hybrid paradigm and variational quantum algorithms in ideal, noisy and approximate cases. It also supports quantum hardware access and provides CPU/GPU/QPU hybrid deployment solutions.
30+
TensorCircuit-NG is built on top of modern machine learning frameworks: Jax, TensorFlow, and PyTorch. It is specifically suitable for large-scale simulations of quantum-classical hybrid paradigm and variational quantum algorithms in ideal, noisy, approximate and analog cases. It also supports quantum hardware access and provides CPU/GPU/QPU hybrid deployment solutions.
3131

32-
TensorCircuit-NG is [fully compatible](https://tensorcircuit-ng.readthedocs.io/en/latest/faq.html#what-is-the-relation-between-tensorcircuit-and-tensorcircuit-ng) with TensorCircuit with more new features and bug fixes (support numpy>2 and qiskit>1).
32+
TensorCircuit-NG is [fully compatible](https://tensorcircuit-ng.readthedocs.io/en/latest/faq.html#what-is-the-relation-between-tensorcircuit-and-tensorcircuit-ng) with TensorCircuit with more new features and bug fixes (support latest `numpy>2` and `qiskit>1`).
3333

3434
## Getting Started
3535

3636
Please begin with [Quick Start](/docs/source/quickstart.rst) in the [full documentation](https://tensorcircuit-ng.readthedocs.io/).
3737

3838
For more information on software usage, sota algorithm implementation and engineer paradigm demonstration, please refer to 70+ [example scripts](/examples) and 30+ [tutorial notebooks](https://tensorcircuit-ng.readthedocs.io/en/latest/#tutorials). API docstrings and test cases in [tests](/tests) are also informative.
3939

40+
For beginners, please refer to [quantum computing lectures with TC-NG](https://github.com/sxzgroup/qc_lecture) to learn both quantum computing basis and representative usage of TensorCircuit-NG.
41+
4042
The following are some minimal demos.
4143

42-
- Circuit manipulation:
44+
- Circuit construction:
4345

4446
```python
4547
import tensorcircuit as tc
@@ -60,7 +62,7 @@ tc.set_dtype("complex128")
6062
tc.set_contractor("greedy")
6163
```
6264

63-
- Automatic differentiations with jit:
65+
- Automatic differentiation with jit:
6466

6567
```python
6668
def forward(theta):
@@ -348,7 +350,7 @@ Reference paper: https://arxiv.org/abs/2303.08154 (published in PRR as a Letter)
348350

349351
### TenCirChem
350352

351-
[TenCirChem](https://github.com/tencent-quantum-lab/TenCirChem) is an efficient and versatile quantum computation package for molecular properties. TenCirChem is based on TensorCircuit and is optimized for chemistry applications.
353+
[TenCirChem](https://github.com/tencent-quantum-lab/TenCirChem) is an efficient and versatile quantum computation package for molecular properties. TenCirChem is based on TensorCircuit and is optimized for chemistry applications. The latest version TenCirChem-NG is open source and available at [TenCirChem-NG](https://github.com/tensorcircuit/TenCirChem-NG).
352354

353355
Reference paper: https://arxiv.org/abs/2303.10825 (published in JCTC).
354356

@@ -364,6 +366,12 @@ For the setup and simulation code of neural network encoded variational quantum
364366

365367
Reference paper: https://arxiv.org/abs/2308.01068 (published in PRApplied).
366368

369+
### Effective temperature in approximate ansatzes
370+
371+
For the simulation implementation of quantum states based on neural networks, tensor networs and quantum circuits using TensorCircuit-NG, see the [project repo](https://github.com/sxzgroup/et).
372+
373+
Reference paper: https://arxiv.org/abs/2411.18921.
374+
367375
### More works
368376

369377
<details>
@@ -426,3 +434,11 @@ Reference paper: https://arxiv.org/abs/2308.01068 (published in PRApplied).
426434
</details>
427435

428436
If you want to highlight your research work or projects here, feel free to add by opening PR.
437+
438+
## Users
439+
440+
Our users, developers, and partners:
441+
442+
<p align="center">
443+
<img width=90% src="docs/source/statics/user_logo.png">
444+
</p>

README_cn.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ TensorCircuit-NG 现在支持真实量子硬件连接和实验,并提供优雅
3333

3434
有关软件用法,算法实现和工程范式演示的更多信息和介绍,请参阅 70+ [示例脚本](/examples) 和 30+ [案例教程](https://tensorcircuit-ng.readthedocs.io/en/latest/#tutorials)[测试](/tests) 用例和 API docstring 也提供了丰富的使用信息。
3535

36+
初学者也可以参考[量子计算教程](https://github.com/sxzgroup/qc_lecture)学习量子计算基础和 TensorCircuit-NG 的典型用法.
37+
3638
以下是一些最简易的演示。
3739

3840
- 电路操作:
@@ -186,3 +188,17 @@ VQEX 在 MBL 相位识别上的应用见 [教程](/docs/source/tutorials/vqex_mb
186188
关于神经网络编码的变分量子算法的实现和工作流, 见 [教程](/docs/source/tutorials/nnvqe.ipynb)
187189

188190
参考论文: https://arxiv.org/abs/2308.01068。
191+
192+
### 变分多体态的等效温度
193+
194+
关于基于神经网络、张量网络和量子线路的变分量子态的模拟优化和分析,见 [项目](https://github.com/sxzgroup/et).
195+
196+
参考论文: https://arxiv.org/abs/2411.18921.
197+
198+
## 用户
199+
200+
我们的用户,开发者和合作伙伴:
201+
202+
<p align="center">
203+
<img width=90% src="docs/source/statics/user_logo.png">
204+
</p>

docs/source/advance.rst

Lines changed: 130 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,65 @@ Advanced Usage
55
MPS Simulator
66
----------------
77

8-
(Still experimental support)
9-
10-
Very simple, we provide the same set of API for ``MPSCircuit`` as ``Circuit``,
8+
Very straightforward to use, we provide the same set of API for ``MPSCircuit`` as ``Circuit``,
119
the only new line is to set the bond dimension for the new simulator.
1210

1311
.. code-block:: python
1412
1513
c = tc.MPSCircuit(n)
1614
c.set_split_rules({"max_singular_values": 50})
1715
18-
The larger bond dimension we set, the better approximation ratio (of course the more computational cost we pay)
16+
The larger bond dimension we set, the better approximation ratio (of course the more computational cost we pay).
17+
18+
19+
Stacked gates
20+
----------------
21+
22+
Stacked gates is a simple grammar sugar to make constructing the circuit easily when multiple gate of the same type are applied on the different qubits, namely, the index for gate function can accept list of ints instead of one integer.
23+
24+
.. code-block:: python
25+
26+
>>> import tensorcircuit as tc
27+
>>> c = tc.Circuit(4)
28+
>>> c.h(range(3))
29+
>>> c.draw()
30+
┌───┐
31+
q_0: ┤ H ├
32+
├───┤
33+
q_1: ┤ H ├
34+
├───┤
35+
q_2: ┤ H ├
36+
└───┘
37+
q_3: ─────
38+
39+
40+
>>> c = tc.Circuit(4)
41+
>>> c.cnot([0, 1], [2, 3])
42+
>>> c.draw()
43+
44+
q_0: ──■───────
45+
46+
q_1: ──┼────■──
47+
┌─┴─┐ │
48+
q_2: ┤ X ├──┼──
49+
└───┘┌─┴─┐
50+
q_3: ─────┤ X ├
51+
└───┘
52+
53+
>>> c = tc.Circuit(4)
54+
>>> c.rx(range(4), theta=tc.backend.convert_to_tensor([0.1, 0.2, 0.3, 0.4]))
55+
>>> c.draw()
56+
┌─────────┐
57+
q_0: ┤ Rx(0.1) ├
58+
├─────────┤
59+
q_1: ┤ Rx(0.2) ├
60+
├─────────┤
61+
q_2: ┤ Rx(0.3) ├
62+
├─────────┤
63+
q_3: ┤ Rx(0.4) ├
64+
└─────────┘
65+
66+
1967
2068
Split Two-qubit Gates
2169
-------------------------
@@ -45,15 +93,92 @@ The two-qubit gates applied on the circuit can be decomposed via SVD, which may
4593
4694
Note ``max_singular_values`` must be specified to make the whole procedure static and thus jittable.
4795

96+
Analog circuit simulation
97+
-----------------------------
98+
99+
TensorCircuit-NG support digital-analog hybrid simulation (say cases in Rydberg atom arrays), where the analog part is simulated by the neural differential equation solver given the API to specify a time dependent Hamiltonian.
100+
The simulation is still differentiable and jittable. Only jax backend is supported for analog simulation as the neural ode engine is built on top of jax.
101+
This utility is super helpful for optimizing quantum control or investigating digital-analog hybrid variational quantum schemes.
102+
We support two modes of analog simulation, where :py:meth:`tensorcircuit.experimentaql.evol_global` evolve the state via a Hamiltonian define on the whole system, and :py:meth:`tensorcircuit.experimentaql.evol_local` evolve the state via a Hamiltonian define on a local subsystem.
103+
104+
.. Note::
105+
106+
``evol_global`` use sparse Hamiltonian while ``evol_local`` use dense Hamiltonian.
107+
108+
109+
.. code-block:: python
110+
111+
# in this demo, we build a jittable and differentiable simulation function `hybrid_evol`
112+
# with both digital gates and local/global analog Hamiltonian evolutions
113+
114+
import optax
115+
import tensorcircuit as tc
116+
from tensorcircuit.experimental import evol_global, evol_local
117+
118+
K = tc.set_backend("jax")
119+
120+
121+
def h_fun(t, b):
122+
return b * tc.gates.x().tensor
123+
124+
125+
hy = tc.quantum.PauliStringSum2COO([[2, 0]])
126+
127+
128+
def h_fun2(t, b):
129+
return b[2] * K.cos(b[0] * t + b[1]) * hy
130+
131+
132+
@K.jit
133+
@K.value_and_grad
134+
def hybrid_evol(params):
135+
c = tc.Circuit(2)
136+
c.x([0, 1])
137+
c = evol_local(c, [1], h_fun, 1.0, params[0])
138+
c.cx(1, 0)
139+
c.h(0)
140+
c = evol_global(c, h_fun2, 1.0, params[1:])
141+
return K.real(c.expectation_ps(z=[0, 1]))
142+
143+
144+
b = K.implicit_randn([4])
145+
v, gs = hybrid_evol(b)
146+
147+
48148
49149
Jitted Function Save/Load
50150
-----------------------------
51151

52152
To reuse the jitted function, we can save it on the disk via support from the TensorFlow `SavedModel <https://www.tensorflow.org/guide/saved_model>`_. That is to say, only jitted quantum function on the TensorFlow backend can be saved on the disk.
53153

154+
We wrap the tf-backend `SavedModel` as very easy-to-use function :py:meth:`tensorcircuit.keras.save_func` and :py:meth:`tensorcircuit.keras.load_func`.
155+
54156
For the JAX-backend quantum function, one can first transform them into the tf-backend function via JAX experimental support: `jax2tf <https://github.com/google/jax/tree/main/jax/experimental/jax2tf>`_.
55157

56-
We wrap the tf-backend `SavedModel` as very easy-to-use function :py:meth:`tensorcircuit.keras.save_func` and :py:meth:`tensorcircuit.keras.load_func`.
158+
**Updates**: jax now also support jitted function save/load via ``export`` module, see `jax documentation <https://jax.readthedocs.io/en/latest/export/export.html>_`.
159+
160+
We wrape the jax function export capability in ``experimental`` module and can be used as follows
161+
162+
.. code-block:: python
163+
164+
from tensorcircuit import experimental
165+
166+
K = tc.set_backend("jax")
167+
168+
@K.jit
169+
def f(weights):
170+
c = tc.Circuit(3)
171+
c.rx(range(3), theta=weights)
172+
return K.real(c.expectation_ps(z=[0]))
173+
174+
print(f(K.ones([3])))
175+
176+
experimental.jax_jitted_function_save("temp.bin", f, K.ones([3]))
177+
178+
f_load = tc.experimental.jax_jitted_function_load("temp.bin")
179+
f_load(K.ones([3]))
180+
181+
57182
58183
Parameterized Measurements
59184
-----------------------------

docs/source/quickstart.rst

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,8 @@ For more details on docker setup, please refer to `docker readme <https://github
2929

3030
- For Windows, due to the lack of support for Jax, we recommend to use docker or WSL, please refer to `TC via windows docker <contribs/development_windows.html>`_ or `TC via WSL <contribs/development_wsl2.html>`_.
3131

32-
- For MacOS, please refer to `TC on Mac <contribs/development_Mac.html>`_.
33-
34-
Overall, the installation of TensorCircuit is simple, since it is purely in Python and hence very portable.
35-
As long as the users can take care of the installation of ML frameworks on the corresponding system, TensorCircuit will work as expected.
32+
Overall, the installation of TensorCircuit-NG is simple, since it is purely in Python and hence very portable.
33+
As long as the users can take care of the installation of ML frameworks on the corresponding system, TensorCircuit-NG will work as expected.
3634

3735
To debug the installation issue or report bugs, please check the environment information by ``tc.about()``.
3836

docs/source/statics/user_logo.png

2 MB
Loading

tensorcircuit/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__version__ = "1.0.1"
1+
__version__ = "1.0.2"
22
__author__ = "TensorCircuit Authors"
33
__creator__ = "refraction-ray"
44

tensorcircuit/abstractcircuit.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,16 @@ def to_openqasm(self, **kws: Any) -> str:
792792
qasm_str = dumps(qc) # type: ignore
793793
return qasm_str # type: ignore
794794

795+
def to_openqasm_file(self, file: str, **kws: Any) -> None:
796+
"""
797+
save the circuit to openqasm file
798+
799+
:param file: the file path to save the circuit
800+
:type file: str
801+
"""
802+
with open(file, "w") as f:
803+
f.write(self.to_openqasm(**kws))
804+
795805
@classmethod
796806
def from_openqasm(
797807
cls,

tensorcircuit/backends/numpy_backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ def jit(
392392
jit_compile: Optional[bool] = None,
393393
**kws: Any
394394
) -> Callable[..., Any]:
395-
logger.warning("numpy backend has no jit interface, just do nothing")
395+
logger.info("numpy backend has no jit interface, just do nothing")
396396
return f
397397
# raise NotImplementedError("numpy backend doesn't support jit compiling")
398398

tensorcircuit/basecircuit.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,7 @@ def sample(
528528
format: Optional[str] = None,
529529
random_generator: Optional[Any] = None,
530530
status: Optional[Tensor] = None,
531+
jittable: bool = True,
531532
) -> Any:
532533
"""
533534
batched sampling from state or circuit tensor network directly
@@ -541,12 +542,29 @@ def sample(
541542
:type readout_error: Optional[Sequence[Any]]. Tensor, List, Tuple
542543
:param format: sample format, defaults to None as backward compatibility
543544
check the doc in :py:meth:`tensorcircuit.quantum.measurement_results`
545+
Six formats of measurement counts results:
546+
547+
"sample_int": # np.array([0, 0])
548+
549+
"sample_bin": # [np.array([1, 0]), np.array([1, 0])]
550+
551+
"count_vector": # np.array([2, 0, 0, 0])
552+
553+
"count_tuple": # (np.array([0]), np.array([2]))
554+
555+
"count_dict_bin": # {"00": 2, "01": 0, "10": 0, "11": 0}
556+
557+
"count_dict_int": # {0: 2, 1: 0, 2: 0, 3: 0}
558+
544559
:type format: Optional[str]
545560
:param random_generator: random generator, defaults to None
546561
:type random_generator: Optional[Any], optional
547562
:param status: external randomness given by tensor uniformly from [0, 1],
548563
if set, can overwrite random_generator
549564
:type status: Optional[Tensor]
565+
:param jittable: when converting to count, whether keep the full size. if false, may be conflict
566+
external jit, if true, may fail for large scale system with actual limited count results
567+
:type jittable: bool, defaults true
550568
:return: List (if batch) of tuple (binary configuration tensor and corresponding probability)
551569
if the format is None, and consistent with format when given
552570
:rtype: Any
@@ -612,7 +630,9 @@ def perfect_sampling(key: Any) -> Any:
612630
if batch is None:
613631
r = r[0] # type: ignore
614632
return r
615-
return sample2all(sample=ch, n=self._nqubits, format=format, jittable=True)
633+
if self._nqubits > 35:
634+
jittable = False
635+
return sample2all(sample=ch, n=self._nqubits, format=format, jittable=jittable)
616636

617637
def sample_expectation_ps(
618638
self,

0 commit comments

Comments
 (0)