|
| 1 | +from typing import List |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch |
| 5 | + |
| 6 | +from trinity.common.config import DataSelectorConfig, StorageConfig |
| 7 | + |
| 8 | +from .diff_estimator import InterpolationBetaPREstimator |
| 9 | + |
| 10 | + |
| 11 | +def build_diff_estimator(dataset, config: DataSelectorConfig): |
| 12 | + print(f"[DEBUG]: {config=}") |
| 13 | + feature_keys = config.feature_keys |
| 14 | + features = np.concat([np.array(list(dataset[k]))[:, None] for k in feature_keys], axis=1) |
| 15 | + print(f"[DEBUG]: {features.shape=}") |
| 16 | + print(f"[DEBUG]: {features[:5]=}") |
| 17 | + adaptive_rho = hasattr(config, "adaptive_rho") and config.adaptive_rho |
| 18 | + return InterpolationBetaPREstimator( |
| 19 | + features=features, m=config.m, lamb=config.lamb, rho=config.rho, adaptive_rho=adaptive_rho |
| 20 | + ) |
| 21 | + |
| 22 | + |
| 23 | +class BaseSelector: |
| 24 | + def __init__(self, data_source, config: DataSelectorConfig): |
| 25 | + self.data_source = data_source |
| 26 | + self.config = config |
| 27 | + |
| 28 | + def get_indices(self, batch_size: int, return_extra_info: bool = False): |
| 29 | + raise NotImplementedError |
| 30 | + |
| 31 | + def update(self, indices: List[int], values: List[float]): |
| 32 | + raise NotImplementedError |
| 33 | + |
| 34 | + |
| 35 | +class RandomSelector(BaseSelector): |
| 36 | + def __init__(self, data_source, config: DataSelectorConfig): |
| 37 | + super().__init__(data_source, config) |
| 38 | + self.n = len(data_source) |
| 39 | + print(f"[DEBUG]: RandomSelector-{self.n=}") |
| 40 | + |
| 41 | + def get_indices(self, batch_size, return_extra_info=False): |
| 42 | + selected_indices = torch.from_numpy(np.random.permutation(self.n)[:batch_size]) |
| 43 | + print(f"[DEBUG]: RandomSelector-{selected_indices=}") |
| 44 | + if return_extra_info: |
| 45 | + return selected_indices, {} |
| 46 | + else: |
| 47 | + return selected_indices |
| 48 | + |
| 49 | + def update(self, *args, **kwargs): |
| 50 | + pass |
| 51 | + |
| 52 | + |
| 53 | +class OfflineEasy2HardSelector(BaseSelector): |
| 54 | + def __init__(self, data_source, config: DataSelectorConfig): |
| 55 | + super().__init__(data_source, config) |
| 56 | + |
| 57 | + feature_keys = config.feature_keys |
| 58 | + self.features = np.concat( |
| 59 | + [np.array(list(data_source[k]))[:, None] for k in feature_keys], axis=1 |
| 60 | + ) |
| 61 | + features_with_index = [list(self.features[i]) + [i] for i in range(len(self.features))] |
| 62 | + features_with_index = sorted(features_with_index)[::-1] |
| 63 | + print(f"[DEBUG]: OfflineEasy2HardSelector, sorted {features_with_index[:20]}") |
| 64 | + self.sorted_index = np.array([i[2] for i in features_with_index]) |
| 65 | + |
| 66 | + self.n = len(data_source) |
| 67 | + self.current_position = 0 |
| 68 | + |
| 69 | + def update(self, *args, **kwargs) -> None: |
| 70 | + pass |
| 71 | + |
| 72 | + def get_indices(self, batch_size, return_extra_info=False): |
| 73 | + if self.current_position + batch_size > self.n: |
| 74 | + new_position = self.current_position + batch_size - self.n |
| 75 | + selected_indices = np.concatenate( |
| 76 | + [self.sorted_index[self.current_position :], self.sorted_index[:new_position]] |
| 77 | + ) |
| 78 | + else: |
| 79 | + new_position = self.current_position + batch_size |
| 80 | + selected_indices = self.sorted_index[self.current_position : new_position] |
| 81 | + self.current_position = new_position |
| 82 | + if not return_extra_info: |
| 83 | + return selected_indices |
| 84 | + else: |
| 85 | + extra_info = { |
| 86 | + "indices": selected_indices.tolist(), |
| 87 | + "feat1": self.features[selected_indices, 0].tolist(), |
| 88 | + "feat2": self.features[selected_indices, 1].tolist(), |
| 89 | + } |
| 90 | + return selected_indices, extra_info |
| 91 | + |
| 92 | + |
| 93 | +class DiffBasedSelector(BaseSelector): |
| 94 | + def __init__(self, data_source, config: DataSelectorConfig) -> None: |
| 95 | + super().__init__(data_source, config) |
| 96 | + self.diff_estimator = build_diff_estimator(data_source, config) |
| 97 | + |
| 98 | + def update(self, indices: List[int], values: List[float]) -> None: |
| 99 | + self.diff_estimator.update(indices, values) |
| 100 | + |
| 101 | + def get_scores(self) -> List[float]: |
| 102 | + predicted_pr = self.diff_estimator.predict_pr(do_sample=self.config.do_sample) |
| 103 | + scores = -np.abs(self.config.target_reward - predicted_pr) |
| 104 | + return scores |
| 105 | + |
| 106 | + def get_indices(self, batch_size, return_extra_info=False): |
| 107 | + sampling_scores = self.get_scores() |
| 108 | + sampling_scores = torch.from_numpy(sampling_scores) |
| 109 | + if self.config.tau == 0: |
| 110 | + selected_indices = torch.topk(sampling_scores, batch_size).indices |
| 111 | + else: |
| 112 | + sampling_logits = sampling_scores / self.config.tau |
| 113 | + sampling_logits -= sampling_logits.max() |
| 114 | + sampling_probabilities = torch.softmax(sampling_logits, dim=0) |
| 115 | + selected_indices = torch.multinomial( |
| 116 | + sampling_probabilities, batch_size, replacement=False |
| 117 | + ) |
| 118 | + print(f"[DEBUG]: {selected_indices=}") |
| 119 | + print(f"[DEBUG]: {sampling_scores=}") |
| 120 | + print(f"[DEBUG]: {sampling_scores[selected_indices]=}") |
| 121 | + |
| 122 | + if return_extra_info: |
| 123 | + selected_indices_list = selected_indices.tolist() |
| 124 | + alphas = self.diff_estimator.alphas[selected_indices_list] |
| 125 | + betas = self.diff_estimator.betas[selected_indices_list] |
| 126 | + point_est = alphas / (alphas + betas) |
| 127 | + extra_info = { |
| 128 | + "indices": selected_indices_list, |
| 129 | + "scores": sampling_scores[selected_indices].tolist(), |
| 130 | + "alphas": alphas.tolist(), |
| 131 | + "betas": betas.tolist(), |
| 132 | + "point": point_est.tolist(), |
| 133 | + } |
| 134 | + return selected_indices, extra_info |
| 135 | + else: |
| 136 | + return selected_indices |
| 137 | + |
| 138 | + |
| 139 | +def build_selector(dataset, config: StorageConfig) -> BaseSelector: |
| 140 | + selector_config = config.task_selector |
| 141 | + assert selector_config is not None |
| 142 | + selector_type = selector_config.selector_type |
| 143 | + if selector_type == "random": |
| 144 | + return RandomSelector(dataset, selector_config) |
| 145 | + elif selector_type == "diff": |
| 146 | + return DiffBasedSelector(dataset, selector_config) |
| 147 | + elif selector_type == "offline": |
| 148 | + return OfflineEasy2HardSelector(dataset, selector_config) |
| 149 | + else: |
| 150 | + raise ValueError(f"Unknown selector type: {selector_type}") |
0 commit comments