forked from Ziyad-Firos/Efficode-ACRR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodebert_demo.py
More file actions
380 lines (312 loc) Β· 13.2 KB
/
Copy pathcodebert_demo.py
File metadata and controls
380 lines (312 loc) Β· 13.2 KB
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
#!/usr/bin/env python
"""
CodeBERT-Powered Code Optimization Demo
Demonstrates how EFFICODE can use CodeBERT for semantic code understanding and optimization
"""
import sys
import os
import time
import torch
from pathlib import Path
# Add backend to path
backend_dir = Path(__file__).parent / 'backend' / 'src'
sys.path.insert(0, str(backend_dir))
print("π€ EFFICODE-ACRR with CodeBERT Integration")
print("π§ Semantic Code Understanding and Optimization")
print("=" * 60)
# Check if transformers is available
try:
from transformers import AutoTokenizer, AutoModel
print("β
Transformers library available")
TRANSFORMERS_AVAILABLE = True
except ImportError:
print("β Transformers library not available")
print(" Install with: pip install transformers")
TRANSFORMERS_AVAILABLE = False
class CodeBERTAnalyzer:
"""CodeBERT-based code analyzer for semantic understanding"""
def __init__(self):
self.model_name = "microsoft/codebert-base"
self.tokenizer = None
self.model = None
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def initialize(self):
"""Initialize CodeBERT model"""
if not TRANSFORMERS_AVAILABLE:
return False
try:
print(f"π Loading CodeBERT model: {self.model_name}")
print(f" Device: {self.device}")
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = AutoModel.from_pretrained(self.model_name)
self.model.to(self.device)
self.model.eval()
print("β
CodeBERT model loaded successfully")
return True
except Exception as e:
print(f"β Error loading CodeBERT: {e}")
return False
def encode_code(self, code: str):
"""Encode code using CodeBERT"""
if not self.model:
return None
try:
# Tokenize code
inputs = self.tokenizer(
code,
return_tensors='pt',
max_length=512,
padding=True,
truncation=True
).to(self.device)
# Get embeddings
with torch.no_grad():
outputs = self.model(**inputs)
# Use [CLS] token representation
code_embedding = outputs.last_hidden_state[:, 0, :]
return code_embedding
except Exception as e:
print(f"β Error encoding code: {e}")
return None
def analyze_semantic_similarity(self, code1: str, code2: str):
"""Analyze semantic similarity between two code snippets"""
emb1 = self.encode_code(code1)
emb2 = self.encode_code(code2)
if emb1 is None or emb2 is None:
return 0.0
# Calculate cosine similarity
similarity = torch.cosine_similarity(emb1, emb2).item()
return similarity
def analyze_code_complexity_features(self, code: str):
"""Extract complexity-related features using CodeBERT"""
embedding = self.encode_code(code)
if embedding is None:
return {}
# Convert to numpy for analysis
emb_np = embedding.cpu().numpy().flatten()
# Extract statistical features from embeddings
features = {
'embedding_mean': float(emb_np.mean()),
'embedding_std': float(emb_np.std()),
'embedding_max': float(emb_np.max()),
'embedding_min': float(emb_np.min()),
'complexity_score': float(abs(emb_np.mean()) * emb_np.std()), # Heuristic complexity score
}
return features
class CodeBERTOptimizer:
"""CodeBERT-powered code optimizer"""
def __init__(self):
self.analyzer = CodeBERTAnalyzer()
self.optimization_templates = {
'fibonacci_recursive': {
'pattern_embedding': None,
'optimized_code': '''def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
# CodeBERT-optimized iterative approach
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
return b''',
'explanation': 'CodeBERT detected recursive Fibonacci pattern and applied iterative optimization'
}
}
def initialize(self):
"""Initialize the optimizer"""
return self.analyzer.initialize()
def optimize_with_codebert(self, code: str):
"""Optimize code using CodeBERT semantic understanding"""
if not self.analyzer.model:
return self._fallback_optimization(code)
print(f"π€ Analyzing code with CodeBERT...")
# Get code embedding
code_embedding = self.analyzer.encode_code(code)
if code_embedding is None:
return self._fallback_optimization(code)
# Extract semantic features
features = self.analyzer.analyze_code_complexity_features(code)
print(f"π CodeBERT Features:")
for key, value in features.items():
print(f" β’ {key}: {value:.4f}")
# Check for optimization patterns using semantic similarity
best_match = None
best_similarity = 0.0
# Fibonacci pattern detection
fibonacci_patterns = [
"def fibonacci(n): return fibonacci(n-1) + fibonacci(n-2)",
"fibonacci recursive exponential",
"recursive function fibonacci"
]
for pattern in fibonacci_patterns:
similarity = self.analyzer.analyze_semantic_similarity(code, pattern)
print(f"π Similarity to '{pattern}': {similarity:.3f}")
if similarity > best_similarity and similarity > 0.7:
best_similarity = similarity
best_match = 'fibonacci_recursive'
# Apply optimization if pattern detected
if best_match:
template = self.optimization_templates[best_match]
# Verify semantic preservation
original_similarity = self.analyzer.analyze_semantic_similarity(
code, template['optimized_code']
)
print(f"β
Pattern detected: {best_match} (similarity: {best_similarity:.3f})")
print(f"π Semantic preservation: {original_similarity:.3f}")
if original_similarity > 0.5: # Ensure semantic similarity
return {
'optimized_code': template['optimized_code'],
'explanation': template['explanation'],
'method': 'codebert_semantic',
'confidence': best_similarity,
'semantic_preservation': original_similarity,
'features': features
}
# No optimization found
return {
'optimized_code': code,
'explanation': 'CodeBERT analysis completed - no optimization patterns detected',
'method': 'codebert_analysis',
'confidence': 0.0,
'semantic_preservation': 1.0,
'features': features
}
def _fallback_optimization(self, code):
"""Fallback when CodeBERT is not available"""
return {
'optimized_code': code,
'explanation': 'CodeBERT not available - using fallback analysis',
'method': 'fallback',
'confidence': 0.0,
'semantic_preservation': 1.0,
'features': {}
}
def demonstrate_codebert_optimization():
"""Demonstrate CodeBERT-powered optimization"""
print("π Initializing CodeBERT Optimizer...")
optimizer = CodeBERTOptimizer()
if not optimizer.initialize():
print("β οΈ CodeBERT not available - showing conceptual demo")
print(" Install transformers: pip install transformers torch")
return False
# Test cases
test_cases = [
{
'name': 'Fibonacci Recursive Pattern',
'code': '''def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)''',
'expected': 'Should detect recursive Fibonacci pattern'
},
{
'name': 'Factorial Recursive',
'code': '''def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)''',
'expected': 'Should analyze recursive factorial pattern'
},
{
'name': 'Simple Loop',
'code': '''def sum_numbers(n):
total = 0
for i in range(n):
total += i
return total''',
'expected': 'Should analyze loop complexity'
}
]
results = []
for i, test_case in enumerate(test_cases, 1):
print(f"\nπ§ͺ Test {i}: {test_case['name']}")
print(f"π― Expected: {test_case['expected']}")
print("β" * 50)
# Show original code
print("π Original Code:")
for j, line in enumerate(test_case['code'].split('\n'), 1):
print(f" {j:2d}: {line}")
try:
start_time = time.time()
result = optimizer.optimize_with_codebert(test_case['code'])
end_time = time.time()
print(f"\nβ‘ CodeBERT Analysis Results:")
print(f" π§ Method: {result['method']}")
print(f" π― Confidence: {result['confidence']:.3f}")
print(f" π Semantic Preservation: {result['semantic_preservation']:.3f}")
print(f" β±οΈ Processing Time: {end_time - start_time:.3f}s")
print(f" π‘ Explanation: {result['explanation']}")
if result['features']:
print(f" π Complexity Score: {result['features'].get('complexity_score', 0):.4f}")
# Show optimized code if different
if result['optimized_code'] != test_case['code']:
print(f"\nβ‘ CodeBERT-Optimized Code:")
for j, line in enumerate(result['optimized_code'].split('\n'), 1):
print(f" {j:2d}: {line}")
print("π Code was optimized using semantic understanding!")
else:
print("βΉοΈ No optimization applied (code may already be optimal)")
results.append({
'name': test_case['name'],
'success': True,
'optimized': result['optimized_code'] != test_case['code'],
'confidence': result['confidence'],
'method': result['method']
})
except Exception as e:
print(f"β Error: {e}")
results.append({
'name': test_case['name'],
'success': False,
'error': str(e)
})
print()
# Summary
print("=" * 60)
print("π CODEBERT OPTIMIZATION SUMMARY")
print("=" * 60)
successful_tests = sum(1 for r in results if r['success'])
optimized_tests = sum(1 for r in results if r.get('optimized', False))
print(f"π§ͺ Total Tests: {len(results)}")
print(f"β
Successful: {successful_tests}")
print(f"π Optimized by CodeBERT: {optimized_tests}")
print(f"\nπ Results:")
for result in results:
status = "β
" if result['success'] else "β"
method = result.get('method', 'unknown')
confidence = result.get('confidence', 0)
print(f" {status} {result['name']} ({method}, confidence: {confidence:.3f})")
print(f"\nπ CodeBERT Capabilities Demonstrated:")
print(f" β
Semantic code understanding")
print(f" β
Pattern recognition using embeddings")
print(f" β
Similarity-based optimization matching")
print(f" β
Semantic preservation validation")
print(f" β
Feature extraction from code embeddings")
return successful_tests > 0
if __name__ == "__main__":
success = demonstrate_codebert_optimization()
print(f"\n{'='*60}")
print("π― CODEBERT INTEGRATION STATUS")
print('='*60)
if success:
print("π CodeBERT integration successful!")
print("π€ EFFICODE can now use semantic understanding for optimization!")
else:
print("β οΈ CodeBERT integration needs setup")
print("π Install requirements: pip install transformers torch")
print(f"\nπ Integration Points:")
print(f" β’ Semantic similarity analysis")
print(f" β’ Pattern-based optimization detection")
print(f" β’ Code embedding feature extraction")
print(f" β’ Confidence scoring using similarity")
print(f" β’ Semantic preservation validation")
print(f"\nπ Next Steps for Full CodeBERT Integration:")
print(f" β’ Fine-tune CodeBERT on optimization datasets")
print(f" β’ Expand pattern templates with embeddings")
print(f" β’ Implement sequence-to-sequence optimization")
print(f" β’ Add attention visualization for explainability")