News

日本語 · English · 中文

[Guest Contribution] What You Should Learn from Internships: Part 3/3 – LLMs, Diffusion Models, and Tensor Networks

This article explores the mathematical foundations of LLMs and diffusion models through Python, and addresses efficient representations of quantum circuits using tensor networks. It explains examples from Hugging Face and Stable Diffusion, as well as quantum state calculations using PyTorch's einsum.

See the previous article here

【Contributed】blueqat Internship Course: Practical Models from Regression to Image Classification

Session 5: Generative and Exploratory AI (LLM + Diffusion)

In this session, we cover two pillars supporting modern AI.

  1. Large Language Model (LLM)
  2. Diffusion Model

LLMs are "AI that generates and explores text,"
while Diffusion Models are "AI that generates images and data."

Objectives:

  • Understand the mathematical foundations of generative AI
  • Experience LLM APIs and diffusion processes using Python

1. Fundamentals of LLM (Large Language Model)

Based on the Transformer architecture, these models generate text by autoregressively predicting the next word.

Basic equation:

\[P(w_1, w_2, ..., w_T) = \prod_{t=1}^{T} P(w_t | w_{<t})\]

Example: Generation using HuggingFace API

!pip install transformers -q

from transformers import pipeline

# English text generation pipeline
generator = pipeline("text-generation", model="gpt2")

prompt = "In the future, quantum computers will"
result = generator(prompt, max_length=40, num_return_sequences=1)

print("Generated text:\n", result[0]["generated_text"])

Generated text:
In the future, quantum computers will likely evolve into machines with the capacity to perform a number of important tasks, including computational models of the general population, which would lead to new applications in the field of

The output shows the model predicting based on learned "future contexts."

LLMs perform probabilistic generation, outputting slightly different text each time even with the same input.

Next, let's look at the Diffusion Model, which generates images.

2. Diffusion Model

A model that generates data by gradually removing noise.

Diffusion process (forward process):

\[q(x_t | x_{t-1}) = \mathcal{N}(x_t; \sqrt{1-\beta_t}x_{t-1}, \beta_t I)\]

Reverse diffusion process (denoising process):

\[p_\theta(x_{t-1}|x_t)\]

Intuitively:

  1. Add noise to an image (diffusion)
  2. The trained model reconstructs the image while removing noise (generation)
import numpy as np
import matplotlib.pyplot as plt

# Sample image (sine wave)
x0 = np.sin(np.linspace(0, 4*np.pi, 100))
noise_levels = np.linspace(0, 1, 5)

plt.figure(figsize=(8,3))
for i, nl in enumerate(noise_levels):
    noisy = x0 + np.random.randn(len(x0)) * nl
    plt.plot(noisy, label=f"Noise={nl:.1f}")
plt.legend()
plt.title("Diffusion Process (adding noise)")
plt.show()

The graph above visualizes the process of progressively adding noise to "break" the data.
The model reverses this process by removing the noise to reproduce the original distribution.

Next, we briefly introduce an example of actual image generation (Stable Diffusion).

!pip install diffusers transformers accelerate safetensors -q

from diffusers import StableDiffusionPipeline
import torch

# Automatic device detection
device = "cuda" if torch.cuda.is_available() else "cpu"

# Remove torch_dtype or specify float32 to run on CPU
pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float32   # ✅ Correction point
).to(device)

prompt = "A futuristic cityscape with quantum computers, art style, 8k"
image = pipe(prompt).images[0]
image.save("generated_city.png")

image

The code above generates an image from a text prompt.

Stable Diffusion is a representative diffusion model,
producing high-quality images by learning "probabilistic noise removal."

Session 6: Quantum Computing and Tensor Networks

Quantum computer calculations involve massive matrix computations. However, as the number of qubits increases, the size of the matrices grows exponentially, making them impossible to handle with conventional computing. This is where the concept of Tensor Networks comes in, which decomposes calculations into a "network" to improve efficiency.


1. Fundamentals of Tensors: Dimensions and Axes

While tensors are familiar in deep learning, they are easier to understand in the context of quantum computing as diagrams with "legs (indices)."

  • Scalar (0th-order tensor): No legs
  • Vector (1st-order tensor): One leg
  • Matrix (2nd-order tensor): Two legs
  • 3rd-order and higher tensors: Three or more legs

2. Einstein Summation Notation (einsum)

The most powerful tool for tensor network calculations is torch.einsum. It allows you to specify which axes (legs) to connect and sum over using character notation.

For example, the matrix-vector product \(y_i = \sum_j A_{ij} x_j\) is an operation where the common index \(j\) disappears (is contracted).

import torch

# Matrix A (2x2) and Vector x (2)
A = torch.randn(2, 2)
x = torch.randn(2)

# Standard matrix multiplication
y_matmul = torch.matmul(A, x)

# einsum notation: 'ij,j->i' 
# Means contracting the matrix (i,j) and vector (j) by eliminating the common j, leaving i
y_einsum = torch.einsum('ij,j->i', A, x)

print("Are they equal:", torch.allclose(y_matmul, y_einsum))

Are they equal: True


3. Viewing Quantum Circuits as Tensor Networks

Quantum states are vectors, and quantum gates are matrices. A quantum circuit can be viewed as a network where these are connected by "lines (qubits)."

Practice: Simulation of Hadamard and CNOT Gates

Let's calculate a 2-qubit circuit \(\mathrm{CNOT}\,(H \otimes I)\,|00\rangle\) using PyTorch.

# 1. Prepare quantum state |0> (vector)
zero = torch.tensor([1.0, 0.0]) # |0>

# 2. Define gates (matrices)
H = torch.tensor([[1.0, 1.0], [1.0, -1.0]]) / (2.0**0.5) # Hadamard
CNOT = torch.zeros(2, 2, 2, 2) # 2-qubit gate defined as a 4th-order tensor
CNOT[0,0,0,0] = 1; CNOT[0,1,0,1] = 1; CNOT[1,0,1,1] = 1; CNOT[1,1,1,0] = 1

# 3. Initial state |00> = |0> ⊗ |0>
# With indices i, j
state = torch.einsum('i,j->ij', zero, zero)

# 4. Apply H gate to the first bit
# Connect axis i of state(i,j) with H(k,i) to create a new axis k
state = torch.einsum('ki,ij->kj', H, state)

# 5. Apply CNOT gate
# Contract CNOT(out1, out2, in1, in2) with state(in1, in2)
state = torch.einsum('klmn,mn->kl', CNOT, state)

print("Final state vector (Bell State):\n", state)
# If the result is [[0.7071, 0], [0, 0.7071]], it represents the Bell state (|00> + |11>)/√2

Final state vector (Bell State):
tensor([[0.7071, 0.0000],
[0.0000, 0.7071]])


4. Why use PyTorch? (Practical Benefits)

There are reasons for intentionally using PyTorch (tensor networks) in quantum computing environments like blueqat.

  1. Automatic differentiation: Gate parameters (angles) can be optimized using gradient descent (quantum machine learning).
  2. GPU acceleration: Simulations of dozens of qubits can be accelerated.
  3. Efficient contraction: Even when circuits become large, calculations can be performed without creating huge matrices by optimizing the order of connections.

Summary of Chapter 6

  • Tensors are containers that express qubits and gates.
  • einsum is a very convenient tool for formalizing the "wiring" of circuits mathematically.
  • By solving quantum circuits as tensor networks, deep learning techniques (PyTorch) can be directly applied to quantum computing.

This article was translated from the Japanese original. 日本語で読む

← Latest articles