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

Class LossAwareSampler

diff2flow/openai_diffusion/timestep_sampler.py:71–117  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

69
70
71class LossAwareSampler(ScheduleSampler):
72 def update_with_local_losses(self, local_ts, local_losses):
73 """
74 Update the reweighting using losses from a model.
75 Call this method from each rank with a batch of timesteps and the
76 corresponding losses for each of those timesteps.
77 This method will perform synchronization to make sure all of the ranks
78 maintain the exact same reweighting.
79 :param local_ts: an integer Tensor of timesteps.
80 :param local_losses: a 1D Tensor of losses.
81 """
82 batch_sizes = [
83 th.tensor([0], dtype=th.int32, device=local_ts.device)
84 for _ in range(dist.get_world_size())
85 ]
86 dist.all_gather(
87 batch_sizes,
88 th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),
89 )
90
91 # Pad all_gather batches to be the maximum batch size.
92 batch_sizes = [x.item() for x in batch_sizes]
93 max_bs = max(batch_sizes)
94
95 timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]
96 loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]
97 dist.all_gather(timestep_batches, local_ts)
98 dist.all_gather(loss_batches, local_losses)
99 timesteps = [
100 x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]
101 ]
102 losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]
103 self.update_with_all_losses(timesteps, losses)
104
105 @abstractmethod
106 def update_with_all_losses(self, ts, losses):
107 """
108 Update the reweighting using losses from a model.
109 Sub-classes should override this method to update the reweighting
110 using losses from the model.
111 This method directly updates the reweighting without synchronizing
112 between workers. It is called by update_with_local_losses from all
113 ranks with identical arguments. Thus, it should have deterministic
114 behavior to maintain state across workers.
115 :param ts: a list of int timesteps.
116 :param losses: a list of float losses, one per timestep.
117 """
118
119
120class LossSecondMomentResampler(LossAwareSampler):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected