File size: 2,509 Bytes
10979b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import math

import torch
from torch import nn

from gmnet.robustness.attacks import (
    perturbation_band_fraction,
    pgd_l2_frequency,
    pgd_linf,
    project_frequency,
    radial_frequency_mask,
)
from gmnet.robustness.corruptions import apply_imagenet_corruption


class TinyClassifier(nn.Module):
    def forward(self, images: torch.Tensor) -> torch.Tensor:
        means = images.mean(dim=(2, 3))
        return torch.stack((means[:, 0], means[:, 1]), dim=1)


def test_jpeg_and_noise_are_deterministic() -> None:
    image = torch.linspace(0, 1, 3 * 32 * 32).reshape(3, 32, 32)
    assert torch.equal(
        apply_imagenet_corruption(image, "gaussian_noise", 7),
        apply_imagenet_corruption(image, "gaussian_noise", 7),
    )
    jpeg = apply_imagenet_corruption(image, "jpeg", 0)
    assert jpeg.shape == image.shape
    assert 0.0 <= jpeg.min() <= jpeg.max() <= 1.0


def test_frequency_projection_is_band_limited() -> None:
    delta = torch.randn(2, 3, 16, 16)
    mask = radial_frequency_mask(16, 16, (0.0, 0.2), delta.device)
    projected = project_frequency(delta, mask)
    fraction = perturbation_band_fraction(projected, mask)
    assert torch.all(fraction > 1.0 - 1e-6)


def test_linf_pgd_obeys_pixel_and_norm_constraints() -> None:
    model = TinyClassifier()
    clean = torch.rand(2, 3, 8, 8)
    target = torch.tensor([0, 1])
    epsilon = 4 / 255
    adversarial, diagnostics = pgd_linf(
        model,
        clean,
        target,
        lambda value: value,
        epsilon=epsilon,
        step_size=1 / 255,
        steps=2,
        generator=torch.Generator().manual_seed(1),
    )
    assert adversarial.min() >= 0 and adversarial.max() <= 1
    assert diagnostics["linf"].max() <= epsilon + 1e-7


def test_frequency_pgd_has_equal_budget_constraint() -> None:
    model = TinyClassifier()
    clean = 0.1 + 0.8 * torch.rand(2, 3, 16, 16)
    target = torch.tensor([0, 1])
    epsilon = 0.5
    adversarial, diagnostics = pgd_l2_frequency(
        model,
        clean,
        target,
        lambda value: value,
        band=(0.15, 0.4),
        epsilon=epsilon,
        step_size=0.1,
        steps=2,
        generator=torch.Generator().manual_seed(2),
        projection_iterations=8,
    )
    assert adversarial.min() >= 0 and adversarial.max() <= 1
    assert diagnostics["l2"].max() <= epsilon + 1e-6
    assert diagnostics["band_fraction"].min() > 0.999
    assert math.isfinite(float(diagnostics["l2"].mean()))