Spaces:
Sleeping
Sleeping
File size: 14,296 Bytes
5c6379b | 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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | #!/usr/bin/env python3
"""
Optimized CodeT5+ Code Analyzer
This script implements CodeT5+ with multiple speed optimizations:
- FP16 by default (fastest on your GPU); optional INT8/INT4
- Response streaming for better UX
- Progress indicators
- Result caching
- Optimized generation parameters
Author: AI Code Analyzer Project
Date: 2025
"""
import torch
import time
import hashlib
import json
import os
from typing import Dict, Any, Optional, Generator
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, BitsAndBytesConfig
from tqdm import tqdm
import streamlit as st
class OptimizedCodeAnalyzer:
"""
Optimized CodeT5+ analyzer with speed improvements.
"""
def __init__(
self,
model_id: str = "Salesforce/codet5p-220m",
cache_dir: str = "./cache",
precision: str = "fp16", # one of: fp16 | int8 | int4
quick_max_new_tokens: int = 180,
detailed_max_new_tokens: int = 240,
):
"""
Initialize the optimized analyzer.
Args:
model_id: Hugging Face model ID
cache_dir: Directory to store cached results
"""
self.model_id = model_id
self.cache_dir = cache_dir
self.model = None
self.tokenizer = None
self.cache = {}
self.precision = precision.lower().strip()
self.quick_max_new_tokens = quick_max_new_tokens
self.detailed_max_new_tokens = detailed_max_new_tokens
# Create cache directory
os.makedirs(cache_dir, exist_ok=True)
# Load cache if exists
self._load_cache()
def _create_quantization_config(self) -> BitsAndBytesConfig:
"""
Create 4-bit quantization configuration for faster inference.
Returns:
BitsAndBytesConfig: Quantization configuration
"""
# Default to INT4 nf4 when precision==int4; callers should not use this
return BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
)
def _load_model(self):
"""
Load the model with optimizations.
"""
if self.model is not None:
return
print("π Loading optimized CodeT5+ model...")
# Load tokenizer
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
# Decide precision based on config
quantization_config = None
dtype = None
banner = ""
if self.precision == "fp16":
dtype = torch.float16
banner = "FP16 precision"
elif self.precision == "int8":
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
banner = "INT8 quantization"
elif self.precision == "int4":
quantization_config = self._create_quantization_config()
banner = "INT4 (nf4) quantization"
else:
# Fallback to fp16
dtype = torch.float16
banner = f"Unknown precision '{self.precision}', defaulting to FP16"
self.model = AutoModelForSeq2SeqLM.from_pretrained(
self.model_id,
device_map="auto",
dtype=dtype,
quantization_config=quantization_config,
)
print(f"β
Model loaded with {banner}!")
def _get_cache_key(self, code: str) -> str:
"""
Generate cache key for code.
Args:
code: Code to analyze
Returns:
str: Cache key
"""
return hashlib.md5(code.encode()).hexdigest()
def _load_cache(self):
"""
Load cached results from disk.
"""
cache_file = os.path.join(self.cache_dir, "analysis_cache.json")
if os.path.exists(cache_file):
try:
with open(cache_file, 'r') as f:
self.cache = json.load(f)
print(f"π Loaded {len(self.cache)} cached analyses")
except:
self.cache = {}
def _save_cache(self):
"""
Save cache to disk.
"""
cache_file = os.path.join(self.cache_dir, "analysis_cache.json")
with open(cache_file, 'w') as f:
json.dump(self.cache, f)
def _check_cache(self, code: str) -> Optional[Dict[str, Any]]:
"""
Check if analysis is cached.
Args:
code: Code to analyze
Returns:
Optional[Dict]: Cached result or None
"""
cache_key = self._get_cache_key(code)
return self.cache.get(cache_key)
def _save_to_cache(self, code: str, result: Dict[str, Any]):
"""
Save analysis result to cache.
Args:
code: Code that was analyzed
result: Analysis result
"""
cache_key = self._get_cache_key(code)
self.cache[cache_key] = result
self._save_cache()
def analyze_code_streaming(
self,
code: str,
show_progress: bool = True,
mode: str = "detailed", # "quick" | "detailed"
) -> Generator[str, None, Dict[str, Any]]:
"""
Analyze code with streaming response and progress indicators.
Args:
code: Code to analyze
show_progress: Whether to show progress indicators
Yields:
str: Partial analysis results
"""
# Check cache first
cached_result = self._check_cache(code)
if cached_result:
print("β‘ Using cached result!")
yield cached_result["analysis"]
return cached_result
# Load model if not loaded
self._load_model()
# Create analysis prompt
prompt = f"""Analyze this code for bugs, performance issues, and security concerns:
{code}
Analysis:"""
# Tokenize input
inputs = self.tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=512,
padding=True,
)
device = next(self.model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
# Generate analysis with optimized parameters
start_time = time.time()
if show_progress:
print("π Analyzing code...")
progress_bar = tqdm(total=100, desc="Analysis Progress")
try:
with torch.no_grad():
# Use optimized generation parameters for speed
max_new = self.detailed_max_new_tokens if mode == "detailed" else self.quick_max_new_tokens
num_beams = 2 if mode == "detailed" else 1
outputs = self.model.generate(
inputs["input_ids"],
attention_mask=inputs.get("attention_mask"),
max_new_tokens=max_new,
num_beams=num_beams,
do_sample=False,
pad_token_id=self.tokenizer.eos_token_id,
use_cache=True,
)
if show_progress:
progress_bar.update(50)
# Decode analysis
analysis = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
analysis_text = analysis[len(prompt):].strip()
if show_progress:
progress_bar.update(50)
progress_bar.close()
# Calculate quality score
quality_score = self._calculate_quality_score(analysis_text)
total_time = time.time() - start_time
# Create result
result = {
"analysis": analysis_text,
"quality_score": quality_score,
"execution_time": total_time,
"model": self.model_id,
"cached": False
}
# Save to cache
self._save_to_cache(code, result)
# Yield the analysis
yield analysis_text
return result
except Exception as e:
if show_progress:
progress_bar.close()
raise e
def analyze_code_fast(self, code: str, mode: str = "quick") -> Dict[str, Any]:
"""
Fast analysis without streaming (for batch processing).
Args:
code: Code to analyze
Returns:
Dict: Analysis result
"""
# Check cache first
cached_result = self._check_cache(code)
if cached_result:
cached_result["cached"] = True
return cached_result
# Load model if not loaded
self._load_model()
# Create analysis prompt
prompt = f"""Analyze this code for bugs, performance issues, and security concerns:
{code}
Analysis:"""
# Tokenize input
inputs = self.tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=512,
padding=True,
)
device = next(self.model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
# Generate analysis with speed optimizations
start_time = time.time()
with torch.no_grad():
max_new = self.quick_max_new_tokens if mode == "quick" else self.detailed_max_new_tokens
num_beams = 1 if mode == "quick" else 2
outputs = self.model.generate(
inputs["input_ids"],
attention_mask=inputs.get("attention_mask"),
max_new_tokens=max_new,
num_beams=num_beams,
do_sample=False,
pad_token_id=self.tokenizer.eos_token_id,
use_cache=True,
)
# Decode analysis
analysis = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
analysis_text = analysis[len(prompt):].strip()
# Calculate quality score
quality_score = self._calculate_quality_score(analysis_text)
total_time = time.time() - start_time
# Create result
result = {
"analysis": analysis_text,
"quality_score": quality_score,
"execution_time": total_time,
"model": self.model_id,
"cached": False
}
# Save to cache
self._save_to_cache(code, result)
return result
def _calculate_quality_score(self, analysis_text: str) -> int:
"""
Calculate quality score for analysis.
Args:
analysis_text: Analysis text
Returns:
int: Quality score (0-100)
"""
score = 0
analysis_lower = analysis_text.lower()
# Check for different types of analysis (20 points each)
if any(word in analysis_lower for word in ['bug', 'error', 'issue', 'problem', 'flaw']):
score += 20
if any(word in analysis_lower for word in ['performance', 'slow', 'efficient', 'complexity', 'optimization']):
score += 20
if any(word in analysis_lower for word in ['security', 'vulnerability', 'safe', 'unsafe', 'risk']):
score += 20
if any(word in analysis_lower for word in ['suggest', 'improve', 'better', 'recommend', 'fix', 'solution']):
score += 20
# Bonus for detailed analysis
if len(analysis_text) > 200:
score += 10
if len(analysis_text) > 500:
score += 10
return min(score, 100)
def get_model_info(self) -> Dict[str, Any]:
"""
Get information about the loaded model.
Returns:
Dict: Model information
"""
if self.model is None:
return {"status": "Model not loaded"}
param_count = sum(p.numel() for p in self.model.parameters())
device = next(self.model.parameters()).device
return {
"model_id": self.model_id,
"parameters": param_count,
"device": str(device),
"precision": self.precision,
"quick_max_new_tokens": self.quick_max_new_tokens,
"detailed_max_new_tokens": self.detailed_max_new_tokens,
"cache_size": len(self.cache)
}
def main():
"""
Demo of the optimized analyzer.
"""
print("π Optimized CodeT5+ Analyzer Demo")
print("=" * 60)
# Initialize analyzer
analyzer = OptimizedCodeAnalyzer()
# Test code
test_code = """
def calculate_fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)
# This will be slow for large numbers
result = calculate_fibonacci(35)
print(result)
"""
print(f"Test Code:\n{test_code}")
print("=" * 60)
# Test streaming analysis
print("\nπ Streaming Analysis:")
print("-" * 40)
for partial_result in analyzer.analyze_code_streaming(test_code):
print(partial_result)
# Test fast analysis
print("\nβ‘ Fast Analysis:")
print("-" * 40)
result = analyzer.analyze_code_fast(test_code)
print(f"Analysis: {result['analysis']}")
print(f"Quality Score: {result['quality_score']}/100")
print(f"Execution Time: {result['execution_time']:.2f}s")
print(f"Cached: {result['cached']}")
# Show model info
print("\nπ Model Information:")
print("-" * 40)
model_info = analyzer.get_model_info()
for key, value in model_info.items():
print(f"{key}: {value}")
if __name__ == "__main__":
main()
|