text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_params(self):
""" Create all Variables to be returned later by get_params. By default this is a no-op. Models that need their fprop to be called for the... |
if self.needs_dummy_fprop:
if hasattr(self, "_dummy_input"):
return
self._dummy_input = self.make_input_placeholder()
self.fprop(self._dummy_input) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_lsh(self):
""" Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. """ |
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
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_train_knns(self, data_activations):
""" Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in th... |
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(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preds_conf_cred(self, knns_not_in_class):
""" Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, c... |
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.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fprop_np(self, data_np):
""" Performs a forward pass through the DkNN on an numpy array of data. """ |
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_labe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fprop(self, x):
""" Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. """ |
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support.""" |
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_lanczos_params(self):
"""Computes matrices T and V using the Lanczos algorithm. Args: k: number of iterations and dimensionality of the tridiagonal... |
# 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_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_differentiable_objective(self):
"""Function that constructs minimization objective from dual variables.""" |
# 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]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_full_psd_matrix(self):
"""Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corre... |
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]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_certificate(self, current_step, feed_dictionary):
""" Function to compute the certificate based either current value or dual variables loaded from du... |
feed_dict = feed_dictionary.copy()
nu = feed_dict[self.nu]
second_term = self.make_m_psd(nu, feed_dict)
tf.logging.info('Nu after modifying: ' + str(second_term))
feed_dict.update({self.nu: second_term})
computed_certificate = self.sess.run(self.unconstrained_objective, feed_dict=feed_dict)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_extract_command_template(filename):
"""Returns extraction command based on the filename extension.""" |
for k, v in iteritems(EXTRACT_COMMAND):
if filename.endswith(k):
return v
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell_call(command, **kwargs):
"""Calls shell command with parameter substitution. Args: command: command to run as a list of tokens **kwargs: dirctionary wi... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody. Args: dirname: name of the directory Returns: True if operation was ... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_submission(self, filename):
"""Extracts submission and moves it into self._extracted_submission_dir.""" |
# 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 = g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verify_docker_image_size(self, image_name):
"""Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is wit... |
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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_sample_data(self, submission_type):
"""Prepares sample data for the submission. Args: submission_type: type of the submission. """ |
# 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verify_output(self, submission_type):
"""Verifies correctness of the submission output. Args: submission_type: type of the submission Returns: True if outpu... |
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_classifi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_submission(self, filename):
"""Validates submission. Args: filename: submission filename Returns: submission metadata or None if submission is inval... |
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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, path):
"""Save loss in json format """ |
json.dump(dict(loss=self.__class__.__name__,
params=self.hparams),
open(os.path.join(path, 'loss.json'), 'wb')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_np(self, x_val, **kwargs):
""" Generate adversarial examples and return them as a NumPy array. :param x_val: A NumPy array with the original inputs.... |
tfe = tf.contrib.eager
x = tfe.Variable(x_val)
adv_x = self.generate(x, **kwargs)
return adv_x.numpy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_files(suffix=""):
""" Returns a list of all files in CleverHans with the given suffix. Parameters suffix : str Returns ------- file_list : list A list o... |
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 = _lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _list_files(path, suffix=""):
""" Returns a list of all files ending in `suffix` contained within `path`. Parameters path : str a filepath suffix : str Retur... |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file.""" |
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args):
"""Main function which runs master.""" |
if args.blacklisted_submissions:
logging.warning('BLACKLISTED SUBMISSIONS: %s',
args.blacklisted_submissions)
if args.limited_dataset:
logging.info('Using limited dataset: 3 batches * 10 images')
max_dataset_num_images = 30
batch_size = 10
else:
logging.info('Using full da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ask_when_work_is_populated(self, work):
"""When work is already populated asks whether we should continue. This method prints warning message that work is po... |
work.read_all_from_datastore()
if work.work:
print('Work is already written to datastore.\n'
'If you continue these data will be overwritten and '
'possible corrupted.')
inp = input_str('Do you want to continue? '
'(type "yes" without quotes to confirm)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_attacks(self):
"""Prepares all data needed for evaluation of attacks.""" |
print_header('PREPARING ATTACKS DATA')
# verify that attacks data not written yet
if not self.ask_when_work_is_populated(self.attack_work):
return
self.attack_work = eval_lib.AttackWorkPieces(
datastore_client=self.datastore_client)
# prepare submissions
print_header('Initializing... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_defenses(self):
"""Prepares all data needed for evaluation of defenses.""" |
print_header('PREPARING DEFENSE DATA')
# verify that defense data not written yet
if not self.ask_when_work_is_populated(self.defense_work):
return
self.defense_work = eval_lib.DefenseWorkPieces(
datastore_client=self.datastore_client)
# load results of attacks
self.submissions.in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_work_results(self, run_stats, scores, num_processed_images, filename):
"""Saves statistics about each submission. Saved statistics include score; numbe... |
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(
['SubmissionID', 'ExternalSubmissionId', 'Score',
'CompletedBatches', 'BatchesWithError', 'ProcessedImages',
'MinEvalTime', 'MaxEvalTime',
'MedianEvalTime', 'MeanEvalTime',
'Erro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_dataset_metadata(self):
"""Reads dataset metadata. Returns: instance of DatasetMetadata """ |
blob = self.storage_client.get_blob(
'dataset/' + self.dataset_name + '_dataset.csv')
buf = BytesIO()
blob.download_to_file(buf)
buf.seek(0)
return eval_lib.DatasetMetadata(buf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _show_status_for_work(self, work):
"""Shows status for given work pieces. Args: work: instance of either AttackWorkPieces or DefenseWorkPieces """ |
work_count = len(work.work)
work_completed = {}
work_completed_count = 0
for v in itervalues(work.work):
if v['is_completed']:
work_completed_count += 1
worker_id = v['claimed_worker_id']
if worker_id not in work_completed:
work_completed[worker_id] = {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _export_work_errors(self, work, output_file):
"""Saves errors for given work pieces into file. Args: work: instance of either AttackWorkPieces or DefenseWork... |
errors = set()
for v in itervalues(work.work):
if v['is_completed'] and v['error'] is not None:
errors.add(v['error'])
with open(output_file, 'w') as f:
for e in sorted(errors):
f.write(e)
f.write('\n') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_status(self):
"""Shows current status of competition evaluation. Also this method saves error messages generated by attacks and defenses into attack_err... |
print_header('Attack work statistics')
self.attack_work.read_all_from_datastore()
self._show_status_for_work(self.attack_work)
self._export_work_errors(
self.attack_work,
os.path.join(self.results_dir, 'attack_errors.txt'))
print_header('Defense work statistics')
self.defense_wo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_failed_attacks(self):
"""Cleans up data of failed attacks.""" |
print_header('Cleaning up failed attacks')
attacks_to_replace = {}
self.attack_work.read_all_from_datastore()
failed_submissions = set()
error_msg = set()
for k, v in iteritems(self.attack_work.work):
if v['error'] is not None:
attacks_to_replace[k] = dict(v)
failed_submis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_attacks_with_zero_images(self):
"""Cleans up data about attacks which generated zero images.""" |
print_header('Cleaning up attacks which generated 0 images.')
# find out attack work to cleanup
self.adv_batches.init_from_datastore()
self.attack_work.read_all_from_datastore()
new_attack_work = {}
affected_adversarial_batches = set()
for work_id, work in iteritems(self.attack_work.work):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cleanup_keys_with_confirmation(self, keys_to_delete):
"""Asks confirmation and then deletes entries with keys. Args: keys_to_delete: list of datastore keys ... |
print('Round name: ', self.round_name)
print('Number of entities to be deleted: ', len(keys_to_delete))
if not keys_to_delete:
return
if self.verbose:
print('Entities to delete:')
idx = 0
prev_key_prefix = None
dots_printed_after_same_prefix = False
for k in keys_to_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_defenses(self):
"""Cleans up all data about defense work in current round.""" |
print_header('CLEANING UP DEFENSES DATA')
work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')
keys_to_delete = [
e.key
for e in self.datastore_client.query_fetch(kind=u'ClassificationBatch')
] + [
e.key
for e in self.datastore_client.query_fetch(kind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_datastore(self):
"""Cleans up datastore and deletes all information about current round.""" |
print_header('CLEANING UP ENTIRE DATASTORE')
kinds_to_delete = [u'Submission', u'SubmissionType',
u'DatasetImage', u'DatasetBatch',
u'AdversarialImage', u'AdversarialBatch',
u'Work', u'WorkType',
u'ClassificationBatch']... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
""" Create a multi-GPU model similar to the basic cnn in the tutorials. """ |
model = make_basic_cnn()
layers = model.layers
model = MLPnGPU(nb_classes, layers, input_shape)
return model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_cost(self, labels, logits):
""" Build the graph for cost from the logits if logits are provided. If predictions are provided, logits are extracted from... |
op = logits.op
if "softmax" in str(op).lower():
logits, = op.inputs
with tf.variable_scope('costs'):
xent = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
cost = tf.reduce_mean(xent, name='xent')
cost += self._decay()
cost = cost
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _layer_norm(self, name, x):
"""Layer normalization.""" |
if self.init_layers:
bn = LayerNorm()
bn.name = name
self.layers += [bn]
else:
bn = self.layers[self.layer_idx]
self.layer_idx += 1
bn.device_name = self.device_name
bn.set_training(self.training)
x = bn.fprop(x)
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bottleneck_residual(self, x, in_filter, out_filter, stride, activate_before_residual=False):
"""Bottleneck residual unit with 3 sub layers.""" |
if activate_before_residual:
with tf.variable_scope('common_bn_relu'):
x = self._layer_norm('init_bn', x)
x = self._relu(x, self.hps.relu_leakiness)
orig_x = x
else:
with tf.variable_scope('residual_bn_relu'):
orig_x = x
x = self._layer_norm('init_bn', x)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_classification_results(storage_client, file_path):
"""Reads classification results from the file in Cloud Storage. This method reads file with classific... |
if storage_client:
# file on Cloud
success = False
retry_count = 0
while retry_count < 4:
try:
blob = storage_client.get_blob(file_path)
if not blob:
return {}
if blob.size > MAX_ALLOWED_CLASSIFICATION_RESULT_SIZE:
logging.warning('Skipping classifica... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze_one_classification_result(storage_client, file_path, adv_batch, dataset_batches, dataset_meta):
"""Reads and analyzes one classification result. This... |
class_result = read_classification_results(storage_client, file_path)
if class_result is None:
return 0, 0, 0, 0
adv_images = adv_batch['images']
dataset_batch_images = (
dataset_batches.data[adv_batch['dataset_batch_id']]['images'])
count_correctly_classified = 0
count_errors = 0
count_hit_tar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_to_file(self, filename, remap_dim0=None, remap_dim1=None):
"""Saves matrix to the file. Args: filename: name of the file where to save matrix remap_dim0... |
# rows - first index
# columns - second index
with open(filename, 'w') as fobj:
columns = list(sorted(self._dim1))
for col in columns:
fobj.write(',')
fobj.write(str(remap_dim1[col] if remap_dim1 else col))
fobj.write('\n')
for row in sorted(self._dim0):
fobj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_from_adversarial_batches_write_to_datastore(self, submissions, adv_batches):
"""Populates data from adversarial batches and writes to datastore. Args: s... |
# prepare classification batches
idx = 0
for s_id in iterkeys(submissions.defenses):
for adv_id in iterkeys(adv_batches.data):
class_batch_id = CLASSIFICATION_BATCH_ID_PATTERN.format(idx)
idx += 1
self.data[class_batch_id] = {
'adversarial_batch_id': adv_id,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_from_datastore(self):
"""Initializes data by reading it from the datastore.""" |
self._data = {}
client = self._datastore_client
for entity in client.query_fetch(kind=KIND_CLASSIFICATION_BATCH):
class_batch_id = entity.key.flat_path[-1]
self.data[class_batch_id] = dict(entity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_batch_from_datastore(self, class_batch_id):
"""Reads and returns single batch from the datastore.""" |
client = self._datastore_client
key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id)
result = client.get(key)
if result is not None:
return dict(result)
else:
raise KeyError(
'Key {0} not found in the datastore'.format(key.flat_path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_classification_results(self, adv_batches, dataset_batches, dataset_meta, defense_work=None):
"""Computes classification results. Args: adv_batches: i... |
class_batch_to_work = {}
if defense_work:
for v in itervalues(defense_work.work):
class_batch_to_work[v['output_classification_batch_id']] = v
# accuracy_matrix[defense_id, attack_id] = num correctly classified
accuracy_matrix = ResultMatrix()
# error_matrix[defense_id, attack_id] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def participant_from_submission_path(submission_path):
"""Parses type of participant based on submission filename. Args: submission_path: path to the submission ... |
basename = os.path.basename(submission_path)
file_ext = None
for e in ALLOWED_EXTENSIONS:
if basename.endswith(e):
file_ext = e
break
if not file_ext:
raise ValueError('Invalid submission path: ' + submission_path)
basename = basename[:-len(file_ext)]
if basename.isdigit():
return {... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_submissions_from_datastore_dir(self, dir_suffix, id_pattern):
"""Loads list of submissions from the directory. Args: dir_suffix: suffix of the director... |
submissions = self._storage_client.list_blobs(
prefix=os.path.join(self._round_name, dir_suffix))
return {
id_pattern.format(idx): SubmissionDescriptor(
path=s, participant_id=participant_from_submission_path(s))
for idx, s in enumerate(submissions)
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_from_storage_write_to_datastore(self):
"""Init list of sumibssions from Storage and saves them to Datastore. Should be called only once (typically by ma... |
# Load submissions
self._attacks = self._load_submissions_from_datastore_dir(
ATTACK_SUBDIR, ATTACK_ID_PATTERN)
self._targeted_attacks = self._load_submissions_from_datastore_dir(
TARGETED_ATTACK_SUBDIR, TARGETED_ATTACK_ID_PATTERN)
self._defenses = self._load_submissions_from_datastore_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_to_datastore(self):
"""Writes all submissions to datastore.""" |
# Populate datastore
roots_and_submissions = zip([ATTACKS_ENTITY_KEY,
TARGET_ATTACKS_ENTITY_KEY,
DEFENSES_ENTITY_KEY],
[self._attacks,
self._targeted_attacks,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_from_datastore(self):
"""Init list of submission from Datastore. Should be called by each worker during initialization. """ |
self._attacks = {}
self._targeted_attacks = {}
self._defenses = {}
for entity in self._datastore_client.query_fetch(kind=KIND_SUBMISSION):
submission_id = entity.key.flat_path[-1]
submission_path = entity['submission_path']
participant_id = {k: entity[k]
for k ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_by_id(self, submission_id):
"""Finds submission by ID. Args: submission_id: ID of the submission Returns: SubmissionDescriptor with information about su... |
return self._attacks.get(
submission_id,
self._defenses.get(
submission_id,
self._targeted_attacks.get(submission_id, None))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_external_id(self, submission_id):
"""Returns human readable submission external ID. Args: submission_id: internal submission ID. Returns: human readable ... |
submission = self.find_by_id(submission_id)
if not submission:
return None
if 'team_id' in submission.participant_id:
return submission.participant_id['team_id']
elif 'baseline_id' in submission.participant_id:
return 'baseline_' + submission.participant_id['baseline_id']
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_and_verify_metadata(self, submission_type):
"""Loads and verifies metadata. Args: submission_type: type of the submission Returns: dictionaty with meta... |
metadata_filename = os.path.join(self._extracted_submission_dir,
'metadata.json')
if not os.path.isfile(metadata_filename):
logging.error('metadata.json not found')
return None
try:
with open(metadata_filename, 'r') as f:
metadata = json.load(f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_submission(self, metadata):
"""Runs submission inside Docker container. Args: metadata: dictionary with submission metadata Returns: True if status code... |
if self._use_gpu:
docker_binary = 'nvidia-docker'
container_name = metadata['container_gpu']
else:
docker_binary = 'docker'
container_name = metadata['container']
if metadata['type'] == 'defense':
cmd = [docker_binary, 'run',
'--network=none',
'-m=24g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_pdf(path):
""" Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ |
pp = PdfPages(path)
pp.savefig(pyplot.gcf())
pp.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_shift(x, pad=(4, 4), mode='REFLECT'):
"""Pad a single image and then crop to the original size with a random offset.""" |
assert mode in 'REFLECT SYMMETRIC CONSTANT'.split()
assert x.get_shape().ndims == 3
xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode)
return tf.random_crop(xp, tf.shape(x)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_crop_and_flip(x, pad_rows=4, pad_cols=4):
"""Augment a batch by randomly cropping and horizontally flipping it.""" |
rows = tf.shape(x)[1]
cols = tf.shape(x)[2]
channels = x.get_shape()[3]
def _rand_crop_img(img):
"""Randomly crop an individual image"""
return tf.random_crop(img, [rows, cols, channels])
# Some of these ops are only on CPU.
# This function will often be called with the device set to GPU.
# We ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _project_perturbation(perturbation, epsilon, input_image, clip_min=None, clip_max=None):
"""Project `perturbation` onto L-infinity ball of radius `epsilon`. ... |
if clip_min is None or clip_max is None:
raise NotImplementedError("_project_perturbation currently has clipping "
"hard-coded in.")
# Ensure inputs are in the correct range
with tf.control_dependencies([
utils_tf.assert_less_equal(input_image,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None):
"""Computes difference between logit for `label` and next highest logit. The loss is... |
if num_classes is not None:
warnings.warn("`num_classes` is depreciated. Switch to `nb_classes`."
" `num_classes` may be removed on or after 2019-04-23.")
nb_classes = num_classes
del num_classes
if 'int' in str(label.dtype):
logit_mask = tf.one_hot(label, depth=nb_classes, axis=-... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute a new value of `x` to minimize `loss_fn`. Args: loss_fn: a callable that takes `x`, a ba... |
# Assumes `x` is a list,
# and contains a tensor representing a batch of images
assert len(x) == 1 and isinstance(x, list), \
'x should be a list and contain only one image tensor'
x = x[0]
loss = reduce_mean(loss_fn(x), axis=0)
return tf.gradients(loss, x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minimize(self, loss_fn, x, optim_state):
""" Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list o... |
grads = self._compute_gradients(loss_fn, x, optim_state)
return self._apply_gradients(grads, x, optim_state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_state(self, x):
""" Initialize t, m, and u """ |
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_gradients(self, grads, x, optim_state):
"""Refer to parent class documentation.""" |
new_x = [None] * len(x)
new_optim_state = {
"t": optim_state["t"] + 1.,
"m": [None] * len(x),
"u": [None] * len(x)
}
t = new_optim_state["t"]
for i in xrange(len(x)):
g = grads[i]
m_old = optim_state["m"][i]
u_old = optim_state["u"][i]
new_optim_state... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute gradient estimates using SPSA.""" |
# Assumes `x` is a list, containing a [1, H, W, C] image
# If static batch dimension is None, tf.reshape to batch size 1
# so that static shape can be inferred
assert len(x) == 1
static_x_shape = x[0].get_shape().as_list()
if static_x_shape[0] is None:
x[0] = tf.reshape(x[0], [1] + static... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_submissions_from_directory(dirname, use_gpu):
"""Scans directory and read all submissions. Args: dirname: directory to scan. use_gpu: whether submission... |
result = []
for sub_dir in os.listdir(dirname):
submission_path = os.path.join(dirname, sub_dir)
try:
if not os.path.isdir(submission_path):
continue
if not os.path.exists(os.path.join(submission_path, 'metadata.json')):
continue
with open(os.path.join(submission_path, 'me... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_defense_output(filename):
"""Loads output of defense from given file.""" |
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if image_filename.endswith('.png') or image_filename.endswith('.jpg'):
image_filename = image_filename[:image_filename.rfind('.')]
label = int(row[1])
except (IndexError, V... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Run all attacks against all defenses and compute results. """ |
args = parse_args()
attacks_output_dir = os.path.join(args.intermediate_results_dir,
'attacks_output')
targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir,
'targeted_attacks_output')
defenses_output_dir = os.p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_dataset_clipping(self, dataset_dir, epsilon):
"""Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the da... |
self.dataset_max_clip = {}
self.dataset_min_clip = {}
self._dataset_image_count = 0
for fname in os.listdir(dataset_dir):
if not fname.endswith('.png'):
continue
image_id = fname[:-4]
image = np.array(
Image.open(os.path.join(dataset_dir, fname)).convert('RGB'))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
"""Clips results of attack and copy it to directory with all images. Args: attack_name: name of... |
if is_targeted:
self._targeted_attack_names.add(attack_name)
else:
self._attack_names.add(attack_name)
attack_dir = os.path.join(self.targeted_attacks_output_dir
if is_targeted
else self.attacks_output_dir,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_target_classes(self, filename):
"""Saves target classed for all dataset images into given file.""" |
with open(filename, 'w') as f:
for k, v in self._target_classes.items():
f.write('{0}.png,{1}\n'.format(k, v)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small... |
noise_attack = Noise(model, sess)
pgd_attack = ProjectedGradientDescent(model, sess)
threat_params = {"eps": eps, "clip_min": clip_min, "clip_max": clip_max}
noise_attack_config = AttackConfig(noise_attack, threat_params, "noise")
attack_configs = [noise_attack_config]
pgd_attack_configs = []
pgd_params ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_search_max_confidence_recipe(sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000):
"""Max confidenc... |
noise_attack = Noise(model, sess)
threat_params = {"eps": eps, "clip_min": clip_min, "clip_max": clip_max}
noise_attack_config = AttackConfig(noise_attack, threat_params)
attack_configs = [noise_attack_config]
assert batch_size % num_devices == 0
new_work_goal = {noise_attack_config: num_noise_points}
go... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
""" Runs attack bundling. Us... |
assert isinstance(sess, tf.Session)
assert isinstance(model, Model)
assert all(isinstance(attack_config, AttackConfig) for attack_config
in attack_configs)
assert all(isinstance(goal, AttackGoal) for goal in goals)
assert isinstance(report_path, six.string_types)
if x.shape[0] != y.shape[0]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_... |
goal.start(run_counts)
_logger.info("Running criteria for new goal...")
criteria = goal.get_criteria(sess, model, adv_x, y, batch_size=eval_batch_size)
assert 'correctness' in criteria
_logger.info("Accuracy: " + str(criteria['correctness'].mean()))
assert 'confidence' in criteria
while not goal.is_satis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE):
""" Runs at... |
attack_config = goal.get_attack_config(attack_configs, run_counts, criteria)
idxs = goal.request_examples(attack_config, criteria, run_counts,
attack_batch_size)
x_batch = x[idxs]
assert x_batch.shape[0] == attack_batch_size
y_batch = y[idxs]
assert y_batch.shape[0] == attack... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE):
""" A post-processor version of attack bundling, that choose... |
# Check the input
num_attacks = len(adv_x_list)
assert num_attacks > 0
adv_x_0 = adv_x_list[0]
assert isinstance(adv_x_0, np.ndarray)
assert all(adv_x.shape == adv_x_0.shape for adv_x in adv_x_list)
# Allocate the output
out = np.zeros_like(adv_x_0)
m = adv_x_0.shape[0]
# Initialize with negative... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, nb_iter, report_path, spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES, spsa_iters=SP... |
spsa = SPSA(model, sess)
spsa_params = {"eps": eps, "clip_min" : clip_min, "clip_max" : clip_max,
"nb_iter": nb_iter, "spsa_samples": spsa_samples,
"spsa_iters": spsa_iters}
attack_configs = []
dev_batch_size = 1 # The only batch size supported by SPSA
batch_size = num_devic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE):
""" Returns a dictionary mapping the name of each criterion to a NumPy array containing the ... |
names, factory = self.extra_criteria()
factory = _CriteriaFactory(model, factory)
results = batch_eval_multi_worker(sess, factory, [advx, y],
batch_size=batch_size, devices=devices)
names = ['correctness', 'confidence'] + names
out = dict(safe_zip(names, resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_examples(self, attack_config, criteria, run_counts, batch_size):
""" Returns a numpy array of integer example indices to run in the next batch. """ |
raise NotImplementedError(str(type(self)) +
"needs to implement request_examples") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, run_counts, criteria):
""" Return run counts only for examples that are still correctly classified """ |
correctness = criteria['correctness']
assert correctness.dtype == np.bool
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = filtered_counts[key][correctness]
return filtered_counts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, run_counts, criteria):
""" Return the counts for only those examples that are below the threshold """ |
wrong_confidence = criteria['wrong_confidence']
below_t = wrong_confidence <= self.t
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = filtered_counts[key][below_t]
return filtered_counts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clip_image(image, clip_min, clip_max):
""" Clip an image, or an image batch, with upper and lower threshold. """ |
return np.minimum(np.maximum(clip_min, image), clip_max) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_distance(x_ori, x_pert, constraint='l2'):
""" Compute the distance between two images. """ |
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'linf':
dist = np.max(abs(x_ori - x_pert))
return dist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max):
""" Gradient direction estimation """ |
# Generate random vectors.
noise_shape = [num_evals] + list(shape)
if constraint == 'l2':
rv = np.random.randn(*noise_shape)
elif constraint == 'linf':
rv = np.random.uniform(low=-1, high=1, size=noise_shape)
axis = tuple(range(1, 1 + len(shape)))
rv = rv / np.sqrt(np.sum(rv ** 2, axis=axis, keepd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta):
""" Binary search to approach the boundary. """ |
# Compute distance between each of perturbed image and original image.
dists_post_update = np.array([
compute_distance(
original_image,
perturbed_image,
constraint
)
for perturbed_image in perturbed_images])
# Choose upper thresholds in binary searchs based on co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize(decision_function, sample, shape, clip_min, clip_max):
""" Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ |
success = 0
num_evals = 0
# Find a misclassified random noise.
while True:
random_noise = np.random.uniform(clip_min, clip_max, size=shape)
success = decision_function(random_noise[None])[0]
if success:
break
num_evals += 1
message = "Initialization failed! Try to use a misclassified... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration):
""" Geometric progression to search for stepsize. Keep decreasing ... |
epsilon = dist / np.sqrt(current_iteration)
while True:
updated = x + epsilon * update
success = decision_function(updated[None])[0]
if success:
break
else:
epsilon = epsilon / 2.0
return epsilon |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint):
""" Choose the delta at the scale of distance between x and pert... |
if current_iteration == 1:
delta = 0.1 * (clip_max - clip_min)
else:
if constraint == 'l2':
delta = np.sqrt(d) * theta * dist_post_update
elif constraint == 'linf':
delta = d * theta * dist_post_update
return delta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attack_single_step(self, x, eta, g_feat):
""" TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient M... |
adv_x = x + eta
a_feat = self.model.fprop(adv_x)[self.layer]
# feat.shape = (batch, c) or (batch, w, h, c)
axis = list(range(1, len(a_feat.shape)))
# Compute loss
# This is a targeted attack, hence the negative sign
loss = -reduce_sum(tf.square(a_feat - g_feat), axis)
# Define gradi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
"""Builds the 35x35 resnet block.""" |
with tf.variable_scope(scope, 'Block35', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')
tower_conv1_1 = slim.conv2d(tower_con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
"""Builds the 17x17 resnet block.""" |
with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1')
tower_conv1_1 = slim.conv2d(tower_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_class... |
if num_classes is not None:
warnings.warn("`num_classes` is deprecated. Switch to `nb_classes`."
" `num_classes` may be removed on or after 2019-04-23.")
nb_classes = num_classes
del num_classes
end_points = {}
with tf.variable_scope(scope, 'InceptionResnetV2', [inputs, nb_classes]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001):
"""Returns the scope with the default parameters for ... |
# Set weight_decay for weights in conv2d and fully_connected layers.
with slim.arg_scope([slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay),
biases_regularizer=slim.l2_regularizer(weight_decay)):
batch_norm_params = {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args):
"""Validate all submissions and copy them into place""" |
random.seed()
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
validator = SubmissionValidator(
source_dir=args.source_dir,
target_dir=args.target_dir,
temp_dir=temp_dir,
do_copy=args.copy,
use_gpu=args.use_gpu,
containers_file=args.con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_stat(self, submission_type, increase_success, increase_fail):
"""Common method to update submission statistics.""" |
stat = self.stats.get(submission_type, (0, 0))
stat = (stat[0] + increase_success, stat[1] + increase_fail)
self.stats[submission_type] = stat |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_stats(self):
"""Print statistics into log.""" |
logging.info('Validation statistics: ')
for k, v in iteritems(self.stats):
logging.info('%s - %d valid out of %d total submissions',
k, v[0], v[0] + v[1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.