MCPcopy Create free account
hub / github.com/MotrixLab/insactor / LossAwareSampler

Class LossAwareSampler

diffplanner/models/utils/gaussian_diffusion.py:74–120  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

72
73
74class LossAwareSampler(ScheduleSampler):
75 def update_with_local_losses(self, local_ts, local_losses):
76 """
77 Update the reweighting using losses from a model.
78 Call this method from each rank with a batch of timesteps and the
79 corresponding losses for each of those timesteps.
80 This method will perform synchronization to make sure all of the ranks
81 maintain the exact same reweighting.
82 :param local_ts: an integer Tensor of timesteps.
83 :param local_losses: a 1D Tensor of losses.
84 """
85 batch_sizes = [
86 th.tensor([0], dtype=th.int32, device=local_ts.device)
87 for _ in range(dist.get_world_size())
88 ]
89 dist.all_gather(
90 batch_sizes,
91 th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),
92 )
93
94 # Pad all_gather batches to be the maximum batch size.
95 batch_sizes = [x.item() for x in batch_sizes]
96 max_bs = max(batch_sizes)
97
98 timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]
99 loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]
100 dist.all_gather(timestep_batches, local_ts)
101 dist.all_gather(loss_batches, local_losses)
102 timesteps = [
103 x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]
104 ]
105 losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]
106 self.update_with_all_losses(timesteps, losses)
107
108 @abstractmethod
109 def update_with_all_losses(self, ts, losses):
110 """
111 Update the reweighting using losses from a model.
112 Sub-classes should override this method to update the reweighting
113 using losses from the model.
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 :param ts: a list of int timesteps.
119 :param losses: a list of float losses, one per timestep.
120 """
121
122
123class LossSecondMomentResampler(LossAwareSampler):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected