======================== CODE SNIPPETS ======================== TITLE: Installation and Setup Commands DESCRIPTION: Commands for installing TensorCircuit-NG, its dependencies (like TensorFlow, Jax, PyTorch), and running it via Docker. Includes commands for checking environment information and installing nightly builds. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst#_snippet_0 LANGUAGE: shell CODE: ``` pip install tensorcircuit-ng ``` LANGUAGE: shell CODE: ``` pip install 'tensorflow[and-cuda]' ``` LANGUAGE: shell CODE: ``` pip install 'jax[cuda-12]' ``` LANGUAGE: shell CODE: ``` sudo docker run -it --network host --gpus all tensorcircuit/tensorcircuit ``` LANGUAGE: shell CODE: ``` tc.about() ``` LANGUAGE: shell CODE: ``` pip uninstall tensorcircuit-ng pip install tensorcircuit-nightly ``` ---------------------------------------- TITLE: Verify TensorFlow Installation (ResNet50 Example) DESCRIPTION: Verifies a TensorFlow installation by loading the CIFAR-100 dataset, defining a ResNet50 model, compiling it with the Adam optimizer, and performing a short training run for 5 epochs. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md#_snippet_5 LANGUAGE: Python CODE: ``` import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]) model.fit(x_train, y_train, epochs=5, batch_size=64) ``` ---------------------------------------- TITLE: Install Tensorcircuit DESCRIPTION: Installs the Tensorcircuit library using pip. This is the final step after setting up the necessary backends. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_6 LANGUAGE: bash CODE: ``` pip install tensorcircuit ``` ---------------------------------------- TITLE: Install Jax or PyTorch Backends DESCRIPTION: Installs optional backend libraries such as Jax or PyTorch using pip. Replace '[Package Name]' with the specific library you intend to install. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_1 LANGUAGE: bash CODE: ``` pip install [Package Name] ``` ---------------------------------------- TITLE: TensorCircuit Setup and Version Check DESCRIPTION: This snippet demonstrates the basic setup for using TensorCircuit with TensorFlow as the backend. It includes importing necessary libraries and printing the installed version of TensorCircuit. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/tutorials/template_cn.ipynb#_snippet_0 LANGUAGE: python CODE: ``` import numpy as np import tensorcircuit as tc tc.set_backend("tensorflow") print(tc.__version__) ``` ---------------------------------------- TITLE: Install Tensorcircuit DESCRIPTION: Installs the Tensorcircuit library using pip. This is the final step to get Tensorcircuit ready for use after setting up prerequisites and optional backends. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md#_snippet_7 LANGUAGE: Python CODE: ``` pip install tensorcircuit ``` ---------------------------------------- TITLE: GPU Setup and Configuration DESCRIPTION: Instructions for setting up GPU support by installing compatible ML backend packages and configuring environment variables for device selection. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/faq.rst#_snippet_0 LANGUAGE: bash CODE: ``` pip install "tensorflow[and-cuda]" ``` LANGUAGE: bash CODE: ``` pip install -U "jax[cuda12]" ``` LANGUAGE: bash CODE: ``` # Set environment variable to specify which GPU(s) to use export CUDA_VISIBLE_DEVICES=0,1 ``` ---------------------------------------- TITLE: TensorCircuit Backend API Listing DESCRIPTION: Provides an example of how to list all available backend-agnostic APIs supported by TensorCircuit. These APIs are implemented either in the TensorNetwork package or TensorCircuit itself. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst#_snippet_11 LANGUAGE: python CODE: ``` >>> [s for s in dir(tc.backend) if not s.startswith("_")] ['abs', 'acos', 'acosh', 'addition', 'adjoint', 'arange', 'argmax', 'argmin', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'broadcast_left_multiplication', 'broadcast_right_multiplication', 'cast', 'cholesky', 'concat', 'cond', 'conj', 'convert_to_tensor', 'coo_sparse_matrix', 'coo_sparse_matrix_from_numpy', 'copy', 'cos', 'cosh', 'cumsum', 'deserialize_tensor', 'device', 'device_move', 'diagflat', 'diagonal', 'divide', 'dtype', 'eigh', 'eigs', 'eigsh', 'eigsh_lanczos', 'eigvalsh', 'einsum' ``` ---------------------------------------- TITLE: TensorCircuit JIT Acceleration Example DESCRIPTION: Illustrates the performance benefits of Just-In-Time (JIT) compilation for quantum circuit simulations. It compares the execution time of a noisy circuit with and without JIT. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst#_snippet_8 LANGUAGE: python CODE: ``` import time import tensorcircuit as tc K = tc.set_backend("tensorflow") # Define a quantum circuit function def noisy_circuit(key): c = tc.Circuit(5) for i in range(5): c.h(i) c.depolarizing(i, px=0.01, py=0.01, pz=0.01, status=key[i]) return c.expectation_ps(z=[0]) # Compare performance with and without JIT start = time.time() for _ in range(100): noisy_circuit(K.ones([5])) print("Without JIT:", time.time() - start) jitted_circuit = K.jit(noisy_circuit) start = time.time() for _ in range(100): jitted_circuit(K.ones([5])) print("With JIT:", time.time() - start) ``` ---------------------------------------- TITLE: Setup Conda Environment and Install Packages DESCRIPTION: Creates a new Conda virtual environment named 'NewEnv' with Python version 3.8.5, activates it, and proceeds to install TensorFlow (from a local .whl file), Jax, and Optax using specific versions. It also includes a step to install 'chardet' if it's missing and finally installs the tensorcircuit package. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacM2.md#_snippet_2 LANGUAGE: shell CODE: ``` conda create --name NewEnv python==3.8.5 conda activate NewEnv pip install ~/Downloads/tensorflow-2.4.1-py3-none-any.whl conda install jax==0.3.0 conda install optax==0.1.4 conda install chardet pip install tensorcircuit ``` ---------------------------------------- TITLE: Install Miniconda for Tensorflow Optimization DESCRIPTION: Installs Miniconda, a minimal installer for the conda package manager. This is recommended for installing Tensorflow optimized for MacOS (tensorflow-macos) or with Metal support (tensorflow-metal). SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_2 LANGUAGE: bash CODE: ``` curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh bash ~/miniconda.sh -b -p $HOME/miniconda source ~/miniconda/bin/activate conda install -c apple tensorflow-deps ``` ---------------------------------------- TITLE: Setup and Backend Initialization DESCRIPTION: Imports necessary libraries (matplotlib, PCA, tensorflow, tensorcircuit) and sets the backend for tensorcircuit to TensorFlow. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/tutorials/qml_scenarios.ipynb#_snippet_0 LANGUAGE: python CODE: ``` from matplotlib import pyplot as plt from sklearn.decomposition import PCA import tensorflow as tf import tensorcircuit as tc K = tc.set_backend("tensorflow") ``` ---------------------------------------- TITLE: TensorCircuit Setup and Version Check DESCRIPTION: This snippet demonstrates the basic setup for using TensorCircuit with TensorFlow as the backend. It includes importing necessary libraries and printing the installed version of TensorCircuit. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/tutorials/template.ipynb#_snippet_0 LANGUAGE: python CODE: ``` import numpy as np import tensorcircuit as tc tc.set_backend("tensorflow") print(tc.__version__) ``` ---------------------------------------- TITLE: TensorCircuit Backend Agnosticism and API Usage DESCRIPTION: Demonstrates how to set and use different computational backends (TensorFlow, Jax) within TensorCircuit. It shows examples of creating tensors and accessing backend-agnostic functions. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst#_snippet_10 LANGUAGE: python CODE: ``` >>> import tensorcircuit as tc >>> K = tc.set_backend("tensorflow") >>> K.ones([2,2]) >>> tc.backend.eye(3) >>> tc.set_backend("jax") >>> tc.backend.name 'jax' >>> tc.backend.implicit_randu() WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.) DeviceArray([0.7400521], dtype=float32) ``` ---------------------------------------- TITLE: Install Tensorflow-Metal Plugin DESCRIPTION: Installs the tensorflow-metal PluggableDevice, which enables Tensorflow to utilize Apple's Metal GPU acceleration. This installation is optional and not recommended for all users. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_4 LANGUAGE: bash CODE: ``` pip install tensorflow-metal ``` ---------------------------------------- TITLE: Install Xcode Command Line Tools DESCRIPTION: Installs essential command-line tools for macOS development. This is a prerequisite for many software installations and is recommended for a smooth development experience. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md#_snippet_0 LANGUAGE: Shell CODE: ``` xcode-select --install ``` ---------------------------------------- TITLE: TensorCircuit Setup DESCRIPTION: Imports necessary libraries for TensorCircuit, NumPy, Cotengra, and Opt-einsum, and sets the backend for TensorCircuit. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/tutorials/contractors.ipynb#_snippet_0 LANGUAGE: python CODE: ``` import tensorcircuit as tc import numpy as np import cotengra as ctg import opt_einsum as oem K = tc.set_backend("tensorflow") ``` ---------------------------------------- TITLE: TensorCircuit Example Circuit Block DESCRIPTION: Demonstrates the usage of a pre-defined circuit block, `example_block`, within TensorCircuit. This block is applied to a circuit, showcasing modular circuit construction. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst#_snippet_33 LANGUAGE: python CODE: ``` c = tc.Circuit(4) c = tc.templates.blocks.example_block(c, tc.backend.ones([16])) ``` ---------------------------------------- TITLE: Install Vanilla Tensorflow DESCRIPTION: Installs the standard Tensorflow package developed by Google using pip. This step can be skipped if you are installing Tensorflow optimized for MacOS or with Metal support via Miniconda. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_3 LANGUAGE: bash CODE: ``` pip install tensorflow ``` ---------------------------------------- TITLE: PyTorch Interface with JIT DESCRIPTION: Demonstrates using the PyTorch interface with JIT compilation enabled for a function. It shows how to integrate a quantum circuit computation within a PyTorch workflow, including automatic differentiation. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/quickstart.rst#_snippet_23 LANGUAGE: python CODE: ``` import tensorcircuit as tc import torch def f(a): # Assume f is a function that uses tensorcircuit operations # For demonstration, let's simulate a simple operation c = tc.Circuit(1) c.rx(0, theta=a[0]) return tc.backend.real(c.expectation_ps(z=[0])) f_torch = tc.interfaces.torch_interface(f, jit=True) a = torch.ones([2], requires_grad=True) b = f_torch(a) c = b ** 2 c.backward() print(a.grad) ``` ---------------------------------------- TITLE: JuliaCall Setup and Installation DESCRIPTION: Steps required to set up the JuliaCall environment, including installing Julia, configuring the PATH, installing the JuliaCall Python package, and installing necessary Julia packages like OMEinsum. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/examples/omeinsum_julia/README.md#_snippet_6 LANGUAGE: shell CODE: ``` Step 1: Install Julia (>= 1.8.5 recommended). Step 2: Add Julia path to the PATH env variable. Step 3: pip install juliacall Step 4: Install Julia package: "using Pkg; Pkg.add(\"OMEinsum\")" Step 5: Set environment variable for Julia multi-threading: PYTHON_JULIACALL_THREADS= ``` ---------------------------------------- TITLE: TensorCircuit Setup and Backend Configuration DESCRIPTION: Initializes TensorCircuit, imports necessary libraries like NumPy, cotengra, and opt_einsum, and sets the backend to TensorFlow. This is the foundational setup for running TensorCircuit simulations. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/tutorials/contractors_cn.ipynb#_snippet_0 LANGUAGE: python CODE: ``` import tensorcircuit as tc import numpy as np import cotengra as ctg import opt_einsum as oem K = tc.set_backend("tensorflow") ``` ---------------------------------------- TITLE: Install Miniconda for Python Environment Management DESCRIPTION: Downloads and installs the latest Miniconda distribution for macOS ARM64. It sets up a base environment and installs TensorFlow dependencies, crucial for managing Python packages and environments. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_MacARM.md#_snippet_1 LANGUAGE: Shell CODE: ``` curl -o ~/miniconda.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh bash ~/miniconda.sh -b -p $HOME/miniconda source ~/miniconda/bin/activate conda install -c apple tensorflow-deps ``` ---------------------------------------- TITLE: Verify TensorFlow Installation DESCRIPTION: Loads the CIFAR-100 dataset, defines a ResNet50 model, compiles it with Adam optimizer, and trains it for a few epochs to verify the TensorFlow installation and backend functionality. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md#_snippet_5 LANGUAGE: python CODE: ``` import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]) model.fit(x_train, y_train, epochs=5, batch_size=64) ``` ---------------------------------------- TITLE: Install Xcode Command Line Tools DESCRIPTION: Installs essential command line tools for development on MacOS. This command can be run directly in the terminal or by downloading an installer image from Apple if internet connectivity is poor. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_0 LANGUAGE: bash CODE: ``` xcode-select --install ``` ---------------------------------------- TITLE: Install Jax, Pytorch (Optional) DESCRIPTION: Installs optional backend libraries like Jax or Pytorch for Tensorcircuit. These packages are installed using pip, the Python package installer. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac_cn.md#_snippet_1 LANGUAGE: bash CODE: ``` pip install [Package Name] ``` ---------------------------------------- TITLE: Verify Tensorflow Installation DESCRIPTION: Verifies the Tensorflow installation by loading the CIFAR-100 dataset, defining a ResNet50 model, compiling it with the Adam optimizer, and performing a short training run. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/contribs/development_Mac.md#_snippet_5 LANGUAGE: python CODE: ``` import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]) model.fit(x_train, y_train, epochs=5, batch_size=64) ``` ---------------------------------------- TITLE: Setup and Imports DESCRIPTION: Imports necessary libraries for TensorCircuit operations, including functools, inspect, sys, numpy, tensorflow, and tensorcircuit itself. These are foundational for building and simulating quantum circuits. SOURCE: https://github.com/tensorcircuit/tensorcircuit-ng/blob/master/docs/source/tutorials/circuit_basics.ipynb#_snippet_0 LANGUAGE: python CODE: ``` from functools import partial import inspect import sys import numpy as np import tensorflow as tf import tensorcircuit as tc ```