MCPcopy Create free account
hub / github.com/Sin3DM/Sin3DM / LossAwareSampler

Class LossAwareSampler

src/diffusion/resample.py:70–121  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected