Quick Start#
This chapter gets you up and running with Kaiwu-PyTorch-Plugin through short, self-contained examples.
1. Basic Examples#
1.1 Restricted Boltzmann Machine (RBM)#
The snippet below shows basic training with the RestrictedBoltzmannMachine class. You can set the number of visible and hidden units and optionally supply custom initial values for the quadratic and linear terms.
import torch
from torch.optim import SGD
import kaiwu as kw
from kaiwu.torch_plugin import RestrictedBoltzmannMachine
from kaiwu.classical import SimulatedAnnealingOptimizer
from kaiwu.cim import CIMOptimizer, PrecisionReducer
from kaiwu.cim import CIMOptimizer, PrecisionReducer
# 添加licence认证
# print("User ID:", os.getenv("USER_ID"), "SDK Code:", os.getenv("SDK_CODE"))
# kw.license.init(os.getenv("USER_ID"), os.getenv("SDK_CODE"))
if __name__ == "__main__":
NUM_READS = 1
SAMPLE_SIZE = 1
USE_CIM = False
if USE_CIM:
kw.common.CheckpointManager.save_dir = "./tmp"
sampler = CIMOptimizer(task_name="test_kpp", wait=True)
sampler = PrecisionReducer(
sampler,
precision=8,
truncated_precision=10,
target_bits=550,
only_feasible_solution=False,
)
else:
sampler = SimulatedAnnealingOptimizer()
num_nodes = 5
num_visible = 2
x = 1.0 * torch.randint(0, 2, (SAMPLE_SIZE, num_visible))
# Instantiate the model
rbm = RestrictedBoltzmannMachine(
num_visible,
num_nodes - num_visible,
quadratic_coef=torch.FloatTensor(
[
[2, -3, 0],
[-1, 2, 0],
]
),
linear_bias=torch.FloatTensor([1, 1, 0, -1, 2]),
)
# Instantiate the optimizer
opt_rbm = SGD(rbm.parameters())
# Example of one iteration in a training loop
# Generate a sample set from the model
x = rbm.get_hidden(x, bernoulli=True)
s = rbm.sample(sampler)
opt_rbm.zero_grad()
# Compute the objective---this objective yields the same gradient as the negative
# log likelihood of the model
objective = rbm.objective(x, s)
# Update model weights with a step of stochastic gradient descent
objective.backward()
1.2 Boltzmann Machine (BM)#
The next example demonstrates the BoltzmannMachine class:
import torch
from torch.optim import SGD
from kaiwu.classical import SimulatedAnnealingOptimizer
from kaiwu.torch_plugin import BoltzmannMachine
# 这里添加licence认证
if __name__ == "__main__":
SAMPLE_SIZE = 5
sampler = SimulatedAnnealingOptimizer(alpha=0.99, size_limit=5)
sample_kwargs = {}
num_nodes = 5
num_visible = 2
x = 1.0 * torch.randint(0, 2, (SAMPLE_SIZE, num_visible))
# Instantiate the model
rbm = BoltzmannMachine(num_nodes)
# Instantiate the optimizer
opt_rbm = SGD(rbm.parameters())
# Example of one iteration in a training loop
# Generate a sample set from the model
x = rbm.condition_sample(sampler, x)
s = rbm.sample(sampler)
opt_rbm.zero_grad()
# Compute the objective---this objective yields the same gradient as the negative
# log likelihood of the model
objective = rbm.objective(x, s)
# Backpropgate gradients
print("call backward")
objective.backward()
print("after backward")
# Update model weights with a step of stochastic gradient descent
opt_rbm.step()
print(objective)
3. Using Different Samplers#
Kaiwu SDK offers several samplers; pick the one that best fits your needs:
from kaiwu.classical import SimulatedAnnealingOptimizer
# Simulated-annealing optimizer (recommended for most scenarios)
sampler_sa = SimulatedAnnealingOptimizer()
# To use the quantum sampler (requires real-machine access)
# from kaiwu.cim import CIMOptimizer
4. Next Steps#
Congratulations—you have finished the quick-start! Where to go next:
Tutorials: read Tutorials for Beginners for more real-world cases
RBM classification: RBM Classification: Handwritten Digit Recognition – classify handwritten digits with an RBM
DBN classification: DBN Classification: Deep Belief Network – classify with a Deep Belief Network
BM generation: BM Generation: Boltzmann Machine Data Generation – generate data with a Boltzmann Machine
Q-VAE: Q-VAE: Quantum Variational Autoencoder – quantum variational auto-encoder for generation and representation learning
API docs: explore every module’s interface and parameters
Example code: the
example/folder contains additional complete examples