File size: 11,609 Bytes
05c5c96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Inference & Evaluation for Qwen-0.8B Student Model
"""

import torch
import torch.nn.functional as F
from transformers import AutoTokenizer
from pathlib import Path
import logging
import time
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# ============================================================================
# INFERENCE
# ============================================================================

class StudentInference:
    """Run inference with distilled student model"""
    
    def __init__(self, checkpoint_path: str, device: str = "cuda"):
        self.device = torch.device(device)
        self.checkpoint_path = checkpoint_path
        
        logger.info(f"Loading checkpoint: {checkpoint_path}")
        self.checkpoint = torch.load(checkpoint_path, map_location=device)
        self.config = self.checkpoint['config']
        
        # Reconstruct student model
        from qwen_distill import QwenDistillationConfig, QwenStudentModel
        
        config_obj = QwenDistillationConfig()
        for key, val in self.config.items():
            setattr(config_obj, key, val)
        
        self.model = QwenStudentModel(config_obj).to(device)
        self.model.load_state_dict(self.checkpoint['model_state_dict'])
        self.model.eval()
        
        # Load tokenizer
        self.tokenizer = AutoTokenizer.from_pretrained(
            config_obj.teacher_model_name,
            trust_remote_code=True,
        )
        self.tokenizer.pad_token = self.tokenizer.eos_token
        
        logger.info(f"✓ Model loaded. Parameters: {sum(p.numel() for p in self.model.parameters())/1e6:.1f}M")
    
    def generate(
        self,
        prompt: str,
        max_length: int = 100,
        temperature: float = 0.7,
        top_p: float = 0.95,
    ) -> str:
        """Generate text from prompt"""
        
        input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
        
        with torch.no_grad():
            for _ in range(max_length):
                outputs = self.model(input_ids)
                logits = outputs['logits'][:, -1, :]
                
                # Temperature scaling
                logits = logits / temperature
                
                # Top-p sampling
                probs = F.softmax(logits, dim=-1)
                sorted_probs, sorted_indices = torch.sort(probs, descending=True)
                cumsum_probs = torch.cumsum(sorted_probs, dim=-1)
                
                # Remove tokens with cumulative probability > top_p
                sorted_indices_to_remove = cumsum_probs > top_p
                sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
                sorted_indices_to_remove[..., 0] = 0
                
                indices_to_remove = sorted_indices[sorted_indices_to_remove]
                logits[0, indices_to_remove] = -float('inf')
                
                # Sample
                next_token = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
                input_ids = torch.cat([input_ids, next_token], dim=-1)
                
                if next_token.item() == self.tokenizer.eos_token_id:
                    break
        
        return self.tokenizer.decode(input_ids[0], skip_special_tokens=True)
    
    def inference_speed_test(self, prompt: str = "The future of AI", num_runs: int = 10):
        """Benchmark inference speed"""
        logger.info(f"Running speed test ({num_runs} iterations)...")
        
        input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
        
        # Warmup
        with torch.no_grad():
            _ = self.model(input_ids)
        
        # Measure
        times = []
        with torch.no_grad():
            for _ in range(num_runs):
                torch.cuda.synchronize()
                start = time.time()
                _ = self.model(input_ids)
                torch.cuda.synchronize()
                times.append(time.time() - start)
        
        avg_time = sum(times) / len(times) * 1000  # ms
        logger.info(f"Average inference time: {avg_time:.1f}ms")
        logger.info(f"Throughput: {1000/avg_time:.1f} samples/sec")
        
        return {
            'avg_time_ms': avg_time,
            'throughput': 1000 / avg_time,
        }


# ============================================================================
# EVALUATION
# ============================================================================

class StudentEvaluator:
    """Evaluate student model quality"""
    
    def __init__(self, student_checkpoint: str, teacher_model_name: str, device: str = "cuda"):
        self.device = torch.device(device)
        self.student_inf = StudentInference(student_checkpoint, device)
        
        # Load teacher
        from transformers import AutoModelForCausalLM
        logger.info(f"Loading teacher: {teacher_model_name}")
        
        self.teacher = AutoModelForCausalLM.from_pretrained(
            teacher_model_name,
            torch_dtype=torch.float16,
            device_map="auto",
            trust_remote_code=True,
        )
        self.teacher.eval()
        
        self.tokenizer = self.student_inf.tokenizer
    
    def compute_perplexity(self, texts: List[str], max_length: int = 256) -> float:
        """Compute perplexity on text samples"""
        total_loss = 0.0
        num_tokens = 0
        
        self.student_inf.model.eval()
        
        with torch.no_grad():
            for text in texts:
                enc = self.tokenizer(
                    text,
                    max_length=max_length,
                    truncation=True,
                    return_tensors="pt",
                ).to(self.device)
                
                outputs = self.student_inf.model(enc['input_ids'])
                logits = outputs['logits']
                
                # Compute cross-entropy loss
                loss = F.cross_entropy(
                    logits[0, :-1, :],
                    enc['input_ids'][0, 1:],
                    reduction='mean'
                )
                
                total_loss += loss.item()
                num_tokens += enc['input_ids'].numel()
        
        perplexity = torch.exp(torch.tensor(total_loss / len(texts))).item()
        logger.info(f"Student perplexity: {perplexity:.2f}")
        return perplexity
    
    def compute_teacher_perplexity(self, texts: List[str], max_length: int = 256) -> float:
        """Compute perplexity on teacher for comparison"""
        total_loss = 0.0
        
        self.teacher.eval()
        
        with torch.no_grad():
            for text in texts:
                enc = self.tokenizer(
                    text,
                    max_length=max_length,
                    truncation=True,
                    return_tensors="pt",
                ).to(self.device)
                
                outputs = self.teacher(enc['input_ids'], output_hidden_states=True)
                logits = outputs.logits
                
                loss = F.cross_entropy(
                    logits[0, :-1, :],
                    enc['input_ids'][0, 1:],
                    reduction='mean'
                )
                
                total_loss += loss.item()
        
        perplexity = torch.exp(torch.tensor(total_loss / len(texts))).item()
        logger.info(f"Teacher perplexity: {perplexity:.2f}")
        return perplexity
    
    def top_k_agreement(self, texts: List[str], k: int = 5) -> float:
        """Measure how well student matches teacher top-k predictions"""
        match_count = 0
        total = 0
        
        self.student_inf.model.eval()
        self.teacher.eval()
        
        with torch.no_grad():
            for text in texts:
                enc = self.tokenizer(
                    text,
                    return_tensors="pt",
                    max_length=256,
                    truncation=True,
                ).to(self.device)
                
                student_out = self.student_inf.model(enc['input_ids'])
                student_logits = student_out['logits']
                
                teacher_out = self.teacher(enc['input_ids'])
                teacher_logits = teacher_out.logits
                
                # Top-k tokens
                _, student_topk = torch.topk(student_logits, k, dim=-1)
                _, teacher_topk = torch.topk(teacher_logits, k, dim=-1)
                
                # Count matches
                matches = (student_topk == teacher_topk).float().sum().item()
                match_count += matches
                total += student_topk.numel()
        
        agreement = match_count / total if total > 0 else 0.0
        logger.info(f"Top-{k} agreement with teacher: {agreement*100:.1f}%")
        return agreement
    
    def generate_comparison(self, prompt: str = "The future of AI", max_length: int = 100):
        """Compare student vs teacher generation"""
        logger.info(f"\nPrompt: {prompt}\n")
        
        # Student generation
        student_text = self.student_inf.generate(prompt, max_length=max_length)
        logger.info(f"Student:\n{student_text}\n")
        
        # Teacher generation
        input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
        with torch.no_grad():
            outputs = self.teacher.generate(
                input_ids,
                max_length=max_length,
                temperature=0.7,
                top_p=0.95,
            )
        teacher_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
        logger.info(f"Teacher:\n{teacher_text}\n")


# ============================================================================
# MAIN
# ============================================================================

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--checkpoint", default="checkpoints/student_final.pt", help="Student checkpoint path")
    parser.add_argument("--teacher", default="Qwen/Qwen2.5-0.5B", help="Teacher model name")
    parser.add_argument("--prompt", default="The future of artificial intelligence", help="Generation prompt")
    parser.add_argument("--speed", action="store_true", help="Run speed test")
    parser.add_argument("--eval", action="store_true", help="Run evaluation")
    
    args = parser.parse_args()
    
    # Simple generation
    logger.info("Loading student model...")
    inference = StudentInference(args.checkpoint)
    
    logger.info(f"Generating from prompt: {args.prompt}\n")
    text = inference.generate(args.prompt, max_length=100)
    print(text)
    
    if args.speed:
        logger.info("\nBenchmarking speed...")
        inference.inference_speed_test()
    
    if args.eval:
        logger.info("\nRunning evaluation...")
        evaluator = StudentEvaluator(args.checkpoint, args.teacher)
        
        # Test data
        test_texts = [
            "Artificial intelligence is transforming industries.",
            "Machine learning models require careful tuning.",
            "Distillation compresses large models efficiently.",
        ]
        
        evaluator.compute_perplexity(test_texts)
        evaluator.compute_teacher_perplexity(test_texts)
        evaluator.top_k_agreement(test_texts, k=5)
        evaluator.generate_comparison(args.prompt, max_length=100)