File size: 15,079 Bytes
24c2665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
TTRLVR + AZR ํ™˜๊ฒฝ ๊ฒ€์ฆ ์Šคํฌ๋ฆฝํŠธ

์‹ค์ œ ์‹คํ–‰ ํ™˜๊ฒฝ์—์„œ ํ•„์š”ํ•œ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์„ค์ •๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค:
1. Python ํŒจํ‚ค์ง€ ๋ฐ ๋ฒ„์ „ ํ™•์ธ
2. GPU ๋ฐ CUDA ํ™˜๊ฒฝ ํ™•์ธ  
3. ํŒŒ์ผ ๊ฒฝ๋กœ ๋ฐ ๊ถŒํ•œ ํ™•์ธ
4. ๋ชจ๋ธ ๋กœ๋”ฉ ํ…Œ์ŠคํŠธ
5. AZR ์„ค์ • ํŒŒ์ผ ๊ฒ€์ฆ
6. ๊ฐ„๋‹จํ•œ ํŒŒ์ดํ”„๋ผ์ธ ์‹คํ–‰ ํ…Œ์ŠคํŠธ
"""

import os
import sys
import json
import subprocess
import tempfile
import traceback
from pathlib import Path
from datetime import datetime

# ๊ฒฝ๋กœ ์„ค์ •
sys.path.append('/home/ubuntu/RLVR/TestTime-RLVR-v2')

class EnvironmentValidator:
    """ํ™˜๊ฒฝ ๊ฒ€์ฆ ํด๋ž˜์Šค"""
    
    def __init__(self):
        self.results = {
            'timestamp': datetime.now().isoformat(),
            'tests': {},
            'overall_success': False,
            'recommendations': []
        }
        
    def log_test(self, test_name: str, success: bool, message: str, details: str = None):
        """ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ ๋กœ๊น…"""
        
        status = "โœ… PASS" if success else "โŒ FAIL"
        print(f"{status} {test_name}: {message}")
        
        if details:
            print(f"   Details: {details}")
            
        self.results['tests'][test_name] = {
            'success': success,
            'message': message,
            'details': details
        }
        
        if not success:
            print()
    
    def add_recommendation(self, recommendation: str):
        """๊ถŒ์žฅ์‚ฌํ•ญ ์ถ”๊ฐ€"""
        self.results['recommendations'].append(recommendation)
        print(f"๐Ÿ’ก Recommendation: {recommendation}")
    
    def test_python_packages(self):
        """Python ํŒจํ‚ค์ง€ ํ™•์ธ"""
        
        required_packages = {
            'torch': '2.0.0',
            'transformers': '4.30.0', 
            'pandas': '1.5.0',
            'numpy': '1.21.0',
            'vllm': '0.3.0'
        }
        
        missing_packages = []
        version_issues = []
        
        for package, min_version in required_packages.items():
            try:
                if package == 'vllm':
                    # vLLM์€ ์„ ํƒ์  ํŒจํ‚ค์ง€
                    try:
                        import vllm
                        version = vllm.__version__
                    except ImportError:
                        self.add_recommendation(f"Consider installing vLLM for better GPU performance: pip install vllm")
                        continue
                else:
                    exec(f"import {package}")
                    version = eval(f"{package}.__version__")
                
                # ๋ฒ„์ „ ๋น„๊ต๋Š” ๊ฐ„๋‹จํžˆ ๋ฌธ์ž์—ด๋กœ (์ •ํ™•ํ•œ ๋น„๊ต๋Š” packaging ๋ชจ๋“ˆ ํ•„์š”)
                if version < min_version:
                    version_issues.append(f"{package}: {version} < {min_version}")
                    
            except ImportError:
                missing_packages.append(package)
            except Exception as e:
                version_issues.append(f"{package}: Error checking version - {e}")
        
        if missing_packages:
            self.log_test(
                "Python Packages", 
                False, 
                f"Missing packages: {', '.join(missing_packages)}",
                f"Install with: pip install {' '.join(missing_packages)}"
            )
            return False
        elif version_issues:
            self.log_test(
                "Python Packages",
                False,
                f"Version issues: {', '.join(version_issues)}",
                "Update packages to meet minimum requirements"
            )
            return False
        else:
            self.log_test("Python Packages", True, "All required packages installed")
            return True
    
    def test_gpu_environment(self):
        """GPU ๋ฐ CUDA ํ™˜๊ฒฝ ํ™•์ธ"""
        
        try:
            import torch
            
            # CUDA ์‚ฌ์šฉ ๊ฐ€๋Šฅ์„ฑ ํ™•์ธ
            if not torch.cuda.is_available():
                self.log_test("GPU Environment", False, "CUDA not available")
                self.add_recommendation("Install CUDA toolkit and PyTorch with CUDA support")
                return False
            
            # GPU ๊ฐœ์ˆ˜ ๋ฐ ๋ฉ”๋ชจ๋ฆฌ ํ™•์ธ
            gpu_count = torch.cuda.device_count()
            current_device = torch.cuda.current_device()
            device_name = torch.cuda.get_device_name(current_device)
            
            # ๋ฉ”๋ชจ๋ฆฌ ์ •๋ณด
            memory_allocated = torch.cuda.memory_allocated() / 1024**3  # GB
            memory_reserved = torch.cuda.memory_reserved() / 1024**3   # GB
            memory_total = torch.cuda.get_device_properties(current_device).total_memory / 1024**3  # GB
            
            details = f"GPUs: {gpu_count}, Current: {device_name}, Memory: {memory_total:.1f}GB total, {memory_reserved:.1f}GB reserved"
            
            if memory_total < 8.0:  # 8GB ๋ฏธ๋งŒ
                self.log_test("GPU Environment", False, f"GPU memory insufficient: {memory_total:.1f}GB", details)
                self.add_recommendation("Use a GPU with at least 8GB VRAM for 7B models")
                return False
            
            self.log_test("GPU Environment", True, f"GPU environment ready", details)
            return True
            
        except Exception as e:
            self.log_test("GPU Environment", False, f"Error checking GPU: {e}")
            return False
    
    def test_file_paths_and_permissions(self):
        """ํŒŒ์ผ ๊ฒฝ๋กœ ๋ฐ ๊ถŒํ•œ ํ™•์ธ"""
        
        critical_paths = {
            '/home/ubuntu/RLVR/TestTime-RLVR-v2': 'Main project directory',
            '/home/ubuntu/RLVR/TestTime-RLVR-v2/test/configs/ttrlvr_azr_7b_single_gpu.sh': 'AZR config script',
            '/data/RLVR/checkpoints': 'Checkpoint directory (will be created)',
            '/tmp': 'Temporary directory'
        }
        
        issues = []
        
        for path, description in critical_paths.items():
            if not os.path.exists(path):
                if 'checkpoints' in path:
                    # ์ฒดํฌํฌ์ธํŠธ ๋””๋ ‰ํ† ๋ฆฌ๋Š” ์ƒ์„ฑ ์‹œ๋„
                    try:
                        os.makedirs(path, exist_ok=True)
                        self.log_test(f"Path: {description}", True, f"Created directory: {path}")
                    except Exception as e:
                        issues.append(f"{description}: Cannot create {path} - {e}")
                else:
                    issues.append(f"{description}: Not found - {path}")
            else:
                # ์ฝ๊ธฐ/์“ฐ๊ธฐ ๊ถŒํ•œ ํ™•์ธ
                readable = os.access(path, os.R_OK)
                writable = os.access(path, os.W_OK)
                
                if not readable:
                    issues.append(f"{description}: No read permission - {path}")
                elif os.path.isdir(path) and not writable:
                    issues.append(f"{description}: No write permission - {path}")
                else:
                    self.log_test(f"Path: {description}", True, f"Accessible: {path}")
        
        if issues:
            self.log_test("File Paths", False, f"{len(issues)} path issues", "; ".join(issues))
            return False
        else:
            self.log_test("File Paths", True, "All critical paths accessible")
            return True
    
    def test_model_loading(self):
        """๋ชจ๋ธ ๋กœ๋”ฉ ํ…Œ์ŠคํŠธ (๊ฐ„๋‹จํ•œ ํ™•์ธ)"""
        
        try:
            # ๋น ๋ฅธ ํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•ด transformers ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋งŒ ํ™•์ธ
            from transformers import AutoTokenizer
            
            # ์‹ค์ œ ๋ชจ๋ธ ๋กœ๋”ฉ ๋Œ€์‹  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ธฐ๋Šฅ๋งŒ ํ…Œ์ŠคํŠธ
            self.log_test("Model Loading", True, "Transformers library available for model loading")
            self.add_recommendation("Model loading test skipped to avoid timeout. Run full model test separately if needed.")
            return True
                
        except Exception as e:
            self.log_test("Model Loading", False, f"Failed to import transformers: {e}")
            self.add_recommendation("Install transformers library: pip install transformers")
            return False
    
    def test_azr_config(self):
        """AZR ์„ค์ • ํŒŒ์ผ ๊ฒ€์ฆ"""
        
        config_path = '/home/ubuntu/RLVR/TestTime-RLVR-v2/test/configs/ttrlvr_azr_7b_single_gpu.sh'
        
        try:
            if not os.path.exists(config_path):
                self.log_test("AZR Config", False, f"Config file not found: {config_path}")
                return False
            
            # ์Šคํฌ๋ฆฝํŠธ ์‹คํ–‰ ๊ถŒํ•œ ํ™•์ธ
            if not os.access(config_path, os.X_OK):
                self.log_test("AZR Config", False, f"Config file not executable: {config_path}")
                self.add_recommendation(f"Make config executable: chmod +x {config_path}")
                return False
            
            # ์„ค์ • ํŒŒ์ผ ๋‚ด์šฉ ๊ธฐ๋ณธ ๊ฒ€์ฆ
            with open(config_path, 'r') as f:
                content = f.read()
                
            required_settings = [
                'trainer.project_name=ttrlvr_azr',
                'azr.train_propose=False',
                'data.train_batch_size=8',
                'actor_rollout_ref.actor.ppo_mini_batch_size=24'
            ]
            
            missing_settings = []
            for setting in required_settings:
                if setting not in content:
                    missing_settings.append(setting)
            
            if missing_settings:
                self.log_test(
                    "AZR Config", 
                    False, 
                    f"Missing settings: {', '.join(missing_settings)}",
                    f"Check config file: {config_path}"
                )
                return False
            
            self.log_test("AZR Config", True, f"Config file validated: {config_path}")
            return True
            
        except Exception as e:
            self.log_test("AZR Config", False, f"Error validating config: {e}")
            return False
    
    def test_simple_pipeline(self):
        """๊ฐ„๋‹จํ•œ ํŒŒ์ดํ”„๋ผ์ธ ์‹คํ–‰ ํ…Œ์ŠคํŠธ"""
        
        try:
            from absolute_zero_reasoner.testtime.config import TestTimeConfig
            from absolute_zero_reasoner.testtime.logger import TestTimeLogger
            from absolute_zero_reasoner.testtime.task_generator import TestTimeTaskGenerator
            
            # ๊ธฐ๋ณธ ์„ค์ • ์ƒ์„ฑ
            config = TestTimeConfig()
            config.model_name = "Qwen/Qwen2.5-7B"
            logger = TestTimeLogger()
            
            # Task Generator ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
            task_generator = TestTimeTaskGenerator(config, logger)
            
            # ํ…Œ์ŠคํŠธ์šฉ IPO ํŠธ๋ฆฌํ”Œ
            test_ipo_triples = [
                {
                    'id': 'test_triple_0',
                    'input': '[1, 2, 3]',
                    'actual_output': '[2, 4, 6]',
                    'program': 'def test_func(lst):\n    return [x * 2 for x in lst]',
                    'full_input_str': 'test_func([1, 2, 3])',
                    'source_program_id': 'program_0',
                    'ipo_index': 0
                }
            ]
            
            # Task ์ƒ์„ฑ ํ…Œ์ŠคํŠธ
            tasks = task_generator.generate_tasks(test_ipo_triples, "TestProblem", 1)
            
            # ๊ฒฐ๊ณผ ๊ฒ€์ฆ
            if not tasks or not any(len(task_list) > 0 for task_list in tasks.values()):
                self.log_test("Simple Pipeline", False, "No tasks generated")
                return False
            
            # AZR ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ํ™•์ธ
            for task_type, task_list in tasks.items():
                if task_list:
                    task = task_list[0]
                    required_fields = ['uid', 'ipo_group_id', 'basic_accuracy', 'ground_truth']
                    missing_fields = [field for field in required_fields if field not in task]
                    
                    if missing_fields:
                        self.log_test(
                            "Simple Pipeline", 
                            False, 
                            f"Missing AZR metadata: {missing_fields}"
                        )
                        return False
            
            total_tasks = sum(len(task_list) for task_list in tasks.values())
            self.log_test("Simple Pipeline", True, f"Generated {total_tasks} tasks successfully")
            return True
            
        except Exception as e:
            self.log_test("Simple Pipeline", False, f"Pipeline test failed: {e}")
            return False
    
    def run_all_tests(self):
        """๋ชจ๋“  ํ…Œ์ŠคํŠธ ์‹คํ–‰"""
        
        print("๐Ÿ” TTRLVR + AZR ํ™˜๊ฒฝ ๊ฒ€์ฆ ์‹œ์ž‘")
        print("=" * 60)
        
        tests = [
            self.test_python_packages,
            self.test_gpu_environment, 
            self.test_file_paths_and_permissions,
            self.test_model_loading,
            self.test_azr_config,
            self.test_simple_pipeline
        ]
        
        passed_tests = 0
        total_tests = len(tests)
        
        for test in tests:
            try:
                if test():
                    passed_tests += 1
                print()  # ๋นˆ ์ค„ ์ถ”๊ฐ€
            except Exception as e:
                print(f"โŒ Test {test.__name__} crashed: {e}")
                print(f"   Traceback: {traceback.format_exc()}")
                print()
        
        # ์ตœ์ข… ๊ฒฐ๊ณผ
        success_rate = passed_tests / total_tests * 100
        self.results['overall_success'] = passed_tests == total_tests
        
        print("=" * 60)
        print("๐Ÿ“Š ํ™˜๊ฒฝ ๊ฒ€์ฆ ๊ฒฐ๊ณผ:")
        print(f"   - ํ†ต๊ณผํ•œ ํ…Œ์ŠคํŠธ: {passed_tests}/{total_tests} ({success_rate:.1f}%)")
        
        if self.results['recommendations']:
            print(f"\n๐Ÿ’ก ๊ถŒ์žฅ์‚ฌํ•ญ ({len(self.results['recommendations'])}๊ฐœ):")
            for i, rec in enumerate(self.results['recommendations'], 1):
                print(f"   {i}. {rec}")
        
        if self.results['overall_success']:
            print("\n๐ŸŽ‰ ํ™˜๊ฒฝ ๊ฒ€์ฆ ์™„๋ฃŒ! TTRLVR + AZR ์‹คํ–‰ ์ค€๋น„๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        else:
            print(f"\nโš ๏ธ ํ™˜๊ฒฝ ๊ฒ€์ฆ ์‹คํŒจ: {total_tests - passed_tests}๊ฐœ ํ…Œ์ŠคํŠธ ์‹คํŒจ")
            print("   ์œ„์˜ ๊ถŒ์žฅ์‚ฌํ•ญ์„ ์ฐธ๊ณ ํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•˜์„ธ์š”.")
        
        return self.results


def main():
    """๋ฉ”์ธ ์‹คํ–‰ ํ•จ์ˆ˜"""
    
    validator = EnvironmentValidator()
    results = validator.run_all_tests()
    
    # ๊ฒฐ๊ณผ๋ฅผ ํŒŒ์ผ๋กœ ์ €์žฅ
    output_file = f"/tmp/ttrlvr_azr_validation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    with open(output_file, 'w') as f:
        json.dump(results, f, indent=2)
    
    print(f"\n๐Ÿ“„ ์ƒ์„ธ ๊ฒฐ๊ณผ ์ €์žฅ: {output_file}")
    
    return 0 if results['overall_success'] else 1


if __name__ == '__main__':
    sys.exit(main())