Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
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'
from cleverhans.utils_tf import jacobian_graph
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
# Define graph wrt to this input placeholder
logits = self.model.get_logits(x)
self.nb_classes = logits.get_shape().as_list()[-1]
assert self.nb_candidate <= self.nb_classes, \
'nb_candidate should not be greater than nb_classes'
preds = tf.reshape(
tf.nn.top_k(logits, k=self.nb_candidate)[0],
[-1, self.nb_candidate])
# grads will be the shape [batch_size, nb_candidate, image_size]
grads = tf.stack(jacobian_graph(preds, x, self.nb_candidate), axis=1)
# Define graph
def deepfool_wrap(x_val):
return deepfool_batch(self.sess, x, preds, logits, grads, x_val,
self.nb_candidate, self.overshoot,
self.max_iter, self.clip_min, self.clip_max,
self.nb_classes)
wrap = tf.py_func(deepfool_wrap, [x], self.tf_dtype)
wrap.set_shape(x.get_shape())
return wrap
|
[
"\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 ",
"deepfool function for py_func"
] |
Please provide a description of the function:def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
self.nb_candidate = nb_candidate
self.overshoot = overshoot
self.max_iter = max_iter
self.clip_min = clip_min
self.clip_max = clip_max
if len(kwargs.keys()) > 0:
warnings.warn("kwargs is unused and will be removed on or after "
"2019-04-26.")
return True
|
[
"\n :param nb_candidate: The number of classes to test against, i.e.,\n deepfool only consider nb_candidate classes when\n attacking(thus accelerate speed). The nb_candidate\n classes are chosen according to the prediction\n confidence during implementation.\n :param overshoot: A termination criterion to prevent vanishing updates\n :param max_iter: Maximum number of iteration for deepfool\n :param clip_min: Minimum component value for clipping\n :param clip_max: Maximum component value for clipping\n "
] |
Please provide a description of the function:def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
# Generate random name in order to avoid conflicts with inbuilt names
rnd_name = 'PyFuncGrad-' + '%0x' % getrandbits(30 * 4)
# Register Tensorflow Gradient
tf.RegisterGradient(rnd_name)(grad_func)
# Get current graph
g = tf.get_default_graph()
# Add gradient override map
with g.gradient_override_map({"PyFunc": rnd_name,
"PyFuncStateless": rnd_name}):
return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
|
[
"\n PyFunc defined as given by Tensorflow\n :param func: Custom Function\n :param inp: Function Inputs\n :param Tout: Ouput Type of out Custom Function\n :param stateful: Calculate Gradients when stateful is True\n :param name: Name of the PyFunction\n :param grad: Custom Gradient Function\n :return:\n "
] |
Please provide a description of the function:def convert_pytorch_model_to_tf(model, out_dims=None):
warnings.warn("convert_pytorch_model_to_tf is deprecated, switch to"
+ " dedicated PyTorch support provided by CleverHans v4.")
torch_state = {
'logits': None,
'x': None,
}
if not out_dims:
out_dims = list(model.modules())[-1].out_features
def _fprop_fn(x_np):
x_tensor = torch.Tensor(x_np)
if torch.cuda.is_available():
x_tensor = x_tensor.cuda()
torch_state['x'] = Variable(x_tensor, requires_grad=True)
torch_state['logits'] = model(torch_state['x'])
return torch_state['logits'].data.cpu().numpy()
def _bprop_fn(x_np, grads_in_np):
_fprop_fn(x_np)
grads_in_tensor = torch.Tensor(grads_in_np)
if torch.cuda.is_available():
grads_in_tensor = grads_in_tensor.cuda()
# Run our backprop through our logits to our xs
loss = torch.sum(torch_state['logits'] * grads_in_tensor)
loss.backward()
return torch_state['x'].grad.cpu().data.numpy()
def _tf_gradient_fn(op, grads_in):
return tf.py_func(_bprop_fn, [op.inputs[0], grads_in],
Tout=[tf.float32])
def tf_model_fn(x_op):
out = _py_func_with_gradient(_fprop_fn, [x_op], Tout=[tf.float32],
stateful=True,
grad_func=_tf_gradient_fn)[0]
out.set_shape([None, out_dims])
return out
return tf_model_fn
|
[
"\n Convert a pytorch model into a tensorflow op that allows backprop\n :param model: A pytorch nn.Module object\n :param out_dims: The number of output dimensions (classes) for the model\n :return: A model function that maps an input (tf.Tensor) to the\n output of the model (tf.Tensor)\n ",
"TODO: write this",
"TODO: write this",
"TODO: write this",
"TODO: write this"
] |
Please provide a description of the function:def clip_eta(eta, ord, eps):
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.device)
reduc_ind = list(range(1, len(eta.size())))
if ord == np.inf:
eta = torch.clamp(eta, -eps, eps)
else:
if ord == 1:
# TODO
# raise NotImplementedError("L1 clip is not implemented.")
norm = torch.max(
avoid_zero_div,
torch.sum(torch.abs(eta), dim=reduc_ind, keepdim=True)
)
elif ord == 2:
norm = torch.sqrt(torch.max(
avoid_zero_div,
torch.sum(eta ** 2, dim=reduc_ind, keepdim=True)
))
factor = torch.min(
torch.tensor(1., dtype=eta.dtype, device=eta.device),
eps / norm
)
eta *= factor
return eta
|
[
"\n PyTorch implementation of the clip_eta in utils_tf.\n\n :param eta: Tensor\n :param ord: np.inf, 1, or 2\n :param eps: float\n "
] |
Please provide a description of the function:def get_or_guess_labels(model, x, **kwargs):
if 'y' in kwargs and 'y_target' in kwargs:
raise ValueError("Can not set both 'y' and 'y_target'.")
if 'y' in kwargs:
labels = kwargs['y']
elif 'y_target' in kwargs and kwargs['y_target'] is not None:
labels = kwargs['y_target']
else:
_, labels = torch.max(model(x), 1)
return labels
|
[
"\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 attack and use that as the label.\n Otherwise, use the model's prediction as the label and perform an\n untargeted attack.\n\n :param model: PyTorch model. Do not add a softmax gate to the output.\n :param x: Tensor, shape (N, d_1, ...).\n :param y: (optional) Tensor, shape (N).\n :param y_target: (optional) Tensor, shape (N).\n "
] |
Please provide a description of the function:def optimize_linear(grad, eps, ord=np.inf):
red_ind = list(range(1, len(grad.size())))
avoid_zero_div = torch.tensor(1e-12, dtype=grad.dtype, device=grad.device)
if ord == np.inf:
# Take sign of gradient
optimal_perturbation = torch.sign(grad)
elif ord == 1:
abs_grad = torch.abs(grad)
sign = torch.sign(grad)
red_ind = list(range(1, len(grad.size())))
abs_grad = torch.abs(grad)
ori_shape = [1]*len(grad.size())
ori_shape[0] = grad.size(0)
max_abs_grad, _ = torch.max(abs_grad.view(grad.size(0), -1), 1)
max_mask = abs_grad.eq(max_abs_grad.view(ori_shape)).to(torch.float)
num_ties = max_mask
for red_scalar in red_ind:
num_ties = torch.sum(num_ties, red_scalar, keepdim=True)
optimal_perturbation = sign * max_mask / num_ties
# TODO integrate below to a test file
# check that the optimal perturbations have been correctly computed
opt_pert_norm = optimal_perturbation.abs().sum(dim=red_ind)
assert torch.all(opt_pert_norm == torch.ones_like(opt_pert_norm))
elif ord == 2:
square = torch.max(
avoid_zero_div,
torch.sum(grad ** 2, red_ind, keepdim=True)
)
optimal_perturbation = grad / torch.sqrt(square)
# TODO integrate below to a test file
# check that the optimal perturbations have been correctly computed
opt_pert_norm = optimal_perturbation.pow(2).sum(dim=red_ind, keepdim=True).sqrt()
one_mask = (square <= avoid_zero_div).to(torch.float) * opt_pert_norm + \
(square > avoid_zero_div).to(torch.float)
assert torch.allclose(opt_pert_norm, one_mask, rtol=1e-05, atol=1e-08)
else:
raise NotImplementedError("Only L-inf, L1 and L2 norms are "
"currently implemented.")
# Scale perturbation to be the solution for the norm=eps rather than
# norm=1 problem
scaled_perturbation = eps * optimal_perturbation
return scaled_perturbation
|
[
"\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: Tensor, shape (N, d_1, ...). Batch of gradients\n :param eps: float. Scalar specifying size of constraint region\n :param ord: np.inf, 1, or 2. Order of norm constraint.\n :returns: Tensor, shape (N, d_1, ...). Optimal perturbation\n "
] |
Please provide a description of the function:def parse_params(self,
y=None,
y_target=None,
beta=1e-2,
decision_rule='EN',
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
max_iterations=1000,
abort_early=False,
initial_const=1e-3,
clip_min=0,
clip_max=1):
# ignore the y and y_target argument
self.beta = beta
self.decision_rule = decision_rule
self.batch_size = batch_size
self.confidence = confidence
self.learning_rate = learning_rate
self.binary_search_steps = binary_search_steps
self.max_iterations = max_iterations
self.abort_early = abort_early
self.initial_const = initial_const
self.clip_min = clip_min
self.clip_max = clip_max
|
[
"\n :param y: (optional) A tensor with the true labels for an untargeted\n attack. If None (and y_target is None) then use the\n original labels the classifier assigns.\n :param y_target: (optional) A tensor with the target labels for a\n targeted attack.\n :param beta: Trades off L2 distortion with L1 distortion: higher\n produces examples with lower L1 distortion, at the\n cost of higher L2 (and typically Linf) distortion\n :param decision_rule: EN or L1. Select final adversarial example from\n all successful examples based on the least\n elastic-net or L1 distortion criterion.\n :param confidence: Confidence of adversarial examples: higher produces\n examples with larger l2 distortion, but more\n strongly classified as adversarial.\n :param batch_size: Number of attacks to run simultaneously.\n :param learning_rate: The learning rate for the attack algorithm.\n Smaller values produce better results but are\n slower to converge.\n :param binary_search_steps: The number of times we perform binary\n search to find the optimal tradeoff-\n constant between norm of the perturbation\n and confidence of the classification. Set\n 'initial_const' to a large value and fix\n this param to 1 for speed.\n :param max_iterations: The maximum number of iterations. Setting this\n to a larger value will produce lower distortion\n results. Using only a few iterations requires\n a larger learning rate, and will produce larger\n distortion results.\n :param abort_early: If true, allows early abort when the total\n loss starts to increase (greatly speeds up attack,\n but hurts performance, particularly on ImageNet)\n :param initial_const: The initial tradeoff-constant to use to tune the\n relative importance of size of the perturbation\n and confidence of classification.\n If binary_search_steps is large, the initial\n constant is not important. A smaller value of\n this constant gives lower distortion results.\n For computational efficiency, fix\n binary_search_steps to 1 and set this param\n to a large value.\n :param clip_min: (optional float) Minimum input component value\n :param clip_max: (optional float) Maximum input component value\n "
] |
Please provide a description of the function:def attack(self, imgs, targets):
batch_size = self.batch_size
r = []
for i in range(0, len(imgs) // batch_size):
_logger.debug(
("Running EAD attack on instance %s of %s",
i * batch_size, len(imgs)))
r.extend(
self.attack_batch(
imgs[i * batch_size:(i + 1) * batch_size],
targets[i * batch_size:(i + 1) * batch_size]))
if len(imgs) % batch_size != 0:
last_elements = len(imgs) - (len(imgs) % batch_size)
_logger.debug(
("Running EAD attack on instance %s of %s",
last_elements, len(imgs)))
temp_imgs = np.zeros((batch_size, ) + imgs.shape[2:])
temp_targets = np.zeros((batch_size, ) + targets.shape[2:])
temp_imgs[:(len(imgs) % batch_size)] = imgs[last_elements:]
temp_targets[:(len(imgs) % batch_size)] = targets[last_elements:]
temp_data = self.attack_batch(temp_imgs, temp_targets)
r.extend(temp_data[:(len(imgs) % batch_size)],
targets[last_elements:])
return np.array(r)
|
[
"\n Perform the EAD attack on the given instance for the given targets.\n\n If self.targeted is true, then the targets represents the target labels\n If self.targeted is false, then targets are the original class labels\n "
] |
Please provide a description of the function:def print_in_box(text):
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('')
|
[
"\n Prints `text` surrounded by a box made of *s\n "
] |
Please provide a description of the function:def main(args):
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_temp_dir = True
validator = submission_validator_lib.SubmissionValidator(temp_dir,
args.use_gpu)
if validator.validate_submission(args.submission_filename,
args.submission_type):
print_in_box('Submission is VALID!')
else:
print_in_box('Submission is INVALID, see log messages for details')
if delete_temp_dir:
logging.info('Deleting temporary directory: %s', temp_dir)
subprocess.call(['rm', '-rf', temp_dir])
|
[
"\n Validates the submission.\n "
] |
Please provide a description of the function:def main(argv=None):
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_set,
report_path=FLAGS.report_path,
mc_batch_size=FLAGS.mc_batch_size,
nb_iter=FLAGS.nb_iter,
base_eps_iter=FLAGS.base_eps_iter,
batch_size=FLAGS.batch_size,
save_advx=FLAGS.save_advx)
|
[
"\n Make a confidence report and save it to disk.\n "
] |
Please provide a description of the function:def make_confidence_report_spsa(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,
report_path=REPORT_PATH,
nb_iter=NB_ITER_SPSA,
spsa_samples=SPSA_SAMPLES,
spsa_iters=SPSA.DEFAULT_SPSA_ITERS):
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
# Set logging level to see debug information
set_log_level(logging.INFO)
# Create TF session
sess = tf.Session()
if report_path is None:
assert filepath.endswith('.joblib')
report_path = filepath[:-len('.joblib')] + "_spsa_report.joblib"
with sess.as_default():
model = load(filepath)
assert len(model.get_params()) > 0
factory = model.dataset_factory
factory.kwargs['train_start'] = train_start
factory.kwargs['train_end'] = train_end
factory.kwargs['test_start'] = test_start
factory.kwargs['test_end'] = test_end
dataset = factory()
center = dataset.kwargs['center']
center = np.float32(center)
max_val = dataset.kwargs['max_val']
max_val = np.float32(max_val)
value_range = max_val * (1. + center)
min_value = np.float32(0. - center * max_val)
if 'CIFAR' in str(factory.cls):
base_eps = 8. / 255.
elif 'MNIST' in str(factory.cls):
base_eps = .3
else:
raise NotImplementedError(str(factory.cls))
eps = np.float32(base_eps * value_range)
clip_min = min_value
clip_max = max_val
x_data, y_data = dataset.get_set(which_set)
nb_classes = dataset.NB_CLASSES
spsa_max_confidence_recipe(sess, model, x_data, y_data, nb_classes, eps,
clip_min, clip_max, nb_iter, report_path,
spsa_samples=spsa_samples,
spsa_iters=spsa_iters,
eval_batch_size=batch_size)
|
[
"\n Load a saved model, gather its predictions, and save a confidence report.\n\n\n This function works by running a single MaxConfidence attack on each example,\n using SPSA as the underyling optimizer.\n This is not intended to be a strong generic attack.\n It is intended to be a test to uncover gradient masking.\n\n :param filepath: path to model to evaluate\n :param train_start: index of first training set example to use\n :param train_end: index of last training set example to use\n :param test_start: index of first test set example to use\n :param test_end: index of last test set example to use\n :param batch_size: size of evaluation batches\n :param which_set: 'train' or 'test'\n :param nb_iter: Number of iterations of PGD to run per class\n :param spsa_samples: Number of samples for SPSA\n "
] |
Please provide a description of the function:def main(argv=None):
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report_spsa(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end,
which_set=FLAGS.which_set,
report_path=FLAGS.report_path,
nb_iter=FLAGS.nb_iter,
batch_size=FLAGS.batch_size,
spsa_samples=FLAGS.spsa_samples,
spsa_iters=FLAGS.spsa_iters)
|
[
"\n Make a confidence report and save it to disk.\n "
] |
Please provide a description of the function:def attack(self, x, y_p, **kwargs):
inputs = []
outputs = []
# Create the initial random perturbation
device_name = '/gpu:0'
self.model.set_device(device_name)
with tf.device(device_name):
with tf.variable_scope('init_rand'):
if self.rand_init:
eta = tf.random_uniform(tf.shape(x), -self.eps, self.eps)
eta = clip_eta(eta, self.ord, self.eps)
eta = tf.stop_gradient(eta)
else:
eta = tf.zeros_like(x)
# TODO: Break the graph only nGPU times instead of nb_iter times.
# The current implementation by the time an adversarial example is
# used for training, the weights of the model have changed nb_iter
# times. This can cause slower convergence compared to the single GPU
# adversarial training.
for i in range(self.nb_iter):
# Create the graph for i'th step of attack
inputs += [OrderedDict()]
outputs += [OrderedDict()]
device_name = x.device
self.model.set_device(device_name)
with tf.device(device_name):
with tf.variable_scope('step%d' % i):
if i > 0:
# Clone the variables to separate the graph of 2 GPUs
x = clone_variable('x', x)
y_p = clone_variable('y_p', y_p)
eta = clone_variable('eta', eta)
inputs[i]['x'] = x
inputs[i]['y_p'] = y_p
outputs[i]['x'] = x
outputs[i]['y_p'] = y_p
inputs[i]['eta'] = eta
eta = self.attack_single_step(x, eta, y_p)
if i < self.nb_iter-1:
outputs[i]['eta'] = eta
else:
# adv_x, not eta is the output of the last step
adv_x = x + eta
if (self.clip_min is not None and self.clip_max is not None):
adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)
adv_x = tf.stop_gradient(adv_x, name='adv_x')
outputs[i]['adv_x'] = adv_x
return inputs, outputs
|
[
"\n This method creates a symoblic graph of the MadryEtAl attack on\n multiple GPUs. The graph is created on the first n GPUs.\n\n Stop gradient is needed to get the speed-up. This prevents us from\n being able to back-prop through the attack.\n\n :param x: A tensor with the input image.\n :param y_p: Ground truth label or predicted label.\n :return: Two lists containing the input and output tensors of each GPU.\n "
] |
Please provide a description of the function:def generate_np(self, x_val, **kwargs):
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):
# x is a special placeholder we always want to have
with tf.device('/gpu:0'):
x = tf.placeholder(tf.float32, shape=x_val.shape, name='x')
inputs, outputs = self.generate(x, **kwargs)
from runner import RunnerMultiGPU
runner = RunnerMultiGPU(inputs, outputs, sess=self.sess)
self.graphs[hash_key] = runner
runner = self.graphs[hash_key]
feed_dict = {'x': x_val}
for name in feedable:
feed_dict[name] = feedable[name]
fvals = runner.run(feed_dict)
while not runner.is_finished():
fvals = runner.run()
return fvals['adv_x']
|
[
"\n Facilitates testing this attack.\n "
] |
Please provide a description of the function:def parse_params(self, ngpu=1, **kwargs):
return_status = super(MadryEtAlMultiGPU, self).parse_params(**kwargs)
self.ngpu = ngpu
return return_status
|
[
"\n Take in a dictionary of parameters and applies attack-specific checks\n before saving them as attributes.\n\n Attack-specific parameters:\n :param ngpu: (required int) the number of GPUs available.\n :param kwargs: A dictionary of parameters for MadryEtAl attack.\n "
] |
Please provide a description of the function:def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
_check_x(x)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueError("Number of input examples and labels do not match.")
factory = _CorrectFactory(model, attack, attack_params)
correct, = batch_eval_multi_worker(sess, factory, [x, y],
batch_size=batch_size, devices=devices,
feed=feed)
return correct.mean()
|
[
"\n Compute the accuracy of a TF model on some data\n :param sess: TF session to use when training the graph\n :param model: cleverhans.model.Model instance\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing example labels (e.g. MNIST().y_test )\n :param batch_size: Number of examples to use in a single evaluation batch.\n If not specified, this function will use a reasonable guess and\n may run out of memory.\n When choosing the batch size, keep in mind that the batch will\n be divided up evenly among available devices. If you can fit 128\n examples in memory on one GPU and you have 8 GPUs, you probably\n want to use a batch size of 1024 (unless a different batch size\n runs faster with the ops you are using, etc.)\n :param devices: An optional list of string device names to use.\n If not specified, this function will use all visible GPUs.\n :param feed: An optional dictionary that is appended to the feeding\n dictionary before the session runs. Can be used to feed\n the learning phase of a Keras model for instance.\n :param attack: cleverhans.attack.Attack\n Optional. If no attack specified, evaluates the model on clean data.\n If attack is specified, evaluates the model on adversarial examples\n created by the attack.\n :param attack_params: dictionary\n If attack is specified, this dictionary is passed to attack.generate\n as keyword arguments.\n :return: a float with the accuracy value\n "
] |
Please provide a description of the function:def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
_check_x(x)
inputs = [x]
if attack is not None:
inputs.append(y)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueError("Number of input examples and labels do not match.")
factory = _ClassAndProbFactory(model, attack, attack_params)
out = batch_eval_multi_worker(sess, factory, inputs, batch_size=batch_size,
devices=devices, feed=feed)
classes, confidence = out
assert classes.shape == (x.shape[0],)
assert confidence.shape == (x.shape[0],)
min_confidence = confidence.min()
if min_confidence < 0.:
raise ValueError("Model does not return valid probabilities: " +
str(min_confidence))
max_confidence = confidence.max()
if max_confidence > 1.:
raise ValueError("Model does not return valid probablities: " +
str(max_confidence))
assert confidence.min() >= 0., confidence.min()
return out
|
[
"\n Return the model's classification of the input data, and the confidence\n (probability) assigned to each example.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing true labels\n (Needed only if using an attack that avoids these labels)\n :param batch_size: Number of examples to use in a single evaluation batch.\n If not specified, this function will use a reasonable guess and\n may run out of memory.\n When choosing the batch size, keep in mind that the batch will\n be divided up evenly among available devices. If you can fit 128\n examples in memory on one GPU and you have 8 GPUs, you probably\n want to use a batch size of 1024 (unless a different batch size\n runs faster with the ops you are using, etc.)\n :param devices: An optional list of string device names to use.\n If not specified, this function will use all visible GPUs.\n :param feed: An optional dictionary that is appended to the feeding\n dictionary before the session runs. Can be used to feed\n the learning phase of a Keras model for instance.\n :param attack: cleverhans.attack.Attack\n Optional. If no attack specified, evaluates the model on clean data.\n If attack is specified, evaluates the model on adversarial examples\n created by the attack.\n :param attack_params: dictionary\n If attack is specified, this dictionary is passed to attack.generate\n as keyword arguments.\n :return:\n an ndarray of ints indicating the class assigned to each example\n an ndarray of probabilities assigned to the prediction for each example\n "
] |
Please provide a description of the function:def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
_check_x(x)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueError("Number of input examples and labels do not match.")
factory = _CorrectAndProbFactory(model, attack, attack_params)
out = batch_eval_multi_worker(sess, factory, [x, y], batch_size=batch_size,
devices=devices, feed=feed)
correctness, confidence = out
assert correctness.shape == (x.shape[0],)
assert confidence.shape == (x.shape[0],)
min_confidence = confidence.min()
if min_confidence < 0.:
raise ValueError("Model does not return valid probabilities: " +
str(min_confidence))
max_confidence = confidence.max()
if max_confidence > 1.:
raise ValueError("Model does not return valid probablities: " +
str(max_confidence))
assert confidence.min() >= 0., confidence.min()
return out
|
[
"\n Report whether the model is correct and its confidence on each example in\n a dataset.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing example labels (e.g. MNIST().y_test )\n :param batch_size: Number of examples to use in a single evaluation batch.\n If not specified, this function will use a reasonable guess and\n may run out of memory.\n When choosing the batch size, keep in mind that the batch will\n be divided up evenly among available devices. If you can fit 128\n examples in memory on one GPU and you have 8 GPUs, you probably\n want to use a batch size of 1024 (unless a different batch size\n runs faster with the ops you are using, etc.)\n :param devices: An optional list of string device names to use.\n If not specified, this function will use all visible GPUs.\n :param feed: An optional dictionary that is appended to the feeding\n dictionary before the session runs. Can be used to feed\n the learning phase of a Keras model for instance.\n :param attack: cleverhans.attack.Attack\n Optional. If no attack specified, evaluates the model on clean data.\n If attack is specified, evaluates the model on adversarial examples\n created by the attack.\n :param attack_params: dictionary\n If attack is specified, this dictionary is passed to attack.generate\n as keyword arguments.\n :return:\n an ndarray of bools indicating whether each example is correct\n an ndarray of probabilities assigned to the prediction for each example\n "
] |
Please provide a description of the function:def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
_check_x(x)
_check_y(y)
factory = _AttackFactory(model, attack, attack_params, pass_y)
out, = batch_eval_multi_worker(sess, factory, [x, y], batch_size=batch_size,
devices=devices, feed=feed)
return out
|
[
"\n Run attack on every example in a dataset.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing example labels (e.g. MNIST().y_test )\n :param attack: cleverhans.attack.Attack\n :param attack_params: dictionary\n passed to attack.generate as keyword arguments.\n :param batch_size: Number of examples to use in a single evaluation batch.\n If not specified, this function will use a reasonable guess and\n may run out of memory.\n When choosing the batch size, keep in mind that the batch will\n be divided up evenly among available devices. If you can fit 128\n examples in memory on one GPU and you have 8 GPUs, you probably\n want to use a batch size of 1024 (unless a different batch size\n runs faster with the ops you are using, etc.)\n :param devices: An optional list of string device names to use.\n If not specified, this function will use all visible GPUs.\n :param feed: An optional dictionary that is appended to the feeding\n dictionary before the session runs. Can be used to feed\n the learning phase of a Keras model for instance.\n :param pass_y: bool. If true pass 'y' to `attack.generate`\n :return:\n an ndarray of bools indicating whether each example is correct\n an ndarray of probabilities assigned to the prediction for each example\n "
] |
Please provide a description of the function:def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
canary.run_canary()
global _batch_eval_multi_worker_cache
devices = infer_devices(devices)
if batch_size is None:
# For big models this might result in OOM and then the user
# should just specify batch_size
batch_size = len(devices) * DEFAULT_EXAMPLES_PER_DEVICE
n = len(numpy_inputs)
assert n > 0
m = numpy_inputs[0].shape[0]
for i in range(1, n):
m_i = numpy_inputs[i].shape[0]
if m != m_i:
raise ValueError("All of numpy_inputs must have the same number of examples, but the first one has " + str(m)
+ " examples and input " + str(i) + " has " + str(m_i) + "examples.")
out = []
replicated_tf_inputs = []
replicated_tf_outputs = []
p = None
num_devices = len(devices)
assert batch_size % num_devices == 0
device_batch_size = batch_size // num_devices
cache_key = (graph_factory, tuple(devices))
if cache_key in _batch_eval_multi_worker_cache:
# Retrieve graph for multi-GPU inference from cache.
# This avoids adding tf ops to the graph
packed = _batch_eval_multi_worker_cache[cache_key]
replicated_tf_inputs, replicated_tf_outputs = packed
p = len(replicated_tf_outputs[0])
assert p > 0
else:
# This graph has not been built before.
# Build it now.
for device in devices:
with tf.device(device):
tf_inputs, tf_outputs = graph_factory()
assert len(tf_inputs) == n
if p is None:
p = len(tf_outputs)
assert p > 0
else:
assert len(tf_outputs) == p
replicated_tf_inputs.append(tf_inputs)
replicated_tf_outputs.append(tf_outputs)
del tf_inputs
del tf_outputs
# Store the result in the cache
packed = replicated_tf_inputs, replicated_tf_outputs
_batch_eval_multi_worker_cache[cache_key] = packed
for _ in range(p):
out.append([])
flat_tf_outputs = []
for output in range(p):
for dev_idx in range(num_devices):
flat_tf_outputs.append(replicated_tf_outputs[dev_idx][output])
# pad data to have # examples be multiple of batch size
# we discard the excess later
num_batches = int(np.ceil(float(m) / batch_size))
needed_m = num_batches * batch_size
excess = needed_m - m
if excess > m:
raise NotImplementedError(("Your batch size (%(batch_size)d) is bigger"
" than the dataset (%(m)d), this function is "
"probably overkill.") % locals())
def pad(array):
if excess > 0:
array = np.concatenate((array, array[:excess]), axis=0)
return array
numpy_inputs = [pad(numpy_input) for numpy_input in numpy_inputs]
orig_m = m
m = needed_m
for start in range(0, m, batch_size):
batch = start // batch_size
if batch % 100 == 0 and batch > 0:
_logger.debug("Batch " + str(batch))
# Compute batch start and end indices
end = start + batch_size
numpy_input_batches = [numpy_input[start:end]
for numpy_input in numpy_inputs]
feed_dict = {}
for dev_idx, tf_inputs in enumerate(replicated_tf_inputs):
for tf_input, numpy_input in zip(tf_inputs, numpy_input_batches):
dev_start = dev_idx * device_batch_size
dev_end = (dev_idx + 1) * device_batch_size
value = numpy_input[dev_start:dev_end]
assert value.shape[0] == device_batch_size
feed_dict[tf_input] = value
if feed is not None:
feed_dict.update(feed)
flat_output_batches = sess.run(flat_tf_outputs, feed_dict=feed_dict)
for e in flat_output_batches:
assert e.shape[0] == device_batch_size, e.shape
output_batches = []
for output in range(p):
o_start = output * num_devices
o_end = (output + 1) * num_devices
device_values = flat_output_batches[o_start:o_end]
assert len(device_values) == num_devices
output_batches.append(device_values)
for out_elem, device_values in zip(out, output_batches):
assert len(device_values) == num_devices, (len(device_values),
num_devices)
for device_value in device_values:
assert device_value.shape[0] == device_batch_size
out_elem.extend(device_values)
out = [np.concatenate(x, axis=0) for x in out]
for e in out:
assert e.shape[0] == m, e.shape
# Trim off the examples we used to pad up to batch size
out = [e[:orig_m] for e in out]
assert len(out) == p, (len(out), p)
return out
|
[
"\n Generic computation engine for evaluating an expression across a whole\n dataset, divided into batches.\n\n This function assumes that the work can be parallelized with one worker\n device handling one batch of data. If you need multiple devices per\n batch, use `batch_eval`.\n\n The tensorflow graph for multiple workers is large, so the first few\n runs of the graph will be very slow. If you expect to run the graph\n few times (few calls to `batch_eval_multi_worker` that each run few\n batches) the startup cost might dominate the runtime, and it might be\n preferable to use the single worker `batch_eval` just because its\n startup cost will be lower.\n\n :param sess: tensorflow Session\n :param graph_factory: callable\n When called, returns (tf_inputs, tf_outputs) where:\n tf_inputs is a list of placeholders to feed from the dataset\n tf_outputs is a list of tf tensors to calculate\n Example: tf_inputs is [x, y] placeholders, tf_outputs is [accuracy].\n This factory must make new tensors when called, rather than, e.g.\n handing out a reference to existing tensors.\n This factory must make exactly equivalent expressions every time\n it is called, otherwise the results of `batch_eval` will vary\n depending on how work is distributed to devices.\n This factory must respect \"with tf.device()\" context managers\n that are active when it is called, otherwise work will not be\n distributed to devices correctly.\n :param numpy_inputs:\n A list of numpy arrays defining the dataset to be evaluated.\n The list should have the same length as tf_inputs.\n Each array should have the same number of examples (shape[0]).\n Example: numpy_inputs is [MNIST().x_test, MNIST().y_test]\n :param batch_size: Number of examples to use in a single evaluation batch.\n If not specified, this function will use a reasonable guess and\n may run out of memory.\n When choosing the batch size, keep in mind that the batch will\n be divided up evenly among available devices. If you can fit 128\n examples in memory on one GPU and you have 8 GPUs, you probably\n want to use a batch size of 1024 (unless a different batch size\n runs faster with the ops you are using, etc.)\n :param devices: List of devices to run on. If unspecified, uses all\n available GPUs if any GPUS are available, otherwise uses CPUs.\n :param feed: An optional dictionary that is appended to the feeding\n dictionary before the session runs. Can be used to feed\n the learning phase of a Keras model for instance.\n :returns: List of numpy arrays corresponding to the outputs produced by\n the graph_factory\n ",
"Pads an array with replicated examples to have `excess` more entries"
] |
Please provide a description of the function:def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
if args is not None:
warnings.warn("`args` is deprecated and will be removed on or "
"after 2019-03-09. Pass `batch_size` directly.")
if "batch_size" in args:
assert batch_size is None
batch_size = args["batch_size"]
if batch_size is None:
batch_size = DEFAULT_EXAMPLES_PER_DEVICE
n = len(numpy_inputs)
assert n > 0
assert n == len(tf_inputs)
m = numpy_inputs[0].shape[0]
for i in range(1, n):
assert numpy_inputs[i].shape[0] == m
out = []
for _ in tf_outputs:
out.append([])
for start in range(0, m, batch_size):
batch = start // batch_size
if batch % 100 == 0 and batch > 0:
_logger.debug("Batch " + str(batch))
# Compute batch start and end indices
start = batch * batch_size
end = start + batch_size
numpy_input_batches = [numpy_input[start:end]
for numpy_input in numpy_inputs]
cur_batch_size = numpy_input_batches[0].shape[0]
assert cur_batch_size <= batch_size
for e in numpy_input_batches:
assert e.shape[0] == cur_batch_size
feed_dict = dict(zip(tf_inputs, numpy_input_batches))
if feed is not None:
feed_dict.update(feed)
numpy_output_batches = sess.run(tf_outputs, feed_dict=feed_dict)
for e in numpy_output_batches:
assert e.shape[0] == cur_batch_size, e.shape
for out_elem, numpy_output_batch in zip(out, numpy_output_batches):
out_elem.append(numpy_output_batch)
out = [np.concatenate(x, axis=0) for x in out]
for e in out:
assert e.shape[0] == m, e.shape
return out
|
[
"\n A helper function that computes a tensor on numpy inputs by batches.\n This version uses exactly the tensorflow graph constructed by the\n caller, so the caller can place specific ops on specific devices\n to implement model parallelism.\n Most users probably prefer `batch_eval_multi_worker` which maps\n a single-device expression to multiple devices in order to evaluate\n faster by parallelizing across data.\n\n :param sess: tf Session to use\n :param tf_inputs: list of tf Placeholders to feed from the dataset\n :param tf_outputs: list of tf tensors to calculate\n :param numpy_inputs: list of numpy arrays defining the dataset\n :param batch_size: int, batch size to use for evaluation\n If not specified, this function will try to guess the batch size,\n but might get an out of memory error or run the model with an\n unsupported batch size, etc.\n :param feed: An optional dictionary that is appended to the feeding\n dictionary before the session runs. Can be used to feed\n the learning phase of a Keras model for instance.\n :param args: dict or argparse `Namespace` object.\n Deprecated and included only for backwards compatibility.\n Should contain `batch_size`\n "
] |
Please provide a description of the function:def _check_y(y):
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y)))
|
[
"\n Makes sure a `y` argument is a vliad numpy dataset.\n "
] |
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:
images[idx, :, :, :] = imread(f, mode='RGB').astype(np.float) / 255.0
filenames.append(os.path.basename(filepath))
idx += 1
if idx == batch_size:
yield filenames, images
filenames = []
images = np.zeros(batch_shape)
idx = 0
if idx > 0:
yield filenames, images
|
[
"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 Length of this list could be less than batch_size, in this case only\n first few images of the result are elements of the minibatch.\n images: array with all images from this batch\n "
] |
Please provide a description of the function:def main(_):
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir)
|
[
"Run the sample attack"
] |
Please provide a description of the function:def preprocess_batch(images_batch, preproc_func=None):
if preproc_func is None:
return images_batch
with tf.variable_scope('preprocess'):
images_list = tf.split(images_batch, int(images_batch.shape[0]))
result_list = []
for img in images_list:
reshaped_img = tf.reshape(img, img.shape[1:])
processed_img = preproc_func(reshaped_img)
result_list.append(tf.expand_dims(processed_img, axis=0))
result_images = tf.concat(result_list, axis=0)
return result_images
|
[
"\n Creates a preprocessing graph for a batch given a function that processes\n a single image.\n\n :param images_batch: A tensor for an image batch.\n :param preproc_func: (optional function) A function that takes in a\n tensor and returns a preprocessed input.\n "
] |
Please provide a description of the function:def get_logits(self, x, **kwargs):
outputs = self.fprop(x, **kwargs)
if self.O_LOGITS in outputs:
return outputs[self.O_LOGITS]
raise NotImplementedError(str(type(self)) + "must implement `get_logits`"
" or must define a " + self.O_LOGITS +
" output in `fprop`")
|
[
"\n :param x: A symbolic representation (Tensor) of the network input\n :return: A symbolic representation (Tensor) of the output logits\n (i.e., the values fed as inputs to the softmax layer).\n "
] |
Please provide a description of the function:def get_predicted_class(self, x, **kwargs):
return tf.argmax(self.get_logits(x, **kwargs), axis=1)
|
[
"\n :param x: A symbolic representation (Tensor) of the network input\n :return: A symbolic representation (Tensor) of the predicted label\n "
] |
Please provide a description of the function:def get_probs(self, x, **kwargs):
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
output = d[self.O_PROBS]
min_prob = tf.reduce_min(output)
max_prob = tf.reduce_max(output)
asserts = [utils_tf.assert_greater_equal(min_prob,
tf.cast(0., min_prob.dtype)),
utils_tf.assert_less_equal(max_prob,
tf.cast(1., min_prob.dtype))]
with tf.control_dependencies(asserts):
output = tf.identity(output)
return output
elif self.O_LOGITS in d:
return tf.nn.softmax(logits=d[self.O_LOGITS])
else:
raise ValueError('Cannot find probs or logits.')
|
[
"\n :param x: A symbolic representation (Tensor) of the network input\n :return: A symbolic representation (Tensor) of the output\n probabilities (i.e., the output values produced by the softmax layer).\n "
] |
Please provide a description of the function:def get_params(self):
if hasattr(self, 'params'):
return list(self.params)
# Catch eager execution and assert function overload.
try:
if tf.executing_eagerly():
raise NotImplementedError("For Eager execution - get_params "
"must be overridden.")
except AttributeError:
pass
# For graph-based execution
scope_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
self.scope + "/")
if len(scope_vars) == 0:
self.make_params()
scope_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
self.scope + "/")
assert len(scope_vars) > 0
# Make sure no parameters have been added or removed
if hasattr(self, "num_params"):
if self.num_params != len(scope_vars):
print("Scope: ", self.scope)
print("Expected " + str(self.num_params) + " variables")
print("Got " + str(len(scope_vars)))
for var in scope_vars:
print("\t" + str(var))
assert False
else:
self.num_params = len(scope_vars)
return scope_vars
|
[
"\n Provides access to the model's parameters.\n :return: A list of all Variables defining the model parameters.\n "
] |
Please provide a description of the function:def make_params(self):
if self.needs_dummy_fprop:
if hasattr(self, "_dummy_input"):
return
self._dummy_input = self.make_input_placeholder()
self.fprop(self._dummy_input)
|
[
"\n Create all Variables to be returned later by get_params.\n By default this is a no-op.\n Models that need their fprop to be called for their params to be\n created can set `needs_dummy_fprop=True` in the constructor.\n "
] |
Please provide a description of the function:def get_layer(self, x, layer, **kwargs):
return self.fprop(x, **kwargs)[layer]
|
[
"Return a layer output.\n :param x: tensor, the input to the network.\n :param layer: str, the name of the layer to compute.\n :param **kwargs: dict, extra optional params to pass to self.fprop.\n :return: the content of layer `layer`\n "
] |
Please provide a description of the function:def plot_reliability_diagram(confidence, labels, filepath):
assert len(confidence.shape) == 2
assert len(labels.shape) == 1
assert confidence.shape[0] == labels.shape[0]
print('Saving reliability diagram at: ' + str(filepath))
if confidence.max() <= 1.:
# confidence array is output of softmax
bins_start = [b / 10. for b in xrange(0, 10)]
bins_end = [b / 10. for b in xrange(1, 11)]
bins_center = [(b + .5) / 10. for b in xrange(0, 10)]
preds_conf = np.max(confidence, axis=1)
preds_l = np.argmax(confidence, axis=1)
else:
raise ValueError('Confidence values go above 1.')
print(preds_conf.shape, preds_l.shape)
# Create var for reliability diagram
# Will contain mean accuracies for each bin
reliability_diag = []
num_points = [] # keeps the number of points in each bar
# Find average accuracy per confidence bin
for bin_start, bin_end in zip(bins_start, bins_end):
above = preds_conf >= bin_start
if bin_end == 1.:
below = preds_conf <= bin_end
else:
below = preds_conf < bin_end
mask = np.multiply(above, below)
num_points.append(np.sum(mask))
bin_mean_acc = max(0, np.mean(preds_l[mask] == labels[mask]))
reliability_diag.append(bin_mean_acc)
# Plot diagram
assert len(reliability_diag) == len(bins_center)
print(reliability_diag)
print(bins_center)
print(num_points)
fig, ax1 = plt.subplots()
_ = ax1.bar(bins_center, reliability_diag, width=.1, alpha=0.8)
plt.xlim([0, 1.])
ax1.set_ylim([0, 1.])
ax2 = ax1.twinx()
print(sum(num_points))
ax2.plot(bins_center, num_points, color='r', linestyle='-', linewidth=7.0)
ax2.set_ylabel('Number of points in the data', fontsize=16, color='r')
if len(np.argwhere(confidence[0] != 0.)) == 1:
# This is a DkNN diagram
ax1.set_xlabel('Prediction Credibility', fontsize=16)
else:
# This is a softmax diagram
ax1.set_xlabel('Prediction Confidence', fontsize=16)
ax1.set_ylabel('Prediction Accuracy', fontsize=16)
ax1.tick_params(axis='both', labelsize=14)
ax2.tick_params(axis='both', labelsize=14, colors='r')
fig.tight_layout()
plt.savefig(filepath, bbox_inches='tight')
|
[
"\n Takes in confidence values for predictions and correct\n labels for the data, plots a reliability diagram.\n :param confidence: nb_samples x nb_classes (e.g., output of softmax)\n :param labels: vector of nb_samples\n :param filepath: where to save the diagram\n :return:\n "
] |
Please provide a description of the function:def init_lsh(self):
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to be substracted before LSH).
self.centers = {}
for layer in self.layers:
assert self.nb_tables >= self.neighbors
# Normalize all the lenghts, since we care about the cosine similarity.
self.train_activations_lsh[layer] /= np.linalg.norm(
self.train_activations_lsh[layer], axis=1).reshape(-1, 1)
# Center the dataset and the queries: this improves the performance of LSH quite a bit.
center = np.mean(self.train_activations_lsh[layer], axis=0)
self.train_activations_lsh[layer] -= center
self.centers[layer] = center
# LSH parameters
params_cp = falconn.LSHConstructionParameters()
params_cp.dimension = len(self.train_activations_lsh[layer][1])
params_cp.lsh_family = falconn.LSHFamily.CrossPolytope
params_cp.distance_function = falconn.DistanceFunction.EuclideanSquared
params_cp.l = self.nb_tables
params_cp.num_rotations = 2 # for dense set it to 1; for sparse data set it to 2
params_cp.seed = 5721840
# we want to use all the available threads to set up
params_cp.num_setup_threads = 0
params_cp.storage_hash_table = falconn.StorageHashTable.BitPackedFlatHashTable
# we build 18-bit hashes so that each table has
# 2^18 bins; this is a good choice since 2^18 is of the same
# order of magnitude as the number of data points
falconn.compute_number_of_hash_functions(self.number_bits, params_cp)
print('Constructing the LSH table')
table = falconn.LSHIndex(params_cp)
table.setup(self.train_activations_lsh[layer])
# Parse test feature vectors and find k nearest neighbors
query_object = table.construct_query_object()
query_object.set_num_probes(self.nb_tables)
self.query_objects[layer] = query_object
|
[
"\n Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.\n "
] |
Please provide a description of the function:def find_train_knns(self, data_activations):
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to normalize and remove training data mean.
data_activations_layer = copy.copy(data_activations[layer])
nb_data = data_activations_layer.shape[0]
data_activations_layer /= np.linalg.norm(
data_activations_layer, axis=1).reshape(-1, 1)
data_activations_layer -= self.centers[layer]
# Use FALCONN to find indices of nearest neighbors in training data.
knns_ind[layer] = np.zeros(
(data_activations_layer.shape[0], self.neighbors), dtype=np.int32)
knn_errors = 0
for i in range(data_activations_layer.shape[0]):
query_res = self.query_objects[layer].find_k_nearest_neighbors(
data_activations_layer[i], self.neighbors)
try:
knns_ind[layer][i, :] = query_res
except: # pylint: disable-msg=W0702
knns_ind[layer][i, :len(query_res)] = query_res
knn_errors += knns_ind[layer].shape[1] - len(query_res)
# Find labels of neighbors found in the training data.
knns_labels[layer] = np.zeros((nb_data, self.neighbors), dtype=np.int32)
for data_id in range(nb_data):
knns_labels[layer][data_id, :] = self.train_labels[knns_ind[layer][data_id]]
return knns_ind, knns_labels
|
[
"\n Given a data_activation dictionary that contains a np array with activations for each layer,\n find the knns in the training data.\n "
] |
Please provide a description of the function:def nonconformity(self, knns_labels):
nb_data = knns_labels[self.layers[0]].shape[0]
knns_not_in_class = np.zeros((nb_data, self.nb_classes), dtype=np.int32)
for i in range(nb_data):
# Compute number of nearest neighbors per class
knns_in_class = np.zeros(
(len(self.layers), self.nb_classes), dtype=np.int32)
for layer_id, layer in enumerate(self.layers):
knns_in_class[layer_id, :] = np.bincount(
knns_labels[layer][i], minlength=self.nb_classes)
# Compute number of knns in other class than class_id
for class_id in range(self.nb_classes):
knns_not_in_class[i, class_id] = np.sum(
knns_in_class) - np.sum(knns_in_class[:, class_id])
return knns_not_in_class
|
[
"\n Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of\n each candidate label for each data point: i.e. the number of knns whose label is\n different from the candidate label.\n "
] |
Please provide a description of the function:def preds_conf_cred(self, knns_not_in_class):
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros((nb_data, self.nb_classes), dtype=np.float32)
creds = np.zeros((nb_data, self.nb_classes), dtype=np.float32)
for i in range(nb_data):
# p-value of test input for each class
p_value = np.zeros(self.nb_classes, dtype=np.float32)
for class_id in range(self.nb_classes):
# p-value of (test point, candidate label)
p_value[class_id] = (float(self.nb_cali) - bisect_left(
self.cali_nonconformity, knns_not_in_class[i, class_id])) / float(self.nb_cali)
preds_knn[i] = np.argmax(p_value)
confs[i, preds_knn[i]] = 1. - p_value[np.argsort(p_value)[-2]]
creds[i, preds_knn[i]] = p_value[preds_knn[i]]
return preds_knn, confs, creds
|
[
"\n Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute\n the DkNN's prediction, confidence and credibility.\n "
] |
Please provide a description of the function:def fprop_np(self, data_np):
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_np)
_, knns_labels = self.find_train_knns(data_activations)
knns_not_in_class = self.nonconformity(knns_labels)
_, _, creds = self.preds_conf_cred(knns_not_in_class)
return creds
|
[
"\n Performs a forward pass through the DkNN on an numpy array of data.\n "
] |
Please provide a description of the function:def fprop(self, x):
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits}
|
[
"\n Performs a forward pass through the DkNN on a TF tensor by wrapping\n the fprop_np method.\n "
] |
Please provide a description of the function:def calibrate(self, cali_data, cali_labels):
self.nb_cali = cali_labels.shape[0]
self.cali_activations = self.get_activations(cali_data)
self.cali_labels = cali_labels
print("Starting calibration of DkNN.")
cali_knns_ind, cali_knns_labels = self.find_train_knns(
self.cali_activations)
assert all([v.shape == (self.nb_cali, self.neighbors)
for v in cali_knns_ind.itervalues()])
assert all([v.shape == (self.nb_cali, self.neighbors)
for v in cali_knns_labels.itervalues()])
cali_knns_not_in_class = self.nonconformity(cali_knns_labels)
cali_knns_not_in_l = np.zeros(self.nb_cali, dtype=np.int32)
for i in range(self.nb_cali):
cali_knns_not_in_l[i] = cali_knns_not_in_class[i, cali_labels[i]]
cali_knns_not_in_l_sorted = np.sort(cali_knns_not_in_l)
self.cali_nonconformity = np.trim_zeros(cali_knns_not_in_l_sorted, trim='f')
self.nb_cali = self.cali_nonconformity.shape[0]
self.calibrated = True
print("DkNN calibration complete.")
|
[
"\n Runs the DkNN on holdout data to calibrate the credibility metric.\n :param cali_data: np array of calibration data.\n :param cali_labels: np vector of calibration labels.\n "
] |
Please provide a description of the function:def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
# Train a pytorch MNIST model
torch_model = PytorchMnistModel()
if torch.cuda.is_available():
torch_model = torch_model.cuda()
report = AccuracyReport()
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('data', train=True, download=True,
transform=transforms.ToTensor()),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('data', train=False, transform=transforms.ToTensor()),
batch_size=batch_size)
# Truncate the datasets so that our test run more quickly
train_loader.dataset.train_data = train_loader.dataset.train_data[
:train_end]
test_loader.dataset.test_data = test_loader.dataset.test_data[:test_end]
# Train our model
optimizer = optim.Adam(torch_model.parameters(), lr=learning_rate)
train_loss = []
total = 0
correct = 0
step = 0
for _epoch in range(nb_epochs):
for xs, ys in train_loader:
xs, ys = Variable(xs), Variable(ys)
if torch.cuda.is_available():
xs, ys = xs.cuda(), ys.cuda()
optimizer.zero_grad()
preds = torch_model(xs)
loss = F.nll_loss(preds, ys)
loss.backward() # calc gradients
train_loss.append(loss.data.item())
optimizer.step() # update gradients
preds_np = preds.cpu().detach().numpy()
correct += (np.argmax(preds_np, axis=1) == ys.cpu().detach().numpy()).sum()
total += train_loader.batch_size
step += 1
if total % 1000 == 0:
acc = float(correct) / total
print('[%s] Training accuracy: %.2f%%' % (step, acc * 100))
total = 0
correct = 0
# Evaluate on clean data
total = 0
correct = 0
for xs, ys in test_loader:
xs, ys = Variable(xs), Variable(ys)
if torch.cuda.is_available():
xs, ys = xs.cuda(), ys.cuda()
preds = torch_model(xs)
preds_np = preds.cpu().detach().numpy()
correct += (np.argmax(preds_np, axis=1) == ys.cpu().detach().numpy()).sum()
total += len(xs)
acc = float(correct) / total
report.clean_train_clean_eval = acc
print('[%s] Clean accuracy: %.2f%%' % (step, acc * 100))
# We use tf for evaluation on adversarial data
sess = tf.Session()
x_op = tf.placeholder(tf.float32, shape=(None, 1, 28, 28,))
# Convert pytorch model to a tf_model and wrap it in cleverhans
tf_model_fn = convert_pytorch_model_to_tf(torch_model)
cleverhans_model = CallableModelWrapper(tf_model_fn, output_layer='logits')
# Create an FGSM attack
fgsm_op = FastGradientMethod(cleverhans_model, sess=sess)
fgsm_params = {'eps': 0.3,
'clip_min': 0.,
'clip_max': 1.}
adv_x_op = fgsm_op.generate(x_op, **fgsm_params)
adv_preds_op = tf_model_fn(adv_x_op)
# Run an evaluation of our model against fgsm
total = 0
correct = 0
for xs, ys in test_loader:
adv_preds = sess.run(adv_preds_op, feed_dict={x_op: xs})
correct += (np.argmax(adv_preds, axis=1) == ys.cpu().detach().numpy()).sum()
total += test_loader.batch_size
acc = float(correct) / total
print('Adv accuracy: {:.3f}'.format(acc * 100))
report.clean_train_adv_eval = acc
return report
|
[
"\n MNIST cleverhans tutorial\n :param nb_epochs: number of epochs to train model\n :param batch_size: size of training batches\n :param learning_rate: learning rate for training\n :return: an AccuracyReport object\n "
] |
Please provide a description of the function:def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
warnings.warn(
"This function is dead code and will be removed on or after 2019-07-18")
# perturb our input sample
if increase:
X[0, i] = np.minimum(clip_max, X[0, i] + theta)
X[0, j] = np.minimum(clip_max, X[0, j] + theta)
else:
X[0, i] = np.maximum(clip_min, X[0, i] - theta)
X[0, j] = np.maximum(clip_min, X[0, j] - theta)
return X
|
[
"\n TensorFlow implementation for apply perturbations to input features based\n on salency maps\n :param i: index of first selected feature\n :param j: index of second selected feature\n :param X: a matrix containing our input features for our sample\n :param increase: boolean; true if we are increasing pixels, false otherwise\n :param theta: delta for each feature adjustment\n :param clip_min: mininum value for a feature in our sample\n :param clip_max: maximum value for a feature in our sample\n : return: a perturbed input feature matrix for a target class\n "
] |
Please provide a description of the function:def saliency_map(grads_target, grads_other, search_domain, increase):
warnings.warn(
"This function is dead code and will be removed on or after 2019-07-18")
# Compute the size of the input (the number of features)
nf = len(grads_target)
# Remove the already-used input features from the search space
invalid = list(set(range(nf)) - search_domain)
increase_coef = (2 * int(increase) - 1)
grads_target[invalid] = -increase_coef * np.max(np.abs(grads_target))
grads_other[invalid] = increase_coef * np.max(np.abs(grads_other))
# Create a 2D numpy array of the sum of grads_target and grads_other
target_sum = grads_target.reshape((1, nf)) + grads_target.reshape((nf, 1))
other_sum = grads_other.reshape((1, nf)) + grads_other.reshape((nf, 1))
# Create a mask to only keep features that match saliency map conditions
if increase:
scores_mask = ((target_sum > 0) & (other_sum < 0))
else:
scores_mask = ((target_sum < 0) & (other_sum > 0))
# Create a 2D numpy array of the scores for each pair of candidate features
scores = scores_mask * (-target_sum * other_sum)
# A pixel can only be selected (and changed) once
np.fill_diagonal(scores, 0)
# Extract the best two pixels
best = np.argmax(scores)
p1, p2 = best % nf, best // nf
# Remove used pixels from our search domain
search_domain.discard(p1)
search_domain.discard(p2)
return p1, p2, search_domain
|
[
"\n TensorFlow implementation for computing saliency maps\n :param grads_target: a matrix containing forward derivatives for the\n target class\n :param grads_other: a matrix where every element is the sum of forward\n derivatives over all non-target classes at that index\n :param search_domain: the set of input indices that we are considering\n :param increase: boolean; true if we are increasing pixels, false otherwise\n :return: (i, j, search_domain) the two input indices selected and the\n updated search domain\n "
] |
Please provide a description of the function:def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
warnings.warn(
"This function is dead code and will be removed on or after 2019-07-18")
# Prepare feeding dictionary for all gradient computations
feed_dict = {x: X}
if feed is not None:
feed_dict.update(feed)
# Initialize a numpy array to hold the Jacobian component values
jacobian_val = np.zeros((nb_classes, nb_features), dtype=np_dtype)
# Compute the gradients for all classes
for class_ind, grad in enumerate(grads):
run_grad = sess.run(grad, feed_dict)
jacobian_val[class_ind] = np.reshape(run_grad, (1, nb_features))
# Sum over all classes different from the target class to prepare for
# saliency map computation in the next step of the attack
other_classes = utils.other_classes(nb_classes, target)
grad_others = np.sum(jacobian_val[other_classes, :], axis=0)
return jacobian_val[target], grad_others
|
[
"\n TensorFlow implementation of the foward derivative / Jacobian\n :param x: the input placeholder\n :param grads: the list of TF gradients returned by jacobian_graph()\n :param target: the target misclassification class\n :param X: numpy array with sample input\n :param nb_features: the number of features in the input\n :return: matrix of forward derivatives flattened into vectors\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, (eps_iter, eps)
if ord == 1:
raise NotImplementedError("It's not clear that FGM is a good inner loop"
" step for PGD when ord=1, because ord=1 FGM "
" changes only one pixel at a time. We need "
" to rigorously test a strong ord=1 PGD "
"before enabling this feature.")
if ord not in [np.inf, 2]:
raise ValueError("Norm order must be either np.inf or 2.")
asserts = []
# If a data range was specified, check that the input was in that range
if clip_min is not None:
assert_ge = torch.all(torch.ge(x, torch.tensor(clip_min, device=x.device, dtype=x.dtype)))
asserts.append(assert_ge)
if clip_max is not None:
assert_le = torch.all(torch.le(x, torch.tensor(clip_max, device=x.device, dtype=x.dtype)))
asserts.append(assert_le)
# Initialize loop variables
if rand_init:
rand_minmax = eps
eta = torch.zeros_like(x).uniform_(-rand_minmax, rand_minmax)
else:
eta = torch.zeros_like(x)
# Clip eta
eta = clip_eta(eta, ord, eps)
adv_x = x + eta
if clip_min is not None or clip_max is not None:
adv_x = torch.clamp(adv_x, clip_min, clip_max)
if y is None:
# Using model predictions as ground truth to avoid label leaking
_, y = torch.max(model_fn(x), 1)
i = 0
while i < nb_iter:
adv_x = fast_gradient_method(model_fn, adv_x, eps_iter, ord,
clip_min=clip_min, clip_max=clip_max, y=y, targeted=targeted)
# Clipping perturbation eta to ord norm ball
eta = adv_x - x
eta = clip_eta(eta, ord, eps)
adv_x = x + eta
# Redo the clipping.
# FGM already did it, but subtracting and re-adding eta can add some
# small numerical error.
if clip_min is not None or clip_max is not None:
adv_x = torch.clamp(adv_x, clip_min, clip_max)
i += 1
asserts.append(eps_iter <= eps)
if ord == np.inf and clip_min is not None:
# TODO necessary to cast clip_min and clip_max to x.dtype?
asserts.append(eps + clip_min <= clip_max)
if sanity_checks:
assert np.all(asserts)
return adv_x
|
[
"\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/1706.06083.pdf\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 eps_iter: step size for each attack iteration\n :param nb_iter: Number of attack iterations.\n :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.\n :param clip_min: (optional) float. Minimum float value for adversarial example components.\n :param clip_max: (optional) float. Maximum float value for adversarial example components.\n :param y: (optional) Tensor with true labels. If targeted is true, then provide the\n target label. Otherwise, only provide this parameter if you'd like to use true\n labels when crafting adversarial samples. Otherwise, model predictions are used\n as labels to avoid the \"label leaking\" effect (explained in this paper:\n https://arxiv.org/abs/1611.01236). Default is None.\n :param targeted: (optional) bool. Is the attack targeted or untargeted?\n Untargeted, the default, will try to make the label incorrect.\n Targeted will instead try to move in the direction of being more like y.\n :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /\n memory or for unit tests that intentionally pass strange input)\n :return: a tensor for the adversarial example\n "
] |
Please provide a description of the function:def _batch_norm(name, x):
with tf.name_scope(name):
return tf.contrib.layers.batch_norm(
inputs=x,
decay=.9,
center=True,
scale=True,
activation_fn=None,
updates_collections=None,
is_training=False)
|
[
"Batch normalization."
] |
Please provide a description of the function:def _residual(x, in_filter, out_filter, stride,
activate_before_residual=False):
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = _batch_norm('init_bn', x)
x = _relu(x, 0.1)
orig_x = x
else:
with tf.variable_scope('residual_only_activation'):
orig_x = x
x = _batch_norm('init_bn', x)
x = _relu(x, 0.1)
with tf.variable_scope('sub1'):
x = _conv('conv1', x, 3, in_filter, out_filter, stride)
with tf.variable_scope('sub2'):
x = _batch_norm('bn2', x)
x = _relu(x, 0.1)
x = _conv('conv2', x, 3, out_filter, out_filter, [1, 1, 1, 1])
with tf.variable_scope('sub_add'):
if in_filter != out_filter:
orig_x = tf.nn.avg_pool(orig_x, stride, stride, 'VALID')
orig_x = tf.pad(
orig_x, [[0, 0], [0, 0],
[0, 0], [(out_filter - in_filter) // 2,
(out_filter - in_filter) // 2]])
x += orig_x
tf.logging.debug('image after unit %s', x.get_shape())
return x
|
[
"Residual unit with 2 sub layers."
] |
Please provide a description of the function:def _decay():
costs = []
for var in tf.trainable_variables():
if var.op.name.find('DW') > 0:
costs.append(tf.nn.l2_loss(var))
return tf.add_n(costs)
|
[
"L2 weight decay loss."
] |
Please provide a description of the function:def _relu(x, leakiness=0.0):
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu')
|
[
"Relu, with optional leaky support."
] |
Please provide a description of the function:def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
input_shape = list(input_shape)
input_shape[0] = 1
dummy_batch = tf.zeros(input_shape)
dummy_output = self.fprop(dummy_batch)
output_shape = [int(e) for e in dummy_output.get_shape()]
output_shape[0] = batch_size
self.output_shape = tuple(output_shape)
|
[
"Build the core model within the graph."
] |
Please provide a description of the function:def create_projected_dual(self):
# TODO: consider whether we can use shallow copy of the lists without
# using tf.identity
projected_nu = tf.placeholder(tf.float32, shape=[])
min_eig_h = tf.placeholder(tf.float32, shape=[])
projected_lambda_pos = [tf.identity(x) for x in self.lambda_pos]
projected_lambda_neg = [tf.identity(x) for x in self.lambda_neg]
projected_lambda_quad = [
tf.identity(x) for x in self.lambda_quad
]
projected_lambda_lu = [tf.identity(x) for x in self.lambda_lu]
for i in range(self.nn_params.num_hidden_layers + 1):
# Making H PSD
projected_lambda_lu[i] = self.lambda_lu[i] + 0.5*tf.maximum(-min_eig_h, 0) + TOL
# Adjusting the value of \lambda_neg to make change in g small
projected_lambda_neg[i] = self.lambda_neg[i] + tf.multiply(
(self.lower[i] + self.upper[i]),
(self.lambda_lu[i] - projected_lambda_lu[i]))
projected_lambda_neg[i] = (tf.multiply(self.negative_indices[i],
projected_lambda_neg[i]) +
tf.multiply(self.switch_indices[i],
tf.maximum(projected_lambda_neg[i], 0)))
projected_dual_var = {
'lambda_pos': projected_lambda_pos,
'lambda_neg': projected_lambda_neg,
'lambda_lu': projected_lambda_lu,
'lambda_quad': projected_lambda_quad,
'nu': projected_nu,
}
projected_dual_object = DualFormulation(
self.sess, projected_dual_var, self.nn_params,
self.test_input, self.true_class,
self.adv_class, self.input_minval,
self.input_maxval, self.epsilon,
self.lzs_params,
project_dual=False)
projected_dual_object.min_eig_val_h = min_eig_h
return projected_dual_object
|
[
"Function to create variables for the projected dual object.\n Function that projects the input dual variables onto the feasible set.\n Returns:\n projected_dual: Feasible dual solution corresponding to current dual\n "
] |
Please provide a description of the function:def construct_lanczos_params(self):
# Using autograph to automatically handle
# the control flow of minimum_eigen_vector
self.min_eigen_vec = autograph.to_graph(utils.tf_lanczos_smallest_eigval)
def _m_vector_prod_fn(x):
return self.get_psd_product(x, dtype=self.lanczos_dtype)
def _h_vector_prod_fn(x):
return self.get_h_product(x, dtype=self.lanczos_dtype)
# Construct nodes for computing eigenvalue of M
self.m_min_vec_estimate = np.zeros(shape=(self.matrix_m_dimension, 1), dtype=np.float64)
zeros_m = tf.zeros(shape=(self.matrix_m_dimension, 1), dtype=tf.float64)
self.m_min_vec_ph = tf.placeholder_with_default(input=zeros_m,
shape=(self.matrix_m_dimension, 1),
name='m_min_vec_ph')
self.m_min_eig, self.m_min_vec = self.min_eigen_vec(_m_vector_prod_fn,
self.matrix_m_dimension,
self.m_min_vec_ph,
self.lzs_params['max_iter'],
dtype=self.lanczos_dtype)
self.m_min_eig = tf.cast(self.m_min_eig, self.nn_dtype)
self.m_min_vec = tf.cast(self.m_min_vec, self.nn_dtype)
self.h_min_vec_estimate = np.zeros(shape=(self.matrix_m_dimension - 1, 1), dtype=np.float64)
zeros_h = tf.zeros(shape=(self.matrix_m_dimension - 1, 1), dtype=tf.float64)
self.h_min_vec_ph = tf.placeholder_with_default(input=zeros_h,
shape=(self.matrix_m_dimension - 1, 1),
name='h_min_vec_ph')
self.h_min_eig, self.h_min_vec = self.min_eigen_vec(_h_vector_prod_fn,
self.matrix_m_dimension-1,
self.h_min_vec_ph,
self.lzs_params['max_iter'],
dtype=self.lanczos_dtype)
self.h_min_eig = tf.cast(self.h_min_eig, self.nn_dtype)
self.h_min_vec = tf.cast(self.h_min_vec, self.nn_dtype)
|
[
"Computes matrices T and V using the Lanczos algorithm.\n\n Args:\n k: number of iterations and dimensionality of the tridiagonal matrix\n Returns:\n eig_vec: eigen vector corresponding to min eigenvalue\n "
] |
Please provide a description of the function:def set_differentiable_objective(self):
# Checking if graphs are already created
if self.vector_g is not None:
return
# Computing the scalar term
bias_sum = 0
for i in range(0, self.nn_params.num_hidden_layers):
bias_sum = bias_sum + tf.reduce_sum(
tf.multiply(self.nn_params.biases[i], self.lambda_pos[i + 1]))
lu_sum = 0
for i in range(0, self.nn_params.num_hidden_layers + 1):
lu_sum = lu_sum + tf.reduce_sum(
tf.multiply(tf.multiply(self.lower[i], self.upper[i]),
self.lambda_lu[i]))
self.scalar_f = -bias_sum - lu_sum + self.final_constant
# Computing the vector term
g_rows = []
for i in range(0, self.nn_params.num_hidden_layers):
if i > 0:
current_row = (self.lambda_neg[i] + self.lambda_pos[i] -
self.nn_params.forward_pass(self.lambda_pos[i+1],
i, is_transpose=True) +
tf.multiply(self.lower[i]+self.upper[i],
self.lambda_lu[i]) +
tf.multiply(self.lambda_quad[i],
self.nn_params.biases[i-1]))
else:
current_row = (-self.nn_params.forward_pass(self.lambda_pos[i+1],
i, is_transpose=True)
+ tf.multiply(self.lower[i]+self.upper[i],
self.lambda_lu[i]))
g_rows.append(current_row)
# Term for final linear term
g_rows.append((self.lambda_pos[self.nn_params.num_hidden_layers] +
self.lambda_neg[self.nn_params.num_hidden_layers] +
self.final_linear +
tf.multiply((self.lower[self.nn_params.num_hidden_layers]+
self.upper[self.nn_params.num_hidden_layers]),
self.lambda_lu[self.nn_params.num_hidden_layers])
+ tf.multiply(
self.lambda_quad[self.nn_params.num_hidden_layers],
self.nn_params.biases[
self.nn_params.num_hidden_layers-1])))
self.vector_g = tf.concat(g_rows, axis=0)
self.unconstrained_objective = self.scalar_f + 0.5 * self.nu
|
[
"Function that constructs minimization objective from dual variables."
] |
Please provide a description of the function:def get_h_product(self, vector, dtype=None):
# Computing the product of matrix_h with beta (input vector)
# At first layer, h is simply diagonal
if dtype is None:
dtype = self.nn_dtype
beta = tf.cast(vector, self.nn_dtype)
h_beta_rows = []
for i in range(self.nn_params.num_hidden_layers):
# Split beta of this block into [gamma, delta]
gamma = beta[self.dual_index[i]:self.dual_index[i + 1]]
delta = beta[self.dual_index[i + 1]:self.dual_index[i + 2]]
# Expanding the product with diagonal matrices
if i == 0:
h_beta_rows.append(
tf.multiply(2 * self.lambda_lu[i], gamma) -
self.nn_params.forward_pass(
tf.multiply(self.lambda_quad[i + 1], delta),
i,
is_transpose=True))
else:
h_beta_rows[i] = (h_beta_rows[i] +
tf.multiply(self.lambda_quad[i] +
self.lambda_lu[i], gamma) -
self.nn_params.forward_pass(
tf.multiply(self.lambda_quad[i+1], delta),
i, is_transpose=True))
new_row = (
tf.multiply(self.lambda_quad[i + 1] + self.lambda_lu[i + 1], delta) -
tf.multiply(self.lambda_quad[i + 1],
self.nn_params.forward_pass(gamma, i)))
h_beta_rows.append(new_row)
# Last boundary case
h_beta_rows[self.nn_params.num_hidden_layers] = (
h_beta_rows[self.nn_params.num_hidden_layers] +
tf.multiply((self.lambda_quad[self.nn_params.num_hidden_layers] +
self.lambda_lu[self.nn_params.num_hidden_layers]),
delta))
h_beta = tf.concat(h_beta_rows, axis=0)
return tf.cast(h_beta, dtype)
|
[
"Function that provides matrix product interface with PSD matrix.\n\n Args:\n vector: the vector to be multiplied with matrix H\n\n Returns:\n result_product: Matrix product of H and vector\n "
] |
Please provide a description of the function:def get_psd_product(self, vector, dtype=None):
# For convenience, think of x as [\alpha, \beta]
if dtype is None:
dtype = self.nn_dtype
vector = tf.cast(vector, self.nn_dtype)
alpha = tf.reshape(vector[0], shape=[1, 1])
beta = vector[1:]
# Computing the product of matrix_h with beta part of vector
# At first layer, h is simply diagonal
h_beta = self.get_h_product(beta)
# Constructing final result using vector_g
result = tf.concat(
[
alpha * self.nu + tf.reduce_sum(tf.multiply(beta, self.vector_g)),
tf.multiply(alpha, self.vector_g) + h_beta
],
axis=0)
return tf.cast(result, dtype)
|
[
"Function that provides matrix product interface with PSD matrix.\n\n Args:\n vector: the vector to be multiplied with matrix M\n\n Returns:\n result_product: Matrix product of M and vector\n "
] |
Please provide a description of the function:def get_full_psd_matrix(self):
if self.matrix_m is not None:
return self.matrix_h, self.matrix_m
# Computing the matrix term
h_columns = []
for i in range(self.nn_params.num_hidden_layers + 1):
current_col_elems = []
for j in range(i):
current_col_elems.append(
tf.zeros([self.nn_params.sizes[j], self.nn_params.sizes[i]]))
# For the first layer, there is no relu constraint
if i == 0:
current_col_elems.append(utils.diag(self.lambda_lu[i]))
else:
current_col_elems.append(
utils.diag(self.lambda_lu[i] + self.lambda_quad[i]))
if i < self.nn_params.num_hidden_layers:
current_col_elems.append(tf.matmul(
utils.diag(-1 * self.lambda_quad[i + 1]),
self.nn_params.weights[i]))
for j in range(i + 2, self.nn_params.num_hidden_layers + 1):
current_col_elems.append(
tf.zeros([self.nn_params.sizes[j], self.nn_params.sizes[i]]))
current_column = tf.concat(current_col_elems, 0)
h_columns.append(current_column)
self.matrix_h = tf.concat(h_columns, 1)
self.matrix_h = (self.matrix_h + tf.transpose(self.matrix_h))
self.matrix_m = tf.concat(
[
tf.concat([tf.reshape(self.nu, (1, 1)), tf.transpose(self.vector_g)], axis=1),
tf.concat([self.vector_g, self.matrix_h], axis=1)
],
axis=0)
return self.matrix_h, self.matrix_m
|
[
"Function that returns the tf graph corresponding to the entire matrix M.\n\n Returns:\n matrix_h: unrolled version of tf matrix corresponding to H\n matrix_m: unrolled tf matrix corresponding to M\n "
] |
Please provide a description of the function:def make_m_psd(self, original_nu, feed_dictionary):
feed_dict = feed_dictionary.copy()
_, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict)
lower_nu = original_nu
upper_nu = original_nu
num_iter = 0
# Find an upper bound on nu
while min_eig_val_m - TOL < 0 and num_iter < (MAX_BINARY_SEARCH_ITER / 2):
num_iter += 1
upper_nu *= NU_UPDATE_CONSTANT
feed_dict.update({self.nu: upper_nu})
_, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict)
final_nu = upper_nu
# Perform binary search to find best value of nu
while lower_nu <= upper_nu and num_iter < MAX_BINARY_SEARCH_ITER:
num_iter += 1
mid_nu = (lower_nu + upper_nu) / 2
feed_dict.update({self.nu: mid_nu})
_, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict)
if min_eig_val_m - TOL < 0:
lower_nu = mid_nu
else:
upper_nu = mid_nu
final_nu = upper_nu
return final_nu
|
[
"Run binary search to find a value for nu that makes M PSD\n Args:\n original_nu: starting value of nu to do binary search on\n feed_dictionary: dictionary of updated lambda variables to feed into M\n Returns:\n new_nu: new value of nu\n "
] |
Please provide a description of the function:def get_lanczos_eig(self, compute_m=True, feed_dict=None):
if compute_m:
min_eig, min_vec = self.sess.run([self.m_min_eig, self.m_min_vec], feed_dict=feed_dict)
else:
min_eig, min_vec = self.sess.run([self.h_min_eig, self.h_min_vec], feed_dict=feed_dict)
return min_vec, min_eig
|
[
"Computes the min eigen value and corresponding vector of matrix M or H\n using the Lanczos algorithm.\n Args:\n compute_m: boolean to determine whether we should compute eig val/vec\n for M or for H. True for M; False for H.\n feed_dict: dictionary mapping from TF placeholders to values (optional)\n Returns:\n min_eig_vec: Corresponding eigen vector to min eig val\n eig_val: Minimum eigen value\n "
] |
Please provide a description of the function:def generate(self, x, **kwargs):
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
from cleverhans.attacks_tf import spm
labels, _ = self.get_or_guess_labels(x, kwargs)
return spm(
x,
self.model,
y=labels,
n_samples=self.n_samples,
dx_min=self.dx_min, dx_max=self.dx_max, n_dxs=self.n_dxs,
dy_min=self.dy_min, dy_max=self.dy_max, n_dys=self.n_dys,
angle_min=self.angle_min, angle_max=self.angle_max,
n_angles=self.n_angles, black_border_size=self.black_border_size)
|
[
"\n Generate symbolic graph for adversarial examples and return.\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,
n_samples=None,
dx_min=-0.1,
dx_max=0.1,
n_dxs=2,
dy_min=-0.1,
dy_max=0.1,
n_dys=2,
angle_min=-30,
angle_max=30,
n_angles=6,
black_border_size=0,
**kwargs):
self.n_samples = n_samples
self.dx_min = dx_min
self.dx_max = dx_max
self.n_dxs = n_dxs
self.dy_min = dy_min
self.dy_max = dy_max
self.n_dys = n_dys
self.angle_min = angle_min
self.angle_max = angle_max
self.n_angles = n_angles
self.black_border_size = black_border_size
if self.dx_min < -1 or self.dy_min < -1 or \
self.dx_max > 1 or self.dy_max > 1:
raise ValueError("The value of translation must be bounded "
"within [-1, 1]")
if len(kwargs.keys()) > 0:
warnings.warn("kwargs is unused and will be removed on or after "
"2019-04-26.")
return True
|
[
"\n Take in a dictionary of parameters and applies attack-specific checks\n before saving them as attributes.\n :param n_samples: (optional) The number of transformations sampled to\n construct the attack. Set it to None to run\n full grid attack.\n :param dx_min: (optional float) Minimum translation ratio along x-axis.\n :param dx_max: (optional float) Maximum translation ratio along x-axis.\n :param n_dxs: (optional int) Number of discretized translation ratios\n along x-axis.\n :param dy_min: (optional float) Minimum translation ratio along y-axis.\n :param dy_max: (optional float) Maximum translation ratio along y-axis.\n :param n_dys: (optional int) Number of discretized translation ratios\n along y-axis.\n :param angle_min: (optional float) Largest counter-clockwise rotation\n angle.\n :param angle_max: (optional float) Largest clockwise rotation angle.\n :param n_angles: (optional int) Number of discretized angles.\n :param black_border_size: (optional int) size of the black border in pixels.\n "
] |
Please provide a description of the function:def conv_2d(filters, kernel_shape, strides, padding, input_shape=None):
if input_shape is not None:
return Conv2D(filters=filters, kernel_size=kernel_shape,
strides=strides, padding=padding,
input_shape=input_shape)
else:
return Conv2D(filters=filters, kernel_size=kernel_shape,
strides=strides, padding=padding)
|
[
"\n Defines the right convolutional layer according to the\n version of Keras that is installed.\n :param filters: (required integer) the dimensionality of the output\n space (i.e. the number output of filters in the\n convolution)\n :param kernel_shape: (required tuple or list of 2 integers) specifies\n the kernel shape of the convolution\n :param strides: (required tuple or list of 2 integers) specifies\n the strides of the convolution along the width and\n height.\n :param padding: (required string) can be either 'valid' (no padding around\n input or feature map) or 'same' (pad to ensure that the\n output feature map size is identical to the layer input)\n :param input_shape: (optional) give input shape if this is the first\n layer of the model\n :return: the Keras layer\n "
] |
Please provide a description of the function:def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28,
channels=1, nb_filters=64, nb_classes=10):
model = Sequential()
# Define the layers successively (convolution layers are version dependent)
if tf.keras.backend.image_data_format() == 'channels_first':
input_shape = (channels, img_rows, img_cols)
else:
assert tf.keras.backend.image_data_format() == 'channels_last'
input_shape = (img_rows, img_cols, channels)
layers = [conv_2d(nb_filters, (8, 8), (2, 2), "same",
input_shape=input_shape),
Activation('relu'),
conv_2d((nb_filters * 2), (6, 6), (2, 2), "valid"),
Activation('relu'),
conv_2d((nb_filters * 2), (5, 5), (1, 1), "valid"),
Activation('relu'),
Flatten(),
Dense(nb_classes)]
for layer in layers:
model.add(layer)
if logits:
logits_tensor = model(input_ph)
model.add(Activation('softmax'))
if logits:
return model, logits_tensor
else:
return model
|
[
"\n Defines a CNN model using Keras sequential model\n :param logits: If set to False, returns a Keras model, otherwise will also\n return logits tensor\n :param input_ph: The TensorFlow tensor for the input\n (needed if returning logits)\n (\"ph\" stands for placeholder but it need not actually be a\n placeholder)\n :param img_rows: number of row in the image\n :param img_cols: number of columns in the image\n :param channels: number of color channels (e.g., 1 for MNIST)\n :param nb_filters: number of convolutional filters per layer\n :param nb_classes: the number of output classes\n :return:\n "
] |
Please provide a description of the function:def _get_softmax_name(self):
for layer in self.model.layers:
cfg = layer.get_config()
if 'activation' in cfg and cfg['activation'] == 'softmax':
return layer.name
raise Exception("No softmax layers found")
|
[
"\n Looks for the name of the softmax layer.\n :return: Softmax layer name\n "
] |
Please provide a description of the function:def _get_abstract_layer_name(self):
abstract_layers = []
for layer in self.model.layers:
if 'layers' in layer.get_config():
abstract_layers.append(layer.name)
return abstract_layers
|
[
"\n Looks for the name of abstracted layer.\n Usually these layers appears when model is stacked.\n :return: List of abstracted layers\n "
] |
Please provide a description of the function:def _get_logits_name(self):
softmax_name = self._get_softmax_name()
softmax_layer = self.model.get_layer(softmax_name)
if not isinstance(softmax_layer, Activation):
# In this case, the activation is part of another layer
return softmax_name
if not hasattr(softmax_layer, '_inbound_nodes'):
raise RuntimeError("Please update keras to version >= 2.1.3")
node = softmax_layer._inbound_nodes[0]
logits_name = node.inbound_layers[0].name
return logits_name
|
[
"\n Looks for the name of the layer producing the logits.\n :return: name of layer producing the logits\n "
] |
Please provide a description of the function:def get_logits(self, x):
logits_name = self._get_logits_name()
logits_layer = self.get_layer(x, logits_name)
# Need to deal with the case where softmax is part of the
# logits layer
if logits_name == self._get_softmax_name():
softmax_logit_layer = self.get_layer(x, logits_name)
# The final op is the softmax. Return its input
logits_layer = softmax_logit_layer._op.inputs[0]
return logits_layer
|
[
"\n :param x: A symbolic representation of the network input.\n :return: A symbolic representation of the logits\n "
] |
Please provide a description of the function:def get_probs(self, x):
name = self._get_softmax_name()
return self.get_layer(x, name)
|
[
"\n :param x: A symbolic representation of the network input.\n :return: A symbolic representation of the probs\n "
] |
Please provide a description of the function:def get_layer_names(self):
layer_names = [x.name for x in self.model.layers]
return layer_names
|
[
"\n :return: Names of all the layers kept by Keras\n "
] |
Please provide a description of the function:def fprop(self, x):
if self.keras_model is None:
# Get the input layer
new_input = self.model.get_input_at(0)
# Make a new model that returns each of the layers as output
abstract_layers = self._get_abstract_layer_name()
if abstract_layers:
warnings.warn(
"Abstract layer detected, picking last ouput node as default."
"This could happen due to using of stacked model.")
layer_outputs = []
# For those abstract model layers, return their last output node as
# default.
for x_layer in self.model.layers:
if x_layer.name not in abstract_layers:
layer_outputs.append(x_layer.output)
else:
layer_outputs.append(x_layer.get_output_at(-1))
self.keras_model = KerasModel(new_input, layer_outputs)
# and get the outputs for that model on the input x
outputs = self.keras_model(x)
# Keras only returns a list for outputs of length >= 1, if the model
# is only one layer, wrap a list
if len(self.model.layers) == 1:
outputs = [outputs]
# compute the dict to return
fprop_dict = dict(zip(self.get_layer_names(), outputs))
return fprop_dict
|
[
"\n Exposes all the layers of the model returned by get_layer_names.\n :param x: A symbolic representation of the network input\n :return: A dictionary mapping layer names to the symbolic\n representation of their output.\n "
] |
Please provide a description of the function:def get_layer(self, x, layer):
# Return the symbolic representation for this layer.
output = self.fprop(x)
try:
requested = output[layer]
except KeyError:
raise NoSuchLayerError()
return requested
|
[
"\n Expose the hidden features of a model given a layer name.\n :param x: A symbolic representation of the network input\n :param layer: The name of the hidden layer to return features at.\n :return: A symbolic representation of the hidden features\n :raise: NoSuchLayerError if `layer` is not in the model.\n "
] |
Please provide a description of the function:def get_extract_command_template(filename):
for k, v in iteritems(EXTRACT_COMMAND):
if filename.endswith(k):
return v
return None
|
[
"Returns extraction command based on the filename extension."
] |
Please provide a description of the function:def shell_call(command, **kwargs):
command = list(command)
for i in range(len(command)):
m = CMD_VARIABLE_RE.match(command[i])
if m:
var_id = m.group(1)
if var_id in kwargs:
command[i] = kwargs[var_id]
return subprocess.call(command) == 0
|
[
"Calls shell command with parameter substitution.\n\n Args:\n command: command to run as a list of tokens\n **kwargs: dirctionary with substitutions\n\n Returns:\n whether command was successful, i.e. returned 0 status code\n\n Example of usage:\n shell_call(['cp', '${A}', '${B}'], A='src_file', B='dst_file')\n will call shell command:\n cp src_file dst_file\n "
] |
Please provide a description of the function:def make_directory_writable(dirname):
retval = shell_call(['docker', 'run', '-v',
'{0}:/output_dir'.format(dirname),
'busybox:1.27.2',
'chmod', '-R', 'a+rwx', '/output_dir'])
if not retval:
logging.error('Failed to change permissions on directory: %s', dirname)
return retval
|
[
"Makes directory readable and writable by everybody.\n\n Args:\n dirname: name of the directory\n\n Returns:\n True if operation was successfull\n\n If you run something inside Docker container and it writes files, then\n these files will be written as root user with restricted permissions.\n So to be able to read/modify these files outside of Docker you have to change\n permissions to be world readable and writable.\n "
] |
Please provide a description of the function:def _prepare_temp_dir(self):
if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]):
logging.error('Failed to cleanup temporary directory.')
sys.exit(1)
# 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_submission_dir
os.mkdir(self._tmp_extracted_dir)
os.mkdir(self._sample_input_dir)
os.mkdir(self._sample_output_dir)
# make output dir world writable
shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])
|
[
"Cleans up and prepare temporary directory."
] |
Please provide a description of the function:def _extract_submission(self, filename):
# verify filesize
file_size = os.path.getsize(filename)
if file_size > MAX_SUBMISSION_SIZE_ZIPPED:
logging.error('Submission archive size %d is exceeding limit %d',
file_size, MAX_SUBMISSION_SIZE_ZIPPED)
return False
# determime archive type
exctract_command_tmpl = get_extract_command_template(filename)
if not exctract_command_tmpl:
logging.error('Input file has to be zip, tar or tar.gz archive; however '
'found: %s', filename)
return False
# extract archive
submission_dir = os.path.dirname(filename)
submission_basename = os.path.basename(filename)
logging.info('Extracting archive %s', filename)
retval = shell_call(
['docker', 'run',
'--network=none',
'-v', '{0}:/input_dir'.format(submission_dir),
'-v', '{0}:/output_dir'.format(self._tmp_extracted_dir),
'busybox:1.27.2'] + exctract_command_tmpl,
src=os.path.join('/input_dir', submission_basename),
dst='/output_dir')
if not retval:
logging.error('Failed to extract submission from file %s', filename)
return False
if not make_directory_writable(self._tmp_extracted_dir):
return False
# find submission root
root_dir = self._tmp_extracted_dir
root_dir_content = [d for d in os.listdir(root_dir) if d != '__MACOSX']
if (len(root_dir_content) == 1
and os.path.isdir(os.path.join(root_dir, root_dir_content[0]))):
logging.info('Looks like submission root is in subdirectory "%s" of '
'the archive', root_dir_content[0])
root_dir = os.path.join(root_dir, root_dir_content[0])
# Move files to self._extracted_submission_dir.
# At this point self._extracted_submission_dir does not exist,
# so following command will simply rename root_dir into
# self._extracted_submission_dir
if not shell_call(['mv', root_dir, self._extracted_submission_dir]):
logging.error('Can''t move submission files from root directory')
return False
return True
|
[
"Extracts submission and moves it into self._extracted_submission_dir."
] |
Please provide a description of the function:def _verify_docker_image_size(self, image_name):
shell_call(['docker', 'pull', image_name])
try:
image_size = subprocess.check_output(
['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
image_size = int(image_size)
except (ValueError, subprocess.CalledProcessError) as e:
logging.error('Failed to determine docker image size: %s', e)
return False
logging.info('Size of docker image %s is %d', image_name, image_size)
if image_size > MAX_DOCKER_IMAGE_SIZE:
logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
return image_size <= MAX_DOCKER_IMAGE_SIZE
|
[
"Verifies size of Docker image.\n\n Args:\n image_name: name of the Docker image.\n\n Returns:\n True if image size is within the limits, False otherwise.\n "
] |
Please provide a description of the function:def _prepare_sample_data(self, submission_type):
# write images
images = np.random.randint(0, 256,
size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
for i in range(BATCH_SIZE):
Image.fromarray(images[i, :, :, :]).save(
os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i)))
# write target class for targeted attacks
if submission_type == 'targeted_attack':
target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE])
target_class_filename = os.path.join(self._sample_input_dir,
'target_class.csv')
with open(target_class_filename, 'w') as f:
for i in range(BATCH_SIZE):
f.write((IMAGE_NAME_PATTERN + ',{1}\n').format(i, target_classes[i]))
|
[
"Prepares sample data for the submission.\n\n Args:\n submission_type: type of the submission.\n "
] |
Please provide a description of the function:def _verify_output(self, submission_type):
result = True
if submission_type == 'defense':
try:
image_classification = load_defense_output(
os.path.join(self._sample_output_dir, 'result.csv'))
expected_keys = [IMAGE_NAME_PATTERN.format(i)
for i in range(BATCH_SIZE)]
if set(image_classification.keys()) != set(expected_keys):
logging.error('Classification results are not saved for all images')
result = False
except IOError as e:
logging.error('Failed to read defense output file: %s', e)
result = False
else:
for i in range(BATCH_SIZE):
image_filename = os.path.join(self._sample_output_dir,
IMAGE_NAME_PATTERN.format(i))
try:
img = np.array(Image.open(image_filename).convert('RGB'))
if list(img.shape) != [299, 299, 3]:
logging.error('Invalid image size %s for image %s',
str(img.shape), image_filename)
result = False
except IOError as e:
result = False
return result
|
[
"Verifies correctness of the submission output.\n\n Args:\n submission_type: type of the submission\n\n Returns:\n True if output looks valid\n "
] |
Please provide a description of the function:def validate_submission(self, filename):
self._prepare_temp_dir()
# Convert filename to be absolute path, relative path might cause problems
# with mounting directory in Docker
filename = os.path.abspath(filename)
# extract submission
if not self._extract_submission(filename):
return None
# verify submission size
if not self._verify_submission_size():
return None
# Load metadata
metadata = self._load_and_verify_metadata()
if not metadata:
return None
submission_type = metadata['type']
# verify docker container size
if not self._verify_docker_image_size(metadata['container_gpu']):
return None
# Try to run submission on sample data
self._prepare_sample_data(submission_type)
if not self._run_submission(metadata):
logging.error('Failure while running submission')
return None
if not self._verify_output(submission_type):
logging.warning('Some of the outputs of your submission are invalid or '
'missing. You submission still will be evaluation '
'but you might get lower score.')
return metadata
|
[
"Validates submission.\n\n Args:\n filename: submission filename\n\n Returns:\n submission metadata or None if submission is invalid\n "
] |
Please provide a description of the function:def save(self, path):
json.dump(dict(loss=self.__class__.__name__,
params=self.hparams),
open(os.path.join(path, 'loss.json'), 'wb'))
|
[
"Save loss in json format\n "
] |
Please provide a description of the function:def pairwise_euclid_distance(A, B):
batchA = tf.shape(A)[0]
batchB = tf.shape(B)[0]
sqr_norm_A = tf.reshape(tf.reduce_sum(tf.pow(A, 2), 1), [1, batchA])
sqr_norm_B = tf.reshape(tf.reduce_sum(tf.pow(B, 2), 1), [batchB, 1])
inner_prod = tf.matmul(B, A, transpose_b=True)
tile_1 = tf.tile(sqr_norm_A, [batchB, 1])
tile_2 = tf.tile(sqr_norm_B, [1, batchA])
return (tile_1 + tile_2 - 2 * inner_prod)
|
[
"Pairwise Euclidean distance between two matrices.\n :param A: a matrix.\n :param B: a matrix.\n\n :returns: A tensor for the pairwise Euclidean between A and B.\n "
] |
Please provide a description of the function:def pairwise_cos_distance(A, B):
normalized_A = tf.nn.l2_normalize(A, dim=1)
normalized_B = tf.nn.l2_normalize(B, dim=1)
prod = tf.matmul(normalized_A, normalized_B, adjoint_b=True)
return 1 - prod
|
[
"Pairwise cosine distance between two matrices.\n :param A: a matrix.\n :param B: a matrix.\n\n :returns: A tensor for the pairwise cosine between A and B.\n "
] |
Please provide a description of the function:def fits(A, B, temp, cos_distance):
if cos_distance:
distance_matrix = SNNLCrossEntropy.pairwise_cos_distance(A, B)
else:
distance_matrix = SNNLCrossEntropy.pairwise_euclid_distance(A, B)
return tf.exp(-(distance_matrix / temp))
|
[
"Exponentiated pairwise distance between each element of A and\n all those of B.\n :param A: a matrix.\n :param B: a matrix.\n :param temp: Temperature\n :cos_distance: Boolean for using cosine or Euclidean distance.\n\n :returns: A tensor for the exponentiated pairwise distance between\n each element and A and all those of B.\n "
] |
Please provide a description of the function:def pick_probability(x, temp, cos_distance):
f = SNNLCrossEntropy.fits(
x, x, temp, cos_distance) - tf.eye(tf.shape(x)[0])
return f / (
SNNLCrossEntropy.STABILITY_EPS + tf.expand_dims(tf.reduce_sum(f, 1), 1))
|
[
"Row normalized exponentiated pairwise distance between all the elements\n of x. Conceptualized as the probability of sampling a neighbor point for\n every element of x, proportional to the distance between the points.\n :param x: a matrix\n :param temp: Temperature\n :cos_distance: Boolean for using cosine or euclidean distance\n\n :returns: A tensor for the row normalized exponentiated pairwise distance\n between all the elements of x.\n "
] |
Please provide a description of the function:def same_label_mask(y, y2):
return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32)
|
[
"Masking matrix such that element i,j is 1 iff y[i] == y2[i].\n :param y: a list of labels\n :param y2: a list of labels\n\n :returns: A tensor for the masking matrix.\n "
] |
Please provide a description of the function:def masked_pick_probability(x, y, temp, cos_distance):
return SNNLCrossEntropy.pick_probability(x, temp, cos_distance) * \
SNNLCrossEntropy.same_label_mask(y, y)
|
[
"The pairwise sampling probabilities for the elements of x for neighbor\n points which share labels.\n :param x: a matrix\n :param y: a list of labels for each element of x\n :param temp: Temperature\n :cos_distance: Boolean for using cosine or Euclidean distance\n\n :returns: A tensor for the pairwise sampling probabilities.\n "
] |
Please provide a description of the function:def SNNL(x, y, temp, cos_distance):
summed_masked_pick_prob = tf.reduce_sum(
SNNLCrossEntropy.masked_pick_probability(x, y, temp, cos_distance), 1)
return tf.reduce_mean(
-tf.log(SNNLCrossEntropy.STABILITY_EPS + summed_masked_pick_prob))
|
[
"Soft Nearest Neighbor Loss\n :param x: a matrix.\n :param y: a list of labels for each element of x.\n :param temp: Temperature.\n :cos_distance: Boolean for using cosine or Euclidean distance.\n\n :returns: A tensor for the Soft Nearest Neighbor Loss of the points\n in x with labels y.\n "
] |
Please provide a description of the function:def optimized_temp_SNNL(x, y, initial_temp, cos_distance):
t = tf.Variable(1, dtype=tf.float32, trainable=False, name="temp")
def inverse_temp(t):
# pylint: disable=missing-docstring
# we use inverse_temp because it was observed to be more stable when optimizing.
return tf.div(initial_temp, t)
ent_loss = SNNLCrossEntropy.SNNL(x, y, inverse_temp(t), cos_distance)
updated_t = tf.assign(t, tf.subtract(t, 0.1*tf.gradients(ent_loss, t)[0]))
inverse_t = inverse_temp(updated_t)
return SNNLCrossEntropy.SNNL(x, y, inverse_t, cos_distance)
|
[
"The optimized variant of Soft Nearest Neighbor Loss. Every time this\n tensor is evaluated, the temperature is optimized to minimize the loss\n value, this results in more numerically stable calculations of the SNNL.\n :param x: a matrix.\n :param y: a list of labels for each element of x.\n :param initial_temp: Temperature.\n :cos_distance: Boolean for using cosine or Euclidean distance.\n\n :returns: A tensor for the Soft Nearest Neighbor Loss of the points\n in x with labels y, optimized for temperature.\n "
] |
Please provide a description of the function:def show(ndarray, min_val=None, max_val=None):
# Create a temporary file with the suffix '.png'.
fd, path = mkstemp(suffix='.png')
os.close(fd)
save(path, ndarray, min_val, max_val)
shell_call(VIEWER_COMMAND + [path])
|
[
"\n Display an image.\n :param ndarray: The image as an ndarray\n :param min_val: The minimum pixel value in the image format\n :param max_val: The maximum pixel valie in the image format\n If min_val and max_val are not specified, attempts to\n infer whether the image is in any of the common ranges:\n [0, 1], [-1, 1], [0, 255]\n This can be ambiguous, so it is better to specify if known.\n "
] |
Please provide a description of the function:def save(path, ndarray, min_val=None, max_val=None):
as_pil(ndarray, min_val, max_val).save(path)
|
[
"\n Save an image, represented as an ndarray, to the filesystem\n :param path: string, filepath\n :param ndarray: The image as an ndarray\n :param min_val: The minimum pixel value in the image format\n :param max_val: The maximum pixel valie in the image format\n If min_val and max_val are not specified, attempts to\n infer whether the image is in any of the common ranges:\n [0, 1], [-1, 1], [0, 255]\n This can be ambiguous, so it is better to specify if known.\n "
] |
Please provide a description of the function:def as_pil(ndarray, min_val=None, max_val=None):
assert isinstance(ndarray, np.ndarray)
# rows x cols for grayscale image
# rows x cols x channels for color
assert ndarray.ndim in [2, 3]
if ndarray.ndim == 3:
channels = ndarray.shape[2]
# grayscale or RGB
assert channels in [1, 3]
actual_min = ndarray.min()
actual_max = ndarray.max()
if min_val is not None:
assert actual_min >= min_val
assert actual_max <= max_val
if np.issubdtype(ndarray.dtype, np.floating):
if min_val is None:
if actual_min < -1.:
raise ValueError("Unrecognized range")
if actual_min < 0:
min_val = -1.
else:
min_val = 0.
if max_val is None:
if actual_max > 255.:
raise ValueError("Unrecognized range")
if actual_max > 1.:
max_val = 255.
else:
max_val = 1.
ndarray = (ndarray - min_val)
value_range = max_val - min_val
ndarray *= (255. / value_range)
ndarray = np.cast['uint8'](ndarray)
elif 'int' in str(ndarray.dtype):
if min_val is not None:
assert min_val == 0
else:
assert actual_min >= 0.
if max_val is not None:
assert max_val == 255
else:
assert actual_max <= 255.
else:
raise ValueError("Unrecognized dtype")
out = Image.fromarray(ndarray)
return out
|
[
"\n Converts an ndarray to a PIL image.\n :param ndarray: The numpy ndarray to convert\n :param min_val: The minimum pixel value in the image format\n :param max_val: The maximum pixel valie in the image format\n If min_val and max_val are not specified, attempts to\n infer whether the image is in any of the common ranges:\n [0, 1], [-1, 1], [0, 255]\n This can be ambiguous, so it is better to specify if known.\n "
] |
Please provide a description of the function:def make_grid(image_batch):
m, ir, ic, ch = image_batch.shape
pad = 3
padded = np.zeros((m, ir + pad * 2, ic + pad * 2, ch))
padded[:, pad:-pad, pad:-pad, :] = image_batch
m, ir, ic, ch = padded.shape
pr = int(np.sqrt(m))
pc = int(np.ceil(float(m) / pr))
extra_m = pr * pc
assert extra_m > m
padded = np.concatenate((padded, np.zeros((extra_m - m, ir, ic, ch))), axis=0)
row_content = np.split(padded, pr)
row_content = [np.split(content, pc) for content in row_content]
rows = [np.concatenate(content, axis=2) for content in row_content]
grid = np.concatenate(rows, axis=1)
assert grid.shape[0] == 1, grid.shape
grid = grid[0]
return grid
|
[
"\n Turns a batch of images into one big image.\n :param image_batch: ndarray, shape (batch_size, rows, cols, channels)\n :returns : a big image containing all `batch_size` images in a grid\n "
] |
Please provide a description of the function:def generate_np(self, x_val, **kwargs):
tfe = tf.contrib.eager
x = tfe.Variable(x_val)
adv_x = self.generate(x, **kwargs)
return adv_x.numpy()
|
[
"\n Generate adversarial examples and return them as a NumPy array.\n\n :param x_val: A NumPy array with the original inputs.\n :param **kwargs: optional parameters used by child classes.\n :return: A NumPy array holding the adversarial examples.\n "
] |
Please provide a description of the function:def generate(self, x, **kwargs):
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
labels, _nb_classes = self.get_or_guess_labels(x, kwargs)
return self.fgm(x, labels=labels, targeted=(self.y_target is not None))
|
[
"\n Generates the adversarial sample for the given input.\n :param x: The model's inputs.\n :param eps: (optional float) attack step size (input variation)\n :param ord: (optional) Order of the norm (mimics NumPy).\n Possible values: np.inf, 1 or 2.\n :param y: (optional) A tf variable` with the model labels. Only provide\n this parameter if you'd like to use true labels when crafting\n adversarial samples. Otherwise, model predictions are used as\n labels to avoid the \"label leaking\" effect (explained in this\n paper: https://arxiv.org/abs/1611.01236). Default is None.\n Labels should be one-hot-encoded.\n :param y_target: (optional) A tf variable` with the labels to target.\n Leave y_target=None if y is also set.\n Labels should be one-hot-encoded.\n :param clip_min: (optional float) Minimum input component value\n :param clip_max: (optional float) Maximum input component value\n "
] |
Please provide a description of the function:def fgm(self, x, labels, targeted=False):
# Compute loss
with tf.GradientTape() as tape:
# input should be watched because it may be
# combination of trainable and non-trainable variables
tape.watch(x)
loss_obj = LossCrossEntropy(self.model, smoothing=0.)
loss = loss_obj.fprop(x=x, y=labels)
if targeted:
loss = -loss
# Define gradient of loss wrt input
grad = tape.gradient(loss, x)
optimal_perturbation = attacks.optimize_linear(grad, self.eps, self.ord)
# Add perturbation to original example to obtain adversarial example
adv_x = x + optimal_perturbation
# If clipping is needed
# reset all values outside of [clip_min, clip_max]
if (self.clip_min is not None) and (self.clip_max is not None):
adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)
return adv_x
|
[
"\n TensorFlow Eager implementation of the Fast Gradient Method.\n :param x: the input variable\n :param targeted: Is the attack targeted or untargeted? Untargeted, the\n default, will try to make the label incorrect.\n Targeted will instead try to move in the direction\n of being more like y.\n :return: a tensor for the adversarial example\n "
] |
Please provide a description of the function:def random_feed_dict(rng, placeholders):
output = {}
for placeholder in placeholders:
if placeholder.dtype != 'float32':
raise NotImplementedError()
value = rng.randn(*placeholder.shape).astype('float32')
output[placeholder] = value
return output
|
[
"\n Returns random data to be used with `feed_dict`.\n :param rng: A numpy.random.RandomState instance\n :param placeholders: List of tensorflow placeholders\n :return: A dict mapping placeholders to random numpy values\n "
] |
Please provide a description of the function:def list_files(suffix=""):
cleverhans_path = os.path.abspath(cleverhans.__path__[0])
# In some environments cleverhans_path does not point to a real directory.
# In such case return empty list.
if not os.path.isdir(cleverhans_path):
return []
repo_path = os.path.abspath(os.path.join(cleverhans_path, os.pardir))
file_list = _list_files(cleverhans_path, suffix)
extra_dirs = ['cleverhans_tutorials', 'examples', 'scripts', 'tests_tf', 'tests_pytorch']
for extra_dir in extra_dirs:
extra_path = os.path.join(repo_path, extra_dir)
if os.path.isdir(extra_path):
extra_files = _list_files(extra_path, suffix)
extra_files = [os.path.join(os.pardir, path) for path in extra_files]
file_list = file_list + extra_files
return file_list
|
[
"\n Returns a list of all files in CleverHans with the given suffix.\n\n Parameters\n ----------\n suffix : str\n\n Returns\n -------\n\n file_list : list\n A list of all files in CleverHans whose filepath ends with `suffix`.\n "
] |
Please provide a description of the function:def _list_files(path, suffix=""):
if os.path.isdir(path):
incomplete = os.listdir(path)
complete = [os.path.join(path, entry) for entry in incomplete]
lists = [_list_files(subpath, suffix) for subpath in complete]
flattened = []
for one_list in lists:
for elem in one_list:
flattened.append(elem)
return flattened
else:
assert os.path.exists(path), "couldn't find file '%s'" % path
if path.endswith(suffix):
return [path]
return []
|
[
"\n Returns a list of all files ending in `suffix` contained within `path`.\n\n Parameters\n ----------\n path : str\n a filepath\n suffix : str\n\n Returns\n -------\n l : list\n A list of all files ending in `suffix` contained within `path`.\n (If `path` is a file rather than a directory, it is considered\n to \"contain\" itself)\n "
] |
Please provide a description of the function:def print_header(text):
print()
print('#'*(len(text)+4))
print('# ' + text + ' #')
print('#'*(len(text)+4))
print()
|
[
"Prints header with given text and frame composed of '#' characters."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.