@property
def satisfied(self):
self._previous_vr = self._vr
return self._vr > self._vr_th
@property
def previously_satisfied(self):
return self._previous_vr > self._vr_th
def update(self, scores):
u = 1.0 / len(scores)
S = scores.sum()
if S == 0:
g = np.array(u)
else:
g = scores / S
new_vr = 1.0 / np.sqrt(1 - ((g - u) ** 2).sum() / (g ** 2).sum())
self._vr = (
self._momentum * self._vr +
(1 - self._momentum) * new_vr
)
Assistant
class ConstantTimeSampler(BaseSampler):
def init(self, dataset, reweighting, model, B=128, K=16,
backward_time=2.0, tau_th=1.2, ratio=0.5, min_a=0.2):
"""
Args:
dataset: The dataset to sample from.
reweighting: Reweighting policy.
model: The model wrapper with score method.
B: Number of samples to score per batch.
K: Number of samples to select via quantum optimizer.
backward_time: Time multiplier for backward pass.
tau_th: Variance reduction threshold.
ratio: Ratio to determine additional samples.
min_a: Minimum number of additional samples.
"""
self.condition = VarianceReductionCondition(tau_th)
self.backward_time = backward_time
self.ratio = ratio
self.min_a = min_a
self.model = model
self.B = B # Subset size to score
self.K = K # Number of samples to select
self.N = len(dataset.train_data) if hasattr(dataset, 'train_data') else _get_dataset_length(dataset, default=1)
print(f"Dataset size (self.N): {self.N}")
self.usage_counts = np.zeros(self.N, dtype=int)
super(ConstantTimeSampler, self).init(dataset, reweighting)
code
def _determine_devide(self, std_scores, batch_size):
# Adjust threshold based on standard deviation
if std_scores > 1.0:
devide = int(batch_size * 0.7)
elif std_scores > 0.5:
devide = int(batch_size * 0.5)
else:
devide = int(batch_size * 0.3)
return devide
def _random_sample(self, batch_size):
# Implement random sampling as a fallback strategy
random_indices = np.random.choice(self.N, size=batch_size, replace=False)
x, y = self.dataset.train_data[random_indices]
w = np.ones((batch_size, 1)) # Assuming weight_size=1 for simplicity
return random_indices, (x, y), w
def sample(self, batch_size):
print(f"Entering sample method")
print(f"Requested batch_size: {batch_size}, self.N: {self.N}")
print(f"Condition satisfied: {self.condition.satisfied}")
# Step 1: Sample B samples uniformly from the dataset
sampled_indices = np.random.choice(self.N, self.B, replace=False)
x_sampled, y_sampled = self.dataset.train_data[sampled_indices]
# Step 2: Compute scores for the sampled B samples
scores_sampled = self.model.score(x_sampled, y_sampled, batch_size=self.B)
scores_sampled = np.nan_to_num(scores_sampled, nan=0.0, posinf=1.0, neginf=0.0)
scores_sampled += 1e-8 # To avoid division by zero
# Step 3: Use quantum optimizer to select top K samples
optimizer = GroverOptimizer(num_value_qubits=4, num_key_qubits=5, num_iterations=3)
result = optimizer.solve(scores_sampled, self.K)
top_k_indices = np.array(list(result.keys()))
print(f"Selected top K indices via quantum optimizer: {top_k_indices}")
print(f"Number of top K samples selected: {len(top_k_indices)}")
if len(top_k_indices) == 0:
print("Warning: Failed to get valid sample indices, falling back to random sampling.")
return self._random_sample(batch_size)
# Handle remaining samples with random sampling if needed
num_selected = len(top_k_indices)
num_other = batch_size - num_selected
if num_other > 0:
remaining_indices = np.setdiff1d(np.arange(self.B), top_k_indices)
if len(remaining_indices) >= num_other:
idxs_other = np.random.choice(remaining_indices, num_other, replace=False)
else:
idxs_other = np.random.choice(remaining_indices, num_other, replace=True)
else:
idxs_other = np.array([], dtype=int)
# Combine high-score and random indices
final_indices = top_k_indices
if num_other > 0:
final_indices = np.concatenate([top_k_indices, idxs_other])
# Retrieve selected samples and their scores
selected_indices = sampled_indices[final_indices]
x_selected, y_selected = self._slice_data(self.dataset.train_data, self.dataset.train_labels, selected_indices)
scores_selected = scores_sampled[final_indices]
# Step 4: Compute weights for unbiasedness
# Q(x) = B/N, selecting K samples from B uniformly via optimizer
# Thus, P(x) = K/N (assuming target distribution is uniform P(x) = 1/N)
# Hence, w(x) = P(x)/Q(x) = (K/N)/(B/N) = K/B
weights = np.ones((len(final_indices), 1)) * (self.K / self.B)
print(f"Computed weights (uniform for selected K samples): {weights.flatten()}")
# Step 5: Update variance reduction condition
self.condition.update(scores_selected)
# Step 6: Send sampling messages
self._send_messages(selected_indices, (x_selected, y_selected), weights, scores_selected)
print(f"Returned batch shapes: x: {x_selected.shape}, y: {y_selected.shape}, w: {weights.shape}")
return (selected_indices, (x_selected, y_selected), weights)
from functools import partial
import sys
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input, Layer, multiply
from tensorflow.keras.models import Model, clone_model
from tensorflow.keras import losses
from blinker import signal
from .layers import GradientNormLayer, LossLayer, MetricLayer
from .reweighting import NoReweightingPolicy # Using NoReweightingPolicy since weights are handled in sampler
from .utils.functional import _tolist, compose
class ModelWrapper(object):
"""ModelWrapper 的目的是包装一个神经网络,并添加一些额外的层,以生成得分、损失和样本权重,以执行重要性采样。"""
code
def _iterate_batches(self, x, y, batch_size):
bs = batch_size
for s in range(0, len(y), bs):
if isinstance(x, (list, tuple)):
xs = [xi[s:s+bs] for xi in x]
else:
xs = x[s:s+bs]
yield xs, y[s:s+bs]
def evaluate(self, x, y, batch_size=128):
result = np.mean(
np.vstack([
self.evaluate_batch(xi, yi)
for xi, yi in self._iterate_batches(x, y, batch_size)
]),
axis=0
)
signal("is.evaluation").send(result)
return result
def score(self, x, y, batch_size=128):
bs = batch_size
result = np.hstack([
self.score_batch(xi, yi).T
for xi, yi in self._iterate_batches(x, y, batch_size)
]).T
signal("is.score").send(result)
return result
def set_lr(self, lr):
"""设置模型的学习率。"""
try:
K.set_value(
self.optimizer.lr,
lr
)
except AttributeError:
try:
K.set_value(
self.model.optimizer.lr,
lr
)
except AttributeError:
raise NotImplementedError()
try:
K.set_value(
self.small.optimizer.lr,
lr
)
except AttributeError:
pass
def evaluate_batch(self, x, y):
raise NotImplementedError()
def score_batch(self, x, y):
raise NotImplementedError()
def train_batch(self, x, y, w):
raise NotImplementedError()
class OracleWrapper(ModelWrapper):
AVG_LOSS = 0
LOSS = 1
WEIGHTED_LOSS = 2
SCORE = 3
METRIC0 = 4
code
FUSED_ACTIVATION_WARNING = ("[WARNING]: 最后一层具有融合激活函数,例如 Dense(..., activation=\"sigmoid\")。\n"
"为了自动提取预激活张量,请使用单独的激活层(参见示例)。\n")
def __init__(self, model, reweighting, score="loss", layer=None):
self.reweighting = reweighting
self.layer = self._gnorm_layer(model, layer)
# Augment the model with reweighting, scoring etc
# Save the new model and the training functions in member variables
self._augment_model(model, score, reweighting)
def _gnorm_layer(self, model, layer):
# If we were given a layer then use it directly
if isinstance(layer, Layer):
return layer
# If we were given a layer index extract the layer
if isinstance(layer, int):
return model.layers[layer]
try:
# Get the last or the previous to last layer depending on whether
# the last has trainable weights
skip_one = not bool(model.layers[-1].trainable_weights)
last_layer = -2 if skip_one else -1
# If the last layer has trainable weights that means that we cannot
# automatically extract the preactivation tensor so we have to warn
# them because they might be missing out or they might not even
# have noticed
if last_layer == -1:
config = model.layers[-1].get_config()
if config.get("activation", "linear") != "linear":
sys.stderr.write(self.FUSED_ACTIVATION_WARNING)
return model.layers[last_layer]
except:
# In case of an error then probably we are not using the gnorm
# importance
return None
def _augment_model(self, model, score, reweighting):
# Extract some info from the model
loss = model.loss
optimizer = model.optimizer.__class__.from_config(model.optimizer.get_config())
output_shape = model.get_output_shape_at(0)[1:]
if isinstance(loss, str) and loss.startswith("sparse"):
output_shape = output_shape[:-1] + (1,)
# Make sure that some stuff look ok
assert not isinstance(loss, list)
# We need to create two more inputs
# 1. the targets
# 2. the predicted scores
y_true = Input(shape=output_shape, name='y_true')
pred_score = Input(shape=(reweighting.weight_size,), name='pred_score')
# Create a loss layer and a score layer
loss_tensor = LossLayer(loss)([y_true, model.get_output_at(0)])
score_tensor = _get_scoring_layer(
score,
y_true,
model.get_output_at(0),
loss,
self.layer,
model
)
# Create the sample weights
weights = reweighting.weight_layer()([score_tensor, pred_score])
# Create the output
weighted_loss = multiply([loss_tensor, weights])
for l in model.losses:
weighted_loss += l
weighted_loss_mean = K.mean(weighted_loss)
# Create the metric layers
metrics = model.metrics or []
metrics = [
MetricLayer(metric)([y_true, model.get_output_at(0)])
for metric in metrics
]
# Create a model for plotting and providing access to things such as
# trainable_weights etc.
new_model = Model(
inputs=_tolist(model.get_input_at(0)) + [y_true, pred_score],
outputs=[weighted_loss_mean]
)
# Build separate on_batch keras functions for scoring and training
updates = optimizer.get_updates(
weighted_loss_mean,
new_model.trainable_weights
)
metrics_updates = []
if hasattr(model, "metrics_updates"):
metrics_updates = model.metrics_updates
learning_phase = []
if weighted_loss_mean._uses_learning_phase:
learning_phase.append(K.learning_phase())
inputs = _tolist(model.get_input_at(0)) + [y_true, pred_score] + learning_phase
outputs = [
weighted_loss_mean,
loss_tensor,
weighted_loss,
score_tensor
] + metrics
train_on_batch = K.function(
inputs=inputs,
outputs=outputs,
updates=updates + model.updates + metrics_updates
)
evaluate_on_batch = K.function(
inputs=inputs,
outputs=outputs,
updates=model.state_updates + metrics_updates
)
self.model = new_model
self.optimizer = optimizer
self.model.optimizer = optimizer
self._train_on_batch = train_on_batch
self._evaluate_on_batch = evaluate_on_batch
def evaluate_batch(self, x, y):
if len(y.shape) == 1:
y = np.expand_dims(y, axis=1)
dummy_weights = np.ones((y.shape[0], self.reweighting.weight_size))
inputs = _tolist(x) + [y, dummy_weights] + [0]
outputs = self._evaluate_on_batch(inputs)
signal("is.evaluate_batch").send(outputs)
return np.hstack([outputs[self.LOSS]] + outputs[self.METRIC0:])
def score_batch(self, x, y):
if len(y.shape) == 1:
y = np.expand_dims(y, axis=1)
dummy_weights = np.ones((y.shape[0], self.reweighting.weight_size))
inputs = _tolist(x) + [y, dummy_weights] + [0]
outputs = self._evaluate_on_batch(inputs)
return outputs[self.SCORE].ravel()
def train_batch(self, x, y, w):
if len(y.shape) == 1:
y = np.expand_dims(y, axis=1)
# train on a single batch
outputs = self._train_on_batch(_tolist(x) + [y, w, 1])
# Add the outputs in a tuple to send to whoever is listening
result = (
outputs[self.WEIGHTED_LOSS],
outputs[self.METRIC0:],
outputs[self.SCORE]
)
signal("is.training").send(result)
return result
def _tolist(x, acceptable_iterables=(list, tuple)):
if not isinstance(x, acceptable_iterables):
x = [x]
return x
关键修改点说明
ConstantTimeSampler 类修改:
参数:
添加参数 B(每批次采样的样本数)和 K(从B个样本中选择的样本数)。
采样流程:
Step 1:从整个数据集中随机均匀采样 B 个样本。
Step 2:计算这 B 个样本的得分。
Step 3:使用量子优化器 GroverOptimizer 从这 B 个样本中选择得分最高的 K 个样本。
Step 4:为选择的 K 个样本分配权重 w(x) = K / B 以确保无偏。
Step 5:更新条件以决定是否在下一个批次应用重要性采样。
无偏权重计算:
每个被选中的样本权重设置为 w(x) = K / B。这基于以下假设:
目标分布 P(x) = 1/N(均匀分布)。
采样分布 Q(x) = B/N(从N个样本中均匀采样B个)。
选择分布 P_select(x | B) = 1/K(从B个样本中均匀选择K个)。
因此,w(x) = P(x) / (Q(x) * P_select(x | B)) = (1/N) / ((B/N) * (1/K)) ) = K/B。
发送采样消息:
将被采样的K个样本及其权重发送出去,供训练过程使用。
2. 修改 model_wrappers.py 文件
确保模型包装器 (OracleWrapper) 能够正确接受和应用样本权重。假设 OracleWrapper 已设计为处理样本权重,我们需要确保其与修改后的采样器兼容。
修改后的 model_wrappers.py
model_wrappers.py
from functools import partial
import sys
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input, Layer, multiply
from tensorflow.keras.models import Model, clone_model
from tensorflow.keras import losses
from blinker import signal
from .layers import GradientNormLayer, LossLayer, MetricLayer
from .reweighting import NoReweightingPolicy # Using NoReweightingPolicy since weights are handled in sampler
from .utils.functional import _tolist, compose
class ModelWrapper(object):
"""ModelWrapper 的目的是包装一个神经网络,并添加一些额外的层,以生成得分、损失和样本权重,以执行重要性采样。"""
code
def _iterate_batches(self, x, y, batch_size):
bs = batch_size
for s in range(0, len(y), bs):
if isinstance(x, (list, tuple)):
xs = [xi[s:s+bs] for xi in x]
else:
xs = x[s:s+bs]
yield xs, y[s:s+bs]
def evaluate(self, x, y, batch_size=128):
result = np.mean(
np.vstack([
self.evaluate_batch(xi, yi)
for xi, yi in self._iterate_batches(x, y, batch_size)
]),
axis=0
)
signal("is.evaluation").send(result)
return result
def score(self, x, y, batch_size=128):
bs = batch_size
result = np.hstack([
self.score_batch(xi, yi).T
for xi, yi in self._iterate_batches(x, y, batch_size)
]).T
signal("is.score").send(result)
return result
def set_lr(self, lr):
"""设置模型的学习率。"""
try:
K.set_value(
self.optimizer.lr,
lr
)
except AttributeError:
try:
K.set_value(
self.model.optimizer.lr,
lr
)
except AttributeError:
raise NotImplementedError()
try:
K.set_value(
self.small.optimizer.lr,
lr
)
except AttributeError:
pass
def evaluate_batch(self, x, y):
raise NotImplementedError()
def score_batch(self, x, y):
raise NotImplementedError()
def train_batch(self, x, y, w):
raise NotImplementedError()
class OracleWrapper(ModelWrapper):
AVG_LOSS = 0
LOSS = 1
WEIGHTED_LOSS = 2
SCORE = 3
METRIC0 = 4
code
FUSED_ACTIVATION_WARNING = ("[WARNING]: 最后一层具有融合激活函数,例如 Dense(..., activation=\"sigmoid\")。\n"
"为了自动提取预激活张量,请使用单独的激活层(参见示例)。\n")
def __init__(self, model, reweighting, score="loss", layer=None):
self.reweighting = reweighting
self.layer = self._gnorm_layer(model, layer)
# Augment the model with reweighting, scoring etc
# Save the new model and the training functions in member variables
self._augment_model(model, score, reweighting)
def _gnorm_layer(self, model, layer):
# If we were given a layer then use it directly
if isinstance(layer, Layer):
return layer
# If we were given a layer index extract the layer
if isinstance(layer, int):
return model.layers[layer]
try:
# Get the last or the previous to last layer depending on whether
# the last has trainable weights
skip_one = not bool(model.layers[-1].trainable_weights)
last_layer = -2 if skip_one else -1
# If the last layer has trainable weights that means that we cannot
# automatically extract the preactivation tensor so we have to warn
# them because they might be missing out or they might not even
# have noticed
if last_layer == -1:
config = model.layers[-1].get_config()
if config.get("activation", "linear") != "linear":
sys.stderr.write(self.FUSED_ACTIVATION_WARNING)
return model.layers[last_layer]
except:
# In case of an error then probably we are not using the gnorm
# importance
return None
def _augment_model(self, model, score, reweighting):
# Extract some info from the model
loss = model.loss
optimizer = model.optimizer.__class__.from_config(model.optimizer.get_config())
output_shape = model.get_output_shape_at(0)[1:]
if isinstance(loss, str) and loss.startswith("sparse"):
output_shape = output_shape[:-1] + (1,)
# Make sure that some stuff look ok
assert not isinstance(loss, list)
# We need to create two more inputs
# 1. the targets
# 2. the predicted scores
y_true = Input(shape=output_shape, name='y_true')
pred_score = Input(shape=(reweighting.weight_size,), name='pred_score')
# Create a loss layer and a score layer
loss_tensor = LossLayer(loss)([y_true, model.get_output_at(0)])
score_tensor = _get_scoring_layer(
score,
y_true,
model.get_output_at(0),
loss,
self.layer,
model
)
# Create the sample weights
weights = reweighting.weight_layer()([score_tensor, pred_score])
# Create the output
weighted_loss = multiply([loss_tensor, weights])
for l in model.losses:
weighted_loss += l
weighted_loss_mean = K.mean(weighted_loss)
# Create the metric layers
metrics = model.metrics or []
metrics = [
MetricLayer(metric)([y_true, model.get_output_at(0)])
for metric in metrics
]
# Create a model for plotting and providing access to things such as
# trainable_weights etc.
new_model = Model(
inputs=_tolist(model.get_input_at(0)) + [y_true, pred_score],
outputs=[weighted_loss_mean]
)
# Build separate on_batch keras functions for scoring and training
updates = optimizer.get_updates(
weighted_loss_mean,
new_model.trainable_weights
)
metrics_updates = []
if hasattr(model, "metrics_updates"):
metrics_updates = model.metrics_updates
learning_phase = []
if weighted_loss_mean._uses_learning_phase:
learning_phase.append(K.learning_phase())
inputs = _tolist(model.get_input_at(0)) + [y_true, pred_score] + learning_phase
outputs = [
weighted_loss_mean,
loss_tensor,
weighted_loss,
score_tensor
] + metrics
train_on_batch = K.function(
inputs=inputs,
outputs=outputs,
updates=updates + model.updates + metrics_updates
)
evaluate_on_batch = K.function(
inputs=inputs,
outputs=outputs,
updates=model.state_updates + metrics_updates
)
self.model = new_model
self.optimizer = optimizer
self.model.optimizer = optimizer
self._train_on_batch = train_on_batch
self._evaluate_on_batch = evaluate_on_batch
def evaluate_batch(self, x, y):
if len(y.shape) == 1:
y = np.expand_dims(y, axis=1)
dummy_weights = np.ones((y.shape[0], self.reweighting.weight_size))
inputs = _tolist(x) + [y, dummy_weights] + [0]
outputs = self._evaluate_on_batch(inputs)
signal("is.evaluate_batch").send(outputs)
return np.hstack([outputs[self.LOSS]] + outputs[self.METRIC0:])
def score_batch(self, x, y):
if len(y.shape) == 1:
y = np.expand_dims(y, axis=1)
dummy_weights = np.ones((y.shape[0], self.reweighting.weight_size))
inputs = _tolist(x) + [y, dummy_weights] + [0]
outputs = self._evaluate_on_batch(inputs)
return outputs[self.SCORE].ravel()
def train_batch(self, x, y, w):
if len(y.shape) == 1:
y = np.expand_dims(y, axis=1)
# train on a single batch
outputs = self._train_on_batch(_tolist(x) + [y, w, 1])
# Add the outputs in a tuple to send to whoever is listening
result = (
outputs[self.WEIGHTED_LOSS],
outputs[self.METRIC0:],
outputs[self.SCORE]
)
signal("is.training").send(result)
return result
from tensorflow.keras.layers import Layer
from tensorflow.keras import backend as K
import numpy as np
class ReweightingPolicy(object):
"""ReweightingPolicy defines how we weigh the samples given their
importance.
code
Each policy should provide
1. A layer implementation for use with Keras models
2. A python implementation for use with the samplers
"""
def weight_layer(self):
"""Return a layer that accepts the scores and the return value of the
sample_weights() method and produces new sample weights."""
raise NotImplementedError()
def sample_weights(self, idxs, scores):
raise NotImplementedError()
@property
def weight_size(self):
raise NotImplementedError()
class NoReweightingPolicy(ReweightingPolicy):
"""Set all sample weights to 1. In our case, weights are already handled in sampler."""
def weight_layer(self):
return ExternalReweighting()
code
def sample_weights(self, idxs, scores):
return np.ones((len(idxs), 1)) # This won't be used as weights are handled in sampler
@property
def weight_size(self):
return 1
class ExternalReweighting(Layer):
"""Use the provided input as sample weights"""
def build(self, input_shape):
super(ExternalReweighting, self).build(input_shape)
import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.decomposition import PCA
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense
from importance_sampling.training import ConstantTimeImportanceTraining # 确保该库已安装
class Tee(object):
def init(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
# 应用变分层
for layer in range(rot_weights.shape[0]):
for qubit in range(n_qubits):
rot_angles = rot_weights[layer, qubit, :] # 形状:(3,)
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# 修改纠缠方式,使用全连接纠缠
for i in range(n_qubits):
for j in range(i + 1, n_qubits):
qml.CRX(np.pi / 2, wires=[i, j])
# 测量期望值
return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]
# 应用变分层
for layer in range(rot_weights.shape[0]):
for qubit in range(n_qubits):
rot_angles = rot_weights[layer, qubit, :] # 形状:(3,)
qml.Rot(rot_angles[0], rot_angles[1], rot_angles[2], wires=qubit)
# 修改纠缠方式,使用全连接纠缠
for i in range(n_qubits):
for j in range(i + 1, n_qubits):
qml.CRX(np.pi / 2, wires=[i, j])
# 测量期望值
return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]