sqmm-cello-reproduction / code /baselines.py
Fred-Rcky's picture
repro: six baselines at exact param counts
e8fcb5c verified
Raw History Blame Contribute Delete
18.5 kB
"""Self-contained baseline INR models for the SQMM comparison.
Each factory returns (model, lr). Classes are copied verbatim from the
reference repos (paths in comments); only imports are adapted and the
qiskit noise import is guarded (qiskit is not installed here, and noise
is only used when use_noise != 0, which no baseline uses).
Param-count targets (cello: coord_dim=1, out_features=1):
qiren 649, siren 673, finer 691, iga 673, msa_inr 673, cafe_enc 703.
"""
from __future__ import annotations
import math
import numpy as np
import torch
import torch.nn as nn
try:
import qiskit.providers.aer.noise as noise # noqa: F401 (only used when use_noise != 0)
except ImportError:
noise = None
try:
import pennylane as qml
except ImportError: # qiren is unavailable without pennylane
qml = None
# =====================================================================================
# SIREN (verbatim from /work/QIREN/qinr/modules.py)
# =====================================================================================
class SineLayer(nn.Module):
def __init__(self, in_features, out_features, bias=True, is_first=False, omega_0=30, idx=0):
super().__init__()
self.idx = idx
self.omega_0 = omega_0
self.is_first = is_first
self.in_features = in_features
self.linear = nn.Linear(in_features, out_features, bias=bias)
self.init_weights()
def init_weights(self):
with torch.no_grad():
if self.is_first:
self.linear.weight.uniform_(-1 / self.in_features, 1 / self.in_features)
else:
self.linear.weight.uniform_(-np.sqrt(6 / self.in_features) / self.omega_0,
np.sqrt(6 / self.in_features) / self.omega_0)
def forward(self, input):
out = self.omega_0 * self.linear(input)
return torch.sin(out)
def forward_with_intermediate(self, input):
# For visualization of activation distributions
intermediate = self.omega_0 * self.linear(input)
return torch.sin(intermediate), intermediate
class Siren(nn.Module):
def __init__(self, in_features, hidden_features, hidden_layers, out_features, outermost_linear=True,
first_omega_0=30, hidden_omega_0=30):
super().__init__()
self.net = []
self.net.append(SineLayer(in_features, hidden_features, is_first=True, omega_0=first_omega_0, idx=1))
for i in range(hidden_layers):
self.net.append(
SineLayer(hidden_features, hidden_features, is_first=False, omega_0=hidden_omega_0, idx=i + 2))
if outermost_linear:
final_linear = nn.Linear(hidden_features, out_features)
with torch.no_grad():
final_linear.weight.uniform_(-np.sqrt(6 / hidden_features) / hidden_omega_0,
np.sqrt(6 / hidden_features) / hidden_omega_0)
self.net.append(final_linear)
else:
self.net.append(SineLayer(hidden_features, out_features, is_first=False, omega_0=hidden_omega_0))
self.net = nn.Sequential(*self.net)
def forward(self, coords):
output = self.net(coords)
return output, coords
# =====================================================================================
# QIREN (verbatim from /work/QIREN/qinr/modules.py; qiskit import guarded above)
# =====================================================================================
class QuantumLayer(nn.Module):
def __init__(self, in_features, spectrum_layer, use_noise):
super().__init__()
self.in_features = in_features
self.n_layer = spectrum_layer
self.use_noise = use_noise
def _circuit(inputs, weights1, weights2):
for i in range(self.n_layer):
qml.StronglyEntanglingLayers(weights1[i], wires=range(self.in_features), imprimitive=qml.ops.CZ)
for j in range(self.in_features):
qml.RZ(inputs[:, j], wires=j)
qml.StronglyEntanglingLayers(weights2, wires=range(self.in_features), imprimitive=qml.ops.CZ)
if self.use_noise != 0:
for i in range(self.in_features):
rand_angle = np.pi + self.use_noise * np.random.rand()
qml.RX(rand_angle, wires=i)
res = []
for i in range(self.in_features):
res.append(qml.expval(qml.PauliZ(i)))
return res
torch_device = qml.device('default.qubit', wires=in_features)
weight_shape = {"weights1": (self.n_layer, 2, in_features, 3),
"weights2": (2, in_features, 3)}
self.qnode = qml.QNode(_circuit, torch_device, diff_method="backprop", interface="torch")
self.qnn = qml.qnn.TorchLayer(self.qnode, weight_shape)
def forward(self, x):
orgin_shape = list(x.shape[0:-1]) + [-1]
if len(orgin_shape) > 2:
x = x.reshape((-1, self.in_features))
out = self.qnn(x)
return out.reshape(orgin_shape)
class HybridLayer(nn.Module):
def __init__(self, in_features, out_features, spectrum_layer, use_noise, bias=True, idx=0):
super().__init__()
self.idx = idx
self.clayer = nn.Linear(in_features, out_features, bias=bias)
self.norm = nn.BatchNorm1d(out_features)
self.qlayer = QuantumLayer(out_features, spectrum_layer, use_noise)
def forward(self, x):
x1 = self.clayer(x)
x1 = self.norm(x1.permute(0, 2, 1)).permute(0, 2, 1)
out = self.qlayer(x1)
return out
class Hybridren(nn.Module):
def __init__(self, in_features, hidden_features, hidden_layers, out_features, spectrum_layer, use_noise,
outermost_linear=True):
super().__init__()
self.net = []
self.net.append(HybridLayer(in_features, hidden_features, spectrum_layer, use_noise, idx=1))
for i in range(hidden_layers):
self.net.append(HybridLayer(hidden_features, hidden_features, spectrum_layer, use_noise, idx=i + 2))
if outermost_linear:
final_linear = nn.Linear(hidden_features, out_features)
else:
final_linear = HybridLayer(hidden_features, out_features, spectrum_layer, use_noise)
self.net.append(final_linear)
self.net = nn.Sequential(*self.net)
def forward(self, coords):
coords = coords.clone().detach().requires_grad_(True)
output = self.net(coords)
return output, coords
# =====================================================================================
# FINER (verbatim from /work/FINER/models.py)
# =====================================================================================
class FinerLayer(nn.Module):
def __init__(self, in_features, out_features, bias=True, is_first=False, omega_0=30,
first_bias_scale=None, scale_req_grad=False):
super().__init__()
self.omega_0 = omega_0
self.is_first = is_first
self.in_features = in_features
self.linear = nn.Linear(in_features, out_features, bias=bias)
self.init_weights()
self.scale_req_grad = scale_req_grad
self.first_bias_scale = first_bias_scale
if self.first_bias_scale != None:
self.init_first_bias()
def init_weights(self):
with torch.no_grad():
if self.is_first:
self.linear.weight.uniform_(-1 / self.in_features,
1 / self.in_features)
else:
self.linear.weight.uniform_(-np.sqrt(6 / self.in_features) / self.omega_0,
np.sqrt(6 / self.in_features) / self.omega_0)
def init_first_bias(self):
with torch.no_grad():
if self.is_first:
self.linear.bias.uniform_(-self.first_bias_scale, self.first_bias_scale)
def generate_scale(self, x):
if self.scale_req_grad:
scale = torch.abs(x) + 1
else:
with torch.no_grad():
scale = torch.abs(x) + 1
return scale
def forward(self, input):
x = self.linear(input)
scale = self.generate_scale(x)
out = torch.sin(self.omega_0 * scale * x)
return out
class Finer(nn.Module):
def __init__(self, in_features, hidden_features, hidden_layers, out_features, first_omega_0=30,
hidden_omega_0=30.0, first_bias_scale=None, scale_req_grad=False):
super().__init__()
self.net = []
self.net.append(FinerLayer(in_features, hidden_features, is_first=True, omega_0=first_omega_0,
first_bias_scale=first_bias_scale, scale_req_grad=scale_req_grad))
for i in range(hidden_layers):
self.net.append(FinerLayer(hidden_features, hidden_features, omega_0=hidden_omega_0,
scale_req_grad=scale_req_grad))
final_linear = nn.Linear(hidden_features, out_features)
with torch.no_grad():
final_linear.weight.uniform_(-np.sqrt(6 / hidden_features) / hidden_omega_0,
np.sqrt(6 / hidden_features) / hidden_omega_0)
self.net.append(final_linear)
self.net = nn.Sequential(*self.net)
def forward(self, coords):
output = self.net(coords)
return output
# =====================================================================================
# MSA-INR (verbatim from /work/MSA-INR/models/msa.py)
# =====================================================================================
class SineActivation(nn.Module):
def __init__(self, s_min, s_max):
super().__init__()
self.s_min = s_min
self.s_max = s_max
def forward(self, x):
size = x.size(-1)
device = x.device
freqs = torch.logspace(self.s_min, self.s_max, steps=size, device=device)
amps = 1.0 / freqs
return amps.view(*([1] * (x.dim() - 1)), size) * torch.sin(freqs.view(*([1] * (x.dim() - 1)), size) * x)
class MSANet(nn.Module):
def __init__(self,
in_features=3,
hidden_features=256,
hidden_layers=2,
out_features=1,
s_min=None,
s_max=None
):
super().__init__()
if s_min is None:
s_min = [1.0] * hidden_layers
if s_max is None:
s_max = [5.0] * hidden_layers
assert len(s_min) == hidden_layers, "s_min must match hidden_layers"
assert len(s_max) == hidden_layers, "s_max must match hidden_layers"
layers = []
layers.append(nn.Linear(in_features, hidden_features))
layers.append(SineActivation(s_min[0], s_max[0]))
for i in range(1, hidden_layers - 1):
layers.append(nn.Linear(hidden_features, hidden_features))
layers.append(SineActivation(s_min[i], s_max[i]))
layers.append(nn.Linear(hidden_features, hidden_features))
layers.append(SineActivation(s_min[hidden_layers - 1], s_max[hidden_layers - 1]))
layers.append(nn.Linear(hidden_features, out_features))
self.network = nn.Sequential(*layers)
def forward(self, x):
return self.network(x)
# =====================================================================================
# CAFE (verbatim encoders / blocks from /work/CAFE/model.py)
# =====================================================================================
class ChebyshevEncoder(nn.Module):
def __init__(self, in_features: int = 2, order: int = 30):
super().__init__()
self.in_features = in_features
self.order = order
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, N, D = x.shape
assert D == self.in_features
out = []
for d in range(D):
xd = x[..., d].unsqueeze(-1) # [B, N, 1]
T = [torch.ones_like(xd), xd] # T0, T1
for _ in range(2, self.order):
Tn = 2 * xd * T[-1] - T[-2] # Chebyshev recurrence formula
T.append(Tn)
T_all = torch.cat(T[:self.order], dim=-1)
out.append(T_all)
return torch.cat(out, dim=-1) # [B, N, D * order]
class RandomFourierEncoder(nn.Module):
def __init__(self, in_features: int = 2, mapping_size: int = 88, scale: float = 30.0):
super().__init__()
self.B = nn.Parameter(torch.randn(mapping_size, in_features) * scale, requires_grad=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x_proj = torch.matmul(x, self.B.t()) # [B, N, mapping_size]
sin_feat = torch.sin(2 * np.pi * x_proj)
cos_feat = torch.cos(2 * np.pi * x_proj)
return torch.cat([sin_feat, cos_feat], dim=-1) # [B, N, 2 * mapping_size]
class CAFEBlock(nn.Module):
def __init__(self, in_features: int, hidden_features: int, num_branches: int = 3):
super().__init__()
self.num_branches = num_branches
self.branches = nn.ModuleList([
nn.Linear(in_features, hidden_features, bias=True)
for _ in range(num_branches)
])
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = self.branches[0](x)
for i in range(1, self.num_branches):
out = out * self.branches[i](x)
return out
class BackboneMLP(nn.Module):
def __init__(self, hidden_features: int, hidden_layers: int = 1, activation: str = "relu"):
super().__init__()
act_mapping = {
"relu": nn.ReLU,
"silu": nn.SiLU
}
act_name = activation.lower()
if act_name not in act_mapping:
raise ValueError(f"Unsupported activation: {activation}. Choose from {list(act_mapping.keys())}")
act_class = act_mapping[act_name]
layers = []
for _ in range(hidden_layers):
layers.append(nn.Linear(hidden_features, hidden_features, bias=True))
layers.append(act_class(inplace=True))
self.net = nn.Sequential(*layers) if hidden_layers > 0 else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
class CAFE_Net(nn.Module):
def __init__(self,
in_features: int = 2,
out_features: int = 3,
rff_mapping_size: int = 88,
rff_scale: float = 30.0,
cheb_order: int = 30,
hidden_features: int = 0,
num_branches: int = 3,
hidden_layers: int = 1):
super().__init__()
self.encoder_rff = RandomFourierEncoder(in_features, rff_mapping_size, rff_scale)
self.encoder_cheb = ChebyshevEncoder(in_features, cheb_order)
encoded_dim = (rff_mapping_size * 2) + (cheb_order * in_features)
if hidden_features == 0:
hidden_features = encoded_dim
self.mult_block = CAFEBlock(encoded_dim, hidden_features, num_branches)
self.backbone = BackboneMLP(hidden_features, hidden_layers)
self.out_linear = nn.Linear(hidden_features, out_features, bias=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x_rff = self.encoder_rff(x)
x_cheb = self.encoder_cheb(x)
x_encoded = torch.cat([x_rff, x_cheb], dim=-1)
feat = self.mult_block(x_encoded)
feat = self.backbone(feat)
out = self.out_linear(feat)
return out
# =====================================================================================
# Factories, param counts
# =====================================================================================
TARGET_PARAMS = {"qiren": 649, "siren": 673, "finer": 691, "iga": 673,
"msa_inr": 673, "cafe_enc": 703}
BASELINE_LRS = {"qiren": 0.03, "siren": 1e-3, "finer": 1e-3, "iga": 1e-3,
"msa_inr": 3e-2, "cafe_enc": 3e-2}
def baseline_forward(model, coords):
"""Uniform forward: unwrap the (output, coords) tuple some reference models return."""
out = model(coords)
if isinstance(out, tuple):
out = out[0]
return out
def parameter_counts(model) -> dict:
"""Same fields as SQMM.parameter_counts(); trainable = requires_grad params."""
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
quantum = sum(p.numel() for name, p in model.named_parameters()
if p.requires_grad and ("qnn" in name or "qlayer" in name))
return {"trainable_params": trainable, "quantum_params": quantum,
"classical_params": trainable - quantum}
def build_baseline(name: str, *, coord_dim: int, out_features: int):
"""Factory: name -> (model, lr). Prints and asserts the trainable param count."""
if name == "qiren":
model = Hybridren(in_features=coord_dim, hidden_features=8, hidden_layers=2,
out_features=out_features, spectrum_layer=2, use_noise=0)
elif name == "siren":
model = Siren(coord_dim, 14, 3, out_features, first_omega_0=30, hidden_omega_0=30)
elif name == "iga":
model = Siren(coord_dim, 14, 3, out_features, first_omega_0=30, hidden_omega_0=30)
elif name == "msa_inr":
model = MSANet(in_features=coord_dim, hidden_features=24, hidden_layers=1,
out_features=out_features, s_min=[1.0], s_max=[5.0])
elif name == "cafe_enc":
model = CAFE_Net(in_features=coord_dim, out_features=out_features,
rff_mapping_size=5, rff_scale=30.0, cheb_order=2,
hidden_features=13, num_branches=3, hidden_layers=1)
elif name == "finer":
model = Finer(coord_dim, 10, 6, out_features, first_omega_0=30, hidden_omega_0=30,
first_bias_scale=None, scale_req_grad=False)
else:
raise ValueError(f"unknown baseline {name!r}")
counts = parameter_counts(model)
target = TARGET_PARAMS.get(name)
if target is not None and (coord_dim, out_features) == (1, 1):
assert counts["trainable_params"] == target, (
f"{name}: trainable params {counts['trainable_params']} != target {target}")
print(f"[baselines] {name}: trainable_params={counts['trainable_params']} "
f"(target {target})", flush=True)
return model, BASELINE_LRS[name]