qukan 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- qukan-0.1.0/LICENSE +165 -0
- qukan-0.1.0/PKG-INFO +70 -0
- qukan-0.1.0/README.md +47 -0
- qukan-0.1.0/pyproject.toml +46 -0
- qukan-0.1.0/src/qukan/__init__.py +20 -0
- qukan-0.1.0/src/qukan/devices.py +16 -0
- qukan-0.1.0/src/qukan/neuron.py +118 -0
- qukan-0.1.0/src/qukan/qcbm.py +50 -0
- qukan-0.1.0/src/qukan/qukan.py +338 -0
- qukan-0.1.0/src/qukan/splines.py +101 -0
qukan-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or installing an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
捕捉 "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not governed by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that numbered version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version ever published by
|
|
159
|
+
the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
which future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
qukan-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qukan
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official implementation for 'Quantum Kolmogorov Arnold Network' (QuKAN) implementated using PennyLane and PyTorch. Paper: Werner, Y., Malemath, A., Liu, M., Fortes Rey, V., Palaiodimopoulos, N., Lukowicz, P., & Kiefer-Emmanouilidis, M. (2025). QuKAN: A Quantum Circuit Born Machine Approach to Quantum Kolmogorov Arnold Networks. Scientific Reports, 15(1), 35239.
|
|
5
|
+
License-Expression: LGPL-3.0-only
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Yannick Werner
|
|
8
|
+
Author-email: yannick.werner@dfki.de
|
|
9
|
+
Requires-Python: >=3.10,<3.13
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Requires-Dist: icecream (>=2.1.0)
|
|
15
|
+
Requires-Dist: matplotlib (>=3.9.0)
|
|
16
|
+
Requires-Dist: numpy (>=1.26.0)
|
|
17
|
+
Requires-Dist: pennylane (>=0.40.0)
|
|
18
|
+
Requires-Dist: torch (>=2.4.0)
|
|
19
|
+
Requires-Dist: tqdm (>=4.66.0)
|
|
20
|
+
Project-URL: Homepage, https://github.com/QuanTUK/QuKAN
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# QuKAN: Quantum Kolmogorov Arnold Network
|
|
24
|
+
|
|
25
|
+
QuKAN is a Python package for Quantum Kolmogorov Arnold Networks, built on top of [PennyLane](https://pennylane.ai/) and [PyTorch](https://pytorch.org/). It inlcudes hybrid and fully quantum neuron architecture implementations.
|
|
26
|
+
|
|
27
|
+
## Features
|
|
28
|
+
- Quantum Spline implementation
|
|
29
|
+
- Quantum KAN Neurons
|
|
30
|
+
- Scalable QuKAN architecture
|
|
31
|
+
- Support for QCBM-based spline pretraining
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# Using poetry
|
|
37
|
+
poetry install
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import torch
|
|
44
|
+
import torch.nn as nn
|
|
45
|
+
from qukan import QuKAN
|
|
46
|
+
|
|
47
|
+
# 1. Initialize model
|
|
48
|
+
model = QuKAN(feature_dim=2, num_hlayers=1)
|
|
49
|
+
|
|
50
|
+
# 2. Setup training components
|
|
51
|
+
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
|
|
52
|
+
criterion = nn.MSELoss()
|
|
53
|
+
|
|
54
|
+
# 3. Dummy data
|
|
55
|
+
x = torch.rand(10, 2)
|
|
56
|
+
y = torch.rand(10, 1)
|
|
57
|
+
|
|
58
|
+
# 4. Training loop
|
|
59
|
+
for epoch in range(5):
|
|
60
|
+
optimizer.zero_grad()
|
|
61
|
+
output = model(x)
|
|
62
|
+
loss = criterion(output, y)
|
|
63
|
+
loss.backward()
|
|
64
|
+
optimizer.step()
|
|
65
|
+
print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
LGPL-3.0-only
|
|
70
|
+
|
qukan-0.1.0/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# QuKAN: Quantum Kolmogorov Arnold Network
|
|
2
|
+
|
|
3
|
+
QuKAN is a Python package for Quantum Kolmogorov Arnold Networks, built on top of [PennyLane](https://pennylane.ai/) and [PyTorch](https://pytorch.org/). It inlcudes hybrid and fully quantum neuron architecture implementations.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
- Quantum Spline implementation
|
|
7
|
+
- Quantum KAN Neurons
|
|
8
|
+
- Scalable QuKAN architecture
|
|
9
|
+
- Support for QCBM-based spline pretraining
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
# Using poetry
|
|
15
|
+
poetry install
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import torch
|
|
22
|
+
import torch.nn as nn
|
|
23
|
+
from qukan import QuKAN
|
|
24
|
+
|
|
25
|
+
# 1. Initialize model
|
|
26
|
+
model = QuKAN(feature_dim=2, num_hlayers=1)
|
|
27
|
+
|
|
28
|
+
# 2. Setup training components
|
|
29
|
+
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
|
|
30
|
+
criterion = nn.MSELoss()
|
|
31
|
+
|
|
32
|
+
# 3. Dummy data
|
|
33
|
+
x = torch.rand(10, 2)
|
|
34
|
+
y = torch.rand(10, 1)
|
|
35
|
+
|
|
36
|
+
# 4. Training loop
|
|
37
|
+
for epoch in range(5):
|
|
38
|
+
optimizer.zero_grad()
|
|
39
|
+
output = model(x)
|
|
40
|
+
loss = criterion(output, y)
|
|
41
|
+
loss.backward()
|
|
42
|
+
optimizer.step()
|
|
43
|
+
print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## License
|
|
47
|
+
LGPL-3.0-only
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "qukan"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Official implementation for 'Quantum Kolmogorov Arnold Network' (QuKAN) implementated using PennyLane and PyTorch. Paper: Werner, Y., Malemath, A., Liu, M., Fortes Rey, V., Palaiodimopoulos, N., Lukowicz, P., & Kiefer-Emmanouilidis, M. (2025). QuKAN: A Quantum Circuit Born Machine Approach to Quantum Kolmogorov Arnold Networks. Scientific Reports, 15(1), 35239."
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Yannick Werner", email="yannick.werner@dfki.de"},
|
|
7
|
+
{name = "Akash Malemath"},
|
|
8
|
+
{name = "Mengxi Liu"},
|
|
9
|
+
{name = "Vitor Fortes Rey"},
|
|
10
|
+
{name = "Nik Palaiodimopoulos"},
|
|
11
|
+
{name = "Paul Lukowicz"},
|
|
12
|
+
{name = "Maximilian Kiefer-Emmanouilidis"},
|
|
13
|
+
|
|
14
|
+
]
|
|
15
|
+
license = "LGPL-3.0-only"
|
|
16
|
+
readme = "README.md"
|
|
17
|
+
requires-python = ">=3.10,<3.13"
|
|
18
|
+
dependencies = [
|
|
19
|
+
"torch>=2.4.0",
|
|
20
|
+
"pennylane>=0.40.0",
|
|
21
|
+
"matplotlib>=3.9.0",
|
|
22
|
+
"icecream>=2.1.0",
|
|
23
|
+
"numpy>=1.26.0",
|
|
24
|
+
"tqdm>=4.66.0",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/QuanTUK/QuKAN"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
32
|
+
build-backend = "poetry.core.masonry.api"
|
|
33
|
+
|
|
34
|
+
[tool.poetry]
|
|
35
|
+
packages = [{include = "qukan", from = "src"}]
|
|
36
|
+
|
|
37
|
+
[tool.poetry.group.dev.dependencies]
|
|
38
|
+
ruff = "^0.15.9"
|
|
39
|
+
|
|
40
|
+
[tool.ruff]
|
|
41
|
+
line-length = 100
|
|
42
|
+
target-version = "py312"
|
|
43
|
+
|
|
44
|
+
[tool.ruff.lint]
|
|
45
|
+
select = ["E", "F", "I", "UP", "N", "B", "A", "C4", "SIM", "PLE"]
|
|
46
|
+
ignore = ["N801", "N802", "N803", "N806"] # Allow camelCase for models to match existing student code style where appropriate
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .devices import DEFAULT_QML_DEVICE_NAME, DEFAULT_TORCH_DEVICE, get_qml_device
|
|
2
|
+
from .neuron import FQuKANNeuron, QuKANNeuron
|
|
3
|
+
from .qcbm import MMD, QCBM
|
|
4
|
+
from .qukan import FQuKAN, QuKAN
|
|
5
|
+
from .splines import encode_bsplines, encode_bsplinesSILU, trained_splines
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"QuKAN",
|
|
9
|
+
"FQuKAN",
|
|
10
|
+
"QuKANNeuron",
|
|
11
|
+
"FQuKANNeuron",
|
|
12
|
+
"encode_bsplines",
|
|
13
|
+
"trained_splines",
|
|
14
|
+
"encode_bsplinesSILU",
|
|
15
|
+
"QCBM",
|
|
16
|
+
"MMD",
|
|
17
|
+
"DEFAULT_TORCH_DEVICE",
|
|
18
|
+
"DEFAULT_QML_DEVICE_NAME",
|
|
19
|
+
"get_qml_device",
|
|
20
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import pennylane as qml
|
|
3
|
+
|
|
4
|
+
# Centralized Torch device (Explicitly locked to CPU for stability)
|
|
5
|
+
DEFAULT_TORCH_DEVICE = torch.device("cpu")
|
|
6
|
+
|
|
7
|
+
# Centralized PennyLane device configuration
|
|
8
|
+
DEFAULT_QML_DEVICE_NAME = "default.qubit"
|
|
9
|
+
|
|
10
|
+
def get_qml_device(n_qubits, name=DEFAULT_QML_DEVICE_NAME):
|
|
11
|
+
"""
|
|
12
|
+
Factory function to create a PennyLane device.
|
|
13
|
+
Centralizing this allows for easy switching of backends (e.g. to 'lightning.qubit')
|
|
14
|
+
across the entire library.
|
|
15
|
+
"""
|
|
16
|
+
return qml.device(name, wires=n_qubits)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pennylane as qml
|
|
3
|
+
import torch
|
|
4
|
+
from torch.nn.functional import silu
|
|
5
|
+
|
|
6
|
+
from .devices import DEFAULT_TORCH_DEVICE, get_qml_device
|
|
7
|
+
from .splines import encode_bsplines, encode_bsplinesSILU
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def get_circuit(num_qubits):
|
|
11
|
+
dev = get_qml_device(num_qubits)
|
|
12
|
+
|
|
13
|
+
@qml.qnode(device=dev, interface="torch")
|
|
14
|
+
def circuit(state, weights):
|
|
15
|
+
qml.AmplitudeEmbedding(state, wires=range(num_qubits), normalize=True)
|
|
16
|
+
for layer in range(weights.shape[0]):
|
|
17
|
+
for qubit in range(weights.shape[1]):
|
|
18
|
+
qml.RY(phi=weights[layer, qubit], wires=qubit)
|
|
19
|
+
for qubit in range(weights.shape[1] - 1):
|
|
20
|
+
qml.CNOT(wires=[qubit, qubit + 1])
|
|
21
|
+
qml.CNOT(wires=[weights.shape[1] - 1, 0])
|
|
22
|
+
return qml.probs()
|
|
23
|
+
|
|
24
|
+
return circuit
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def QuKANNeuron(
|
|
28
|
+
inputs_batch,
|
|
29
|
+
params,
|
|
30
|
+
weights,
|
|
31
|
+
num_splines=4,
|
|
32
|
+
min_val=0,
|
|
33
|
+
max_val=1,
|
|
34
|
+
num_points=64,
|
|
35
|
+
strat="Mott",
|
|
36
|
+
state=None,
|
|
37
|
+
norm=None,
|
|
38
|
+
):
|
|
39
|
+
# Encoding strategy for the splines
|
|
40
|
+
if strat == "Mott":
|
|
41
|
+
state, norm = encode_bsplines(
|
|
42
|
+
n=num_splines, num_points=num_points, min_v=min_val, max_v=max_val
|
|
43
|
+
)
|
|
44
|
+
if strat == "QCBM":
|
|
45
|
+
state, norm = state, norm
|
|
46
|
+
|
|
47
|
+
state.to(dtype=torch.complex64)
|
|
48
|
+
|
|
49
|
+
# Adjust interval with the range of the input data
|
|
50
|
+
if torch.min(inputs_batch) < min_val:
|
|
51
|
+
min_val = torch.min(inputs_batch)
|
|
52
|
+
if torch.max(inputs_batch) > max_val:
|
|
53
|
+
max_val = torch.max(inputs_batch)
|
|
54
|
+
|
|
55
|
+
# min_val,max_val = torch.min(inputs_batch),torch.max(inputs_batch)
|
|
56
|
+
intval = torch.linspace(min_val, max_val, steps=num_points)
|
|
57
|
+
|
|
58
|
+
num_qubits = int(np.log2(num_splines * num_points))
|
|
59
|
+
_circuit = get_circuit(num_qubits)
|
|
60
|
+
out = _circuit(state, params)
|
|
61
|
+
|
|
62
|
+
closest_index = torch.argmin(torch.abs(intval.view(1, -1) - inputs_batch.view(-1, 1)), dim=1)
|
|
63
|
+
offsets = torch.tensor([i * num_points for i in range(num_splines)])
|
|
64
|
+
indeces = closest_index.view(-1, 1) + offsets.view(1, -1)
|
|
65
|
+
|
|
66
|
+
values = out[indeces]
|
|
67
|
+
values = values[:, ::2] # <-- This still needs some changes
|
|
68
|
+
# values = values[:,1:]
|
|
69
|
+
qsum = torch.sum(values, dim=1)
|
|
70
|
+
|
|
71
|
+
return weights[0] * silu(inputs_batch) + norm * weights[1] * qsum
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def FQuKANNeuron(
|
|
75
|
+
inputs_batch,
|
|
76
|
+
params,
|
|
77
|
+
weights,
|
|
78
|
+
num_splines=4,
|
|
79
|
+
min_val=0,
|
|
80
|
+
max_val=1,
|
|
81
|
+
num_points=64,
|
|
82
|
+
strat="Mott",
|
|
83
|
+
state=None,
|
|
84
|
+
norm=None,
|
|
85
|
+
):
|
|
86
|
+
# Encoding strategy for the splines
|
|
87
|
+
if strat == "Mott":
|
|
88
|
+
state, norm = encode_bsplinesSILU(
|
|
89
|
+
n=num_splines, num_points=num_points, min_v=min_val, max_v=max_val
|
|
90
|
+
)
|
|
91
|
+
if strat == "QCBM":
|
|
92
|
+
state, norm = state, norm
|
|
93
|
+
|
|
94
|
+
state.to(dtype=torch.complex64)
|
|
95
|
+
|
|
96
|
+
# Adjust interval with the range of the input data
|
|
97
|
+
if torch.min(inputs_batch) < min_val:
|
|
98
|
+
min_val = torch.min(inputs_batch)
|
|
99
|
+
if torch.max(inputs_batch) > max_val:
|
|
100
|
+
max_val = torch.max(inputs_batch)
|
|
101
|
+
|
|
102
|
+
# min_val,max_val = torch.min(inputs_batch),torch.max(inputs_batch)
|
|
103
|
+
intval = torch.linspace(min_val, max_val, steps=num_points)
|
|
104
|
+
|
|
105
|
+
num_qubits = int(np.log2(num_splines * num_points))
|
|
106
|
+
_circuit = get_circuit(num_qubits)
|
|
107
|
+
out = _circuit(state, params)
|
|
108
|
+
|
|
109
|
+
closest_index = torch.argmin(torch.abs(intval.view(1, -1) - inputs_batch.view(-1, 1)), dim=1)
|
|
110
|
+
offsets = torch.tensor([i * num_points for i in range(num_splines)])
|
|
111
|
+
indeces = closest_index.view(-1, 1) + offsets.view(1, -1)
|
|
112
|
+
|
|
113
|
+
values = out[indeces]
|
|
114
|
+
values = values[:, ::2] # <-- This still needs some changes
|
|
115
|
+
# values = values[:,1:]
|
|
116
|
+
qsum = torch.sum(values, dim=1)
|
|
117
|
+
|
|
118
|
+
return norm * weights * qsum
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import pennylane as qml
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn as nn
|
|
4
|
+
from .devices import DEFAULT_TORCH_DEVICE, get_qml_device
|
|
5
|
+
|
|
6
|
+
class MMD(nn.Module):
|
|
7
|
+
def __init__(self, scales=None, n_qubits=8):
|
|
8
|
+
super().__init__()
|
|
9
|
+
if scales is None:
|
|
10
|
+
scales = torch.tensor([0.25, 0.5, 1.0])
|
|
11
|
+
space = torch.arange(2**n_qubits, dtype=torch.float64)
|
|
12
|
+
gammas = 1.0 / (2.0 * (scales**2)) # RBF kernel widths
|
|
13
|
+
sq_dists = torch.cdist(space.unsqueeze(1), space.unsqueeze(1), p=2).pow(2) # shape [n, n]
|
|
14
|
+
kernel_matrix = sum(torch.exp(-gamma * sq_dists) for gamma in gammas) / len(scales)
|
|
15
|
+
self.register_buffer("K", kernel_matrix.to(dtype=torch.complex128))
|
|
16
|
+
|
|
17
|
+
def k_expval(self, px, py):
|
|
18
|
+
return px @ self.K @ py
|
|
19
|
+
|
|
20
|
+
def forward(self, px, py):
|
|
21
|
+
px = px / px.sum()
|
|
22
|
+
py = py / py.sum()
|
|
23
|
+
return self.k_expval(px - py, px - py).to(dtype=torch.float64)
|
|
24
|
+
|
|
25
|
+
def get_circuit(n_qubits):
|
|
26
|
+
dev = get_qml_device(n_qubits)
|
|
27
|
+
|
|
28
|
+
@qml.qnode(device=dev, interface="torch")
|
|
29
|
+
def circuit(weights):
|
|
30
|
+
for layer in range(weights.shape[0]):
|
|
31
|
+
for qubit in range(weights.shape[1]):
|
|
32
|
+
qml.RY(phi=weights[layer, qubit], wires=qubit)
|
|
33
|
+
for qubit in range(weights.shape[1] - 1):
|
|
34
|
+
qml.CNOT(wires=[qubit, qubit + 1])
|
|
35
|
+
qml.CNOT(wires=[weights.shape[1] - 1, 0])
|
|
36
|
+
return qml.probs()
|
|
37
|
+
|
|
38
|
+
return circuit
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class QCBM(nn.Module):
|
|
42
|
+
def __init__(self, n_layers=25, n_qubits=8):
|
|
43
|
+
super().__init__()
|
|
44
|
+
self.n_layers = n_layers
|
|
45
|
+
self.n_qubits = n_qubits
|
|
46
|
+
self.weights = nn.Parameter(torch.rand(self.n_layers, self.n_qubits))
|
|
47
|
+
self.circuit = get_circuit(n_qubits)
|
|
48
|
+
|
|
49
|
+
def forward(self):
|
|
50
|
+
return self.circuit(self.weights)
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn as nn
|
|
4
|
+
from torch.func import vmap
|
|
5
|
+
|
|
6
|
+
from .neuron import FQuKANNeuron, QuKANNeuron
|
|
7
|
+
from .splines import trained_splines
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class QuKAN(nn.Module):
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
num_hlayers=1,
|
|
14
|
+
feature_dim=2,
|
|
15
|
+
circ_layer=3,
|
|
16
|
+
num_rot=4,
|
|
17
|
+
num_splines=4,
|
|
18
|
+
num_points=64,
|
|
19
|
+
strat="Mott",
|
|
20
|
+
min_val=0,
|
|
21
|
+
max_val=1,
|
|
22
|
+
):
|
|
23
|
+
super().__init__()
|
|
24
|
+
self.feature_dim = feature_dim
|
|
25
|
+
self.num_hlayers = num_hlayers
|
|
26
|
+
self.circ_layer = circ_layer
|
|
27
|
+
self.num_splines = num_splines
|
|
28
|
+
self.num_rot = int(np.log2(self.num_splines))
|
|
29
|
+
self.num_points = num_points
|
|
30
|
+
self.strat = strat
|
|
31
|
+
self.state = None
|
|
32
|
+
self.norm = None
|
|
33
|
+
if self.strat == 'QCBM':
|
|
34
|
+
print('Pretraining QCBM ...')
|
|
35
|
+
self.state, self.norm = trained_splines(
|
|
36
|
+
n=self.num_splines,
|
|
37
|
+
min_v=min_val,
|
|
38
|
+
max_v=max_val,
|
|
39
|
+
num_points=self.num_points,
|
|
40
|
+
method="QuKAN",
|
|
41
|
+
)
|
|
42
|
+
if self.strat == 'Mott':
|
|
43
|
+
print('Using Mottonen encoding.')
|
|
44
|
+
|
|
45
|
+
# Per-hidden-layer, per-feature params
|
|
46
|
+
# [L, F, circ_layer, num_rot] and [L, F, 2]
|
|
47
|
+
self.h_params = nn.Parameter(torch.rand(num_hlayers, feature_dim, circ_layer, num_rot))
|
|
48
|
+
self.h_weights = nn.Parameter(torch.rand(num_hlayers, feature_dim, 2) * 0.1)
|
|
49
|
+
|
|
50
|
+
# Output head params (global, not tied to a particular feature)
|
|
51
|
+
self.out_params = nn.Parameter(torch.rand(circ_layer, num_rot))
|
|
52
|
+
self.out_weights = nn.Parameter(torch.rand(2) * 0.1)
|
|
53
|
+
|
|
54
|
+
# If you really want matmul semantics, keep a ones matrix as a buffer
|
|
55
|
+
# (not recommended for speed)
|
|
56
|
+
self.register_buffer("ones_ff", torch.ones(feature_dim, feature_dim))
|
|
57
|
+
|
|
58
|
+
def apply_qukan_per_feature(self, H, params_l, weights_l):
|
|
59
|
+
"""
|
|
60
|
+
H: [B, F]; params_l: [F, circ_layer, num_rot]; weights_l: [F, 2]
|
|
61
|
+
returns: [B, F]
|
|
62
|
+
"""
|
|
63
|
+
# Try vectorizing across feature dimension (PyTorch 2.x)
|
|
64
|
+
try:
|
|
65
|
+
|
|
66
|
+
def neuron(x_1d, p, w):
|
|
67
|
+
output = QuKANNeuron(
|
|
68
|
+
x_1d,
|
|
69
|
+
p,
|
|
70
|
+
w,
|
|
71
|
+
num_splines=self.num_splines,
|
|
72
|
+
num_points=self.num_points,
|
|
73
|
+
strat=self.strat,
|
|
74
|
+
state=self.state,
|
|
75
|
+
norm=self.norm,
|
|
76
|
+
)
|
|
77
|
+
return output# -> [B]
|
|
78
|
+
# vmap over features: in_dims (H along dim=1, params/weights along dim=0)
|
|
79
|
+
#ic(neuron)
|
|
80
|
+
feats = vmap(neuron, in_dims=(1, 0, 0))(H, params_l, weights_l) # [F, B]
|
|
81
|
+
feats_t = feats.transpose(0, 1)
|
|
82
|
+
#ic(feats_t)
|
|
83
|
+
return feats_t# [B, F]
|
|
84
|
+
except Exception:
|
|
85
|
+
# Fallback: Python loop
|
|
86
|
+
return torch.stack(
|
|
87
|
+
[
|
|
88
|
+
QuKANNeuron(
|
|
89
|
+
H[:, i],
|
|
90
|
+
params_l[i],
|
|
91
|
+
weights_l[i],
|
|
92
|
+
num_splines=self.num_splines,
|
|
93
|
+
num_points=self.num_points,
|
|
94
|
+
strat=self.strat,
|
|
95
|
+
state=self.state,
|
|
96
|
+
norm=self.norm,
|
|
97
|
+
)
|
|
98
|
+
for i in range(self.feature_dim)
|
|
99
|
+
],
|
|
100
|
+
dim=1
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def forward(self, x):
|
|
104
|
+
"""
|
|
105
|
+
x: [B, F]
|
|
106
|
+
returns: logits [B, 1]
|
|
107
|
+
"""
|
|
108
|
+
B, F = x.shape
|
|
109
|
+
assert self.feature_dim == F, "Input feature_dim mismatch."
|
|
110
|
+
H = x
|
|
111
|
+
|
|
112
|
+
for layer in range(self.num_hlayers):
|
|
113
|
+
# Featurewise nonlinearity in parallel
|
|
114
|
+
H = self.apply_qukan_per_feature(H, self.h_params[layer], self.h_weights[layer])
|
|
115
|
+
#ic(H)
|
|
116
|
+
#ic(H.shape)
|
|
117
|
+
# Fixed sum coupling (fast): replicate the sum across all features
|
|
118
|
+
s = H.sum(dim=1, keepdim=True) # [B, 1]
|
|
119
|
+
H = s.expand(-1, self.feature_dim) # [B, F] view, no copy
|
|
120
|
+
#ic(H)
|
|
121
|
+
#ic(H.shape)
|
|
122
|
+
# If you insist on matmul (slower):
|
|
123
|
+
# H = H @ self.ones_ff # O(B·F²)
|
|
124
|
+
|
|
125
|
+
# Aggregate to scalar before output neuron
|
|
126
|
+
out_scalar = H.sum(dim=1) # use mean for scale stability (sum also works) TAKE A LOOK
|
|
127
|
+
logit = QuKANNeuron(
|
|
128
|
+
out_scalar,
|
|
129
|
+
self.out_params,
|
|
130
|
+
self.out_weights,
|
|
131
|
+
num_splines=self.num_splines,
|
|
132
|
+
num_points=self.num_points,
|
|
133
|
+
strat=self.strat,
|
|
134
|
+
state=self.state,
|
|
135
|
+
norm=self.norm,
|
|
136
|
+
)
|
|
137
|
+
return logit.unsqueeze(1) # [B,1]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class FQuKAN(nn.Module):
|
|
142
|
+
def __init__(
|
|
143
|
+
self,
|
|
144
|
+
num_hlayers=1,
|
|
145
|
+
feature_dim=2,
|
|
146
|
+
circ_layer=3,
|
|
147
|
+
num_rot=4,
|
|
148
|
+
num_splines=4,
|
|
149
|
+
num_points=64,
|
|
150
|
+
strat="Mott",
|
|
151
|
+
min_val=0,
|
|
152
|
+
max_val=1,
|
|
153
|
+
):
|
|
154
|
+
super().__init__()
|
|
155
|
+
self.feature_dim = feature_dim
|
|
156
|
+
self.num_hlayers = num_hlayers
|
|
157
|
+
self.circ_layer = circ_layer
|
|
158
|
+
self.num_rot = num_rot
|
|
159
|
+
self.num_splines = num_splines
|
|
160
|
+
self.num_points = num_points
|
|
161
|
+
self.strat = strat
|
|
162
|
+
self.state = None
|
|
163
|
+
self.norm = None
|
|
164
|
+
if self.strat == 'QCBM':
|
|
165
|
+
print('Pretraining QCBM ...')
|
|
166
|
+
self.state, self.norm = trained_splines(
|
|
167
|
+
n=self.num_splines,
|
|
168
|
+
min_v=min_val,
|
|
169
|
+
max_v=max_val,
|
|
170
|
+
num_points=self.num_points,
|
|
171
|
+
method="QuKAN",
|
|
172
|
+
)
|
|
173
|
+
if self.strat == 'Mott':
|
|
174
|
+
print('Using Mottonen encoding.')
|
|
175
|
+
|
|
176
|
+
# Per-hidden-layer, per-feature params
|
|
177
|
+
# [L, F, circ_layer, num_rot] and [L, F, 2]
|
|
178
|
+
self.h_params = nn.Parameter(torch.rand(num_hlayers, feature_dim, circ_layer, num_rot))
|
|
179
|
+
self.h_weights = nn.Parameter(torch.rand(num_hlayers, feature_dim, 1) * 0.1)
|
|
180
|
+
|
|
181
|
+
# Output head params (global, not tied to a particular feature)
|
|
182
|
+
self.out_params = nn.Parameter(torch.rand(circ_layer, num_rot))
|
|
183
|
+
self.out_weights = nn.Parameter(torch.rand(1) * 0.1)
|
|
184
|
+
|
|
185
|
+
# If you really want matmul semantics, keep a ones matrix as a buffer
|
|
186
|
+
# (not recommended for speed)
|
|
187
|
+
self.register_buffer("ones_ff", torch.ones(feature_dim, feature_dim))
|
|
188
|
+
|
|
189
|
+
def apply_qukan_per_feature(self, H, params_l, weights_l):
|
|
190
|
+
"""
|
|
191
|
+
H: [B, F]; params_l: [F, circ_layer, num_rot]; weights_l: [F, 2]
|
|
192
|
+
returns: [B, F]
|
|
193
|
+
"""
|
|
194
|
+
# Try vectorizing across feature dimension (PyTorch 2.x)
|
|
195
|
+
try:
|
|
196
|
+
|
|
197
|
+
def neuron(x_1d, p, w):
|
|
198
|
+
output = FQuKANNeuron(
|
|
199
|
+
x_1d,
|
|
200
|
+
p,
|
|
201
|
+
w,
|
|
202
|
+
num_splines=self.num_splines,
|
|
203
|
+
num_points=self.num_points,
|
|
204
|
+
strat=self.strat,
|
|
205
|
+
state=self.state,
|
|
206
|
+
norm=self.norm,
|
|
207
|
+
)
|
|
208
|
+
return output# -> [B]
|
|
209
|
+
# vmap over features: in_dims (H along dim=1, params/weights along dim=0)
|
|
210
|
+
#ic(neuron)
|
|
211
|
+
feats = vmap(neuron, in_dims=(1, 0, 0))(H, params_l, weights_l) # [F, B]
|
|
212
|
+
feats_t = feats.transpose(0, 1)
|
|
213
|
+
#ic(feats_t)
|
|
214
|
+
return feats_t# [B, F]
|
|
215
|
+
except Exception:
|
|
216
|
+
# Fallback: Python loop
|
|
217
|
+
return torch.stack(
|
|
218
|
+
[
|
|
219
|
+
FQuKANNeuron(
|
|
220
|
+
H[:, i],
|
|
221
|
+
params_l[i],
|
|
222
|
+
weights_l[i],
|
|
223
|
+
num_splines=self.num_splines,
|
|
224
|
+
num_points=self.num_points,
|
|
225
|
+
strat=self.strat,
|
|
226
|
+
state=self.state,
|
|
227
|
+
norm=self.norm,
|
|
228
|
+
)
|
|
229
|
+
for i in range(self.feature_dim)
|
|
230
|
+
],
|
|
231
|
+
dim=1
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
def forward(self, x):
|
|
235
|
+
"""
|
|
236
|
+
x: [B, F]
|
|
237
|
+
returns: logits [B, 1]
|
|
238
|
+
"""
|
|
239
|
+
B, F = x.shape
|
|
240
|
+
assert self.feature_dim == F, "Input feature_dim mismatch."
|
|
241
|
+
H = x
|
|
242
|
+
|
|
243
|
+
for layer in range(self.num_hlayers):
|
|
244
|
+
# Featurewise nonlinearity in parallel
|
|
245
|
+
H = self.apply_qukan_per_feature(H, self.h_params[layer], self.h_weights[layer])
|
|
246
|
+
#ic(H)
|
|
247
|
+
#ic(H.shape)
|
|
248
|
+
# Fixed sum coupling (fast): replicate the sum across all features
|
|
249
|
+
s = H.sum(dim=1, keepdim=True) # [B, 1]
|
|
250
|
+
H = s.expand(-1, self.feature_dim) # [B, F] view, no copy
|
|
251
|
+
#ic(H)
|
|
252
|
+
#ic(H.shape)
|
|
253
|
+
# If you insist on matmul (slower):
|
|
254
|
+
# H = H @ self.ones_ff # O(B·F²)
|
|
255
|
+
|
|
256
|
+
# Aggregate to scalar before output neuron
|
|
257
|
+
out_scalar = H.sum(dim=1) # use mean for scale stability (sum also works) TAKE A LOOK
|
|
258
|
+
logit = FQuKANNeuron(
|
|
259
|
+
out_scalar,
|
|
260
|
+
self.out_params,
|
|
261
|
+
self.out_weights,
|
|
262
|
+
num_splines=self.num_splines,
|
|
263
|
+
num_points=self.num_points,
|
|
264
|
+
strat=self.strat,
|
|
265
|
+
state=self.state,
|
|
266
|
+
norm=self.norm,
|
|
267
|
+
)
|
|
268
|
+
return logit.unsqueeze(1) # [B,1]
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class GQuKAN(nn.Module):
|
|
272
|
+
def __init__(self, num_hlayers=1, feature_dim=2, circ_layer=3, num_rot=4, num_splines=4,num_points=64,strat='Mott',min_val=0,max_val=1):
|
|
273
|
+
super().__init__()
|
|
274
|
+
self.feature_dim = feature_dim
|
|
275
|
+
self.num_hlayers = num_hlayers
|
|
276
|
+
self.circ_layer = circ_layer
|
|
277
|
+
self.num_rot = num_rot
|
|
278
|
+
self.num_splines = num_splines
|
|
279
|
+
self.num_points = num_points
|
|
280
|
+
self.strat = strat
|
|
281
|
+
self.state = None
|
|
282
|
+
self.norm = None
|
|
283
|
+
if self.strat == 'QCBM':
|
|
284
|
+
print(f'Pretraining QCBM ...')
|
|
285
|
+
self.state,self.norm = trained_splines(n=self.num_splines,min=min_val,max=max_val,num_points=self.num_points,method='QuKAN')
|
|
286
|
+
if self.strat == 'Mott':
|
|
287
|
+
print(f'Using Mottonen encoding.')
|
|
288
|
+
|
|
289
|
+
# Per-hidden-layer, per-feature params
|
|
290
|
+
# [L, F, circ_layer, num_rot] and [L, F, 2]
|
|
291
|
+
self.h_params = nn.Parameter(torch.rand(num_hlayers, feature_dim, circ_layer, num_rot))
|
|
292
|
+
self.h_weights = nn.Parameter(torch.rand(num_hlayers, feature_dim, 2) * 0.1)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
self.register_buffer("ones_ff", torch.ones(feature_dim, feature_dim))
|
|
296
|
+
|
|
297
|
+
def apply_qukan_per_feature(self, H, params_l, weights_l):
|
|
298
|
+
"""
|
|
299
|
+
H: [B, F]; params_l: [F, circ_layer, num_rot]; weights_l: [F, 2]
|
|
300
|
+
returns: [B, F]
|
|
301
|
+
"""
|
|
302
|
+
# Try vectorizing across feature dimension (PyTorch 2.x)
|
|
303
|
+
try:
|
|
304
|
+
|
|
305
|
+
def neuron(x_1d, p, w):
|
|
306
|
+
output = QuKANNeuron(x_1d, p, w, num_splines=self.num_splines,num_points=self.num_points,strat=self.strat,state=self.state,norm=self.norm)
|
|
307
|
+
return output# -> [B]
|
|
308
|
+
# vmap over features: in_dims (H along dim=1, params/weights along dim=0)
|
|
309
|
+
#ic(neuron)
|
|
310
|
+
feats = vmap(neuron, in_dims=(1, 0, 0))(H, params_l, weights_l) # [F, B]
|
|
311
|
+
feats_t = feats.transpose(0, 1)
|
|
312
|
+
#ic(feats_t)
|
|
313
|
+
return feats_t# [B, F]
|
|
314
|
+
except Exception:
|
|
315
|
+
# Fallback: Python loop
|
|
316
|
+
return torch.stack(
|
|
317
|
+
[QuKANNeuron(H[:, i], params_l[i], weights_l[i], num_splines=self.num_splines,num_points=self.num_points,strat=self.strat,state=self.state,norm=self.norm)
|
|
318
|
+
for i in range(self.feature_dim)],
|
|
319
|
+
dim=1
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
def forward(self, x):
|
|
323
|
+
"""
|
|
324
|
+
x: [B, F]
|
|
325
|
+
returns: logits [B, 1]
|
|
326
|
+
"""
|
|
327
|
+
B, F = x.shape
|
|
328
|
+
assert F == self.feature_dim, "Input feature_dim mismatch."
|
|
329
|
+
H = x
|
|
330
|
+
|
|
331
|
+
for l in range(self.num_hlayers):
|
|
332
|
+
H = self.apply_qukan_per_feature(H, self.h_params[l], self.h_weights[l]) # [B, F]
|
|
333
|
+
s = H.sum(dim=1, keepdim=True) # [B, 1]
|
|
334
|
+
H = s.expand(-1, self.feature_dim) # [B, F] view, no copy
|
|
335
|
+
|
|
336
|
+
out_scalar = H.sum(dim=1)
|
|
337
|
+
return out_scalar.unsqueeze(1) # [B,1]
|
|
338
|
+
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import torch
|
|
3
|
+
import torch.optim as optim
|
|
4
|
+
from torch.nn.functional import silu
|
|
5
|
+
from tqdm import tqdm
|
|
6
|
+
|
|
7
|
+
from .qcbm import MMD, QCBM
|
|
8
|
+
|
|
9
|
+
from .devices import DEFAULT_TORCH_DEVICE
|
|
10
|
+
|
|
11
|
+
def bspline_basis_functions(min_val, max_val, n, num_points, deg):
|
|
12
|
+
x = torch.linspace(min_val, max_val, num_points, device=DEFAULT_TORCH_DEVICE)
|
|
13
|
+
|
|
14
|
+
# Number of knots needed
|
|
15
|
+
num_knots = n + deg + 1
|
|
16
|
+
knot_vector = torch.linspace(min_val, max_val, num_knots, device=DEFAULT_TORCH_DEVICE)
|
|
17
|
+
|
|
18
|
+
# Recursive Cox–de Boor function
|
|
19
|
+
def cox_de_boor(x, i, k, knots):
|
|
20
|
+
if k == 0:
|
|
21
|
+
return ((x >= knots[i]) & (x < knots[i + 1])).float()
|
|
22
|
+
else:
|
|
23
|
+
denom1 = knots[i + k] - knots[i]
|
|
24
|
+
denom2 = knots[i + k + 1] - knots[i + 1]
|
|
25
|
+
|
|
26
|
+
term1 = 0.0
|
|
27
|
+
if denom1 != 0:
|
|
28
|
+
term1 = (x - knots[i]) / denom1 * cox_de_boor(x, i, k - 1, knots)
|
|
29
|
+
|
|
30
|
+
term2 = 0.0
|
|
31
|
+
if denom2 != 0:
|
|
32
|
+
term2 = (knots[i + k + 1] - x) / denom2 * cox_de_boor(x, i + 1, k - 1, knots)
|
|
33
|
+
|
|
34
|
+
return term1 + term2
|
|
35
|
+
|
|
36
|
+
# Stack basis functions
|
|
37
|
+
basis = torch.stack([cox_de_boor(x, i, deg, knot_vector) for i in range(n)], dim=0)
|
|
38
|
+
return x, basis
|
|
39
|
+
|
|
40
|
+
def encode_bsplines(n, deg=3, min_v=0, max_v=1, num_points=64):
|
|
41
|
+
x, basis = bspline_basis_functions(
|
|
42
|
+
min_val=min_v, max_val=max_v, n=n, num_points=num_points, deg=deg
|
|
43
|
+
)
|
|
44
|
+
res = torch.zeros(n*num_points,dtype=torch.complex64)
|
|
45
|
+
for i in range(n):
|
|
46
|
+
res += torch.kron(torch.eye(n,dtype=torch.complex64)[:,i],basis[i])
|
|
47
|
+
norm = torch.norm(res)
|
|
48
|
+
res /= norm
|
|
49
|
+
return res,norm
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def trained_splines(
|
|
54
|
+
epochs=100,
|
|
55
|
+
n_layers=20,
|
|
56
|
+
n=4,
|
|
57
|
+
deg=3,
|
|
58
|
+
min_v=0,
|
|
59
|
+
max_v=1,
|
|
60
|
+
num_points=64,
|
|
61
|
+
method="QuKAN",
|
|
62
|
+
):
|
|
63
|
+
n_qubits = int(np.log2(n)) + int(np.log2(num_points))
|
|
64
|
+
model = QCBM(n_qubits=n_qubits)
|
|
65
|
+
criterion = MMD(n_qubits=n_qubits)
|
|
66
|
+
optimizer = optim.Adam(model.parameters(), lr=0.1)
|
|
67
|
+
|
|
68
|
+
if method == "QuKAN":
|
|
69
|
+
data, norm = encode_bsplines(
|
|
70
|
+
n=n, deg=deg, min_v=min_v, max_v=max_v, num_points=num_points
|
|
71
|
+
)
|
|
72
|
+
if method == "FQuKAN":
|
|
73
|
+
data, norm = encode_bsplinesSILU(
|
|
74
|
+
n=n, deg=deg, min_v=min_v, max_v=max_v, num_points=num_points
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
for _ in tqdm(range(epochs)):
|
|
78
|
+
optimizer.zero_grad()
|
|
79
|
+
output = model()
|
|
80
|
+
loss = criterion(output,data)
|
|
81
|
+
loss.backward()
|
|
82
|
+
optimizer.step()
|
|
83
|
+
|
|
84
|
+
output = model().detach()
|
|
85
|
+
output = 1/torch.norm(output) * output
|
|
86
|
+
return output,norm
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def encode_bsplinesSILU(n, deg=3, min_v=0, max_v=1, num_points=64):
|
|
90
|
+
x, basis = bspline_basis_functions(
|
|
91
|
+
min_val=min_v, max_val=max_v, n=n, num_points=num_points, deg=deg
|
|
92
|
+
)
|
|
93
|
+
Si = silu(x)
|
|
94
|
+
res = torch.zeros(n * num_points, dtype=torch.complex64)
|
|
95
|
+
for i in range(n - 1):
|
|
96
|
+
res += torch.kron(torch.eye(n, dtype=torch.complex64)[:, i], basis[i])
|
|
97
|
+
res += torch.kron(torch.eye(n, dtype=torch.complex64)[:, -1], Si)
|
|
98
|
+
norm = torch.norm(res)
|
|
99
|
+
res /= norm
|
|
100
|
+
return res, norm
|
|
101
|
+
|