File size: 11,145 Bytes
ebe598e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script for the improved push_to_huggingface.py script
"""

import os
import sys
import tempfile
import json
from pathlib import Path
from unittest.mock import patch, MagicMock

def test_huggingface_pusher_initialization():
    """Test HuggingFacePusher initialization with new parameters"""
    print("πŸ§ͺ Testing HuggingFacePusher initialization...")
    
    try:
        from scripts.model_tonic.push_to_huggingface import HuggingFacePusher
        
        # Test 1: Default initialization
        print("\n1. Testing default initialization...")
        with patch('push_to_huggingface.HfApi'):
            pusher = HuggingFacePusher(
                model_path="/tmp/test_model",
                repo_name="test-user/test-model"
            )
            print(f"   Dataset repo: {pusher.dataset_repo}")
            print(f"   HF token set: {'Yes' if pusher.hf_token else 'No'}")
        
        # Test 2: Custom initialization
        print("\n2. Testing custom initialization...")
        with patch('push_to_huggingface.HfApi'):
            pusher = HuggingFacePusher(
                model_path="/tmp/test_model",
                repo_name="test-user/test-model",
                dataset_repo="test-user/test-experiments",
                hf_token="test_token_123"
            )
            print(f"   Dataset repo: {pusher.dataset_repo}")
            print(f"   HF token set: {'Yes' if pusher.hf_token else 'No'}")
        
        # Test 3: Environment variable initialization
        print("\n3. Testing environment variable initialization...")
        with patch.dict(os.environ, {
            'HF_TOKEN': 'env_test_token',
            'TRACKIO_DATASET_REPO': 'env-user/env-dataset'
        }), patch('push_to_huggingface.HfApi'):
            pusher = HuggingFacePusher(
                model_path="/tmp/test_model",
                repo_name="test-user/test-model"
            )
            print(f"   Dataset repo: {pusher.dataset_repo}")
            print(f"   HF token set: {'Yes' if pusher.hf_token else 'No'}")
        
        print("βœ… HuggingFacePusher initialization tests passed!")
        return True
        
    except Exception as e:
        print(f"❌ Failed to test HuggingFacePusher initialization: {e}")
        return False

def test_model_card_creation():
    """Test model card creation with HF Datasets integration"""
    print("\nπŸ§ͺ Testing model card creation...")
    
    try:
        from scripts.model_tonic.push_to_huggingface import HuggingFacePusher
        
        with patch('push_to_huggingface.HfApi'):
            pusher = HuggingFacePusher(
                model_path="/tmp/test_model",
                repo_name="test-user/test-model",
                dataset_repo="test-user/test-experiments"
            )
            
            training_config = {
                "model_name": "HuggingFaceTB/SmolLM3-3B",
                "batch_size": 8,
                "learning_rate": 1e-5
            }
            
            results = {
                "final_loss": 0.5,
                "total_steps": 1000,
                "training_time_hours": 2.5
            }
            
            model_card = pusher.create_model_card(training_config, results)
            
            # Check that dataset repository is included
            if "test-user/test-experiments" in model_card:
                print("βœ… Dataset repository included in model card")
            else:
                print("❌ Dataset repository not found in model card")
                return False
            
            # Check that experiment tracking section is included
            if "Experiment Tracking" in model_card:
                print("βœ… Experiment tracking section included")
            else:
                print("❌ Experiment tracking section not found")
                return False
            
            print("βœ… Model card creation tests passed!")
            return True
            
    except Exception as e:
        print(f"❌ Failed to test model card creation: {e}")
        return False

def test_logging_integration():
    """Test logging integration with HF Datasets"""
    print("\nπŸ§ͺ Testing logging integration...")
    
    try:
        from scripts.model_tonic.push_to_huggingface import HuggingFacePusher
        
        with patch('push_to_huggingface.HfApi'), patch('push_to_huggingface.SmolLM3Monitor') as mock_monitor:
            # Create mock monitor
            mock_monitor_instance = MagicMock()
            mock_monitor.return_value = mock_monitor_instance
            
            pusher = HuggingFacePusher(
                model_path="/tmp/test_model",
                repo_name="test-user/test-model",
                dataset_repo="test-user/test-experiments",
                hf_token="test_token_123"
            )
            
            # Test logging
            details = {
                "model_path": "/tmp/test_model",
                "repo_name": "test-user/test-model"
            }
            
            pusher.log_to_trackio("model_push", details)
            
            # Check that monitor methods were called
            if mock_monitor_instance.log_metrics.called:
                print("βœ… Log metrics called")
            else:
                print("❌ Log metrics not called")
                return False
            
            if mock_monitor_instance.log_training_summary.called:
                print("βœ… Log training summary called")
            else:
                print("❌ Log training summary not called")
                return False
            
            print("βœ… Logging integration tests passed!")
            return True
            
    except Exception as e:
        print(f"❌ Failed to test logging integration: {e}")
        return False

def test_argument_parsing():
    """Test command line argument parsing"""
    print("\nπŸ§ͺ Testing argument parsing...")
    
    try:
        from scripts.model_tonic.push_to_huggingface import parse_args
        
        # Test with new arguments
        test_args = [
            "push_to_huggingface.py",
            "/tmp/test_model",
            "test-user/test-model",
            "--dataset-repo", "test-user/test-experiments",
            "--hf-token", "test_token_123",
            "--private"
        ]
        
        with patch('sys.argv', test_args):
            args = parse_args()
            
            print(f"   Model path: {args.model_path}")
            print(f"   Repo name: {args.repo_name}")
            print(f"   Dataset repo: {args.dataset_repo}")
            print(f"   HF token: {'Set' if args.hf_token else 'Not set'}")
            print(f"   Private: {args.private}")
            
            if args.dataset_repo == "test-user/test-experiments":
                print("βœ… Dataset repo argument parsed correctly")
            else:
                print("❌ Dataset repo argument not parsed correctly")
                return False
            
            if args.hf_token == "test_token_123":
                print("βœ… HF token argument parsed correctly")
            else:
                print("❌ HF token argument not parsed correctly")
                return False
            
            print("βœ… Argument parsing tests passed!")
            return True
            
    except Exception as e:
        print(f"❌ Failed to test argument parsing: {e}")
        return False

def test_environment_variable_handling():
    """Test environment variable handling"""
    print("\nπŸ§ͺ Testing environment variable handling...")
    
    try:
        from scripts.model_tonic.push_to_huggingface import HuggingFacePusher
        
        # Test with environment variables set
        with patch.dict(os.environ, {
            'HF_TOKEN': 'env_test_token',
            'TRACKIO_DATASET_REPO': 'env-user/env-dataset'
        }), patch('push_to_huggingface.HfApi'):
            pusher = HuggingFacePusher(
                model_path="/tmp/test_model",
                repo_name="test-user/test-model"
            )
            
            print(f"   Dataset repo: {pusher.dataset_repo}")
            print(f"   HF token: {'Set' if pusher.hf_token else 'Not set'}")
            
            if pusher.dataset_repo == "env-user/env-dataset":
                print("βœ… Environment variable for dataset repo used")
            else:
                print("❌ Environment variable for dataset repo not used")
                return False
            
            if pusher.hf_token == "env_test_token":
                print("βœ… Environment variable for HF token used")
            else:
                print("❌ Environment variable for HF token not used")
                return False
        
        print("βœ… Environment variable tests passed!")
        return True
        
    except Exception as e:
        print(f"❌ Failed to test environment variables: {e}")
        return False

def main():
    """Run all tests"""
    print("πŸš€ Testing Improved Push Script")
    print("=" * 50)
    
    tests = [
        ("HuggingFacePusher Initialization", test_huggingface_pusher_initialization),
        ("Model Card Creation", test_model_card_creation),
        ("Logging Integration", test_logging_integration),
        ("Argument Parsing", test_argument_parsing),
        ("Environment Variables", test_environment_variable_handling)
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\nπŸ”§ Running: {test_name}")
        try:
            if test_func():
                print(f"βœ… {test_name}: PASSED")
                passed += 1
            else:
                print(f"❌ {test_name}: FAILED")
        except Exception as e:
            print(f"❌ {test_name}: ERROR - {e}")
    
    print(f"\nπŸ“Š Test Results")
    print("=" * 30)
    print(f"Passed: {passed}/{total}")
    print(f"Failed: {total - passed}/{total}")
    
    if passed == total:
        print("πŸŽ‰ All tests passed! Push script is working correctly.")
        print("\nπŸ“‹ New Features:")
        print("βœ… HF Datasets integration")
        print("βœ… Environment variable support")
        print("βœ… Enhanced model card creation")
        print("βœ… Improved logging to HF Datasets")
        print("βœ… Better argument parsing")
        print("βœ… Dataset repository tracking")
    else:
        print("⚠️  Some tests failed. Check the logs above for details.")
    
    print(f"\nπŸ“‹ Usage Examples:")
    print("Basic usage:")
    print("  python push_to_huggingface.py /path/to/model username/repo-name")
    print("\nWith HF Datasets:")
    print("  python push_to_huggingface.py /path/to/model username/repo-name --dataset-repo username/experiments")
    print("\nWith custom token:")
    print("  python push_to_huggingface.py /path/to/model username/repo-name --hf-token your_token_here")
    print("\nWith all options:")
    print("  python push_to_huggingface.py /path/to/model username/repo-name --dataset-repo username/experiments --hf-token your_token_here --private")

if __name__ == "__main__":
    main()