Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reproduce #122

Merged
merged 121 commits into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
121 commits
Select commit Hold shift + click to select a range
ee203d3
fixed art bug
simplymathematics May 23, 2023
9e891f0
fixed param bug
simplymathematics May 23, 2023
e4483f6
art bug
simplymathematics May 23, 2023
e132634
+tested attacks on torch
simplymathematics May 23, 2023
7a8f481
generate_grid draft
simplymathematics May 31, 2023
10c9a54
Initial terraform instructions
salehsedghpour Jun 24, 2023
e292038
add networks and firewall rules for K8s
salehsedghpour Jun 24, 2023
99f76b2
create VMs
salehsedghpour Jun 24, 2023
4c17e32
rename functions to main
salehsedghpour Jun 24, 2023
a69bd93
add README
salehsedghpour Jun 24, 2023
a756254
setup and cleanup infrastructure
salehsedghpour Aug 21, 2023
bd2f3d5
not working version
salehsedghpour Aug 23, 2023
b9a5005
add GCP support
salehsedghpour Aug 30, 2023
4ab0f3d
linting
simplymathematics Sep 1, 2023
d85eace
Merge branch 'main' of github.com:simplymathematics/deckard into add-…
simplymathematics Sep 1, 2023
2da52dd
moved iaac folder
simplymathematics Sep 1, 2023
1fb7d5e
draft dataclass and deploy script for gcp
simplymathematics Sep 1, 2023
f604dbc
added package stuff
simplymathematics Sep 1, 2023
3792bda
linting
simplymathematics Sep 1, 2023
503de61
improved compile.py, plots.py
simplymathematics Sep 3, 2023
4b46e5a
linting
simplymathematics Sep 3, 2023
73c611d
linting
simplymathematics Sep 3, 2023
338c307
linting
simplymathematics Sep 3, 2023
4459d49
linting
simplymathematics Sep 3, 2023
4cdba38
linting
simplymathematics Sep 4, 2023
5d08c04
more changes
simplymathematics Sep 4, 2023
e445870
fix compile, plot scripts
simplymathematics Sep 4, 2023
7f1981c
Merge branch 'add-iaac' of github.com:simplymathematics/deckard into …
simplymathematics Sep 4, 2023
f75bc1a
linting
simplymathematics Sep 4, 2023
9daf2d0
linting
simplymathematics Sep 4, 2023
022310c
fixed Dockerfile
simplymathematics Sep 4, 2023
2235ea2
+fixed install, dockerfile
simplymathematics Sep 4, 2023
7a8f572
dockerfile
simplymathematics Sep 6, 2023
c723035
linting
simplymathematics Sep 6, 2023
eba5459
deploy script updates, new docker.yml action
simplymathematics Sep 6, 2023
fb0bc27
Merge branch 'add-iaac' of https://github.com/simplymathematics/decka…
simplymathematics Sep 6, 2023
9c87d06
update precommit file and linting
simplymathematics Sep 6, 2023
ed385ad
+change docker workflow to push to gh
simplymathematics Sep 6, 2023
a73a78b
+change docker workflow to push to gh
simplymathematics Sep 6, 2023
d324cf3
Dockerfile changes
simplymathematics Sep 6, 2023
9b0e896
Dockerfile changes
simplymathematics Sep 6, 2023
13748f1
Dockerfile changes
simplymathematics Sep 6, 2023
dce524f
Dockerfile changes
simplymathematics Sep 6, 2023
a458242
moved gcp conf
simplymathematics Sep 6, 2023
26ca22c
+deploy.py script fixes (still broken)
simplymathematics Sep 6, 2023
e5c805b
Dockerfile
simplymathematics Sep 6, 2023
1dac445
add csi driver
salehsedghpour Sep 6, 2023
5b55e13
fixed python alias in dockerfile
simplymathematics Sep 6, 2023
eb42845
split docker workflow into test/push
simplymathematics Sep 6, 2023
28fc833
add the imagePullPolicy for the pod
salehsedghpour Sep 6, 2023
e2215a1
Merge branch 'add-iaac' of https://github.com/simplymathematics/decka…
simplymathematics Sep 6, 2023
a720beb
update sklearn
simplymathematics Sep 6, 2023
cca5dd7
update sklearn example
simplymathematics Sep 6, 2023
9b269c5
update sklearn example
simplymathematics Sep 7, 2023
e538f12
moved configs
simplymathematics Sep 7, 2023
cd98387
updated iaac code
simplymathematics Sep 7, 2023
7ef52ce
updated deploy script to handle non-GPU configs
simplymathematics Sep 7, 2023
a636896
fixed bug in conf
simplymathematics Sep 7, 2023
e16f0b2
update README, fixed find_best bug
simplymathematics Sep 7, 2023
de6543c
update sklearn dvc lock file
simplymathematics Sep 7, 2023
580f122
update sklearn to grid search
simplymathematics Sep 7, 2023
2859f98
+sklearn/conf/hydra
simplymathematics Sep 7, 2023
b646398
+RQ draft in sklearn examples
simplymathematics Sep 7, 2023
a77f438
+attacks.sh full
simplymathematics Sep 7, 2023
daf589e
linting
simplymathematics Sep 7, 2023
184de1c
Merge branch 'main' of github.com:simplymathematics/deckard into add-…
simplymathematics Sep 7, 2023
8b8e9d5
Merge branch 'add-iaac' of github.com:simplymathematics/deckard into …
simplymathematics Sep 7, 2023
375e7f8
linting
simplymathematics Sep 7, 2023
0f0a9f7
make dockerfile smaller
simplymathematics Sep 7, 2023
1bdd519
add redis deployment
salehsedghpour Sep 7, 2023
87995a7
add redis sc
salehsedghpour Sep 7, 2023
eb91405
add redis pvc
salehsedghpour Sep 7, 2023
58076c5
add redis svc
salehsedghpour Sep 7, 2023
7a6e897
+ deploy script changes
simplymathematics Sep 7, 2023
e25c7ec
fixed merge conflict
simplymathematics Sep 7, 2023
d5acb37
add redis env variables
salehsedghpour Sep 7, 2023
fde0908
Merge branch 'main' of github.com:simplymathematics/deckard into add-…
simplymathematics Sep 7, 2023
a8d73bf
removed deploy script
simplymathematics Sep 7, 2023
e64ad43
update pytorch
simplymathematics Sep 7, 2023
7e7434d
Merge branch 'main' into add-iaac
simplymathematics Sep 7, 2023
4adffcf
merge redis
simplymathematics Sep 7, 2023
e57dadf
linting
simplymathematics Sep 7, 2023
2c99358
linting
simplymathematics Sep 7, 2023
4b6ca64
update docker test name
simplymathematics Sep 7, 2023
c0e8fed
+cifar example
simplymathematics Sep 12, 2023
50e1931
config changes for torch, plots/optimise bug fix
simplymathematics Sep 18, 2023
f5bd008
shorten param file
simplymathematics Sep 18, 2023
5f26154
fixed optimise bug, reduce cifar runtime
simplymathematics Sep 18, 2023
d1b158f
update plots
simplymathematics Sep 19, 2023
0339005
fixed attack time bug
simplymathematics Sep 21, 2023
07a1e0e
fixed attack time bug
simplymathematics Sep 21, 2023
66ce02b
added diabetes support
simplymathematics Sep 21, 2023
5d8be50
fixed hashing bug
simplymathematics Sep 21, 2023
3731b82
+pytorch mnist experiments
simplymathematics Sep 21, 2023
9832c68
update weibull
simplymathematics Sep 21, 2023
d36365a
+weibull score of .8
simplymathematics Sep 22, 2023
dc4d5c4
update weibull
simplymathematics Sep 25, 2023
bb51864
update plots
simplymathematics Sep 29, 2023
3b3c5dd
add conf for scratch folder
simplymathematics Sep 29, 2023
4c8bce6
add compute_success as default metric
simplymathematics Sep 29, 2023
ae5045d
update pytorch
simplymathematics Sep 29, 2023
38ab1c9
linting
simplymathematics Sep 29, 2023
423f503
update to NEURIPS experiments
simplymathematics Oct 9, 2023
b6ea3a1
+ EAI AISEC draft
simplymathematics Oct 9, 2023
e399ec9
scratch folder (WIP)
simplymathematics Oct 9, 2023
fbf9265
update models.sh to remove stage name
simplymathematics Oct 9, 2023
4ebf324
linting
simplymathematics Oct 9, 2023
68d3829
linting
simplymathematics Oct 9, 2023
00e51c5
linting
simplymathematics Oct 9, 2023
03d3be6
classification conf
simplymathematics Oct 14, 2023
62377a1
+ kdd nsl
simplymathematics Oct 14, 2023
cffa8e4
update git ignore
simplymathematics Oct 14, 2023
7243aae
add truthseeker data
simplymathematics Oct 14, 2023
4d73ad4
add kdd-nsl data
simplymathematics Oct 14, 2023
85cf4c6
moved security stuff to one folder
simplymathematics Oct 14, 2023
02ac7ae
linting
simplymathematics Oct 14, 2023
8d0bba6
linting
simplymathematics Oct 14, 2023
78a716d
linting
simplymathematics Oct 14, 2023
06238c1
fixed dockerfile
simplymathematics Oct 14, 2023
59c9e74
fixed dockerfile, tests
simplymathematics Oct 14, 2023
6e5b0ba
fixed bug in data
simplymathematics Oct 14, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
2 changes: 1 addition & 1 deletion .github/workflows/docker-test.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#
name: Create and publish a Docker image
name: Test Docker Image

# Configures this workflow to run every time a change is pushed to the branch called `release`.
on:
Expand Down
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ ipython_config.py
*.json
*.npz
*.npy
examples/pytorch/output/models/model.optimizer.pt


# PyTorch Model Checkpoints
Expand Down Expand Up @@ -129,3 +128,6 @@ examples/*/output/*
**/*.egg-info/*
**/*.egg-info
deckard/deckard.egg-info/*

*log.txt
examples/*/*/*/*/*/params.yaml
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ RUN apt-get install -y python3 python3-distutils python3-pip ffmpeg libavcodec-e
RUN python3 -m pip install nvidia-pyindex nvidia-cuda-runtime-cu11
RUN git clone https://github.com/simplymathematics/deckard.git
WORKDIR /deckard
RUN python3 -m pip install --editable .[pytorch_image]
RUN python3 -m pip install --editable .[torch,torchvision,tensorflow]
RUN python3 -m pip install pytest
RUN git clone https://github.com/Trusted-AI/adversarial-robustness-toolbox.git
RUN cd adversarial-robustness-toolbox && python3 -m pip install .
RUN apt install python-is-python3
6 changes: 2 additions & 4 deletions deckard.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
{
"path": "."
},
{
"path": "../../../Home/staff/cmeyers/.art"
}

],
"settings": {
"python.testing.pytestEnabled": true,
"python.testing.pytestPath": "${workspaceFolder}/deckard/test/",
"python.envFile": "${workspaceFolder}/.env",
"yaml.schemas": {
"https://raw.githubusercontent.com/iterative/dvcyaml-schema/master/schema.json": }
"https://raw.githubusercontent.com/iterative/dvcyaml-schema/master/schema.json": ["dvc.yaml"] }
}
}
65 changes: 41 additions & 24 deletions deckard/base/attack/attack.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from time import process_time_ns
from omegaconf import DictConfig, OmegaConf
from hydra.utils import instantiate
from art.utils import to_categorical
from art.utils import to_categorical, compute_success
from ..data import Data
from ..model import Model
from ..utils import my_hash
Expand Down Expand Up @@ -58,8 +58,6 @@ def __call__(self, model=None, data=None, attack_size=-1):
for thing in pop_list:
kwargs.pop(thing, None)
logger.info(f"Initializing attack {name} with parameters {kwargs}")
self.data = data
self.model = model
if "x_train" in kwargs:
assert (
data is not None
Expand Down Expand Up @@ -92,15 +90,16 @@ def __call__(self, model=None, data=None, attack_size=-1):
logger.info("Attempting black-box attack.")
config = {"_target_": name}
config.update(**kwargs)
attack = instantiate(config)
attack = instantiate(config, model)
except TypeError as e:
if "verbose" in str(e):
config.pop("verbose", None)
attack = instantiate(config)
attack = instantiate(config, model)
else:
raise e
except Exception as e:
if "estimator" or "classifier" in str(e):
logger.warning(f"Black-box attack failed with error: {e}")
logger.info("Attempting white-box attack.")
if "has not been fitted correctly" in str(e):
model, _ = self.model.fit(data=data, model=model)
attack = instantiate(config, model)
else:
raise e
Expand Down Expand Up @@ -141,28 +140,44 @@ def __call__(
):
time_dict = {}
results = {}
kwargs = deepcopy(self.init.kwargs)
scale_max = kwargs.pop("scale_max", 1)
targeted = kwargs.pop("targeted", False)
ben_samples = data[1][: self.attack_size]
if attack_file is not None and Path(attack_file).exists():
samples = self.data.load(attack_file)
else:
ben_samples = data[0][: self.attack_size]
start = process_time_ns()
atk = self.init(model=model, attack_size=self.attack_size)
kwargs = deepcopy(self.init.kwargs)
scale_max = kwargs.pop("scale_max", 1)
targeted = kwargs.pop("targeted", False)

if targeted is True:
kwargs.update({"y": data[2][: self.attack_size]})
if "AdversarialPatch" in self.name:
patches, masks = atk.generate(ben_samples, **kwargs)
samples = atk.apply_patch(ben_samples, scale=scale_max)
else:
samples = atk.generate(ben_samples)
end = process_time_ns()
time_dict.update({"adv_fit_time": (end - start) / 1e9})
time_dict.update(
{"adv_fit_time_per_sample": (end - start) / (len(samples) * 1e9)},
start = process_time_ns()
patches, _ = atk.generate(ben_samples, **kwargs)
samples = atk.apply_patch(
ben_samples,
scale=scale_max,
patch_external=patches,
)
else:
start = process_time_ns()
samples = atk.generate(ben_samples, **kwargs)
end = process_time_ns()
time_dict.update({"adv_fit_time": (end - start) / 1e9})
time_dict.update(
{"adv_fit_time_per_sample": (end - start) / (len(samples) * 1e9)},
)
results["adv_samples"] = samples
try:
results["adv_success"] = compute_success(
classifier=model,
x_clean=ben_samples,
labels=data[3][: self.attack_size],
x_adv=samples,
targeted=self.kwargs.pop("targeted", False),
)
except TypeError as e:
logger.error(f"Failed to compute success rate. Error: {e}")
if attack_file is not None:
self.data.save(samples, attack_file)
if adv_predictions_file is not None and Path(adv_predictions_file).exists():
Expand Down Expand Up @@ -234,8 +249,8 @@ def __call__(
adv_loss = log_loss(data[3][: self.attack_size], preds)
self.data.save(adv_loss, adv_losses_file)
results["adv_loss"] = adv_loss
results["time_dict"] = time_dict

if len(time_dict) > 0:
results["time_dict"] = time_dict
return results


Expand Down Expand Up @@ -331,6 +346,7 @@ def __call__(
x_trigger = torch.tensor(x_trigger, device=device)
y_trigger = y_trigger.to(torch.long)
y_trigger = y_trigger.to(torch.long)
start = process_time_ns()
samples, _ = atk.poison(
x_trigger=x_trigger,
y_trigger=y_trigger,
Expand Down Expand Up @@ -722,7 +738,7 @@ def __init__(
self.method = method
self.attack_size = attack_size
if isinstance(kwargs, DictConfig):
kwargs = OmegaConf.to_container(kwargs)
kwargs = OmegaConf.to_container(kwargs, resolve=True)
elif isinstance(kwargs, dict):
pass
else:
Expand Down Expand Up @@ -817,6 +833,7 @@ def __call__(
)
else:
raise NotImplementedError(f"Attack method {self.method} not implemented.")

return result

def __hash__(self):
Expand Down
29 changes: 20 additions & 9 deletions deckard/base/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Union

import numpy as np
from pandas import DataFrame, read_csv, read_excel
from pandas import DataFrame, read_csv, read_excel, Series

from ..utils import my_hash
from .generator import DataGenerator
Expand Down Expand Up @@ -97,14 +97,24 @@ def initialize(self):
assert len(result) == 4, f"Data is not generated: {self.name}"
else:
result = self.load(self.name)
if len(result) == 1:
assert self.target is not None, "Target is not specified"
if isinstance(result, list) and len(result) == 2:
result = self.sample(*result)
elif isinstance(result, DataFrame) and self.target is not None:
if not isinstance(result, DataFrame):
result = DataFrame(result)
assert (
self.target in result
), f"Target {self.target} not in data with columns {result.columns}"
y = result[self.target]
X = result.drop(self.target, axis=1)
if isinstance(result, DataFrame):
X = result.drop(self.target, axis=1)
else:
X = result[~self.target]
result = self.sample(X, y)
if len(result) == 2:
result = self.sample(*result)
assert len(result) == 4
else:
assert len(result) == 4
if self.sklearn_pipeline is not None:
result = self.sklearn_pipeline(*result)
return result

def load(self, filename) -> DataFrame:
Expand All @@ -118,8 +128,7 @@ def load(self, filename) -> DataFrame:
with open(filename, "r") as f:
data = json.load(f)
elif suffix in [".csv"]:
data = read_csv(filename)
data = data.to_numpy()
data = read_csv(filename, delimiter=",", header=0)
elif suffix in [".pkl", ".pickle"]:
with open(filename, "rb") as f:
data = pickle.load(f)
Expand All @@ -141,6 +150,8 @@ def save(self, data, filename):
if suffix in [".json"]:
if isinstance(data, DataFrame):
data = data.to_dict(orient="records")
elif isinstance(data, Series):
data = data.to_dict()
elif isinstance(data, np.ndarray):
data = data.tolist()
with open(filename, "w") as f:
Expand Down
44 changes: 37 additions & 7 deletions deckard/base/data/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from dataclasses import dataclass, field
from ..utils import my_hash
import numpy as np
from art.utils import load_mnist, load_cifar10
from art.utils import load_mnist, load_cifar10, load_diabetes

__all__ = [
"SklearnDataGenerator",
Expand All @@ -21,10 +21,26 @@
]
logger = logging.getLogger(__name__)

SKLEARN_DATASETS = [
"classification",
"regression",
"blobs",
"moons",
"circles",
"biclusters",
]


@dataclass
class SklearnDataGenerator:
name: Literal["classification", "regression"] = "classification"
name: Literal[
"classification",
"regression",
"blobs",
"moons",
"circles",
"biclusters",
] = "classification"
kwargs: dict = field(default_factory=dict)

def __init__(self, name, **kwargs):
Expand Down Expand Up @@ -55,9 +71,12 @@ def __hash__(self):
return int(my_hash(self), 16)


TORCH_DATASETS = ["torch_mnist", "torch_cifar10", "torch_diabetes"]


@dataclass
class TorchDataGenerator:
name: Literal["torch_mnist", "torch_cifar10"] = "torch_mnist"
name: Literal["torch_mnist", "torch_cifar10", "torch_diabetes"] = "torch_mnist"
path = None
kwargs: dict = field(default_factory=dict)

Expand All @@ -84,6 +103,10 @@ def __call__(self):
X_test = np.transpose(X_test, (0, 3, 1, 2)).astype(np.float32)
X = np.concatenate((X_train, X_test))
y = np.concatenate((y_train, y_test))
elif self.name == "torch_diabetes":
(X_train, y_train), (X_test, y_test), _, _ = load_diabetes()
X = np.concatenate((X_train, X_test))
y = np.concatenate((y_train, y_test))
else:
raise ValueError(f"Unknown dataset name {self.name}")
return [X, y]
Expand All @@ -92,9 +115,12 @@ def __hash__(self):
return int(my_hash(self), 16)


KERAS_DATASETS = ["keras_mnist", "keras_cifar10", "mnist", "cifar10", "diabetes"]


@dataclass
class KerasDataGenerator:
name: Literal["mnist", "cifar10"] = "mnist"
name: Literal["mnist", "cifar10", "diabetes"] = "mnist"
kwargs: dict = field(default_factory=dict)

def __init__(self, name, **kwargs):
Expand All @@ -113,6 +139,10 @@ def __call__(self):
(X_train, y_train), (X_test, y_test), _, _ = load_mnist()
X = np.concatenate((X_train, X_test))
y = np.concatenate((y_train, y_test))
elif "diabetes" in self.name:
(X_train, y_train), (X_test, y_test), _, _ = load_diabetes()
X = np.concatenate((X_train, X_test))
y = np.concatenate((y_train, y_test))
else:
raise ValueError(f"Unknown dataset name {self.name}")
return [X, y]
Expand All @@ -131,11 +161,11 @@ def __init__(self, name, **kwargs):
self.kwargs = {k: v for k, v in kwargs.items() if v is not None}

def __call__(self):
if self.name in ["classification", "regression"]:
if self.name in SKLEARN_DATASETS:
return SklearnDataGenerator(self.name, **self.kwargs)()
elif self.name in ["torch_mnist", "torch_cifar10"]:
elif self.name in TORCH_DATASETS:
return TorchDataGenerator(self.name, **self.kwargs)()
elif self.name in ["keras_mnist", "keras_cifar10", "mnist", "cifar10"]:
elif self.name in KERAS_DATASETS:
return KerasDataGenerator(self.name, **self.kwargs)()
else:
raise ValueError(f"Invalid name {self.name}. Please choose from ")
Expand Down
Loading
Loading