-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathdapo_learner_test.py
More file actions
306 lines (277 loc) · 9.31 KB
/
dapo_learner_test.py
File metadata and controls
306 lines (277 loc) · 9.31 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from flax import nnx
import jax.numpy as jnp
from tunix.rl import function_registry as fr
from tunix.rl.grpo import dapo_learner as dapo_lib
from tunix.rl.grpo import grpo_learner as grpo_lib
from tunix.tests import test_common as tc
class DAPOlearnerTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.mock_model = mock.MagicMock()
self.pad_id = 0
self.eos_id = 1
# Common data shapes
self.batch_size = 2
self.seq_len = 4
self.prompt_ids = jnp.zeros(
(self.batch_size, self.seq_len), dtype=jnp.int32
)
self.completion_ids = jnp.ones(
(self.batch_size, self.seq_len), dtype=jnp.int32
)
self.completion_mask = jnp.array(
[[1, 1, 1, 0], [1, 1, 0, 0]], dtype=jnp.float32
)
self.advantages = jnp.array([0.5, -0.2], dtype=jnp.float32)
self.ref_per_token_logps = (
jnp.ones_like(self.completion_ids, dtype=jnp.float32) * -0.2
)
self.old_per_token_logps = (
jnp.ones_like(self.completion_ids, dtype=jnp.float32) * -0.15
)
def create_train_example(self):
example = mock.MagicMock()
example.prompt_ids = self.prompt_ids
example.completion_ids = self.completion_ids
example.completion_mask = self.completion_mask
example.advantages = self.advantages
example.ref_per_token_logps = self.ref_per_token_logps
example.old_per_token_logps = self.old_per_token_logps
example.segment_ids = None
example.segment_positions = None
return example
def test_diff_loss(self):
dapo_config = dapo_lib.DAPOConfig()
grpo_config = grpo_lib.GRPOConfig()
dapo_loss_fn_impl = fr.default_registry.get(
"policy_loss_fn", dapo_config.policy_loss_fn
)
grpo_loss_fn_impl = fr.default_registry.get(
"policy_loss_fn", grpo_config.policy_loss_fn
)
# Test that the functions is same
self.assertEqual(dapo_loss_fn_impl, grpo_loss_fn_impl)
# Create the same input for both functions
train_example = self.create_train_example()
pad_id = self.pad_id
eos_id = self.eos_id
vocab = tc.MockVocab()
model = tc.ToyTransformer(
config=tc.ModelConfig(vocab_size=vocab.GetPieceSize()),
rngs=nnx.Rngs(0),
)
# Call DAPO loss function
dapo_loss, dapo_aux = dapo_loss_fn_impl(
model, train_example, dapo_config, pad_id, eos_id
)
# Call GRPO loss function
grpo_loss, grpo_aux = grpo_loss_fn_impl(
model, train_example, grpo_config, pad_id, eos_id
)
# Assert that the loss values are different
self.assertNotEqual(
dapo_loss.item(),
grpo_loss.item(),
msg=(
"DAPO and GRPO loss values should be different for the same input"
" due to different loss aggregation logics."
),
)
self.assertIn("kl", dapo_aux)
self.assertIn("kl", grpo_aux)
self.assertEqual(dapo_aux["kl"], 0.0) # DAPO does not have KL term.
class TestDAPOConfigPostInit(parameterized.TestCase):
def test_valid_default(self):
"""Tests that default values pass validation."""
try:
dapo_lib.DAPOConfig()
except ValueError as e:
self.fail(f"DAPOConfig raised ValueError on default initialization: {e}")
@parameterized.named_parameters(
dict(testcase_name="custom_epsilons", epsilon=0.1, epsilon_high=0.15),
dict(testcase_name="epsilons_equal", epsilon=0.1, epsilon_high=0.1),
dict(
testcase_name="buffer_disabled",
overlong_buffer={"enable": False},
),
dict(testcase_name="buffer_none", overlong_buffer=None),
dict(
testcase_name="valid_buffer",
overlong_buffer={
"enable": True,
"overlong_buffer_length": 2000,
"overlong_buffer_penalty": 0.5,
"max_response_length": 10000,
},
),
)
def test_valid_configurations(self, **kwargs):
"""Tests various valid custom configurations."""
try:
dapo_lib.DAPOConfig(**kwargs)
except ValueError as e:
self.fail(f"DAPOConfig raised ValueError for valid case {kwargs}: {e}")
@parameterized.named_parameters(
dict(
testcase_name="invalid_epsilon_high",
config_kwargs=dict(epsilon=0.2, epsilon_high=0.1),
expected_regex=(
"epsilon_high must be greater than or equal to epsilon."
),
),
dict(
testcase_name="buffer_missing_length",
config_kwargs=dict(
overlong_buffer={
"enable": True,
"overlong_buffer_penalty": 1.0,
"max_response_length": 20480,
}
),
expected_regex=(
"overlong_buffer is enabled but missing.*overlong_buffer_length.*"
),
),
dict(
testcase_name="buffer_missing_penalty",
config_kwargs=dict(
overlong_buffer={
"enable": True,
"overlong_buffer_length": 4096,
"max_response_length": 20480,
}
),
expected_regex=(
"overlong_buffer is enabled but missing"
".*overlong_buffer_penalty.*"
),
),
dict(
testcase_name="buffer_missing_max_length",
config_kwargs=dict(
overlong_buffer={
"enable": True,
"overlong_buffer_length": 4096,
"overlong_buffer_penalty": 1.0,
}
),
expected_regex=(
"overlong_buffer is enabled but missing.*max_response_length.*"
),
),
dict(
testcase_name="buffer_length_is_none",
config_kwargs=dict(
overlong_buffer={
"enable": True,
"overlong_buffer_length": None,
"overlong_buffer_penalty": 1.0,
"max_response_length": 20480,
}
),
expected_regex=(
"overlong_buffer is enabled but missing.*overlong_buffer_length.*"
),
),
dict(
testcase_name="negative_penalty",
config_kwargs=dict(
overlong_buffer={
"enable": True,
"overlong_buffer_length": 4096,
"overlong_buffer_penalty": -0.5,
"max_response_length": 20480,
}
),
expected_regex="overlong_buffer_penalty must be non-negative",
),
)
def test_invalid_configurations(self, config_kwargs, expected_regex):
"""Tests various invalid configurations that should raise ValueError."""
with self.assertRaisesRegex(ValueError, expected_regex):
dapo_lib.DAPOConfig(**config_kwargs)
class RewardShapingTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.mock_cluster = mock.MagicMock()
def test_raises_error_on_none_buffer(self):
with self.assertRaisesRegex(
ValueError, "reward_shaping is called but with empty overlong_buffer."
):
dapo_lib.reward_shaping(
prompts=["test prompt"],
completions=["test completion"],
mode=self.mock_cluster.Mode,
overlong_buffer=None,
)
@parameterized.named_parameters(
dict(
testcase_name="under_length",
lengths=[70],
expected_scores=[0.0],
),
dict(
testcase_name="at_expected_length",
lengths=[80],
expected_scores=[0.0],
),
dict(
testcase_name="in_buffer_zone",
lengths=[90],
expected_scores=[-5.0],
),
dict(
testcase_name="at_max_length",
lengths=[100],
expected_scores=[-10.0],
),
dict(
testcase_name="over_max_length",
lengths=[110],
expected_scores=[-15.0],
),
dict(
testcase_name="mixed_lengths",
lengths=[70, 80, 90, 100, 110],
expected_scores=[0.0, 0.0, -5.0, -10.0, -15.0],
),
dict(
testcase_name="zero_penalty",
lengths=[110],
expected_scores=[0.0],
penalty=0,
),
)
def test_reward_scores(self, lengths, expected_scores, penalty=10):
completions = ["a" * length for length in lengths]
overlong_buffer = {
"overlong_buffer_length": 20,
"overlong_buffer_penalty": penalty,
"max_response_length": 100,
}
# expected_response_length = 100 - 20 = 80
scores = dapo_lib.reward_shaping(
prompts=[""] * len(completions),
completions=completions,
mode=self.mock_cluster.Mode,
overlong_buffer=overlong_buffer,
)
self.assertSequenceAlmostEqual(expected_scores, scores, places=4)
if __name__ == "__main__":
absltest.main()