Use Arbitrary Expressions as Gate Parameters via Embedding
By default, a Parametric
operation expects a values
dict with a
value for its parameter in the forward-pass when initialized using a str
parameter.
Using arbitrary expressions as parameters
pyqtorch
allows for using arbitary expressions as parameters, for instance sin(x)
where x
can be
a FeatureParameter. To do so, a name has to be assigned to the outcome of the evaluation of sin(x)
and
supplied to the pyq.QuantumCircuit
within an instance of Embedding
.
Creating parameter expressions using ConcretizedCallable
pyq.ConcretizedCallable
expects a name for a function and a list of arguments
import torch
import pyqtorch as pyq
sin_x, sin_x_fn = 'sin_x', pyq.ConcretizedCallable(call_name = 'sin', abstract_args=['x'])
# We can now evaluate sin_x_fn using a values dict
x = torch.rand(1, requires_grad=True)
values = {'x': x}
result = sin_x_fn(values)
print(torch.autograd.grad(result, x, torch.ones_like(result))[0])
Interfacing ConcretizedCallable
with QuantumCircuit parameters via the Embedding
class
Lets use sin_x
in another callable, so our gate will be parametrized by the result of the expression y * sin(x)
where y
is trainable and x
is a feature parameter.
We can tell pyq
how to associate each callable with its underlying parameters via the Embedding
class which expects arguments regarding what are trainable and non-trainable symbols.
mul_sinx_y, mul_sinx_y_fn = 'mul_sinx_y', pyq.ConcretizedCallable(call_name = 'mul', abstract_args=['sin_x', 'y'])
embedding = pyq.Embedding(vparam_names=['y'], fparam_names=['x'], var_to_call={sin_x: sin_x_fn, mul_sinx_y: mul_sinx_y_fn})
circ = pyq.QuantumCircuit(1, [pyq.RX(0, mul_sinx_y)])
state= pyq.zero_state(1)
y = torch.rand(1, requires_grad=True)
values = {'x': x, 'y': y}
obs = pyq.Observable([pyq.Z(0)])
expval = pyq.expectation(circuit=circ, state=state, values=values, observable=obs, diff_mode=pyq.DiffMode.AD, embedding=embedding)
print(torch.autograd.grad(expval, (x, y), torch.ones_like(expval)))
Tracking and Reembedding a tracked parameter
For specific usecases, a tparam
argument can be passed to the Embedding
which tells the class to track the
computations depending on it which enables for their efficient recomputation given different
values for tparam
.
v_params = ["theta"]
f_params = ["x"]
tparam = "t"
leaf0, native_call0 = "%0", pyq.ConcretizedCallable(
"mul", ["x", "theta"], {}
)
leaf1, native_call1 = "%1", pyq.ConcretizedCallable(
"mul", ["t", "%0"], {}
)
leaf2, native_call2 = "%2", pyq.ConcretizedCallable("sin", ["%1"], {})
embedding = pyq.Embedding(
v_params,
f_params,
var_to_call={leaf0: native_call0, leaf1: native_call1, leaf2: native_call2},
tparam_name=tparam,
)
inputs = {
"x": torch.rand(1),
"theta": torch.rand(1),
tparam: torch.rand(1),
}
all_params = embedding.embed_all(inputs)
print(f'{leaf2} value before reembedding: {all_params[leaf2]}')
new_tparam_val = torch.rand(1)
reembedded_params = embedding.reembed_tparam(all_params, new_tparam_val)
print(f'{leaf2} value after reembedding: {reembedded_params[leaf2]}')
See the docstrings for more details and examples:
ConcretizedCallable
Transform an abstract function name and arguments into a callable in a linear algebra engine which can be evaluated using user input. Arguments: call_name: The name of the function. abstract_args: A list of arguments to the function, can be numeric types for constants or strings for parameters instruction_mapping: A dict containing user-passed mappings from a function name to its implementation. engine_name: The name of the framework to use. device: Which device to use.
Example:
import torch
from pyqtorch.embed import ConcretizedCallable
In [11]: call = ConcretizedCallable('sin', ['x'], engine_name='numpy')
In [12]: call({'x': 0.5})
Out[12]: 0.479425538604203
In [13]: call = ConcretizedCallable('sin', ['x'], engine_name='torch')
In [14]: call({'x': torch.rand(1)})
Out[14]: tensor([0.5531])
In [15]: call = ConcretizedCallable('sin', ['x'], engine_name='jax')
In [16]: call({'x': 0.5})
Out[16]: Array(0.47942555, dtype=float32, weak_type=True)
Source code in pyqtorch/embed.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
|
Embedding
A class relating variational and feature parameters used in ConcretizedCallable instances to parameter names used in gates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vparam_names
|
list[str]
|
A list of variational parameters. |
[]
|
fparam_names
|
list[str]
|
A list of feature parameters. |
[]
|
var_to_call
|
dict[str, ConcretizedCallable] | None
|
A dict mapping from < |
None
|
tparam_name
|
str | None
|
Optional name for a time parameter. |
None
|
engine_name
|
str
|
The name of the linear algebra engine. |
'torch'
|
device
|
str
|
The device to use |
'cpu'
|
Example:
from __future__ import annotations
import numpy as np
import pytest
import torch
import torch.autograd.gradcheck
import pyqtorch as pyq
from pyqtorch.embed import ConcretizedCallable, Embedding
name0, fn0 = "fn0", ConcretizedCallable("sin", ["x"])
name1, fn1 = "fn1", ConcretizedCallable("mul", ["fn0", "y"])
name2, fn2 = "fn2", ConcretizedCallable("mul", ["fn1", 2.0])
name3, fn3 = "fn3", ConcretizedCallable("log", ["fn2"])
embedding = pyq.Embedding(
vparam_names=["x"],
fparam_names=["y"],
var_to_call={name0: fn0, name1: fn1, name2: fn2, name3: fn3},
)
rx = pyq.RX(0, param_name=name0)
cry = pyq.CRY(0, 1, param_name=name1)
phase = pyq.PHASE(1, param_name=name2)
ry = pyq.RY(1, param_name=name3)
cnot = pyq.CNOT(1, 2)
ops = [rx, cry, phase, ry, cnot]
n_qubits = 3
circ = pyq.QuantumCircuit(n_qubits, ops)
obs = pyq.Observable([pyq.Z(0)])
state = pyq.zero_state(n_qubits)
x = torch.rand(1, requires_grad=True)
y = torch.rand(1, requires_grad=True)
values_ad = {"x": x, "y": y}
embedded_params = embedding(values_ad)
wf = pyq.run(circ, state, embedded_params, embedding)
Source code in pyqtorch/embed.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 |
|
__call__(inputs=None)
Functional version of legacy embedding: Return a new dictionary with all embedded parameters.
embed_all(inputs=None)
The standard embedding of all intermediate and leaf parameters. Include the root_params, i.e., the vparams and fparams original values to be reused in computations.
Source code in pyqtorch/embed.py
reembed_tparam(embedded_params, tparam_value)
Receive already embedded params containing intermediate and leaf parameters
and recalculate the those which are dependent on tparam_name
using the new value
tparam_value
.