Skip to content

Commit 7b921ac

Browse files
committed
merge grpo-latest
2 parents ee939d9 + c8b368c commit 7b921ac

File tree

2 files changed

+32
-21
lines changed

2 files changed

+32
-21
lines changed

applications/ColossalChat/coati/distributed/consumer.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -124,17 +124,17 @@ def loop(self) -> None:
124124
raw_batch_with_reward = self.calculate_reward({k:v.view(-1, v.size(-1)) if k!='temperature' else v for k, v in raw_batch.items()})
125125
raw_batch_with_reward = {k: v.view(-1, self.num_generations, v.size(-1)) if k!='temperature' else v for k, v in raw_batch_with_reward.items()}
126126
# [batch_size, num_generations] -> [batch_size]
127-
group_reward_mean = raw_batch_with_reward["reward"][:,:,0].mean(dim=-1)
128-
group_format_acc_mean = raw_batch_with_reward["format_acc"][:,:,0].mean(dim=-1)
129-
group_ans_acc_mean = raw_batch_with_reward["ans_acc"][:,:,0].mean(dim=-1)
130-
group_response_len = (
127+
reward = raw_batch_with_reward["reward"][:,:,0]
128+
format_acc = raw_batch_with_reward["format_acc"][:,:,0]
129+
ans_acc = raw_batch_with_reward["ans_acc"][:,:,0]
130+
response_len = (
131131
(raw_batch_with_reward["response_idx"][:, :, 1] - raw_batch_with_reward["response_idx"][:, :, 0] + 1)
132132
.type(torch.float32)
133-
.mean(dim=-1)
134133
)
135134
effective_group_mask = None
136135
if self.filter_range is not None and self.grpo_config.get("dynamic_batching", True):
137136
# filter the group based on the reward and accuracy
137+
group_ans_acc_mean = ans_acc.mean(dim=1)
138138
effective_group_mask = torch.logical_and(
139139
group_ans_acc_mean > self.filter_range[0], group_ans_acc_mean < self.filter_range[1]
140140
)
@@ -143,15 +143,15 @@ def loop(self) -> None:
143143
self.buffer.append(
144144
[
145145
group_with_reward if effective_group_mask is None or effective_group_mask[group_idx] else None,
146-
group_reward_mean[group_idx],
147-
group_format_acc_mean[group_idx],
148-
group_ans_acc_mean[group_idx],
149-
group_response_len[group_idx],
146+
reward[group_idx],
147+
format_acc[group_idx],
148+
ans_acc[group_idx],
149+
response_len[group_idx],
150150
]
151151
)
152152
if effective_group_mask is not None:
153153
print(
154-
f"[T{dist.get_rank()}] Filter recv data: {len(raw_batch)} -> {torch.sum(effective_group_mask).cpu().item()} effective groups"
154+
f"[T{dist.get_rank()}] Filter recv data: {len(raw_batch_with_reward)} -> {torch.sum(effective_group_mask).cpu().item()} effective groups"
155155
)
156156
# mapping the effective group to the raw group for indexing
157157
effective_group_to_raw_group_mapping = {}
@@ -160,7 +160,7 @@ def loop(self) -> None:
160160
effective_group_to_raw_group_mapping[len(effective_group_to_raw_group_mapping)] = (
161161
buffer_idx
162162
)
163-
pbar.set_postfix({"Collect Effective Prompt": f"{len(effective_group_to_raw_group_mapping)}/{self.dp_size * self.minibatch_size}"})
163+
print(f"[T{dist.get_rank()}] Collect Effective Prompt: {len(effective_group_to_raw_group_mapping)}/{self.dp_size * self.minibatch_size}")
164164

165165
while len(effective_group_to_raw_group_mapping) >= self.dp_size * self.minibatch_size:
166166
# on each dp_rank, we use minibatch_size effective samples to form a batch

applications/ColossalChat/coati/distributed/grpo_consumer.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,17 @@ def step(self, step_idx: int, pbar: Any, **kwargs) -> Optional[float]:
211211
loss_mask,
212212
action_mask[:, -1] == False,
213213
)
214+
if self.filter_range is not None and self.grpo_config.get("dynamic_batching", False)==False:
215+
# filter out samples with reward outside the range
216+
# if dynamic batching is enabled, we filter out out of range groups before training
217+
group_ans_acc_mean = ans_acc.view(-1, self.num_generations).mean(dim=1).repeat_interleave(self.num_generations, dim=-1)
218+
loss_mask = torch.logical_and(
219+
loss_mask,
220+
torch.logical_and(
221+
group_ans_acc_mean > self.filter_range[0],
222+
group_ans_acc_mean < self.filter_range[1],
223+
),
224+
)
214225
self.effective_prompt_count += group_reward.size(0) * self.dp_size
215226

216227
mean_kl, mean_loss = [], []
@@ -229,8 +240,7 @@ def step(self, step_idx: int, pbar: Any, **kwargs) -> Optional[float]:
229240
pbar.set_postfix(
230241
{
231242
"Global Step": self.global_step,
232-
"Effective prompts": f"{self.effective_prompt_count}/{self.batch_size * self.dp_size}",
233-
"Effective samples": f"{self.effective_sample_count}/{self.batch_size * self.dp_size * self.num_generations}",
243+
"Gradient Accumulation on": f"{self.effective_prompt_count}/{self.batch_size * self.dp_size} effective prompts, {self.effective_sample_count}/{self.batch_size * self.dp_size * self.num_generations} effective samples",
234244
}
235245
)
236246

@@ -428,6 +438,7 @@ def _criterion(outputs, inputs):
428438
self.optimizer.step()
429439
self.optimizer.zero_grad()
430440
self.global_step += 1
441+
# no need to run all reduce as raw_train_batch_* are not splited across dp rank
431442
sample_utilization = self.effective_sample_count / len(self.raw_train_batch_reward) / self.num_generations
432443
self.effective_prompt_count = 0
433444
self.effective_sample_count = 0
@@ -438,14 +449,12 @@ def _criterion(outputs, inputs):
438449
if (not self.plugin.pp_size > 1 and self.rank == 0) or (
439450
self.plugin.pp_size > 1 and self.booster.plugin.stage_manager.is_last_stage() and self.tp_rank == 0
440451
):
441-
raw_batch_reward_mean = sum(self.raw_train_batch_reward) / len(self.raw_train_batch_reward)
442-
raw_batch_format_acc_mean = sum(self.raw_train_batch_format_acc) / len(
443-
self.raw_train_batch_format_acc
444-
)
445-
raw_batch_ans_acc_mean = sum(self.raw_train_batch_ans_acc) / len(self.raw_train_batch_ans_acc)
446-
raw_batch_response_len_mean = sum(self.raw_train_batch_response_len) / len(
447-
self.raw_train_batch_response_len
448-
)
452+
raw_batch_reward_mean = torch.cat(self.raw_train_batch_reward, dim=0).mean().cpu().item()
453+
raw_batch_format_acc_mean = torch.cat(self.raw_train_batch_format_acc, dim=0).mean().cpu().item()
454+
raw_batch_ans_acc_mean = torch.cat(self.raw_train_batch_ans_acc, dim=0).mean().cpu().item()
455+
raw_batch_response_len = torch.cat(self.raw_train_batch_response_len, dim=0)
456+
raw_batch_response_len_mean = raw_batch_response_len.mean().cpu().item()
457+
overlength_samples_ratio = (raw_batch_response_len >= action_mask.size(-1)).to(float).mean().cpu().item() # not an exact figure, but a close estimate
449458
self.raw_train_batch_reward = []
450459
self.raw_train_batch_format_acc = []
451460
self.raw_train_batch_ans_acc = []
@@ -458,6 +467,7 @@ def _criterion(outputs, inputs):
458467
f"Advantages: {self.accum_advantages.item() / self.accum_count:.4f}",
459468
f"Response Length: {raw_batch_response_len_mean:.4f}",
460469
f"Sample_utilization: {sample_utilization:.4f}",
470+
f"Overlength samples ratio: {overlength_samples_ratio:.4f}",
461471
] + ([f"KL: {self.accum_kl.item() / self.accum_count:.4f}"] if self.policy_loss_fn.beta > 0 else [])
462472
print("\n".join(to_log_msg))
463473
metrics = {
@@ -469,6 +479,7 @@ def _criterion(outputs, inputs):
469479
"train/advantages": self.accum_advantages.item() / self.accum_count,
470480
"train/learning_rate": self.lr_scheduler.get_last_lr()[0],
471481
"train/sample_utilization": sample_utilization,
482+
"train/overlength_samples_ratio": overlength_samples_ratio,
472483
"rollout/temperature": data["temperature"].cpu().numpy()[0][0],
473484
}
474485
if self.policy_loss_fn.beta > 0:

0 commit comments

Comments
 (0)