Repository navigation
Expand file tree
/
Copy pathtest_batch_size_fix.py
More file actions
143 lines (114 loc) · 4.64 KB
/
Copy pathtest_batch_size_fix.py
File metadata and controls
143 lines (114 loc) · 4.64 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script for batch size fix
Verify that batch size of 1 does not produce empty tensors
"""
import sys
import os
import torch
import numpy as np
# Add current directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
def test_concatenated_inputs():
"""Test concatenated_inputs function"""
print("🧪 Testing concatenated_inputs function...")
try:
from trainers import concatenated_inputs
# Create test batch
pad_token_id = 42
batch = {
'chosen_input_ids': torch.randint(0, 1000, (2, 10)),
'rejected_input_ids': torch.randint(0, 1000, (2, 8)),
'chosen_attention_mask': torch.ones(2, 10, dtype=torch.long),
'rejected_attention_mask': torch.ones(2, 8, dtype=torch.long),
}
# Test normal case
print("Testing normal batch...")
result = concatenated_inputs(batch, pad_token_id=pad_token_id)
print(f"✅ Normal batch test passed")
print(f"Result shape: {result['concatenated_input_ids'].shape}")
# Verify padding semantics: wherever attention_mask == 0, input_ids should equal pad_token_id
if 'concatenated_attention_mask' in result:
pad_positions = (result['concatenated_attention_mask'] == 0)
if pad_positions.any():
padded_ids = result['concatenated_input_ids'][pad_positions]
if not torch.all(padded_ids == pad_token_id):
print("❌ Padding value mismatch: input_ids not padded with pad_token_id")
return False
# Test empty batch (should raise exception)
print("Testing empty batch...")
empty_batch = {
'chosen_input_ids': torch.empty(0, 0, dtype=torch.long),
'rejected_input_ids': torch.empty(0, 0, dtype=torch.long),
'chosen_attention_mask': torch.empty(0, 0, dtype=torch.long),
'rejected_attention_mask': torch.empty(0, 0, dtype=torch.long)
}
try:
result = concatenated_inputs(empty_batch, pad_token_id=pad_token_id)
print("❌ Empty batch test failed - should raise exception")
return False
except Exception as e:
print(f"✅ Empty batch test passed - correctly raised exception: {e}")
return True
except Exception as e:
print(f"❌ concatenated_inputs test failed: {e}")
return False
def test_batch_iterator():
"""Test batch iterator with small batch size"""
print("\n🧪 Testing batch iterator with small batch size...")
try:
from preference_datasets import get_batch_iterator
# Simulate dataset with small batch size
dataset = [
{'chosen': 'Hello world', 'rejected': 'Hi there'},
{'chosen': 'Good morning', 'rejected': 'Morning'},
{'chosen': 'How are you', 'rejected': 'How do you do'},
{'chosen': 'Nice to meet you', 'rejected': 'Pleased to meet you'}
]
# Test with batch_size=1
batch_size = 1
iterator = get_batch_iterator(dataset, batch_size)
batch_count = 0
for batch in iterator:
batch_count += 1
print(f"Batch {batch_count}: {batch['chosen_input_ids'].shape}")
# Verify batch is not empty
if batch['chosen_input_ids'].shape[0] == 0:
print(f"❌ Batch {batch_count} is empty")
return False
print(f"✅ Batch iterator test passed, processed {batch_count} batches")
return True
except Exception as e:
print(f"❌ Batch iterator test failed: {e}")
return False
def main():
"""Main test function"""
print("🚀 Batch Size Fix Test")
print("=" * 50)
# Run all tests
tests = [
test_concatenated_inputs,
test_batch_iterator,
]
results = []
for test in tests:
try:
result = test()
results.append(result)
except Exception as e:
print(f"❌ Test execution failed: {e}")
results.append(False)
# Summary
print("\n" + "=" * 50)
print("📊 Test Results Summary:")
passed = sum(results)
total = len(results)
print(f"Passed tests: {passed}/{total}")
if passed == total:
print("🎉 All tests passed! Batch size fix is working correctly!")
else:
print("⚠️ Some tests failed, please check the implementation")
return passed == total
if __name__ == "__main__":
main()