|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import pytest |
| 8 | +import torch |
| 9 | +from torchtune.dev.rl.rewards import RewardOutput |
| 10 | + |
| 11 | + |
| 12 | +class TestRewardOutput: |
| 13 | + @pytest.fixture |
| 14 | + def sample_reward_output(self): |
| 15 | + return RewardOutput( |
| 16 | + reward_base_name="test_reward", |
| 17 | + total_reward=torch.tensor([1.0, 2.0, 3.0]), |
| 18 | + successes=torch.tensor([1.0, 0.0, 1.0]), |
| 19 | + rewards={ |
| 20 | + "sub_reward_1": torch.tensor([0.5, 1.5, 2.5]), |
| 21 | + "sub_reward_2": torch.tensor([10.0, 20.0, 30.0]), |
| 22 | + }, |
| 23 | + ) |
| 24 | + |
| 25 | + def test_log(self, sample_reward_output): |
| 26 | + log_dict = sample_reward_output.log(prefix="train") |
| 27 | + expected_log = { |
| 28 | + "train/test_reward/sub_reward_1": 1.5, |
| 29 | + "train/test_reward/sub_reward_2": 20.0, |
| 30 | + "train/test_reward": 2.0, |
| 31 | + "train/test_reward/successes": 2.0 / 3.0, |
| 32 | + } |
| 33 | + assert log_dict.keys() == expected_log.keys() |
| 34 | + for key in expected_log: |
| 35 | + assert log_dict[key] == pytest.approx(expected_log[key]) |
| 36 | + |
| 37 | + def test_log_no_prefix(self, sample_reward_output): |
| 38 | + log_dict = sample_reward_output.log() |
| 39 | + expected_log = { |
| 40 | + "test_reward/sub_reward_1": 1.5, |
| 41 | + "test_reward/sub_reward_2": 20.0, |
| 42 | + "test_reward": 2.0, |
| 43 | + "test_reward/successes": 2.0 / 3.0, |
| 44 | + } |
| 45 | + assert log_dict.keys() == expected_log.keys() |
| 46 | + for key in expected_log: |
| 47 | + assert log_dict[key] == pytest.approx(expected_log[key]) |
0 commit comments