super(ConstantTimeSampler, self).__init__(dataset, reweighting)
def sample(self, batch_size):
print(f"Entering sample method")
print(f"batch_size: {batch_size}, self.N: {self.N}")
print(f"Condition satisfied: {self.condition.satisfied}")
print(f"Requested batch_size: {batch_size}")
if batch_size > self.N:
batch_size = min(batch_size, self.N)
# 初始化 scores_selected
scores_selected = None
# 如果条件满足,进行重要性采样
if self.condition.satisfied:
print("Entering satisfied condition block")
t = (1.0 + self.backward_time) * batch_size
B = 32 # Number of samples to evaluate
idxs = np.random.choice(self.N, B, replace=False)
x, y = self.dataset.train_data[idxs]
# Get sample scores
scores = self.model.score(x, y, batch_size=B)
# Handle possible NaN or Inf values
scores = np.nan_to_num(scores, nan=0.0, posinf=1.0, neginf=0.0)
# Ensure scores are positive
scores = scores + 1e-8 # 防止出现零或负值
# Normalize scores
if np.max(scores) != np.min(scores): # Avoid division by zero
scores = (scores - np.min(scores)) / (np.max(scores) - np.min(scores))
else:
scores = np.full_like(scores, 0.5)
# Scale scores to 0-7 range
scores = scores * 7 + 1e-8 # 加上 1e-8 防止为零
# Clip to ensure range is between 1e-8 and 7
scores = np.clip(scores, 1e-8, 7)
scores = np.ceil(scores)
print("Normalized and adjusted scores:", scores)
# Compute standard deviation of scores
std_scores = np.std(scores)
print("Standard deviation of scores:", std_scores)
# Determine devide value based on std
devide = self._determine_devide(std_scores, batch_size)
print(f"Calculated devide value: {devide}")
num_high = devide
num_other = batch_size - devide
# 如果 devide > 0,使用 GAS_for_N_max.py 选择高分样本
if num_high > 0:
# 此处省略具体实现
idxs_high = np.random.choice(B, num_high, replace=False)
else:
idxs_high = np.array([], dtype=int)
# 对剩余样本,使用均匀随机采样
if num_other > 0:
remaining_indices = np.setdiff1d(np.arange(B), idxs_high)
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)
# 合并索引
idxs2 = np.concatenate([idxs_high, idxs_other])
if len(idxs2) == 0:
print("Warning: Failed to get valid sample indices, falling back to random sampling.")
return self._random_sample(batch_size)
# 获取对应数据
x, y = self._slice_data(x, y, idxs2)
scores_selected = scores[idxs2]
scores_selected = scores_selected + 1e-8 # 防止出现零值
w = self.reweighting.sample_weights(np.arange(len(scores_selected)), scores_selected)
else:
# 如果条件未满足,进行均匀随机采样
idxs = np.random.choice(self.N, batch_size, replace=False)
idxs2 = np.arange(len(idxs))
x, y = self.dataset.train_data[idxs]
scores_selected = np.ones(len(idxs))
w = np.ones((len(idxs), self.reweighting.weight_size))
# 无论条件是否满足,都更新条件状态
self.condition.update(scores_selected)
self._send_messages(idxs[idxs2], (x, y), w, scores_selected)
print(f"Returned batch shapes: x: {x.shape}, y: {y.shape}, w: {w.shape}")
return (idxs[idxs2], (x, y), w)
def _determine_devide(self, std_scores, batch_size):
# 您可以根据标准差调整阈值
# 这里简单地根据标准差大小决定 devide 值
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
class UniformSampler(BaseSampler):
"""UniformSampler is the simplest possible sampler which samples the
dataset uniformly."""
code
def __init__(self, dataset, reweighting):
super(UniformSampler, self).__init__(dataset, reweighting)
# Basically if we don't know the length the indices don't matter so
# sample batch_size 0s.
self.idxs = np.arange(_get_dataset_length(self.dataset, default=1))
def _get_samples_with_scores(self, batch_size):
return (
self.idxs,
None,
None
)
class ModelSampler(BaseSampler):
"""ModelSampler uses a model to score the samples and then performs
importance sampling based on those scores.
code
It can be used to implement several training pipelines where the scoring
model is separately trained or is sampled from the main model or is the
main model."""
def __init__(self, dataset, reweighting, model, large_batch=1024,
forward_batch_size=128):
self.model = model
self.large_batch = large_batch
self.forward_batch_size = forward_batch_size
self.N = _get_dataset_length(dataset, default=1)
super(ModelSampler, self).__init__(dataset, reweighting)
def _get_samples_with_scores(self, batch_size):
assert batch_size < self.large_batch
# Sample a large number of points in random and score them
idxs = np.random.choice(self.N, self.large_batch)
x, y = self.dataset.train_data[idxs]
scores = self.model.score(x, y, batch_size=self.forward_batch_size)
return (
idxs,
scores,
(x, y)
)
class CacheSampler(BaseSampler):
"""CacheSampler uses the recent outputs of the model to determine the
importance of the samples"""
code
def __init__(self, dataset, reweighting, staleness=3, cache_prob=0.5,
smooth=0.2):
# Necessary state for implementing the cache sampler
self._N = N = len(dataset.train_data)
self._idxs = np.arange(N)
self._scores = np.ones((N,))
self._cache = {}
self._score_sum = 0.0
# Configuration
self._staleness = staleness
self._alpha = cache_prob / (1 - cache_prob)
self._smooth = smooth
super(CacheSampler, self).__init__(dataset, reweighting)
def _get_samples_with_scores(self, batch_size):
return (
self._idxs,
self._scores,
None
)
def update(self, idxs, x):
# Add the new scores to the cache
for idx, xi in zip(idxs, x):
self._cache[idx] = (self._smooth + xi, 0)
# Remove the stale values
self._score_sum = 0.0
keys = self._cache.keys()
for k in keys:
item = self._cache[k]
if item[1] > self._staleness:
self._scores[k] = 1
del self._cache[k]
else:
self._cache[k] = (item[0], item[1] + 1)
self._score_sum += item[0]
# Recompute the scores for sampling
N = self._N
S = self._score_sum
a = self._alpha
for k, (s, _) in self._cache.items():
self._scores[k] = 1 + a * N * s / S
The issue you're encountering—where the devide value consistently remains at 11—can be traced back to how the devide is calculated within the ConstantTimeSampler class. Let's delve into the detailed reasoning to understand why this happens.
1. Understanding the devide Calculation
The devide value is determined by the _determine_devide method based on the standard deviation (std_scores) of the sampled scores. Here's the relevant part of the code:
python
def _determine_devide(self, std_scores, batch_size):
# Adjust the threshold based on the 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
Given this method:
If std_scores > 1.0, then devide = int(batch_size * 0.7)
If 0.5 < std_scores <= 1.0, then devide = int(batch_size * 0.5)
Otherwise, devide = int(batch_size * 0.3)
2. Analyzing the sample Method
Within the sample method, std_scores is calculated as follows:
python
scores = self.model.score(x, y, batch_size=B)
scores = np.nan_to_num(scores, nan=0.0, posinf=1.0, neginf=0.0)
scores = scores + 1e-8 # Prevent zero or negative values
# Normalize scores
if np.max(scores) != np.min(scores):
scores = (scores - np.min(scores)) / (np.max(scores) - np.min(scores))
else:
scores = np.full_like(scores, 0.5)
# Scale scores to 0-7 range and ceil
scores = scores * 7 + 1e-8
scores = np.clip(scores, 1e-8, 7)
scores = np.ceil(scores)
# Compute standard deviation
std_scores = np.std(scores)
Key Points:
Normalization and Scaling: The scores are normalized between 0 and 1, then scaled to a range of approximately 1 to 7.
Ceiling Operation: Applying np.ceil ensures that all scores are integers between 1 and 7.
Standard Deviation (std_scores): Given that scores range between 1 and 7, the standard deviation is inherently influenced by this spread.
3. Why devide is Always 11
Assuming the default batch_size of 16:
If std_scores > 1.0:
devide = int(16 * 0.7) = 11.2, which is truncated to 11.
Given the score distribution:
Uniform Distribution Example: If scores are uniformly distributed between 1 and 7, the expected standard deviation is approximately 2.0.
Typical Scenarios: Even with some variations, it's highly likely that std_scores remains above 1.0 due to the wide range (1-7) introduced by the ceiling operation.
Therefore, in most practical cases, especially when the scores exhibit substantial variability post-normalization and ceiling, std_scores will consistently exceed 1.0, leading devide to be calculated as 11.
4. Potential Solutions
If the consistent value of 11 for devide is undesirable, consider the following adjustments:
Adjust Thresholds: Modify the thresholds in the _determine_devide method to better match the observed std_scores.
Alter Score Scaling: Change how scores are normalized and scaled to reduce the spread.
python
# Example: Scale to a smaller range
scores = scores * 3.5 + 1e-8 # Scale to approximately 1-4
Dynamic Thresholding: Implement a more dynamic method to determine devide based on percentile ranks or other statistical measures rather than fixed thresholds.
Conclusion
The devide value remains at 11 because the standard deviation of scores after normalization and ceiling operations typically exceeds 1.0. This results in the _determine_devide method consistently selecting int(batch_size * 0.7), which is 11 for a batch_size of 16. Adjusting the thresholds or the score scaling process can help achieve a more varied devide value based on your specific requirements.