Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def save_dict_to_file(filename, dictionary):
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) | [
"Saves dictionary as CSV file."
] |
Please provide a description of the function:def main(args):
if args.blacklisted_submissions:
logging.warning('BLACKLISTED SUBMISSIONS: %s',
args.blacklisted_submissions)
if args.limited_dataset:
logging.info('Using limited dataset: 3 batches * 10 images')
max_dataset_num_images =... | [
"Main function which runs master."
] |
Please provide a description of the function:def ask_when_work_is_populated(self, work):
work.read_all_from_datastore()
if work.work:
print('Work is already written to datastore.\n'
'If you continue these data will be overwritten and '
'possible corrupted.')
inp = input_... | [
"When work is already populated asks whether we should continue.\n\n This method prints warning message that work is populated and asks\n whether user wants to continue or not.\n\n Args:\n work: instance of WorkPiecesBase\n\n Returns:\n True if we should continue and populate datastore, False ... |
Please provide a description of the function:def prepare_attacks(self):
print_header('PREPARING ATTACKS DATA')
# verify that attacks data not written yet
if not self.ask_when_work_is_populated(self.attack_work):
return
self.attack_work = eval_lib.AttackWorkPieces(
datastore_client=sel... | [
"Prepares all data needed for evaluation of attacks."
] |
Please provide a description of the function:def prepare_defenses(self):
print_header('PREPARING DEFENSE DATA')
# verify that defense data not written yet
if not self.ask_when_work_is_populated(self.defense_work):
return
self.defense_work = eval_lib.DefenseWorkPieces(
datastore_client... | [
"Prepares all data needed for evaluation of defenses."
] |
Please provide a description of the function:def _save_work_results(self, run_stats, scores, num_processed_images,
filename):
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(
['SubmissionID', 'ExternalSubmissionId', 'Score',
'Compl... | [
"Saves statistics about each submission.\n\n Saved statistics include score; number of completed and failed batches;\n min, max, average and median time needed to run one batch.\n\n Args:\n run_stats: dictionary with runtime statistics for submissions,\n can be generated by WorkPiecesBase.compu... |
Please provide a description of the function:def _save_sorted_results(self, run_stats, scores, image_count, filename):
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(['SubmissionID', 'ExternalTeamId', 'Score',
'MedianTime', 'ImageCount'])
def get... | [
"Saves sorted (by score) results of the evaluation.\n\n Args:\n run_stats: dictionary with runtime statistics for submissions,\n can be generated by WorkPiecesBase.compute_work_statistics\n scores: dictionary mapping submission ids to scores\n image_count: dictionary with number of images p... |
Please provide a description of the function:def _read_dataset_metadata(self):
blob = self.storage_client.get_blob(
'dataset/' + self.dataset_name + '_dataset.csv')
buf = BytesIO()
blob.download_to_file(buf)
buf.seek(0)
return eval_lib.DatasetMetadata(buf) | [
"Reads dataset metadata.\n\n Returns:\n instance of DatasetMetadata\n "
] |
Please provide a description of the function:def compute_results(self):
# read all data
logging.info('Reading data from datastore')
dataset_meta = self._read_dataset_metadata()
self.submissions.init_from_datastore()
self.dataset_batches.init_from_datastore()
self.adv_batches.init_from_datas... | [
"Computes results (scores, stats, etc...) of competition evaluation.\n\n Results are saved into output directory (self.results_dir).\n Also this method saves all intermediate data into output directory as well,\n so it can resume computation if it was interrupted for some reason.\n This is useful becaus... |
Please provide a description of the function:def _show_status_for_work(self, work):
work_count = len(work.work)
work_completed = {}
work_completed_count = 0
for v in itervalues(work.work):
if v['is_completed']:
work_completed_count += 1
worker_id = v['claimed_worker_id']
... | [
"Shows status for given work pieces.\n\n Args:\n work: instance of either AttackWorkPieces or DefenseWorkPieces\n "
] |
Please provide a description of the function:def _export_work_errors(self, work, output_file):
errors = set()
for v in itervalues(work.work):
if v['is_completed'] and v['error'] is not None:
errors.add(v['error'])
with open(output_file, 'w') as f:
for e in sorted(errors):
f.... | [
"Saves errors for given work pieces into file.\n\n Args:\n work: instance of either AttackWorkPieces or DefenseWorkPieces\n output_file: name of the output file\n "
] |
Please provide a description of the function:def show_status(self):
print_header('Attack work statistics')
self.attack_work.read_all_from_datastore()
self._show_status_for_work(self.attack_work)
self._export_work_errors(
self.attack_work,
os.path.join(self.results_dir, 'attack_error... | [
"Shows current status of competition evaluation.\n\n Also this method saves error messages generated by attacks and defenses\n into attack_errors.txt and defense_errors.txt.\n "
] |
Please provide a description of the function:def cleanup_failed_attacks(self):
print_header('Cleaning up failed attacks')
attacks_to_replace = {}
self.attack_work.read_all_from_datastore()
failed_submissions = set()
error_msg = set()
for k, v in iteritems(self.attack_work.work):
if v[... | [
"Cleans up data of failed attacks."
] |
Please provide a description of the function:def cleanup_attacks_with_zero_images(self):
print_header('Cleaning up attacks which generated 0 images.')
# find out attack work to cleanup
self.adv_batches.init_from_datastore()
self.attack_work.read_all_from_datastore()
new_attack_work = {}
aff... | [
"Cleans up data about attacks which generated zero images."
] |
Please provide a description of the function:def _cleanup_keys_with_confirmation(self, keys_to_delete):
print('Round name: ', self.round_name)
print('Number of entities to be deleted: ', len(keys_to_delete))
if not keys_to_delete:
return
if self.verbose:
print('Entities to delete:')
... | [
"Asks confirmation and then deletes entries with keys.\n\n Args:\n keys_to_delete: list of datastore keys for which entries should be deleted\n "
] |
Please provide a description of the function:def cleanup_defenses(self):
print_header('CLEANING UP DEFENSES DATA')
work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')
keys_to_delete = [
e.key
for e in self.datastore_client.query_fetch(kind=u'ClassificationBatch')
... | [
"Cleans up all data about defense work in current round."
] |
Please provide a description of the function:def cleanup_datastore(self):
print_header('CLEANING UP ENTIRE DATASTORE')
kinds_to_delete = [u'Submission', u'SubmissionType',
u'DatasetImage', u'DatasetBatch',
u'AdversarialImage', u'AdversarialBatch',
... | [
"Cleans up datastore and deletes all information about current round."
] |
Please provide a description of the function:def main(_):
eps = FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
with tf.Graph().as_default():
x_input = tf.placeholder(tf.float32, shape=batch_shape)
noisy_images = x_input + eps * tf.sign(tf.random_no... | [
"Run the sample attack"
] |
Please provide a description of the function:def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max):
nb_classes = int(y_target.shape[-1].value)
nb_features = int(np.product(x.shape[1:]).value)
if x.dtype == tf.float32 and y_target.dtype == tf.int64:
y_target = tf.cast(y_target, tf.int32)... | [
"\n TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528\n for details about the algorithm design choices).\n\n :param x: the input placeholder\n :param y_target: the target tensor\n :param model: a cleverhans.model.Model object.\n :param theta: delta for each feature adjustment\n :par... |
Please provide a description of the function:def generate(self, x, **kwargs):
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
if self.symbolic_impl:
# Create random targets if y_target not provided
if self.y_target is None:
from random import randint
... | [
"\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,
theta=1.,
gamma=1.,
clip_min=0.,
clip_max=1.,
y_target=None,
symbolic_impl=True,
**kwargs):
self.theta = theta... | [
"\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 theta: (optional float) Perturbation introduced to modified\n components (can be positive or negative)\n :param gamma: (optional fl... |
Please provide a description of the function:def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
model = make_basic_cnn()
layers = model.layers
model = MLPnGPU(nb_classes, layers, input_shape)
return model | [
"\n Create a multi-GPU model similar to the basic cnn in the tutorials.\n "
] |
Please provide a description of the function:def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
layers = [Conv2DnGPU(32, (5, 5), (1, 1), "SAME"),
ReLU(),
MaxPool((2, 2), (2, 2), "SAME"),
Conv2DnGPU(64, (5, 5), (1, 1), "SAME"),
ReLU(),
... | [
"\n Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).\n "
] |
Please provide a description of the function:def _build_model(self, x):
with tf.variable_scope('init'):
x = self._conv('init_conv', x, 3, x.shape[3], 16,
self._stride_arr(1))
strides = [1, 2, 2]
activate_before_residual = [True, False, False]
if self.hps.use_bottleneck:
... | [
"Build the core model within the graph."
] |
Please provide a description of the function:def build_cost(self, labels, logits):
op = logits.op
if "softmax" in str(op).lower():
logits, = op.inputs
with tf.variable_scope('costs'):
xent = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
cost = tf.re... | [
"\n Build the graph for cost from the logits if logits are provided.\n If predictions are provided, logits are extracted from the operation.\n "
] |
Please provide a description of the function:def build_train_op_from_cost(self, cost):
self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32,
name='learning_rate')
self.momentum = tf.constant(self.hps.momentum, tf.float32,
name='momentum')... | [
"Build training specific ops for the graph."
] |
Please provide a description of the function:def _layer_norm(self, name, x):
if self.init_layers:
bn = LayerNorm()
bn.name = name
self.layers += [bn]
else:
bn = self.layers[self.layer_idx]
self.layer_idx += 1
bn.device_name = self.device_name
bn.set_training(self.train... | [
"Layer normalization."
] |
Please provide a description of the function:def _residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = self._layer_norm('init_bn', x)
x = self._relu(x, self.hps.relu_... | [
"Residual unit with 2 sub layers."
] |
Please provide a description of the function:def _bottleneck_residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
if activate_before_residual:
with tf.variable_scope('common_bn_relu'):
x = self._layer_norm('init_bn', x)
x = self._rel... | [
"Bottleneck residual unit with 3 sub layers."
] |
Please provide a description of the function:def _decay(self):
if self.decay_cost is not None:
return self.decay_cost
costs = []
if self.device_name is None:
for var in tf.trainable_variables():
if var.op.name.find(r'DW') > 0:
costs.append(tf.nn.l2_loss(var))
else:
... | [
"L2 weight decay loss."
] |
Please provide a description of the function:def _conv(self, name, x, filter_size, in_filters, out_filters, strides):
if self.init_layers:
conv = Conv2DnGPU(out_filters,
(filter_size, filter_size),
strides[1:3], 'SAME', w_name='DW')
conv.name = name
... | [
"Convolution."
] |
Please provide a description of the function:def _fully_connected(self, x, out_dim):
if self.init_layers:
fc = LinearnGPU(out_dim, w_name='DW')
fc.name = 'logits'
self.layers += [fc]
else:
fc = self.layers[self.layer_idx]
self.layer_idx += 1
fc.device_name = self.device_na... | [
"FullyConnected layer for final output."
] |
Please provide a description of the function:def read_classification_results(storage_client, file_path):
if storage_client:
# file on Cloud
success = False
retry_count = 0
while retry_count < 4:
try:
blob = storage_client.get_blob(file_path)
if not blob:
return {}
... | [
"Reads classification results from the file in Cloud Storage.\n\n This method reads file with classification results produced by running\n defense on singe batch of adversarial images.\n\n Args:\n storage_client: instance of CompetitionStorageClient or None for local file\n file_path: path of the file with... |
Please provide a description of the function:def analyze_one_classification_result(storage_client, file_path,
adv_batch, dataset_batches,
dataset_meta):
class_result = read_classification_results(storage_client, file_path)
if class_resul... | [
"Reads and analyzes one classification result.\n\n This method reads file with classification result and counts\n how many images were classified correctly and incorrectly,\n how many times target class was hit and total number of images.\n\n Args:\n storage_client: instance of CompetitionStorageClient\n ... |
Please provide a description of the function:def save_to_file(self, filename, remap_dim0=None, remap_dim1=None):
# rows - first index
# columns - second index
with open(filename, 'w') as fobj:
columns = list(sorted(self._dim1))
for col in columns:
fobj.write(',')
fobj.write(... | [
"Saves matrix to the file.\n\n Args:\n filename: name of the file where to save matrix\n remap_dim0: dictionary with mapping row indices to row names which should\n be saved to file. If none then indices will be used as names.\n remap_dim1: dictionary with mapping column indices to column n... |
Please provide a description of the function:def init_from_adversarial_batches_write_to_datastore(self, submissions,
adv_batches):
# prepare classification batches
idx = 0
for s_id in iterkeys(submissions.defenses):
for adv_id in iterkeys(adv... | [
"Populates data from adversarial batches and writes to datastore.\n\n Args:\n submissions: instance of CompetitionSubmissions\n adv_batches: instance of AversarialBatches\n "
] |
Please provide a description of the function:def init_from_datastore(self):
self._data = {}
client = self._datastore_client
for entity in client.query_fetch(kind=KIND_CLASSIFICATION_BATCH):
class_batch_id = entity.key.flat_path[-1]
self.data[class_batch_id] = dict(entity) | [
"Initializes data by reading it from the datastore."
] |
Please provide a description of the function:def read_batch_from_datastore(self, class_batch_id):
client = self._datastore_client
key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id)
result = client.get(key)
if result is not None:
return dict(result)
else:
raise KeyError(
... | [
"Reads and returns single batch from the datastore."
] |
Please provide a description of the function:def compute_classification_results(self, adv_batches, dataset_batches,
dataset_meta, defense_work=None):
class_batch_to_work = {}
if defense_work:
for v in itervalues(defense_work.work):
class_batch_to_work[v['o... | [
"Computes classification results.\n\n Args:\n adv_batches: instance of AversarialBatches\n dataset_batches: instance of DatasetBatches\n dataset_meta: instance of DatasetMetadata\n defense_work: instance of DefenseWorkPieces\n\n Returns:\n accuracy_matrix, error_matrix, hit_target_cla... |
Please provide a description of the function:def participant_from_submission_path(submission_path):
basename = os.path.basename(submission_path)
file_ext = None
for e in ALLOWED_EXTENSIONS:
if basename.endswith(e):
file_ext = e
break
if not file_ext:
raise ValueError('Invalid submission p... | [
"Parses type of participant based on submission filename.\n\n Args:\n submission_path: path to the submission in Google Cloud Storage\n\n Returns:\n dict with one element. Element key correspond to type of participant\n (team, baseline), element value is ID of the participant.\n\n Raises:\n ValueErro... |
Please provide a description of the function:def _load_submissions_from_datastore_dir(self, dir_suffix, id_pattern):
submissions = self._storage_client.list_blobs(
prefix=os.path.join(self._round_name, dir_suffix))
return {
id_pattern.format(idx): SubmissionDescriptor(
path=s, p... | [
"Loads list of submissions from the directory.\n\n Args:\n dir_suffix: suffix of the directory where submissions are stored,\n one of the folowing constants: ATTACK_SUBDIR, TARGETED_ATTACK_SUBDIR\n or DEFENSE_SUBDIR.\n id_pattern: pattern which is used to generate (internal) IDs\n ... |
Please provide a description of the function:def init_from_storage_write_to_datastore(self):
# Load submissions
self._attacks = self._load_submissions_from_datastore_dir(
ATTACK_SUBDIR, ATTACK_ID_PATTERN)
self._targeted_attacks = self._load_submissions_from_datastore_dir(
TARGETED_ATTAC... | [
"Init list of sumibssions from Storage and saves them to Datastore.\n\n Should be called only once (typically by master) during evaluation of\n the competition.\n "
] |
Please provide a description of the function:def _write_to_datastore(self):
# Populate datastore
roots_and_submissions = zip([ATTACKS_ENTITY_KEY,
TARGET_ATTACKS_ENTITY_KEY,
DEFENSES_ENTITY_KEY],
[self._attacks... | [
"Writes all submissions to datastore."
] |
Please provide a description of the function:def init_from_datastore(self):
self._attacks = {}
self._targeted_attacks = {}
self._defenses = {}
for entity in self._datastore_client.query_fetch(kind=KIND_SUBMISSION):
submission_id = entity.key.flat_path[-1]
submission_path = entity['submi... | [
"Init list of submission from Datastore.\n\n Should be called by each worker during initialization.\n "
] |
Please provide a description of the function:def get_all_attack_ids(self):
return list(self.attacks.keys()) + list(self.targeted_attacks.keys()) | [
"Returns IDs of all attacks (targeted and non-targeted)."
] |
Please provide a description of the function:def find_by_id(self, submission_id):
return self._attacks.get(
submission_id,
self._defenses.get(
submission_id,
self._targeted_attacks.get(submission_id, None))) | [
"Finds submission by ID.\n\n Args:\n submission_id: ID of the submission\n\n Returns:\n SubmissionDescriptor with information about submission or None if\n submission is not found.\n "
] |
Please provide a description of the function:def get_external_id(self, submission_id):
submission = self.find_by_id(submission_id)
if not submission:
return None
if 'team_id' in submission.participant_id:
return submission.participant_id['team_id']
elif 'baseline_id' in submission.parti... | [
"Returns human readable submission external ID.\n\n Args:\n submission_id: internal submission ID.\n\n Returns:\n human readable ID.\n "
] |
Please provide a description of the function:def _prepare_temp_dir(self):
shell_call(['rm', '-rf', os.path.join(self._temp_dir, '*')])
# NOTE: we do not create self._extracted_submission_dir
# this is intentional because self._tmp_extracted_dir or it's subdir
# will be renames into self._extracted_... | [
"Cleans up and prepare temporary directory."
] |
Please provide a description of the function:def _load_and_verify_metadata(self, submission_type):
metadata_filename = os.path.join(self._extracted_submission_dir,
'metadata.json')
if not os.path.isfile(metadata_filename):
logging.error('metadata.json not found')
... | [
"Loads and verifies metadata.\n\n Args:\n submission_type: type of the submission\n\n Returns:\n dictionaty with metadata or None if metadata not found or invalid\n "
] |
Please provide a description of the function:def _run_submission(self, metadata):
if self._use_gpu:
docker_binary = 'nvidia-docker'
container_name = metadata['container_gpu']
else:
docker_binary = 'docker'
container_name = metadata['container']
if metadata['type'] == 'defense':
... | [
"Runs submission inside Docker container.\n\n Args:\n metadata: dictionary with submission metadata\n\n Returns:\n True if status code of Docker command was success (i.e. zero),\n False otherwise.\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 Tensorflow 2.0 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).... |
Please provide a description of the function:def compute_gradient(model_fn, x, y, targeted):
loss_fn = tf.nn.sparse_softmax_cross_entropy_with_logits
with tf.GradientTape() as g:
g.watch(x)
# Compute loss
loss = loss_fn(labels=y, logits=model_fn(x))
if targeted: # attack is targeted, minimize lo... | [
"\n Computes the gradient of the loss with respect to the input tensor.\n :param model_fn: a callable that takes an input tensor and returns the model logits.\n :param x: input tensor\n :param y: Tensor with true labels. If targeted is true, then provide the target label.\n :param targeted: bool. Is the attac... |
Please provide a description of the function:def optimize_linear(grad, eps, ord=np.inf):
# Convert the iterator returned by `range` into a list.
axis = list(range(1, len(grad.get_shape())))
avoid_zero_div = 1e-12
if ord == np.inf:
# Take sign of gradient
optimal_perturbation = tf.sign(grad)
# Th... | [
"\n Solves for the optimal input to a linear function under a norm constraint.\n\n Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)\n\n :param grad: tf tensor containing a batch of gradients\n :param eps: float scalar specifying size of constraint region\n :param ord: int specifying orde... |
Please provide a description of the function:def save_pdf(path):
pp = PdfPages(path)
pp.savefig(pyplot.gcf())
pp.close() | [
"\n Saves a pdf of the current matplotlib figure.\n\n :param path: str, filepath to save to\n "
] |
Please provide a description of the function:def clip_eta(eta, ord, eps):
# Clipping perturbation eta to self.ord norm ball
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
axis = list(range(1, len(eta.get_shape())))
avoid_zero_div = 1e-12
if ord == np.inf:
eta = tf.c... | [
"\n Helper function to clip the perturbation to epsilon norm ball.\n :param eta: A tensor with the current perturbation.\n :param ord: Order of the norm (mimics Numpy).\n Possible values: np.inf, 1 or 2.\n :param eps: Epsilon, bound of the perturbation.\n "
] |
Please provide a description of the function:def prep_bbox(sess, x, y, x_train, y_train, x_test, y_test,
nb_epochs, batch_size, learning_rate,
rng, nb_classes=10, img_rows=28, img_cols=28, nchannels=1):
# Define TF model graph (for the black-box model)
nb_filters = 64
model = Model... | [
"\n Define and train a model that simulates the \"remote\"\n black-box oracle described in the original paper.\n :param sess: the TF session\n :param x: the input placeholder for MNIST\n :param y: the ouput placeholder for MNIST\n :param x_train: the training data for the oracle\n :param y_train: the trainin... |
Please provide a description of the function:def train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes,
nb_epochs_s, batch_size, learning_rate, data_aug, lmbda,
aug_batch_size, rng, img_rows=28, img_cols=28,
nchannels=1):
# Define TF model graph (for the black-box mod... | [
"\n This function creates the substitute by alternatively\n augmenting the training data and training the substitute.\n :param sess: TF session\n :param x: input TF placeholder\n :param y: output TF placeholder\n :param bbox_preds: output of black-box model predictions\n :param x_sub: initial substitute trai... |
Please provide a description of the function:def mnist_blackbox(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_classes=NB_CLASSES,
batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE,
nb_epochs=NB_EPOCHS, holdout=HOLDOUT, data_aug=DATA_AUG,
... | [
"\n MNIST tutorial for the black-box attack from arxiv.org/abs/1602.02697\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 :return: a diction... |
Please provide a description of the function:def random_shift(x, pad=(4, 4), mode='REFLECT'):
assert mode in 'REFLECT SYMMETRIC CONSTANT'.split()
assert x.get_shape().ndims == 3
xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode)
return tf.random_crop(xp, tf.shape(x)) | [
"Pad a single image and then crop to the original size with a random\n offset."
] |
Please provide a description of the function:def batch_augment(x, func, device='/CPU:0'):
with tf.device(device):
return tf.map_fn(func, x) | [
"\n Apply dataset augmentation to a batch of exmaples.\n :param x: Tensor representing a batch of examples.\n :param func: Callable implementing dataset augmentation, operating on\n a single image.\n :param device: String specifying which device to use.\n "
] |
Please provide a description of the function:def random_crop_and_flip(x, pad_rows=4, pad_cols=4):
rows = tf.shape(x)[1]
cols = tf.shape(x)[2]
channels = x.get_shape()[3]
def _rand_crop_img(img):
return tf.random_crop(img, [rows, cols, channels])
# Some of these ops are only on CPU.
# This func... | [
"Augment a batch by randomly cropping and horizontally flipping it.",
"Randomly crop an individual image"
] |
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=CLEAN_TRAIN,
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 :param ba... |
Please provide a description of the function:def _project_perturbation(perturbation, epsilon, input_image, clip_min=None,
clip_max=None):
if clip_min is None or clip_max is None:
raise NotImplementedError("_project_perturbation currently has clipping "
"... | [
"Project `perturbation` onto L-infinity ball of radius `epsilon`.\n Also project into hypercube such that the resulting adversarial example\n is between clip_min and clip_max, if applicable.\n "
] |
Please provide a description of the function:def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None):
if num_classes is not None:
warnings.warn("`num_classes` is depreciated. Switch to `nb_classes`."
" `num_classes` may be removed on or after 2019-04-23.")
nb_classes =... | [
"Computes difference between logit for `label` and next highest logit.\n\n The loss is high when `label` is unlikely (targeted by default).\n This follows the same interface as `loss_fn` for TensorOptimizer and\n projected_optimization, i.e. it returns a batch of loss values.\n "
] |
Please provide a description of the function:def spm(x, model, y=None, n_samples=None, dx_min=-0.1,
dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5,
angle_min=-30, angle_max=30, n_angles=31, black_border_size=0):
if y is None:
preds = model.get_probs(x)
# Using model predictions as gr... | [
"\n TensorFlow implementation of the Spatial Transformation Method.\n :return: a tensor for the adversarial example\n "
] |
Please provide a description of the function:def parallel_apply_transformations(x, transforms, black_border_size=0):
transforms = tf.convert_to_tensor(transforms, dtype=tf.float32)
x = _apply_black_border(x, black_border_size)
num_transforms = transforms.get_shape().as_list()[0]
im_shape = x.get_shape().as_... | [
"\n Apply image transformations in parallel.\n :param transforms: TODO\n :param black_border_size: int, size of black border to apply\n Returns:\n Transformed images\n "
] |
Please provide a description of the function:def projected_optimization(loss_fn,
input_image,
label,
epsilon,
num_steps,
clip_min=None,
clip_max=None,
... | [
"Generic projected optimization, generalized to work with approximate\n gradients. Used for e.g. the SPSA attack.\n\n Args:\n :param loss_fn: A callable which takes `input_image` and `label` as\n arguments, and returns a batch of loss values. Same\n interface as TensorOpti... |
Please provide a description of the function:def generate(self,
x,
y=None,
y_target=None,
eps=None,
clip_min=None,
clip_max=None,
nb_iter=None,
is_targeted=None,
early_stop_loss_thresho... | [
"\n Generate symbolic graph for adversarial examples.\n\n :param x: The model's symbolic inputs. Must be a batch of size 1.\n :param y: A Tensor or None. The index of the correct label.\n :param y_target: A Tensor or None. The index of the target label in a\n targeted attack.\n :p... |
Please provide a description of the function:def _compute_gradients(self, loss_fn, x, unused_optim_state):
# Assumes `x` is a list,
# and contains a tensor representing a batch of images
assert len(x) == 1 and isinstance(x, list), \
'x should be a list and contain only one image tensor'
x ... | [
"Compute a new value of `x` to minimize `loss_fn`.\n\n Args:\n loss_fn: a callable that takes `x`, a batch of images, and returns\n a batch of loss values. `x` will be optimized to minimize\n `loss_fn(x)`.\n x: A list of Tensors, the values to be updated. This is analogous\n ... |
Please provide a description of the function:def minimize(self, loss_fn, x, optim_state):
grads = self._compute_gradients(loss_fn, x, optim_state)
return self._apply_gradients(grads, x, optim_state) | [
"\n Analogous to tf.Optimizer.minimize\n\n :param loss_fn: tf Tensor, representing the loss to minimize\n :param x: list of Tensor, analogous to tf.Optimizer's var_list\n :param optim_state: A possibly nested dict, containing any optimizer state.\n\n Returns:\n new_x: list of Tensor, updated ver... |
Please provide a description of the function:def init_state(self, x):
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state | [
"\n Initialize t, m, and u\n "
] |
Please provide a description of the function:def _apply_gradients(self, grads, x, optim_state):
new_x = [None] * len(x)
new_optim_state = {
"t": optim_state["t"] + 1.,
"m": [None] * len(x),
"u": [None] * len(x)
}
t = new_optim_state["t"]
for i in xrange(len(x)):
g ... | [
"Refer to parent class documentation."
] |
Please provide a description of the function:def _compute_gradients(self, loss_fn, x, unused_optim_state):
# Assumes `x` is a list, containing a [1, H, W, C] image
# If static batch dimension is None, tf.reshape to batch size 1
# so that static shape can be inferred
assert len(x) == 1
static_x_... | [
"Compute gradient estimates using SPSA."
] |
Please provide a description of the function:def parse_args():
parser = argparse.ArgumentParser(
description='Tool to run attacks and defenses.')
parser.add_argument('--attacks_dir', required=True,
help='Location of all attacks.')
parser.add_argument('--targeted_attacks_dir', requir... | [
"Parses command line arguments."
] |
Please provide a description of the function:def read_submissions_from_directory(dirname, use_gpu):
result = []
for sub_dir in os.listdir(dirname):
submission_path = os.path.join(dirname, sub_dir)
try:
if not os.path.isdir(submission_path):
continue
if not os.path.exists(os.path.join(... | [
"Scans directory and read all submissions.\n\n Args:\n dirname: directory to scan.\n use_gpu: whether submissions should use GPU. This argument is\n used to pick proper Docker container for each submission and create\n instance of Attack or Defense class.\n\n Returns:\n List with submissions (s... |
Please provide a description of the function:def load_defense_output(filename):
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if image_filename.endswith('.png') or image_filename.endswith('.jpg'):
image_filename = image_filename[:... | [
"Loads output of defense from given file."
] |
Please provide a description of the function:def compute_and_save_scores_and_ranking(attacks_output,
defenses_output,
dataset_meta,
output_dir,
save_all_classif... | [
"Computes scores and ranking and saves it.\n\n Args:\n attacks_output: output of attacks, instance of AttacksOutput class.\n defenses_output: outputs of defenses. Dictionary of dictionaries, key in\n outer dictionary is name of the defense, key of inner dictionary is\n name of the image, value of i... |
Please provide a description of the function:def main():
args = parse_args()
attacks_output_dir = os.path.join(args.intermediate_results_dir,
'attacks_output')
targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir,
... | [
"Run all attacks against all defenses and compute results.\n "
] |
Please provide a description of the function:def run(self, input_dir, output_dir, epsilon):
print('Running attack ', self.name)
cmd = [self.docker_binary(), 'run',
'-v', '{0}:/input_images'.format(input_dir),
'-v', '{0}:/output_images'.format(output_dir),
'-v', '{0}:/code'.... | [
"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 "
] |
Please provide a description of the function:def _load_dataset_clipping(self, dataset_dir, epsilon):
self.dataset_max_clip = {}
self.dataset_min_clip = {}
self._dataset_image_count = 0
for fname in os.listdir(dataset_dir):
if not fname.endswith('.png'):
continue
image_id = fname... | [
"Helper method which loads dataset and determines clipping range.\n\n Args:\n dataset_dir: location of the dataset.\n epsilon: maximum allowed size of adversarial perturbation.\n "
] |
Please provide a description of the function:def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
if is_targeted:
self._targeted_attack_names.add(attack_name)
else:
self._attack_names.add(attack_name)
attack_dir = os.path.join(self.targeted_attacks_output_dir
... | [
"Clips results of attack and copy it to directory with all images.\n\n Args:\n attack_name: name of the attack.\n is_targeted: if True then attack is targeted, otherwise non-targeted.\n "
] |
Please provide a description of the function:def save_target_classes(self, filename):
with open(filename, 'w') as f:
for k, v in self._target_classes.items():
f.write('{0}.png,{1}\n'.format(k, v)) | [
"Saves target classed for all dataset images into given file."
] |
Please provide a description of the function:def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps,
clip_min, clip_max, eps_iter, nb_iter,
report_path,
batch_size=BATCH_SIZE,
... | [
"A reasonable attack bundling recipe for a max norm threat model and\n a defender that uses confidence thresholding. This recipe uses both\n uniform noise and randomly-initialized PGD targeted attacks.\n\n References:\n https://openreview.net/forum?id=H1g0piA9tQ\n\n This version runs each attack (noise, target... |
Please provide a description of the function:def random_search_max_confidence_recipe(sess, model, x, y, eps,
clip_min, clip_max,
report_path, batch_size=BATCH_SIZE,
num_noise_points=10000):
noise... | [
"Max confidence using random search.\n\n References:\n https://openreview.net/forum?id=H1g0piA9tQ\n Describes the max_confidence procedure used for the bundling in this recipe\n https://arxiv.org/abs/1802.00420\n Describes using random search with 1e5 or more random points to avoid\n gradient masking.\n... |
Please provide a description of the function:def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path,
attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
assert isinstance(sess, tf.Session)
assert isinstance(model, Model)
assert all(isinstance(attack_config, AttackCon... | [
"\n Runs attack bundling.\n Users of cleverhans may call this function but are more likely to call\n one of the recipes above.\n\n Reference: https://openreview.net/forum?id=H1g0piA9tQ\n\n :param sess: tf.session.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing clean example ... |
Please provide a description of the function:def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs,
run_counts,
goal, report, report_path,
attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
goal.start(run... | [
"\n Runs attack bundling, working on one specific AttackGoal.\n This function is mostly intended to be called by `bundle_attacks`.\n\n Reference: https://openreview.net/forum?id=H1g0piA9tQ\n\n :param sess: tf.session.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing clean examp... |
Please provide a description of the function:def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs,
run_counts, goal, report, report_path,
attack_batch_size=BATCH_SIZE):
attack_config = goal.get_attack_config(attack_configs, run_counts, crite... | [
"\n Runs attack bundling on one batch of data.\n This function is mostly intended to be called by\n `bundle_attacks_with_goal`.\n\n :param sess: tf.session.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing clean example inputs to attack\n :param y: numpy array containing true ... |
Please provide a description of the function:def save(criteria, report, report_path, adv_x_val):
print_stats(criteria['correctness'], criteria['confidence'], 'bundled')
print("Saving to " + report_path)
serial.save(report_path, report)
assert report_path.endswith(".joblib")
adv_x_path = report_path[:-len... | [
"\n Saves the report and adversarial examples.\n :param criteria: dict, of the form returned by AttackGoal.get_criteria\n :param report: dict containing a confidence report\n :param report_path: string, filepath\n :param adv_x_val: numpy array containing dataset of adversarial examples\n "
] |
Please provide a description of the function:def unfinished_attack_configs(new_work_goal, work_before, run_counts,
log=False):
assert isinstance(work_before, dict), work_before
for key in work_before:
value = work_before[key]
assert value.ndim == 1, value.shape
if key ... | [
"\n Returns a list of attack configs that have not yet been run the desired\n number of times.\n :param new_work_goal: dict mapping attacks to desired number of times to run\n :param work_before: dict mapping attacks to number of times they were run\n before starting this new goal. Should be prefiltered to i... |
Please provide a description of the function:def bundle_examples_with_goal(sess, model, adv_x_list, y, goal,
report_path, batch_size=BATCH_SIZE):
# Check the input
num_attacks = len(adv_x_list)
assert num_attacks > 0
adv_x_0 = adv_x_list[0]
assert isinstance(adv_x_0, np.ndarr... | [
"\n A post-processor version of attack bundling, that chooses the strongest\n example from the output of multiple earlier bundling strategies.\n\n :param sess: tf.session.Session\n :param model: cleverhans.model.Model\n :param adv_x_list: list of numpy arrays\n Each entry in the list is the output of a prev... |
Please provide a description of the function:def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps,
clip_min, clip_max, nb_iter,
report_path,
spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES,
sp... | [
"Runs the MaxConfidence attack using SPSA as the underlying optimizer.\n\n Even though this runs only one attack, it must be implemented as a bundler\n because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence\n attack internally multiplies the batch size by nb_classes, so it can't take\n SP... |
Please provide a description of the function:def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE):
names, factory = self.extra_criteria()
factory = _CriteriaFactory(model, factory)
results = batch_eval_multi_worker(sess, factory, [advx, y],
batch_si... | [
"\n Returns a dictionary mapping the name of each criterion to a NumPy\n array containing the value of that criterion for each adversarial\n example.\n Subclasses can add extra criteria by implementing the `extra_criteria`\n method.\n\n :param sess: tf.session.Session\n :param model: cleverhans... |
Please provide a description of the function:def request_examples(self, attack_config, criteria, run_counts, batch_size):
raise NotImplementedError(str(type(self)) +
"needs to implement request_examples") | [
"\n Returns a numpy array of integer example indices to run in the next batch.\n "
] |
Please provide a description of the function:def new_wins(self, orig_criteria, orig_idx, new_criteria, new_idx):
raise NotImplementedError(str(type(self))
+ " needs to implement new_wins.") | [
"\n Returns a bool indicating whether a new adversarial example is better\n than the pre-existing one for the same clean example.\n :param orig_criteria: dict mapping names of criteria to their value\n for each example in the whole dataset\n :param orig_idx: The position of the pre-existing example... |
Please provide a description of the function:def filter(self, run_counts, criteria):
correctness = criteria['correctness']
assert correctness.dtype == np.bool
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = filtered_counts[key][correctness]
retur... | [
"\n Return run counts only for examples that are still correctly classified\n "
] |
Please provide a description of the function:def filter(self, run_counts, criteria):
wrong_confidence = criteria['wrong_confidence']
below_t = wrong_confidence <= self.t
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = filtered_counts[key][below_t]
... | [
"\n Return the counts for only those examples that are below the threshold\n "
] |
Please provide a description of the function:def projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, ord,
clip_min=None, clip_max=None, y=None, targeted=False,
rand_init=None, rand_minmax=0.3, sanity_checks=True):
assert eps_iter <= eps, (e... | [
"\n This class implements either the Basic Iterative Method\n (Kurakin et al. 2016) when rand_init is set to 0. or the\n Madry et al. (2017) method when rand_minmax is larger than 0.\n Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf\n Paper link (Madry et al. 2017): https://arxiv.org/pdf... |
Please provide a description of the function:def clip_image(image, clip_min, clip_max):
return np.minimum(np.maximum(clip_min, image), clip_max) | [
" Clip an image, or an image batch, with upper and lower threshold. "
] |
Please provide a description of the function:def compute_distance(x_ori, x_pert, constraint='l2'):
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'linf':
dist = np.max(abs(x_ori - x_pert))
return dist | [
" Compute the distance between two images. "
] |
Please provide a description of the function:def approximate_gradient(decision_function, sample, num_evals,
delta, constraint, shape, clip_min, clip_max):
# Generate random vectors.
noise_shape = [num_evals] + list(shape)
if constraint == 'l2':
rv = np.random.randn(*noise_shape)
... | [
" Gradient direction estimation "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.