INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
A wrapper around tf division that does more automatic casting of the input. | def div(a, b):
"""
A wrapper around tf division that does more automatic casting of
the input.
"""
def divide(a, b):
"""Division"""
return a / b
return op_with_scalar_cast(a, b, divide) |
Builds the graph to compute f ( a b ). If only one of the two arguments is a scalar and the operation would cause a type error without casting casts the scalar to match the tensor.: param a: a tf - compatible array or scalar: param b: a tf - compatible array or scalar | def op_with_scalar_cast(a, b, f):
"""
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar
""... |
Create the Jacobian graph to be ran later in a TF session: param predictions: the model s symbolic output ( linear output pre - softmax ): param x: the input placeholder: param nb_classes: the number of classes the model has: return: | def jacobian_graph(predictions, x, nb_classes):
"""
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
"""
# This fun... |
Augment an adversary s substitute training set using the Jacobian of a substitute model to generate new synthetic inputs. See https:// arxiv. org/ abs/ 1602. 02697 for more details. See cleverhans_tutorials/ mnist_blackbox. py for example use case: param sess: TF session in which the substitute model is defined: param ... | def jacobian_augmentation(sess,
x,
X_sub_prev,
Y_sub,
grads,
lmbda,
aug_batch_size=512,
feed=None):
"""
Augment an adversary's substit... |
Run evaluation on a saved model: param filepath: path to model to evaluate: param train_start: index of first training set example: param train_end: index of last training set example: param test_start: index of first test set example: param test_end: index of last test set example: param batch_size: size of evaluation... | def evaluate_model(filepath,
train_start=0, train_end=60000, test_start=0,
test_end=10000, batch_size=128,
testing=False, num_threads=None):
"""
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first ... |
Preprocessing the inputs before calling session. run () | def set_input(self, X_batch=None):
"""
Preprocessing the inputs before calling session.run()
:param X_batch: A dictionary of inputs to the first sub-graph
:return: A tuple, `(fetches, fd)`, with `fetches` being a list of
Tensors to be fetches and `fd` the feed dictionary.
"""
input... |
Postprocess the outputs of the Session. run (). Move the outputs of sub - graphs to next ones and return the output of the last sub - graph. | def proc_fvals(self, fvals):
"""
Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-g... |
Helper method to write images from single batch into datastore. | def _write_single_batch_images_internal(self, batch_id, client_batch):
"""Helper method to write images from single batch into datastore."""
client = self._datastore_client
batch_key = client.key(self._entity_kind_batches, batch_id)
for img_id, img in iteritems(self._data[batch_id]['images']):
img... |
Writes all image batches to the datastore. | def write_to_datastore(self):
"""Writes all image batches to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
for batch_id, batch_data in iteritems(self._data):
batch_key = client.key(self._entity_kind_batches, batch_id)
batch_entity = ... |
Writes only images from one batch to the datastore. | def write_single_batch_images_to_datastore(self, batch_id):
"""Writes only images from one batch to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
self._write_single_batch_images_internal(batch_id, client_batch) |
Initializes batches by reading from the datastore. | def init_from_datastore(self):
"""Initializes batches by reading from the datastore."""
self._data = {}
for entity in self._datastore_client.query_fetch(
kind=self._entity_kind_batches):
batch_id = entity.key.flat_path[-1]
self._data[batch_id] = dict(entity)
self._data[batch_id]['i... |
Adds batch with give ID and list of properties. | def add_batch(self, batch_id, batch_properties=None):
"""Adds batch with give ID and list of properties."""
if batch_properties is None:
batch_properties = {}
if not isinstance(batch_properties, dict):
raise ValueError('batch_properties has to be dict, however it was: '
+ ... |
Adds image to given batch. | def add_image(self, batch_id, image_id, image_properties=None):
"""Adds image to given batch."""
if batch_id not in self._data:
raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id))
if image_properties is None:
image_properties = {}
if not isinstance(image_properties, dict):
... |
Reads list of dataset images from the datastore. | def _read_image_list(self, skip_image_ids=None):
"""Reads list of dataset images from the datastore."""
if skip_image_ids is None:
skip_image_ids = []
images = self._storage_client.list_blobs(
prefix=os.path.join('dataset', self._dataset_name) + '/')
zip_files = [i for i in images if i.end... |
Initializes dataset batches from the list of images in the datastore. | def init_from_storage_write_to_datastore(self,
batch_size=100,
allowed_epsilon=None,
skip_image_ids=None,
max_num_images=None):
"""Initializes d... |
Init list of adversarial batches from dataset batches and submissions. | def init_from_dataset_and_submissions_write_to_datastore(
self, dataset_batches, attack_submission_ids):
"""Init list of adversarial batches from dataset batches and submissions.
Args:
dataset_batches: instances of DatasetBatches
attack_submission_ids: iterable with IDs of all (targeted and n... |
Returns total number of all generated adversarial examples. | def count_generated_adv_examples(self):
"""Returns total number of all generated adversarial examples."""
result = {}
for v in itervalues(self.data):
s_id = v['submission_id']
result[s_id] = result.get(s_id, 0) + len(v['images'])
return result |
Load a saved model gather its predictions and save a confidence report.: param filepath: path to model to evaluate: param train_start: index of first training set example to use: param train_end: index of last training set example to use: param test_start: index of first test set example to use: param test_end: index o... | def make_confidence_report_bundled(filepath, train_start=TRAIN_START,
train_end=TRAIN_END, test_start=TEST_START,
test_end=TEST_END, which_set=WHICH_SET,
recipe=RECIPE, report_path=REPORT_PATH,
... |
Prints out accuracy coverage etc. statistics: param correctness: ndarray One bool per example specifying whether it was correctly classified: param confidence: ndarray The probability associated with each prediction: param name: str The name of this type of data ( e. g. clean MaxConfidence ) | def print_stats(correctness, confidence, name):
"""
Prints out accuracy, coverage, etc. statistics
:param correctness: ndarray
One bool per example specifying whether it was correctly classified
:param confidence: ndarray
The probability associated with each prediction
:param name: str
The name of... |
Load a saved model gather its predictions and save a confidence report. | def make_confidence_report(filepath, train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
mc_batch_size=MC_BATCH_SIZE,
... |
MNIST CleverHans tutorial: param train_start: index of first training set example: param train_end: index of last training set example: param test_start: index of first test set example: param test_end: index of last test set example: param nb_epochs: number of epochs to train model: param batch_size: size of training ... | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE, train_dir=TRAIN_DIR,
filename=FILENAME, load_model=LOAD_MODEL,
testing=False, label_smooth... |
Generate symbolic graph for adversarial examples and return. | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments for the base attacker
"""
assert self.parse_params(**kwargs)
labels, _nb_classes = self.get_or_guess_labels(x, kwargs)
... |
Runs the untargeted attack.: param x: The input: param true_y: The correct label for x. This attack aims to produce misclassification. | def attack(self, x, true_y):
"""
Runs the untargeted attack.
:param x: The input
:param true_y: The correct label for `x`. This attack aims to produce misclassification.
"""
adv_x_cls = []
prob_cls = []
m = tf.shape(x)[0]
true_y_idx = tf.argmax(true_y, axis=1)
expanded_x = tf.co... |
Run the attack on a specific target class.: param x: tf Tensor. The input example.: param target_y: tf Tensor. The attacker s desired target class. Returns: A targeted adversarial example intended to be classified as the target class. | def attack_class(self, x, target_y):
"""
Run the attack on a specific target class.
:param x: tf Tensor. The input example.
:param target_y: tf Tensor. The attacker's desired target class.
Returns:
A targeted adversarial example, intended to be classified as the target class.
"""
adv =... |
This helper function computes a batch start and end index: param batch_nb: the batch number: param data_length: the total length of the data being parsed by batches: param batch_size: the number of inputs in each batch: return: pair of ( start end ) indices | def batch_indices(batch_nb, data_length, batch_size):
"""
This helper function computes a batch start and end index
:param batch_nb: the batch number
:param data_length: the total length of the data being parsed by batches
:param batch_size: the number of inputs in each batch
:return: pair of (start, end) i... |
Returns a list of class indices excluding the class indexed by class_ind: param nb_classes: number of classes in the task: param class_ind: the class index to be omitted: return: list of class indices excluding the class indexed by class_ind | def other_classes(nb_classes, class_ind):
"""
Returns a list of class indices excluding the class indexed by class_ind
:param nb_classes: number of classes in the task
:param class_ind: the class index to be omitted
:return: list of class indices excluding the class indexed by class_ind
"""
if class_ind <... |
Converts a class vector ( integers ) to binary class matrix. This is adapted from the Keras function with the same name.: param y: class vector to be converted into a matrix ( integers from 0 to nb_classes ).: param nb_classes: nb_classes: total number of classes.: param num_classses: depricated version of nb_classes: ... | def to_categorical(y, nb_classes, num_classes=None):
"""
Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classes: total... |
Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks ( i. e. when the search algorithm takes in both a source class and target class to compute the adversarial example ).: p... | def random_targets(gt, nb_classes):
"""
Take in an array of correct labels and randomly select a different label
for each label in the array. This is typically used to randomly select a
target class in targeted adversarial examples attacks (i.e., when the
search algorithm takes in both a source class and targ... |
Deprecation wrapper | def pair_visual(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. "
"cleverhans.utils.pair_visual may be removed on or after "
"2019-04-24.")
from cleverhans.plot.pyplot_image import pair_visual as new_pair_visual
... |
Deprecation wrapper | def grid_visual(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`grid_visual` has moved to `cleverhans.plot.pyplot_image`. "
"cleverhans.utils.grid_visual may be removed on or after "
"2019-04-24.")
from cleverhans.plot.pyplot_image import grid_visual as new_grid_visual
... |
Deprecation wrapper | def get_logits_over_interval(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`get_logits_over_interval` has moved to "
"`cleverhans.plot.pyplot_image`. "
"cleverhans.utils.get_logits_over_interval may be removed on "
"or after 2019-04-24.")
# pylint:disab... |
Deprecation wrapper | def linear_extrapolation_plot(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`linear_extrapolation_plot` has moved to "
"`cleverhans.plot.pyplot_image`. "
"cleverhans.utils.linear_extrapolation_plot may be removed on "
"or after 2019-04-24.")
# pylint:di... |
Create a logger object with the given name. | def create_logger(name):
"""
Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter.
"""
base = logging.getLogger("cleverhans")
if len(base.handlers) == 0:
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(levelna... |
Returns a version of normal_dict whose iteration order is always the same | def deterministic_dict(normal_dict):
"""
Returns a version of `normal_dict` whose iteration order is always the same
"""
out = OrderedDict()
for key in sorted(normal_dict.keys()):
out[key] = normal_dict[key]
return out |
Return the union of l1 and l2 with a deterministic ordering. ( Union of python sets does not necessarily have a consisten iteration order ): param l1: list of items: param l2: list of items: returns: list containing one copy of each item that is in l1 or in l2 | def ordered_union(l1, l2):
"""
Return the union of l1 and l2, with a deterministic ordering.
(Union of python sets does not necessarily have a consisten iteration
order)
:param l1: list of items
:param l2: list of items
:returns: list containing one copy of each item that is in l1 or in l2
"""
out = [... |
like zip but with these properties: - returns a list rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. ( normal zip silently drops entries to make them the same length ) | def safe_zip(*args):
"""like zip but with these properties:
- returns a list, rather than an iterator. This is the old Python2 zip behavior.
- a guarantee that all arguments are the same length.
(normal zip silently drops entries to make them the same length)
"""
length = len(args[0])
if not all(len(arg) ... |
Calls shell command with argument substitution. | def shell_call(command, **kwargs):
"""Calls shell command with argument substitution.
Args:
command: command represented as a list. Each element of the list is one
token of the command. For example "cp a b" becomes ['cp', 'a', 'b']
If any element of the list looks like '${NAME}' then it will be rep... |
Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. | def deep_copy(numpy_dict):
"""
Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them.
"""
out = {}
for key in numpy_dict:
out[key] = numpy_dict[key].copy()
return out |
Load and preprocess MNIST dataset: param datadir: path to folder where data should be stored: param train_start: index of first training set example: param train_end: index of last training set example: param test_start: index of first test set example: param test_end: index of last test set example: return: tuple of f... | def data_mnist(datadir=tempfile.gettempdir(), train_start=0,
train_end=60000, test_start=0, test_end=10000):
"""
Load and preprocess MNIST dataset
:param datadir: path to folder where data should be stored
:param train_start: index of first training set example
:param train_end: index of last t... |
Preprocess CIFAR10 dataset: return: | def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000):
"""
Preprocess CIFAR10 dataset
:return:
"""
# These values are specific to CIFAR10
img_rows = 32
img_cols = 32
nb_classes = 10
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_... |
Load a saved model and print out its accuracy on different data distributions | def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER):
"""
Load a saved model... |
The actual implementation of the evaluation.: param sess: tf. Session: param model: cleverhans. model. Model: param dataset: cleverhans. dataset. Dataset: param factory: the dataset factory corresponding to dataset: param x_data: numpy array of input examples: param y_data: numpy array of class labels: param base_eps_i... | def impl(sess, model, dataset, factory, x_data, y_data,
base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER,
batch_size=BATCH_SIZE):
"""
The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhans.dataset.Dataset
:param fact... |
Print accuracies | def main(argv=None):
"""
Print accuracies
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print_accuracies(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_set,
nb_iter=FLAGS.nb_it... |
PyTorch implementation of the Fast Gradient Method.: param model_fn: a callable that takes an input tensor and returns the model logits.: param x: input tensor.: param eps: epsilon ( input variation parameter ) ; see https:// arxiv. org/ abs/ 1412. 6572.: param ord: Order of the norm ( mimics NumPy ). Possible values: ... | def fast_gradient_method(model_fn, x, eps, ord,
clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False):
"""
PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor... |
Read png images from input directory in batches. | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be le... |
Saves images to the output directory. | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... |
Run the sample attack | def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size... |
Load training and test data. | def ld_cifar10():
"""Load training and test data."""
train_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
test_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
train_dataset = torchvision.datasets.CIFAR10(root='/tmp/data', train=True, transform=t... |
Plots a success - fail curve from a confidence report stored on disk: param path: string filepath for the stored report. ( Should be the output of make_confidence_report *. py ): param success_name: The name ( confidence report key ) of the data that should be used to measure success rate: param fail_names: A list of n... | def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plots a success-fail curve fr... |
Plot a success fail curve from a confidence report: param report: A confidence report ( the type of object saved by make_confidence_report. py ): param success_name: see plot_report_from_path: param fail_names: see plot_report_from_path: param label: see plot_report_from_path: param is_max_confidence: see plot_report_f... | def plot_report(report, success_name, fail_names, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confide... |
Make a success - failure curve.: param report: A confidence report ( the type of object saved by make_confidence_report. py ): param success_name: see plot_report_from_path: param fail_names: see plot_report_from_path: returns: fail_optimal: list of failure rates on adversarial data for the optimal ( t > =. 5 ) part of... | def make_curve(report, success_name, fail_names):
"""
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of f... |
Train a TF graph: param sess: TF session to use when training the graph: param x: input placeholder: param y: output placeholder ( for labels ): param predictions: model output predictions: param X_train: numpy array with training inputs: param Y_train: numpy array with training outputs: param hparams. save: boolean co... | def model_train(self):
"""
Train a TF graph
:param sess: TF session to use when training the graph
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_train: numpy array with training inputs
:param Y_train: numpy arr... |
Clone variables unused by the attack on all GPUs. Specifically the ground - truth label y has to be preserved until the training step. | def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs):
"""
Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
:param outputs: A list of dic... |
Return a tensor that constructs adversarial examples for the given input. Generate uses tf. py_func in order to operate over tensors.: param x: ( required ) A tensor with the inputs.: param kwargs: See parse_params | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
... |
: param y_target: ( optional ) A tensor with the one - hot target labels.: param batch_size: The number of inputs to include in a batch and process simultaneously.: param binary_search_steps: The number of times we perform binary search to find the optimal tradeoff - constant between norm of the purturbation and cross ... | def parse_params(self,
y_target=None,
batch_size=1,
binary_search_steps=5,
max_iterations=1000,
initial_const=1e-2,
clip_min=0,
clip_max=1):
"""
:param y_target: (optional) A tens... |
Perform the attack on the given instance for the given targets. | def attack(self, x_val, targets):
"""
Perform the attack on the given instance for the given targets.
"""
def lbfgs_objective(adv_x, self, targets, oimgs, CONST):
""" returns the function value and the gradient for fmin_l_bfgs_b """
loss = self.sess.run(
self.loss,
feed_... |
Set the device before the next fprop to create a new graph on the specified device. | def set_device(self, device_name):
"""
Set the device before the next fprop to create a new graph on the
specified device.
"""
device_name = unify_device_name(device_name)
self.device_name = device_name
for layer in self.layers:
layer.device_name = device_name |
Return a list of assignment operations that syncs the parameters of all model copies with the one on host_device.: param host_device: ( required str ) the name of the device with latest parameters | def create_sync_ops(self, host_device):
"""
Return a list of assignment operations that syncs the parameters
of all model copies with the one on host_device.
:param host_device: (required str) the name of the device with latest
parameters
"""
host_device = unify_device_na... |
Create and initialize a variable using a numpy array and set trainable.: param name: ( required str ) name of the variable: param initializer: a numpy array or a tensor | def get_variable(self, name, initializer):
"""
Create and initialize a variable using a numpy array and set trainable.
:param name: (required str) name of the variable
:param initializer: a numpy array or a tensor
"""
v = tf.get_variable(name, shape=initializer.shape,
ini... |
Create and initialize layer parameters on the device previously set in self. device_name. | def set_input_shape_ngpu(self, new_input_shape):
"""
Create and initialize layer parameters on the device previously set
in self.device_name.
:param new_input_shape: a list or tuple for the shape of the input.
"""
assert self.device_name, "Device name has not been set."
device_name = self.... |
Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the host_device. | def create_sync_ops(self, host_device):
"""Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'.
"""
sync_ops = []
host_params = self.params_device[host_device]
for device, params in (self.params_device).iteritems():
... |
Tensorflow implementation of the perturbation method used for virtual adversarial training: https:// arxiv. org/ abs/ 1507. 00677: param model: the model which returns the network unnormalized logits: param x: the input placeholder: param logits: the model s unnormalized output tensor ( the input to the softmax layer )... | def vatm(model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param mo... |
Generate symbolic graph for adversarial examples and return. | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(
self.model,... |
Take in a dictionary of parameters and applies attack - specific checks before saving them as attributes. | def parse_params(self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-spec... |
Iterate with exponential backoff on failures. | def iterate_with_exp_backoff(base_iter,
max_num_tries=6,
max_backoff=300.0,
start_backoff=4.0,
backoff_multiplier=2.0,
frac_random_backoff=0.25):
"""Iterate with exponential... |
Lists names of all blobs by their prefix. | def list_blobs(self, prefix=''):
"""Lists names of all blobs by their prefix."""
return [b.name for b in self.bucket.list_blobs(prefix=prefix)] |
Begins a batch. | def begin(self):
"""Begins a batch."""
if self._cur_batch:
raise ValueError('Previous batch is not committed.')
self._cur_batch = self._client.batch()
self._cur_batch.begin()
self._num_mutations = 0 |
Rolls back pending mutations. | def rollback(self):
"""Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able ... |
Adds mutation of the entity to the mutation buffer. | def put(self, entity):
"""Adds mutation of the entity to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
entity: entity which should be put into the datastore
"""
self._cur_batch.put(entity)
... |
Adds deletion of the entity with given key to the mutation buffer. | def delete(self, key):
"""Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted
"""
self._cur_batch.delet... |
Retrieves an entity given its key. | def get(self, key, transaction=None):
"""Retrieves an entity given its key."""
return self._client.get(key, transaction=transaction) |
MNIST tutorial for Carlini and Wagner s attack: param train_start: index of first training set example: param train_end: index of last training set example: param test_start: index of first test set example: param test_end: index of last test set example: param viz_enabled: ( boolean ) activate plots of adversarial exa... | def mnist_tutorial_cw(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE,
... |
Selects the Attack Class using string input.: param attack_string: adversarial attack name in string format: return: attack class defined in cleverhans. attacks_eager | def attack_selection(attack_string):
"""
Selects the Attack Class using string input.
:param attack_string: adversarial attack name in string format
:return: attack class defined in cleverhans.attacks_eager
"""
# List of Implemented attacks
attacks_list = AVAILABLE_ATTACKS.keys()
# Checking for reque... |
MNIST cleverhans tutorial: param train_start: index of first training set example.: param train_end: index of last training set example.: param test_start: index of first test set example.: param test_end: index of last test set example.: param nb_epochs: number of epochs to train model.: param batch_size: size of trai... | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE,
clean_train=True,
testing=False,
backprop_through_attack=False,
... |
Removes directory tree as a superuser. | def sudo_remove_dirtree(dir_name):
"""Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root.
"""
try:
subproce... |
Main function which runs worker. | def main(args):
"""Main function which runs worker."""
title = '## Starting evaluation of round {0} ##'.format(args.round_name)
logging.info('\n'
+ '#' * len(title) + '\n'
+ '#' * len(title) + '\n'
+ '##' + ' ' * (len(title)-2) + '##' + '\n'
+ title + '\... |
Method which downloads submission to local directory. | def download(self):
"""Method which downloads submission to local directory."""
# Structure of the download directory:
# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id
# submission_dir/s.ext <-- archived submission
# submission_dir/extracted <-- extracted submission
# Check whether s... |
Creates a temporary copy of extracted submission. | def temp_copy_extracted_submission(self):
"""Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary c... |
Runs docker command without time limit. | def run_without_time_limit(self, cmd):
"""Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution ... |
Runs docker command and enforces time limit. | def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
"""Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
... |
Runs attack inside Docker. | def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 25... |
Runs defense inside Docker. | def run(self, input_dir, output_file_path):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
"""
logging.info('Running defense %s', self.sub... |
Read dataset_meta field from bucket | def read_dataset_metadata(self):
"""Read `dataset_meta` field from bucket"""
if self.dataset_meta:
return
shell_call(['gsutil', 'cp',
'gs://' + self.storage_client.bucket_name + '/'
+ 'dataset/' + self.dataset_name + '_dataset.csv',
LOCAL_DATASET_METADAT... |
Initializes data necessary to execute attacks. | def fetch_attacks_data(self):
"""Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop.
"""
if self.attacks_data_initialized:
return
# init data from datastore
self.submissions.init_fro... |
Runs one attack work. | def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
adv_batch_id = (
s... |
Method which evaluates all attack work. | def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is av... |
Lazy initialization of data necessary to execute defenses. | def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_dat... |
Runs one defense work. | def run_defense_work(self, work_id):
"""Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
class_batch_id = (
... |
Method which evaluates all defense work. | def run_defenses(self):
"""Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
"""
logging.info('******** Start evaluation of defenses ********')
prev_submission_id = None
need_reload_work = True
while Tr... |
Run attacks and defenses | def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() |
Returns a hashable summary of the types of arg_names within kwargs.: param arg_names: tuple containing names of relevant arguments: param kwargs: dict mapping string argument names to values. These must be values for which we can create a tf placeholder. Currently supported: numpy darray or something that can ducktype ... | def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently su... |
Construct the graph required to run the attack through generate_np. | def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take diff... |
Generate adversarial examples and return them as a NumPy array. Sub - classes * should not * implement this method unless they must perform special handling of arguments. | def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional para... |
Construct the inputs to the attack graph to be used by generate_np. | def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
""... |
Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If y is in kwargs then assume it s an untargeted attack and use that as the label. If y_target is in kwargs and is not none then assume it s a targeted attack and use that as the label. Otherwise ... | def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not no... |
As described in https:// arxiv. org/ abs/ 1511. 06581 | def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers... |
MNIST tutorial for the Jacobian - based saliency map approach ( JSMA ): param train_start: index of first training set example: param train_end: index of last training set example: param test_start: index of first test set example: param test_end: index of last test set example: param viz_enabled: ( boolean ) activate ... | def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE):
"""
... |
Generate symbolic graph for adversarial examples and return. | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)... |
Take in a dictionary of parameters and applies attack - specific checks before saving them as attributes. | def parse_params(self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
... |
Run ( optionally multi - replica synchronous ) training to minimize loss: param sess: TF session to use when training the graph: param loss: tensor the loss to minimize: param x_train: numpy array with training inputs or tf Dataset: param y_train: numpy array with training outputs or tf Dataset: param init_all: ( boole... | def train(sess, loss, x_train, y_train,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None,
devices=None, x_batch_preprocessor=None, use_ema=False,
ema_decay=.998, run_canary=None,
loss_threshold=1e5, dataset_tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.