File size: 13,944 Bytes
af2c3f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Benchmarking Agent - Tests model performance with real inference
"""

import torch
import time
import asyncio
import numpy as np
from transformers import (
    AutoModelForSequenceClassification, 
    AutoTokenizer, 
    pipeline,
    AutoModelForCausalLM
)
from typing import List, Dict, Any, Optional

from src.models.schemas import (
    TaskType, UserRequirements, BenchmarkResult
)


class BenchmarkingAgent:
    """
    Benchmarks models with real inference tests to measure latency and memory usage.
    
    This agent loads each model, runs warmup inferences, then measures
    performance over multiple iterations.
    """
    
    def __init__(self, sample_data: Dict[str, Any] = None):
        self.sample_data = sample_data or self._get_default_samples()
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print(f"   Using device: {self.device}")
    
    async def benchmark_models(self, 
                              model_ids: List[str], 
                              task_type: TaskType,
                              requirements: UserRequirements,
                              max_models: int = 3) -> List[BenchmarkResult]:
        """
        Benchmark top models with quick inference tests.
        
        Args:
            model_ids: List of model IDs to benchmark
            task_type: Type of ML task
            requirements: User requirements
            max_models: Maximum number of models to benchmark
            
        Returns:
            List of BenchmarkResult objects
        """
        results = []
        
        print(f"   Benchmarking up to {max_models} models...")
        
        for i, model_id in enumerate(model_ids[:max_models]):
            print(f"    Testing {i+1}/{min(len(model_ids), max_models)}: {model_id}")
            
            try:
                result = await self._benchmark_single_model(
                    model_id, task_type, requirements
                )
                results.append(result)
                
                if not result.error:
                    print(f"       Latency: {result.latency_ms:.2f}ms, "
                          f"Memory: {result.memory_usage_mb:.2f}MB")
                else:
                    print(f"       Error: {result.error}")
                    
            except Exception as e:
                print(f"       Failed: {e}")
                # FIXED: Added task_type to the error response
                results.append(BenchmarkResult(
                    model_id=model_id,
                    task_type=task_type,  # This was missing!
                    latency_ms=0,
                    memory_usage_mb=0,
                    error=str(e)
                ))
            
            # Small delay between models
            await asyncio.sleep(0.5)
        
        return results
    
    async def _benchmark_single_model(self, 
                                model_id: str,
                                task_type: TaskType,
                                requirements: UserRequirements) -> BenchmarkResult:
        """Benchmark a single model"""
        
        model = None
        tokenizer = None
        nlp_pipeline = None
        
        # Load model and tokenizer
        try:
            print(f"      Loading model...")
            
            if task_type == TaskType.TRANSLATION:
                # For translation models, we need to use pipeline with specific task format
                try:
                    # Try the standard translation pipeline first
                    nlp_pipeline = pipeline(
                        "translation",
                        model=model_id,
                        device=self.device
                    )
                except Exception as e:
                    # If that fails, try with specific language pair format
                    if requirements.translation_reqs:
                        src = requirements.translation_reqs.source_language.value
                        tgt = requirements.translation_reqs.target_language.value
                        task_name = f"translation_{src}_to_{tgt}"
                        try:
                            nlp_pipeline = pipeline(
                                task_name,
                                model=model_id,
                                device=self.device
                            )
                        except:
                            # If both fail, try loading as a general seq2seq model
                            from transformers import AutoModelForSeq2SeqLM
                            tokenizer = AutoTokenizer.from_pretrained(model_id)
                            model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
                
            elif task_type in [TaskType.TEXT_CLASSIFICATION, TaskType.NAMED_ENTITY_RECOGNITION]:
                tokenizer = AutoTokenizer.from_pretrained(model_id)
                model = AutoModelForSequenceClassification.from_pretrained(model_id)
                
            elif task_type == TaskType.TEXT_GENERATION:
                tokenizer = AutoTokenizer.from_pretrained(model_id)
                model = AutoModelForCausalLM.from_pretrained(model_id)
                
            else:
                # Use pipeline for other tasks
                nlp_pipeline = pipeline(
                    task_type.value,
                    model=model_id,
                    device=self.device
                )
                
        except Exception as e:
            return BenchmarkResult(
                model_id=model_id,
                task_type=task_type,
                latency_ms=0,
                memory_usage_mb=0,
                error=f"Failed to load model: {str(e)}"
            )
        
        # Move model to device
        if model:
            model.to(self.device)
            model.eval()
        
        # Get appropriate sample data
        sample = self._get_task_sample(task_type)
        
        # Run warmup (first inference is always slower)
        try:
            await self._run_warmup(model_id, task_type, sample, model, tokenizer, nlp_pipeline, requirements)
        except Exception as e:
            print(f"      Warmup warning: {e}")
        
        # Benchmark inference
        latencies = []
        memory_usage = []
        
        for i in range(5):  # Run 5 iterations for stable measurement
            # Reset memory stats if using CUDA
            if self.device.type == "cuda":
                torch.cuda.reset_peak_memory_stats()
                start_memory = torch.cuda.memory_allocated()
            
            start_time = time.perf_counter()
            
            # Run inference
            try:
                with torch.no_grad():
                    if task_type == TaskType.TRANSLATION and nlp_pipeline:
                        # For translation pipeline
                        result = nlp_pipeline(sample["text"], max_length=128)
                        
                    elif task_type == TaskType.TRANSLATION and model and tokenizer:
                        # For seq2seq model
                        inputs = tokenizer(
                            sample["text"], 
                            return_tensors="pt", 
                            truncation=True, 
                            max_length=128
                        ).to(self.device)
                        outputs = model.generate(**inputs, max_new_tokens=50)
                        
                    elif task_type == TaskType.TEXT_CLASSIFICATION and model and tokenizer:
                        inputs = tokenizer(
                            sample["text"], 
                            return_tensors="pt", 
                            truncation=True, 
                            max_length=128
                        ).to(self.device)
                        outputs = model(**inputs)
                        
                    elif task_type == TaskType.TEXT_GENERATION and model and tokenizer:
                        inputs = tokenizer(
                            sample["text"], 
                            return_tensors="pt", 
                            truncation=True
                        ).to(self.device)
                        outputs = model.generate(**inputs, max_new_tokens=20)
                        
                    elif nlp_pipeline:
                        result = nlp_pipeline(sample["text"])
                        
            except Exception as e:
                return BenchmarkResult(
                    model_id=model_id,
                    task_type=task_type,
                    latency_ms=0,
                    memory_usage_mb=0,
                    error=f"Inference failed: {str(e)}"
                )
            
            end_time = time.perf_counter()
            
            # Measure memory
            if self.device.type == "cuda":
                end_memory = torch.cuda.memory_allocated()
                peak_memory = torch.cuda.max_memory_allocated()
                memory_used = (peak_memory - start_memory) / (1024 ** 2)  # Convert to MB
                memory_usage.append(memory_used)
            
            latency_ms = (end_time - start_time) * 1000
            latencies.append(latency_ms)
            
            # Small delay between runs
            await asyncio.sleep(0.1)
        
        # Clean up
        if model:
            del model
        if tokenizer:
            del tokenizer
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        
        # Calculate statistics
        avg_latency = float(np.mean(latencies))
        avg_memory = float(np.mean(memory_usage)) if memory_usage else 0
        
        return BenchmarkResult(
            model_id=model_id,
            task_type=task_type,
            latency_ms=avg_latency,
            memory_usage_mb=avg_memory,
            throughput=1000 / avg_latency if avg_latency > 0 else 0
        )
    
    async def _run_warmup(self, model_id: str, task_type: TaskType, sample: Dict,
                     model=None, tokenizer=None, nlp_pipeline=None, requirements=None):
        """Run warmup inference to initialize model"""
        try:
            with torch.no_grad():
                if task_type == TaskType.TRANSLATION and nlp_pipeline:
                    nlp_pipeline(sample["text"], max_length=50)
                    
                elif task_type == TaskType.TRANSLATION and model and tokenizer:
                    inputs = tokenizer(
                        sample["text"], 
                        return_tensors="pt", 
                        truncation=True
                    ).to(self.device)
                    model.generate(**inputs, max_new_tokens=20)
                    
                elif task_type == TaskType.TEXT_CLASSIFICATION and model and tokenizer:
                    inputs = tokenizer(
                        sample["text"], 
                        return_tensors="pt", 
                        truncation=True
                    ).to(self.device)
                    model(**inputs)
                    
                elif task_type == TaskType.TEXT_GENERATION and model and tokenizer:
                    inputs = tokenizer(
                        sample["text"], 
                        return_tensors="pt", 
                        truncation=True
                    ).to(self.device)
                    model.generate(**inputs, max_new_tokens=10)
                    
                elif nlp_pipeline:
                    nlp_pipeline(sample["text"])
                    
        except Exception as e:
            raise e
    
    def _get_task_sample(self, task_type: TaskType) -> Dict[str, Any]:
        """Get sample data for benchmarking"""
        samples = {
            TaskType.TEXT_CLASSIFICATION: {
                "text": "This is a sample text for classification benchmarking."
            },
            TaskType.TEXT_GENERATION: {
                "text": "Once upon a time in a land far away",
            },
            TaskType.SUMMARIZATION: {
                "text": """Artificial intelligence is transforming industries across the globe. 
                From healthcare to finance, AI systems are being deployed to solve complex problems. 
                Machine learning algorithms can now diagnose diseases, predict market trends, 
                and even create art. The rapid advancement of AI technology brings both opportunities 
                and challenges that society must address."""
            },
            TaskType.QUESTION_ANSWERING: {
                "context": "The Eiffel Tower is located in Paris, France.",
                "question": "Where is the Eiffel Tower?"
            },
            TaskType.TRANSLATION: {
                "text": "Hello, how are you today?"
            },
            TaskType.TEXT_TO_SPEECH: {
                "text": "Hello, this is a test of the text to speech system."
            },
            TaskType.SPEECH_TO_TEXT: {
                "text": "This is a sample audio transcription test."
            },
            TaskType.OCR: {
                "text": "Sample text from an image."
            }
        }
        
        return samples.get(task_type, {"text": "Sample text for benchmarking."})
    
    def _get_default_samples(self) -> Dict[str, Any]:
        """Get default sample data for various tasks"""
        return {
            "text_classification": [
                {"text": "I love this product, it's amazing!", "label": "positive"},
                {"text": "This is the worst experience ever.", "label": "negative"}
            ],
            "summarization": [
                {"text": "Long article about AI advancements..."}
            ],
            "translation": [
                {"text": "Hello world", "source_lang": "en", "target_lang": "fr"}
            ]
        }