-
Notifications
You must be signed in to change notification settings - Fork 597
Expand file tree
/
Copy pathtest_adv_norm_config.py
More file actions
1270 lines (985 loc) · 45.6 KB
/
Copy pathtest_adv_norm_config.py
File metadata and controls
1270 lines (985 loc) · 45.6 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from dataclasses import asdict
from unittest.mock import patch
import pytest
import torch
from areal.api.cli_args import NormConfig
from areal.utils.data import Normalization
# =============================================================================
# NormConfig Tests
# =============================================================================
def test_adv_norm_config_inheritance():
"""Test that NormConfig inherits all properties from NormConfig."""
adv_config = NormConfig()
# Verify that NormConfig has expected attributes
assert hasattr(adv_config, "mean_level"), (
"NormConfig should have mean_level attribute"
)
assert hasattr(adv_config, "std_level"), (
"NormConfig should have std_level attribute"
)
assert hasattr(adv_config, "group_size"), (
"NormConfig should have group_size attribute"
)
assert hasattr(adv_config, "mean_leave1out"), (
"NormConfig should have mean_leave1out attribute"
)
assert hasattr(adv_config, "std_unbiased"), (
"NormConfig should have std_unbiased attribute"
)
# Verify default values
assert adv_config.mean_level == "batch", "Default mean_level should be 'batch'"
assert adv_config.std_level == "batch", "Default std_level should be 'batch'"
assert adv_config.group_size == 1, "Default group_size should be 1"
assert adv_config.mean_leave1out is False, "Default mean_leave1out should be False"
assert adv_config.std_unbiased is True, "Default std_unbiased should be False"
def test_adv_norm_config_custom_values():
"""Test NormConfig with custom values."""
adv_config = NormConfig(
mean_level=None,
std_level="batch",
group_size=4,
mean_leave1out=True,
std_unbiased=True,
)
assert adv_config.mean_level is None
assert adv_config.std_level == "batch"
assert adv_config.group_size == 4
assert adv_config.mean_leave1out is True
assert adv_config.std_unbiased is True
def test_adv_norm_config_asdict():
"""Test conversion of NormConfig to dictionary."""
adv_config = NormConfig(
mean_level="batch",
std_level="group",
group_size=32,
mean_leave1out=True,
std_unbiased=True,
)
config_dict = asdict(adv_config)
assert config_dict["mean_level"] == "batch"
assert config_dict["std_level"] == "group"
assert config_dict["group_size"] == 32
assert config_dict["mean_leave1out"] is True
assert config_dict["std_unbiased"] is True
@pytest.mark.parametrize("mean_level", ["batch", "group", None])
@pytest.mark.parametrize("std_level", ["batch", "group", None])
@pytest.mark.parametrize("group_size", [1, 8, 32, 128])
@pytest.mark.parametrize("mean_leave1out", [True, False])
@pytest.mark.parametrize("std_unbiased", [True, False])
def test_adv_norm_config_parameterized(
mean_level, std_level, group_size, mean_leave1out, std_unbiased
):
"""Parameterized test for NormConfig with various combinations."""
adv_config = NormConfig(
mean_level=mean_level,
std_level=std_level,
group_size=group_size,
mean_leave1out=mean_leave1out,
std_unbiased=std_unbiased,
)
assert adv_config.mean_level == mean_level
assert adv_config.std_level == std_level
assert adv_config.group_size == group_size
assert adv_config.mean_leave1out == mean_leave1out
assert adv_config.std_unbiased == std_unbiased
def test_adv_norm_config_equality():
"""Test equality comparison between NormConfig instances."""
adv_config1 = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_config2 = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_config3 = NormConfig(mean_level="group", std_level="batch", group_size=1)
assert adv_config1 == adv_config2
assert adv_config1 != adv_config3
def test_adv_norm_initialization():
"""Test Normalization initialization with various configurations."""
# Test with batch normalization
config = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_norm = Normalization(config)
assert adv_norm.mean_level == "batch"
assert adv_norm.std_level == "batch"
assert adv_norm.group_size == 1
# Test with group normalization
config = NormConfig(mean_level="group", std_level="group", group_size=8)
adv_norm = Normalization(config)
assert adv_norm.mean_level == "group"
assert adv_norm.std_level == "group"
assert adv_norm.group_size == 8
# Test with mixed normalization
config = NormConfig(mean_level="batch", std_level="group", group_size=16)
adv_norm = Normalization(config)
assert adv_norm.mean_level == "batch"
assert adv_norm.std_level == "group"
assert adv_norm.group_size == 16
# Test with no normalization
config = NormConfig(mean_level=None, std_level=None, group_size=1)
adv_norm = Normalization(config)
assert adv_norm.mean_level is None
assert adv_norm.std_level is None
assert adv_norm.group_size == 1
def test_adv_norm_initialization_validation():
"""Test Normalization initialization validation."""
# Test invalid mean_level
with pytest.raises(ValueError, match="mean_level must be 'batch', 'group' or None"):
config = NormConfig(mean_level="invalid", std_level="batch", group_size=1)
Normalization(config)
# Test invalid std_level
with pytest.raises(ValueError, match="std_level must be 'batch', 'group', or None"):
config = NormConfig(mean_level="batch", std_level="invalid", group_size=1)
Normalization(config)
# Test invalid group_size for group normalization
with pytest.raises(
ValueError,
match="group_size must be a positive integer when using group normalization",
):
config = NormConfig(mean_level="group", std_level="batch", group_size=0)
Normalization(config)
def test_adv_norm_batch_normalization():
"""Test batch normalization functionality."""
config = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_norm = Normalization(config)
# Create test data
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.tensor([[1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], dtype=torch.float32)
# Apply normalization
normalized = adv_norm(advantages, loss_mask)
# Check that normalization was applied
assert normalized.shape == advantages.shape
assert not torch.allclose(
normalized, advantages
) # Should be different after normalization
def test_adv_norm_group_normalization():
"""Test group normalization functionality."""
config = NormConfig(mean_level="group", std_level="group", group_size=2)
adv_norm = Normalization(config)
# Create test data with 4 samples (2 groups of 2)
advantages = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0]],
dtype=torch.float32,
)
loss_mask = torch.ones_like(advantages)
# Apply normalization
normalized = adv_norm(advantages, loss_mask)
# Check that normalization was applied
assert normalized.shape == advantages.shape
assert not torch.allclose(normalized, advantages)
def test_adv_norm_mixed_normalization():
"""Test mixed normalization (different mean and std levels)."""
config = NormConfig(mean_level="batch", std_level="group", group_size=2)
adv_norm = Normalization(config)
# Create test data
advantages = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0]],
dtype=torch.float32,
)
loss_mask = torch.ones_like(advantages)
# Apply normalization
normalized = adv_norm(advantages, loss_mask)
# Check that normalization was applied
assert normalized.shape == advantages.shape
assert not torch.allclose(normalized, advantages)
def test_adv_norm_no_normalization():
"""Test no normalization case."""
config = NormConfig(mean_level=None, std_level=None, group_size=1)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
# Apply "normalization" - should return original values
normalized = adv_norm(advantages, loss_mask)
# Should be identical to input
assert torch.allclose(normalized, advantages)
def test_adv_norm_center_only():
"""Test normalization with mean subtraction only (std_level='none')."""
config = NormConfig(mean_level="batch", std_level=None, group_size=1)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
# Apply normalization
normalized = adv_norm(advantages, loss_mask)
# Should be centered but not scaled
assert normalized.shape == advantages.shape
# Mean should be approximately 0
assert torch.abs(normalized.mean()) < 1e-6
def test_adv_norm_without_mask():
"""Test normalization without providing a mask."""
config = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
# Apply normalization without mask
normalized = adv_norm(advantages)
# Should still work and normalize
assert normalized.shape == advantages.shape
assert not torch.allclose(normalized, advantages)
def test_adv_norm_edge_cases():
"""Test edge cases for Normalization."""
# Test with all zeros
config = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_norm = Normalization(config)
advantages = torch.zeros((2, 3), dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Should handle zeros without division by zero
assert torch.allclose(normalized, torch.zeros_like(advantages))
# Test with very small values
advantages = torch.tensor([[1e-10, 2e-10], [3e-10, 4e-10]], dtype=torch.float32)
normalized = adv_norm(advantages)
# Should handle small values without numerical issues
assert normalized.shape == advantages.shape
def test_adv_norm_dtype_preservation():
"""Test that output dtype is preserved as float32."""
config = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32)
normalized = adv_norm(advantages)
# Output should be float32
assert normalized.dtype == torch.float32
@patch("torch.distributed.is_initialized")
@patch("torch.distributed.all_reduce")
def test_adv_norm_distributed(mock_all_reduce, mock_is_initialized):
"""Test Normalization in distributed setting."""
mock_is_initialized.return_value = True
mock_all_reduce.return_value = None
config = NormConfig(mean_level="batch", std_level="batch", group_size=1)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
# Apply normalization with reduce_group
normalized = adv_norm(advantages, loss_mask, reduce_group="dummy_group")
# Should call all_reduce in distributed mode
assert mock_all_reduce.called
assert normalized.shape == advantages.shape
@pytest.mark.parametrize(
"mean_level,std_level",
[
("batch", "batch"),
("group", "group"),
("batch", "group"),
("group", "batch"),
("batch", None),
(None, "batch"),
],
)
def test_adv_norm_parameterized(mean_level, std_level):
"""Parameterized test for different normalization combinations."""
config = NormConfig(
mean_level=mean_level,
std_level=std_level,
group_size=4 if "group" in [mean_level, std_level] else 1,
)
adv_norm = Normalization(config)
# Create test data
advantages = torch.tensor(
[
[1.0, 2.0, 3.0, 4.0],
[5.0, 6.0, 7.0, 8.0],
[9.0, 10.0, 11.0, 12.0],
[13.0, 14.0, 15.0, 16.0],
],
dtype=torch.float32,
)
loss_mask = torch.ones_like(advantages)
# Apply normalization
normalized = adv_norm(advantages, loss_mask)
# Basic validation
assert normalized.shape == advantages.shape
assert normalized.dtype == torch.float32
# For non-"none" normalization, values should change
if mean_level is not None or std_level is not None:
assert not torch.allclose(normalized, advantages)
def test_adv_norm_debug_cases():
"""Debug test cases for mixed and no normalization scenarios."""
# Test mixed normalization (batch mean, group std)
config = NormConfig(mean_level="batch", std_level="group", group_size=2)
adv_norm = Normalization(config)
advantages = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0]],
dtype=torch.float32,
)
loss_mask = torch.ones_like(advantages)
# Should work without shape mismatch errors
normalized = adv_norm(advantages, loss_mask)
assert normalized.shape == advantages.shape
assert not torch.allclose(normalized, advantages) # Should be normalized
# Test no normalization case
config = NormConfig(mean_level=None, std_level=None, group_size=1)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
# Should return original values unchanged
normalized = adv_norm(advantages, loss_mask)
assert torch.allclose(normalized, advantages)
# =============================================================================
# Tests for mean_leave1out option
# =============================================================================
def test_mean_leave1out_basic():
"""Test basic functionality of mean_leave1out option."""
# Test with mean_leave1out=True
config = NormConfig(mean_level="batch", std_level=None, mean_leave1out=True)
adv_norm = Normalization(config)
# Simple test data: 2 samples with 3 features each
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# With leave-one-out, each element should be centered by the mean of all other elements
# For element at [0,0] = 1.0, leave-one-out mean = (2+3+4+5+6)/(6-1) = 20/5 = 4.0
# So normalized[0,0] should be 1.0 - 4.0 = -3.0
expected_leave1out_mean_00 = (2.0 + 3.0 + 4.0 + 5.0 + 6.0) / 5.0 # 4.0
assert torch.allclose(
normalized[0, 0], torch.tensor(1.0 - expected_leave1out_mean_00)
)
# Compare with regular mean (mean_leave1out=False)
config_regular = NormConfig(
mean_level="batch", std_level=None, mean_leave1out=False
)
adv_norm_regular = Normalization(config_regular)
normalized_regular = adv_norm_regular(advantages, loss_mask)
# Results should be different
assert not torch.allclose(normalized, normalized_regular)
def test_mean_leave1out_single_element():
"""Test mean_leave1out with single element (edge case)."""
config = NormConfig(mean_level="batch", std_level=None, mean_leave1out=True)
adv_norm = Normalization(config)
# Single element
advantages = torch.tensor([[5.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# With single element, leave-one-out should return zero (no other elements to compute mean)
assert torch.allclose(
normalized, torch.tensor([[5.0]])
) # Should remain unchanged since mean=0
def test_mean_leave1out_with_mask():
"""Test mean_leave1out with loss mask."""
config = NormConfig(mean_level="batch", std_level=None, mean_leave1out=True)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
# Mask out the last element
loss_mask = torch.tensor([[1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], dtype=torch.float32)
normalized = adv_norm(advantages, loss_mask)
# Only elements where mask=1 should be considered for leave-one-out mean calculation
# Effective elements: [1.0, 2.0, 4.0, 5.0, 6.0] (3.0 is masked out)
assert normalized.shape == advantages.shape
def test_mean_leave1out_group_level():
"""Test mean_leave1out with group-level normalization."""
config = NormConfig(
mean_level="group", std_level=None, group_size=2, mean_leave1out=True
)
adv_norm = Normalization(config)
# 4 samples, 2 groups of 2
advantages = torch.tensor(
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], dtype=torch.float32
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Group 1: [1,2,3,4] -> leave-one-out for element 1: mean=(2+3+4)/3 = 3.0
# Group 2: [5,6,7,8] -> leave-one-out for element 5: mean=(6+7+8)/3 = 7.0
assert normalized.shape == advantages.shape
assert not torch.allclose(normalized, advantages)
@pytest.mark.parametrize("mean_leave1out", [True, False])
def test_mean_leave1out_parameterized(mean_leave1out):
"""Parameterized test for mean_leave1out option."""
config = NormConfig(
mean_level="batch", std_level="batch", mean_leave1out=mean_leave1out
)
adv_norm = Normalization(config)
advantages = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], dtype=torch.float32
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Basic validation
assert normalized.shape == advantages.shape
assert normalized.dtype == torch.float32
assert not torch.allclose(normalized, advantages) # Should be normalized
# =============================================================================
# Tests for std_unbiased option
# =============================================================================
def test_std_unbiased_basic():
"""Test basic functionality of std_unbiased option."""
# Test with std_unbiased=True
config = NormConfig(mean_level="batch", std_level="batch", std_unbiased=True)
adv_norm = Normalization(config)
# Use data with known variance
advantages = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized_unbiased = adv_norm(advantages, loss_mask)
# Compare with biased version (std_unbiased=False)
config_biased = NormConfig(
mean_level="batch", std_level="batch", std_unbiased=False
)
adv_norm_biased = Normalization(config_biased)
normalized_biased = adv_norm_biased(advantages, loss_mask)
# Results should be different
assert not torch.allclose(normalized_unbiased, normalized_biased)
# Both should have same shape and be normalized
assert normalized_unbiased.shape == advantages.shape
assert normalized_biased.shape == advantages.shape
def test_std_unbiased_single_element():
"""Test std_unbiased with single element (edge case)."""
config = NormConfig(mean_level="batch", std_level="batch", std_unbiased=True)
adv_norm = Normalization(config)
advantages = torch.tensor([[5.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# With single element, unbiased std should return zero (undefined)
# The normalization should handle this gracefully
assert normalized.shape == advantages.shape
assert torch.isfinite(normalized).all()
def test_std_unbiased_with_mask():
"""Test std_unbiased with loss mask."""
config = NormConfig(mean_level="batch", std_level="batch", std_unbiased=True)
adv_norm = Normalization(config)
advantages = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32)
# Mask out some elements
loss_mask = torch.tensor([[1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], dtype=torch.float32)
normalized = adv_norm(advantages, loss_mask)
# Only elements where mask=1 should be considered for std calculation
assert normalized.shape == advantages.shape
assert torch.isfinite(normalized).all()
def test_std_unbiased_group_level():
"""Test std_unbiased with group-level normalization."""
config = NormConfig(
mean_level="group", std_level="group", group_size=2, std_unbiased=True
)
adv_norm = Normalization(config)
# 4 samples, 2 groups of 2
advantages = torch.tensor(
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], dtype=torch.float32
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Should compute unbiased std within each group
assert normalized.shape == advantages.shape
assert torch.isfinite(normalized).all()
@pytest.mark.parametrize("std_unbiased", [True, False])
def test_std_unbiased_parameterized(std_unbiased):
"""Parameterized test for std_unbiased option."""
config = NormConfig(
mean_level="batch", std_level="batch", std_unbiased=std_unbiased
)
adv_norm = Normalization(config)
advantages = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], dtype=torch.float32
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Basic validation
assert normalized.shape == advantages.shape
assert normalized.dtype == torch.float32
assert not torch.allclose(normalized, advantages) # Should be normalized
assert torch.isfinite(normalized).all()
# =============================================================================
# Combined tests for both options
# =============================================================================
@pytest.mark.parametrize("mean_leave1out", [True, False])
@pytest.mark.parametrize("std_unbiased", [True, False])
def test_combined_mean_leave1out_std_unbiased(mean_leave1out, std_unbiased):
"""Test combined mean_leave1out and std_unbiased options."""
config = NormConfig(
mean_level="batch",
std_level="batch",
mean_leave1out=mean_leave1out,
std_unbiased=std_unbiased,
)
adv_norm = Normalization(config)
advantages = torch.tensor(
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0]],
dtype=torch.float32,
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Basic validation
assert normalized.shape == advantages.shape
assert normalized.dtype == torch.float32
assert not torch.allclose(normalized, advantages) # Should be normalized
assert torch.isfinite(normalized).all()
def test_normalization_initialization_with_new_options():
"""Test Normalization initialization with new options."""
# Test with both new options enabled
config = NormConfig(
mean_level="batch",
std_level="batch",
group_size=1,
mean_leave1out=True,
std_unbiased=True,
)
adv_norm = Normalization(config)
assert adv_norm.mean_level == "batch"
assert adv_norm.std_level == "batch"
assert adv_norm.mean_leave1out is True
assert adv_norm.std_unbiased is True
assert adv_norm.group_size == 1
# Test with both new options disabled
config = NormConfig(
mean_level="group",
std_level="group",
group_size=4,
mean_leave1out=False,
std_unbiased=False,
)
adv_norm = Normalization(config)
assert adv_norm.mean_level == "group"
assert adv_norm.std_level == "group"
assert adv_norm.mean_leave1out is False
assert adv_norm.std_unbiased is False
assert adv_norm.group_size == 4
def test_mathematical_correctness_mean_leave1out():
"""Test mathematical correctness of mean_leave1out implementation."""
config = NormConfig(mean_level="batch", std_level=None, mean_leave1out=True)
adv_norm = Normalization(config)
# Simple case: [1, 2, 3, 4]
advantages = torch.tensor([[1.0], [2.0], [3.0], [4.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# For element 1: leave-one-out mean = (2+3+4)/3 = 3.0, so result = 1-3 = -2
# For element 2: leave-one-out mean = (1+3+4)/3 = 8/3, so result = 2-8/3 = -2/3
# For element 3: leave-one-out mean = (1+2+4)/3 = 7/3, so result = 3-7/3 = 2/3
# For element 4: leave-one-out mean = (1+2+3)/3 = 2.0, so result = 4-2 = 2
expected = torch.tensor(
[[-2.0], [-2.0 / 3.0], [2.0 / 3.0], [2.0]], dtype=torch.float32
)
assert torch.allclose(normalized, expected, atol=1e-6)
def test_mathematical_correctness_std_unbiased():
"""Test mathematical correctness of std_unbiased implementation."""
# Use a case where we can manually compute the expected result
advantages = torch.tensor([[1.0], [2.0], [3.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
# Test biased std
config_biased = NormConfig(
mean_level="batch", std_level="batch", std_unbiased=False
)
adv_norm_biased = Normalization(config_biased)
normalized_biased = adv_norm_biased(advantages, loss_mask)
# Test unbiased std
config_unbiased = NormConfig(
mean_level="batch", std_level="batch", std_unbiased=True
)
adv_norm_unbiased = Normalization(config_unbiased)
normalized_unbiased = adv_norm_unbiased(advantages, loss_mask)
# Both should have the same mean (approximately 0) but different scaling
assert torch.allclose(normalized_biased.mean(), torch.tensor(0.0), atol=1e-6)
assert torch.allclose(normalized_unbiased.mean(), torch.tensor(0.0), atol=1e-6)
# The ratio between biased and unbiased should be sqrt(n/(n-1)) = sqrt(3/2)
# Because biased normalization divides by smaller std, it produces larger spread
ratio = torch.std(normalized_biased) / torch.std(normalized_unbiased)
expected_ratio = torch.sqrt(torch.tensor(3.0 / 2.0))
assert torch.allclose(ratio, expected_ratio, atol=1e-4)
# =============================================================================
# Edge Cases and Error Condition Tests
# =============================================================================
def test_leave_one_out_edge_cases():
"""Test edge cases for leave-one-out mean computation."""
# Test with all zeros - should handle gracefully
config = NormConfig(mean_level="batch", std_level=None, mean_leave1out=True)
adv_norm = Normalization(config)
advantages = torch.zeros((3, 2), dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
assert torch.allclose(normalized, advantages) # Should remain zeros
# Test with single non-zero element among zeros
advantages = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]], dtype=torch.float32)
normalized = adv_norm(advantages, loss_mask)
# With leave-one-out:
# For 0.0 elements: leave-one-out mean = (0+1+0+0+0)/5 = 0.2, result = 0.0 - 0.2 = -0.2
# For 1.0 element: leave-one-out mean = (0+0+0+0+0)/5 = 0.0, result = 1.0 - 0.0 = 1.0
expected = torch.tensor(
[[-0.2, -0.2], [1.0, -0.2], [-0.2, -0.2]], dtype=torch.float32
)
assert torch.allclose(normalized, expected, atol=1e-4)
def test_unbiased_std_edge_cases():
"""Test edge cases for unbiased standard deviation."""
# Test with identical values - variance should be zero
config = NormConfig(mean_level="batch", std_level="batch", std_unbiased=True)
adv_norm = Normalization(config)
advantages = torch.full((4, 2), 5.0, dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Should handle zero variance gracefully without NaN or inf
assert torch.isfinite(normalized).all()
# With zero variance, result should be zeros (after mean subtraction)
assert torch.allclose(normalized, torch.zeros_like(advantages), atol=1e-6)
def test_mask_edge_cases():
"""Test edge cases with loss masks."""
config = NormConfig(
mean_level="batch", std_level="batch", mean_leave1out=True, std_unbiased=True
)
adv_norm = Normalization(config)
# Test with all elements masked out except one
advantages = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=torch.float32)
loss_mask = torch.tensor([[1.0, 0.0], [0.0, 0.0], [0.0, 0.0]], dtype=torch.float32)
normalized = adv_norm(advantages, loss_mask)
assert torch.isfinite(normalized).all()
# With single effective element, leave-one-out mean is 0, std is 1 (for stability)
# So result should be approximately (original_value - 0) / 1 = original_value
assert torch.allclose(normalized[0, 0], torch.tensor(1.0), atol=1e-4)
# Test with no elements masked (all zeros mask)
loss_mask = torch.zeros_like(advantages)
normalized = adv_norm(advantages, loss_mask)
assert torch.allclose(normalized, advantages) # Should return original values
def test_mixed_normalization_with_new_options():
"""Test mixed normalization levels with new options."""
# Batch mean + Group std + both new options
config = NormConfig(
mean_level="batch",
std_level="group",
group_size=2,
mean_leave1out=True,
std_unbiased=True,
)
adv_norm = Normalization(config)
advantages = torch.tensor(
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], dtype=torch.float32
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
assert normalized.shape == advantages.shape
assert torch.isfinite(normalized).all()
assert not torch.allclose(normalized, advantages)
# Group mean + Batch std + both new options
config = NormConfig(
mean_level="group",
std_level="batch",
group_size=2,
mean_leave1out=True,
std_unbiased=True,
)
adv_norm = Normalization(config)
normalized = adv_norm(advantages, loss_mask)
assert normalized.shape == advantages.shape
assert torch.isfinite(normalized).all()
def test_group_size_edge_cases():
"""Test edge cases with group sizes."""
# Group size equals batch size
config = NormConfig(
mean_level="group",
std_level="group",
group_size=4,
mean_leave1out=True,
std_unbiased=True,
)
adv_norm = Normalization(config)
advantages = torch.tensor(
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], dtype=torch.float32
)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
assert normalized.shape == advantages.shape
assert torch.isfinite(normalized).all()
# Group size of 1 (each element is its own group)
config = NormConfig(
mean_level="group",
std_level="group",
group_size=1,
mean_leave1out=True,
std_unbiased=True,
)
adv_norm = Normalization(config)
normalized = adv_norm(advantages, loss_mask)
# With group size 1 and leave-one-out, each element should remain approximately unchanged
# because mean=0 (no other elements) and std=1 (for stability), so result ≈ (x-0)/1 = x
assert torch.allclose(
normalized, advantages, atol=1e-3
) # Should remain approximately unchanged
def test_precision_and_numerical_stability():
"""Test numerical stability with extreme values."""
config = NormConfig(
mean_level="batch", std_level="batch", mean_leave1out=True, std_unbiased=True
)
adv_norm = Normalization(config)
# Test with very large values
advantages = torch.tensor([[1e6, 2e6], [3e6, 4e6]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
assert torch.isfinite(normalized).all()
assert not torch.isnan(normalized).any()
# Test with very small values
advantages = torch.tensor([[1e-6, 2e-6], [3e-6, 4e-6]], dtype=torch.float32)
normalized = adv_norm(advantages, loss_mask)
assert torch.isfinite(normalized).all()
assert not torch.isnan(normalized).any()
# Test with mixed sign values
advantages = torch.tensor([[-1e3, 1e3], [-2e3, 2e3]], dtype=torch.float32)
normalized = adv_norm(advantages, loss_mask)
assert torch.isfinite(normalized).all()
def test_distributed_simulation():
"""Test behavior that simulates distributed training scenarios."""
config = NormConfig(
mean_level="batch", std_level="batch", mean_leave1out=True, std_unbiased=True
)
adv_norm = Normalization(config)
# Simulate multiple workers with different data
advantages_worker1 = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32)
advantages_worker2 = torch.tensor([[5.0, 6.0], [7.0, 8.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages_worker1)
# Test each worker independently (simulating before all_reduce)
normalized1 = adv_norm(advantages_worker1, loss_mask)
normalized2 = adv_norm(advantages_worker2, loss_mask)
assert torch.isfinite(normalized1).all()
assert torch.isfinite(normalized2).all()
# Test combined data (simulating after all_reduce)
advantages_combined = torch.cat([advantages_worker1, advantages_worker2], dim=0)
loss_mask_combined = torch.ones_like(advantages_combined)
normalized_combined = adv_norm(advantages_combined, loss_mask_combined)
assert torch.isfinite(normalized_combined).all()
def test_leave_one_out_mathematical_consistency():
"""Test mathematical consistency of leave-one-out implementation."""
config = NormConfig(mean_level="batch", std_level=None, mean_leave1out=True)
adv_norm = Normalization(config)
# Test with known values where we can verify manually
advantages = torch.tensor([[10.0], [20.0], [30.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
normalized = adv_norm(advantages, loss_mask)
# Manual calculation:
# For 10.0: leave-one-out mean = (20+30)/2 = 25, result = 10-25 = -15
# For 20.0: leave-one-out mean = (10+30)/2 = 20, result = 20-20 = 0
# For 30.0: leave-one-out mean = (10+20)/2 = 15, result = 30-15 = 15
expected = torch.tensor([[-15.0], [0.0], [15.0]], dtype=torch.float32)
assert torch.allclose(normalized, expected, atol=1e-5)
def test_unbiased_std_mathematical_consistency():
"""Test mathematical consistency of unbiased std implementation."""
# Test with a simple case where we can verify the math
advantages = torch.tensor([[0.0], [1.0], [2.0]], dtype=torch.float32)
loss_mask = torch.ones_like(advantages)
# Biased version
config_biased = NormConfig(
mean_level="batch", std_level="batch", std_unbiased=False
)
adv_norm_biased = Normalization(config_biased)
normalized_biased = adv_norm_biased(advantages, loss_mask)
# Unbiased version
config_unbiased = NormConfig(
mean_level="batch", std_level="batch", std_unbiased=True
)
adv_norm_unbiased = Normalization(config_unbiased)
normalized_unbiased = adv_norm_unbiased(advantages, loss_mask)
# Manual calculation:
# Mean = 1.0, deviations = [-1, 0, 1]
# Biased variance = (1+0+1)/3 = 2/3, std = sqrt(2/3)
# Unbiased variance = (1+0+1)/2 = 1, std = 1
# Biased normalization: x / sqrt(2/3) -> scales by sqrt(3/2)
# Unbiased normalization: x / 1 -> no additional scaling
# Ratio of result stds = sqrt(3/2) / 1 = sqrt(3/2)
ratio = torch.std(normalized_biased) / torch.std(normalized_unbiased)
expected_ratio = torch.sqrt(torch.tensor(3.0 / 2.0))
assert torch.allclose(ratio, expected_ratio, atol=1e-5)
def test_comprehensive_option_combinations():
"""Test all combinations of normalization options comprehensively."""
test_cases = [
# (mean_level, std_level, group_size, mean_leave1out, std_unbiased)
("batch", "batch", 1, True, True),
("batch", "group", 2, True, False),
("group", "batch", 2, False, True),
("group", "group", 2, True, True),
(None, "batch", 1, True, True),