MCPcopy Create free account
hub / github.com/CompVis/diff2flow / LossSecondMomentResampler

Class LossSecondMomentResampler

diff2flow/openai_diffusion/timestep_sampler.py:120–150  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

118
119
120class LossSecondMomentResampler(LossAwareSampler):
121 def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001):
122 self.diffusion = diffusion
123 self.history_per_term = history_per_term
124 self.uniform_prob = uniform_prob
125 self._loss_history = np.zeros(
126 [diffusion.num_timesteps, history_per_term], dtype=np.float64
127 )
128 self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)
129
130 def weights(self):
131 if not self._warmed_up():
132 return np.ones([self.diffusion.num_timesteps], dtype=np.float64)
133 weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1))
134 weights /= np.sum(weights)
135 weights *= 1 - self.uniform_prob
136 weights += self.uniform_prob / len(weights)
137 return weights
138
139 def update_with_all_losses(self, ts, losses):
140 for t, loss in zip(ts, losses):
141 if self._loss_counts[t] == self.history_per_term:
142 # Shift out the oldest loss term.
143 self._loss_history[t, :-1] = self._loss_history[t, 1:]
144 self._loss_history[t, -1] = loss
145 else:
146 self._loss_history[t, self._loss_counts[t]] = loss
147 self._loss_counts[t] += 1
148
149 def _warmed_up(self):
150 return (self._loss_counts == self.history_per_term).all()

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected