pgd
Search for classification and general-property counterexamples using projected gradient descent.
pgd_attack(model, data, target, x_L, x_U, restarts=1, step_size=0.2, n_steps=200, early_stopping=True, device='cuda', decay_factor=0.1, decay_checkpoints=(), *, loss_fn=None, is_success=None)
Search for counterexamples using Projected Gradient Descent (PGD).
Each restart begins at a random point in the input box. Gradient-sign updates maximise the attack objective and are projected back into that box. The step size is scaled by the largest coordinate half-width. The caller chooses the model mode; the attack computes input gradients without accumulating parameter gradients. Optional callbacks extend the search from misclassification to general output-property violations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The neural network model to attack. |
required |
data
|
Tensor
|
The input data to perturb. |
required |
target
|
Tensor | None
|
Labels, or None with both property callbacks. |
required |
x_L
|
Tensor
|
The lower bound of the input data. |
required |
x_U
|
Tensor
|
The upper bound of the input data. |
required |
restarts
|
int
|
The number of random restarts. |
1
|
step_size
|
float
|
Step-size factor multiplied by the largest coordinate half-width of the search box. |
0.2
|
n_steps
|
int
|
The number of steps for the attack. |
200
|
early_stopping
|
bool
|
Whether to stop early if adversarial examples are found. |
True
|
device
|
str
|
The device to perform the attack on. |
'cuda'
|
decay_factor
|
float
|
The factor by which to decay the step size at each checkpoint. |
0.1
|
decay_checkpoints
|
tuple
|
The checkpoints at which to decay the step size. |
()
|
loss_fn
|
callable
|
Per-example attack objective to maximise, called as loss_fn(output, target). Defaults to cross-entropy. |
None
|
is_success
|
callable
|
Per-example Boolean violation test, called as is_success(output, target). Defaults to misclassification. General-property callbacks may use target=None. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The best successful candidate per input, or the largest attack-objective candidate if none succeeded. Checks nominal inputs, random initializations and every update, including with n_steps=0. |
Source code in CTRAIN/attacks/pgd.py
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 | |