| 130 | |
| 131 | |
| 132 | class LossSecondMomentResampler(LossAwareSampler): |
| 133 | |
| 134 | def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001): |
| 135 | self.diffusion = diffusion |
| 136 | self.history_per_term = history_per_term |
| 137 | self.uniform_prob = uniform_prob |
| 138 | self._loss_history = np.zeros( |
| 139 | [diffusion.num_timesteps, history_per_term], dtype=np.float64) |
| 140 | self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int) |
| 141 | |
| 142 | def weights(self): |
| 143 | if not self._warmed_up(): |
| 144 | return np.ones([self.diffusion.num_timesteps], dtype=np.float64) |
| 145 | weights = np.sqrt(np.mean(self._loss_history**2, axis=-1)) |
| 146 | weights /= np.sum(weights) |
| 147 | weights *= 1 - self.uniform_prob |
| 148 | weights += self.uniform_prob / len(weights) |
| 149 | return weights |
| 150 | |
| 151 | def update_with_all_losses(self, ts, losses): |
| 152 | for t, loss in zip(ts, losses): |
| 153 | if self._loss_counts[t] == self.history_per_term: |
| 154 | # Shift out the oldest loss term. |
| 155 | self._loss_history[t, :-1] = self._loss_history[t, 1:] |
| 156 | self._loss_history[t, -1] = loss |
| 157 | else: |
| 158 | self._loss_history[t, self._loss_counts[t]] = loss |
| 159 | self._loss_counts[t] += 1 |
| 160 | |
| 161 | def _warmed_up(self): |
| 162 | return (self._loss_counts == self.history_per_term).all() |
| 163 | |
| 164 | |
| 165 | def mean_flat(tensor): |
no outgoing calls
no test coverage detected