-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadal_v3_train.py
More file actions
2922 lines (2590 loc) · 141 KB
/
Copy pathadal_v3_train.py
File metadata and controls
2922 lines (2590 loc) · 141 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
"""
RADAR × RAID — Multi-Generator + Multi-Evasion Adversarial Training
====================================================================
Paper : "RADAR: Robust AI-Text Detection via Adversarial Learning"
Hu et al., NeurIPS 2023 — https://arxiv.org/pdf/2307.03838
Dataset: RAID (liamdugan/raid) — Dugan et al., ACL 2024
═══════════════════════════════════════════════════════════════════
DESIGN PHILOSOPHY: TWO-TRACK ADVERSARIAL GAME
═══════════════════════════════════════════════════════════════════
Original RADAR has ONE evasion strategy: the learnable T5 paraphraser (Gσ).
We extend it with an EvasionAttackPool of 6 strategies, split into two tracks:
Track A — LEARNABLE (PPO)
─────────────────────────
T5-Paraphrase : Gσ rewrites AI text via seq2seq. Updated via cppo-ep.
This is the only attack for which log-probs exist, so
it is the only one that feeds the PPO gradient.
Track B — DETERMINISTIC (Data Augmentation for Detector)
──────────────────────────────────────────────────────────
RecursiveParaphrase: T5 applied N times in a chain (xm→xp1→xp2…).
Increases linguistic distance from original AI text.
SynonymReplacement : Replaces content words with WordNet synonyms at rate p.
Mimics manual word-swap evasion (common in student essays).
Homoglyphs : Swaps ASCII chars with visually identical Unicode chars
(e.g. 'a'→'а' Cyrillic). Exploits tokeniser blind spots.
ArticleDeletion : Removes 'a','an','the' randomly at rate p. Non-native
English writers do this naturally; detectors misfire.
RandomMisspelling : Inserts adjacent-key typos at rate p per word.
Simulates rushed human writing and confuses n-gram signals.
Training loop per outer step:
1. Sample xm from generator pool.
2. Track A: Gσ generates xp_ppo → PPO reward → update Gσ.
3. Track B: ALL 5 deterministic attacks produce xp_det_i for each xm.
4. Detector update: sees xh vs {xm, xp_ppo, xp_det_1…xp_det_5}.
This is a multi-attack reweighted logistic loss (Eq. 3 extended).
Why this matters
────────────────
• Gσ is trained against the current Dϕ → learns neural evasion.
• Dϕ is trained against ALL attacks simultaneously → robust to the full
threat model, not just T5 paraphrasing.
• At test time, ONLY Dϕ is deployed. It has seen every attack during
training, generalising far beyond the original RADAR paper.
Stability fixes from previous iteration (all retained)
────────────────────────────────────────────────────────
Fix 1 — Label smoothing (LABEL_SMOOTHING_ALPHA=0.10)
Fix 2 — Detector update frequency (DETECTOR_UPDATE_EVERY=2)
Fix 3 — Reward clipping [REWARD_CLIP_MIN, REWARD_CLIP_MAX]
Fix 4 — Paraphraser MLE warm-start (WARMSTART_STEPS=5)
Fix 5 — KL penalty on PPO (KL_COEFF=0.1)
Dependencies
────────────
pip install transformers datasets scikit-learn torch sentencepiece nltk
python -c "import nltk; nltk.download('wordnet'); nltk.download('averaged_perceptron_tagger_eng')"
"""
import os
import math
# Fix OOM-5: reduce fragmentation from mixed T5/RoBERTa allocation pattern
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import re
import random
import string
import logging
import unicodedata
import itertools
from collections import defaultdict
from typing import Dict, List, Optional, Tuple, NamedTuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import AdamW
from transformers import (
T5ForConditionalGeneration,
T5Tokenizer,
RobertaTokenizer,
RobertaForSequenceClassification,
get_linear_schedule_with_warmup,
BitsAndBytesConfig,
)
from transformers import LogitsProcessor, LogitsProcessorList
from raid.utils import load_data as raid_load_data # official RAID train/test splits
from transformers import AutoModelForSequenceClassification, AutoTokenizer
class NanSafeLogitsProcessor(LogitsProcessor):
"""Intercept logits before torch.multinomial — replace NaN/inf so sampling never crashes."""
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
scores = torch.nan_to_num(scores, nan=-1e9, posinf=1e4, neginf=-1e9)
all_dead = (scores <= -1e8).all(dim=-1)
if all_dead.any():
scores[all_dead] = 0.0 # uniform fallback — all tokens equally likely
return scores
_NAN_SAFE_PROCESSOR = LogitsProcessorList([NanSafeLogitsProcessor()])
from sklearn.metrics import roc_auc_score, roc_curve, precision_recall_curve, precision_score, recall_score, f1_score
from sklearn.isotonic import IsotonicRegression
from huggingface_hub import HfApi, login
# NLTK imports (graceful fallback if not installed)
try:
from nltk.corpus import wordnet
from nltk import pos_tag, word_tokenize
import nltk
nltk.download("wordnet", quiet=True)
nltk.download("averaged_perceptron_tagger_eng", quiet=True)
nltk.download("punkt", quiet=True)
nltk.download("punkt_tab", quiet=True)
NLTK_AVAILABLE = True
except ImportError:
NLTK_AVAILABLE = False
# ══════════════════════════════════════════════════════════════════════════════
# GLOBAL CONFIGURATION — no argparse, edit these variables only
# ══════════════════════════════════════════════════════════════════════════════
SEED = 42
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# ── Model identifiers ─────────────────────────────────────────────────────────
# Fine-tuned paraphrase model — much better evasion diversity than vanilla t5-large.
# "Vamsi/T5_Paraphrase_Paws" is trained on PAWS paraphrase pairs; understands
# "Paraphrase: <text>" prefix natively. Swap back to "t5-large" if download fails.
# Vamsi/T5_Paraphrase_Paws generates over-formal text that scores LOWER (more AI-like)
# than the original. Switch to DIPPER (T5-XXL, ~22GB fp16) — the dedicated diversity
# paraphraser from Krishna et al. 2023, the standard evasion attack in the RAID paper.
# Fallback: "humarin/chatgpt_paraphraser_on_T5_base" if VRAM is tight.
# T5-base fine-tuned for paraphrasing — ~900 MB, clean checkpoint, no tied-weight
# inconsistencies. humarin/chatgpt_paraphraser_on_T5_base has mismatched tied weights
# (lm_head/encoder/decoder embed tokens all present but untied) causing gradient
# explosion in warmstart (MLE→NaN on step 2) which then poisons generate() logits.
PARAPHRASER_MODEL_NAME = "ramsrigouthamg/t5_paraphraser"
PARAPHRASER_LOAD_IN_8BIT = False # not needed — model is only ~900 MB
DETECTOR_MODEL_NAME = "microsoft/deberta-v3-large"
# ── RAID dataset ──────────────────────────────────────────────────────────────
# Install: pip install raid-bench
# train split → adversarial training | test split → validation (no leakage)
GENERATORS_TO_USE: Optional[List[str]] = None # None = all generators found in data
RAID_FILTER_DOMAIN: Optional[str] = None # None = all domains
RAID_FILTER_ATTACK: Optional[str] = "none" # TRAIN only: use clean (attack="none") rows.
# The TEST split contains ONLY adversarial rows
# (no attack="none"), so this filter is skipped
# for validation — see load_raid_multigenerator().
# ── Sample sizes ──────────────────────────────────────────────────────────────
# Caps applied to the TRAIN split before the train/val split is performed.
# Set None to use all available data.
NUM_HUMAN_SAMPLES = None # 10,000 human texts total (split into train+val below)
SAMPLES_PER_GENERATOR = None # 1,000 AI texts per generator (split into train+val below)
# Train/val split ratio — applied AFTER sampling the caps above.
# e.g. 0.9 → 90% train, 10% val of the NUM_HUMAN_SAMPLES / SAMPLES_PER_GENERATOR totals.
# The RAID official test split is NOT used for validation: it has NO human texts and uses
# a different schema (empty model field), making it unsuitable as a validation set.
VAL_SPLIT_RATIO = 0.1 # → ~9,000 train / ~1,000 val human; ~900 train / ~100 val per gen
# ── Multi-generator sampling strategy ────────────────────────────────────────
# "uniform" | "round_robin" | "mixed" | "curriculum"
GENERATOR_SAMPLING_STRATEGY = "mixed"
CURRICULUM_SWITCH_STEPS = 20
# ══════════════════════════════════════════════════════════════════════════════
# EVASION ATTACK POOL SETTINGS — ADAL v2 (11 attacks + 4 decoding strategies)
# ══════════════════════════════════════════════════════════════════════════════
# ── Track A: Learnable (PPO-trained) ─────────────────────────────────────────
ATTACK_T5_PARAPHRASE = True # Gσ — T5 paraphraser trained via PPO
ATTACK_RECURSIVE_PARA = False # SPEED: disabled; re-enable for 2-pass T5
RECURSIVE_PARA_DEPTH = 2
# ── Track B: Deterministic evasion attacks (11 total) ────────────────────────
# Original 4 (RADAR baseline)
ATTACK_SYNONYM_REPLACEMENT = True
ATTACK_HOMOGLYPHS = True
ATTACK_ARTICLE_DELETION = True
ATTACK_MISSPELLING = True
# ── New 7 attacks added in ADAL v2 ───────────────────────────────────────────
ATTACK_NUMBER_SWAP = True # digit → similar digit (3→8, 6→9)
ATTACK_WHITESPACE_ADDITION = True # insert extra spaces between words
ATTACK_UPPER_LOWER_SWAP = True # randomly flip case of letters
ATTACK_ZERO_WIDTH_SPACE = True # inject invisible Unicode chars (U+200B)
ATTACK_INSERT_PARAGRAPHS = True # break long text with random newlines
ATTACK_ALTERNATIVE_SPELLING = True # UK↔US (colour↔color, organise↔organize)
# ── Track C: Decoding strategies (offline data augmentation) ─────────────────
# These do NOT run as live attacks during training. They are applied once to
# generate alternative AI-text versions that join the xm pool. The RAID dataset
# already contains decoding variants, but enabling this re-samples them under
# explicit regimes so the detector sees all 4 styles in balanced proportions.
DECODING_STRATEGIES_ENABLED = True
DECODING_STRATEGIES = {
"greedy": {"do_sample": False, "temperature": 0.0, "repetition_penalty": 1.0},
"sampling": {"do_sample": True, "temperature": 1.0, "repetition_penalty": 1.0},
"greedy_reppen": {"do_sample": False, "temperature": 0.0, "repetition_penalty": 1.2},
"sampling_reppen": {"do_sample": True, "temperature": 1.0, "repetition_penalty": 1.2},
}
# ── Attack rates ─────────────────────────────────────────────────────────────
SYNONYM_REPLACE_RATE = 0.40 # fraction of content words replaced
HOMOGLYPH_RATE = 0.20 # fraction of eligible chars replaced
ARTICLE_DELETE_RATE = 0.60 # fraction of articles dropped
MISSPELLING_RATE = 0.09 # fraction of words typoed
NUMBER_SWAP_RATE = 0.30 # fraction of digits swapped
WHITESPACE_ADD_RATE = 0.20 # probability of extra space per word gap
UPPER_LOWER_SWAP_RATE = 0.05 # fraction of letters with case flipped
ZERO_WIDTH_INJECT_RATE = 0.15 # probability of ZWSP between words
INSERT_PARA_RATE = 0.05 # probability of inserting paragraph break per sentence
ALT_SPELLING_RATE = 0.70 # fraction of UK/US-variant words swapped
# ── Detector multi-attack loss weights ───────────────────────────────────────
# Sum ≈ 5.5 — each attack contributes proportionally to its difficulty/value.
# T5 paraphrase gets highest weight because it's the adversarial target.
ATTACK_LOSS_WEIGHTS: Dict[str, float] = {
"t5_paraphrase": 1.0,
"recursive_para": 0.8,
"synonym_replacement": 0.6,
"homoglyphs": 0.4,
"article_deletion": 0.5,
"misspelling": 0.5,
"number_swap": 0.3,
"whitespace_addition": 0.3,
"upper_lower_swap": 0.3,
"zero_width_space": 0.4,
"insert_paragraphs": 0.3,
"alternative_spelling": 0.4,
}
# ── PPO / Paraphraser ─────────────────────────────────────────────────────────
PPO_BUFFER_SIZE = 64 # SPEED: was 128; halved → ~2× faster buffer fill + PPO
# 8 epochs per buffer — more gradient steps per collection cycle,
# helping the paraphraser learn faster against a strong detector.
PPO_EPOCHS = 8
PPO_EPSILON = 0.2
ENTROPY_COEFF = 0.01 # FIX: was 0.05; para loss = -136 at step 2 means
# entropy term was dominating. 0.01 matches original paper.
PARAPHRASER_LR = 2e-5 # BALANCE: 2x faster than before; essential to outpace detector
PARAPHRASER_MAX_NEW_TOKENS = 128
# temperature=1.5 caused NaN probs → multinomial crash. temperature=1.0 is stable.
# top_k=50 with top_p disabled keeps a focused but varied distribution.
# Beam search (do_sample=False) killed PPO: zero reward variance → para_loss=0 always.
PARAPHRASER_TOP_K = 50 # restored — focused distribution, stable sampling
PARAPHRASER_TOP_P = 1.0 # keep disabled
PARAPHRASER_TEMPERATURE = 1.0 # safe — temperature=1.5 caused NaN/crash
PARAPHRASER_REPETITION_PEN = 1.3 # penalise repeating the same tokens
PARAPHRASER_MAX_INPUT_LEN = 256
# FIX: was 0.1 — too strong. Keeps paraphraser close to reference T5, limiting
# the diversity of generated paraphrases and collapsing reward variance.
# 0.01 allows more deviation so PPO has meaningful gradient signal.
# Lower KL allows paraphraser to deviate more from reference → more reward variance
KL_COEFF = 0.001
# ── Detector ──────────────────────────────────────────────────────────────────
LAMBDA = 0.5
# 1e-5 caused detector to memorize val set in 4 steps (AUROC 0.80→0.99).
# 3e-6 gives slower, more stable learning that stays competitive with paraphraser.
DETECTOR_LR = 3e-6
DETECTOR_BATCH = 8 # Fix OOM-1: halved to cut RoBERTa activation memory
ATTACK_MICRO_BATCH = 4 # Fix OOM-2: micro-batch for per-attack loss groups
DETECTOR_MAX_LEN = 512
# ── ADAL v2: Asymmetric label smoothing ──────────────────────────────────────
# Penalise FP harder than FN (critical for 1% FPR target).
# Human side uses near-zero smoothing so the detector is confidently trained
# NOT to fire on humans. AI side keeps normal smoothing to avoid memorisation.
# This shifts the model's decision surface away from human-text region.
LABEL_SMOOTHING_ALPHA = 0.15 # legacy — kept for backward compat
HUMAN_SMOOTHING_ALPHA = 0.02 # NEW: near-zero smoothing on human class
AI_SMOOTHING_ALPHA = 0.15 # same smoothing as before on AI class
# ── ADAL v2: Target operating point for model selection ──────────────────────
# Primary metric for best checkpoint = TPR @ 1% FPR (not macro AUROC).
# At 1% FPR, only 1 in 100 human texts triggers false accusation — suitable
# for real academic use. Secondary metric macro AUROC is still tracked.
TARGET_FPR = 0.01 # 1% FPR operating point
USE_TPR_AT_FPR_FOR_BEST = True # True → best ckpt = max(TPR@1%FPR)
# False → best ckpt = max(macro AUROC)
# Fit post-hoc isotonic calibrator on best checkpoint's val scores.
# Gives a 1-3 point TPR@1%FPR boost via better score calibration.
FIT_ISOTONIC_CALIBRATOR = True
# ══════════════════════════════════════════════════════════════════════════════
# ADAL v3 — BIDIRECTIONAL ADVERSARIAL GAME (Humanizer of Humans, Gψ)
# ══════════════════════════════════════════════════════════════════════════════
# Extends the RADAR framework with a SECOND PPO-trained attacker:
#
# Gσ (paraphraser) : AI text → "looks human" (original RADAR game)
# Gψ (humanizer) : human text → "looks AI" (NEW — attacks FP side)
# Dϕ (detector) : must resist BOTH directions
#
# The detector now sees 4 streams each batch:
# 1. clean human → target = HUMAN
# 2. clean AI → target = AI
# 3. AI→humanized (Gσ) → target = AI (still AI — same as RADAR)
# 4. human→AI-ified (Gψ) → target = HUMAN (NEW — still human, despite Gψ's perturbation)
#
# The symmetric game directly punishes false positives at training time:
# Gψ tries to push human text above the detector's decision threshold;
# the detector is forced to learn that "perturbed human" is still human,
# which tightens the low-FPR side of the ROC curve.
#
# Reference: novel to ADAL v3. No published work on symmetric bidirectional
# adversarial AI-text detection to author's knowledge.
# ══════════════════════════════════════════════════════════════════════════════
HUMANIZER_ENABLED = True # Master switch for v3 bidirectional game
HUMANIZER_MODEL_NAME = "ramsrigouthamg/t5_paraphraser" # same as Gσ
HUMANIZER_LR = 2e-5 # match paraphraser LR
HUMANIZER_MAX_NEW_TOKENS = 128
HUMANIZER_MAX_INPUT_LEN = 256
HUMANIZER_TOP_K = 50
HUMANIZER_TOP_P = 1.0
HUMANIZER_TEMPERATURE = 1.0
HUMANIZER_REPETITION_PEN = 1.3
HUMANIZER_WARMSTART_STEPS = 0 # no MLE warmstart — diverge from paraphraser
# Humanizer prompt — encourages "AI-like" rewrite (formal, bullet-heavy,
# perfect punctuation, longer sentences). Experiment with these prompts;
# they dramatically change what Gψ learns to produce.
HUMANIZER_PROMPT_PREFIX = "YOU ARE AN EXPERT IN WRITING STYLES FOLLOWED BY AI MODELS. GIVEN A HUMAN-WRITTEN TEXT YOU CAN CONVERT IT TO AI-GENERATED TEXT STYLE. REWRITE THE GIVEN TEXT IN A FORMAL, POLISHED AI-LIKE STYLE. "
# Reward for Gψ is P(AI) from the detector on humanized human text.
# We want the humanizer to MAXIMIZE this (push humans past threshold).
# Detector is trained to RESIST this (keep P(AI) low even on humanized humans).
HUMANIZER_REWARD_CLIP_MIN = 0.01
HUMANIZER_REWARD_CLIP_MAX = 0.99
# Humanizer PPO hyperparameters (mostly mirror paraphraser)
HUMANIZER_PPO_EPSILON = 0.2
HUMANIZER_ENTROPY_COEFF = 0.01
HUMANIZER_KL_COEFF = 0.001
# Detector loss weight for L_xh_humanized (the critical FP-defense term).
# Higher = stronger pressure to maintain low FPR on perturbed humans.
# Default 1.5 — slightly higher than clean-human weight (1.0) because
# humanized humans are the hard negatives we explicitly care about.
HUMANIZER_LOSS_WEIGHT = 1.5
# Humanizer update frequency — same as paraphraser by default.
# Setting HUMANIZER_UPDATE_EVERY=4 would let detector catch up between
# humanizer updates; useful if humanizer overwhelms detector early.
HUMANIZER_UPDATE_EVERY = 1 # every buffer fill
# Update detector every 2 steps — updating every step caused memorization
# of the 9900-sample training set in just 4 steps (AUROC 0.80→0.99).
DETECTOR_UPDATE_EVERY = 2
# Dynamic freeze: if macro AUROC exceeds this threshold the detector update
# is skipped for the next DETECTOR_FREEZE_STEPS steps, giving the paraphraser
# room to catch up before the detector is allowed to train again.
AUROC_FREEZE_THRESHOLD = 0.995
DETECTOR_FREEZE_STEPS = 3
# ── Reward clipping ───────────────────────────────────────────────────────────
# Wider clip range — rewards were stuck at 0.31 which is well within [0.05,0.95]
# so clipping was not the issue. Keep wide to not interfere with natural signal.
REWARD_CLIP_MIN = 0.01
REWARD_CLIP_MAX = 0.99
# ── Warm-start ────────────────────────────────────────────────────────────────
# Warmstart is disabled: some T5-base checkpoints have gradient instability on step 1
# (MLE→NaN) which poisons all subsequent generate() calls with NaN logits.
# PPO works fine without warmstart — the paraphraser learns from reward signal directly.
WARMSTART_STEPS = 0
# ── Training loop ─────────────────────────────────────────────────────────────
MAX_OUTER_STEPS = 200
WARMUP_STEPS = 50
VALIDATE_EVERY = 5 # BALANCE: validate more often so we can catch the peak before collapse
PATIENCE = 25 # BALANCE: more patience since reward oscillates in a healthy game
GRAD_CLIP = 1.0
# ── Output paths ──────────────────────────────────────────────────────────────
OUTPUT_DIR = "./adal_v3_raid"
DETECTOR_SAVE_PATH = os.path.join(OUTPUT_DIR, "best_detector")
PARAPHRASER_SAVE_PATH = os.path.join(OUTPUT_DIR, "best_paraphraser")
HUMANIZER_SAVE_PATH = os.path.join(OUTPUT_DIR, "best_humanizer") # ADAL v3
LOG_FILE = os.path.join(OUTPUT_DIR, "training.log")
AUROC_LOG_FILE = os.path.join(OUTPUT_DIR, "per_generator_auroc.tsv")
ATTACK_AUROC_LOG = os.path.join(OUTPUT_DIR, "per_attack_auroc.tsv")
# ── HuggingFace Hub — push trained models here ────────────────────────────────
# Get your token from: https://huggingface.co/settings/tokens (write access needed)
HF_TOKEN = "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" # ← paste your HF write token
HF_USERNAME = "Shushanta" # ← MUST match exactly: huggingface.co/settings/profile
# The 403 error means this is wrong or the org
# namespace does not exist. Use your personal handle.
# Repo IDs: will be created automatically if they don't exist
# Final repo URLs:
# https://huggingface.co/{HF_USERNAME}/{HF_DETECTOR_REPO}
# https://huggingface.co/{HF_USERNAME}/{HF_PARAPHRASER_REPO}
HF_DETECTOR_REPO = "ADAL-v3" # ← repo name for the detector
HF_PARAPHRASER_REPO = "adal-v3-t5-paraphraser" # ← repo name for the paraphraser
# When to push:
# "best" → push only when a new best AUROC checkpoint is saved (recommended)
# "final" → push only at the end of training
# "both" → push on every new best AND at end of training
HF_PUSH_STRATEGY = "both"
# Set False to skip HF push entirely (e.g. for quick debug runs)
HF_PUSH_ENABLED = True
# ══════════════════════════════════════════════════════════════════════════════
# Logging
# ══════════════════════════════════════════════════════════════════════════════
os.makedirs(OUTPUT_DIR, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
handlers=[
logging.FileHandler(LOG_FILE),
logging.StreamHandler(),
],
)
logger = logging.getLogger(__name__)
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
# ══════════════════════════════════════════════════════════════════════════════
# EVASION ATTACK POOL
# ══════════════════════════════════════════════════════════════════════════════
# ─── Homoglyph mapping ────────────────────────────────────────────────────────
# ASCII char → list of visually near-identical Unicode alternatives.
# Covers Cyrillic, Greek, and other scripts that look identical in many fonts.
HOMOGLYPH_MAP: Dict[str, List[str]] = {
'a': ['а', 'ɑ', 'α'], # Cyrillic а, Latin alpha, Greek alpha
'c': ['с', 'ϲ'], # Cyrillic с, Greek lunate sigma
'e': ['е', 'ė'], # Cyrillic е
'i': ['і', 'і'], # Cyrillic і
'j': ['ϳ'], # Cyrillic ϳ
'o': ['о', 'ο', '0'], # Cyrillic о, Greek omicron, fullwidth 0
'p': ['р', 'ρ'], # Cyrillic р, Greek rho
's': ['ѕ'], # Cyrillic ѕ
'u': ['υ'], # Greek upsilon
'x': ['х', 'χ'], # Cyrillic х, Greek chi
'y': ['у', 'ý'], # Cyrillic у
'B': ['В', 'Β'], # Cyrillic В, Greek Beta
'C': ['С', 'Ϲ'],
'E': ['Е', 'Ε'], # Cyrillic Е, Greek Epsilon
'H': ['Н', 'Η'], # Cyrillic Н, Greek Eta
'I': ['І', 'Ι'],
'K': ['К', 'Κ'], # Cyrillic К, Greek Kappa
'M': ['М', 'Μ'],
'N': ['Ν'], # Greek Nu
'O': ['О', 'Ο', '0'], # Cyrillic О, Greek Omicron
'P': ['Р', 'Ρ'], # Cyrillic Р, Greek Rho
'T': ['Т', 'Τ'],
'X': ['Х', 'Χ'],
'Z': ['Ζ'], # Greek Zeta
}
# Adjacent keys on a QWERTY keyboard for realistic typo generation
QWERTY_ADJACENT: Dict[str, str] = {
'q':'wa', 'w':'qeas', 'e':'wsdr', 'r':'edft', 't':'rfgy', 'y':'tghu',
'u':'yhji', 'i':'ujko', 'o':'iklp', 'p':'ol',
'a':'qwsz', 's':'awedxz', 'd':'serfcx', 'f':'drtgvc', 'g':'ftyhbv',
'h':'gyujnb', 'j':'huikmn', 'k':'jiolm', 'l':'kop',
'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn',
'n':'bhjm', 'm':'njk',
}
ARTICLES = {'a', 'an', 'the'}
# ─── Number swap mapping (visually similar digits) ────────────────────────────
# 3↔8, 6↔9, 0↔O — chosen to be visually confusing but preserve plausibility.
NUMBER_SWAP_MAP: Dict[str, List[str]] = {
'0': ['O', 'o', 'Q'],
'1': ['l', 'I', '7'],
'2': ['Z', 'z'],
'3': ['8', 'B'],
'4': ['A', '9'],
'5': ['S', 's'],
'6': ['9', 'G'],
'7': ['1', 'T'],
'8': ['3', 'B'],
'9': ['6', '4', 'g'],
}
# ─── Zero-width invisible Unicode characters ──────────────────────────────────
# Invisible to humans but tokenizers see them → breaks detector's tokenization.
ZERO_WIDTH_CHARS = [
'\u200b', # ZERO WIDTH SPACE
'\u200c', # ZERO WIDTH NON-JOINER
'\u200d', # ZERO WIDTH JOINER
'\ufeff', # ZERO WIDTH NO-BREAK SPACE
]
# ─── UK ↔ US spelling variant map ─────────────────────────────────────────────
# Swaps British/American spellings. Common in academic writing & a real-world
# source of false positives when detectors are trained on one variant only.
# Bidirectional: entries here are applied in both directions at random.
UK_US_SPELLING_MAP: Dict[str, str] = {
# -our / -or
'colour': 'color', 'colours': 'colors', 'coloured': 'colored',
'flavour': 'flavor', 'flavours': 'flavors',
'honour': 'honor', 'honours': 'honors',
'labour': 'labor', 'labours': 'labors',
'behaviour': 'behavior', 'behaviours': 'behaviors',
'favourite': 'favorite', 'favourites': 'favorites',
'neighbour': 'neighbor', 'neighbours': 'neighbors',
'humour': 'humor',
'rumour': 'rumor', 'rumours': 'rumors',
'harbour': 'harbor', 'harbours': 'harbors',
# -ise / -ize
'organise': 'organize', 'organised': 'organized', 'organising': 'organizing',
'organisation': 'organization', 'organisations': 'organizations',
'realise': 'realize', 'realised': 'realized', 'realising': 'realizing',
'recognise': 'recognize', 'recognised': 'recognized',
'analyse': 'analyze', 'analysed': 'analyzed', 'analysing': 'analyzing',
'criticise': 'criticize', 'criticised': 'criticized',
'emphasise': 'emphasize', 'emphasised': 'emphasized',
'summarise': 'summarize', 'summarised': 'summarized',
'categorise': 'categorize', 'categorised': 'categorized',
'maximise': 'maximize', 'minimise': 'minimize',
'optimise': 'optimize', 'optimised': 'optimized',
'prioritise': 'prioritize', 'prioritised': 'prioritized',
# -re / -er
'centre': 'center', 'centres': 'centers', 'centred': 'centered',
'theatre': 'theater', 'theatres': 'theaters',
'metre': 'meter', 'metres': 'meters',
'litre': 'liter', 'litres': 'liters',
'fibre': 'fiber', 'fibres': 'fibers',
# -ce / -se (nouns)
'defence': 'defense', 'offence': 'offense',
'licence': 'license', 'practise': 'practice',
# -gue / -g
'catalogue': 'catalog', 'catalogues': 'catalogs',
'dialogue': 'dialog', 'dialogues': 'dialogs',
# misc
'travelled': 'traveled', 'travelling': 'traveling',
'modelled': 'modeled', 'modelling': 'modeling',
'programme': 'program', 'programmes': 'programs',
'grey': 'gray', 'cheque': 'check',
'aluminium': 'aluminum', 'aeroplane': 'airplane',
'judgement': 'judgment', 'acknowledgement': 'acknowledgment',
'enrolment': 'enrollment', 'fulfilment': 'fulfillment',
'sceptical': 'skeptical', 'manoeuvre': 'maneuver',
'ageing': 'aging', 'whilst': 'while', 'amongst': 'among',
'learnt': 'learned', 'burnt': 'burned', 'spelt': 'spelled',
'dreamt': 'dreamed', 'spoilt': 'spoiled',
}
# Also include the reverse direction (US → UK)
UK_US_SPELLING_MAP_REVERSE = {v: k for k, v in UK_US_SPELLING_MAP.items()}
class AttackResult(NamedTuple):
text: str
attack_name: str
class EvasionAttackPool:
"""
Pool of 6 text evasion attacks (1 learnable, 5 deterministic).
All deterministic attacks are pure Python — no GPU required.
They run in milliseconds and are applied in-process during buffer filling.
Attack taxonomy
───────────────
Neural (Track A, PPO-trained):
t5_paraphrase — Gσ rewrites the text via seq2seq
Linguistic (Track B, data augmentation for detector):
recursive_para — chain T5 paraphrase N times
synonym_replacement— WordNet-based word swap
article_deletion — drop 'a/an/the' tokens
misspelling — QWERTY adjacent-key typo injection
Character-level (Track B):
homoglyphs — swap ASCII → visually identical Unicode
"""
def __init__(self, paraphraser_model=None, paraphraser_tokenizer=None):
"""
paraphraser_model / tokenizer: the T5 model instance.
Pass None to disable neural attacks (pure deterministic mode).
"""
self.t5_model = paraphraser_model
self.t5_tokenizer = paraphraser_tokenizer
# ─── Track A: Neural T5 paraphrase ───────────────────────────────────────
@torch.no_grad()
def t5_paraphrase(self, texts: List[str], depth: int = 1) -> List[str]:
"""
Apply T5 paraphrase `depth` times in a chain.
depth=1 → standard single-pass paraphrase (same as original RADAR).
depth=2 → recursive double paraphrase.
"""
if self.t5_model is None:
return texts # fallback: no-op
current = texts
for _ in range(depth):
# Use the model's ACTUAL device — may be CPU when offloaded
model_device = next(self.t5_model.parameters()).device
# Use model-aware prefix — ramsrigouthamg uses lowercase "paraphrase: "
prefix = "paraphrase: " if any(x in PARAPHRASER_MODEL_NAME
for x in ("humarin", "ramsrigouthamg")) else "Paraphrase: "
prefixed = [f"{prefix}{t}" for t in current]
enc = self.t5_tokenizer(
prefixed, return_tensors="pt", padding=True,
truncation=True, max_length=PARAPHRASER_MAX_INPUT_LEN,
).to(model_device)
first_param = next(self.t5_model.parameters())
if torch.isnan(first_param).any():
raise RuntimeError("Attack pool T5 weights contain NaN — model corrupted.")
# Use beam search (do_sample=False) for the attack pool — this is only
# used for AUROC measurement, not PPO gradient computation.
# Beam search never calls torch.multinomial so it CANNOT crash with the
# "inf/nan in probability tensor" error that stochastic sampling can hit.
try:
gen_ids = self.t5_model.generate(
input_ids=enc["input_ids"],
attention_mask=enc["attention_mask"],
max_new_tokens=PARAPHRASER_MAX_NEW_TOKENS,
do_sample=False, # beam search — no multinomial, no NaN crash
num_beams=4,
repetition_penalty=PARAPHRASER_REPETITION_PEN,
pad_token_id=self.t5_tokenizer.pad_token_id,
early_stopping=True,
)
current = [
self.t5_tokenizer.decode(ids, skip_special_tokens=True)
for ids in gen_ids
]
except RuntimeError as e:
logger.warning(f" attack_pool.t5_paraphrase generate failed: {e} — returning originals")
current = current # return input unchanged if generate crashes
return current
# ─── Synonym Replacement ─────────────────────────────────────────────────
@staticmethod
def _get_wordnet_pos(treebank_tag: str) -> Optional[str]:
"""Convert Penn Treebank POS tag to WordNet POS."""
if treebank_tag.startswith('J'):
return wordnet.ADJ
if treebank_tag.startswith('V'):
return wordnet.VERB
if treebank_tag.startswith('N'):
return wordnet.NOUN
if treebank_tag.startswith('R'):
return wordnet.ADV
return None
@staticmethod
def synonym_replace(text: str, rate: float = SYNONYM_REPLACE_RATE) -> str:
"""
Replace content words (N/V/ADJ/ADV) with a random WordNet synonym.
Preserves original capitalisation and non-content tokens.
Example:
"The quick brown fox" → "The swift brown fox"
"""
if not NLTK_AVAILABLE:
return text
try:
tokens = word_tokenize(text)
pos_tags = pos_tag(tokens)
except Exception:
return text
new_tokens = []
for word, tag in pos_tags:
wn_pos = EvasionAttackPool._get_wordnet_pos(tag)
if wn_pos and random.random() < rate:
synsets = wordnet.synsets(word, pos=wn_pos)
synonyms = [
lemma.name().replace('_', ' ')
for syn in synsets
for lemma in syn.lemmas()
if lemma.name().lower() != word.lower()
and '_' not in lemma.name() # exclude multi-word
]
if synonyms:
chosen = random.choice(synonyms)
# Preserve capitalisation
if word[0].isupper():
chosen = chosen.capitalize()
new_tokens.append(chosen)
continue
new_tokens.append(word)
return ' '.join(new_tokens)
# ─── Homoglyphs ───────────────────────────────────────────────────────────
@staticmethod
def homoglyph_replace(text: str, rate: float = HOMOGLYPH_RATE) -> str:
"""
Randomly replace ASCII characters with visually identical Unicode
homoglyphs. The text looks identical to humans but changes the token
sequence seen by the detector's tokeniser.
Only substitutes characters that have a known safe homoglyph.
Replaces at most `rate` fraction of eligible characters.
Example (ASCII 'o' → Cyrillic 'о'):
"Hello world" → "Hellо wоrld" (two characters changed)
"""
chars = list(text)
eligible = [
i for i, ch in enumerate(chars) if ch in HOMOGLYPH_MAP
]
n_replace = max(1, int(len(eligible) * rate))
targets = random.sample(eligible, min(n_replace, len(eligible)))
for idx in targets:
ch = chars[idx]
chars[idx] = random.choice(HOMOGLYPH_MAP[ch])
return ''.join(chars)
# ─── Article Deletion ─────────────────────────────────────────────────────
@staticmethod
def article_deletion(text: str, rate: float = ARTICLE_DELETE_RATE) -> str:
"""
Delete articles ('a', 'an', 'the') with probability `rate`.
This mimics the writing style of non-native English speakers, who
frequently omit articles. The RADAR paper (§1) notes that detectors
show bias against non-native writers; this attack exploits that.
Example:
"The cat sat on a mat" → "cat sat on mat" (rate=1.0)
"""
tokens = text.split()
new_tokens = []
for tok in tokens:
if tok.lower() in ARTICLES and random.random() < rate:
continue # drop the article
new_tokens.append(tok)
return ' '.join(new_tokens)
# ─── Random Misspelling ───────────────────────────────────────────────────
@staticmethod
def random_misspelling(text: str, rate: float = MISSPELLING_RATE) -> str:
"""
Introduce realistic typos via QWERTY adjacent-key substitution.
Only affects words longer than 3 chars. One typo per affected word.
Types of insertion (randomly chosen for each typo):
• adjacent-key swap : 'e' → 'w' or 'r' (most common real typo)
• character deletion : removes a random interior char
• character duplication: doubles a random interior char
Example:
"detection" → "dwtection" (e→w swap)
"""
words = text.split()
new_words = []
for word in words:
if len(word) > 3 and random.random() < rate:
typo_type = random.choice(['swap', 'delete', 'duplicate'])
chars = list(word)
idx = random.randint(1, len(chars) - 2) # avoid first/last
if typo_type == 'swap':
ch = chars[idx].lower()
neighbors = QWERTY_ADJACENT.get(ch, '')
if neighbors:
replacement = random.choice(neighbors)
if chars[idx].isupper():
replacement = replacement.upper()
chars[idx] = replacement
elif typo_type == 'delete':
chars.pop(idx)
elif typo_type == 'duplicate':
chars.insert(idx, chars[idx])
new_words.append(''.join(chars))
else:
new_words.append(word)
return ' '.join(new_words)
# ═══════════════════════════════════════════════════════════════════════
# ADAL v2: NEW ATTACKS (7 added)
# ═══════════════════════════════════════════════════════════════════════
# ─── Number Swap ──────────────────────────────────────────────────────────
@staticmethod
def number_swap(text: str, rate: float = NUMBER_SWAP_RATE) -> str:
"""
Replace digits with visually similar characters or other digits.
Mimics OCR-style confusion and attempts to fool stylometric detectors
that use digit frequency as a feature.
Example: "I have 3 apples and 8 oranges" → "I have 8 apples and 3 oranges"
"""
chars = list(text)
for i, ch in enumerate(chars):
if ch in NUMBER_SWAP_MAP and random.random() < rate:
chars[i] = random.choice(NUMBER_SWAP_MAP[ch])
return ''.join(chars)
# ─── Whitespace Addition ──────────────────────────────────────────────────
@staticmethod
def whitespace_addition(text: str, rate: float = WHITESPACE_ADD_RATE) -> str:
"""
Insert extra spaces between words. Common evasion when copying from PDFs
or when humans type with inconsistent spacing. Breaks BPE tokenization
slightly → can confuse transformer-based detectors at the token level.
Example: "the cat sat" → "the cat sat"
"""
words = text.split(' ')
new_parts = []
for i, w in enumerate(words):
new_parts.append(w)
if i < len(words) - 1:
# Normal single space, plus extra spaces with probability=rate
new_parts.append(' ')
while random.random() < rate:
new_parts.append(' ')
return ''.join(new_parts)
# ─── Upper-Lower Case Swap ────────────────────────────────────────────────
@staticmethod
def upper_lower_swap(text: str, rate: float = UPPER_LOWER_SWAP_RATE) -> str:
"""
Randomly flip the case of individual letters. At low rates this looks
like sloppy capitalisation; at high rates it resembles "mocking text".
Affects RoBERTa-cased tokenization → breaks token identity.
Example: "The quick brown fox" → "The qUick brOwn fox"
"""
chars = list(text)
for i, ch in enumerate(chars):
if ch.isalpha() and random.random() < rate:
chars[i] = ch.lower() if ch.isupper() else ch.upper()
return ''.join(chars)
# ─── Zero-Width Space Injection ───────────────────────────────────────────
@staticmethod
def zero_width_space_inject(text: str, rate: float = ZERO_WIDTH_INJECT_RATE) -> str:
"""
Inject invisible Unicode characters (U+200B etc.) between words.
These are invisible to humans but tokenizers see them, splitting
words into strange subword sequences. A well-known detector-evasion
technique reported in Pangram's adversarial attack analysis.
Example (visually): "the cat sat" → "the cat sat" (with invisible ZWSPs)
"""
words = text.split(' ')
new_parts = []
for i, w in enumerate(words):
# With probability `rate`, inject a zero-width char inside the word
if w and random.random() < rate:
zw = random.choice(ZERO_WIDTH_CHARS)
# Insert at a random mid-position inside the word
pos = random.randint(1, len(w)) if len(w) > 1 else 0
w = w[:pos] + zw + w[pos:]
new_parts.append(w)
return ' '.join(new_parts)
# ─── Insert Paragraphs ────────────────────────────────────────────────────
@staticmethod
def insert_paragraphs(text: str, rate: float = INSERT_PARA_RATE) -> str:
"""
Randomly break the text into paragraphs by inserting newlines after
sentence boundaries. Humans naturally write in paragraphs; many AI
outputs are single walls of text. Adding paragraph breaks is a common
"humanizer" technique that fools detectors relying on paragraph-level
structure as a signal.
Example: "...first sentence. Second sentence..." →
"...first sentence.\n\nSecond sentence..."
"""
# Simple sentence boundary: split on .!? followed by space + capital letter
# Keep the punctuation attached to the preceding sentence
parts = re.split(r'(?<=[.!?])\s+(?=[A-Z])', text)
if len(parts) <= 1:
return text
new_parts = []
for i, part in enumerate(parts):
new_parts.append(part)
if i < len(parts) - 1:
if random.random() < rate:
new_parts.append('\n\n') # paragraph break
else:
new_parts.append(' ')
return ''.join(new_parts)
# ─── Alternative Spelling (UK ↔ US) ───────────────────────────────────────
@staticmethod
def alternative_spelling(text: str, rate: float = ALT_SPELLING_RATE) -> str:
"""
Swap British ↔ American spellings (colour↔color, organise↔organize).
Done at a per-word level with probability `rate`. Uses both maps so
UK and US variants are both targeted. Critical for academic settings
where non-native speakers mix variants — a genuine FP source in the
wild, not just a synthetic attack.
Example: "I organised the colour palette" → "I organized the color palette"
"""
words = text.split(' ')
new_words = []
for w in words:
# Strip punctuation to match dict keys; remember suffix to re-attach
stripped = w.rstrip('.,;:!?"\')(')
suffix = w[len(stripped):]
prefix = ''
while stripped and stripped[0] in '"\'(':
prefix += stripped[0]
stripped = stripped[1:]
lower = stripped.lower()
replacement = None
if lower in UK_US_SPELLING_MAP and random.random() < rate:
replacement = UK_US_SPELLING_MAP[lower]
elif lower in UK_US_SPELLING_MAP_REVERSE and random.random() < rate:
replacement = UK_US_SPELLING_MAP_REVERSE[lower]
if replacement is not None:
# Preserve case of original
if stripped.isupper():
replacement = replacement.upper()
elif stripped and stripped[0].isupper():
replacement = replacement.capitalize()
new_words.append(prefix + replacement + suffix)
else:
new_words.append(w)
return ' '.join(new_words)
# ─── Apply all deterministic attacks to a batch ───────────────────────────
def apply_all_deterministic(
self,
ai_texts: List[str],
) -> Dict[str, List[str]]:
"""
Apply every enabled deterministic attack to the batch of AI texts.
Returns a dict mapping attack_name → list of evaded texts.
These outputs are used ONLY for detector training (Track B).
They do not participate in PPO updates.
"""
results: Dict[str, List[str]] = {}
if ATTACK_RECURSIVE_PARA and self.t5_model is not None:
results["recursive_para"] = self.t5_paraphrase(
ai_texts, depth=RECURSIVE_PARA_DEPTH
)
if ATTACK_SYNONYM_REPLACEMENT and NLTK_AVAILABLE:
results["synonym_replacement"] = [
self.synonym_replace(t) for t in ai_texts
]
if ATTACK_HOMOGLYPHS:
results["homoglyphs"] = [
self.homoglyph_replace(t) for t in ai_texts
]
if ATTACK_ARTICLE_DELETION:
results["article_deletion"] = [
self.article_deletion(t) for t in ai_texts
]
if ATTACK_MISSPELLING:
results["misspelling"] = [
self.random_misspelling(t) for t in ai_texts
]
# ── ADAL v2: 7 new deterministic attacks ────────────────────────────
if ATTACK_NUMBER_SWAP:
results["number_swap"] = [
self.number_swap(t) for t in ai_texts
]
if ATTACK_WHITESPACE_ADDITION:
results["whitespace_addition"] = [
self.whitespace_addition(t) for t in ai_texts
]
if ATTACK_UPPER_LOWER_SWAP:
results["upper_lower_swap"] = [
self.upper_lower_swap(t) for t in ai_texts
]
if ATTACK_ZERO_WIDTH_SPACE:
results["zero_width_space"] = [
self.zero_width_space_inject(t) for t in ai_texts
]
if ATTACK_INSERT_PARAGRAPHS:
results["insert_paragraphs"] = [
self.insert_paragraphs(t) for t in ai_texts
]
if ATTACK_ALTERNATIVE_SPELLING:
results["alternative_spelling"] = [