-
Notifications
You must be signed in to change notification settings - Fork 0
/
score_safe_run.py
1873 lines (1618 loc) · 76.5 KB
/
score_safe_run.py
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import random
import json
import threading
import argparse
import logging
from typing import Any, Dict, List, Optional, Tuple
from dataclasses import dataclass
from difflib import SequenceMatcher
from typing_extensions import TypedDict
from peft import PeftModel, LoraConfig, get_peft_model
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import time
import torch
import torch.nn as nn
from torch.optim import AdamW
from torch.utils.data import DataLoader, Dataset
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
get_linear_schedule_with_warmup,
StoppingCriteria, StoppingCriteriaList
)
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import nltk
from rouge import Rouge
import radon.complexity as radon_complexity
from sympy import simplify, SympifyError
from sympy.parsing.sympy_parser import parse_expr
import ast
import wandb
import math
# Initialize NLTK
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def set_seed(seed: int) -> None:
"""
Set the seed for reproducibility.
Args:
seed (int): The seed value to set.
"""
try:
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
logger.info(f"Seed set to {seed}.")
except Exception as e:
logger.error(f"Error setting seed: {e}")
raise RuntimeError("Failed to set seed.") from e
@dataclass
class Config:
"""
Configuration dataclass for training parameters.
"""
beta_1: float = 0.01
beta_2: float = 0.1
alpha: float = 5.0
learning_rate: float = 1e-5
batch_size: int = 1
max_seq_len: int = 2048
max_new_tokens: int = 2048
num_epochs_stage_one: int = 0
num_epochs_stage_two: int = 1
device: torch.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seed: int = 42
task: str = 'CODE'
model_variant: str = 'Qwen/Qwen2.5-Coder-0.5B-Instruct'
ablation: str = 'none'
data_path: str = './data'
output_dir: str = './outputs'
num_workers: int = 8
gradient_accumulation_steps: int = 8
max_grad_norm: float = 1.0
warmup_steps: int = 100
save_steps: int = 1000
logging_steps: int = 10
eval_steps: int = 1000
max_eval_samples: int = 500
mixed_precision: bool = True
save_total_limit: int = 2
compute_cyclomatic_complexity: bool = False
persistent_workers: bool = True
def validate(self) -> None:
"""
Validate configuration parameters.
"""
if self.batch_size <= 0:
raise ValueError("batch_size must be a positive integer.")
if self.max_seq_len <= 0:
raise ValueError("max_seq_len must be a positive integer.")
if self.num_epochs_stage_one < 0 or self.num_epochs_stage_two < 0:
raise ValueError("Number of epochs must be non-negative.")
if not os.path.isdir(self.data_path):
raise FileNotFoundError(f"Data path does not exist: {self.data_path}")
if not os.path.isdir(self.output_dir):
try:
os.makedirs(self.output_dir, exist_ok=True)
logger.info(f"Created output directory at {self.output_dir}.")
except Exception as e:
logger.error(f"Failed to create output directory: {e}")
raise
CODING_EXAMPLES = [
{
"problem": "Write a function to find the minimum cost path to reach (m, n) from (0, 0) for the given cost matrix cost[][] and a position (m, n) in cost[][].",
"tests": [
"assert min_cost([[1, 2, 3], [4, 8, 2], [1, 5, 3]], 2, 2) == 8",
"assert min_cost([[2, 3, 4], [5, 9, 3], [2, 6, 4]], 2, 2) == 12",
"assert min_cost([[3, 4, 5], [6, 10, 4], [3, 7, 5]], 2, 2) == 16"
],
"solution": """R = 3
C = 3
def min_cost(cost, m, n):
tc = [[0 for x in range(C)] for x in range(R)]
tc[0][0] = cost[0][0]
for i in range(1, m+1):
tc[i][0] = tc[i-1][0] + cost[i][0]
for j in range(1, n+1):
tc[0][j] = tc[0][j-1] + cost[0][j]
for i in range(1, m+1):
for j in range(1, n+1):
tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]
return tc[m][n]"""
},
{
"problem": "Write a function to find the similar elements from the given two tuple lists.",
"tests": [
"assert similar_elements((3, 4, 5, 6),(5, 7, 4, 10)) == (4, 5)",
"assert similar_elements((1, 2, 3, 4),(5, 4, 3, 7)) == (3, 4)",
"assert similar_elements((11, 12, 14, 13),(17, 15, 14, 13)) == (13, 14)"
],
"solution": """def similar_elements(test_tup1, test_tup2):
res = tuple(set(test_tup1) & set(test_tup2))
return (res)"""
},
{
"problem": "Write a python function to identify non-prime numbers.",
"tests": [
"assert is_not_prime(2) == False",
"assert is_not_prime(10) == True",
"assert is_not_prime(35) == True"
],
"solution": """import math
def is_not_prime(n):
result = False
for i in range(2,int(math.sqrt(n)) + 1):
if n % i == 0:
result = True
return result"""
}
]
def format_examples() -> str:
"""Format coding examples into a string."""
examples_str = ""
for i, example in enumerate(CODING_EXAMPLES, 1):
examples_str += f"\nExample {i}:\n"
examples_str += f"Problem: {example['problem']}\n"
examples_str += f"Your code should pass these tests:\n"
examples_str += "\n".join(example["tests"]) + "\n"
examples_str += "Solution:\n```python\n" # Using markdown code block syntax
examples_str += example["solution"] + "\n"
examples_str += "```\n"
return examples_str
def get_code_first_turn_prompt(problem: str, test_list: List[str]) -> str:
"""Generate the first turn prompt for code problems.
Args:
problem (str): Problem description
test_list (List[str]): List of test cases
Returns:
str: Formatted prompt for first attempt
"""
prompt = (
"<|im_start|>system\nYou are an expert Python programmer. Here are some examples of problems and their test cases:\n"
f"{format_examples()}"
"<|im_end|>\n"
f"<|im_start|>user\nNow please solve this problem, try not to use while loops:\n{problem}\n\n"
"<|im_end|>\n"
"<|im_start|>assistant\n"
)
return prompt
def get_code_correction_prompt(problem: str, prev_attempt: str) -> str:
"""Generate the self-correction prompt for code problems.
Args:
problem (str): Original problem description including function signature and test cases
prev_attempt (str): Previous code attempt to be corrected
Returns:
str: Formatted prompt for correction attempt
"""
return (
"<|im_start|>system\nYou are an expert Python programmer. Here are some examples of problems and their test cases:\n"
f"{format_examples()}"
"<|im_end|>\n"
f"<|im_start|>user\nNow please solve this problem, try not to use while loops:\n{problem}\n\n"
"<|im_end|>\n"
"<|im_start|>assistant\n"
f"{prev_attempt}\n\n"
"<|im_start|>user\n"
"There might be an error in the code above because of lack of understanding of the question. "
"Please correct the error, if any, and rewrite the solution. Only output the final correct Python program!\n"
"<|im_end|>\n"
"<|im_start|>assistant\n"
)
class BaseDataset(Dataset):
"""
Base dataset class for loading data.
"""
def __init__(self, data: List[Dict[str, Any]], task: str = 'CODE'):
self.data = data
self.task = task
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def __len__(self) -> int:
return len(self.data)
def prepare_prompt(self, item: Dict[str, Any], turn: int = 1, prev_attempt: Optional[str] = None) -> str:
"""
Prepare prompt based on task and turn number.
Args:
item: Data item containing problem/prompt
turn: Turn number (1 or 2)
prev_attempt: Previous attempt for turn 2
Returns:
Formatted prompt string
"""
if self.task == 'CODE':
if turn == 1:
test_list = item.get('test_list', [])
return get_code_first_turn_prompt(item.get('text', item.get('prompt', '')), test_list)
else:
return get_code_correction_prompt(item.get('text', item.get('prompt', '')), prev_attempt)
else:
raise NotImplementedError(f"Task {self.task} is not implemented")
def __getitem__(self, idx: int) -> Dict[str, Any]:
try:
item = self.data[idx]
# Format prompt for first turn
item['formatted_prompt'] = self.prepare_prompt(item)
return item
except IndexError as e:
logger.error(f"Index {idx} out of range for dataset of size {len(self.data)}.")
raise IndexError("Dataset index out of range.") from e
except Exception as e:
logger.error(f"Error retrieving item at index {idx}: {e}")
raise
def load_json(file_path: str, max_samples: Optional[int] = None) -> List[Dict[str, Any]]:
"""
Load data from a JSON or JSONL file.
Args:
file_path (str): Path to the JSON or JSONL file.
max_samples (Optional[int]): Maximum number of samples to load.
Returns:
List[Dict[str, Any]]: Loaded data.
"""
if max_samples is not None and max_samples < 0:
raise ValueError("max_samples must be a non-negative integer or None")
data = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
if file_path.endswith('.jsonl'):
for idx, line in enumerate(f):
if max_samples is not None and idx >= max_samples:
break
if line.strip(): # Skip empty lines
data.append(json.loads(line))
else:
file_content = f.read().strip()
if file_content:
loaded_data = json.loads(file_content)
if isinstance(loaded_data, list):
data = loaded_data[:max_samples] if max_samples else loaded_data
else:
data = [loaded_data]
except FileNotFoundError as e:
logger.error(f"File not found: {file_path}")
raise FileNotFoundError(f"Data file not found: {file_path}") from e
except json.JSONDecodeError as e:
logger.error(f"JSON decode error in file {file_path}: {e}")
raise ValueError(f"Invalid JSON format in file: {file_path}") from e
except Exception as e:
logger.error(f"Unexpected error while loading JSON from {file_path}: {e}")
raise RuntimeError(f"Failed to load data from {file_path}") from e
logger.info(f"Loaded {len(data)} samples from {file_path}.")
return data
class StopOnTokens(StoppingCriteria):
"""Custom stopping criteria for text generation."""
def __init__(self, stop_token_ids: List[List[int]], min_length: int = 20, timeout: float = 30.0):
self.stop_token_ids = stop_token_ids
self.min_length = min_length
self.timeout = timeout
self.start_time = time.time()
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
# Check for timeout
if time.time() - self.start_time > self.timeout:
logger.warning("Generation timed out")
return True
# Don't stop if we haven't generated minimum length
if input_ids.shape[-1] < self.min_length:
return False
# Check for stop sequences
for stop_ids in self.stop_token_ids:
stop_tensor = stop_ids.clone().detach().to(input_ids.device)
if torch.all((input_ids[0][-len(stop_ids):] == stop_tensor)).item():
return True
return False
class AdvancedModel(nn.Module):
"""
Advanced model wrapper with tokenizer and generation capabilities.
"""
def __init__(self, model_name: str, device: torch.device):
super().__init__()
try:
self.tokenizer = AutoTokenizer.from_pretrained(
model_name,
use_fast=True,
padding_side='left',
trust_remote_code=True,
device_map=device
)
# Update markers for Qwen
self.system_marker = "<|im_start|>system"
self.user_marker = "<|im_start|>user"
self.assistant_marker = "<|im_start|>assistant"
self.stop_sequences = [
"<|im_end|>",
self.system_marker,
self.user_marker,
"Previous Attempt:",
"Instructions:"
]
logger.info(f"Tokenizer loaded for {model_name}.")
except Exception as e:
logger.error(f"Error loading tokenizer for {model_name}: {e}")
raise RuntimeError(f"Failed to load tokenizer for {model_name}") from e
if not self.tokenizer.pad_token:
self.tokenizer.pad_token = self.tokenizer.eos_token
logger.info("Using EOS token as PAD token.")
try:
lora_config = LoraConfig(
r=16,
lora_alpha=16,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM"
)
self.model = AutoModelForCausalLM.from_pretrained(
model_name,
trust_remote_code=True,
device_map=device,
torch_dtype=torch.float16, # Use fp16 for efficiency
low_cpu_mem_usage=True
)
self.model.gradient_checkpointing_enable()
self.model = get_peft_model(self.model, lora_config)
self.model.print_trainable_parameters()
logger.info(f"Model loaded and moved to {device}.")
except Exception as e:
logger.error(f"Error loading model {model_name}: {e}")
raise RuntimeError(f"Failed to load model {model_name}") from e
try:
if not self.tokenizer.pad_token:
self.tokenizer.add_special_tokens({'pad_token': '[PAD]'})
self.model.resize_token_embeddings(len(self.tokenizer))
logger.info("Added pad token and resized token embeddings.")
except Exception as e:
logger.error(f"Error adding pad token or resizing embeddings: {e}")
raise RuntimeError("Failed to add pad token or resize embeddings.") from e
self.device = device
def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
"""
Forward pass through the model.
Args:
input_ids (torch.Tensor): Input token IDs.
attention_mask (torch.Tensor): Attention mask.
Returns:
torch.Tensor: Logits from the model.
"""
try:
return self.model(input_ids=input_ids, attention_mask=attention_mask).logits
except Exception as e:
logger.error(f"Error during forward pass: {e}")
raise RuntimeError("Forward pass failed.") from e
def generate_text(
self,
inputs: Dict[str, torch.Tensor],
max_length: int = 4096,
temperature: float = 1.0,
num_return_sequences: int = 1,
min_length: int = 20,
timeout: float = 60.0 # Add timeout parameter
) -> torch.Tensor:
"""
Generate text using the model with timeout and error handling.
"""
try:
# Create stopping criteria with timeout
stop_sequences = [
self.tokenizer.encode(seq, add_special_tokens=False, return_tensors='pt')
for seq in self.stop_sequences
]
stopping_criteria = StoppingCriteriaList([
StopOnTokens(stop_sequences, min_length=min_length, timeout=timeout)
])
outputs = self.model.generate(
inputs['input_ids'],
attention_mask=inputs['attention_mask'],
max_new_tokens=max_length,
min_new_tokens=min_length,
temperature=max(temperature, 1e-7),
do_sample=temperature > 0,
top_p=0.95,
num_return_sequences=num_return_sequences,
pad_token_id=self.tokenizer.pad_token_id,
eos_token_id=self.tokenizer.eos_token_id,
stopping_criteria=stopping_criteria, # Add stopping criteria
)
# Clear CUDA cache after generation
if torch.cuda.is_available():
torch.cuda.empty_cache()
return outputs
except Exception as e:
logger.error(f"Error during text generation: {e}")
# Return a default/empty response in case of error
return inputs['input_ids'] # Return input as fall
class RewardsDict(TypedDict):
"""
TypedDict for rewards and related metrics.
"""
rewards: torch.Tensor
cyclomatic: List[float]
class SCoReTrainer:
"""
Trainer class for the SCoRe system.
"""
def __init__(
self,
model: AdvancedModel,
ref_model: AdvancedModel,
optimizer: torch.optim.Optimizer,
scheduler: Any,
train_loader: DataLoader,
val_loader: DataLoader,
config: Config
):
self.task = config.task
self.model = model
self.ref_model = ref_model
self.optimizer = optimizer
self.scheduler = scheduler
self.train_loader = train_loader
self.val_loader = val_loader
self.config = config
self.best_reward = float('-inf')
self.kl_loss_fn = nn.KLDivLoss(reduction='batchmean')
self.global_step = 0
self.reward_history: List[float] = []
self.edit_distance_ratios: List[float] = []
self.scaler = torch.amp.GradScaler('cuda', enabled=config.mixed_precision and torch.cuda.is_available())
self.use_wandb = False
if torch.cuda.is_available():
torch.cuda.empty_cache()
try:
wandb.login(key="5846629ab2a2094c5948b4c032301fdae772fbb0", relogin=True)
wandb.init(
project="score-mbpp",
config={
"task": config.task,
"model_variant": config.model_variant,
"batch_size": config.batch_size,
"learning_rate": config.learning_rate,
"beta_1": config.beta_1,
"beta_2": config.beta_2,
"alpha": config.alpha
}
)
self.use_wandb = True
logger.info("Weights & Biases initialized successfully.")
except Exception as e:
logger.warning(f"Failed to initialize Weights & Biases: {e}")
self.use_wandb = False
def compute_kl_divergence(self, logits: torch.Tensor, ref_logits: torch.Tensor) -> torch.Tensor:
"""
Compute KL divergence between model logits and reference logits.
Args:
logits (torch.Tensor): Logits from the model.
ref_logits (torch.Tensor): Logits from the reference model.
Returns:
torch.Tensor: KL divergence loss.
"""
try:
log_probs = nn.functional.log_softmax(logits, dim=-1)
ref_probs = nn.functional.softmax(ref_logits, dim=-1)
kl_div = self.kl_loss_fn(log_probs, ref_probs)
return kl_div
except Exception as e:
logger.error(f"Error computing KL divergence: {e}")
raise RuntimeError("KL divergence computation failed.") from e
def _save_trace(self, trace_info: Dict) -> None:
"""
Save trace information to a JSON file with pretty printing.
"""
try:
trace_file = os.path.join(self.config.output_dir, 'reward_traces_score.jsonl')
with open(trace_file, 'a') as f:
# Pretty print the JSON with indentation
json_str = json.dumps(trace_info, indent=2)
# Add a newline after each JSON object
f.write(json_str + '\n\n')
except Exception as e:
logger.error(f"Error saving trace information: {e}")
def safe_execute_code(self, code: str, test: str, timeout: int = 2) -> bool:
"""
Safely execute generated code with a test case.
Args:
code (str): Generated code.
test (str): Test case code.
timeout (int): Timeout in seconds.
Returns:
bool: Execution success status.
"""
forbidden_ops = [
'input(', 'raw_input(', 'input =', 'raw_input =',
'open(', 'file(', 'open =', 'file =',
'socket.', 'socket =',
'subprocess.', 'subprocess =',
'sys.stdin', 'stdin',
'eval(', 'exec(', 'eval =', 'exec =',
'os.', 'system(', 'os =', 'system =',
'import os', 'import subprocess', 'import socket',
'input', 'raw_input',
'while True', 'while 1',
'for _ in range(99999', # Suspicious large loops
'recursion_depth',
'setrecursionlimit',
'fork(', 'fork =',
'exec(', 'exec =',
'__import__',
'globals()', 'locals()',
'breakpoint()',
'sleep(', 'time.sleep',
'while True', 'while 1', 'while"', "while'",
'while 2', 'while 1.0', 'while -1',
'for i in iter(', 'while float',
'while not False', 'while not None',
'setrecursionlimit',
'fork(', 'fork =',
'exec(', 'exec =',
'__import__',
'globals()', 'locals()',
'breakpoint()',
'sleep(', 'time.sleep',
]
if 'while' in code:
logger.warning("Code contains while loop - not executing")
return False
suspicious_patterns = [
r'while\s+[^:]+:[^=]*\n\s*(?!break|return)', # While loops without break/return
r'for\s+[^:]+:[^=]*\n\s*(?!break|return)', # For loops without break/return
r'def\s+\w+[^:]*:[^=]*\n\s*\w+\([^)]*\)', # Recursive calls
]
import re
for pattern in suspicious_patterns:
if re.search(pattern, code):
logger.warning(f"Suspicious pattern detected: {pattern}")
return False
if len(code) > 10000: # Arbitrary limit, adjust as needed
logger.warning("Code exceeds length limit")
return False
# Check for forbidden operations before execution
code_lower = code.lower()
for op in forbidden_ops:
if op.lower() in code_lower:
logger.warning(f"Forbidden operation or potential infinite loop detected: {op}")
return False
def limit_resources():
import resource
# Limit CPU time to 1 second
resource.setrlimit(resource.RLIMIT_CPU, (1, 1))
# Limit memory to 512MB
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
# Prevent creation of new processes
resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
def target(exec_globals: Dict[str, Any]) -> None:
try:
# Create restricted builtins
safe_builtins = {
k: v for k, v in dict(__builtins__).items()
if k not in ['eval', 'exec', 'compile', '__import__', 'open']
}
limit_resources()
# Add a custom time limit decorator
def timeout_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
if time.time() - start_time > timeout:
raise TimeoutError("Function execution timed out")
return result
return wrapper
# Create safe builtins without dangerous functions
safe_builtins = dict(__builtins__)
for forbidden in ['input', 'raw_input', 'open', 'file']:
safe_builtins.pop(forbidden, None)
exec_globals['input'] = lambda *args, **kwargs: ''
exec_globals['raw_input'] = lambda *args, **kwargs: ''
exec_globals['__builtins__'] = safe_builtins
# Create a restricted environment
allowed_modules = {
'math': __import__('math'),
'random': __import__('random'),
'datetime': __import__('datetime'),
're': __import__('re'),
'collections': __import__('collections'),
'itertools': __import__('itertools'),
'functools': __import__('functools'),
'operator': __import__('operator'),
'string': __import__('string'),
'copy': __import__('copy'),
}
exec_globals.update(allowed_modules)
# Add timeout decorator to the execution environment
exec_globals['timeout_decorator'] = timeout_decorator
wrapped_code = f"""
start_time = __import__('time').time()
{code}
if __import__('time').time() - start_time > {timeout}:
raise TimeoutError("Execution took too long")
"""
# Wrap the code with timeout decorator
modified_code = "import time\n" + wrapped_code
# Execute with shorter timeout for individual operations
exec(modified_code, exec_globals)
exec(test, exec_globals)
exec_globals['exec_success'] = True
except TimeoutError:
logger.warning("Code execution timed out")
exec_globals['exec_success'] = False
except Exception as e:
logger.warning(f"Execution error: {e}")
exec_globals['exec_success'] = False
try:
import resource
resource.setrlimit(resource.RLIMIT_CPU, (timeout + 1, timeout + 1))
except Exception as e:
logger.warning(f"Could not set global resource limits: {e}")
exec_globals: Dict[str, Any] = {}
thread = threading.Thread(target=target, args=(exec_globals,), daemon=True)
try:
thread.start()
thread.join(timeout=timeout) # Overall timeout for the entire execution
if thread.is_alive():
logger.warning("Code execution timed out.")
return False
return exec_globals.get('exec_success', False)
except Exception as e:
logger.error(f"Error during code execution thread: {e}")
return False
def compute_cyclomatic_complexity(self, code: str) -> float:
"""
Compute cyclomatic complexity of the given code.
Args:
code (str): Code to analyze.
Returns:
float: Average cyclomatic complexity.
"""
try:
complexity = radon_complexity.cc_visit(code)
avg_complexity = np.mean([block.complexity for block in complexity]) if complexity else 0.0
logger.debug(f"Cyclomatic complexity: {avg_complexity}")
return avg_complexity
except SyntaxError as e:
logger.warning(f"SyntaxError while computing cyclomatic complexity: {e}")
return 0.0
except Exception as e:
logger.error(f"Unexpected error computing cyclomatic complexity: {e}")
return 0.0
def reward_function_code(self, code: str, test: str, stage: str = None, attempt: str = None) -> Tuple[float, float]:
"""
Compute rewards for code tasks with detailed validation and testing.
Args:
code (str): Generated code to evaluate
test (str): Test cases to run
Returns:
Tuple containing (reward, cyclomatic_complexity)
"""
logger.info("\n=== Code Reward Computation ===")
trace_info = {
"stage": stage,
"attempt": attempt,
"problem": test,
"generated_code": {
"raw": code,
"cleaned": None,
"ast_valid": False,
"execution_result": None,
},
"test_cases": {
"total": 0,
"passed": 0,
"failed": 0,
"execution_details": []
},
"metrics": {
"cyclomatic_complexity": 0.0,
"execution_time": None,
}
}
try:
# Step 1: Clean and normalize the code
logger.info(f"Cleaned code:\n{code}")
trace_info["generated_code"]["cleaned"] = code
# Step 2: Extract function name and normalize test cases if needed
try:
actual_func_name = self.extract_function_name(code)
if actual_func_name:
test_cases = test.split('\n')
if test_cases and test_cases[0].strip():
test_str = test_cases[0].strip().strip('[]\'') # Remove list brackets and quotes
expected_func_name = test_str.split('(')[0].replace('assert ', '').strip()
if actual_func_name != expected_func_name:
test_cases = [test.replace(expected_func_name, actual_func_name) for test in test_cases]
test = '\n'.join(test_cases)
logger.info(f"Normalized function name from {expected_func_name} to {actual_func_name}")
logger.info(f"Normalized test cases:\n{test}")
except Exception as e:
logger.warning(f"Function name extraction failed: {e}")
# Step 3: Validate code syntax using AST
try:
ast.parse(code)
trace_info["generated_code"]["ast_valid"] = True
except SyntaxError as e:
logger.warning(f"Code syntax validation failed: {str(e)}")
self._save_trace(trace_info)
return 0.0, 0.0
# Step 4: Execute code and run test cases
exec_globals = {}
all_tests_passed = True
test_cases = [t for t in test.split('\n') if t.strip()]
trace_info["test_cases"]["total"] = len(test_cases)
try:
# First execute the solution code
start_time = time.time()
# exec(code, exec_globals)
# logger.info("✓ Code execution successful")
# try
if not self.safe_execute_code(code, "", timeout=2): # Execute just the code first
logger.warning("Code execution failed")
trace_info["generated_code"]["execution_result"] = "failed: code execution error"
self._save_trace(trace_info)
return 0.0, 0.0
# Then try all test cases
for i, test_case in enumerate(test_cases, 1):
test_result = {
"test_case": test_case,
"passed": False,
"error": None
}
cleaned_test = test_case.strip().strip('[]\'')
if not self.safe_execute_code(code, cleaned_test, timeout=2):
all_tests_passed = False
test_result["error"] = "Execution failed or timed out"
trace_info["test_cases"]["failed"] += 1
logger.info(f"Test {i}: × Failed execution: {cleaned_test}")
else:
test_result["passed"] = True
trace_info["test_cases"]["passed"] += 1
logger.info(f"Test {i}: ✓ {cleaned_test}")
trace_info["test_cases"]["execution_details"].append(test_result)
execution_time = time.time() - start_time
trace_info["metrics"]["execution_time"] = execution_time
trace_info["generated_code"]["execution_result"] = "success"
except Exception as e:
logger.warning(f"Code execution failed: {str(e)}")
trace_info["generated_code"]["execution_result"] = f"failed: {str(e)}"
self._save_trace(trace_info)
return 0.0, 0.0
# Step 5: Compute cyclomatic complexity if enabled
if self.config.compute_cyclomatic_complexity:
try:
complexity = radon_complexity.cc_visit(code)
avg_complexity = np.mean([block.complexity for block in complexity]) if complexity else 0.0
trace_info["metrics"]["cyclomatic_complexity"] = avg_complexity
except Exception as e:
logger.warning(f"Error computing cyclomatic complexity: {e}")
trace_info["metrics"]["cyclomatic_complexity"] = 0.0
# Step 6: Compute final reward
reward = 1.0 if all_tests_passed else 0.0
self._save_trace(trace_info)
return reward, trace_info["metrics"]["cyclomatic_complexity"]
except Exception as e:
logger.error(f"Error in reward computation: {str(e)}")
trace_info["error"] = str(e)
self._save_trace(trace_info)
return 0.0, 0.0
def extract_function_name(self, code: str) -> Optional[str]:
"""Extract the last module-level function name from code using AST parsing."""
try:
# Parse the code into an AST
tree = ast.parse(code)
# Get only module-level functions (not nested)
module_functions = [
node.name
for node in ast.iter_child_nodes(tree)
if isinstance(node, ast.FunctionDef)
]
if module_functions:
# Get the last module-level function
last_function = module_functions[-1]
logger.info(f"Found last module-level function: {last_function}")
return last_function
logger.warning("No valid module-level function found in generated code.")
return None
except Exception as e:
logger.warning(f"Failed to extract function name: {e}")
return None
def _clean_code_response(self, text: str) -> str:
"""
Clean generated code while preserving indentation and structure.
Only extracts the last code block from the response.
"""
try:
# Find all code blocks
code_blocks = []
if '```' in text:
blocks = text.split('```')
for i, block in enumerate(blocks):
if i % 2 == 1: # Only process content between backticks
lines = block.splitlines()
# Skip the language identifier line (python, Python, etc.)
if lines and lines[0].lower().strip() in ['python', 'py']:
lines = lines[1:]
# Skip empty lines at start and end
while lines and not lines[0].strip():
lines = lines[1:]
while lines and not lines[-1].strip():
lines = lines[:-1]
if lines: # Only add non-empty blocks
code_blocks.append('\n'.join(lines))
# Return the last code block if any were found
if code_blocks:
return code_blocks[-1]
# If no code blocks found, clean the raw text
lines = []
for line in text.splitlines():
# Skip the language identifier if it appears at the start
if line.lower().strip() in ['python', 'py']:
continue
# Skip empty lines and comments
if not line.strip() or line.lstrip().startswith('#'):
continue
lines.append(line)
return '\n'.join(lines)
except Exception as e:
logger.error(f"Error cleaning code response: {e}")
return text
# Add debug logging
finally:
if hasattr(self, 'global_step') and self.global_step % self.config.logging_steps == 0:
logger.debug("Code Cleaning Results:")
logger.debug(f"Original:\n{text}")
# if code_blocks:
# logger.debug(f"Selected code block:\n{code_blocks[-1]}")
# else: