Skip to content

Commit 697ba32

Browse files
committed
Cast multimodal forward_kwargs to compute dtype for bf16/fp16 training
1 parent d934eb7 commit 697ba32

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

tests/test_grpo_trainer.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2287,6 +2287,39 @@ def test_single_reward_model_with_single_processing_class(self):
22872287
assert trainer.reward_processing_classes[0] == single_processing_class
22882288

22892289

2290+
def test_forward_kwargs_dtype_casting():
2291+
forward_kwargs = {
2292+
"pixel_values": torch.randn(1, 3, 224, 224, dtype=torch.float32),
2293+
"image_grid_thw": torch.tensor([[1, 14, 14]]),
2294+
}
2295+
2296+
for bf16, fp16, expected_dtype in [
2297+
(True, False, torch.bfloat16),
2298+
(False, True, torch.float16),
2299+
(False, False, None),
2300+
]:
2301+
if bf16:
2302+
compute_dtype = torch.bfloat16
2303+
elif fp16:
2304+
compute_dtype = torch.float16
2305+
else:
2306+
compute_dtype = None
2307+
2308+
if compute_dtype is not None:
2309+
result = {
2310+
k: v.to(compute_dtype) if isinstance(v, torch.Tensor) and torch.is_floating_point(v) else v
2311+
for k, v in forward_kwargs.items()
2312+
}
2313+
else:
2314+
result = forward_kwargs
2315+
2316+
if expected_dtype is not None:
2317+
assert result["pixel_values"].dtype == expected_dtype
2318+
else:
2319+
assert result["pixel_values"].dtype == torch.float32
2320+
assert result["image_grid_thw"].dtype == torch.int64
2321+
2322+
22902323
@pytest.mark.slow
22912324
@require_torch_accelerator
22922325
class TestGRPOTrainerSlow(TrlTestCase):

trl/trainer/grpo_trainer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1609,6 +1609,17 @@ def _generate_and_score_completions(
16091609
prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
16101610
prompt_inputs = super()._prepare_inputs(prompt_inputs)
16111611
forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
1612+
if self.args.bf16:
1613+
compute_dtype = torch.bfloat16
1614+
elif self.args.fp16:
1615+
compute_dtype = torch.float16
1616+
else:
1617+
compute_dtype = None
1618+
if compute_dtype is not None:
1619+
forward_kwargs = {
1620+
k: v.to(compute_dtype) if isinstance(v, torch.Tensor) and torch.is_floating_point(v) else v
1621+
for k, v in forward_kwargs.items()
1622+
}
16121623
else:
16131624
forward_kwargs = {}
16141625

0 commit comments

Comments
 (0)