tensorcircuit.cons¶
Constants and setups
- exception tensorcircuit.cons.NodesReturn(value_to_return: Any)[source]¶
Bases:
ExceptionIntentionally stop execution to return a value.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class tensorcircuit.cons.OMEOptimizer(optimizer: Any | None = None)[source]¶
Bases:
objectAdapt an
omecooptimizer fortc.set_contractor("custom", ...).omecostays an optional dependency and is imported lazily only when this adapter is actually used.Example:
>>> import omeco >>> opt = omeco.TreeSA(ntrials=4, niters=8, betas=[0.1, 1.0, 10.0]) >>> tc.set_contractor("custom", optimizer=opt, preprocessing=True)
- tensorcircuit.cons.contraction_info_decorator(algorithm: Callable[[...], Any]) Callable[[...], Any][source]¶
Decorator to add contraction information logging to an optimizer.
This decorator wraps an optimization algorithm and prints detailed information about the contraction cost (FLOPs, size, write) and path finding time.
- Parameters:
algorithm (Callable[..., Any]) – The optimization algorithm to decorate.
- Returns:
The decorated optimization algorithm.
- Return type:
Callable[…, Any]
- tensorcircuit.cons.contractor(nodes: ~typing.List[~typing.Any], *, optimizer: ~typing.Any = <function greedy>, memory_limit: int | None = None, output_edge_order: ~typing.List[~typing.Any] | None = None, ignore_edge_order: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: ~typing.Any) Any¶
- tensorcircuit.cons.custom(nodes: List[Any], optimizer: Any, memory_limit: int | None = None, output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: Any) Any[source]¶
- tensorcircuit.cons.custom_stateful(nodes: List[Any], optimizer: Any, memory_limit: int | None = None, opt_conf: Dict[str, Any] | None = None, output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, use_primitives: bool | None = None, **kws: Any) Any[source]¶
- tensorcircuit.cons.experimental_contractor(nodes: List[Any], output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False, local_steps: int = 2) Any[source]¶
- tensorcircuit.cons.function_nodes_capture(func: Callable[[Any], Any]) Callable[[Any], Any][source]¶
- tensorcircuit.cons.get_contractor(method: str | None = None, optimizer: Any | None = None, memory_limit: int | None = None, opt_conf: Dict[str, Any] | None = None, *, set_global: bool = False, contraction_info: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: Any) Callable[[...], Any]¶
To set runtime contractor of the tensornetwork for a better contraction path. For more information on the usage of contractor, please refer to independent tutorial.
For large tensor networks, the default
greedycontractor may yield expensive or even intractable contraction orders. In that case it is strongly recommended to switch to a dedicated contraction pathfinder such ascotengra(method="cotengra") oromeco(method="omeco").omecois preferred when available, as it is generally faster at finding high-quality paths.- Parameters:
method (Optional[str], optional) – “auto”, “greedy”, “branch”, “plain”, “custom”, “custom_stateful”. Also supports shortcuts like “cotengra”, “cotengra-30-64”, “omeco”, and “omeco-16-32”. defaults to None (“auto”)
optimizer (Optional[Any], optional) – Valid for “custom” or “custom_stateful” as method, defaults to None
memory_limit (Optional[int], optional) – It is not very useful, as
memory_limitleads tobranchcontraction instead ofgreedywhich is rather slow, defaults to None
- Raises:
Exception – Tensornetwork version is too low to support some of the contractors.
ValueError – Unknown method options.
- Returns:
The new tensornetwork with its contractor set.
- Return type:
tn.Node
- tensorcircuit.cons.get_dtype(dtype: str | None = None, *, set_global: bool = False) Tuple[str, str]¶
Set the global runtime numerical dtype of tensors.
- Parameters:
dtype (Optional[str], optional) – “complex64”/”float32” or “complex128”/”float64”, defaults to None, which is equivalent to “complex64”.
- Returns:
complex dtype str and the corresponding real dtype str
- Return type:
Tuple[str, str]
- tensorcircuit.cons.get_symbol(i: int) str[source]¶
Get the symbol corresponding to int
i- runs through the usual 52 letters before resorting to unicode characters, starting atchr(192)and skipping surrogates. From cotengra codebase
- tensorcircuit.cons.get_tn_info(nodes: ~typing.List[~tensornetwork.network_components.Node], *, algorithm: ~typing.Any = <function _identity>) Tuple[List[Tuple[int, int]], List[Node]]¶
import cotengra as ctg import opt_einsum as oem
sys.setrecursionlimit(10000) # for successfullt ctg parallel
- opt = ctg.ReusableHyperOptimizer(
methods=[“greedy”, “kahypar”], parallel=True, minimize=”write”, max_time=30, max_repeats=4096, progbar=True,
) tc.set_contractor(“custom”, optimizer=opt, preprocessing=True) tc.set_contractor(“custom_stateful”, optimizer=oem.RandomGreedy, max_time=60, max_repeats=128, minimize=”size”) tc.set_contractor(“plain-experimental”, local_steps=3)
# hyper efficient contractor: though long computation time required, suitable for extra large circuit simulation opt = ctg.ReusableHyperOptimizer(
minimize=’combo’, max_repeats=1024, max_time=’equil:128’, optlib=’nevergrad’, progbar=True,
)
- def opt_reconf(inputs, output, size, **kws):
tree = opt.search(inputs, output, size) tree_r = tree.subtree_reconfigure_forest(progbar=True, num_trees=10,
num_restarts=20, subtree_weight_what=(“size”, ))
return tree_r.get_path()
tc.set_contractor(“custom”, optimizer=opt_reconf)
- tensorcircuit.cons.plain_contractor(nodes: List[Any], output_edge_order: List[Any] | None = None, ignore_edge_order: bool = False) Any[source]¶
The naive state-vector simulator contraction path.
- Parameters:
nodes (List[Any]) – The list of
tn.Node.output_edge_order (Optional[List[Any]], optional) – The list of dangling node edges, defaults to be None.
- Returns:
The
tn.Nodeafter contraction- Return type:
tn.Node
- tensorcircuit.cons.runtime_backend(backend: str | None = None) Iterator[Any][source]¶
Context manager to set with-level runtime backend
- Parameters:
backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”, defaults to None
- Yield:
the backend object
- Return type:
Iterator[Any]
- tensorcircuit.cons.runtime_contractor(*confargs: Any, **confkws: Any) Iterator[Any][source]¶
Context manager to set a with-level contractor.
- Parameters:
confargs (Any) – Positional arguments forwarded to
set_contractor.confkws (Any) – Keyword arguments forwarded to
set_contractor.
- Yield:
The new contractor callable.
- Return type:
Iterator[Any]
- tensorcircuit.cons.runtime_dtype(dtype: str | None = None) Iterator[Tuple[str, str]][source]¶
Context manager to set with-level runtime dtype
- Parameters:
dtype (Optional[str], optional) – “complex64” or “complex128”, defaults to None (“complex64”)
- Yield:
complex dtype str and real dtype str
- Return type:
Iterator[Tuple[str, str]]
- tensorcircuit.cons.set_backend(backend: str | None = None, set_global: bool = True) Any¶
To set the runtime backend of tensorcircuit.
Note:
tc.set_backendandtc.cons.set_tensornetwork_backendare the same.- Example:
>>> tc.set_backend("numpy") numpy_backend >>> tc.gates.num_to_tensor(0.1) array(0.1+0.j, dtype=complex64) >>> >>> tc.set_backend("tensorflow") tensorflow_backend >>> tc.gates.num_to_tensor(0.1) <tf.Tensor: shape=(), dtype=complex64, numpy=(0.1+0j)> >>> >>> tc.set_backend("pytorch") pytorch_backend >>> tc.gates.num_to_tensor(0.1) tensor(0.1000+0.j) >>> >>> tc.set_backend("jax") jax_backend >>> tc.gates.num_to_tensor(0.1) DeviceArray(0.1+0.j, dtype=complex64)
- Parameters:
backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”. defaults to None, which gives the same behavior as
tensornetwork.backend_contextmanager.get_default_backend().set_global (bool) – Whether the object should be set as global.
- Returns:
The tc.backend object that with all registered universal functions.
- Return type:
backend object
- tensorcircuit.cons.set_contractor(method: str | None = None, optimizer: Any | None = None, memory_limit: int | None = None, opt_conf: Dict[str, Any] | None = None, set_global: bool = True, contraction_info: bool = False, debug_level: int = 0, use_primitives: bool | None = None, **kws: Any) Callable[[...], Any][source]¶
To set runtime contractor of the tensornetwork for a better contraction path. For more information on the usage of contractor, please refer to independent tutorial.
For large tensor networks, the default
greedycontractor may yield expensive or even intractable contraction orders. In that case it is strongly recommended to switch to a dedicated contraction pathfinder such ascotengra(method="cotengra") oromeco(method="omeco").omecois preferred when available, as it is generally faster at finding high-quality paths.- Parameters:
method (Optional[str], optional) – “auto”, “greedy”, “branch”, “plain”, “custom”, “custom_stateful”. Also supports shortcuts like “cotengra”, “cotengra-30-64”, “omeco”, and “omeco-16-32”. defaults to None (“auto”)
optimizer (Optional[Any], optional) – Valid for “custom” or “custom_stateful” as method, defaults to None
memory_limit (Optional[int], optional) – It is not very useful, as
memory_limitleads tobranchcontraction instead ofgreedywhich is rather slow, defaults to None
- Raises:
Exception – Tensornetwork version is too low to support some of the contractors.
ValueError – Unknown method options.
- Returns:
The new tensornetwork with its contractor set.
- Return type:
tn.Node
- tensorcircuit.cons.set_dtype(dtype: str | None = None, set_global: bool = True) Tuple[str, str][source]¶
Set the global runtime numerical dtype of tensors.
- Parameters:
dtype (Optional[str], optional) – “complex64”/”float32” or “complex128”/”float64”, defaults to None, which is equivalent to “complex64”.
- Returns:
complex dtype str and the corresponding real dtype str
- Return type:
Tuple[str, str]
- tensorcircuit.cons.set_function_backend(backend: str | None = None) Callable[[...], Any][source]¶
Function decorator to set function-level runtime backend
- Parameters:
backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”, defaults to None
- Returns:
Decorated function
- Return type:
Callable[…, Any]
- tensorcircuit.cons.set_function_contractor(*confargs: Any, **confkws: Any) Callable[[...], Any][source]¶
Function decorator to set function-level contractor.
- Parameters:
confargs (Any) – Positional arguments forwarded to
set_contractor.confkws (Any) – Keyword arguments forwarded to
set_contractor.
- Returns:
A decorator that wraps
fso it runs under the configured contractor and restores the previous contractor on exit.- Return type:
Callable[…, Any]
- tensorcircuit.cons.set_function_dtype(dtype: str | None = None) Callable[[...], Any][source]¶
Function decorator to set function-level numerical dtype
- Parameters:
dtype (Optional[str], optional) – “complex64” or “complex128”, defaults to None
- Returns:
The decorated function
- Return type:
Callable[…, Any]
- tensorcircuit.cons.set_tensornetwork_backend(backend: str | None = None, set_global: bool = True) Any[source]¶
To set the runtime backend of tensorcircuit.
Note:
tc.set_backendandtc.cons.set_tensornetwork_backendare the same.- Example:
>>> tc.set_backend("numpy") numpy_backend >>> tc.gates.num_to_tensor(0.1) array(0.1+0.j, dtype=complex64) >>> >>> tc.set_backend("tensorflow") tensorflow_backend >>> tc.gates.num_to_tensor(0.1) <tf.Tensor: shape=(), dtype=complex64, numpy=(0.1+0j)> >>> >>> tc.set_backend("pytorch") pytorch_backend >>> tc.gates.num_to_tensor(0.1) tensor(0.1000+0.j) >>> >>> tc.set_backend("jax") jax_backend >>> tc.gates.num_to_tensor(0.1) DeviceArray(0.1+0.j, dtype=complex64)
- Parameters:
backend (Optional[str], optional) – “numpy”, “tensorflow”, “jax”, “pytorch”. defaults to None, which gives the same behavior as
tensornetwork.backend_contextmanager.get_default_backend().set_global (bool) – Whether the object should be set as global.
- Returns:
The tc.backend object that with all registered universal functions.
- Return type:
backend object
- tensorcircuit.cons.split_rules(max_singular_values: int | None = None, max_truncation_err: float | None = None, relative: bool = False) Any[source]¶
Obtain the dictionary of truncation rules
- Parameters:
max_singular_values (int, optional) – The maximum number of singular values to keep.
max_truncation_err (float, optional) – The maximum allowed truncation error.
relative (bool, optional) – Multiply max_truncation_err with the largest singular value.