-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathmain.py
More file actions
1501 lines (1267 loc) · 57.5 KB
/
main.py
File metadata and controls
1501 lines (1267 loc) · 57.5 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
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
#!/usr/bin/env python3
"""
Main entry point for the Correlated Knowledge Jailbreak Project.
This script orchestrates the entire jailbreak evaluation pipeline including:
- Data loading and preprocessing
- Model initialization and configuration
- Baseline and proposed method execution
- Evaluation and metric computation
- Results logging and visualization
Usage:
python main.py --config config/config.yml [--debug] [--dry-run] [--phase full|jailbreak|judge]
"""
import argparse
import logging
import os
import sys
import yaml
import time
import json
from datetime import datetime
from typing import Dict, Any, List, Optional
from tqdm import tqdm
from zoneinfo import ZoneInfo
# Import project modules
from data.dataloader import DataLoader
from model.model_loader import ModelLoader
from methods.method_factory import create_method
from methods.abstract_method import AbstractJailbreakMethod
from evaluation.evaluator import Evaluator
from utils.utils import setup_logging, save_results, create_output_dirs, validate_config
from utils.gpu_manager import initialize_gpu_manager, get_gpu_manager
class JailbreakExperiment:
"""
Main experiment coordinator for jailbreak evaluation.
This class manages the entire experimental pipeline from data loading
to result generation and visualization.
"""
def __init__(self, config_path: str, phase: str = "full"):
"""
Initialize the experiment with configuration.
Args:
config_path (str): Path to the YAML configuration file
phase (str): Experiment phase ('full', 'jailbreak', 'judge', 'resume')
"""
self.config_path = config_path
self.config = self._load_config()
self.phase = phase
# Initialize components (will be set up in setup methods)
self.dataloader = None
self.model_loader = None
self.target_model = None
self.evaluator = None
self.methods = {}
self.results = {}
# Initialize GPU resource manager
self.gpu_manager = None
# Setup output directory based on phase
if phase == "resume" or phase == "judge":
# For resume and judge, use the output_dir directly from config
self.output_dir = self.config.get("experiment", {}).get(
"output_dir", "results/outputs"
)
self.experiment_name = os.path.basename(self.output_dir)
else:
# For other phases, generate new experiment name and directory
self.experiment_name = self._generate_experiment_name()
self.output_dir = self._setup_output_directory()
# Setup logging
self.logger = self._setup_logging()
self.logger.info(f"Initialized experiment: {self.experiment_name}")
self.logger.info(f"Output directory: {self.output_dir}")
def _load_config(self) -> Dict[str, Any]:
"""
Load configuration from YAML file.
Returns:
Dict[str, Any]: Configuration dictionary
Raises:
FileNotFoundError: If config file doesn't exist
yaml.YAMLError: If config file is malformed
"""
try:
with open(self.config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
# Validate configuration
if not validate_config(config):
raise ValueError("Invalid configuration")
return config
except FileNotFoundError:
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
except yaml.YAMLError as e:
raise yaml.YAMLError(f"Error parsing configuration file: {e}")
def _load_method_config(self, method_name: str) -> Dict[str, Any]:
"""
Load method configuration from separate YAML file.
Args:
method_name (str): Name of the method
Returns:
Dict[str, Any]: Method configuration dictionary
Raises:
FileNotFoundError: If method config file doesn't exist
yaml.YAMLError: If method config file is malformed
"""
method_config_path = os.path.join(
os.path.dirname(self.config_path), "method", f"{method_name}.yml"
)
try:
with open(method_config_path, "r", encoding="utf-8") as f:
method_config = yaml.safe_load(f)
self.logger.info(
f"Loaded method configuration for {method_name} from {method_config_path}"
)
return method_config
except FileNotFoundError:
raise FileNotFoundError(
f"Method configuration file not found: {method_config_path}"
)
except yaml.YAMLError as e:
raise yaml.YAMLError(
f"Error parsing method configuration file {method_config_path}: {e}"
)
def _generate_experiment_name(self) -> str:
"""
Generate a unique experiment name based on config and timestamp.
Returns:
str: Unique experiment identifier
"""
base_name = self.config.get("experiment", {}).get(
"name", "jailbreak_experiment"
)
timestamp = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("%Y%m%d_%H%M%S")
return f"{base_name}_{timestamp}"
def _setup_output_directory(self) -> str:
"""
Create output directory for this experiment.
Returns:
str: Path to the output directory
"""
base_output_dir = self.config.get("experiment", {}).get(
"output_dir", "results/outputs"
)
output_dir = os.path.join(base_output_dir, self.experiment_name)
create_output_dirs(output_dir)
return output_dir
def _setup_logging(self) -> logging.Logger:
"""
Setup logging configuration.
Returns:
logging.Logger: Configured logger instance
"""
log_config = self.config.get("logging", {})
log_file = os.path.join(self.output_dir, "experiment.log")
log_level = log_config.get("console_level", "INFO")
return setup_logging(
log_level=log_level, log_file=log_file, logger_name="JailbreakExperiment"
)
def setup_data(self) -> None:
"""
Setup data loading and preprocessing.
"""
self.logger.info("Setting up data loading...")
try:
# Initialize data loader
data_config = self.config.get("data", {})
self.dataloader = DataLoader(
data_dir=data_config.get("data_dir", "data/datasets")
)
# Load datasets specified in config
datasets = data_config.get("datasets", [])
for dataset_config in datasets:
dataset_name = dataset_config["name"]
dataset_size = dataset_config.get("size", "large")
self.logger.info(f"Loading dataset: {dataset_name} ({dataset_size})")
try:
data = self.dataloader.load(dataset_name, dataset_size=dataset_size)
self.logger.info(
f"Successfully loaded {len(data)} samples from {dataset_name}"
)
# Log dataset statistics
dataset_key = (
f"{dataset_name}_{dataset_size}"
if dataset_size != "large"
else dataset_name
)
self._log_dataset_statistics(dataset_key, data)
except Exception as e:
self.logger.error(f"Failed to load dataset {dataset_name}: {e}")
raise
except Exception as e:
self.logger.error(f"Failed to setup data loading: {e}")
raise
def _log_dataset_statistics(
self, dataset_key: str, dataset: List[Dict[str, Any]]
) -> None:
"""
Log statistics about the loaded dataset.
Args:
dataset_key (str): Dataset identifier
dataset (List[Dict[str, Any]]): Dataset samples
"""
if not dataset:
return
# Category distribution
categories = {}
sources = {}
query_lengths = []
for sample in dataset:
category = sample.get("category", "unknown")
source = sample.get("source", "unknown")
query_length = len(sample.get("query", ""))
categories[category] = categories.get(category, 0) + 1
sources[source] = sources.get(source, 0) + 1
query_lengths.append(query_length)
self.logger.info(f"\n=== Dataset Statistics: {dataset_key} ===")
self.logger.info(f"Total Samples: {len(dataset)}")
if categories:
self.logger.info("\nCategory Distribution:")
for cat, count in sorted(categories.items()):
percentage = (count / len(dataset)) * 100
self.logger.info(f" {cat}: {count} ({percentage:.1f}%)")
if sources:
self.logger.info("\nSource Distribution:")
for src, count in sorted(sources.items()):
percentage = (count / len(dataset)) * 100
self.logger.info(f" {src}: {count} ({percentage:.1f}%)")
if query_lengths:
avg_length = sum(query_lengths) / len(query_lengths)
min_length = min(query_lengths)
max_length = max(query_lengths)
self.logger.info(f"\nQuery Length Statistics:")
self.logger.info(f" Average: {avg_length:.2f} characters")
self.logger.info(f" Minimum: {min_length} characters")
self.logger.info(f" Maximum: {max_length} characters")
self.logger.info("-" * 60)
# Original version without defense
# def setup_model(self) -> None:
# """
# Setup target model for jailbreak evaluation.
# """
# self.logger.info("Setting up target model...")
# try:
# self.model_loader = ModelLoader(self.config.get('model', {}))
# self.target_model = self.model_loader.load_model()
# self.logger.info(f"Successfully loaded model: {self.target_model.model_name}")
# except Exception as e:
# self.logger.error(f"Failed to load model {self.target_model.model_name if self.target_model else 'unknown'}: {e}")
# raise
# New version with defense
def setup_model(self) -> None:
"""
Setup target model for jailbreak evaluation with optional defense layer.
"""
self.logger.info("Setting up target model...")
try:
# Initialize GPU resource manager
self.gpu_manager = initialize_gpu_manager(self.logger)
# Merge defense config into model config
# Extract defense configuration from global config
defense_config = self.config.get("defense", {})
# Create a copy of model config and add defense
model_config_with_defense = self.config.get("model", {}).copy()
if defense_config:
model_config_with_defense["defense"] = defense_config
self.logger.info(
f"Defense enabled: {defense_config.get('enabled', False)}, type: {defense_config.get('type', 'none')}"
)
# Allocate GPU for target model
target_model_name = model_config_with_defense.get("whitebox", {}).get(
"name", "unknown"
)
if model_config_with_defense.get("type") == "whitebox":
target_gpus = self.gpu_manager.allocate_target_model(target_model_name)
self.logger.info(
f"Allocated GPUs {target_gpus} for target model: {target_model_name}"
)
# Allocate GPU for defense model if enabled (supports llm_guard, grayswanai_guard and rephrasing)
if defense_config.get("enabled", False):
d_type = defense_config.get("type")
defense_model_name = None
if d_type == "llm_guard":
defense_model_name = defense_config.get("llm_guard", {}).get(
"guard_model_name", "llm_guard"
)
elif d_type == "grayswanai_guard":
defense_model_name = defense_config.get("grayswanai_guard", {}).get(
"guard_model_name", "grayswanai_guard"
)
elif d_type == "rephrasing":
defense_model_name = defense_config.get("rephrasing", {}).get(
"rephrase_model_name", "rephrasing_defense"
)
elif d_type == "perturbation":
defense_model_name = None
if defense_model_name:
defense_gpus = self.gpu_manager.allocate_defense_model(
defense_model_name
)
if defense_gpus:
self.logger.info(
f"Allocated GPUs {defense_gpus} for defense model: {defense_model_name}"
)
# Initialize ModelLoader with merged config
self.model_loader = ModelLoader(model_config_with_defense)
self.target_model = self.model_loader.load_model()
self.logger.info(
f"Successfully loaded model: {self.target_model.model_name}"
)
# Print GPU allocation summary
self.gpu_manager.print_allocation_summary()
except Exception as e:
self.logger.error(
f"Failed to load model {self.target_model.model_name if self.target_model else 'unknown'}: {e}"
)
raise
def setup_methods(self) -> None:
"""
Setup jailbreak methods using modular configuration.
Methods are loaded from separate YAML files in config/method/ directory.
"""
self.logger.info("Setting up jailbreak methods...")
methods_config = self.config.get("methods", {})
# Setup baseline methods
baseline_methods = methods_config.get("baselines", [])
for method_name in baseline_methods:
self.logger.info(f"Initializing baseline method: {method_name}")
try:
# Load method configuration from separate file
method_config = self._load_method_config(method_name)
# Allocate GPUs for this method
self._allocate_method_gpus(method_name, method_config)
# Create method instance
method = self._load_method(method_name, method_config)
self.methods[f"baseline_{method_name}"] = method
self.logger.info(f"Successfully initialized baseline: {method_name}")
except Exception as e:
self.logger.error(f"Failed to initialize baseline {method_name}: {e}")
raise
# Setup proposed methods
proposed_methods = methods_config.get("proposed", [])
for method_name in proposed_methods:
self.logger.info(f"Initializing proposed method: {method_name}")
try:
# Load method configuration from separate file
method_config = self._load_method_config(method_name)
# Allocate GPUs for this method
self._allocate_method_gpus(method_name, method_config)
# Create method instance
method = self._load_method(method_name, method_config)
self.methods[f"proposed_{method_name}"] = method
self.logger.info(
f"Successfully initialized proposed method: {method_name}"
)
except Exception as e:
self.logger.error(
f"Failed to initialize proposed method {method_name}: {e}"
)
raise
def setup_evaluation(self) -> None:
"""
Setup evaluation metrics and evaluator (delayed initialization).
Note: Judge model will be initialized later to avoid GPU memory conflicts.
"""
self.logger.info("Setting up evaluation framework...")
eval_config = self.config.get("evaluation", {})
# Don't initialize the evaluator yet - we'll do it after experiments complete
self.eval_config = eval_config
self.logger.info(
"Evaluation framework configured (judge model will be initialized after experiments)"
)
def _setup_evaluator_with_progress(self) -> None:
"""
Setup evaluator with progress bar for judge model initialization.
"""
self.logger.info("Initializing judge model for evaluation...")
try:
# Show progress bar for judge model initialization
with tqdm(total=100, desc="Initializing Judge Model", unit="%") as pbar:
pbar.set_description("Loading Llama-Guard-3-8B...")
pbar.update(10)
# Initialize evaluator
self.evaluator = Evaluator(
config=self.eval_config,
output_dir=os.path.join(self.output_dir, "evaluation"),
)
pbar.update(40)
pbar.set_description("Judge model loaded successfully")
pbar.update(50)
# Final update
pbar.set_description("Evaluation framework ready")
pbar.update(100)
self.logger.info("Judge model initialization completed successfully")
except Exception as e:
self.logger.error(f"Failed to initialize judge model: {e}")
raise
def run_experiments(self) -> None:
"""
Execute all jailbreak methods on loaded datasets.
"""
self.logger.info("Starting jailbreak experiments...")
# Get experiment configuration
exp_config = self.config.get("experiment", {})
max_samples = exp_config.get("max_samples_per_dataset", None)
# Iterate through all loaded datasets
for dataset_key in self.dataloader.get_loaded_datasets():
self.logger.info(f"Running experiments on dataset: {dataset_key}")
# Get dataset samples
dataset = self.dataloader.get_dataset(dataset_key)
if max_samples:
dataset = dataset[:max_samples]
self.logger.info(f"Limited to {max_samples} samples")
# Initialize results for this dataset
if dataset_key not in self.results:
self.results[dataset_key] = {}
# Run each method on this dataset
for method_name, method in self.methods.items():
self.logger.info(f"Running method: {method_name} on {dataset_key}")
try:
method_results = self._run_method_on_dataset(
method, dataset, dataset_key
)
self.results[dataset_key][method_name] = method_results
self.logger.info(f"Completed {method_name} on {dataset_key}")
except Exception as e:
self.logger.error(
f"Error running {method_name} on {dataset_key}: {e}"
)
self.results[dataset_key][method_name] = {"error": str(e)}
self.logger.info("All experiments completed")
def load_existing_results(self, output_dir: str) -> Dict[str, Any]:
"""
Load existing results from a previous run for resume functionality.
Args:
output_dir: Directory containing previous results
Returns:
Dict containing loaded results and metadata
"""
self.logger.info(f"Loading existing results from: {output_dir}")
# Load pending_judge.jsonl to get completed queries
pending_file = os.path.join(output_dir, "pending_judge.jsonl")
completed_queries = []
completed_count = 0
if os.path.exists(pending_file):
with open(pending_file, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
try:
data = json.loads(line.strip())
if "result" in data and "original_query" in data["result"]:
completed_queries.append(
data["result"]["original_query"]
)
completed_count += 1
except json.JSONDecodeError:
continue
self.logger.info(
f"Found {completed_count} completed queries in existing results"
)
# Determine next index based on pending_result count
# If autodan has 34 pending_results (indices 0-33), next index should be 34
next_index = completed_count
self.logger.info(
f"Completed queries count: {completed_count}, next index will start from: {next_index}"
)
return {
"completed_queries": completed_queries,
"completed_count": completed_count,
"next_index": next_index,
"pending_file": pending_file,
}
def run_resume_pipeline(self) -> None:
"""
Resume interrupted jailbreak experiments.
Loads existing results and continues from where it left off.
"""
self.logger.info("=== Starting Resume Pipeline ===")
try:
# Validate output_dir exists and contains previous results
if not os.path.exists(self.output_dir):
raise ValueError(f"Output directory does not exist: {self.output_dir}")
# Load existing results
existing_data = self.load_existing_results(self.output_dir)
completed_queries = existing_data["completed_queries"]
completed_count = existing_data["completed_count"]
next_index = existing_data["next_index"]
pending_file = existing_data["pending_file"]
# Setup data, model, and methods
self.setup_data()
self.setup_model()
self.setup_methods()
self.setup_evaluation()
# Get experiment configuration
exp_config = self.config.get("experiment", {})
max_samples = exp_config.get("max_samples_per_dataset", None)
# Iterate through all loaded datasets
for dataset_key in self.dataloader.get_loaded_datasets():
self.logger.info(f"Resuming experiments on dataset: {dataset_key}")
# Get dataset samples
dataset = self.dataloader.get_dataset(dataset_key)
if max_samples:
dataset = dataset[:max_samples]
self.logger.info(f"Limited to {max_samples} samples")
# Filter out completed queries
remaining_queries = []
remaining_indices = []
for i, sample in enumerate(dataset):
query = sample.get("query", "")
if query not in completed_queries:
remaining_queries.append(sample)
remaining_indices.append(i)
self.logger.info(
f"Dataset {dataset_key}: {len(dataset)} total, {completed_count} completed, {len(remaining_queries)} remaining"
)
if not remaining_queries:
self.logger.info(
f"All queries in dataset {dataset_key} are already completed"
)
continue
# Initialize results for this dataset
if dataset_key not in self.results:
self.results[dataset_key] = {}
# Run each method on remaining queries
for method_name, method in self.methods.items():
self.logger.info(
f"Resuming method: {method_name} on {dataset_key} ({len(remaining_queries)} remaining queries)"
)
try:
# Set the starting index for intermediate results
method._thread_local = type("ThreadLocal", (), {})()
method._thread_local.sample_index = next_index
method._thread_local.dataset_key = dataset_key
# Run method on remaining queries
method_results = self._run_method_on_dataset_resume(
method,
remaining_queries,
remaining_indices,
dataset_key,
next_index,
pending_file,
)
# Update results
if dataset_key not in self.results:
self.results[dataset_key] = {}
if method_name not in self.results[dataset_key]:
self.results[dataset_key][method_name] = []
self.results[dataset_key][method_name].extend(method_results)
# Update next_index for next method
next_index += len(remaining_queries)
self.logger.info(
f"Completed resume for {method_name} on {dataset_key}"
)
except Exception as e:
self.logger.error(
f"Error resuming {method_name} on {dataset_key}: {e}"
)
if dataset_key not in self.results:
self.results[dataset_key] = {}
self.results[dataset_key][method_name] = {"error": str(e)}
# Free whitebox resources before judge init
self._teardown_whitebox_resources()
# Evaluation phase (judge model initialized here)
self.evaluate_results()
self.generate_reports()
self.logger.info("=== Resume Pipeline completed successfully ===")
print(f"Resume completed! Results saved to: {self.output_dir}")
except Exception as e:
self.logger.error(f"Resume pipeline failed with error: {e}")
raise
def _run_method_on_dataset_resume(
self,
method: AbstractJailbreakMethod,
queries: List[Dict],
original_indices: List[int],
dataset_key: str,
start_index: int,
pending_file: str,
) -> List[Dict[str, Any]]:
"""
Run a method on remaining queries for resume functionality.
Args:
method: Jailbreak method instance
queries: Remaining queries to process
original_indices: Original indices of the queries in the full dataset
dataset_key: Dataset identifier
start_index: Starting index for intermediate results
pending_file: Path to pending_judge.jsonl file
Returns:
List of result dictionaries
"""
results = []
# Extract query strings
query_strings = [q.get("query", "") for q in queries]
self.logger.info(
f"Processing {len(query_strings)} remaining queries starting from index {start_index}"
)
# Process queries with progress bar
from tqdm import tqdm
with tqdm(total=len(query_strings), desc=f"{method.name}") as pbar:
for idx, (query_data, original_idx) in enumerate(
zip(queries, original_indices)
):
current_index = start_index + idx
try:
method._thread_local.sample_index = current_index
method._thread_local.dataset_key = dataset_key
# Extract query string and metadata
query = query_data.get("query", "")
category = query_data.get("category", "unknown")
source = query_data.get("source", "unknown")
# Generate jailbreak with metadata
result = method.generate_jailbreak(
query, category=category, source=source
)
results.append(result)
# Note: Intermediate results are saved by the method itself during execution
# We only save the final result to pending_judge.jsonl
# Append to pending_judge.jsonl
pending_entry = {
"dataset_key": dataset_key,
"method_name": method.name,
"result": result,
}
with open(pending_file, "a", encoding="utf-8") as f:
f.write(json.dumps(pending_entry, ensure_ascii=False) + "\n")
pbar.update(1)
except Exception as e:
self.logger.error(f"Error processing query {current_index}: {e}")
error_result = {
"original_query": query,
"error": str(e),
"success": False,
"metadata": {
"method": method.name,
"category": category,
"source": source,
"error": str(e),
},
}
results.append(error_result)
pbar.update(1)
return results
def evaluate_results(self) -> None:
"""
Evaluate all experimental results using configured metrics.
Judge model is initialized here to avoid GPU memory conflicts.
"""
self.logger.info("Evaluating experimental results...")
# Initialize evaluator with progress bar
self._setup_evaluator_with_progress()
if not self.evaluator or not self.evaluator.get_available_metrics():
self.logger.error(
"No evaluator or no metrics available; skipping evaluation."
)
return
for dataset_key, dataset_results in self.results.items():
self.logger.info(f"Evaluating results for dataset: {dataset_key}")
try:
evaluation_results = self.evaluator.evaluate_dataset_results(
dataset_key, dataset_results
)
self.results[dataset_key]["evaluation"] = evaluation_results
self.logger.info(f"Evaluation completed for {dataset_key}")
# ---- pretty summary in logs ----
for method_name, metrics_out in evaluation_results.items():
if isinstance(metrics_out, dict):
for metric_name, res in metrics_out.items():
self.logger.info(
f"[SUMMARY] dataset={dataset_key} method={method_name} metric={metric_name} -> {res}"
)
except Exception as e:
self.logger.error(f"Error evaluating {dataset_key}: {e}")
self.logger.info("Evaluation completed for all datasets")
def generate_reports(self) -> None:
"""
Generate final reports and visualizations.
"""
self.logger.info("Generating reports and visualizations...")
try:
# Save raw results
results_file = os.path.join(self.output_dir, "results.json")
save_results(self.results, results_file)
self.logger.info(f"Raw results saved to: {results_file}")
# Generate summary report
self._generate_summary_report()
# Generate visualizations
self._generate_visualizations()
self.logger.info("Report generation completed")
except Exception as e:
self.logger.error(f"Error generating reports: {e}")
raise
def _teardown_whitebox_resources(self) -> None:
"""
Release whitebox model resources to free GPU memory before judge init.
Only used in full pipeline between jailbreak and judge phases.
"""
try:
self.logger.info("Releasing whitebox resources to free GPU memory...")
# Release method-level resources (custom teardown if provided)
import gc
import torch
if hasattr(self, "methods") and isinstance(self.methods, dict):
for m_name, m in list(self.methods.items()):
# Call method-specific teardown if available
if hasattr(m, "teardown") and callable(getattr(m, "teardown")):
try:
m.teardown()
except Exception as e:
self.logger.warning(
f"Method {m_name} teardown warning: {e}"
)
for attr in [
"whitebox_model",
"whitebox_tokenizer",
"conv_template",
"criterion",
]:
if hasattr(m, attr):
setattr(m, attr, None)
# Optional: drop methods if not needed anymore
# self.methods = {}
# Release target model (whitebox holder)
if hasattr(self, "target_model") and self.target_model is not None:
for attr in [
"vllm_model", # vLLM engine instance
"model", # HF model
"tokenizer",
]:
if hasattr(self.target_model, attr):
setattr(self.target_model, attr, None)
# Optional: drop the wrapper to let GC reclaim
# self.target_model = None
gc.collect()
try:
torch.cuda.empty_cache()
except Exception:
pass
self.logger.info("Whitebox resources released.")
except Exception as e:
self.logger.warning(f"Failed to fully release whitebox resources: {e}")
def _allocate_method_gpus(
self, method_name: str, method_config: Dict[str, Any]
) -> None:
"""
Allocate GPUs for a specific jailbreak method.
Args:
method_name (str): Name of the method
method_config (Dict[str, Any]): Method configuration
"""
if not self.gpu_manager:
self.logger.warning("GPU manager not initialized, skipping GPU allocation")
return
# Determine method requirements based on method name
needs_controller = False
needs_judge = False
controller_model = ""
judge_model = ""
# Get actual method config (handle nested config structure)
actual_config = method_config.get("config", method_config)
if method_name == "cka-agent":
# CKA-Agent: uses controller_model and judge_model
controller_config = actual_config.get("controller_model", {})
if controller_config.get("name"):
needs_controller = True
controller_model = controller_config["name"]
judge_config = actual_config.get("judge_model", {})
if judge_config.get("type") == "whitebox" and judge_config.get(
"whitebox", {}
).get("name"):
needs_judge = True
judge_model = judge_config["whitebox"]["name"]
elif judge_config.get("type") == "blackbox" and judge_config.get(
"blackbox", {}
).get("name"):
needs_judge = True
judge_model = judge_config["blackbox"]["name"]
elif method_name in [
"agent_self_response",
"multi_agent_jailbreak",
"x_teaming",
]:
# These methods use attack_model directly (no whitebox/blackbox distinction)
attack_config = actual_config.get("attack_model", {})
if attack_config.get("name"):
needs_controller = True
controller_model = attack_config["name"]
elif method_name in ["pap", "pair", "actor_attack"]:
# These methods have attack_model with whitebox/blackbox distinction
attack_config = actual_config.get("attack_model", {})
if attack_config.get("type") == "whitebox" and attack_config.get(
"whitebox", {}
).get("name"):
needs_controller = True
controller_model = attack_config["whitebox"]["name"]
elif attack_config.get("type") == "blackbox" and attack_config.get(
"blackbox", {}
).get("name"):
# Blackbox doesn't need GPU allocation
pass
elif method_name == "parley":
# Parley uses attacker_model (not attack_model)
attacker_config = actual_config.get("attacker_model", {})
if attacker_config.get("type") == "whitebox" and attacker_config.get(
"whitebox", {}
).get("name"):
needs_controller = True
controller_model = attacker_config["whitebox"]["name"]
elif attacker_config.get("type") == "blackbox":
# Blackbox doesn't need GPU allocation
pass
elif method_name in ["vanilla", "autodan"]:
# These methods don't need GPU allocation
pass
else:
# Fallback: try to detect any attack model
attack_config = actual_config.get("attack_model", {})
if attack_config.get("name"):
needs_controller = True
controller_model = attack_config["name"]
# Allocate GPUs for this method
allocations = self.gpu_manager.allocate_attack_method(
method_name=method_name,
needs_controller=needs_controller,
needs_judge=needs_judge,
controller_model=controller_model,
judge_model=judge_model,
)
if allocations:
self.logger.info(f"GPU allocations for {method_name}: {allocations}")