Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def batch_indices(batch_nb, data_length, batch_size):
# Batch start and end index
start = int(batch_nb * batch_size)
end = int((batch_nb + 1) * batch_size)
# When there are not enough inputs left, we reuse some to complete the
# batch
if end > data_length:
... | [
"\n This helper function computes a batch start and end index\n :param batch_nb: the batch number\n :param data_length: the total length of the data being parsed by batches\n :param batch_size: the number of inputs in each batch\n :return: pair of (start, end) indices\n "
] |
Please provide a description of the function:def other_classes(nb_classes, class_ind):
if class_ind < 0 or class_ind >= nb_classes:
error_str = "class_ind must be within the range (0, nb_classes - 1)"
raise ValueError(error_str)
other_classes_list = list(range(nb_classes))
other_classes_list.remove(cl... | [
"\n Returns a list of class indices excluding the class indexed by class_ind\n :param nb_classes: number of classes in the task\n :param class_ind: the class index to be omitted\n :return: list of class indices excluding the class indexed by class_ind\n "
] |
Please provide a description of the function:def to_categorical(y, nb_classes, num_classes=None):
if num_classes is not None:
if nb_classes is not None:
raise ValueError("Should not specify both nb_classes and its deprecated "
"alias, num_classes")
warnings.warn("`num_classes` ... | [
"\n Converts a class vector (integers) to binary class matrix.\n This is adapted from the Keras function with the same name.\n :param y: class vector to be converted into a matrix\n (integers from 0 to nb_classes).\n :param nb_classes: nb_classes: total number of classes.\n :param num_classses: depr... |
Please provide a description of the function:def random_targets(gt, nb_classes):
# If the ground truth labels are encoded as one-hot, convert to labels.
if len(gt.shape) == 2:
gt = np.argmax(gt, axis=1)
# This vector will hold the randomly selected labels.
result = np.zeros(gt.shape, dtype=np.int32)
... | [
"\n Take in an array of correct labels and randomly select a different label\n for each label in the array. This is typically used to randomly select a\n target class in targeted adversarial examples attacks (i.e., when the\n search algorithm takes in both a source class and target class to compute\n the adver... |
Please provide a description of the function:def pair_visual(*args, **kwargs):
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... | [
"Deprecation wrapper"
] |
Please provide a description of the function:def grid_visual(*args, **kwargs):
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... | [
"Deprecation wrapper"
] |
Please provide a description of the function:def get_logits_over_interval(*args, **kwargs):
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... | [
"Deprecation wrapper"
] |
Please provide a description of the function:def linear_extrapolation_plot(*args, **kwargs):
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... | [
"Deprecation wrapper"
] |
Please provide a description of the function:def create_logger(name):
base = logging.getLogger("cleverhans")
if len(base.handlers) == 0:
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(levelname)s %(asctime)s %(name)s] ' +
'%(message)s')
ch.setFormatte... | [
"\n Create a logger object with the given name.\n\n If this is the first time that we call this method, then initialize the\n formatter.\n "
] |
Please provide a description of the function:def deterministic_dict(normal_dict):
out = OrderedDict()
for key in sorted(normal_dict.keys()):
out[key] = normal_dict[key]
return out | [
"\n Returns a version of `normal_dict` whose iteration order is always the same\n "
] |
Please provide a description of the function:def ordered_union(l1, l2):
out = []
for e in l1 + l2:
if e not in out:
out.append(e)
return out | [
"\n Return the union of l1 and l2, with a deterministic ordering.\n (Union of python sets does not necessarily have a consisten iteration\n order)\n :param l1: list of items\n :param l2: list of items\n :returns: list containing one copy of each item that is in l1 or in l2\n "
] |
Please provide a description of the function:def safe_zip(*args):
length = len(args[0])
if not all(len(arg) == length for arg in args):
raise ValueError("Lengths of arguments do not match: "
+ str([len(arg) for arg in args]))
return list(zip(*args)) | [
"like zip but with these properties:\n - returns a list, rather than an iterator. This is the old Python2 zip behavior.\n - a guarantee that all arguments are the same length.\n (normal zip silently drops entries to make them the same length)\n "
] |
Please provide a description of the function:def shell_call(command, **kwargs):
# Regular expression to find instances of '${NAME}' in a string
CMD_VARIABLE_RE = re.compile('^\\$\\{(\\w+)\\}$')
command = list(command)
for i in range(len(command)):
m = CMD_VARIABLE_RE.match(command[i])
if m:
var... | [
"Calls shell command with argument substitution.\n\n Args:\n command: command represented as a list. Each element of the list is one\n token of the command. For example \"cp a b\" becomes ['cp', 'a', 'b']\n If any element of the list looks like '${NAME}' then it will be replaced\n by value from *... |
Please provide a description of the function:def deep_copy(numpy_dict):
out = {}
for key in numpy_dict:
out[key] = numpy_dict[key].copy()
return out | [
"\n Returns a copy of a dictionary whose values are numpy arrays.\n Copies their values rather than copying references to them.\n "
] |
Please provide a description of the function:def data_mnist(datadir=tempfile.gettempdir(), train_start=0,
train_end=60000, test_start=0, test_end=10000):
assert isinstance(train_start, int)
assert isinstance(train_end, int)
assert isinstance(test_start, int)
assert isinstance(test_end, int)
... | [
"\n Load and preprocess MNIST dataset\n :param datadir: path to folder where data should be stored\n :param train_start: index of first training set example\n :param train_end: index of last training set example\n :param test_start: index of first test set example\n :param test_end: index of last test set exa... |
Please provide a description of the function:def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000):
# 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_test... | [
"\n Preprocess CIFAR10 dataset\n :return:\n "
] |
Please provide a description of the function: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,
... | [
"\n Load a saved model and print out its accuracy on different data distributions\n\n This function works by running a single attack on each example.\n This provides a reasonable estimate of the true failure rate quickly, so\n long as the model does not suffer from gradient masking.\n However, this estimate is... |
Please provide a description of the function:def impl(sess, model, dataset, factory, x_data, y_data,
base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER,
batch_size=BATCH_SIZE):
center = dataset.kwargs['center']
max_val = dataset.kwargs['max_val']
value_range = max_val * (1. + center)
min_value =... | [
"\n The actual implementation of the evaluation.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param dataset: cleverhans.dataset.Dataset\n :param factory: the dataset factory corresponding to `dataset`\n :param x_data: numpy array of input examples\n :param y_data: numpy array of class ... |
Please provide a description of the function:def main(argv=None):
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... | [
"\n Print accuracies\n "
] |
Please provide a description of the function:def fast_gradient_method(model_fn, x, eps, ord,
clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False):
if ord not in [np.inf, 1, 2]:
raise ValueError("Norm order must be either np.inf, 1, or 2.")
asserts = []
# If ... | [
"\n PyTorch implementation of the Fast Gradient Method.\n :param model_fn: a callable that takes an input tensor and returns the model logits.\n :param x: input tensor.\n :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.\n :param ord: Order of the norm (mimics NumPy). Possib... |
Please provide a description of the function:def load_images(input_dir, batch_shape):
images = np.zeros(batch_shape)
filenames = []
idx = 0
batch_size = batch_shape[0]
for filepath in tf.gfile.Glob(os.path.join(input_dir, '*.png')):
with tf.gfile.Open(filepath) as f:
image = np.array(Image.open(f... | [
"Read png images from input directory in batches.\n\n Args:\n input_dir: input directory\n batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]\n\n Yields:\n filenames: list file names without path of each image\n Lenght of this list could be less than batch_size, in this case ... |
Please provide a description of the function:def save_images(images, filenames, output_dir):
for i, filename in enumerate(filenames):
# Images for inception classifier are normalized to be in [-1, 1] interval,
# so rescale them back to [0, 1].
with tf.gfile.Open(os.path.join(output_dir, filename), 'w')... | [
"Saves images to the output directory.\n\n Args:\n images: array with minibatch of images\n filenames: list of filenames without path\n If number of file names in this list less than number of images in\n the minibatch then only first len(filenames) images will be saved.\n output_dir: directory ... |
Please provide a description of the function:def main(_):
# 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 =... | [
"Run the sample attack"
] |
Please provide a description of the function:def ld_cifar10():
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, ... | [
"Load training and test data."
] |
Please provide a description of the function: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... | [
"\n Plots a success-fail curve from a confidence report stored on disk,\n :param path: string filepath for the stored report.\n (Should be the output of make_confidence_report*.py)\n :param success_name: The name (confidence report key) of the data that\n should be used to measure success rate\n :param fa... |
Please provide a description of the function:def plot_report(report, success_name, fail_names, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
(fail_optimal, success_optimal, fail_lower_bound, fail_upper_bound,
success_bounded) = m... | [
"\n Plot a success fail curve from a confidence report\n :param report: A confidence report\n (the type of object saved by make_confidence_report.py)\n :param success_name: see plot_report_from_path\n :param fail_names: see plot_report_from_path\n :param label: see plot_report_from_path\n :param is_max_con... |
Please provide a description of the function:def make_curve(report, success_name, fail_names):
success_results = report[success_name]
fail_name = None # pacify pylint
found = False
for fail_name in fail_names:
if fail_name in report:
found = True
break
if not found:
raise ValueError(fai... | [
"\n Make a success-failure curve.\n :param report: A confidence report\n (the type of object saved by make_confidence_report.py)\n :param success_name: see plot_report_from_path\n :param fail_names: see plot_report_from_path\n :returns:\n fail_optimal: list of failure rates on adversarial data for the op... |
Please provide a description of the function:def model_train(self):
assert self.runner is not None, (
)
hparams = self.hparams
batch_size = hparams.batch_size
nb_epochs = hparams.nb_epochs
train_dir = hparams.save_dir
filename = 'model.ckpt'
X_train = self.X_train
Y_train =... | [
"\n Train a TF graph\n :param sess: TF session to use when training the graph\n :param x: input placeholder\n :param y: output placeholder (for labels)\n :param predictions: model output predictions\n :param X_train: numpy array with training inputs\n :param Y_train: numpy array with training o... |
Please provide a description of the function:def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs):
assert len(inputs) == len(outputs), (
'Inputs and outputs should have the same number of elements.')
inputs[0].update(g0_inputs)
outputs[0].update(g0_inputs)
# Copy g0_inputs forwa... | [
"\n Clone variables unused by the attack on all GPUs. Specifically, the\n ground-truth label, y, has to be preserved until the training step.\n\n :param inputs: A list of dictionaries as the inputs to each step.\n :param outputs: A list of dictionaries as the outputs of each step.\n :param g0_inputs:... |
Please provide a description of the function:def generate(self, x, **kwargs):
assert self.sess is not None, \
'Cannot use `generate` when no `sess` was provided'
self.parse_params(**kwargs)
if self.y_target is None:
self.y_target, nb_classes = self.get_or_guess_labels(x, kwargs)
se... | [
"\n Return a tensor that constructs adversarial examples for the given\n input. Generate uses tf.py_func in order to operate over tensors.\n :param x: (required) A tensor with the inputs.\n :param kwargs: See `parse_params`\n ",
"\n Wrapper creating TensorFlow interface for use with py_func\n ... |
Please provide a description of the function: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):
... | [
"\n :param y_target: (optional) A tensor with the one-hot target labels.\n :param batch_size: The number of inputs to include in a batch and\n process simultaneously.\n :param binary_search_steps: The number of times we perform binary\n search to find th... |
Please provide a description of the function:def attack(self, x_val, targets):
def lbfgs_objective(adv_x, self, targets, oimgs, CONST):
loss = self.sess.run(
self.loss,
feed_dict={
self.x: adv_x.reshape(oimgs.shape),
self.targeted_label: targets,
... | [
"\n Perform the attack on the given instance for the given targets.\n ",
" returns the function value and the gradient for fmin_l_bfgs_b ",
" returns attack result "
] |
Please provide a description of the function:def set_device(self, device_name):
device_name = unify_device_name(device_name)
self.device_name = device_name
for layer in self.layers:
layer.device_name = device_name | [
"\n Set the device before the next fprop to create a new graph on the\n specified device.\n "
] |
Please provide a description of the function:def create_sync_ops(self, host_device):
host_device = unify_device_name(host_device)
sync_ops = []
for layer in self.layers:
if isinstance(layer, LayernGPU):
sync_ops += layer.create_sync_ops(host_device)
return sync_ops | [
"\n Return a list of assignment operations that syncs the parameters\n of all model copies with the one on host_device.\n :param host_device: (required str) the name of the device with latest\n parameters\n "
] |
Please provide a description of the function:def get_variable(self, name, initializer):
v = tf.get_variable(name, shape=initializer.shape,
initializer=(lambda shape, dtype, partition_info:
initializer),
trainable=self.training... | [
"\n Create and initialize a variable using a numpy array and set trainable.\n :param name: (required str) name of the variable\n :param initializer: a numpy array or a tensor\n "
] |
Please provide a description of the function:def set_input_shape_ngpu(self, new_input_shape):
assert self.device_name, "Device name has not been set."
device_name = self.device_name
if self.input_shape is None:
# First time setting the input shape
self.input_shape = [None] + [int(d) for d ... | [
"\n Create and initialize layer parameters on the device previously set\n in self.device_name.\n\n :param new_input_shape: a list or tuple for the shape of the input.\n "
] |
Please provide a description of the function:def create_sync_ops(self, host_device):
sync_ops = []
host_params = self.params_device[host_device]
for device, params in (self.params_device).iteritems():
if device == host_device:
continue
for k in self.params_names:
if isinstan... | [
"Create an assignment operation for each weight on all devices. The\n weight is assigned the value of the copy on the `host_device'.\n "
] |
Please provide a description of the function:def vatm(model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None):
with tf.name_scope(scope, "virtual_adversarial_perturbation"):
d = tf.random_normal(tf.shape... | [
"\n Tensorflow implementation of the perturbation method used for virtual\n adversarial training: https://arxiv.org/abs/1507.00677\n :param model: the model which returns the network unnormalized logits\n :param x: the input placeholder\n :param logits: the model's unnormalized output tensor (the input to\n ... |
Please provide a description of the function:def generate(self, x, **kwargs):
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(
self.model,
x,
self.model.get_logits(x),
eps=self.eps,
num_iterations=self.num_iterations,
... | [
"\n Generate symbolic graph for adversarial examples and return.\n\n :param x: The model's symbolic inputs.\n :param kwargs: See `parse_params`\n "
] |
Please provide a description of the function:def parse_params(self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs):
# Save attack-sp... | [
"\n Take in a dictionary of parameters and applies attack-specific checks\n before saving them as attributes.\n\n Attack-specific parameters:\n\n :param eps: (optional float )the epsilon (input variation parameter)\n :param nb_iter: (optional) the number of iterations\n Defaults to 1 if not spec... |
Please provide a description of the function: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... | [
"Iterate with exponential backoff on failures.\n\n Useful to wrap results of datastore Query.fetch to avoid 429 error.\n\n Args:\n base_iter: basic iterator of generator object\n max_num_tries: maximum number of tries for each request\n max_backoff: maximum backoff, in seconds\n start_backoff: initial... |
Please provide a description of the function:def list_blobs(self, prefix=''):
return [b.name for b in self.bucket.list_blobs(prefix=prefix)] | [
"Lists names of all blobs by their prefix."
] |
Please provide a description of the function:def begin(self):
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 | [
"Begins a batch."
] |
Please provide a description of the function:def rollback(self):
try:
if self._cur_batch:
self._cur_batch.rollback()
except ValueError:
# ignore "Batch must be in progress to rollback" error
pass
self._cur_batch = None
self._num_mutations = 0 | [
"Rolls back pending mutations.\n\n Keep in mind that NoTransactionBatch splits all mutations into smaller\n batches and commit them as soon as mutation buffer reaches maximum length.\n That's why rollback method will only roll back pending mutations from the\n buffer, but won't be able to rollback alrea... |
Please provide a description of the function:def put(self, entity):
self._cur_batch.put(entity)
self._num_mutations += 1
if self._num_mutations >= MAX_MUTATIONS_IN_BATCH:
self.commit()
self.begin() | [
"Adds mutation of the entity to the mutation buffer.\n\n If mutation buffer reaches its capacity then this method commit all pending\n mutations from the buffer and emties it.\n\n Args:\n entity: entity which should be put into the datastore\n "
] |
Please provide a description of the function:def delete(self, key):
self._cur_batch.delete(key)
self._num_mutations += 1
if self._num_mutations >= MAX_MUTATIONS_IN_BATCH:
self.commit()
self.begin() | [
"Adds deletion of the entity with given key to the mutation buffer.\n\n If mutation buffer reaches its capacity then this method commit all pending\n mutations from the buffer and emties it.\n\n Args:\n key: key of the entity which should be deleted\n "
] |
Please provide a description of the function:def get(self, key, transaction=None):
return self._client.get(key, transaction=transaction) | [
"Retrieves an entity given its key."
] |
Please provide a description of the function: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,
lea... | [
"\n MNIST tutorial for Carlini and Wagner's attack\n :param train_start: index of first training set example\n :param train_end: index of last training set example\n :param test_start: index of first test set example\n :param test_end: index of last test set example\n :param viz_enabled: (boolean) activate pl... |
Please provide a description of the function:def attack_selection(attack_string):
# List of Implemented attacks
attacks_list = AVAILABLE_ATTACKS.keys()
# Checking for requested attack in list of available attacks.
if attack_string is None:
raise AttributeError("Attack type is not specified, "
... | [
"\n Selects the Attack Class using string input.\n :param attack_string: adversarial attack name in string format\n :return: attack class defined in cleverhans.attacks_eager\n "
] |
Please provide a description of the function: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,
... | [
"\n MNIST cleverhans tutorial\n :param train_start: index of first training set example.\n :param train_end: index of last training set example.\n :param test_start: index of first test set example.\n :param test_end: index of last test set example.\n :param nb_epochs: number of epochs to train model.\n :par... |
Please provide a description of the function:def sudo_remove_dirtree(dir_name):
try:
subprocess.check_output(['sudo', 'rm', '-rf', dir_name])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t remove directory {0}'.format(dir_name), e) | [
"Removes directory tree as a superuser.\n\n Args:\n dir_name: name of the directory to remove.\n\n This function is necessary to cleanup directories created from inside a\n Docker, since they usually written as a root, thus have to be removed as a\n root.\n "
] |
Please provide a description of the function:def main(args):
title = '## Starting evaluation of round {0} ##'.format(args.round_name)
logging.info('\n'
+ '#' * len(title) + '\n'
+ '#' * len(title) + '\n'
+ '##' + ' ' * (len(title)-2) + '##' + '\n'
+ tit... | [
"Main function which runs worker."
] |
Please provide a description of the function:def download(self):
# 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 submission is a... | [
"Method which downloads submission to local directory."
] |
Please provide a description of the function:def temp_copy_extracted_submission(self):
tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy')
shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir),
tmp_copy_dir])
return tmp_copy_dir | [
"Creates a temporary copy of extracted submission.\n\n When executed, submission is allowed to modify it's own directory. So\n to ensure that submission does not pass any data between runs, new\n copy of the submission is made before each run. After a run temporary copy\n of submission is deleted.\n\n ... |
Please provide a description of the function:def run_without_time_limit(self, cmd):
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd
logging.info('Docker command: %s', ' '.join(cmd))
start_time = time.time()
retval = subprocess.call(cmd)
elapsed_time_sec = int(time.time() - start_time)... | [
"Runs docker command without time limit.\n\n Args:\n cmd: list with the command line arguments which are passed to docker\n binary\n\n Returns:\n how long it took to run submission in seconds\n\n Raises:\n WorkerError: if error occurred during execution of the submission\n "
] |
Please provide a description of the function:def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
if time_limit < 0:
return self.run_without_time_limit(cmd)
container_name = str(uuid.uuid4())
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME,
'--detach', '--name', con... | [
"Runs docker command and enforces time limit.\n\n Args:\n cmd: list with the command line arguments which are passed to docker\n binary after run\n time_limit: time limit, in seconds. Negative value means no limit.\n\n Returns:\n how long it took to run submission in seconds\n\n Raise... |
Please provide a description of the function:def run(self, input_dir, output_dir, epsilon):
logging.info('Running attack %s', self.submission_id)
tmp_run_dir = self.temp_copy_extracted_submission()
cmd = ['--network=none',
'-m=24g',
'--cpus=3.75',
'-v', '{0}:/input_imag... | [
"Runs attack inside Docker.\n\n Args:\n input_dir: directory with input (dataset).\n output_dir: directory where output (adversarial images) should be written.\n epsilon: maximum allowed size of adversarial perturbation,\n should be in range [0, 255].\n\n Returns:\n how long it took... |
Please provide a description of the function:def run(self, input_dir, output_file_path):
logging.info('Running defense %s', self.submission_id)
tmp_run_dir = self.temp_copy_extracted_submission()
output_dir = os.path.dirname(output_file_path)
output_filename = os.path.basename(output_file_path)
... | [
"Runs defense inside Docker.\n\n Args:\n input_dir: directory with input (adversarial images).\n output_file_path: path of the output file.\n\n Returns:\n how long it took to run submission in seconds\n "
] |
Please provide a description of the function:def read_dataset_metadata(self):
if self.dataset_meta:
return
shell_call(['gsutil', 'cp',
'gs://' + self.storage_client.bucket_name + '/'
+ 'dataset/' + self.dataset_name + '_dataset.csv',
LOCAL_DATASET_METAD... | [
"Read `dataset_meta` field from bucket"
] |
Please provide a description of the function:def fetch_attacks_data(self):
if self.attacks_data_initialized:
return
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_datastore()
self.adv_batches.init_from_datastore()
# copy dataset locall... | [
"Initializes data necessary to execute attacks.\n\n This method could be called multiple times, only first call does\n initialization, subsequent calls are noop.\n "
] |
Please provide a description of the function:def run_attack_work(self, work_id):
adv_batch_id = (
self.attack_work.work[work_id]['output_adversarial_batch_id'])
adv_batch = self.adv_batches[adv_batch_id]
dataset_batch_id = adv_batch['dataset_batch_id']
submission_id = adv_batch['submission_... | [
"Runs one attack work.\n\n Args:\n work_id: ID of the piece of work to run\n\n Returns:\n elapsed_time_sec, submission_id - elapsed time and id of the submission\n\n Raises:\n WorkerError: if error occurred during execution.\n "
] |
Please provide a description of the function:def run_attacks(self):
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is available
self.attack_work.read_all_from_datastore()
if not self.attack_work.work:
loggi... | [
"Method which evaluates all attack work.\n\n In a loop this method queries not completed attack work, picks one\n attack work and runs it.\n "
] |
Please provide a description of the function:def fetch_defense_data(self):
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_datastore()
self.a... | [
"Lazy initialization of data necessary to execute defenses."
] |
Please provide a description of the function:def run_defense_work(self, work_id):
class_batch_id = (
self.defense_work.work[work_id]['output_classification_batch_id'])
class_batch = self.class_batches.read_batch_from_datastore(class_batch_id)
adversarial_batch_id = class_batch['adversarial_batc... | [
"Runs one defense work.\n\n Args:\n work_id: ID of the piece of work to run\n\n Returns:\n elapsed_time_sec, submission_id - elapsed time and id of the submission\n\n Raises:\n WorkerError: if error occurred during execution.\n "
] |
Please provide a description of the function:def run_defenses(self):
logging.info('******** Start evaluation of defenses ********')
prev_submission_id = None
need_reload_work = True
while True:
# wait until work is available
if need_reload_work:
if self.num_defense_shards:
... | [
"Method which evaluates all defense work.\n\n In a loop this method queries not completed defense work,\n picks one defense work and runs it.\n "
] |
Please provide a description of the function:def run_work(self):
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() | [
"Run attacks and defenses"
] |
Please provide a description of the function:def arg_type(arg_names, kwargs):
assert isinstance(arg_names, tuple)
passed = tuple(name in kwargs for name in arg_names)
passed_and_not_none = []
for name in arg_names:
if name in kwargs:
passed_and_not_none.append(kwargs[name] is not None)
else:
... | [
"\n Returns a hashable summary of the types of arg_names within kwargs.\n :param arg_names: tuple containing names of relevant arguments\n :param kwargs: dict mapping string argument names to values.\n These must be values for which we can create a tf placeholder.\n Currently supported: numpy darray or som... |
Please provide a description of the function:def construct_graph(self, fixed, feedable, x_val, hash_key):
# try our very best to create a TF placeholder for each of the
# feedable keyword arguments, and check the types are one of
# the allowed types
class_name = str(self.__class__).split(".")[-1][:... | [
"\n Construct the graph required to run the attack through generate_np.\n\n :param fixed: Structural elements that require defining a new graph.\n :param feedable: Arguments that can be fed to the same graph when\n they take different values.\n :param x_val: symbolic adversarial exam... |
Please provide a description of the function:def generate_np(self, x_val, **kwargs):
if self.sess is None:
raise ValueError("Cannot use `generate_np` when no `sess` was"
" provided")
packed = self.construct_variables(kwargs)
fixed, feedable, _, hash_key = packed
if h... | [
"\n Generate adversarial examples and return them as a NumPy array.\n Sub-classes *should not* implement this method unless they must\n perform special handling of arguments.\n\n :param x_val: A NumPy array with the original inputs.\n :param **kwargs: optional parameters used by child classes.\n :... |
Please provide a description of the function:def construct_variables(self, kwargs):
if isinstance(self.feedable_kwargs, dict):
warnings.warn("Using a dict for `feedable_kwargs is deprecated."
"Switch to using a tuple."
"It is not longer necessary to specify the typ... | [
"\n Construct the inputs to the attack graph to be used by generate_np.\n\n :param kwargs: Keyword arguments to generate_np.\n :return:\n Structural arguments\n Feedable arguments\n Output of `arg_type` describing feedable arguments\n A unique key\n "
] |
Please provide a description of the function:def get_or_guess_labels(self, x, kwargs):
if 'y' in kwargs and 'y_target' in kwargs:
raise ValueError("Can not set both 'y' and 'y_target'.")
elif 'y' in kwargs:
labels = kwargs['y']
elif 'y_target' in kwargs and kwargs['y_target'] is not None:
... | [
"\n Get the label to use in generating an adversarial example for x.\n The kwargs are fed directly from the kwargs of the attack.\n If 'y' is in kwargs, then assume it's an untargeted attack and\n use that as the label.\n If 'y_target' is in kwargs and is not none, then assume it's a\n targeted at... |
Please provide a description of the function:def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers.convolut... | [
"As described in https://arxiv.org/abs/1511.06581"
] |
Please provide a description of the function: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,
... | [
"\n MNIST tutorial for the Jacobian-based saliency map approach (JSMA)\n :param train_start: index of first training set example\n :param train_end: index of last training set example\n :param test_start: index of first test set example\n :param test_end: index of last test set example\n :param viz_enabled: (... |
Please provide a description of the function:def generate(self, x, **kwargs):
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
asserts = []
# If a data range was specified, check that the input was in that range
if self.clip_min is not None:
asserts.append(... | [
"\n Generate symbolic graph for adversarial examples and return.\n\n :param x: The model's symbolic inputs.\n :param kwargs: Keyword arguments. See `parse_params` for documentation.\n ",
"Iterate until number of iterations completed",
"Do a momentum step"
] |
Please provide a description of the function: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=No... | [
"\n Take in a dictionary of parameters and applies attack-specific checks\n before saving them as attributes.\n\n Attack-specific parameters:\n\n :param eps: (optional float) maximum distortion of adversarial example\n compared to original input\n :param eps_iter: (optional float) step... |
Please provide a description of the function: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=N... | [
"\n Run (optionally multi-replica, synchronous) training to minimize `loss`\n :param sess: TF session to use when training the graph\n :param loss: tensor, the loss to minimize\n :param x_train: numpy array with training inputs or tf Dataset\n :param y_train: numpy array with training outputs or tf Dataset\n ... |
Please provide a description of the function:def avg_grads(tower_grads):
if len(tower_grads) == 1:
return tower_grads[0]
average_grads = []
for grad_and_vars in zip(*tower_grads):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
... | [
"Calculate the average gradient for each shared variable across all\n towers.\n Note that this function provides a synchronization point across all towers.\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradie... |
Please provide a description of the function:def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs):
# TODO: black box attacks
attack_names = {'FGSM': FastGradientMethod,
'MadryEtAl': MadryEtAl,
'MadryEtAl_y': MadryEtAl,
'MadryEtAl_mul... | [
"\n Creates the symbolic graph of an adversarial example given the name of\n an attack. Simplifies creating the symbolic graph of an attack by defining\n dataset-specific parameters.\n Dataset-specific default parameters are used unless a different value is\n given in kwargs.\n\n :param model: an object of Mo... |
Please provide a description of the function:def log_value(self, tag, val, desc=''):
logging.info('%s (%s): %.4f' % (desc, tag, val))
self.summary.value.add(tag=tag, simple_value=val) | [
"\n Log values to standard output and Tensorflow summary.\n\n :param tag: summary tag.\n :param val: (required float or numpy array) value to be logged.\n :param desc: (optional) additional description to be printed.\n "
] |
Please provide a description of the function:def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
end = (len(X_test) // self.batch_size) * self.batch_size
if self.hparams.fast_tests:
end = 10*self.batch_size
acc = model_eval(self.sess, x, y, preds_adv, X_test[:end],
... | [
"\n Evaluate the accuracy of the model on adversarial examples\n\n :param x: symbolic input to model.\n :param y: symbolic variable for the label.\n :param preds_adv: symbolic variable for the prediction on an\n adversarial example.\n :param X_test: NumPy array of test set inputs... |
Please provide a description of the function:def eval_multi(self, inc_epoch=True):
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summary = tf.Su... | [
"\n Run the evaluation on multiple attacks.\n "
] |
Please provide a description of the function:def run_canary():
# Note: please do not edit this function unless you have access to a machine
# with GPUs suffering from the bug and can verify that the canary still
# crashes after your edits. Due to the transient nature of the GPU bug it is
# not possible to u... | [
"\n Runs some code that will crash if the GPUs / GPU driver are suffering from\n a common bug. This helps to prevent contaminating results in the rest of\n the library with incorrect calculations.\n "
] |
Please provide a description of the function:def _wrap(f):
def wrapper(*args, **kwargs):
warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflow. "
" This function was originally needed as a compatibility layer for old versions of tensorflow, "
... | [
"\n Wraps a callable `f` in a function that warns that the function is deprecated.\n ",
"\n Issues a deprecation warning and passes through the arguments.\n "
] |
Please provide a description of the function:def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
warnings.warn("`reduce_function` is deprecated and may be removed on or after 2019-09-08.")
out = op_func(input_tensor, axis=axis, keepdims=k... | [
"\n This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.\n :param op_func: expects the function to handle eg: tf.reduce_sum.\n :param input_tensor: The tensor to reduce. Should have numeric type.\n :param axis: The dimensions to reduce. If None (the def... |
Please provide a description of the function:def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
# Make sure that all arguments were passed as named arguments.
if ... | [
"\n Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle\n deprecated warning\n "
] |
Please provide a description of the function:def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
dataset_images = [f for f in os.listdir(dataset_batch_dir)
if f.endswith('.png')]
image_hashes = {}
resize_warning = False... | [
"Enforces size of perturbation on images, and compute hashes for all images.\n\n Args:\n dataset_batch_dir: directory with the images of specific dataset batch\n adv_dir: directory with generated adversarial images\n output_dir: directory where to copy result\n epsilon: size of perturbation\n\n Return... |
Please provide a description of the function:def download_dataset(storage_client, image_batches, target_dir,
local_dataset_copy=None):
for batch_id, batch_value in iteritems(image_batches.data):
batch_dir = os.path.join(target_dir, batch_id)
os.mkdir(batch_dir)
for image_id, image_... | [
"Downloads dataset, organize it by batches and rename images.\n\n Args:\n storage_client: instance of the CompetitionStorageClient\n image_batches: subclass of ImageBatchesBase with data about images\n target_dir: target directory, should exist and be empty\n local_dataset_copy: directory with local da... |
Please provide a description of the function:def save_target_classes_for_batch(self,
filename,
image_batches,
batch_id):
images = image_batches.data[batch_id]['images']
with open(filename, 'w') as f:... | [
"Saves file with target class for given dataset batch.\n\n Args:\n filename: output filename\n image_batches: instance of ImageBatchesBase with dataset batches\n batch_id: dataset batch ID\n "
] |
Please provide a description of the function:def tf_min_eig_vec(self):
# Full eigen decomposition requires the explicit psd matrix M
_, matrix_m = self.dual_object.get_full_psd_matrix()
[eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
index = tf.argmin(eig_vals)
return tf.reshape(
... | [
"Function for min eigen vector using tf's full eigen decomposition."
] |
Please provide a description of the function:def tf_smooth_eig_vec(self):
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_vals, self.smooth_plac... | [
"Function that returns smoothed version of min eigen vector."
] |
Please provide a description of the function:def get_min_eig_vec_proxy(self, use_tf_eig=False):
if use_tf_eig:
# If smoothness parameter is too small, essentially no smoothing
# Just output the eigen vector corresponding to min
return tf.cond(self.smooth_placeholder < 1E-8,
... | [
"Computes the min eigen value and corresponding vector of matrix M.\n\n Args:\n use_tf_eig: Whether to use tf's default full eigen decomposition\n Returns:\n eig_vec: Minimum absolute eigen value\n eig_val: Corresponding eigen vector\n "
] |
Please provide a description of the function:def get_scipy_eig_vec(self):
if not self.params['has_conv']:
matrix_m = self.sess.run(self.dual_object.matrix_m)
min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR',
tol=1E-4)
... | [
"Computes scipy estimate of min eigenvalue for matrix M.\n\n Returns:\n eig_vec: Minimum absolute eigen value\n eig_val: Corresponding eigen vector\n "
] |
Please provide a description of the function:def prepare_for_optimization(self):
if self.params['eig_type'] == 'TF':
self.eig_vec_estimate = self.get_min_eig_vec_proxy()
elif self.params['eig_type'] == 'LZS':
self.eig_vec_estimate = self.dual_object.m_min_vec
else:
self.eig_vec_estima... | [
"Create tensorflow op for running one step of descent."
] |
Please provide a description of the function:def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
# Running step
step_feed_dict = {self.eig_init_vec_placeholder: eig_init_vec_val,
self.eig_num_iter_placeholder: eig_... | [
"Run one step of gradient descent for optimization.\n\n Args:\n eig_init_vec_val: Start value for eigen value computations\n eig_num_iter_val: Number of iterations to run for eigen computations\n smooth_val: Value of smoothness parameter\n penalty_val: Value of penalty for the current step\n ... |
Please provide a description of the function:def run_optimization(self):
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on = False
smooth_val = 0
learning_rate_val = self.params['init_learning_rate']
self.current_o... | [
"Run the optimization, call run_one_step with suitable placeholders.\n\n Returns:\n True if certificate is found\n False otherwise\n "
] |
Please provide a description of the function:def load_target_class(input_dir):
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | [
"Loads target classes."
] |
Please provide a description of the function:def save_images(images, filenames, output_dir):
for i, filename in enumerate(filenames):
# Images for inception classifier are normalized to be in [-1, 1] interval,
# so rescale them back to [0, 1].
with tf.gfile.Open(os.path.join(output_dir, filename), 'w')... | [
"Saves images to the output directory.\n\n Args:\n images: array with minibatch of images\n filenames: list of filenames without path\n If number of file names in this list less than number of images in\n the minibatch then only first len(filenames) images will be saved.\n output_dir: directory ... |
Please provide a description of the function:def main(_):
# 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
alpha = 2.0 *... | [
"Run the sample attack"
] |
Please provide a description of the function:def deepfool_batch(sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
... | [
"\n Applies DeepFool to a batch of inputs\n :param sess: TF session\n :param x: The input placeholder\n :param pred: The model's sorted symbolic output of logits, only the top\n nb_candidate classes are contained\n :param logits: The model's unnormalized output tensor (the input to\n ... |
Please provide a description of the function:def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
... | [
"\n TensorFlow implementation of DeepFool.\n Paper link: see https://arxiv.org/pdf/1511.04599.pdf\n :param sess: TF session\n :param x: The input placeholder\n :param predictions: The model's sorted symbolic output of logits, only the\n top nb_candidate classes are contained\n :param logit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.