快速开始#

本章通过简单的代码示例,帮助您快速上手 Kaiwu-PyTorch-Plugin。

1. 基本示例#

1.1 受限玻尔兹曼机(RBM)#

以下示例展示了如何使用 RestrictedBoltzmannMachine 类进行基本的模型训练。 可以定义可见节点、隐藏节点的个数,以及自定义二次项和一次项的初始化。

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__":
    USE_QPU = False
    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 玻尔兹曼机(BM)#

以下示例展示了如何使用 BoltzmannMachine 类:

import torch

from torch.optim import SGD
from kaiwu.classical import SimulatedAnnealingOptimizer
from kaiwu.torch_plugin import BoltzmannMachine

#  这里添加licence认证


if __name__ == "__main__":
    USE_QPU = False
    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. 使用不同的采样器#

Kaiwu SDK 提供多种采样器,您可以根据需求选择:

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. 下一步#

恭喜您完成了快速开始!接下来,您可以: