File size: 9,846 Bytes
d7ff85b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import unittest
import torch
import torch.nn.functional as F
from typing import Tuple

# Assuming the canonical code is in a file named 'canonical_simpo.py'
# and the generated code is in a file named 'generated_simpo.py'
# For the purpose of this test suite, we'll use the provided code as canonical
# and assume the 'generated' code would be a separate file with the same function signature.
from canonical import simpo_loss as canonical_simpo_loss
from SimPO.scripts.simpo_loss_calc import simpo_loss as generated_simpo_loss


# Define gamma_beta_ratio globally or as a class variable for testing purposes,
# as it's a global variable in the provided code snippet.
# In a real scenario, this would likely be passed as an argument or managed within a class.
gamma_beta_ratio = 1.0 # Default value for testing, can be changed in specific tests.


class TestSimPOLoss(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # Determine the device to use for tests
        cls.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print(f"Running tests on device: {cls.device}")

    def setUp(self):
        # Reset gamma_beta_ratio for each test to ensure test isolation
        global gamma_beta_ratio
        gamma_beta_ratio = 1.0

    def _run_and_compare(self, policy_chosen_logps_data, policy_rejected_logps_data, loss_type, beta, label_smoothing, test_gamma_beta_ratio=1.0):
        global gamma_beta_ratio
        gamma_beta_ratio = test_gamma_beta_ratio

        # Create tensors from input data
        policy_chosen_logps = torch.tensor(policy_chosen_logps_data, dtype=torch.float32)
        policy_rejected_logps = torch.tensor(policy_rejected_logps_data, dtype=torch.float32)

        # Execute canonical function
        canonical_losses, canonical_chosen_rewards, canonical_rejected_rewards = canonical_simpo_loss(
            policy_chosen_logps, policy_rejected_logps, loss_type, beta, label_smoothing, self.device, test_gamma_beta_ratio
        )

        # Execute generated function
        generated_losses, generated_chosen_rewards, generated_rejected_rewards = generated_simpo_loss(
            policy_chosen_logps, policy_rejected_logps, loss_type, beta, label_smoothing, self.device, test_gamma_beta_ratio
        )

        # Assertions for losses
        self.assertTrue(torch.allclose(canonical_losses, generated_losses, rtol=1e-5, atol=1e-8),
                        f"Losses mismatch for {loss_type} loss.")
        self.assertEqual(canonical_losses.shape, generated_losses.shape, "Losses shape mismatch.")
        self.assertEqual(canonical_losses.dtype, generated_losses.dtype, "Losses dtype mismatch.")

        # Assertions for chosen_rewards
        self.assertTrue(torch.allclose(canonical_chosen_rewards, generated_chosen_rewards, rtol=1e-5, atol=1e-8),
                        f"Chosen rewards mismatch for {loss_type} loss.")
        self.assertEqual(canonical_chosen_rewards.shape, generated_chosen_rewards.shape, "Chosen rewards shape mismatch.")
        self.assertEqual(canonical_chosen_rewards.dtype, generated_chosen_rewards.dtype, "Chosen rewards dtype mismatch.")

        # Assertions for rejected_rewards
        self.assertTrue(torch.allclose(canonical_rejected_rewards, generated_rejected_rewards, rtol=1e-5, atol=1e-8),
                        f"Rejected rewards mismatch for {loss_type} loss.")
        self.assertEqual(canonical_rejected_rewards.shape, generated_rejected_rewards.shape, "Rejected rewards shape mismatch.")
        self.assertEqual(canonical_rejected_rewards.dtype, generated_rejected_rewards.dtype, "Rejected rewards dtype mismatch.")

    # --- Test cases for SimPO Loss Calculation ---

    def test_sigmoid_basic(self):
        # Test case 1: Basic sigmoid loss, chosen is better
        self._run_and_compare(
            policy_chosen_logps_data=[0.5, 1.0],
            policy_rejected_logps_data=[-0.5, 0.0],
            loss_type="sigmoid",
            beta=1.0,
            label_smoothing=0.0
        )

    def test_sigmoid_chosen_worse(self):
        # Test case 2: Sigmoid loss, chosen is worse
        self._run_and_compare(
            policy_chosen_logps_data=[-1.0, -2.0],
            policy_rejected_logps_data=[0.0, -1.0],
            loss_type="sigmoid",
            beta=1.0,
            label_smoothing=0.0
        )

    def test_sigmoid_equal_logps(self):
        # Test case 3: Sigmoid loss, log probabilities are equal
        self._run_and_compare(
            policy_chosen_logps_data=[0.0, 0.0],
            policy_rejected_logps_data=[0.0, 0.0],
            loss_type="sigmoid",
            beta=1.0,
            label_smoothing=0.0
        )

    def test_sigmoid_with_label_smoothing(self):
        # Test case 4: Sigmoid loss with label smoothing
        self._run_and_compare(
            policy_chosen_logps_data=[0.8],
            policy_rejected_logps_data=[-0.2],
            loss_type="sigmoid",
            beta=0.5,
            label_smoothing=0.1
        )

    def test_sigmoid_high_beta(self):
        # Test case 5: Sigmoid loss with a higher beta
        self._run_and_compare(
            policy_chosen_logps_data=[0.5],
            policy_rejected_logps_data=[-0.5],
            loss_type="sigmoid",
            beta=5.0,
            label_smoothing=0.0
        )
    
    def test_sigmoid_different_gamma_beta_ratio(self):
        # Test case 6: Sigmoid loss with a different gamma_beta_ratio
        self._run_and_compare(
            policy_chosen_logps_data=[0.5],
            policy_rejected_logps_data=[-0.5],
            loss_type="sigmoid",
            beta=1.0,
            label_smoothing=0.0,
            test_gamma_beta_ratio=0.5
        )

    def test_hinge_basic(self):
        # Test case 7: Basic hinge loss, chosen is better
        self._run_and_compare(
            policy_chosen_logps_data=[0.5, 1.0],
            policy_rejected_logps_data=[-0.5, 0.0],
            loss_type="hinge",
            beta=1.0,
            label_smoothing=0.0 # Label smoothing doesn't apply to hinge, but included for consistent signature
        )

    def test_hinge_chosen_worse(self):
        # Test case 8: Hinge loss, chosen is worse (should result in positive loss)
        self._run_and_compare(
            policy_chosen_logps_data=[-1.0, -2.0],
            policy_rejected_logps_data=[0.0, -1.0],
            loss_type="hinge",
            beta=1.0,
            label_smoothing=0.0
        )

    def test_hinge_equal_logps(self):
        # Test case 9: Hinge loss, log probabilities are equal
        self._run_and_compare(
            policy_chosen_logps_data=[0.0, 0.0],
            policy_rejected_logps_data=[0.0, 0.0],
            loss_type="hinge",
            beta=1.0,
            label_smoothing=0.0
        )

    def test_hinge_with_beta_gt_one(self):
        # Test case 10: Hinge loss with beta > 1.0
        self._run_and_compare(
            policy_chosen_logps_data=[0.5],
            policy_rejected_logps_data=[-0.5],
            loss_type="hinge",
            beta=2.0,
            label_smoothing=0.0
        )
    
    def test_hinge_different_gamma_beta_ratio(self):
        # Test case 11: Hinge loss with a different gamma_beta_ratio
        self._run_and_compare(
            policy_chosen_logps_data=[0.5],
            policy_rejected_logps_data=[-0.5],
            loss_type="hinge",
            beta=1.0,
            label_smoothing=0.0,
            test_gamma_beta_ratio=0.8
        )

    def test_unknown_loss_type(self):
        # Test case 12: Invalid loss type should raise ValueError
        policy_chosen_logps = torch.tensor([0.5], dtype=torch.float32)
        policy_rejected_logps = torch.tensor([-0.5], dtype=torch.float32)

        with self.assertRaises(ValueError) as cm:
            canonical_simpo_loss(policy_chosen_logps, policy_rejected_logps, "unknown", 1.0, 0.0, self.device, gamma_beta_ratio=1.0)
        self.assertIn("Unknown loss type: unknown", str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            generated_simpo_loss(policy_chosen_logps, policy_rejected_logps, "unknown", 1.0, 0.0, self.device, gamma_beta_ratio=1.0)
        self.assertIn("Unknown loss type: unknown", str(cm.exception))

    def test_zero_beta(self):
        # Test case 13: What happens if beta is zero?
        self._run_and_compare(
            policy_chosen_logps_data=[0.5],
            policy_rejected_logps_data=[-0.5],
            loss_type="sigmoid",
            beta=0.0,
            label_smoothing=0.0
        )
        self._run_and_compare(
            policy_chosen_logps_data=[0.5],
            policy_rejected_logps_data=[-0.5],
            loss_type="hinge",
            beta=0.0,
            label_smoothing=0.0
        )

    def test_large_log_probs(self):
        # Test case 14: Large log probabilities (chosen much better/worse)
        self._run_and_compare(
            policy_chosen_logps_data=[10.0],
            policy_rejected_logps_data=[-10.0],
            loss_type="sigmoid",
            beta=1.0,
            label_smoothing=0.0
        )
        self._run_and_compare(
            policy_chosen_logps_data=[-10.0],
            policy_rejected_logps_data=[10.0],
            loss_type="sigmoid",
            beta=1.0,
            label_smoothing=0.0
        )
        self._run_and_compare(
            policy_chosen_logps_data=[10.0],
            policy_rejected_logps_data=[-10.0],
            loss_type="hinge",
            beta=1.0,
            label_smoothing=0.0
        )
        self._run_and_compare(
            policy_chosen_logps_data=[-10.0],
            policy_rejected_logps_data=[10.0],
            loss_type="hinge",
            beta=1.0,
            label_smoothing=0.0
        )

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)