repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
ExecutableSubmission.download
|
def download(self):
"""Method which downloads submission to local directory."""
# Structure of the download directory:
# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id
# submission_dir/s.ext <-- archived submission
# submission_dir/extracted <-- extracted submission
# Check whether submission is already there
if self.extracted_submission_dir:
return
self.submission_dir = os.path.join(LOCAL_SUBMISSIONS_DIR,
self.submission_id)
if (os.path.isdir(self.submission_dir)
and os.path.isdir(os.path.join(self.submission_dir, 'extracted'))):
# submission already there, just re-read metadata
self.extracted_submission_dir = os.path.join(self.submission_dir,
'extracted')
with open(os.path.join(self.extracted_submission_dir, 'metadata.json'),
'r') as f:
meta_json = json.load(f)
self.container_name = str(meta_json[METADATA_CONTAINER])
self.entry_point = str(meta_json[METADATA_ENTRY_POINT])
return
# figure out submission location in the Cloud and determine extractor
submission_cloud_path = os.path.join('gs://', self.storage_bucket,
self.submission.path)
extract_command_tmpl = None
extension = None
for k, v in iteritems(EXTRACT_COMMAND):
if submission_cloud_path.endswith(k):
extension = k
extract_command_tmpl = v
break
if not extract_command_tmpl:
raise WorkerError('Unsupported submission extension')
# download archive
try:
os.makedirs(self.submission_dir)
tmp_extract_dir = os.path.join(self.submission_dir, 'tmp')
os.makedirs(tmp_extract_dir)
download_path = os.path.join(self.submission_dir, 's' + extension)
try:
logging.info('Downloading submission from %s to %s',
submission_cloud_path, download_path)
shell_call(['gsutil', 'cp', submission_cloud_path, download_path])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t copy submission locally', e)
# extract archive
try:
shell_call(extract_command_tmpl,
src=download_path, dst=tmp_extract_dir)
except subprocess.CalledProcessError as e:
# proceed even if extraction returned non zero error code,
# sometimes it's just warning
logging.warning('Submission extraction returned non-zero error code. '
'It may be just a warning, continuing execution. '
'Error: %s', e)
try:
make_directory_writable(tmp_extract_dir)
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t make submission directory writable', e)
# determine root of the submission
tmp_root_dir = tmp_extract_dir
root_dir_content = [d for d in os.listdir(tmp_root_dir)
if d != '__MACOSX']
if (len(root_dir_content) == 1
and os.path.isdir(os.path.join(tmp_root_dir, root_dir_content[0]))):
tmp_root_dir = os.path.join(tmp_root_dir, root_dir_content[0])
# move files to extract subdirectory
self.extracted_submission_dir = os.path.join(self.submission_dir,
'extracted')
try:
shell_call(['mv', os.path.join(tmp_root_dir),
self.extracted_submission_dir])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t move submission files', e)
# read metadata file
try:
with open(os.path.join(self.extracted_submission_dir, 'metadata.json'),
'r') as f:
meta_json = json.load(f)
except IOError as e:
raise WorkerError(
'Can''t read metadata.json for submission "{0}"'.format(
self.submission_id),
e)
try:
self.container_name = str(meta_json[METADATA_CONTAINER])
self.entry_point = str(meta_json[METADATA_ENTRY_POINT])
type_from_meta = METADATA_JSON_TYPE_TO_TYPE[meta_json[METADATA_TYPE]]
except KeyError as e:
raise WorkerError('Invalid metadata.json file', e)
if type_from_meta != self.type:
raise WorkerError('Inconsistent submission type in metadata: '
+ type_from_meta + ' vs ' + self.type)
except WorkerError as e:
self.extracted_submission_dir = None
sudo_remove_dirtree(self.submission_dir)
raise
|
python
|
def download(self):
"""Method which downloads submission to local directory."""
# Structure of the download directory:
# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id
# submission_dir/s.ext <-- archived submission
# submission_dir/extracted <-- extracted submission
# Check whether submission is already there
if self.extracted_submission_dir:
return
self.submission_dir = os.path.join(LOCAL_SUBMISSIONS_DIR,
self.submission_id)
if (os.path.isdir(self.submission_dir)
and os.path.isdir(os.path.join(self.submission_dir, 'extracted'))):
# submission already there, just re-read metadata
self.extracted_submission_dir = os.path.join(self.submission_dir,
'extracted')
with open(os.path.join(self.extracted_submission_dir, 'metadata.json'),
'r') as f:
meta_json = json.load(f)
self.container_name = str(meta_json[METADATA_CONTAINER])
self.entry_point = str(meta_json[METADATA_ENTRY_POINT])
return
# figure out submission location in the Cloud and determine extractor
submission_cloud_path = os.path.join('gs://', self.storage_bucket,
self.submission.path)
extract_command_tmpl = None
extension = None
for k, v in iteritems(EXTRACT_COMMAND):
if submission_cloud_path.endswith(k):
extension = k
extract_command_tmpl = v
break
if not extract_command_tmpl:
raise WorkerError('Unsupported submission extension')
# download archive
try:
os.makedirs(self.submission_dir)
tmp_extract_dir = os.path.join(self.submission_dir, 'tmp')
os.makedirs(tmp_extract_dir)
download_path = os.path.join(self.submission_dir, 's' + extension)
try:
logging.info('Downloading submission from %s to %s',
submission_cloud_path, download_path)
shell_call(['gsutil', 'cp', submission_cloud_path, download_path])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t copy submission locally', e)
# extract archive
try:
shell_call(extract_command_tmpl,
src=download_path, dst=tmp_extract_dir)
except subprocess.CalledProcessError as e:
# proceed even if extraction returned non zero error code,
# sometimes it's just warning
logging.warning('Submission extraction returned non-zero error code. '
'It may be just a warning, continuing execution. '
'Error: %s', e)
try:
make_directory_writable(tmp_extract_dir)
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t make submission directory writable', e)
# determine root of the submission
tmp_root_dir = tmp_extract_dir
root_dir_content = [d for d in os.listdir(tmp_root_dir)
if d != '__MACOSX']
if (len(root_dir_content) == 1
and os.path.isdir(os.path.join(tmp_root_dir, root_dir_content[0]))):
tmp_root_dir = os.path.join(tmp_root_dir, root_dir_content[0])
# move files to extract subdirectory
self.extracted_submission_dir = os.path.join(self.submission_dir,
'extracted')
try:
shell_call(['mv', os.path.join(tmp_root_dir),
self.extracted_submission_dir])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t move submission files', e)
# read metadata file
try:
with open(os.path.join(self.extracted_submission_dir, 'metadata.json'),
'r') as f:
meta_json = json.load(f)
except IOError as e:
raise WorkerError(
'Can''t read metadata.json for submission "{0}"'.format(
self.submission_id),
e)
try:
self.container_name = str(meta_json[METADATA_CONTAINER])
self.entry_point = str(meta_json[METADATA_ENTRY_POINT])
type_from_meta = METADATA_JSON_TYPE_TO_TYPE[meta_json[METADATA_TYPE]]
except KeyError as e:
raise WorkerError('Invalid metadata.json file', e)
if type_from_meta != self.type:
raise WorkerError('Inconsistent submission type in metadata: '
+ type_from_meta + ' vs ' + self.type)
except WorkerError as e:
self.extracted_submission_dir = None
sudo_remove_dirtree(self.submission_dir)
raise
|
[
"def",
"download",
"(",
"self",
")",
":",
"# Structure of the download directory:",
"# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id",
"# submission_dir/s.ext <-- archived submission",
"# submission_dir/extracted <-- extracted submission",
"# Check whether submission is already there",
"if",
"self",
".",
"extracted_submission_dir",
":",
"return",
"self",
".",
"submission_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_SUBMISSIONS_DIR",
",",
"self",
".",
"submission_id",
")",
"if",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"submission_dir",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'extracted'",
")",
")",
")",
":",
"# submission already there, just re-read metadata",
"self",
".",
"extracted_submission_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'extracted'",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"extracted_submission_dir",
",",
"'metadata.json'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"meta_json",
"=",
"json",
".",
"load",
"(",
"f",
")",
"self",
".",
"container_name",
"=",
"str",
"(",
"meta_json",
"[",
"METADATA_CONTAINER",
"]",
")",
"self",
".",
"entry_point",
"=",
"str",
"(",
"meta_json",
"[",
"METADATA_ENTRY_POINT",
"]",
")",
"return",
"# figure out submission location in the Cloud and determine extractor",
"submission_cloud_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'gs://'",
",",
"self",
".",
"storage_bucket",
",",
"self",
".",
"submission",
".",
"path",
")",
"extract_command_tmpl",
"=",
"None",
"extension",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"EXTRACT_COMMAND",
")",
":",
"if",
"submission_cloud_path",
".",
"endswith",
"(",
"k",
")",
":",
"extension",
"=",
"k",
"extract_command_tmpl",
"=",
"v",
"break",
"if",
"not",
"extract_command_tmpl",
":",
"raise",
"WorkerError",
"(",
"'Unsupported submission extension'",
")",
"# download archive",
"try",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"submission_dir",
")",
"tmp_extract_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'tmp'",
")",
"os",
".",
"makedirs",
"(",
"tmp_extract_dir",
")",
"download_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'s'",
"+",
"extension",
")",
"try",
":",
"logging",
".",
"info",
"(",
"'Downloading submission from %s to %s'",
",",
"submission_cloud_path",
",",
"download_path",
")",
"shell_call",
"(",
"[",
"'gsutil'",
",",
"'cp'",
",",
"submission_cloud_path",
",",
"download_path",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t copy submission locally'",
",",
"e",
")",
"# extract archive",
"try",
":",
"shell_call",
"(",
"extract_command_tmpl",
",",
"src",
"=",
"download_path",
",",
"dst",
"=",
"tmp_extract_dir",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"# proceed even if extraction returned non zero error code,",
"# sometimes it's just warning",
"logging",
".",
"warning",
"(",
"'Submission extraction returned non-zero error code. '",
"'It may be just a warning, continuing execution. '",
"'Error: %s'",
",",
"e",
")",
"try",
":",
"make_directory_writable",
"(",
"tmp_extract_dir",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t make submission directory writable'",
",",
"e",
")",
"# determine root of the submission",
"tmp_root_dir",
"=",
"tmp_extract_dir",
"root_dir_content",
"=",
"[",
"d",
"for",
"d",
"in",
"os",
".",
"listdir",
"(",
"tmp_root_dir",
")",
"if",
"d",
"!=",
"'__MACOSX'",
"]",
"if",
"(",
"len",
"(",
"root_dir_content",
")",
"==",
"1",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmp_root_dir",
",",
"root_dir_content",
"[",
"0",
"]",
")",
")",
")",
":",
"tmp_root_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_root_dir",
",",
"root_dir_content",
"[",
"0",
"]",
")",
"# move files to extract subdirectory",
"self",
".",
"extracted_submission_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'extracted'",
")",
"try",
":",
"shell_call",
"(",
"[",
"'mv'",
",",
"os",
".",
"path",
".",
"join",
"(",
"tmp_root_dir",
")",
",",
"self",
".",
"extracted_submission_dir",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t move submission files'",
",",
"e",
")",
"# read metadata file",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"extracted_submission_dir",
",",
"'metadata.json'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"meta_json",
"=",
"json",
".",
"load",
"(",
"f",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t read metadata.json for submission \"{0}\"'",
".",
"format",
"(",
"self",
".",
"submission_id",
")",
",",
"e",
")",
"try",
":",
"self",
".",
"container_name",
"=",
"str",
"(",
"meta_json",
"[",
"METADATA_CONTAINER",
"]",
")",
"self",
".",
"entry_point",
"=",
"str",
"(",
"meta_json",
"[",
"METADATA_ENTRY_POINT",
"]",
")",
"type_from_meta",
"=",
"METADATA_JSON_TYPE_TO_TYPE",
"[",
"meta_json",
"[",
"METADATA_TYPE",
"]",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Invalid metadata.json file'",
",",
"e",
")",
"if",
"type_from_meta",
"!=",
"self",
".",
"type",
":",
"raise",
"WorkerError",
"(",
"'Inconsistent submission type in metadata: '",
"+",
"type_from_meta",
"+",
"' vs '",
"+",
"self",
".",
"type",
")",
"except",
"WorkerError",
"as",
"e",
":",
"self",
".",
"extracted_submission_dir",
"=",
"None",
"sudo_remove_dirtree",
"(",
"self",
".",
"submission_dir",
")",
"raise"
] |
Method which downloads submission to local directory.
|
[
"Method",
"which",
"downloads",
"submission",
"to",
"local",
"directory",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L211-L309
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
ExecutableSubmission.temp_copy_extracted_submission
|
def temp_copy_extracted_submission(self):
"""Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary copy
of submission is deleted.
Returns:
directory where temporary copy is located
"""
tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy')
shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir),
tmp_copy_dir])
return tmp_copy_dir
|
python
|
def temp_copy_extracted_submission(self):
"""Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary copy
of submission is deleted.
Returns:
directory where temporary copy is located
"""
tmp_copy_dir = os.path.join(self.submission_dir, 'tmp_copy')
shell_call(['cp', '-R', os.path.join(self.extracted_submission_dir),
tmp_copy_dir])
return tmp_copy_dir
|
[
"def",
"temp_copy_extracted_submission",
"(",
"self",
")",
":",
"tmp_copy_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'tmp_copy'",
")",
"shell_call",
"(",
"[",
"'cp'",
",",
"'-R'",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"extracted_submission_dir",
")",
",",
"tmp_copy_dir",
"]",
")",
"return",
"tmp_copy_dir"
] |
Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary copy
of submission is deleted.
Returns:
directory where temporary copy is located
|
[
"Creates",
"a",
"temporary",
"copy",
"of",
"extracted",
"submission",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L311-L325
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
ExecutableSubmission.run_without_time_limit
|
def run_without_time_limit(self, cmd):
"""Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission
"""
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd
logging.info('Docker command: %s', ' '.join(cmd))
start_time = time.time()
retval = subprocess.call(cmd)
elapsed_time_sec = int(time.time() - start_time)
logging.info('Elapsed time of attack: %d', elapsed_time_sec)
logging.info('Docker retval: %d', retval)
if retval != 0:
logging.warning('Docker returned non-zero retval: %d', retval)
raise WorkerError('Docker returned non-zero retval ' + str(retval))
return elapsed_time_sec
|
python
|
def run_without_time_limit(self, cmd):
"""Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission
"""
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME] + cmd
logging.info('Docker command: %s', ' '.join(cmd))
start_time = time.time()
retval = subprocess.call(cmd)
elapsed_time_sec = int(time.time() - start_time)
logging.info('Elapsed time of attack: %d', elapsed_time_sec)
logging.info('Docker retval: %d', retval)
if retval != 0:
logging.warning('Docker returned non-zero retval: %d', retval)
raise WorkerError('Docker returned non-zero retval ' + str(retval))
return elapsed_time_sec
|
[
"def",
"run_without_time_limit",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"[",
"DOCKER_BINARY",
",",
"'run'",
",",
"DOCKER_NVIDIA_RUNTIME",
"]",
"+",
"cmd",
"logging",
".",
"info",
"(",
"'Docker command: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"retval",
"=",
"subprocess",
".",
"call",
"(",
"cmd",
")",
"elapsed_time_sec",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"logging",
".",
"info",
"(",
"'Elapsed time of attack: %d'",
",",
"elapsed_time_sec",
")",
"logging",
".",
"info",
"(",
"'Docker retval: %d'",
",",
"retval",
")",
"if",
"retval",
"!=",
"0",
":",
"logging",
".",
"warning",
"(",
"'Docker returned non-zero retval: %d'",
",",
"retval",
")",
"raise",
"WorkerError",
"(",
"'Docker returned non-zero retval '",
"+",
"str",
"(",
"retval",
")",
")",
"return",
"elapsed_time_sec"
] |
Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission
|
[
"Runs",
"docker",
"command",
"without",
"time",
"limit",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L327-L350
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
ExecutableSubmission.run_with_time_limit
|
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
"""Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission
"""
if time_limit < 0:
return self.run_without_time_limit(cmd)
container_name = str(uuid.uuid4())
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME,
'--detach', '--name', container_name] + cmd
logging.info('Docker command: %s', ' '.join(cmd))
logging.info('Time limit %d seconds', time_limit)
retval = subprocess.call(cmd)
start_time = time.time()
elapsed_time_sec = 0
while is_docker_still_running(container_name):
elapsed_time_sec = int(time.time() - start_time)
if elapsed_time_sec < time_limit:
time.sleep(1)
else:
kill_docker_container(container_name)
logging.warning('Submission was killed because run out of time')
logging.info('Elapsed time of submission: %d', elapsed_time_sec)
logging.info('Docker retval: %d', retval)
if retval != 0:
logging.warning('Docker returned non-zero retval: %d', retval)
raise WorkerError('Docker returned non-zero retval ' + str(retval))
return elapsed_time_sec
|
python
|
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
"""Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission
"""
if time_limit < 0:
return self.run_without_time_limit(cmd)
container_name = str(uuid.uuid4())
cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME,
'--detach', '--name', container_name] + cmd
logging.info('Docker command: %s', ' '.join(cmd))
logging.info('Time limit %d seconds', time_limit)
retval = subprocess.call(cmd)
start_time = time.time()
elapsed_time_sec = 0
while is_docker_still_running(container_name):
elapsed_time_sec = int(time.time() - start_time)
if elapsed_time_sec < time_limit:
time.sleep(1)
else:
kill_docker_container(container_name)
logging.warning('Submission was killed because run out of time')
logging.info('Elapsed time of submission: %d', elapsed_time_sec)
logging.info('Docker retval: %d', retval)
if retval != 0:
logging.warning('Docker returned non-zero retval: %d', retval)
raise WorkerError('Docker returned non-zero retval ' + str(retval))
return elapsed_time_sec
|
[
"def",
"run_with_time_limit",
"(",
"self",
",",
"cmd",
",",
"time_limit",
"=",
"SUBMISSION_TIME_LIMIT",
")",
":",
"if",
"time_limit",
"<",
"0",
":",
"return",
"self",
".",
"run_without_time_limit",
"(",
"cmd",
")",
"container_name",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"cmd",
"=",
"[",
"DOCKER_BINARY",
",",
"'run'",
",",
"DOCKER_NVIDIA_RUNTIME",
",",
"'--detach'",
",",
"'--name'",
",",
"container_name",
"]",
"+",
"cmd",
"logging",
".",
"info",
"(",
"'Docker command: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"logging",
".",
"info",
"(",
"'Time limit %d seconds'",
",",
"time_limit",
")",
"retval",
"=",
"subprocess",
".",
"call",
"(",
"cmd",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"elapsed_time_sec",
"=",
"0",
"while",
"is_docker_still_running",
"(",
"container_name",
")",
":",
"elapsed_time_sec",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"if",
"elapsed_time_sec",
"<",
"time_limit",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"else",
":",
"kill_docker_container",
"(",
"container_name",
")",
"logging",
".",
"warning",
"(",
"'Submission was killed because run out of time'",
")",
"logging",
".",
"info",
"(",
"'Elapsed time of submission: %d'",
",",
"elapsed_time_sec",
")",
"logging",
".",
"info",
"(",
"'Docker retval: %d'",
",",
"retval",
")",
"if",
"retval",
"!=",
"0",
":",
"logging",
".",
"warning",
"(",
"'Docker returned non-zero retval: %d'",
",",
"retval",
")",
"raise",
"WorkerError",
"(",
"'Docker returned non-zero retval '",
"+",
"str",
"(",
"retval",
")",
")",
"return",
"elapsed_time_sec"
] |
Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission
|
[
"Runs",
"docker",
"command",
"and",
"enforces",
"time",
"limit",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L352-L388
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
AttackSubmission.run
|
def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 255].
Returns:
how long it took to run submission in seconds
"""
logging.info('Running attack %s', self.submission_id)
tmp_run_dir = self.temp_copy_extracted_submission()
cmd = ['--network=none',
'-m=24g',
'--cpus=3.75',
'-v', '{0}:/input_images:ro'.format(input_dir),
'-v', '{0}:/output_images'.format(output_dir),
'-v', '{0}:/code'.format(tmp_run_dir),
'-w', '/code',
self.container_name,
'./' + self.entry_point,
'/input_images',
'/output_images',
str(epsilon)]
elapsed_time_sec = self.run_with_time_limit(cmd)
sudo_remove_dirtree(tmp_run_dir)
return elapsed_time_sec
|
python
|
def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 255].
Returns:
how long it took to run submission in seconds
"""
logging.info('Running attack %s', self.submission_id)
tmp_run_dir = self.temp_copy_extracted_submission()
cmd = ['--network=none',
'-m=24g',
'--cpus=3.75',
'-v', '{0}:/input_images:ro'.format(input_dir),
'-v', '{0}:/output_images'.format(output_dir),
'-v', '{0}:/code'.format(tmp_run_dir),
'-w', '/code',
self.container_name,
'./' + self.entry_point,
'/input_images',
'/output_images',
str(epsilon)]
elapsed_time_sec = self.run_with_time_limit(cmd)
sudo_remove_dirtree(tmp_run_dir)
return elapsed_time_sec
|
[
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_dir",
",",
"epsilon",
")",
":",
"logging",
".",
"info",
"(",
"'Running attack %s'",
",",
"self",
".",
"submission_id",
")",
"tmp_run_dir",
"=",
"self",
".",
"temp_copy_extracted_submission",
"(",
")",
"cmd",
"=",
"[",
"'--network=none'",
",",
"'-m=24g'",
",",
"'--cpus=3.75'",
",",
"'-v'",
",",
"'{0}:/input_images:ro'",
".",
"format",
"(",
"input_dir",
")",
",",
"'-v'",
",",
"'{0}:/output_images'",
".",
"format",
"(",
"output_dir",
")",
",",
"'-v'",
",",
"'{0}:/code'",
".",
"format",
"(",
"tmp_run_dir",
")",
",",
"'-w'",
",",
"'/code'",
",",
"self",
".",
"container_name",
",",
"'./'",
"+",
"self",
".",
"entry_point",
",",
"'/input_images'",
",",
"'/output_images'",
",",
"str",
"(",
"epsilon",
")",
"]",
"elapsed_time_sec",
"=",
"self",
".",
"run_with_time_limit",
"(",
"cmd",
")",
"sudo_remove_dirtree",
"(",
"tmp_run_dir",
")",
"return",
"elapsed_time_sec"
] |
Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 255].
Returns:
how long it took to run submission in seconds
|
[
"Runs",
"attack",
"inside",
"Docker",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L411-L439
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
DefenseSubmission.run
|
def run(self, input_dir, output_file_path):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
"""
logging.info('Running defense %s', self.submission_id)
tmp_run_dir = self.temp_copy_extracted_submission()
output_dir = os.path.dirname(output_file_path)
output_filename = os.path.basename(output_file_path)
cmd = ['--network=none',
'-m=24g',
'--cpus=3.75',
'-v', '{0}:/input_images:ro'.format(input_dir),
'-v', '{0}:/output_data'.format(output_dir),
'-v', '{0}:/code'.format(tmp_run_dir),
'-w', '/code',
self.container_name,
'./' + self.entry_point,
'/input_images',
'/output_data/' + output_filename]
elapsed_time_sec = self.run_with_time_limit(cmd)
sudo_remove_dirtree(tmp_run_dir)
return elapsed_time_sec
|
python
|
def run(self, input_dir, output_file_path):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
"""
logging.info('Running defense %s', self.submission_id)
tmp_run_dir = self.temp_copy_extracted_submission()
output_dir = os.path.dirname(output_file_path)
output_filename = os.path.basename(output_file_path)
cmd = ['--network=none',
'-m=24g',
'--cpus=3.75',
'-v', '{0}:/input_images:ro'.format(input_dir),
'-v', '{0}:/output_data'.format(output_dir),
'-v', '{0}:/code'.format(tmp_run_dir),
'-w', '/code',
self.container_name,
'./' + self.entry_point,
'/input_images',
'/output_data/' + output_filename]
elapsed_time_sec = self.run_with_time_limit(cmd)
sudo_remove_dirtree(tmp_run_dir)
return elapsed_time_sec
|
[
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_file_path",
")",
":",
"logging",
".",
"info",
"(",
"'Running defense %s'",
",",
"self",
".",
"submission_id",
")",
"tmp_run_dir",
"=",
"self",
".",
"temp_copy_extracted_submission",
"(",
")",
"output_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_file_path",
")",
"output_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"output_file_path",
")",
"cmd",
"=",
"[",
"'--network=none'",
",",
"'-m=24g'",
",",
"'--cpus=3.75'",
",",
"'-v'",
",",
"'{0}:/input_images:ro'",
".",
"format",
"(",
"input_dir",
")",
",",
"'-v'",
",",
"'{0}:/output_data'",
".",
"format",
"(",
"output_dir",
")",
",",
"'-v'",
",",
"'{0}:/code'",
".",
"format",
"(",
"tmp_run_dir",
")",
",",
"'-w'",
",",
"'/code'",
",",
"self",
".",
"container_name",
",",
"'./'",
"+",
"self",
".",
"entry_point",
",",
"'/input_images'",
",",
"'/output_data/'",
"+",
"output_filename",
"]",
"elapsed_time_sec",
"=",
"self",
".",
"run_with_time_limit",
"(",
"cmd",
")",
"sudo_remove_dirtree",
"(",
"tmp_run_dir",
")",
"return",
"elapsed_time_sec"
] |
Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
|
[
"Runs",
"defense",
"inside",
"Docker",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L462-L489
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.read_dataset_metadata
|
def read_dataset_metadata(self):
"""Read `dataset_meta` field from bucket"""
if self.dataset_meta:
return
shell_call(['gsutil', 'cp',
'gs://' + self.storage_client.bucket_name + '/'
+ 'dataset/' + self.dataset_name + '_dataset.csv',
LOCAL_DATASET_METADATA_FILE])
with open(LOCAL_DATASET_METADATA_FILE, 'r') as f:
self.dataset_meta = eval_lib.DatasetMetadata(f)
|
python
|
def read_dataset_metadata(self):
"""Read `dataset_meta` field from bucket"""
if self.dataset_meta:
return
shell_call(['gsutil', 'cp',
'gs://' + self.storage_client.bucket_name + '/'
+ 'dataset/' + self.dataset_name + '_dataset.csv',
LOCAL_DATASET_METADATA_FILE])
with open(LOCAL_DATASET_METADATA_FILE, 'r') as f:
self.dataset_meta = eval_lib.DatasetMetadata(f)
|
[
"def",
"read_dataset_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"dataset_meta",
":",
"return",
"shell_call",
"(",
"[",
"'gsutil'",
",",
"'cp'",
",",
"'gs://'",
"+",
"self",
".",
"storage_client",
".",
"bucket_name",
"+",
"'/'",
"+",
"'dataset/'",
"+",
"self",
".",
"dataset_name",
"+",
"'_dataset.csv'",
",",
"LOCAL_DATASET_METADATA_FILE",
"]",
")",
"with",
"open",
"(",
"LOCAL_DATASET_METADATA_FILE",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"dataset_meta",
"=",
"eval_lib",
".",
"DatasetMetadata",
"(",
"f",
")"
] |
Read `dataset_meta` field from bucket
|
[
"Read",
"dataset_meta",
"field",
"from",
"bucket"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L556-L565
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.fetch_attacks_data
|
def fetch_attacks_data(self):
"""Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop.
"""
if self.attacks_data_initialized:
return
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_datastore()
self.adv_batches.init_from_datastore()
# copy dataset locally
if not os.path.exists(LOCAL_DATASET_DIR):
os.makedirs(LOCAL_DATASET_DIR)
eval_lib.download_dataset(self.storage_client, self.dataset_batches,
LOCAL_DATASET_DIR,
os.path.join(LOCAL_DATASET_COPY,
self.dataset_name, 'images'))
# download dataset metadata
self.read_dataset_metadata()
# mark as initialized
self.attacks_data_initialized = True
|
python
|
def fetch_attacks_data(self):
"""Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop.
"""
if self.attacks_data_initialized:
return
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_datastore()
self.adv_batches.init_from_datastore()
# copy dataset locally
if not os.path.exists(LOCAL_DATASET_DIR):
os.makedirs(LOCAL_DATASET_DIR)
eval_lib.download_dataset(self.storage_client, self.dataset_batches,
LOCAL_DATASET_DIR,
os.path.join(LOCAL_DATASET_COPY,
self.dataset_name, 'images'))
# download dataset metadata
self.read_dataset_metadata()
# mark as initialized
self.attacks_data_initialized = True
|
[
"def",
"fetch_attacks_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"attacks_data_initialized",
":",
"return",
"# init data from datastore",
"self",
".",
"submissions",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"dataset_batches",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"adv_batches",
".",
"init_from_datastore",
"(",
")",
"# copy dataset locally",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_DATASET_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"LOCAL_DATASET_DIR",
")",
"eval_lib",
".",
"download_dataset",
"(",
"self",
".",
"storage_client",
",",
"self",
".",
"dataset_batches",
",",
"LOCAL_DATASET_DIR",
",",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_DATASET_COPY",
",",
"self",
".",
"dataset_name",
",",
"'images'",
")",
")",
"# download dataset metadata",
"self",
".",
"read_dataset_metadata",
"(",
")",
"# mark as initialized",
"self",
".",
"attacks_data_initialized",
"=",
"True"
] |
Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop.
|
[
"Initializes",
"data",
"necessary",
"to",
"execute",
"attacks",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L567-L589
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.run_attack_work
|
def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
adv_batch_id = (
self.attack_work.work[work_id]['output_adversarial_batch_id'])
adv_batch = self.adv_batches[adv_batch_id]
dataset_batch_id = adv_batch['dataset_batch_id']
submission_id = adv_batch['submission_id']
epsilon = self.dataset_batches[dataset_batch_id]['epsilon']
logging.info('Attack work piece: '
'dataset_batch_id="%s" submission_id="%s" '
'epsilon=%d', dataset_batch_id, submission_id, epsilon)
if submission_id in self.blacklisted_submissions:
raise WorkerError('Blacklisted submission')
# get attack
attack = AttackSubmission(submission_id, self.submissions,
self.storage_bucket)
attack.download()
# prepare input
input_dir = os.path.join(LOCAL_DATASET_DIR, dataset_batch_id)
if attack.type == TYPE_TARGETED:
# prepare file with target classes
target_class_filename = os.path.join(input_dir, 'target_class.csv')
self.dataset_meta.save_target_classes_for_batch(target_class_filename,
self.dataset_batches,
dataset_batch_id)
# prepare output directory
if os.path.exists(LOCAL_OUTPUT_DIR):
sudo_remove_dirtree(LOCAL_OUTPUT_DIR)
os.mkdir(LOCAL_OUTPUT_DIR)
if os.path.exists(LOCAL_PROCESSED_OUTPUT_DIR):
shutil.rmtree(LOCAL_PROCESSED_OUTPUT_DIR)
os.mkdir(LOCAL_PROCESSED_OUTPUT_DIR)
if os.path.exists(LOCAL_ZIPPED_OUTPUT_DIR):
shutil.rmtree(LOCAL_ZIPPED_OUTPUT_DIR)
os.mkdir(LOCAL_ZIPPED_OUTPUT_DIR)
# run attack
elapsed_time_sec = attack.run(input_dir, LOCAL_OUTPUT_DIR, epsilon)
if attack.type == TYPE_TARGETED:
# remove target class file
os.remove(target_class_filename)
# enforce epsilon and compute hashes
image_hashes = eval_lib.enforce_epsilon_and_compute_hash(
input_dir, LOCAL_OUTPUT_DIR, LOCAL_PROCESSED_OUTPUT_DIR, epsilon)
if not image_hashes:
logging.warning('No images saved by the attack.')
return elapsed_time_sec, submission_id
# write images back to datastore
# rename images and add information to adversarial batch
for clean_image_id, hash_val in iteritems(image_hashes):
# we will use concatenation of batch_id and image_id
# as adversarial image id and as a filename of adversarial images
adv_img_id = adv_batch_id + '_' + clean_image_id
# rename the image
os.rename(
os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, clean_image_id + '.png'),
os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, adv_img_id + '.png'))
# populate values which will be written to datastore
image_path = '{0}/adversarial_images/{1}/{1}.zip/{2}.png'.format(
self.round_name, adv_batch_id, adv_img_id)
# u'' + foo is a a python 2/3 compatible way of casting foo to unicode
adv_batch['images'][adv_img_id] = {
'clean_image_id': u'' + str(clean_image_id),
'image_path': u'' + str(image_path),
'image_hash': u'' + str(hash_val),
}
# archive all images and copy to storage
zipped_images_filename = os.path.join(LOCAL_ZIPPED_OUTPUT_DIR,
adv_batch_id + '.zip')
try:
logging.debug('Compressing adversarial images to %s',
zipped_images_filename)
shell_call([
'zip', '-j', '-r', zipped_images_filename,
LOCAL_PROCESSED_OUTPUT_DIR])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t make archive from adversarial iamges', e)
# upload archive to storage
dst_filename = '{0}/adversarial_images/{1}/{1}.zip'.format(
self.round_name, adv_batch_id)
logging.debug(
'Copying archive with adversarial images to %s', dst_filename)
self.storage_client.new_blob(dst_filename).upload_from_filename(
zipped_images_filename)
# writing adv batch to datastore
logging.debug('Writing adversarial batch to datastore')
self.adv_batches.write_single_batch_images_to_datastore(adv_batch_id)
return elapsed_time_sec, submission_id
|
python
|
def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
adv_batch_id = (
self.attack_work.work[work_id]['output_adversarial_batch_id'])
adv_batch = self.adv_batches[adv_batch_id]
dataset_batch_id = adv_batch['dataset_batch_id']
submission_id = adv_batch['submission_id']
epsilon = self.dataset_batches[dataset_batch_id]['epsilon']
logging.info('Attack work piece: '
'dataset_batch_id="%s" submission_id="%s" '
'epsilon=%d', dataset_batch_id, submission_id, epsilon)
if submission_id in self.blacklisted_submissions:
raise WorkerError('Blacklisted submission')
# get attack
attack = AttackSubmission(submission_id, self.submissions,
self.storage_bucket)
attack.download()
# prepare input
input_dir = os.path.join(LOCAL_DATASET_DIR, dataset_batch_id)
if attack.type == TYPE_TARGETED:
# prepare file with target classes
target_class_filename = os.path.join(input_dir, 'target_class.csv')
self.dataset_meta.save_target_classes_for_batch(target_class_filename,
self.dataset_batches,
dataset_batch_id)
# prepare output directory
if os.path.exists(LOCAL_OUTPUT_DIR):
sudo_remove_dirtree(LOCAL_OUTPUT_DIR)
os.mkdir(LOCAL_OUTPUT_DIR)
if os.path.exists(LOCAL_PROCESSED_OUTPUT_DIR):
shutil.rmtree(LOCAL_PROCESSED_OUTPUT_DIR)
os.mkdir(LOCAL_PROCESSED_OUTPUT_DIR)
if os.path.exists(LOCAL_ZIPPED_OUTPUT_DIR):
shutil.rmtree(LOCAL_ZIPPED_OUTPUT_DIR)
os.mkdir(LOCAL_ZIPPED_OUTPUT_DIR)
# run attack
elapsed_time_sec = attack.run(input_dir, LOCAL_OUTPUT_DIR, epsilon)
if attack.type == TYPE_TARGETED:
# remove target class file
os.remove(target_class_filename)
# enforce epsilon and compute hashes
image_hashes = eval_lib.enforce_epsilon_and_compute_hash(
input_dir, LOCAL_OUTPUT_DIR, LOCAL_PROCESSED_OUTPUT_DIR, epsilon)
if not image_hashes:
logging.warning('No images saved by the attack.')
return elapsed_time_sec, submission_id
# write images back to datastore
# rename images and add information to adversarial batch
for clean_image_id, hash_val in iteritems(image_hashes):
# we will use concatenation of batch_id and image_id
# as adversarial image id and as a filename of adversarial images
adv_img_id = adv_batch_id + '_' + clean_image_id
# rename the image
os.rename(
os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, clean_image_id + '.png'),
os.path.join(LOCAL_PROCESSED_OUTPUT_DIR, adv_img_id + '.png'))
# populate values which will be written to datastore
image_path = '{0}/adversarial_images/{1}/{1}.zip/{2}.png'.format(
self.round_name, adv_batch_id, adv_img_id)
# u'' + foo is a a python 2/3 compatible way of casting foo to unicode
adv_batch['images'][adv_img_id] = {
'clean_image_id': u'' + str(clean_image_id),
'image_path': u'' + str(image_path),
'image_hash': u'' + str(hash_val),
}
# archive all images and copy to storage
zipped_images_filename = os.path.join(LOCAL_ZIPPED_OUTPUT_DIR,
adv_batch_id + '.zip')
try:
logging.debug('Compressing adversarial images to %s',
zipped_images_filename)
shell_call([
'zip', '-j', '-r', zipped_images_filename,
LOCAL_PROCESSED_OUTPUT_DIR])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t make archive from adversarial iamges', e)
# upload archive to storage
dst_filename = '{0}/adversarial_images/{1}/{1}.zip'.format(
self.round_name, adv_batch_id)
logging.debug(
'Copying archive with adversarial images to %s', dst_filename)
self.storage_client.new_blob(dst_filename).upload_from_filename(
zipped_images_filename)
# writing adv batch to datastore
logging.debug('Writing adversarial batch to datastore')
self.adv_batches.write_single_batch_images_to_datastore(adv_batch_id)
return elapsed_time_sec, submission_id
|
[
"def",
"run_attack_work",
"(",
"self",
",",
"work_id",
")",
":",
"adv_batch_id",
"=",
"(",
"self",
".",
"attack_work",
".",
"work",
"[",
"work_id",
"]",
"[",
"'output_adversarial_batch_id'",
"]",
")",
"adv_batch",
"=",
"self",
".",
"adv_batches",
"[",
"adv_batch_id",
"]",
"dataset_batch_id",
"=",
"adv_batch",
"[",
"'dataset_batch_id'",
"]",
"submission_id",
"=",
"adv_batch",
"[",
"'submission_id'",
"]",
"epsilon",
"=",
"self",
".",
"dataset_batches",
"[",
"dataset_batch_id",
"]",
"[",
"'epsilon'",
"]",
"logging",
".",
"info",
"(",
"'Attack work piece: '",
"'dataset_batch_id=\"%s\" submission_id=\"%s\" '",
"'epsilon=%d'",
",",
"dataset_batch_id",
",",
"submission_id",
",",
"epsilon",
")",
"if",
"submission_id",
"in",
"self",
".",
"blacklisted_submissions",
":",
"raise",
"WorkerError",
"(",
"'Blacklisted submission'",
")",
"# get attack",
"attack",
"=",
"AttackSubmission",
"(",
"submission_id",
",",
"self",
".",
"submissions",
",",
"self",
".",
"storage_bucket",
")",
"attack",
".",
"download",
"(",
")",
"# prepare input",
"input_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_DATASET_DIR",
",",
"dataset_batch_id",
")",
"if",
"attack",
".",
"type",
"==",
"TYPE_TARGETED",
":",
"# prepare file with target classes",
"target_class_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"'target_class.csv'",
")",
"self",
".",
"dataset_meta",
".",
"save_target_classes_for_batch",
"(",
"target_class_filename",
",",
"self",
".",
"dataset_batches",
",",
"dataset_batch_id",
")",
"# prepare output directory",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_OUTPUT_DIR",
")",
":",
"sudo_remove_dirtree",
"(",
"LOCAL_OUTPUT_DIR",
")",
"os",
".",
"mkdir",
"(",
"LOCAL_OUTPUT_DIR",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_PROCESSED_OUTPUT_DIR",
")",
":",
"shutil",
".",
"rmtree",
"(",
"LOCAL_PROCESSED_OUTPUT_DIR",
")",
"os",
".",
"mkdir",
"(",
"LOCAL_PROCESSED_OUTPUT_DIR",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_ZIPPED_OUTPUT_DIR",
")",
":",
"shutil",
".",
"rmtree",
"(",
"LOCAL_ZIPPED_OUTPUT_DIR",
")",
"os",
".",
"mkdir",
"(",
"LOCAL_ZIPPED_OUTPUT_DIR",
")",
"# run attack",
"elapsed_time_sec",
"=",
"attack",
".",
"run",
"(",
"input_dir",
",",
"LOCAL_OUTPUT_DIR",
",",
"epsilon",
")",
"if",
"attack",
".",
"type",
"==",
"TYPE_TARGETED",
":",
"# remove target class file",
"os",
".",
"remove",
"(",
"target_class_filename",
")",
"# enforce epsilon and compute hashes",
"image_hashes",
"=",
"eval_lib",
".",
"enforce_epsilon_and_compute_hash",
"(",
"input_dir",
",",
"LOCAL_OUTPUT_DIR",
",",
"LOCAL_PROCESSED_OUTPUT_DIR",
",",
"epsilon",
")",
"if",
"not",
"image_hashes",
":",
"logging",
".",
"warning",
"(",
"'No images saved by the attack.'",
")",
"return",
"elapsed_time_sec",
",",
"submission_id",
"# write images back to datastore",
"# rename images and add information to adversarial batch",
"for",
"clean_image_id",
",",
"hash_val",
"in",
"iteritems",
"(",
"image_hashes",
")",
":",
"# we will use concatenation of batch_id and image_id",
"# as adversarial image id and as a filename of adversarial images",
"adv_img_id",
"=",
"adv_batch_id",
"+",
"'_'",
"+",
"clean_image_id",
"# rename the image",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_PROCESSED_OUTPUT_DIR",
",",
"clean_image_id",
"+",
"'.png'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_PROCESSED_OUTPUT_DIR",
",",
"adv_img_id",
"+",
"'.png'",
")",
")",
"# populate values which will be written to datastore",
"image_path",
"=",
"'{0}/adversarial_images/{1}/{1}.zip/{2}.png'",
".",
"format",
"(",
"self",
".",
"round_name",
",",
"adv_batch_id",
",",
"adv_img_id",
")",
"# u'' + foo is a a python 2/3 compatible way of casting foo to unicode",
"adv_batch",
"[",
"'images'",
"]",
"[",
"adv_img_id",
"]",
"=",
"{",
"'clean_image_id'",
":",
"u''",
"+",
"str",
"(",
"clean_image_id",
")",
",",
"'image_path'",
":",
"u''",
"+",
"str",
"(",
"image_path",
")",
",",
"'image_hash'",
":",
"u''",
"+",
"str",
"(",
"hash_val",
")",
",",
"}",
"# archive all images and copy to storage",
"zipped_images_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_ZIPPED_OUTPUT_DIR",
",",
"adv_batch_id",
"+",
"'.zip'",
")",
"try",
":",
"logging",
".",
"debug",
"(",
"'Compressing adversarial images to %s'",
",",
"zipped_images_filename",
")",
"shell_call",
"(",
"[",
"'zip'",
",",
"'-j'",
",",
"'-r'",
",",
"zipped_images_filename",
",",
"LOCAL_PROCESSED_OUTPUT_DIR",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t make archive from adversarial iamges'",
",",
"e",
")",
"# upload archive to storage",
"dst_filename",
"=",
"'{0}/adversarial_images/{1}/{1}.zip'",
".",
"format",
"(",
"self",
".",
"round_name",
",",
"adv_batch_id",
")",
"logging",
".",
"debug",
"(",
"'Copying archive with adversarial images to %s'",
",",
"dst_filename",
")",
"self",
".",
"storage_client",
".",
"new_blob",
"(",
"dst_filename",
")",
".",
"upload_from_filename",
"(",
"zipped_images_filename",
")",
"# writing adv batch to datastore",
"logging",
".",
"debug",
"(",
"'Writing adversarial batch to datastore'",
")",
"self",
".",
"adv_batches",
".",
"write_single_batch_images_to_datastore",
"(",
"adv_batch_id",
")",
"return",
"elapsed_time_sec",
",",
"submission_id"
] |
Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
|
[
"Runs",
"one",
"attack",
"work",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L591-L687
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.run_attacks
|
def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is available
self.attack_work.read_all_from_datastore()
if not self.attack_work.work:
logging.info('Work is not populated, waiting...')
time.sleep(SLEEP_TIME)
continue
if self.attack_work.is_all_work_competed():
logging.info('All attack work completed.')
break
# download all attacks data and dataset
self.fetch_attacks_data()
# pick piece of work
work_id = self.attack_work.try_pick_piece_of_work(
self.worker_id, submission_id=prev_submission_id)
if not work_id:
logging.info('Failed to pick work, waiting...')
time.sleep(SLEEP_TIME_SHORT)
continue
logging.info('Selected work_id: %s', work_id)
# execute work
try:
elapsed_time_sec, prev_submission_id = self.run_attack_work(work_id)
logging.info('Work %s is done', work_id)
# indicate that work is completed
is_work_update = self.attack_work.update_work_as_completed(
self.worker_id, work_id,
other_values={'elapsed_time': elapsed_time_sec})
except WorkerError as e:
logging.info('Failed to run work:\n%s', str(e))
is_work_update = self.attack_work.update_work_as_completed(
self.worker_id, work_id, error=str(e))
if not is_work_update:
logging.warning('Can''t update work "%s" as completed by worker %d',
work_id, self.worker_id)
logging.info('******** Finished evaluation of attacks ********')
|
python
|
def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is available
self.attack_work.read_all_from_datastore()
if not self.attack_work.work:
logging.info('Work is not populated, waiting...')
time.sleep(SLEEP_TIME)
continue
if self.attack_work.is_all_work_competed():
logging.info('All attack work completed.')
break
# download all attacks data and dataset
self.fetch_attacks_data()
# pick piece of work
work_id = self.attack_work.try_pick_piece_of_work(
self.worker_id, submission_id=prev_submission_id)
if not work_id:
logging.info('Failed to pick work, waiting...')
time.sleep(SLEEP_TIME_SHORT)
continue
logging.info('Selected work_id: %s', work_id)
# execute work
try:
elapsed_time_sec, prev_submission_id = self.run_attack_work(work_id)
logging.info('Work %s is done', work_id)
# indicate that work is completed
is_work_update = self.attack_work.update_work_as_completed(
self.worker_id, work_id,
other_values={'elapsed_time': elapsed_time_sec})
except WorkerError as e:
logging.info('Failed to run work:\n%s', str(e))
is_work_update = self.attack_work.update_work_as_completed(
self.worker_id, work_id, error=str(e))
if not is_work_update:
logging.warning('Can''t update work "%s" as completed by worker %d',
work_id, self.worker_id)
logging.info('******** Finished evaluation of attacks ********')
|
[
"def",
"run_attacks",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'******** Start evaluation of attacks ********'",
")",
"prev_submission_id",
"=",
"None",
"while",
"True",
":",
"# wait until work is available",
"self",
".",
"attack_work",
".",
"read_all_from_datastore",
"(",
")",
"if",
"not",
"self",
".",
"attack_work",
".",
"work",
":",
"logging",
".",
"info",
"(",
"'Work is not populated, waiting...'",
")",
"time",
".",
"sleep",
"(",
"SLEEP_TIME",
")",
"continue",
"if",
"self",
".",
"attack_work",
".",
"is_all_work_competed",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'All attack work completed.'",
")",
"break",
"# download all attacks data and dataset",
"self",
".",
"fetch_attacks_data",
"(",
")",
"# pick piece of work",
"work_id",
"=",
"self",
".",
"attack_work",
".",
"try_pick_piece_of_work",
"(",
"self",
".",
"worker_id",
",",
"submission_id",
"=",
"prev_submission_id",
")",
"if",
"not",
"work_id",
":",
"logging",
".",
"info",
"(",
"'Failed to pick work, waiting...'",
")",
"time",
".",
"sleep",
"(",
"SLEEP_TIME_SHORT",
")",
"continue",
"logging",
".",
"info",
"(",
"'Selected work_id: %s'",
",",
"work_id",
")",
"# execute work",
"try",
":",
"elapsed_time_sec",
",",
"prev_submission_id",
"=",
"self",
".",
"run_attack_work",
"(",
"work_id",
")",
"logging",
".",
"info",
"(",
"'Work %s is done'",
",",
"work_id",
")",
"# indicate that work is completed",
"is_work_update",
"=",
"self",
".",
"attack_work",
".",
"update_work_as_completed",
"(",
"self",
".",
"worker_id",
",",
"work_id",
",",
"other_values",
"=",
"{",
"'elapsed_time'",
":",
"elapsed_time_sec",
"}",
")",
"except",
"WorkerError",
"as",
"e",
":",
"logging",
".",
"info",
"(",
"'Failed to run work:\\n%s'",
",",
"str",
"(",
"e",
")",
")",
"is_work_update",
"=",
"self",
".",
"attack_work",
".",
"update_work_as_completed",
"(",
"self",
".",
"worker_id",
",",
"work_id",
",",
"error",
"=",
"str",
"(",
"e",
")",
")",
"if",
"not",
"is_work_update",
":",
"logging",
".",
"warning",
"(",
"'Can'",
"'t update work \"%s\" as completed by worker %d'",
",",
"work_id",
",",
"self",
".",
"worker_id",
")",
"logging",
".",
"info",
"(",
"'******** Finished evaluation of attacks ********'",
")"
] |
Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
|
[
"Method",
"which",
"evaluates",
"all",
"attack",
"work",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L689-L732
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.fetch_defense_data
|
def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_datastore()
self.adv_batches.init_from_datastore()
# read dataset metadata
self.read_dataset_metadata()
# mark as initialized
self.defenses_data_initialized = True
|
python
|
def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_datastore()
self.adv_batches.init_from_datastore()
# read dataset metadata
self.read_dataset_metadata()
# mark as initialized
self.defenses_data_initialized = True
|
[
"def",
"fetch_defense_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"defenses_data_initialized",
":",
"return",
"logging",
".",
"info",
"(",
"'Fetching defense data from datastore'",
")",
"# init data from datastore",
"self",
".",
"submissions",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"dataset_batches",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"adv_batches",
".",
"init_from_datastore",
"(",
")",
"# read dataset metadata",
"self",
".",
"read_dataset_metadata",
"(",
")",
"# mark as initialized",
"self",
".",
"defenses_data_initialized",
"=",
"True"
] |
Lazy initialization of data necessary to execute defenses.
|
[
"Lazy",
"initialization",
"of",
"data",
"necessary",
"to",
"execute",
"defenses",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L734-L746
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.run_defense_work
|
def run_defense_work(self, work_id):
"""Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
class_batch_id = (
self.defense_work.work[work_id]['output_classification_batch_id'])
class_batch = self.class_batches.read_batch_from_datastore(class_batch_id)
adversarial_batch_id = class_batch['adversarial_batch_id']
submission_id = class_batch['submission_id']
cloud_result_path = class_batch['result_path']
logging.info('Defense work piece: '
'adversarial_batch_id="%s" submission_id="%s"',
adversarial_batch_id, submission_id)
if submission_id in self.blacklisted_submissions:
raise WorkerError('Blacklisted submission')
# get defense
defense = DefenseSubmission(submission_id, self.submissions,
self.storage_bucket)
defense.download()
# prepare input - copy adversarial batch locally
input_dir = os.path.join(LOCAL_INPUT_DIR, adversarial_batch_id)
if os.path.exists(input_dir):
sudo_remove_dirtree(input_dir)
os.makedirs(input_dir)
try:
shell_call([
'gsutil', '-m', 'cp',
# typical location of adv batch:
# testing-round/adversarial_images/ADVBATCH000/
os.path.join('gs://', self.storage_bucket, self.round_name,
'adversarial_images', adversarial_batch_id, '*'),
input_dir
])
adv_images_files = os.listdir(input_dir)
if (len(adv_images_files) == 1) and adv_images_files[0].endswith('.zip'):
logging.info('Adversarial batch is in zip archive %s',
adv_images_files[0])
shell_call([
'unzip', os.path.join(input_dir, adv_images_files[0]),
'-d', input_dir
])
os.remove(os.path.join(input_dir, adv_images_files[0]))
adv_images_files = os.listdir(input_dir)
logging.info('%d adversarial images copied', len(adv_images_files))
except (subprocess.CalledProcessError, IOError) as e:
raise WorkerError('Can''t copy adversarial batch locally', e)
# prepare output directory
if os.path.exists(LOCAL_OUTPUT_DIR):
sudo_remove_dirtree(LOCAL_OUTPUT_DIR)
os.mkdir(LOCAL_OUTPUT_DIR)
output_filname = os.path.join(LOCAL_OUTPUT_DIR, 'result.csv')
# run defense
elapsed_time_sec = defense.run(input_dir, output_filname)
# evaluate defense result
batch_result = eval_lib.analyze_one_classification_result(
storage_client=None,
file_path=output_filname,
adv_batch=self.adv_batches.data[adversarial_batch_id],
dataset_batches=self.dataset_batches,
dataset_meta=self.dataset_meta)
# copy result of the defense into storage
try:
shell_call([
'gsutil', 'cp', output_filname,
os.path.join('gs://', self.storage_bucket, cloud_result_path)
])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t result to Cloud Storage', e)
return elapsed_time_sec, submission_id, batch_result
|
python
|
def run_defense_work(self, work_id):
"""Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
class_batch_id = (
self.defense_work.work[work_id]['output_classification_batch_id'])
class_batch = self.class_batches.read_batch_from_datastore(class_batch_id)
adversarial_batch_id = class_batch['adversarial_batch_id']
submission_id = class_batch['submission_id']
cloud_result_path = class_batch['result_path']
logging.info('Defense work piece: '
'adversarial_batch_id="%s" submission_id="%s"',
adversarial_batch_id, submission_id)
if submission_id in self.blacklisted_submissions:
raise WorkerError('Blacklisted submission')
# get defense
defense = DefenseSubmission(submission_id, self.submissions,
self.storage_bucket)
defense.download()
# prepare input - copy adversarial batch locally
input_dir = os.path.join(LOCAL_INPUT_DIR, adversarial_batch_id)
if os.path.exists(input_dir):
sudo_remove_dirtree(input_dir)
os.makedirs(input_dir)
try:
shell_call([
'gsutil', '-m', 'cp',
# typical location of adv batch:
# testing-round/adversarial_images/ADVBATCH000/
os.path.join('gs://', self.storage_bucket, self.round_name,
'adversarial_images', adversarial_batch_id, '*'),
input_dir
])
adv_images_files = os.listdir(input_dir)
if (len(adv_images_files) == 1) and adv_images_files[0].endswith('.zip'):
logging.info('Adversarial batch is in zip archive %s',
adv_images_files[0])
shell_call([
'unzip', os.path.join(input_dir, adv_images_files[0]),
'-d', input_dir
])
os.remove(os.path.join(input_dir, adv_images_files[0]))
adv_images_files = os.listdir(input_dir)
logging.info('%d adversarial images copied', len(adv_images_files))
except (subprocess.CalledProcessError, IOError) as e:
raise WorkerError('Can''t copy adversarial batch locally', e)
# prepare output directory
if os.path.exists(LOCAL_OUTPUT_DIR):
sudo_remove_dirtree(LOCAL_OUTPUT_DIR)
os.mkdir(LOCAL_OUTPUT_DIR)
output_filname = os.path.join(LOCAL_OUTPUT_DIR, 'result.csv')
# run defense
elapsed_time_sec = defense.run(input_dir, output_filname)
# evaluate defense result
batch_result = eval_lib.analyze_one_classification_result(
storage_client=None,
file_path=output_filname,
adv_batch=self.adv_batches.data[adversarial_batch_id],
dataset_batches=self.dataset_batches,
dataset_meta=self.dataset_meta)
# copy result of the defense into storage
try:
shell_call([
'gsutil', 'cp', output_filname,
os.path.join('gs://', self.storage_bucket, cloud_result_path)
])
except subprocess.CalledProcessError as e:
raise WorkerError('Can''t result to Cloud Storage', e)
return elapsed_time_sec, submission_id, batch_result
|
[
"def",
"run_defense_work",
"(",
"self",
",",
"work_id",
")",
":",
"class_batch_id",
"=",
"(",
"self",
".",
"defense_work",
".",
"work",
"[",
"work_id",
"]",
"[",
"'output_classification_batch_id'",
"]",
")",
"class_batch",
"=",
"self",
".",
"class_batches",
".",
"read_batch_from_datastore",
"(",
"class_batch_id",
")",
"adversarial_batch_id",
"=",
"class_batch",
"[",
"'adversarial_batch_id'",
"]",
"submission_id",
"=",
"class_batch",
"[",
"'submission_id'",
"]",
"cloud_result_path",
"=",
"class_batch",
"[",
"'result_path'",
"]",
"logging",
".",
"info",
"(",
"'Defense work piece: '",
"'adversarial_batch_id=\"%s\" submission_id=\"%s\"'",
",",
"adversarial_batch_id",
",",
"submission_id",
")",
"if",
"submission_id",
"in",
"self",
".",
"blacklisted_submissions",
":",
"raise",
"WorkerError",
"(",
"'Blacklisted submission'",
")",
"# get defense",
"defense",
"=",
"DefenseSubmission",
"(",
"submission_id",
",",
"self",
".",
"submissions",
",",
"self",
".",
"storage_bucket",
")",
"defense",
".",
"download",
"(",
")",
"# prepare input - copy adversarial batch locally",
"input_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_INPUT_DIR",
",",
"adversarial_batch_id",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"input_dir",
")",
":",
"sudo_remove_dirtree",
"(",
"input_dir",
")",
"os",
".",
"makedirs",
"(",
"input_dir",
")",
"try",
":",
"shell_call",
"(",
"[",
"'gsutil'",
",",
"'-m'",
",",
"'cp'",
",",
"# typical location of adv batch:",
"# testing-round/adversarial_images/ADVBATCH000/",
"os",
".",
"path",
".",
"join",
"(",
"'gs://'",
",",
"self",
".",
"storage_bucket",
",",
"self",
".",
"round_name",
",",
"'adversarial_images'",
",",
"adversarial_batch_id",
",",
"'*'",
")",
",",
"input_dir",
"]",
")",
"adv_images_files",
"=",
"os",
".",
"listdir",
"(",
"input_dir",
")",
"if",
"(",
"len",
"(",
"adv_images_files",
")",
"==",
"1",
")",
"and",
"adv_images_files",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"logging",
".",
"info",
"(",
"'Adversarial batch is in zip archive %s'",
",",
"adv_images_files",
"[",
"0",
"]",
")",
"shell_call",
"(",
"[",
"'unzip'",
",",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"adv_images_files",
"[",
"0",
"]",
")",
",",
"'-d'",
",",
"input_dir",
"]",
")",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"adv_images_files",
"[",
"0",
"]",
")",
")",
"adv_images_files",
"=",
"os",
".",
"listdir",
"(",
"input_dir",
")",
"logging",
".",
"info",
"(",
"'%d adversarial images copied'",
",",
"len",
"(",
"adv_images_files",
")",
")",
"except",
"(",
"subprocess",
".",
"CalledProcessError",
",",
"IOError",
")",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t copy adversarial batch locally'",
",",
"e",
")",
"# prepare output directory",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_OUTPUT_DIR",
")",
":",
"sudo_remove_dirtree",
"(",
"LOCAL_OUTPUT_DIR",
")",
"os",
".",
"mkdir",
"(",
"LOCAL_OUTPUT_DIR",
")",
"output_filname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"LOCAL_OUTPUT_DIR",
",",
"'result.csv'",
")",
"# run defense",
"elapsed_time_sec",
"=",
"defense",
".",
"run",
"(",
"input_dir",
",",
"output_filname",
")",
"# evaluate defense result",
"batch_result",
"=",
"eval_lib",
".",
"analyze_one_classification_result",
"(",
"storage_client",
"=",
"None",
",",
"file_path",
"=",
"output_filname",
",",
"adv_batch",
"=",
"self",
".",
"adv_batches",
".",
"data",
"[",
"adversarial_batch_id",
"]",
",",
"dataset_batches",
"=",
"self",
".",
"dataset_batches",
",",
"dataset_meta",
"=",
"self",
".",
"dataset_meta",
")",
"# copy result of the defense into storage",
"try",
":",
"shell_call",
"(",
"[",
"'gsutil'",
",",
"'cp'",
",",
"output_filname",
",",
"os",
".",
"path",
".",
"join",
"(",
"'gs://'",
",",
"self",
".",
"storage_bucket",
",",
"cloud_result_path",
")",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"raise",
"WorkerError",
"(",
"'Can'",
"'t result to Cloud Storage'",
",",
"e",
")",
"return",
"elapsed_time_sec",
",",
"submission_id",
",",
"batch_result"
] |
Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
|
[
"Runs",
"one",
"defense",
"work",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L748-L824
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.run_defenses
|
def run_defenses(self):
"""Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
"""
logging.info('******** Start evaluation of defenses ********')
prev_submission_id = None
need_reload_work = True
while True:
# wait until work is available
if need_reload_work:
if self.num_defense_shards:
shard_with_work = self.defense_work.read_undone_from_datastore(
shard_id=(self.worker_id % self.num_defense_shards),
num_shards=self.num_defense_shards)
else:
shard_with_work = self.defense_work.read_undone_from_datastore()
logging.info('Loaded %d records of undone work from shard %s',
len(self.defense_work), str(shard_with_work))
if not self.defense_work.work:
logging.info('Work is not populated, waiting...')
time.sleep(SLEEP_TIME)
continue
if self.defense_work.is_all_work_competed():
logging.info('All defense work completed.')
break
# download all defense data and dataset
self.fetch_defense_data()
need_reload_work = False
# pick piece of work
work_id = self.defense_work.try_pick_piece_of_work(
self.worker_id, submission_id=prev_submission_id)
if not work_id:
need_reload_work = True
logging.info('Failed to pick work, waiting...')
time.sleep(SLEEP_TIME_SHORT)
continue
logging.info('Selected work_id: %s', work_id)
# execute work
try:
elapsed_time_sec, prev_submission_id, batch_result = (
self.run_defense_work(work_id))
logging.info('Work %s is done', work_id)
# indicate that work is completed
is_work_update = self.defense_work.update_work_as_completed(
self.worker_id, work_id,
other_values={'elapsed_time': elapsed_time_sec,
'stat_correct': batch_result[0],
'stat_error': batch_result[1],
'stat_target_class': batch_result[2],
'stat_num_images': batch_result[3]})
except WorkerError as e:
logging.info('Failed to run work:\n%s', str(e))
if str(e).startswith('Docker returned non-zero retval'):
logging.info('Running nvidia-docker to ensure that GPU works')
shell_call(['nvidia-docker', 'run', '--rm', 'nvidia/cuda',
'nvidia-smi'])
is_work_update = self.defense_work.update_work_as_completed(
self.worker_id, work_id, error=str(e))
if not is_work_update:
logging.warning('Can''t update work "%s" as completed by worker %d',
work_id, self.worker_id)
need_reload_work = True
logging.info('******** Finished evaluation of defenses ********')
|
python
|
def run_defenses(self):
"""Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
"""
logging.info('******** Start evaluation of defenses ********')
prev_submission_id = None
need_reload_work = True
while True:
# wait until work is available
if need_reload_work:
if self.num_defense_shards:
shard_with_work = self.defense_work.read_undone_from_datastore(
shard_id=(self.worker_id % self.num_defense_shards),
num_shards=self.num_defense_shards)
else:
shard_with_work = self.defense_work.read_undone_from_datastore()
logging.info('Loaded %d records of undone work from shard %s',
len(self.defense_work), str(shard_with_work))
if not self.defense_work.work:
logging.info('Work is not populated, waiting...')
time.sleep(SLEEP_TIME)
continue
if self.defense_work.is_all_work_competed():
logging.info('All defense work completed.')
break
# download all defense data and dataset
self.fetch_defense_data()
need_reload_work = False
# pick piece of work
work_id = self.defense_work.try_pick_piece_of_work(
self.worker_id, submission_id=prev_submission_id)
if not work_id:
need_reload_work = True
logging.info('Failed to pick work, waiting...')
time.sleep(SLEEP_TIME_SHORT)
continue
logging.info('Selected work_id: %s', work_id)
# execute work
try:
elapsed_time_sec, prev_submission_id, batch_result = (
self.run_defense_work(work_id))
logging.info('Work %s is done', work_id)
# indicate that work is completed
is_work_update = self.defense_work.update_work_as_completed(
self.worker_id, work_id,
other_values={'elapsed_time': elapsed_time_sec,
'stat_correct': batch_result[0],
'stat_error': batch_result[1],
'stat_target_class': batch_result[2],
'stat_num_images': batch_result[3]})
except WorkerError as e:
logging.info('Failed to run work:\n%s', str(e))
if str(e).startswith('Docker returned non-zero retval'):
logging.info('Running nvidia-docker to ensure that GPU works')
shell_call(['nvidia-docker', 'run', '--rm', 'nvidia/cuda',
'nvidia-smi'])
is_work_update = self.defense_work.update_work_as_completed(
self.worker_id, work_id, error=str(e))
if not is_work_update:
logging.warning('Can''t update work "%s" as completed by worker %d',
work_id, self.worker_id)
need_reload_work = True
logging.info('******** Finished evaluation of defenses ********')
|
[
"def",
"run_defenses",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'******** Start evaluation of defenses ********'",
")",
"prev_submission_id",
"=",
"None",
"need_reload_work",
"=",
"True",
"while",
"True",
":",
"# wait until work is available",
"if",
"need_reload_work",
":",
"if",
"self",
".",
"num_defense_shards",
":",
"shard_with_work",
"=",
"self",
".",
"defense_work",
".",
"read_undone_from_datastore",
"(",
"shard_id",
"=",
"(",
"self",
".",
"worker_id",
"%",
"self",
".",
"num_defense_shards",
")",
",",
"num_shards",
"=",
"self",
".",
"num_defense_shards",
")",
"else",
":",
"shard_with_work",
"=",
"self",
".",
"defense_work",
".",
"read_undone_from_datastore",
"(",
")",
"logging",
".",
"info",
"(",
"'Loaded %d records of undone work from shard %s'",
",",
"len",
"(",
"self",
".",
"defense_work",
")",
",",
"str",
"(",
"shard_with_work",
")",
")",
"if",
"not",
"self",
".",
"defense_work",
".",
"work",
":",
"logging",
".",
"info",
"(",
"'Work is not populated, waiting...'",
")",
"time",
".",
"sleep",
"(",
"SLEEP_TIME",
")",
"continue",
"if",
"self",
".",
"defense_work",
".",
"is_all_work_competed",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'All defense work completed.'",
")",
"break",
"# download all defense data and dataset",
"self",
".",
"fetch_defense_data",
"(",
")",
"need_reload_work",
"=",
"False",
"# pick piece of work",
"work_id",
"=",
"self",
".",
"defense_work",
".",
"try_pick_piece_of_work",
"(",
"self",
".",
"worker_id",
",",
"submission_id",
"=",
"prev_submission_id",
")",
"if",
"not",
"work_id",
":",
"need_reload_work",
"=",
"True",
"logging",
".",
"info",
"(",
"'Failed to pick work, waiting...'",
")",
"time",
".",
"sleep",
"(",
"SLEEP_TIME_SHORT",
")",
"continue",
"logging",
".",
"info",
"(",
"'Selected work_id: %s'",
",",
"work_id",
")",
"# execute work",
"try",
":",
"elapsed_time_sec",
",",
"prev_submission_id",
",",
"batch_result",
"=",
"(",
"self",
".",
"run_defense_work",
"(",
"work_id",
")",
")",
"logging",
".",
"info",
"(",
"'Work %s is done'",
",",
"work_id",
")",
"# indicate that work is completed",
"is_work_update",
"=",
"self",
".",
"defense_work",
".",
"update_work_as_completed",
"(",
"self",
".",
"worker_id",
",",
"work_id",
",",
"other_values",
"=",
"{",
"'elapsed_time'",
":",
"elapsed_time_sec",
",",
"'stat_correct'",
":",
"batch_result",
"[",
"0",
"]",
",",
"'stat_error'",
":",
"batch_result",
"[",
"1",
"]",
",",
"'stat_target_class'",
":",
"batch_result",
"[",
"2",
"]",
",",
"'stat_num_images'",
":",
"batch_result",
"[",
"3",
"]",
"}",
")",
"except",
"WorkerError",
"as",
"e",
":",
"logging",
".",
"info",
"(",
"'Failed to run work:\\n%s'",
",",
"str",
"(",
"e",
")",
")",
"if",
"str",
"(",
"e",
")",
".",
"startswith",
"(",
"'Docker returned non-zero retval'",
")",
":",
"logging",
".",
"info",
"(",
"'Running nvidia-docker to ensure that GPU works'",
")",
"shell_call",
"(",
"[",
"'nvidia-docker'",
",",
"'run'",
",",
"'--rm'",
",",
"'nvidia/cuda'",
",",
"'nvidia-smi'",
"]",
")",
"is_work_update",
"=",
"self",
".",
"defense_work",
".",
"update_work_as_completed",
"(",
"self",
".",
"worker_id",
",",
"work_id",
",",
"error",
"=",
"str",
"(",
"e",
")",
")",
"if",
"not",
"is_work_update",
":",
"logging",
".",
"warning",
"(",
"'Can'",
"'t update work \"%s\" as completed by worker %d'",
",",
"work_id",
",",
"self",
".",
"worker_id",
")",
"need_reload_work",
"=",
"True",
"logging",
".",
"info",
"(",
"'******** Finished evaluation of defenses ********'",
")"
] |
Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
|
[
"Method",
"which",
"evaluates",
"all",
"defense",
"work",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L826-L890
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/worker.py
|
EvaluationWorker.run_work
|
def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses()
|
python
|
def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses()
|
[
"def",
"run_work",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
":",
"sudo_remove_dirtree",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
"self",
".",
"run_attacks",
"(",
")",
"self",
".",
"run_defenses",
"(",
")"
] |
Run attacks and defenses
|
[
"Run",
"attacks",
"and",
"defenses"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L892-L897
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/attack.py
|
arg_type
|
def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently supported: numpy darray or something that can ducktype it
returns:
API contract is to return a hashable object describing all
structural consequences of argument values that can otherwise
be fed into a graph of fixed structure.
Currently this is implemented as a tuple of tuples that track:
- whether each argument was passed
- whether each argument was passed and not None
- the dtype of each argument
Callers shouldn't rely on the exact structure of this object,
just its hashability and one-to-one mapping between graph structures.
"""
assert isinstance(arg_names, tuple)
passed = tuple(name in kwargs for name in arg_names)
passed_and_not_none = []
for name in arg_names:
if name in kwargs:
passed_and_not_none.append(kwargs[name] is not None)
else:
passed_and_not_none.append(False)
passed_and_not_none = tuple(passed_and_not_none)
dtypes = []
for name in arg_names:
if name not in kwargs:
dtypes.append(None)
continue
value = kwargs[name]
if value is None:
dtypes.append(None)
continue
assert hasattr(value, 'dtype'), type(value)
dtype = value.dtype
if not isinstance(dtype, np.dtype):
dtype = dtype.as_np_dtype
assert isinstance(dtype, np.dtype)
dtypes.append(dtype)
dtypes = tuple(dtypes)
return (passed, passed_and_not_none, dtypes)
|
python
|
def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently supported: numpy darray or something that can ducktype it
returns:
API contract is to return a hashable object describing all
structural consequences of argument values that can otherwise
be fed into a graph of fixed structure.
Currently this is implemented as a tuple of tuples that track:
- whether each argument was passed
- whether each argument was passed and not None
- the dtype of each argument
Callers shouldn't rely on the exact structure of this object,
just its hashability and one-to-one mapping between graph structures.
"""
assert isinstance(arg_names, tuple)
passed = tuple(name in kwargs for name in arg_names)
passed_and_not_none = []
for name in arg_names:
if name in kwargs:
passed_and_not_none.append(kwargs[name] is not None)
else:
passed_and_not_none.append(False)
passed_and_not_none = tuple(passed_and_not_none)
dtypes = []
for name in arg_names:
if name not in kwargs:
dtypes.append(None)
continue
value = kwargs[name]
if value is None:
dtypes.append(None)
continue
assert hasattr(value, 'dtype'), type(value)
dtype = value.dtype
if not isinstance(dtype, np.dtype):
dtype = dtype.as_np_dtype
assert isinstance(dtype, np.dtype)
dtypes.append(dtype)
dtypes = tuple(dtypes)
return (passed, passed_and_not_none, dtypes)
|
[
"def",
"arg_type",
"(",
"arg_names",
",",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"arg_names",
",",
"tuple",
")",
"passed",
"=",
"tuple",
"(",
"name",
"in",
"kwargs",
"for",
"name",
"in",
"arg_names",
")",
"passed_and_not_none",
"=",
"[",
"]",
"for",
"name",
"in",
"arg_names",
":",
"if",
"name",
"in",
"kwargs",
":",
"passed_and_not_none",
".",
"append",
"(",
"kwargs",
"[",
"name",
"]",
"is",
"not",
"None",
")",
"else",
":",
"passed_and_not_none",
".",
"append",
"(",
"False",
")",
"passed_and_not_none",
"=",
"tuple",
"(",
"passed_and_not_none",
")",
"dtypes",
"=",
"[",
"]",
"for",
"name",
"in",
"arg_names",
":",
"if",
"name",
"not",
"in",
"kwargs",
":",
"dtypes",
".",
"append",
"(",
"None",
")",
"continue",
"value",
"=",
"kwargs",
"[",
"name",
"]",
"if",
"value",
"is",
"None",
":",
"dtypes",
".",
"append",
"(",
"None",
")",
"continue",
"assert",
"hasattr",
"(",
"value",
",",
"'dtype'",
")",
",",
"type",
"(",
"value",
")",
"dtype",
"=",
"value",
".",
"dtype",
"if",
"not",
"isinstance",
"(",
"dtype",
",",
"np",
".",
"dtype",
")",
":",
"dtype",
"=",
"dtype",
".",
"as_np_dtype",
"assert",
"isinstance",
"(",
"dtype",
",",
"np",
".",
"dtype",
")",
"dtypes",
".",
"append",
"(",
"dtype",
")",
"dtypes",
"=",
"tuple",
"(",
"dtypes",
")",
"return",
"(",
"passed",
",",
"passed_and_not_none",
",",
"dtypes",
")"
] |
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently supported: numpy darray or something that can ducktype it
returns:
API contract is to return a hashable object describing all
structural consequences of argument values that can otherwise
be fed into a graph of fixed structure.
Currently this is implemented as a tuple of tuples that track:
- whether each argument was passed
- whether each argument was passed and not None
- the dtype of each argument
Callers shouldn't rely on the exact structure of this object,
just its hashability and one-to-one mapping between graph structures.
|
[
"Returns",
"a",
"hashable",
"summary",
"of",
"the",
"types",
"of",
"arg_names",
"within",
"kwargs",
".",
":",
"param",
"arg_names",
":",
"tuple",
"containing",
"names",
"of",
"relevant",
"arguments",
":",
"param",
"kwargs",
":",
"dict",
"mapping",
"string",
"argument",
"names",
"to",
"values",
".",
"These",
"must",
"be",
"values",
"for",
"which",
"we",
"can",
"create",
"a",
"tf",
"placeholder",
".",
"Currently",
"supported",
":",
"numpy",
"darray",
"or",
"something",
"that",
"can",
"ducktype",
"it",
"returns",
":",
"API",
"contract",
"is",
"to",
"return",
"a",
"hashable",
"object",
"describing",
"all",
"structural",
"consequences",
"of",
"argument",
"values",
"that",
"can",
"otherwise",
"be",
"fed",
"into",
"a",
"graph",
"of",
"fixed",
"structure",
".",
"Currently",
"this",
"is",
"implemented",
"as",
"a",
"tuple",
"of",
"tuples",
"that",
"track",
":",
"-",
"whether",
"each",
"argument",
"was",
"passed",
"-",
"whether",
"each",
"argument",
"was",
"passed",
"and",
"not",
"None",
"-",
"the",
"dtype",
"of",
"each",
"argument",
"Callers",
"shouldn",
"t",
"rely",
"on",
"the",
"exact",
"structure",
"of",
"this",
"object",
"just",
"its",
"hashability",
"and",
"one",
"-",
"to",
"-",
"one",
"mapping",
"between",
"graph",
"structures",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L304-L347
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/attack.py
|
Attack.construct_graph
|
def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take different values.
:param x_val: symbolic adversarial example
:param hash_key: the key used to store this graph in our cache
"""
# try our very best to create a TF placeholder for each of the
# feedable keyword arguments, and check the types are one of
# the allowed types
class_name = str(self.__class__).split(".")[-1][:-2]
_logger.info("Constructing new graph for attack " + class_name)
# remove the None arguments, they are just left blank
for k in list(feedable.keys()):
if feedable[k] is None:
del feedable[k]
# process all of the rest and create placeholders for them
new_kwargs = dict(x for x in fixed.items())
for name, value in feedable.items():
given_type = value.dtype
if isinstance(value, np.ndarray):
if value.ndim == 0:
# This is pretty clearly not a batch of data
new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name)
else:
# Assume that this is a batch of data, make the first axis variable
# in size
new_shape = [None] + list(value.shape[1:])
new_kwargs[name] = tf.placeholder(given_type, new_shape, name=name)
elif isinstance(value, utils.known_number_types):
new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name)
else:
raise ValueError("Could not identify type of argument " +
name + ": " + str(value))
# x is a special placeholder we always want to have
x_shape = [None] + list(x_val.shape)[1:]
x = tf.placeholder(self.tf_dtype, shape=x_shape)
# now we generate the graph that we want
x_adv = self.generate(x, **new_kwargs)
self.graphs[hash_key] = (x, new_kwargs, x_adv)
if len(self.graphs) >= 10:
warnings.warn("Calling generate_np() with multiple different "
"structural parameters is inefficient and should"
" be avoided. Calling generate() is preferred.")
|
python
|
def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take different values.
:param x_val: symbolic adversarial example
:param hash_key: the key used to store this graph in our cache
"""
# try our very best to create a TF placeholder for each of the
# feedable keyword arguments, and check the types are one of
# the allowed types
class_name = str(self.__class__).split(".")[-1][:-2]
_logger.info("Constructing new graph for attack " + class_name)
# remove the None arguments, they are just left blank
for k in list(feedable.keys()):
if feedable[k] is None:
del feedable[k]
# process all of the rest and create placeholders for them
new_kwargs = dict(x for x in fixed.items())
for name, value in feedable.items():
given_type = value.dtype
if isinstance(value, np.ndarray):
if value.ndim == 0:
# This is pretty clearly not a batch of data
new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name)
else:
# Assume that this is a batch of data, make the first axis variable
# in size
new_shape = [None] + list(value.shape[1:])
new_kwargs[name] = tf.placeholder(given_type, new_shape, name=name)
elif isinstance(value, utils.known_number_types):
new_kwargs[name] = tf.placeholder(given_type, shape=[], name=name)
else:
raise ValueError("Could not identify type of argument " +
name + ": " + str(value))
# x is a special placeholder we always want to have
x_shape = [None] + list(x_val.shape)[1:]
x = tf.placeholder(self.tf_dtype, shape=x_shape)
# now we generate the graph that we want
x_adv = self.generate(x, **new_kwargs)
self.graphs[hash_key] = (x, new_kwargs, x_adv)
if len(self.graphs) >= 10:
warnings.warn("Calling generate_np() with multiple different "
"structural parameters is inefficient and should"
" be avoided. Calling generate() is preferred.")
|
[
"def",
"construct_graph",
"(",
"self",
",",
"fixed",
",",
"feedable",
",",
"x_val",
",",
"hash_key",
")",
":",
"# try our very best to create a TF placeholder for each of the",
"# feedable keyword arguments, and check the types are one of",
"# the allowed types",
"class_name",
"=",
"str",
"(",
"self",
".",
"__class__",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"2",
"]",
"_logger",
".",
"info",
"(",
"\"Constructing new graph for attack \"",
"+",
"class_name",
")",
"# remove the None arguments, they are just left blank",
"for",
"k",
"in",
"list",
"(",
"feedable",
".",
"keys",
"(",
")",
")",
":",
"if",
"feedable",
"[",
"k",
"]",
"is",
"None",
":",
"del",
"feedable",
"[",
"k",
"]",
"# process all of the rest and create placeholders for them",
"new_kwargs",
"=",
"dict",
"(",
"x",
"for",
"x",
"in",
"fixed",
".",
"items",
"(",
")",
")",
"for",
"name",
",",
"value",
"in",
"feedable",
".",
"items",
"(",
")",
":",
"given_type",
"=",
"value",
".",
"dtype",
"if",
"isinstance",
"(",
"value",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"value",
".",
"ndim",
"==",
"0",
":",
"# This is pretty clearly not a batch of data",
"new_kwargs",
"[",
"name",
"]",
"=",
"tf",
".",
"placeholder",
"(",
"given_type",
",",
"shape",
"=",
"[",
"]",
",",
"name",
"=",
"name",
")",
"else",
":",
"# Assume that this is a batch of data, make the first axis variable",
"# in size",
"new_shape",
"=",
"[",
"None",
"]",
"+",
"list",
"(",
"value",
".",
"shape",
"[",
"1",
":",
"]",
")",
"new_kwargs",
"[",
"name",
"]",
"=",
"tf",
".",
"placeholder",
"(",
"given_type",
",",
"new_shape",
",",
"name",
"=",
"name",
")",
"elif",
"isinstance",
"(",
"value",
",",
"utils",
".",
"known_number_types",
")",
":",
"new_kwargs",
"[",
"name",
"]",
"=",
"tf",
".",
"placeholder",
"(",
"given_type",
",",
"shape",
"=",
"[",
"]",
",",
"name",
"=",
"name",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Could not identify type of argument \"",
"+",
"name",
"+",
"\": \"",
"+",
"str",
"(",
"value",
")",
")",
"# x is a special placeholder we always want to have",
"x_shape",
"=",
"[",
"None",
"]",
"+",
"list",
"(",
"x_val",
".",
"shape",
")",
"[",
"1",
":",
"]",
"x",
"=",
"tf",
".",
"placeholder",
"(",
"self",
".",
"tf_dtype",
",",
"shape",
"=",
"x_shape",
")",
"# now we generate the graph that we want",
"x_adv",
"=",
"self",
".",
"generate",
"(",
"x",
",",
"*",
"*",
"new_kwargs",
")",
"self",
".",
"graphs",
"[",
"hash_key",
"]",
"=",
"(",
"x",
",",
"new_kwargs",
",",
"x_adv",
")",
"if",
"len",
"(",
"self",
".",
"graphs",
")",
">=",
"10",
":",
"warnings",
".",
"warn",
"(",
"\"Calling generate_np() with multiple different \"",
"\"structural parameters is inefficient and should\"",
"\" be avoided. Calling generate() is preferred.\"",
")"
] |
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take different values.
:param x_val: symbolic adversarial example
:param hash_key: the key used to store this graph in our cache
|
[
"Construct",
"the",
"graph",
"required",
"to",
"run",
"the",
"attack",
"through",
"generate_np",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L113-L165
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/attack.py
|
Attack.generate_np
|
def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples.
"""
if self.sess is None:
raise ValueError("Cannot use `generate_np` when no `sess` was"
" provided")
packed = self.construct_variables(kwargs)
fixed, feedable, _, hash_key = packed
if hash_key not in self.graphs:
self.construct_graph(fixed, feedable, x_val, hash_key)
else:
# remove the None arguments, they are just left blank
for k in list(feedable.keys()):
if feedable[k] is None:
del feedable[k]
x, new_kwargs, x_adv = self.graphs[hash_key]
feed_dict = {x: x_val}
for name in feedable:
feed_dict[new_kwargs[name]] = feedable[name]
return self.sess.run(x_adv, feed_dict)
|
python
|
def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples.
"""
if self.sess is None:
raise ValueError("Cannot use `generate_np` when no `sess` was"
" provided")
packed = self.construct_variables(kwargs)
fixed, feedable, _, hash_key = packed
if hash_key not in self.graphs:
self.construct_graph(fixed, feedable, x_val, hash_key)
else:
# remove the None arguments, they are just left blank
for k in list(feedable.keys()):
if feedable[k] is None:
del feedable[k]
x, new_kwargs, x_adv = self.graphs[hash_key]
feed_dict = {x: x_val}
for name in feedable:
feed_dict[new_kwargs[name]] = feedable[name]
return self.sess.run(x_adv, feed_dict)
|
[
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot use `generate_np` when no `sess` was\"",
"\" provided\"",
")",
"packed",
"=",
"self",
".",
"construct_variables",
"(",
"kwargs",
")",
"fixed",
",",
"feedable",
",",
"_",
",",
"hash_key",
"=",
"packed",
"if",
"hash_key",
"not",
"in",
"self",
".",
"graphs",
":",
"self",
".",
"construct_graph",
"(",
"fixed",
",",
"feedable",
",",
"x_val",
",",
"hash_key",
")",
"else",
":",
"# remove the None arguments, they are just left blank",
"for",
"k",
"in",
"list",
"(",
"feedable",
".",
"keys",
"(",
")",
")",
":",
"if",
"feedable",
"[",
"k",
"]",
"is",
"None",
":",
"del",
"feedable",
"[",
"k",
"]",
"x",
",",
"new_kwargs",
",",
"x_adv",
"=",
"self",
".",
"graphs",
"[",
"hash_key",
"]",
"feed_dict",
"=",
"{",
"x",
":",
"x_val",
"}",
"for",
"name",
"in",
"feedable",
":",
"feed_dict",
"[",
"new_kwargs",
"[",
"name",
"]",
"]",
"=",
"feedable",
"[",
"name",
"]",
"return",
"self",
".",
"sess",
".",
"run",
"(",
"x_adv",
",",
"feed_dict",
")"
] |
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples.
|
[
"Generate",
"adversarial",
"examples",
"and",
"return",
"them",
"as",
"a",
"NumPy",
"array",
".",
"Sub",
"-",
"classes",
"*",
"should",
"not",
"*",
"implement",
"this",
"method",
"unless",
"they",
"must",
"perform",
"special",
"handling",
"of",
"arguments",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L167-L200
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/attack.py
|
Attack.construct_variables
|
def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
"""
if isinstance(self.feedable_kwargs, dict):
warnings.warn("Using a dict for `feedable_kwargs is deprecated."
"Switch to using a tuple."
"It is not longer necessary to specify the types "
"of the arguments---we build a different graph "
"for each received type."
"Using a dict may become an error on or after "
"2019-04-18.")
feedable_names = tuple(sorted(self.feedable_kwargs.keys()))
else:
feedable_names = self.feedable_kwargs
if not isinstance(feedable_names, tuple):
raise TypeError("Attack.feedable_kwargs should be a tuple, but "
"for subclass " + str(type(self)) + " it is "
+ str(self.feedable_kwargs) + " of type "
+ str(type(self.feedable_kwargs)))
# the set of arguments that are structural properties of the attack
# if these arguments are different, we must construct a new graph
fixed = dict(
(k, v) for k, v in kwargs.items() if k in self.structural_kwargs)
# the set of arguments that are passed as placeholders to the graph
# on each call, and can change without constructing a new graph
feedable = {k: v for k, v in kwargs.items() if k in feedable_names}
for k in feedable:
if isinstance(feedable[k], (float, int)):
feedable[k] = np.array(feedable[k])
for key in kwargs:
if key not in fixed and key not in feedable:
raise ValueError(str(type(self)) + ": Undeclared argument: " + key)
feed_arg_type = arg_type(feedable_names, feedable)
if not all(isinstance(value, collections.Hashable)
for value in fixed.values()):
# we have received a fixed value that isn't hashable
# this means we can't cache this graph for later use,
# and it will have to be discarded later
hash_key = None
else:
# create a unique key for this set of fixed paramaters
hash_key = tuple(sorted(fixed.items())) + tuple([feed_arg_type])
return fixed, feedable, feed_arg_type, hash_key
|
python
|
def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
"""
if isinstance(self.feedable_kwargs, dict):
warnings.warn("Using a dict for `feedable_kwargs is deprecated."
"Switch to using a tuple."
"It is not longer necessary to specify the types "
"of the arguments---we build a different graph "
"for each received type."
"Using a dict may become an error on or after "
"2019-04-18.")
feedable_names = tuple(sorted(self.feedable_kwargs.keys()))
else:
feedable_names = self.feedable_kwargs
if not isinstance(feedable_names, tuple):
raise TypeError("Attack.feedable_kwargs should be a tuple, but "
"for subclass " + str(type(self)) + " it is "
+ str(self.feedable_kwargs) + " of type "
+ str(type(self.feedable_kwargs)))
# the set of arguments that are structural properties of the attack
# if these arguments are different, we must construct a new graph
fixed = dict(
(k, v) for k, v in kwargs.items() if k in self.structural_kwargs)
# the set of arguments that are passed as placeholders to the graph
# on each call, and can change without constructing a new graph
feedable = {k: v for k, v in kwargs.items() if k in feedable_names}
for k in feedable:
if isinstance(feedable[k], (float, int)):
feedable[k] = np.array(feedable[k])
for key in kwargs:
if key not in fixed and key not in feedable:
raise ValueError(str(type(self)) + ": Undeclared argument: " + key)
feed_arg_type = arg_type(feedable_names, feedable)
if not all(isinstance(value, collections.Hashable)
for value in fixed.values()):
# we have received a fixed value that isn't hashable
# this means we can't cache this graph for later use,
# and it will have to be discarded later
hash_key = None
else:
# create a unique key for this set of fixed paramaters
hash_key = tuple(sorted(fixed.items())) + tuple([feed_arg_type])
return fixed, feedable, feed_arg_type, hash_key
|
[
"def",
"construct_variables",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"feedable_kwargs",
",",
"dict",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using a dict for `feedable_kwargs is deprecated.\"",
"\"Switch to using a tuple.\"",
"\"It is not longer necessary to specify the types \"",
"\"of the arguments---we build a different graph \"",
"\"for each received type.\"",
"\"Using a dict may become an error on or after \"",
"\"2019-04-18.\"",
")",
"feedable_names",
"=",
"tuple",
"(",
"sorted",
"(",
"self",
".",
"feedable_kwargs",
".",
"keys",
"(",
")",
")",
")",
"else",
":",
"feedable_names",
"=",
"self",
".",
"feedable_kwargs",
"if",
"not",
"isinstance",
"(",
"feedable_names",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"(",
"\"Attack.feedable_kwargs should be a tuple, but \"",
"\"for subclass \"",
"+",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\" it is \"",
"+",
"str",
"(",
"self",
".",
"feedable_kwargs",
")",
"+",
"\" of type \"",
"+",
"str",
"(",
"type",
"(",
"self",
".",
"feedable_kwargs",
")",
")",
")",
"# the set of arguments that are structural properties of the attack",
"# if these arguments are different, we must construct a new graph",
"fixed",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"in",
"self",
".",
"structural_kwargs",
")",
"# the set of arguments that are passed as placeholders to the graph",
"# on each call, and can change without constructing a new graph",
"feedable",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"in",
"feedable_names",
"}",
"for",
"k",
"in",
"feedable",
":",
"if",
"isinstance",
"(",
"feedable",
"[",
"k",
"]",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"feedable",
"[",
"k",
"]",
"=",
"np",
".",
"array",
"(",
"feedable",
"[",
"k",
"]",
")",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"not",
"in",
"fixed",
"and",
"key",
"not",
"in",
"feedable",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\": Undeclared argument: \"",
"+",
"key",
")",
"feed_arg_type",
"=",
"arg_type",
"(",
"feedable_names",
",",
"feedable",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Hashable",
")",
"for",
"value",
"in",
"fixed",
".",
"values",
"(",
")",
")",
":",
"# we have received a fixed value that isn't hashable",
"# this means we can't cache this graph for later use,",
"# and it will have to be discarded later",
"hash_key",
"=",
"None",
"else",
":",
"# create a unique key for this set of fixed paramaters",
"hash_key",
"=",
"tuple",
"(",
"sorted",
"(",
"fixed",
".",
"items",
"(",
")",
")",
")",
"+",
"tuple",
"(",
"[",
"feed_arg_type",
"]",
")",
"return",
"fixed",
",",
"feedable",
",",
"feed_arg_type",
",",
"hash_key"
] |
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
|
[
"Construct",
"the",
"inputs",
"to",
"the",
"attack",
"graph",
"to",
"be",
"used",
"by",
"generate_np",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L202-L258
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/attack.py
|
Attack.get_or_guess_labels
|
def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
"""
if 'y' in kwargs and 'y_target' in kwargs:
raise ValueError("Can not set both 'y' and 'y_target'.")
elif 'y' in kwargs:
labels = kwargs['y']
elif 'y_target' in kwargs and kwargs['y_target'] is not None:
labels = kwargs['y_target']
else:
preds = self.model.get_probs(x)
preds_max = reduce_max(preds, 1, keepdims=True)
original_predictions = tf.to_float(tf.equal(preds, preds_max))
labels = tf.stop_gradient(original_predictions)
del preds
if isinstance(labels, np.ndarray):
nb_classes = labels.shape[1]
else:
nb_classes = labels.get_shape().as_list()[1]
return labels, nb_classes
|
python
|
def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
"""
if 'y' in kwargs and 'y_target' in kwargs:
raise ValueError("Can not set both 'y' and 'y_target'.")
elif 'y' in kwargs:
labels = kwargs['y']
elif 'y_target' in kwargs and kwargs['y_target'] is not None:
labels = kwargs['y_target']
else:
preds = self.model.get_probs(x)
preds_max = reduce_max(preds, 1, keepdims=True)
original_predictions = tf.to_float(tf.equal(preds, preds_max))
labels = tf.stop_gradient(original_predictions)
del preds
if isinstance(labels, np.ndarray):
nb_classes = labels.shape[1]
else:
nb_classes = labels.get_shape().as_list()[1]
return labels, nb_classes
|
[
"def",
"get_or_guess_labels",
"(",
"self",
",",
"x",
",",
"kwargs",
")",
":",
"if",
"'y'",
"in",
"kwargs",
"and",
"'y_target'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Can not set both 'y' and 'y_target'.\"",
")",
"elif",
"'y'",
"in",
"kwargs",
":",
"labels",
"=",
"kwargs",
"[",
"'y'",
"]",
"elif",
"'y_target'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'y_target'",
"]",
"is",
"not",
"None",
":",
"labels",
"=",
"kwargs",
"[",
"'y_target'",
"]",
"else",
":",
"preds",
"=",
"self",
".",
"model",
".",
"get_probs",
"(",
"x",
")",
"preds_max",
"=",
"reduce_max",
"(",
"preds",
",",
"1",
",",
"keepdims",
"=",
"True",
")",
"original_predictions",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"equal",
"(",
"preds",
",",
"preds_max",
")",
")",
"labels",
"=",
"tf",
".",
"stop_gradient",
"(",
"original_predictions",
")",
"del",
"preds",
"if",
"isinstance",
"(",
"labels",
",",
"np",
".",
"ndarray",
")",
":",
"nb_classes",
"=",
"labels",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"nb_classes",
"=",
"labels",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
"]",
"return",
"labels",
",",
"nb_classes"
] |
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
|
[
"Get",
"the",
"label",
"to",
"use",
"in",
"generating",
"an",
"adversarial",
"example",
"for",
"x",
".",
"The",
"kwargs",
"are",
"fed",
"directly",
"from",
"the",
"kwargs",
"of",
"the",
"attack",
".",
"If",
"y",
"is",
"in",
"kwargs",
"then",
"assume",
"it",
"s",
"an",
"untargeted",
"attack",
"and",
"use",
"that",
"as",
"the",
"label",
".",
"If",
"y_target",
"is",
"in",
"kwargs",
"and",
"is",
"not",
"none",
"then",
"assume",
"it",
"s",
"a",
"targeted",
"attack",
"and",
"use",
"that",
"as",
"the",
"label",
".",
"Otherwise",
"use",
"the",
"model",
"s",
"prediction",
"as",
"the",
"label",
"and",
"perform",
"an",
"untargeted",
"attack",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L260-L287
|
train
|
tensorflow/cleverhans
|
examples/RL-attack/model.py
|
dueling_model
|
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers.convolution2d(out, num_outputs=32, kernel_size=8,
stride=4, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=4,
stride=2, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=3,
stride=1, activation_fn=tf.nn.relu)
out = layers.flatten(out)
with tf.variable_scope("state_value"):
if noisy:
# Apply noisy network on fully connected layers
# ref: https://arxiv.org/abs/1706.10295
state_hidden = noisy_dense(out, name='noisy_fc1', size=512,
activation_fn=tf.nn.relu)
state_score = noisy_dense(state_hidden, name='noisy_fc2',
size=1)
else:
state_hidden = layers.fully_connected(
out,
num_outputs=512,
activation_fn=tf.nn.relu
)
state_score = layers.fully_connected(state_hidden,
num_outputs=1,
activation_fn=None)
with tf.variable_scope("action_value"):
if noisy:
# Apply noisy network on fully connected layers
# ref: https://arxiv.org/abs/1706.10295
actions_hidden = noisy_dense(out, name='noisy_fc1', size=512,
activation_fn=tf.nn.relu)
action_scores = noisy_dense(actions_hidden, name='noisy_fc2',
size=num_actions)
else:
actions_hidden = layers.fully_connected(
out,
num_outputs=512,
activation_fn=tf.nn.relu
)
action_scores = layers.fully_connected(
actions_hidden,
num_outputs=num_actions,
activation_fn=None
)
action_scores_mean = tf.reduce_mean(action_scores, 1)
action_scores = action_scores - tf.expand_dims(
action_scores_mean,
1
)
return state_score + action_scores
|
python
|
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers.convolution2d(out, num_outputs=32, kernel_size=8,
stride=4, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=4,
stride=2, activation_fn=tf.nn.relu)
out = layers.convolution2d(out, num_outputs=64, kernel_size=3,
stride=1, activation_fn=tf.nn.relu)
out = layers.flatten(out)
with tf.variable_scope("state_value"):
if noisy:
# Apply noisy network on fully connected layers
# ref: https://arxiv.org/abs/1706.10295
state_hidden = noisy_dense(out, name='noisy_fc1', size=512,
activation_fn=tf.nn.relu)
state_score = noisy_dense(state_hidden, name='noisy_fc2',
size=1)
else:
state_hidden = layers.fully_connected(
out,
num_outputs=512,
activation_fn=tf.nn.relu
)
state_score = layers.fully_connected(state_hidden,
num_outputs=1,
activation_fn=None)
with tf.variable_scope("action_value"):
if noisy:
# Apply noisy network on fully connected layers
# ref: https://arxiv.org/abs/1706.10295
actions_hidden = noisy_dense(out, name='noisy_fc1', size=512,
activation_fn=tf.nn.relu)
action_scores = noisy_dense(actions_hidden, name='noisy_fc2',
size=num_actions)
else:
actions_hidden = layers.fully_connected(
out,
num_outputs=512,
activation_fn=tf.nn.relu
)
action_scores = layers.fully_connected(
actions_hidden,
num_outputs=num_actions,
activation_fn=None
)
action_scores_mean = tf.reduce_mean(action_scores, 1)
action_scores = action_scores - tf.expand_dims(
action_scores_mean,
1
)
return state_score + action_scores
|
[
"def",
"dueling_model",
"(",
"img_in",
",",
"num_actions",
",",
"scope",
",",
"noisy",
"=",
"False",
",",
"reuse",
"=",
"False",
",",
"concat_softmax",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"reuse",
"=",
"reuse",
")",
":",
"out",
"=",
"img_in",
"with",
"tf",
".",
"variable_scope",
"(",
"\"convnet\"",
")",
":",
"# original architecture",
"out",
"=",
"layers",
".",
"convolution2d",
"(",
"out",
",",
"num_outputs",
"=",
"32",
",",
"kernel_size",
"=",
"8",
",",
"stride",
"=",
"4",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"out",
"=",
"layers",
".",
"convolution2d",
"(",
"out",
",",
"num_outputs",
"=",
"64",
",",
"kernel_size",
"=",
"4",
",",
"stride",
"=",
"2",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"out",
"=",
"layers",
".",
"convolution2d",
"(",
"out",
",",
"num_outputs",
"=",
"64",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"1",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"out",
"=",
"layers",
".",
"flatten",
"(",
"out",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"\"state_value\"",
")",
":",
"if",
"noisy",
":",
"# Apply noisy network on fully connected layers",
"# ref: https://arxiv.org/abs/1706.10295",
"state_hidden",
"=",
"noisy_dense",
"(",
"out",
",",
"name",
"=",
"'noisy_fc1'",
",",
"size",
"=",
"512",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"state_score",
"=",
"noisy_dense",
"(",
"state_hidden",
",",
"name",
"=",
"'noisy_fc2'",
",",
"size",
"=",
"1",
")",
"else",
":",
"state_hidden",
"=",
"layers",
".",
"fully_connected",
"(",
"out",
",",
"num_outputs",
"=",
"512",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"state_score",
"=",
"layers",
".",
"fully_connected",
"(",
"state_hidden",
",",
"num_outputs",
"=",
"1",
",",
"activation_fn",
"=",
"None",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"\"action_value\"",
")",
":",
"if",
"noisy",
":",
"# Apply noisy network on fully connected layers",
"# ref: https://arxiv.org/abs/1706.10295",
"actions_hidden",
"=",
"noisy_dense",
"(",
"out",
",",
"name",
"=",
"'noisy_fc1'",
",",
"size",
"=",
"512",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"action_scores",
"=",
"noisy_dense",
"(",
"actions_hidden",
",",
"name",
"=",
"'noisy_fc2'",
",",
"size",
"=",
"num_actions",
")",
"else",
":",
"actions_hidden",
"=",
"layers",
".",
"fully_connected",
"(",
"out",
",",
"num_outputs",
"=",
"512",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"action_scores",
"=",
"layers",
".",
"fully_connected",
"(",
"actions_hidden",
",",
"num_outputs",
"=",
"num_actions",
",",
"activation_fn",
"=",
"None",
")",
"action_scores_mean",
"=",
"tf",
".",
"reduce_mean",
"(",
"action_scores",
",",
"1",
")",
"action_scores",
"=",
"action_scores",
"-",
"tf",
".",
"expand_dims",
"(",
"action_scores_mean",
",",
"1",
")",
"return",
"state_score",
"+",
"action_scores"
] |
As described in https://arxiv.org/abs/1511.06581
|
[
"As",
"described",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1511",
".",
"06581"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/RL-attack/model.py#L38-L95
|
train
|
tensorflow/cleverhans
|
cleverhans_tutorials/mnist_tutorial_jsma.py
|
mnist_tutorial_jsma
|
def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE):
"""
MNIST tutorial for the Jacobian-based saliency map approach (JSMA)
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param viz_enabled: (boolean) activate plots of adversarial examples
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param nb_classes: number of output classes
:param source_samples: number of test inputs to attack
:param learning_rate: learning rate for training
:return: an AccuracyReport object
"""
# Object used to keep track of (and return) key accuracies
report = AccuracyReport()
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
# Create TF session and set as Keras backend session
sess = tf.Session()
print("Created TensorFlow session.")
set_log_level(logging.DEBUG)
# Get MNIST test data
mnist = MNIST(train_start=train_start, train_end=train_end,
test_start=test_start, test_end=test_end)
x_train, y_train = mnist.get_set('train')
x_test, y_test = mnist.get_set('test')
# Obtain Image Parameters
img_rows, img_cols, nchannels = x_train.shape[1:4]
nb_classes = y_train.shape[1]
# Define input TF placeholder
x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols,
nchannels))
y = tf.placeholder(tf.float32, shape=(None, nb_classes))
nb_filters = 64
# Define TF model graph
model = ModelBasicCNN('model1', nb_classes, nb_filters)
preds = model.get_logits(x)
loss = CrossEntropy(model, smoothing=0.1)
print("Defined TensorFlow model graph.")
###########################################################################
# Training the model using TensorFlow
###########################################################################
# Train an MNIST model
train_params = {
'nb_epochs': nb_epochs,
'batch_size': batch_size,
'learning_rate': learning_rate
}
sess.run(tf.global_variables_initializer())
rng = np.random.RandomState([2017, 8, 30])
train(sess, loss, x_train, y_train, args=train_params, rng=rng)
# Evaluate the accuracy of the MNIST model on legitimate test examples
eval_params = {'batch_size': batch_size}
accuracy = model_eval(sess, x, y, preds, x_test, y_test, args=eval_params)
assert x_test.shape[0] == test_end - test_start, x_test.shape
print('Test accuracy on legitimate test examples: {0}'.format(accuracy))
report.clean_train_clean_eval = accuracy
###########################################################################
# Craft adversarial examples using the Jacobian-based saliency map approach
###########################################################################
print('Crafting ' + str(source_samples) + ' * ' + str(nb_classes - 1) +
' adversarial examples')
# Keep track of success (adversarial example classified in target)
results = np.zeros((nb_classes, source_samples), dtype='i')
# Rate of perturbed features for each test set example and target class
perturbations = np.zeros((nb_classes, source_samples), dtype='f')
# Initialize our array for grid visualization
grid_shape = (nb_classes, nb_classes, img_rows, img_cols, nchannels)
grid_viz_data = np.zeros(grid_shape, dtype='f')
# Instantiate a SaliencyMapMethod attack object
jsma = SaliencyMapMethod(model, sess=sess)
jsma_params = {'theta': 1., 'gamma': 0.1,
'clip_min': 0., 'clip_max': 1.,
'y_target': None}
figure = None
# Loop over the samples we want to perturb into adversarial examples
for sample_ind in xrange(0, source_samples):
print('--------------------------------------')
print('Attacking input %i/%i' % (sample_ind + 1, source_samples))
sample = x_test[sample_ind:(sample_ind + 1)]
# We want to find an adversarial example for each possible target class
# (i.e. all classes that differ from the label given in the dataset)
current_class = int(np.argmax(y_test[sample_ind]))
target_classes = other_classes(nb_classes, current_class)
# For the grid visualization, keep original images along the diagonal
grid_viz_data[current_class, current_class, :, :, :] = np.reshape(
sample, (img_rows, img_cols, nchannels))
# Loop over all target classes
for target in target_classes:
print('Generating adv. example for target class %i' % target)
# This call runs the Jacobian-based saliency map approach
one_hot_target = np.zeros((1, nb_classes), dtype=np.float32)
one_hot_target[0, target] = 1
jsma_params['y_target'] = one_hot_target
adv_x = jsma.generate_np(sample, **jsma_params)
# Check if success was achieved
res = int(model_argmax(sess, x, preds, adv_x) == target)
# Computer number of modified features
adv_x_reshape = adv_x.reshape(-1)
test_in_reshape = x_test[sample_ind].reshape(-1)
nb_changed = np.where(adv_x_reshape != test_in_reshape)[0].shape[0]
percent_perturb = float(nb_changed) / adv_x.reshape(-1).shape[0]
# Display the original and adversarial images side-by-side
if viz_enabled:
figure = pair_visual(
np.reshape(sample, (img_rows, img_cols, nchannels)),
np.reshape(adv_x, (img_rows, img_cols, nchannels)), figure)
# Add our adversarial example to our grid data
grid_viz_data[target, current_class, :, :, :] = np.reshape(
adv_x, (img_rows, img_cols, nchannels))
# Update the arrays for later analysis
results[target, sample_ind] = res
perturbations[target, sample_ind] = percent_perturb
print('--------------------------------------')
# Compute the number of adversarial examples that were successfully found
nb_targets_tried = ((nb_classes - 1) * source_samples)
succ_rate = float(np.sum(results)) / nb_targets_tried
print('Avg. rate of successful adv. examples {0:.4f}'.format(succ_rate))
report.clean_train_adv_eval = 1. - succ_rate
# Compute the average distortion introduced by the algorithm
percent_perturbed = np.mean(perturbations)
print('Avg. rate of perturbed features {0:.4f}'.format(percent_perturbed))
# Compute the average distortion introduced for successful samples only
percent_perturb_succ = np.mean(perturbations * (results == 1))
print('Avg. rate of perturbed features for successful '
'adversarial examples {0:.4f}'.format(percent_perturb_succ))
# Close TF session
sess.close()
# Finally, block & display a grid of all the adversarial examples
if viz_enabled:
import matplotlib.pyplot as plt
plt.close(figure)
_ = grid_visual(grid_viz_data)
return report
|
python
|
def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE):
"""
MNIST tutorial for the Jacobian-based saliency map approach (JSMA)
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param viz_enabled: (boolean) activate plots of adversarial examples
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param nb_classes: number of output classes
:param source_samples: number of test inputs to attack
:param learning_rate: learning rate for training
:return: an AccuracyReport object
"""
# Object used to keep track of (and return) key accuracies
report = AccuracyReport()
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
# Create TF session and set as Keras backend session
sess = tf.Session()
print("Created TensorFlow session.")
set_log_level(logging.DEBUG)
# Get MNIST test data
mnist = MNIST(train_start=train_start, train_end=train_end,
test_start=test_start, test_end=test_end)
x_train, y_train = mnist.get_set('train')
x_test, y_test = mnist.get_set('test')
# Obtain Image Parameters
img_rows, img_cols, nchannels = x_train.shape[1:4]
nb_classes = y_train.shape[1]
# Define input TF placeholder
x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols,
nchannels))
y = tf.placeholder(tf.float32, shape=(None, nb_classes))
nb_filters = 64
# Define TF model graph
model = ModelBasicCNN('model1', nb_classes, nb_filters)
preds = model.get_logits(x)
loss = CrossEntropy(model, smoothing=0.1)
print("Defined TensorFlow model graph.")
###########################################################################
# Training the model using TensorFlow
###########################################################################
# Train an MNIST model
train_params = {
'nb_epochs': nb_epochs,
'batch_size': batch_size,
'learning_rate': learning_rate
}
sess.run(tf.global_variables_initializer())
rng = np.random.RandomState([2017, 8, 30])
train(sess, loss, x_train, y_train, args=train_params, rng=rng)
# Evaluate the accuracy of the MNIST model on legitimate test examples
eval_params = {'batch_size': batch_size}
accuracy = model_eval(sess, x, y, preds, x_test, y_test, args=eval_params)
assert x_test.shape[0] == test_end - test_start, x_test.shape
print('Test accuracy on legitimate test examples: {0}'.format(accuracy))
report.clean_train_clean_eval = accuracy
###########################################################################
# Craft adversarial examples using the Jacobian-based saliency map approach
###########################################################################
print('Crafting ' + str(source_samples) + ' * ' + str(nb_classes - 1) +
' adversarial examples')
# Keep track of success (adversarial example classified in target)
results = np.zeros((nb_classes, source_samples), dtype='i')
# Rate of perturbed features for each test set example and target class
perturbations = np.zeros((nb_classes, source_samples), dtype='f')
# Initialize our array for grid visualization
grid_shape = (nb_classes, nb_classes, img_rows, img_cols, nchannels)
grid_viz_data = np.zeros(grid_shape, dtype='f')
# Instantiate a SaliencyMapMethod attack object
jsma = SaliencyMapMethod(model, sess=sess)
jsma_params = {'theta': 1., 'gamma': 0.1,
'clip_min': 0., 'clip_max': 1.,
'y_target': None}
figure = None
# Loop over the samples we want to perturb into adversarial examples
for sample_ind in xrange(0, source_samples):
print('--------------------------------------')
print('Attacking input %i/%i' % (sample_ind + 1, source_samples))
sample = x_test[sample_ind:(sample_ind + 1)]
# We want to find an adversarial example for each possible target class
# (i.e. all classes that differ from the label given in the dataset)
current_class = int(np.argmax(y_test[sample_ind]))
target_classes = other_classes(nb_classes, current_class)
# For the grid visualization, keep original images along the diagonal
grid_viz_data[current_class, current_class, :, :, :] = np.reshape(
sample, (img_rows, img_cols, nchannels))
# Loop over all target classes
for target in target_classes:
print('Generating adv. example for target class %i' % target)
# This call runs the Jacobian-based saliency map approach
one_hot_target = np.zeros((1, nb_classes), dtype=np.float32)
one_hot_target[0, target] = 1
jsma_params['y_target'] = one_hot_target
adv_x = jsma.generate_np(sample, **jsma_params)
# Check if success was achieved
res = int(model_argmax(sess, x, preds, adv_x) == target)
# Computer number of modified features
adv_x_reshape = adv_x.reshape(-1)
test_in_reshape = x_test[sample_ind].reshape(-1)
nb_changed = np.where(adv_x_reshape != test_in_reshape)[0].shape[0]
percent_perturb = float(nb_changed) / adv_x.reshape(-1).shape[0]
# Display the original and adversarial images side-by-side
if viz_enabled:
figure = pair_visual(
np.reshape(sample, (img_rows, img_cols, nchannels)),
np.reshape(adv_x, (img_rows, img_cols, nchannels)), figure)
# Add our adversarial example to our grid data
grid_viz_data[target, current_class, :, :, :] = np.reshape(
adv_x, (img_rows, img_cols, nchannels))
# Update the arrays for later analysis
results[target, sample_ind] = res
perturbations[target, sample_ind] = percent_perturb
print('--------------------------------------')
# Compute the number of adversarial examples that were successfully found
nb_targets_tried = ((nb_classes - 1) * source_samples)
succ_rate = float(np.sum(results)) / nb_targets_tried
print('Avg. rate of successful adv. examples {0:.4f}'.format(succ_rate))
report.clean_train_adv_eval = 1. - succ_rate
# Compute the average distortion introduced by the algorithm
percent_perturbed = np.mean(perturbations)
print('Avg. rate of perturbed features {0:.4f}'.format(percent_perturbed))
# Compute the average distortion introduced for successful samples only
percent_perturb_succ = np.mean(perturbations * (results == 1))
print('Avg. rate of perturbed features for successful '
'adversarial examples {0:.4f}'.format(percent_perturb_succ))
# Close TF session
sess.close()
# Finally, block & display a grid of all the adversarial examples
if viz_enabled:
import matplotlib.pyplot as plt
plt.close(figure)
_ = grid_visual(grid_viz_data)
return report
|
[
"def",
"mnist_tutorial_jsma",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"viz_enabled",
"=",
"VIZ_ENABLED",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"source_samples",
"=",
"SOURCE_SAMPLES",
",",
"learning_rate",
"=",
"LEARNING_RATE",
")",
":",
"# Object used to keep track of (and return) key accuracies",
"report",
"=",
"AccuracyReport",
"(",
")",
"# Set TF random seed to improve reproducibility",
"tf",
".",
"set_random_seed",
"(",
"1234",
")",
"# Create TF session and set as Keras backend session",
"sess",
"=",
"tf",
".",
"Session",
"(",
")",
"print",
"(",
"\"Created TensorFlow session.\"",
")",
"set_log_level",
"(",
"logging",
".",
"DEBUG",
")",
"# Get MNIST test data",
"mnist",
"=",
"MNIST",
"(",
"train_start",
"=",
"train_start",
",",
"train_end",
"=",
"train_end",
",",
"test_start",
"=",
"test_start",
",",
"test_end",
"=",
"test_end",
")",
"x_train",
",",
"y_train",
"=",
"mnist",
".",
"get_set",
"(",
"'train'",
")",
"x_test",
",",
"y_test",
"=",
"mnist",
".",
"get_set",
"(",
"'test'",
")",
"# Obtain Image Parameters",
"img_rows",
",",
"img_cols",
",",
"nchannels",
"=",
"x_train",
".",
"shape",
"[",
"1",
":",
"4",
"]",
"nb_classes",
"=",
"y_train",
".",
"shape",
"[",
"1",
"]",
"# Define input TF placeholder",
"x",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"(",
"None",
",",
"img_rows",
",",
"img_cols",
",",
"nchannels",
")",
")",
"y",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"(",
"None",
",",
"nb_classes",
")",
")",
"nb_filters",
"=",
"64",
"# Define TF model graph",
"model",
"=",
"ModelBasicCNN",
"(",
"'model1'",
",",
"nb_classes",
",",
"nb_filters",
")",
"preds",
"=",
"model",
".",
"get_logits",
"(",
"x",
")",
"loss",
"=",
"CrossEntropy",
"(",
"model",
",",
"smoothing",
"=",
"0.1",
")",
"print",
"(",
"\"Defined TensorFlow model graph.\"",
")",
"###########################################################################",
"# Training the model using TensorFlow",
"###########################################################################",
"# Train an MNIST model",
"train_params",
"=",
"{",
"'nb_epochs'",
":",
"nb_epochs",
",",
"'batch_size'",
":",
"batch_size",
",",
"'learning_rate'",
":",
"learning_rate",
"}",
"sess",
".",
"run",
"(",
"tf",
".",
"global_variables_initializer",
"(",
")",
")",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"[",
"2017",
",",
"8",
",",
"30",
"]",
")",
"train",
"(",
"sess",
",",
"loss",
",",
"x_train",
",",
"y_train",
",",
"args",
"=",
"train_params",
",",
"rng",
"=",
"rng",
")",
"# Evaluate the accuracy of the MNIST model on legitimate test examples",
"eval_params",
"=",
"{",
"'batch_size'",
":",
"batch_size",
"}",
"accuracy",
"=",
"model_eval",
"(",
"sess",
",",
"x",
",",
"y",
",",
"preds",
",",
"x_test",
",",
"y_test",
",",
"args",
"=",
"eval_params",
")",
"assert",
"x_test",
".",
"shape",
"[",
"0",
"]",
"==",
"test_end",
"-",
"test_start",
",",
"x_test",
".",
"shape",
"print",
"(",
"'Test accuracy on legitimate test examples: {0}'",
".",
"format",
"(",
"accuracy",
")",
")",
"report",
".",
"clean_train_clean_eval",
"=",
"accuracy",
"###########################################################################",
"# Craft adversarial examples using the Jacobian-based saliency map approach",
"###########################################################################",
"print",
"(",
"'Crafting '",
"+",
"str",
"(",
"source_samples",
")",
"+",
"' * '",
"+",
"str",
"(",
"nb_classes",
"-",
"1",
")",
"+",
"' adversarial examples'",
")",
"# Keep track of success (adversarial example classified in target)",
"results",
"=",
"np",
".",
"zeros",
"(",
"(",
"nb_classes",
",",
"source_samples",
")",
",",
"dtype",
"=",
"'i'",
")",
"# Rate of perturbed features for each test set example and target class",
"perturbations",
"=",
"np",
".",
"zeros",
"(",
"(",
"nb_classes",
",",
"source_samples",
")",
",",
"dtype",
"=",
"'f'",
")",
"# Initialize our array for grid visualization",
"grid_shape",
"=",
"(",
"nb_classes",
",",
"nb_classes",
",",
"img_rows",
",",
"img_cols",
",",
"nchannels",
")",
"grid_viz_data",
"=",
"np",
".",
"zeros",
"(",
"grid_shape",
",",
"dtype",
"=",
"'f'",
")",
"# Instantiate a SaliencyMapMethod attack object",
"jsma",
"=",
"SaliencyMapMethod",
"(",
"model",
",",
"sess",
"=",
"sess",
")",
"jsma_params",
"=",
"{",
"'theta'",
":",
"1.",
",",
"'gamma'",
":",
"0.1",
",",
"'clip_min'",
":",
"0.",
",",
"'clip_max'",
":",
"1.",
",",
"'y_target'",
":",
"None",
"}",
"figure",
"=",
"None",
"# Loop over the samples we want to perturb into adversarial examples",
"for",
"sample_ind",
"in",
"xrange",
"(",
"0",
",",
"source_samples",
")",
":",
"print",
"(",
"'--------------------------------------'",
")",
"print",
"(",
"'Attacking input %i/%i'",
"%",
"(",
"sample_ind",
"+",
"1",
",",
"source_samples",
")",
")",
"sample",
"=",
"x_test",
"[",
"sample_ind",
":",
"(",
"sample_ind",
"+",
"1",
")",
"]",
"# We want to find an adversarial example for each possible target class",
"# (i.e. all classes that differ from the label given in the dataset)",
"current_class",
"=",
"int",
"(",
"np",
".",
"argmax",
"(",
"y_test",
"[",
"sample_ind",
"]",
")",
")",
"target_classes",
"=",
"other_classes",
"(",
"nb_classes",
",",
"current_class",
")",
"# For the grid visualization, keep original images along the diagonal",
"grid_viz_data",
"[",
"current_class",
",",
"current_class",
",",
":",
",",
":",
",",
":",
"]",
"=",
"np",
".",
"reshape",
"(",
"sample",
",",
"(",
"img_rows",
",",
"img_cols",
",",
"nchannels",
")",
")",
"# Loop over all target classes",
"for",
"target",
"in",
"target_classes",
":",
"print",
"(",
"'Generating adv. example for target class %i'",
"%",
"target",
")",
"# This call runs the Jacobian-based saliency map approach",
"one_hot_target",
"=",
"np",
".",
"zeros",
"(",
"(",
"1",
",",
"nb_classes",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"one_hot_target",
"[",
"0",
",",
"target",
"]",
"=",
"1",
"jsma_params",
"[",
"'y_target'",
"]",
"=",
"one_hot_target",
"adv_x",
"=",
"jsma",
".",
"generate_np",
"(",
"sample",
",",
"*",
"*",
"jsma_params",
")",
"# Check if success was achieved",
"res",
"=",
"int",
"(",
"model_argmax",
"(",
"sess",
",",
"x",
",",
"preds",
",",
"adv_x",
")",
"==",
"target",
")",
"# Computer number of modified features",
"adv_x_reshape",
"=",
"adv_x",
".",
"reshape",
"(",
"-",
"1",
")",
"test_in_reshape",
"=",
"x_test",
"[",
"sample_ind",
"]",
".",
"reshape",
"(",
"-",
"1",
")",
"nb_changed",
"=",
"np",
".",
"where",
"(",
"adv_x_reshape",
"!=",
"test_in_reshape",
")",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"percent_perturb",
"=",
"float",
"(",
"nb_changed",
")",
"/",
"adv_x",
".",
"reshape",
"(",
"-",
"1",
")",
".",
"shape",
"[",
"0",
"]",
"# Display the original and adversarial images side-by-side",
"if",
"viz_enabled",
":",
"figure",
"=",
"pair_visual",
"(",
"np",
".",
"reshape",
"(",
"sample",
",",
"(",
"img_rows",
",",
"img_cols",
",",
"nchannels",
")",
")",
",",
"np",
".",
"reshape",
"(",
"adv_x",
",",
"(",
"img_rows",
",",
"img_cols",
",",
"nchannels",
")",
")",
",",
"figure",
")",
"# Add our adversarial example to our grid data",
"grid_viz_data",
"[",
"target",
",",
"current_class",
",",
":",
",",
":",
",",
":",
"]",
"=",
"np",
".",
"reshape",
"(",
"adv_x",
",",
"(",
"img_rows",
",",
"img_cols",
",",
"nchannels",
")",
")",
"# Update the arrays for later analysis",
"results",
"[",
"target",
",",
"sample_ind",
"]",
"=",
"res",
"perturbations",
"[",
"target",
",",
"sample_ind",
"]",
"=",
"percent_perturb",
"print",
"(",
"'--------------------------------------'",
")",
"# Compute the number of adversarial examples that were successfully found",
"nb_targets_tried",
"=",
"(",
"(",
"nb_classes",
"-",
"1",
")",
"*",
"source_samples",
")",
"succ_rate",
"=",
"float",
"(",
"np",
".",
"sum",
"(",
"results",
")",
")",
"/",
"nb_targets_tried",
"print",
"(",
"'Avg. rate of successful adv. examples {0:.4f}'",
".",
"format",
"(",
"succ_rate",
")",
")",
"report",
".",
"clean_train_adv_eval",
"=",
"1.",
"-",
"succ_rate",
"# Compute the average distortion introduced by the algorithm",
"percent_perturbed",
"=",
"np",
".",
"mean",
"(",
"perturbations",
")",
"print",
"(",
"'Avg. rate of perturbed features {0:.4f}'",
".",
"format",
"(",
"percent_perturbed",
")",
")",
"# Compute the average distortion introduced for successful samples only",
"percent_perturb_succ",
"=",
"np",
".",
"mean",
"(",
"perturbations",
"*",
"(",
"results",
"==",
"1",
")",
")",
"print",
"(",
"'Avg. rate of perturbed features for successful '",
"'adversarial examples {0:.4f}'",
".",
"format",
"(",
"percent_perturb_succ",
")",
")",
"# Close TF session",
"sess",
".",
"close",
"(",
")",
"# Finally, block & display a grid of all the adversarial examples",
"if",
"viz_enabled",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"plt",
".",
"close",
"(",
"figure",
")",
"_",
"=",
"grid_visual",
"(",
"grid_viz_data",
")",
"return",
"report"
] |
MNIST tutorial for the Jacobian-based saliency map approach (JSMA)
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param viz_enabled: (boolean) activate plots of adversarial examples
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param nb_classes: number of output classes
:param source_samples: number of test inputs to attack
:param learning_rate: learning rate for training
:return: an AccuracyReport object
|
[
"MNIST",
"tutorial",
"for",
"the",
"Jacobian",
"-",
"based",
"saliency",
"map",
"approach",
"(",
"JSMA",
")",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end",
":",
"index",
"of",
"last",
"training",
"set",
"example",
":",
"param",
"test_start",
":",
"index",
"of",
"first",
"test",
"set",
"example",
":",
"param",
"test_end",
":",
"index",
"of",
"last",
"test",
"set",
"example",
":",
"param",
"viz_enabled",
":",
"(",
"boolean",
")",
"activate",
"plots",
"of",
"adversarial",
"examples",
":",
"param",
"nb_epochs",
":",
"number",
"of",
"epochs",
"to",
"train",
"model",
":",
"param",
"batch_size",
":",
"size",
"of",
"training",
"batches",
":",
"param",
"nb_classes",
":",
"number",
"of",
"output",
"classes",
":",
"param",
"source_samples",
":",
"number",
"of",
"test",
"inputs",
"to",
"attack",
":",
"param",
"learning_rate",
":",
"learning",
"rate",
"for",
"training",
":",
"return",
":",
"an",
"AccuracyReport",
"object"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_jsma.py#L37-L208
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/momentum_iterative_method.py
|
MomentumIterativeMethod.generate
|
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
asserts = []
# If a data range was specified, check that the input was in that range
if self.clip_min is not None:
asserts.append(utils_tf.assert_greater_equal(x,
tf.cast(self.clip_min,
x.dtype)))
if self.clip_max is not None:
asserts.append(utils_tf.assert_less_equal(x,
tf.cast(self.clip_max,
x.dtype)))
# Initialize loop variables
momentum = tf.zeros_like(x)
adv_x = x
# Fix labels to the first model predictions for loss computation
y, _nb_classes = self.get_or_guess_labels(x, kwargs)
y = y / reduce_sum(y, 1, keepdims=True)
targeted = (self.y_target is not None)
def cond(i, _, __):
"""Iterate until number of iterations completed"""
return tf.less(i, self.nb_iter)
def body(i, ax, m):
"""Do a momentum step"""
logits = self.model.get_logits(ax)
loss = softmax_cross_entropy_with_logits(labels=y, logits=logits)
if targeted:
loss = -loss
# Define gradient of loss wrt input
grad, = tf.gradients(loss, ax)
# Normalize current gradient and add it to the accumulated gradient
red_ind = list(range(1, len(grad.get_shape())))
avoid_zero_div = tf.cast(1e-12, grad.dtype)
grad = grad / tf.maximum(
avoid_zero_div,
reduce_mean(tf.abs(grad), red_ind, keepdims=True))
m = self.decay_factor * m + grad
optimal_perturbation = optimize_linear(m, self.eps_iter, self.ord)
if self.ord == 1:
raise NotImplementedError("This attack hasn't been tested for ord=1."
"It's not clear that FGM makes a good inner "
"loop step for iterative optimization since "
"it updates just one coordinate at a time.")
# Update and clip adversarial example in current iteration
ax = ax + optimal_perturbation
ax = x + utils_tf.clip_eta(ax - x, self.ord, self.eps)
if self.clip_min is not None and self.clip_max is not None:
ax = utils_tf.clip_by_value(ax, self.clip_min, self.clip_max)
ax = tf.stop_gradient(ax)
return i + 1, ax, m
_, adv_x, _ = tf.while_loop(
cond, body, (tf.zeros([]), adv_x, momentum), back_prop=True,
maximum_iterations=self.nb_iter)
if self.sanity_checks:
with tf.control_dependencies(asserts):
adv_x = tf.identity(adv_x)
return adv_x
|
python
|
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
asserts = []
# If a data range was specified, check that the input was in that range
if self.clip_min is not None:
asserts.append(utils_tf.assert_greater_equal(x,
tf.cast(self.clip_min,
x.dtype)))
if self.clip_max is not None:
asserts.append(utils_tf.assert_less_equal(x,
tf.cast(self.clip_max,
x.dtype)))
# Initialize loop variables
momentum = tf.zeros_like(x)
adv_x = x
# Fix labels to the first model predictions for loss computation
y, _nb_classes = self.get_or_guess_labels(x, kwargs)
y = y / reduce_sum(y, 1, keepdims=True)
targeted = (self.y_target is not None)
def cond(i, _, __):
"""Iterate until number of iterations completed"""
return tf.less(i, self.nb_iter)
def body(i, ax, m):
"""Do a momentum step"""
logits = self.model.get_logits(ax)
loss = softmax_cross_entropy_with_logits(labels=y, logits=logits)
if targeted:
loss = -loss
# Define gradient of loss wrt input
grad, = tf.gradients(loss, ax)
# Normalize current gradient and add it to the accumulated gradient
red_ind = list(range(1, len(grad.get_shape())))
avoid_zero_div = tf.cast(1e-12, grad.dtype)
grad = grad / tf.maximum(
avoid_zero_div,
reduce_mean(tf.abs(grad), red_ind, keepdims=True))
m = self.decay_factor * m + grad
optimal_perturbation = optimize_linear(m, self.eps_iter, self.ord)
if self.ord == 1:
raise NotImplementedError("This attack hasn't been tested for ord=1."
"It's not clear that FGM makes a good inner "
"loop step for iterative optimization since "
"it updates just one coordinate at a time.")
# Update and clip adversarial example in current iteration
ax = ax + optimal_perturbation
ax = x + utils_tf.clip_eta(ax - x, self.ord, self.eps)
if self.clip_min is not None and self.clip_max is not None:
ax = utils_tf.clip_by_value(ax, self.clip_min, self.clip_max)
ax = tf.stop_gradient(ax)
return i + 1, ax, m
_, adv_x, _ = tf.while_loop(
cond, body, (tf.zeros([]), adv_x, momentum), back_prop=True,
maximum_iterations=self.nb_iter)
if self.sanity_checks:
with tf.control_dependencies(asserts):
adv_x = tf.identity(adv_x)
return adv_x
|
[
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"asserts",
"=",
"[",
"]",
"# If a data range was specified, check that the input was in that range",
"if",
"self",
".",
"clip_min",
"is",
"not",
"None",
":",
"asserts",
".",
"append",
"(",
"utils_tf",
".",
"assert_greater_equal",
"(",
"x",
",",
"tf",
".",
"cast",
"(",
"self",
".",
"clip_min",
",",
"x",
".",
"dtype",
")",
")",
")",
"if",
"self",
".",
"clip_max",
"is",
"not",
"None",
":",
"asserts",
".",
"append",
"(",
"utils_tf",
".",
"assert_less_equal",
"(",
"x",
",",
"tf",
".",
"cast",
"(",
"self",
".",
"clip_max",
",",
"x",
".",
"dtype",
")",
")",
")",
"# Initialize loop variables",
"momentum",
"=",
"tf",
".",
"zeros_like",
"(",
"x",
")",
"adv_x",
"=",
"x",
"# Fix labels to the first model predictions for loss computation",
"y",
",",
"_nb_classes",
"=",
"self",
".",
"get_or_guess_labels",
"(",
"x",
",",
"kwargs",
")",
"y",
"=",
"y",
"/",
"reduce_sum",
"(",
"y",
",",
"1",
",",
"keepdims",
"=",
"True",
")",
"targeted",
"=",
"(",
"self",
".",
"y_target",
"is",
"not",
"None",
")",
"def",
"cond",
"(",
"i",
",",
"_",
",",
"__",
")",
":",
"\"\"\"Iterate until number of iterations completed\"\"\"",
"return",
"tf",
".",
"less",
"(",
"i",
",",
"self",
".",
"nb_iter",
")",
"def",
"body",
"(",
"i",
",",
"ax",
",",
"m",
")",
":",
"\"\"\"Do a momentum step\"\"\"",
"logits",
"=",
"self",
".",
"model",
".",
"get_logits",
"(",
"ax",
")",
"loss",
"=",
"softmax_cross_entropy_with_logits",
"(",
"labels",
"=",
"y",
",",
"logits",
"=",
"logits",
")",
"if",
"targeted",
":",
"loss",
"=",
"-",
"loss",
"# Define gradient of loss wrt input",
"grad",
",",
"=",
"tf",
".",
"gradients",
"(",
"loss",
",",
"ax",
")",
"# Normalize current gradient and add it to the accumulated gradient",
"red_ind",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"grad",
".",
"get_shape",
"(",
")",
")",
")",
")",
"avoid_zero_div",
"=",
"tf",
".",
"cast",
"(",
"1e-12",
",",
"grad",
".",
"dtype",
")",
"grad",
"=",
"grad",
"/",
"tf",
".",
"maximum",
"(",
"avoid_zero_div",
",",
"reduce_mean",
"(",
"tf",
".",
"abs",
"(",
"grad",
")",
",",
"red_ind",
",",
"keepdims",
"=",
"True",
")",
")",
"m",
"=",
"self",
".",
"decay_factor",
"*",
"m",
"+",
"grad",
"optimal_perturbation",
"=",
"optimize_linear",
"(",
"m",
",",
"self",
".",
"eps_iter",
",",
"self",
".",
"ord",
")",
"if",
"self",
".",
"ord",
"==",
"1",
":",
"raise",
"NotImplementedError",
"(",
"\"This attack hasn't been tested for ord=1.\"",
"\"It's not clear that FGM makes a good inner \"",
"\"loop step for iterative optimization since \"",
"\"it updates just one coordinate at a time.\"",
")",
"# Update and clip adversarial example in current iteration",
"ax",
"=",
"ax",
"+",
"optimal_perturbation",
"ax",
"=",
"x",
"+",
"utils_tf",
".",
"clip_eta",
"(",
"ax",
"-",
"x",
",",
"self",
".",
"ord",
",",
"self",
".",
"eps",
")",
"if",
"self",
".",
"clip_min",
"is",
"not",
"None",
"and",
"self",
".",
"clip_max",
"is",
"not",
"None",
":",
"ax",
"=",
"utils_tf",
".",
"clip_by_value",
"(",
"ax",
",",
"self",
".",
"clip_min",
",",
"self",
".",
"clip_max",
")",
"ax",
"=",
"tf",
".",
"stop_gradient",
"(",
"ax",
")",
"return",
"i",
"+",
"1",
",",
"ax",
",",
"m",
"_",
",",
"adv_x",
",",
"_",
"=",
"tf",
".",
"while_loop",
"(",
"cond",
",",
"body",
",",
"(",
"tf",
".",
"zeros",
"(",
"[",
"]",
")",
",",
"adv_x",
",",
"momentum",
")",
",",
"back_prop",
"=",
"True",
",",
"maximum_iterations",
"=",
"self",
".",
"nb_iter",
")",
"if",
"self",
".",
"sanity_checks",
":",
"with",
"tf",
".",
"control_dependencies",
"(",
"asserts",
")",
":",
"adv_x",
"=",
"tf",
".",
"identity",
"(",
"adv_x",
")",
"return",
"adv_x"
] |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
|
[
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L43-L123
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/momentum_iterative_method.py
|
MomentumIterativeMethod.parse_params
|
def parse_params(self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
sanity_checks=True,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (optional float) step size for each attack iteration
:param nb_iter: (optional int) Number of attack iterations.
:param y: (optional) A tensor with the true labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param decay_factor: (optional) Decay factor for the momentum term.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Save attack-specific parameters
self.eps = eps
self.eps_iter = eps_iter
self.nb_iter = nb_iter
self.y = y
self.y_target = y_target
self.ord = ord
self.decay_factor = decay_factor
self.clip_min = clip_min
self.clip_max = clip_max
self.sanity_checks = sanity_checks
if self.y is not None and self.y_target is not None:
raise ValueError("Must not set both y and y_target")
# Check if order of the norm is acceptable given current implementation
if self.ord not in [np.inf, 1, 2]:
raise ValueError("Norm order must be either np.inf, 1, or 2.")
if len(kwargs.keys()) > 0:
warnings.warn("kwargs is unused and will be removed on or after "
"2019-04-26.")
return True
|
python
|
def parse_params(self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
sanity_checks=True,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (optional float) step size for each attack iteration
:param nb_iter: (optional int) Number of attack iterations.
:param y: (optional) A tensor with the true labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param decay_factor: (optional) Decay factor for the momentum term.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# Save attack-specific parameters
self.eps = eps
self.eps_iter = eps_iter
self.nb_iter = nb_iter
self.y = y
self.y_target = y_target
self.ord = ord
self.decay_factor = decay_factor
self.clip_min = clip_min
self.clip_max = clip_max
self.sanity_checks = sanity_checks
if self.y is not None and self.y_target is not None:
raise ValueError("Must not set both y and y_target")
# Check if order of the norm is acceptable given current implementation
if self.ord not in [np.inf, 1, 2]:
raise ValueError("Norm order must be either np.inf, 1, or 2.")
if len(kwargs.keys()) > 0:
warnings.warn("kwargs is unused and will be removed on or after "
"2019-04-26.")
return True
|
[
"def",
"parse_params",
"(",
"self",
",",
"eps",
"=",
"0.3",
",",
"eps_iter",
"=",
"0.06",
",",
"nb_iter",
"=",
"10",
",",
"y",
"=",
"None",
",",
"ord",
"=",
"np",
".",
"inf",
",",
"decay_factor",
"=",
"1.0",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"sanity_checks",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Save attack-specific parameters",
"self",
".",
"eps",
"=",
"eps",
"self",
".",
"eps_iter",
"=",
"eps_iter",
"self",
".",
"nb_iter",
"=",
"nb_iter",
"self",
".",
"y",
"=",
"y",
"self",
".",
"y_target",
"=",
"y_target",
"self",
".",
"ord",
"=",
"ord",
"self",
".",
"decay_factor",
"=",
"decay_factor",
"self",
".",
"clip_min",
"=",
"clip_min",
"self",
".",
"clip_max",
"=",
"clip_max",
"self",
".",
"sanity_checks",
"=",
"sanity_checks",
"if",
"self",
".",
"y",
"is",
"not",
"None",
"and",
"self",
".",
"y_target",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must not set both y and y_target\"",
")",
"# Check if order of the norm is acceptable given current implementation",
"if",
"self",
".",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"\"Norm order must be either np.inf, 1, or 2.\"",
")",
"if",
"len",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
">",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"kwargs is unused and will be removed on or after \"",
"\"2019-04-26.\"",
")",
"return",
"True"
] |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (optional float) step size for each attack iteration
:param nb_iter: (optional int) Number of attack iterations.
:param y: (optional) A tensor with the true labels.
:param y_target: (optional) A tensor with the labels to target. Leave
y_target=None if y is also set. Labels should be
one-hot-encoded.
:param ord: (optional) Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param decay_factor: (optional) Decay factor for the momentum term.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
|
[
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"applies",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L125-L180
|
train
|
tensorflow/cleverhans
|
cleverhans/train.py
|
train
|
def train(sess, loss, x_train, y_train,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None,
devices=None, x_batch_preprocessor=None, use_ema=False,
ema_decay=.998, run_canary=None,
loss_threshold=1e5, dataset_train=None, dataset_size=None):
"""
Run (optionally multi-replica, synchronous) training to minimize `loss`
:param sess: TF session to use when training the graph
:param loss: tensor, the loss to minimize
:param x_train: numpy array with training inputs or tf Dataset
:param y_train: numpy array with training outputs or tf Dataset
:param init_all: (boolean) If set to true, all TF variables in the session
are (re)initialized, otherwise only previously
uninitialized variables are initialized before training.
:param evaluate: function that is run after each training iteration
(typically to display the test/validation accuracy).
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param args: dict or argparse `Namespace` object.
Should contain `nb_epochs`, `learning_rate`,
`batch_size`
:param rng: Instance of numpy.random.RandomState
:param var_list: Optional list of parameters to train.
:param fprop_args: dict, extra arguments to pass to fprop (loss and model).
:param optimizer: Optimizer to be used for training
:param devices: list of device names to use for training
If None, defaults to: all GPUs, if GPUs are available
all devices, if no GPUs are available
:param x_batch_preprocessor: callable
Takes a single tensor containing an x_train batch as input
Returns a single tensor containing an x_train batch as output
Called to preprocess the data before passing the data to the Loss
:param use_ema: bool
If true, uses an exponential moving average of the model parameters
:param ema_decay: float or callable
The decay parameter for EMA, if EMA is used
If a callable rather than a float, this is a callable that takes
the epoch and batch as arguments and returns the ema_decay for
the current batch.
:param loss_threshold: float
Raise an exception if the loss exceeds this value.
This is intended to rapidly detect numerical problems.
Sometimes the loss may legitimately be higher than this value. In
such cases, raise the value. If needed it can be np.inf.
:param dataset_train: tf Dataset instance.
Used as a replacement for x_train, y_train for faster performance.
:param dataset_size: integer, the size of the dataset_train.
:return: True if model trained
"""
# Check whether the hardware is working correctly
canary.run_canary()
if run_canary is not None:
warnings.warn("The `run_canary` argument is deprecated. The canary "
"is now much cheaper and thus runs all the time. The "
"canary now uses its own loss function so it is not "
"necessary to turn off the canary when training with "
" a stochastic loss. Simply quit passing `run_canary`."
"Passing `run_canary` may become an error on or after "
"2019-10-16.")
args = _ArgsWrapper(args or {})
fprop_args = fprop_args or {}
# Check that necessary arguments were given (see doc above)
# Be sure to support 0 epochs for debugging purposes
if args.nb_epochs is None:
raise ValueError("`args` must specify number of epochs")
if optimizer is None:
if args.learning_rate is None:
raise ValueError("Learning rate was not given in args dict")
assert args.batch_size, "Batch size was not given in args dict"
if rng is None:
rng = np.random.RandomState()
if optimizer is None:
optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate)
else:
if not isinstance(optimizer, tf.train.Optimizer):
raise ValueError("optimizer object must be from a child class of "
"tf.train.Optimizer")
grads = []
xs = []
preprocessed_xs = []
ys = []
if dataset_train is not None:
assert x_train is None and y_train is None and x_batch_preprocessor is None
if dataset_size is None:
raise ValueError("You must provide a dataset size")
data_iterator = dataset_train.make_one_shot_iterator().get_next()
x_train, y_train = sess.run(data_iterator)
devices = infer_devices(devices)
for device in devices:
with tf.device(device):
x = tf.placeholder(x_train.dtype, (None,) + x_train.shape[1:])
y = tf.placeholder(y_train.dtype, (None,) + y_train.shape[1:])
xs.append(x)
ys.append(y)
if x_batch_preprocessor is not None:
x = x_batch_preprocessor(x)
# We need to keep track of these so that the canary can feed
# preprocessed values. If the canary had to feed raw values,
# stochastic preprocessing could make the canary fail.
preprocessed_xs.append(x)
loss_value = loss.fprop(x, y, **fprop_args)
grads.append(optimizer.compute_gradients(
loss_value, var_list=var_list))
num_devices = len(devices)
print("num_devices: ", num_devices)
grad = avg_grads(grads)
# Trigger update operations within the default graph (such as batch_norm).
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
train_step = optimizer.apply_gradients(grad)
epoch_tf = tf.placeholder(tf.int32, [])
batch_tf = tf.placeholder(tf.int32, [])
if use_ema:
if callable(ema_decay):
ema_decay = ema_decay(epoch_tf, batch_tf)
ema = tf.train.ExponentialMovingAverage(decay=ema_decay)
with tf.control_dependencies([train_step]):
train_step = ema.apply(var_list)
# Get pointers to the EMA's running average variables
avg_params = [ema.average(param) for param in var_list]
# Make temporary buffers used for swapping the live and running average
# parameters
tmp_params = [tf.Variable(param, trainable=False)
for param in var_list]
# Define the swapping operation
param_to_tmp = [tf.assign(tmp, param)
for tmp, param in safe_zip(tmp_params, var_list)]
with tf.control_dependencies(param_to_tmp):
avg_to_param = [tf.assign(param, avg)
for param, avg in safe_zip(var_list, avg_params)]
with tf.control_dependencies(avg_to_param):
tmp_to_avg = [tf.assign(avg, tmp)
for avg, tmp in safe_zip(avg_params, tmp_params)]
swap = tmp_to_avg
batch_size = args.batch_size
assert batch_size % num_devices == 0
device_batch_size = batch_size // num_devices
if init_all:
sess.run(tf.global_variables_initializer())
else:
initialize_uninitialized_global_variables(sess)
for epoch in xrange(args.nb_epochs):
if dataset_train is not None:
nb_batches = int(math.ceil(float(dataset_size) / batch_size))
else:
# Indices to shuffle training set
index_shuf = list(range(len(x_train)))
# Randomly repeat a few training examples each epoch to avoid
# having a too-small batch
while len(index_shuf) % batch_size != 0:
index_shuf.append(rng.randint(len(x_train)))
nb_batches = len(index_shuf) // batch_size
rng.shuffle(index_shuf)
# Shuffling here versus inside the loop doesn't seem to affect
# timing very much, but shuffling here makes the code slightly
# easier to read
x_train_shuffled = x_train[index_shuf]
y_train_shuffled = y_train[index_shuf]
prev = time.time()
for batch in range(nb_batches):
if dataset_train is not None:
x_train_shuffled, y_train_shuffled = sess.run(data_iterator)
start, end = 0, batch_size
else:
# Compute batch start and end indices
start = batch * batch_size
end = (batch + 1) * batch_size
# Perform one training step
diff = end - start
assert diff == batch_size
feed_dict = {epoch_tf: epoch, batch_tf: batch}
for dev_idx in xrange(num_devices):
cur_start = start + dev_idx * device_batch_size
cur_end = start + (dev_idx + 1) * device_batch_size
feed_dict[xs[dev_idx]] = x_train_shuffled[cur_start:cur_end]
feed_dict[ys[dev_idx]] = y_train_shuffled[cur_start:cur_end]
if cur_end != end and dataset_train is None:
msg = ("batch_size (%d) must be a multiple of num_devices "
"(%d).\nCUDA_VISIBLE_DEVICES: %s"
"\ndevices: %s")
args = (batch_size, num_devices,
os.environ['CUDA_VISIBLE_DEVICES'],
str(devices))
raise ValueError(msg % args)
if feed is not None:
feed_dict.update(feed)
_, loss_numpy = sess.run(
[train_step, loss_value], feed_dict=feed_dict)
if np.abs(loss_numpy) > loss_threshold:
raise ValueError("Extreme loss during training: ", loss_numpy)
if np.isnan(loss_numpy) or np.isinf(loss_numpy):
raise ValueError("NaN/Inf loss during training")
assert (dataset_train is not None or
end == len(index_shuf)) # Check that all examples were used
cur = time.time()
_logger.info("Epoch " + str(epoch) + " took " +
str(cur - prev) + " seconds")
if evaluate is not None:
if use_ema:
# Before running evaluation, load the running average
# parameters into the live slot, so we can see how well
# the EMA parameters are performing
sess.run(swap)
evaluate()
if use_ema:
# Swap the parameters back, so that we continue training
# on the live parameters
sess.run(swap)
if use_ema:
# When training is done, swap the running average parameters into
# the live slot, so that we use them when we deploy the model
sess.run(swap)
return True
|
python
|
def train(sess, loss, x_train, y_train,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None,
devices=None, x_batch_preprocessor=None, use_ema=False,
ema_decay=.998, run_canary=None,
loss_threshold=1e5, dataset_train=None, dataset_size=None):
"""
Run (optionally multi-replica, synchronous) training to minimize `loss`
:param sess: TF session to use when training the graph
:param loss: tensor, the loss to minimize
:param x_train: numpy array with training inputs or tf Dataset
:param y_train: numpy array with training outputs or tf Dataset
:param init_all: (boolean) If set to true, all TF variables in the session
are (re)initialized, otherwise only previously
uninitialized variables are initialized before training.
:param evaluate: function that is run after each training iteration
(typically to display the test/validation accuracy).
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param args: dict or argparse `Namespace` object.
Should contain `nb_epochs`, `learning_rate`,
`batch_size`
:param rng: Instance of numpy.random.RandomState
:param var_list: Optional list of parameters to train.
:param fprop_args: dict, extra arguments to pass to fprop (loss and model).
:param optimizer: Optimizer to be used for training
:param devices: list of device names to use for training
If None, defaults to: all GPUs, if GPUs are available
all devices, if no GPUs are available
:param x_batch_preprocessor: callable
Takes a single tensor containing an x_train batch as input
Returns a single tensor containing an x_train batch as output
Called to preprocess the data before passing the data to the Loss
:param use_ema: bool
If true, uses an exponential moving average of the model parameters
:param ema_decay: float or callable
The decay parameter for EMA, if EMA is used
If a callable rather than a float, this is a callable that takes
the epoch and batch as arguments and returns the ema_decay for
the current batch.
:param loss_threshold: float
Raise an exception if the loss exceeds this value.
This is intended to rapidly detect numerical problems.
Sometimes the loss may legitimately be higher than this value. In
such cases, raise the value. If needed it can be np.inf.
:param dataset_train: tf Dataset instance.
Used as a replacement for x_train, y_train for faster performance.
:param dataset_size: integer, the size of the dataset_train.
:return: True if model trained
"""
# Check whether the hardware is working correctly
canary.run_canary()
if run_canary is not None:
warnings.warn("The `run_canary` argument is deprecated. The canary "
"is now much cheaper and thus runs all the time. The "
"canary now uses its own loss function so it is not "
"necessary to turn off the canary when training with "
" a stochastic loss. Simply quit passing `run_canary`."
"Passing `run_canary` may become an error on or after "
"2019-10-16.")
args = _ArgsWrapper(args or {})
fprop_args = fprop_args or {}
# Check that necessary arguments were given (see doc above)
# Be sure to support 0 epochs for debugging purposes
if args.nb_epochs is None:
raise ValueError("`args` must specify number of epochs")
if optimizer is None:
if args.learning_rate is None:
raise ValueError("Learning rate was not given in args dict")
assert args.batch_size, "Batch size was not given in args dict"
if rng is None:
rng = np.random.RandomState()
if optimizer is None:
optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate)
else:
if not isinstance(optimizer, tf.train.Optimizer):
raise ValueError("optimizer object must be from a child class of "
"tf.train.Optimizer")
grads = []
xs = []
preprocessed_xs = []
ys = []
if dataset_train is not None:
assert x_train is None and y_train is None and x_batch_preprocessor is None
if dataset_size is None:
raise ValueError("You must provide a dataset size")
data_iterator = dataset_train.make_one_shot_iterator().get_next()
x_train, y_train = sess.run(data_iterator)
devices = infer_devices(devices)
for device in devices:
with tf.device(device):
x = tf.placeholder(x_train.dtype, (None,) + x_train.shape[1:])
y = tf.placeholder(y_train.dtype, (None,) + y_train.shape[1:])
xs.append(x)
ys.append(y)
if x_batch_preprocessor is not None:
x = x_batch_preprocessor(x)
# We need to keep track of these so that the canary can feed
# preprocessed values. If the canary had to feed raw values,
# stochastic preprocessing could make the canary fail.
preprocessed_xs.append(x)
loss_value = loss.fprop(x, y, **fprop_args)
grads.append(optimizer.compute_gradients(
loss_value, var_list=var_list))
num_devices = len(devices)
print("num_devices: ", num_devices)
grad = avg_grads(grads)
# Trigger update operations within the default graph (such as batch_norm).
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
train_step = optimizer.apply_gradients(grad)
epoch_tf = tf.placeholder(tf.int32, [])
batch_tf = tf.placeholder(tf.int32, [])
if use_ema:
if callable(ema_decay):
ema_decay = ema_decay(epoch_tf, batch_tf)
ema = tf.train.ExponentialMovingAverage(decay=ema_decay)
with tf.control_dependencies([train_step]):
train_step = ema.apply(var_list)
# Get pointers to the EMA's running average variables
avg_params = [ema.average(param) for param in var_list]
# Make temporary buffers used for swapping the live and running average
# parameters
tmp_params = [tf.Variable(param, trainable=False)
for param in var_list]
# Define the swapping operation
param_to_tmp = [tf.assign(tmp, param)
for tmp, param in safe_zip(tmp_params, var_list)]
with tf.control_dependencies(param_to_tmp):
avg_to_param = [tf.assign(param, avg)
for param, avg in safe_zip(var_list, avg_params)]
with tf.control_dependencies(avg_to_param):
tmp_to_avg = [tf.assign(avg, tmp)
for avg, tmp in safe_zip(avg_params, tmp_params)]
swap = tmp_to_avg
batch_size = args.batch_size
assert batch_size % num_devices == 0
device_batch_size = batch_size // num_devices
if init_all:
sess.run(tf.global_variables_initializer())
else:
initialize_uninitialized_global_variables(sess)
for epoch in xrange(args.nb_epochs):
if dataset_train is not None:
nb_batches = int(math.ceil(float(dataset_size) / batch_size))
else:
# Indices to shuffle training set
index_shuf = list(range(len(x_train)))
# Randomly repeat a few training examples each epoch to avoid
# having a too-small batch
while len(index_shuf) % batch_size != 0:
index_shuf.append(rng.randint(len(x_train)))
nb_batches = len(index_shuf) // batch_size
rng.shuffle(index_shuf)
# Shuffling here versus inside the loop doesn't seem to affect
# timing very much, but shuffling here makes the code slightly
# easier to read
x_train_shuffled = x_train[index_shuf]
y_train_shuffled = y_train[index_shuf]
prev = time.time()
for batch in range(nb_batches):
if dataset_train is not None:
x_train_shuffled, y_train_shuffled = sess.run(data_iterator)
start, end = 0, batch_size
else:
# Compute batch start and end indices
start = batch * batch_size
end = (batch + 1) * batch_size
# Perform one training step
diff = end - start
assert diff == batch_size
feed_dict = {epoch_tf: epoch, batch_tf: batch}
for dev_idx in xrange(num_devices):
cur_start = start + dev_idx * device_batch_size
cur_end = start + (dev_idx + 1) * device_batch_size
feed_dict[xs[dev_idx]] = x_train_shuffled[cur_start:cur_end]
feed_dict[ys[dev_idx]] = y_train_shuffled[cur_start:cur_end]
if cur_end != end and dataset_train is None:
msg = ("batch_size (%d) must be a multiple of num_devices "
"(%d).\nCUDA_VISIBLE_DEVICES: %s"
"\ndevices: %s")
args = (batch_size, num_devices,
os.environ['CUDA_VISIBLE_DEVICES'],
str(devices))
raise ValueError(msg % args)
if feed is not None:
feed_dict.update(feed)
_, loss_numpy = sess.run(
[train_step, loss_value], feed_dict=feed_dict)
if np.abs(loss_numpy) > loss_threshold:
raise ValueError("Extreme loss during training: ", loss_numpy)
if np.isnan(loss_numpy) or np.isinf(loss_numpy):
raise ValueError("NaN/Inf loss during training")
assert (dataset_train is not None or
end == len(index_shuf)) # Check that all examples were used
cur = time.time()
_logger.info("Epoch " + str(epoch) + " took " +
str(cur - prev) + " seconds")
if evaluate is not None:
if use_ema:
# Before running evaluation, load the running average
# parameters into the live slot, so we can see how well
# the EMA parameters are performing
sess.run(swap)
evaluate()
if use_ema:
# Swap the parameters back, so that we continue training
# on the live parameters
sess.run(swap)
if use_ema:
# When training is done, swap the running average parameters into
# the live slot, so that we use them when we deploy the model
sess.run(swap)
return True
|
[
"def",
"train",
"(",
"sess",
",",
"loss",
",",
"x_train",
",",
"y_train",
",",
"init_all",
"=",
"False",
",",
"evaluate",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"var_list",
"=",
"None",
",",
"fprop_args",
"=",
"None",
",",
"optimizer",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"x_batch_preprocessor",
"=",
"None",
",",
"use_ema",
"=",
"False",
",",
"ema_decay",
"=",
".998",
",",
"run_canary",
"=",
"None",
",",
"loss_threshold",
"=",
"1e5",
",",
"dataset_train",
"=",
"None",
",",
"dataset_size",
"=",
"None",
")",
":",
"# Check whether the hardware is working correctly",
"canary",
".",
"run_canary",
"(",
")",
"if",
"run_canary",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"The `run_canary` argument is deprecated. The canary \"",
"\"is now much cheaper and thus runs all the time. The \"",
"\"canary now uses its own loss function so it is not \"",
"\"necessary to turn off the canary when training with \"",
"\" a stochastic loss. Simply quit passing `run_canary`.\"",
"\"Passing `run_canary` may become an error on or after \"",
"\"2019-10-16.\"",
")",
"args",
"=",
"_ArgsWrapper",
"(",
"args",
"or",
"{",
"}",
")",
"fprop_args",
"=",
"fprop_args",
"or",
"{",
"}",
"# Check that necessary arguments were given (see doc above)",
"# Be sure to support 0 epochs for debugging purposes",
"if",
"args",
".",
"nb_epochs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"`args` must specify number of epochs\"",
")",
"if",
"optimizer",
"is",
"None",
":",
"if",
"args",
".",
"learning_rate",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Learning rate was not given in args dict\"",
")",
"assert",
"args",
".",
"batch_size",
",",
"\"Batch size was not given in args dict\"",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")",
"if",
"optimizer",
"is",
"None",
":",
"optimizer",
"=",
"tf",
".",
"train",
".",
"AdamOptimizer",
"(",
"learning_rate",
"=",
"args",
".",
"learning_rate",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"optimizer",
",",
"tf",
".",
"train",
".",
"Optimizer",
")",
":",
"raise",
"ValueError",
"(",
"\"optimizer object must be from a child class of \"",
"\"tf.train.Optimizer\"",
")",
"grads",
"=",
"[",
"]",
"xs",
"=",
"[",
"]",
"preprocessed_xs",
"=",
"[",
"]",
"ys",
"=",
"[",
"]",
"if",
"dataset_train",
"is",
"not",
"None",
":",
"assert",
"x_train",
"is",
"None",
"and",
"y_train",
"is",
"None",
"and",
"x_batch_preprocessor",
"is",
"None",
"if",
"dataset_size",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You must provide a dataset size\"",
")",
"data_iterator",
"=",
"dataset_train",
".",
"make_one_shot_iterator",
"(",
")",
".",
"get_next",
"(",
")",
"x_train",
",",
"y_train",
"=",
"sess",
".",
"run",
"(",
"data_iterator",
")",
"devices",
"=",
"infer_devices",
"(",
"devices",
")",
"for",
"device",
"in",
"devices",
":",
"with",
"tf",
".",
"device",
"(",
"device",
")",
":",
"x",
"=",
"tf",
".",
"placeholder",
"(",
"x_train",
".",
"dtype",
",",
"(",
"None",
",",
")",
"+",
"x_train",
".",
"shape",
"[",
"1",
":",
"]",
")",
"y",
"=",
"tf",
".",
"placeholder",
"(",
"y_train",
".",
"dtype",
",",
"(",
"None",
",",
")",
"+",
"y_train",
".",
"shape",
"[",
"1",
":",
"]",
")",
"xs",
".",
"append",
"(",
"x",
")",
"ys",
".",
"append",
"(",
"y",
")",
"if",
"x_batch_preprocessor",
"is",
"not",
"None",
":",
"x",
"=",
"x_batch_preprocessor",
"(",
"x",
")",
"# We need to keep track of these so that the canary can feed",
"# preprocessed values. If the canary had to feed raw values,",
"# stochastic preprocessing could make the canary fail.",
"preprocessed_xs",
".",
"append",
"(",
"x",
")",
"loss_value",
"=",
"loss",
".",
"fprop",
"(",
"x",
",",
"y",
",",
"*",
"*",
"fprop_args",
")",
"grads",
".",
"append",
"(",
"optimizer",
".",
"compute_gradients",
"(",
"loss_value",
",",
"var_list",
"=",
"var_list",
")",
")",
"num_devices",
"=",
"len",
"(",
"devices",
")",
"print",
"(",
"\"num_devices: \"",
",",
"num_devices",
")",
"grad",
"=",
"avg_grads",
"(",
"grads",
")",
"# Trigger update operations within the default graph (such as batch_norm).",
"with",
"tf",
".",
"control_dependencies",
"(",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"UPDATE_OPS",
")",
")",
":",
"train_step",
"=",
"optimizer",
".",
"apply_gradients",
"(",
"grad",
")",
"epoch_tf",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"int32",
",",
"[",
"]",
")",
"batch_tf",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"int32",
",",
"[",
"]",
")",
"if",
"use_ema",
":",
"if",
"callable",
"(",
"ema_decay",
")",
":",
"ema_decay",
"=",
"ema_decay",
"(",
"epoch_tf",
",",
"batch_tf",
")",
"ema",
"=",
"tf",
".",
"train",
".",
"ExponentialMovingAverage",
"(",
"decay",
"=",
"ema_decay",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"train_step",
"]",
")",
":",
"train_step",
"=",
"ema",
".",
"apply",
"(",
"var_list",
")",
"# Get pointers to the EMA's running average variables",
"avg_params",
"=",
"[",
"ema",
".",
"average",
"(",
"param",
")",
"for",
"param",
"in",
"var_list",
"]",
"# Make temporary buffers used for swapping the live and running average",
"# parameters",
"tmp_params",
"=",
"[",
"tf",
".",
"Variable",
"(",
"param",
",",
"trainable",
"=",
"False",
")",
"for",
"param",
"in",
"var_list",
"]",
"# Define the swapping operation",
"param_to_tmp",
"=",
"[",
"tf",
".",
"assign",
"(",
"tmp",
",",
"param",
")",
"for",
"tmp",
",",
"param",
"in",
"safe_zip",
"(",
"tmp_params",
",",
"var_list",
")",
"]",
"with",
"tf",
".",
"control_dependencies",
"(",
"param_to_tmp",
")",
":",
"avg_to_param",
"=",
"[",
"tf",
".",
"assign",
"(",
"param",
",",
"avg",
")",
"for",
"param",
",",
"avg",
"in",
"safe_zip",
"(",
"var_list",
",",
"avg_params",
")",
"]",
"with",
"tf",
".",
"control_dependencies",
"(",
"avg_to_param",
")",
":",
"tmp_to_avg",
"=",
"[",
"tf",
".",
"assign",
"(",
"avg",
",",
"tmp",
")",
"for",
"avg",
",",
"tmp",
"in",
"safe_zip",
"(",
"avg_params",
",",
"tmp_params",
")",
"]",
"swap",
"=",
"tmp_to_avg",
"batch_size",
"=",
"args",
".",
"batch_size",
"assert",
"batch_size",
"%",
"num_devices",
"==",
"0",
"device_batch_size",
"=",
"batch_size",
"//",
"num_devices",
"if",
"init_all",
":",
"sess",
".",
"run",
"(",
"tf",
".",
"global_variables_initializer",
"(",
")",
")",
"else",
":",
"initialize_uninitialized_global_variables",
"(",
"sess",
")",
"for",
"epoch",
"in",
"xrange",
"(",
"args",
".",
"nb_epochs",
")",
":",
"if",
"dataset_train",
"is",
"not",
"None",
":",
"nb_batches",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"dataset_size",
")",
"/",
"batch_size",
")",
")",
"else",
":",
"# Indices to shuffle training set",
"index_shuf",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"x_train",
")",
")",
")",
"# Randomly repeat a few training examples each epoch to avoid",
"# having a too-small batch",
"while",
"len",
"(",
"index_shuf",
")",
"%",
"batch_size",
"!=",
"0",
":",
"index_shuf",
".",
"append",
"(",
"rng",
".",
"randint",
"(",
"len",
"(",
"x_train",
")",
")",
")",
"nb_batches",
"=",
"len",
"(",
"index_shuf",
")",
"//",
"batch_size",
"rng",
".",
"shuffle",
"(",
"index_shuf",
")",
"# Shuffling here versus inside the loop doesn't seem to affect",
"# timing very much, but shuffling here makes the code slightly",
"# easier to read",
"x_train_shuffled",
"=",
"x_train",
"[",
"index_shuf",
"]",
"y_train_shuffled",
"=",
"y_train",
"[",
"index_shuf",
"]",
"prev",
"=",
"time",
".",
"time",
"(",
")",
"for",
"batch",
"in",
"range",
"(",
"nb_batches",
")",
":",
"if",
"dataset_train",
"is",
"not",
"None",
":",
"x_train_shuffled",
",",
"y_train_shuffled",
"=",
"sess",
".",
"run",
"(",
"data_iterator",
")",
"start",
",",
"end",
"=",
"0",
",",
"batch_size",
"else",
":",
"# Compute batch start and end indices",
"start",
"=",
"batch",
"*",
"batch_size",
"end",
"=",
"(",
"batch",
"+",
"1",
")",
"*",
"batch_size",
"# Perform one training step",
"diff",
"=",
"end",
"-",
"start",
"assert",
"diff",
"==",
"batch_size",
"feed_dict",
"=",
"{",
"epoch_tf",
":",
"epoch",
",",
"batch_tf",
":",
"batch",
"}",
"for",
"dev_idx",
"in",
"xrange",
"(",
"num_devices",
")",
":",
"cur_start",
"=",
"start",
"+",
"dev_idx",
"*",
"device_batch_size",
"cur_end",
"=",
"start",
"+",
"(",
"dev_idx",
"+",
"1",
")",
"*",
"device_batch_size",
"feed_dict",
"[",
"xs",
"[",
"dev_idx",
"]",
"]",
"=",
"x_train_shuffled",
"[",
"cur_start",
":",
"cur_end",
"]",
"feed_dict",
"[",
"ys",
"[",
"dev_idx",
"]",
"]",
"=",
"y_train_shuffled",
"[",
"cur_start",
":",
"cur_end",
"]",
"if",
"cur_end",
"!=",
"end",
"and",
"dataset_train",
"is",
"None",
":",
"msg",
"=",
"(",
"\"batch_size (%d) must be a multiple of num_devices \"",
"\"(%d).\\nCUDA_VISIBLE_DEVICES: %s\"",
"\"\\ndevices: %s\"",
")",
"args",
"=",
"(",
"batch_size",
",",
"num_devices",
",",
"os",
".",
"environ",
"[",
"'CUDA_VISIBLE_DEVICES'",
"]",
",",
"str",
"(",
"devices",
")",
")",
"raise",
"ValueError",
"(",
"msg",
"%",
"args",
")",
"if",
"feed",
"is",
"not",
"None",
":",
"feed_dict",
".",
"update",
"(",
"feed",
")",
"_",
",",
"loss_numpy",
"=",
"sess",
".",
"run",
"(",
"[",
"train_step",
",",
"loss_value",
"]",
",",
"feed_dict",
"=",
"feed_dict",
")",
"if",
"np",
".",
"abs",
"(",
"loss_numpy",
")",
">",
"loss_threshold",
":",
"raise",
"ValueError",
"(",
"\"Extreme loss during training: \"",
",",
"loss_numpy",
")",
"if",
"np",
".",
"isnan",
"(",
"loss_numpy",
")",
"or",
"np",
".",
"isinf",
"(",
"loss_numpy",
")",
":",
"raise",
"ValueError",
"(",
"\"NaN/Inf loss during training\"",
")",
"assert",
"(",
"dataset_train",
"is",
"not",
"None",
"or",
"end",
"==",
"len",
"(",
"index_shuf",
")",
")",
"# Check that all examples were used",
"cur",
"=",
"time",
".",
"time",
"(",
")",
"_logger",
".",
"info",
"(",
"\"Epoch \"",
"+",
"str",
"(",
"epoch",
")",
"+",
"\" took \"",
"+",
"str",
"(",
"cur",
"-",
"prev",
")",
"+",
"\" seconds\"",
")",
"if",
"evaluate",
"is",
"not",
"None",
":",
"if",
"use_ema",
":",
"# Before running evaluation, load the running average",
"# parameters into the live slot, so we can see how well",
"# the EMA parameters are performing",
"sess",
".",
"run",
"(",
"swap",
")",
"evaluate",
"(",
")",
"if",
"use_ema",
":",
"# Swap the parameters back, so that we continue training",
"# on the live parameters",
"sess",
".",
"run",
"(",
"swap",
")",
"if",
"use_ema",
":",
"# When training is done, swap the running average parameters into",
"# the live slot, so that we use them when we deploy the model",
"sess",
".",
"run",
"(",
"swap",
")",
"return",
"True"
] |
Run (optionally multi-replica, synchronous) training to minimize `loss`
:param sess: TF session to use when training the graph
:param loss: tensor, the loss to minimize
:param x_train: numpy array with training inputs or tf Dataset
:param y_train: numpy array with training outputs or tf Dataset
:param init_all: (boolean) If set to true, all TF variables in the session
are (re)initialized, otherwise only previously
uninitialized variables are initialized before training.
:param evaluate: function that is run after each training iteration
(typically to display the test/validation accuracy).
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param args: dict or argparse `Namespace` object.
Should contain `nb_epochs`, `learning_rate`,
`batch_size`
:param rng: Instance of numpy.random.RandomState
:param var_list: Optional list of parameters to train.
:param fprop_args: dict, extra arguments to pass to fprop (loss and model).
:param optimizer: Optimizer to be used for training
:param devices: list of device names to use for training
If None, defaults to: all GPUs, if GPUs are available
all devices, if no GPUs are available
:param x_batch_preprocessor: callable
Takes a single tensor containing an x_train batch as input
Returns a single tensor containing an x_train batch as output
Called to preprocess the data before passing the data to the Loss
:param use_ema: bool
If true, uses an exponential moving average of the model parameters
:param ema_decay: float or callable
The decay parameter for EMA, if EMA is used
If a callable rather than a float, this is a callable that takes
the epoch and batch as arguments and returns the ema_decay for
the current batch.
:param loss_threshold: float
Raise an exception if the loss exceeds this value.
This is intended to rapidly detect numerical problems.
Sometimes the loss may legitimately be higher than this value. In
such cases, raise the value. If needed it can be np.inf.
:param dataset_train: tf Dataset instance.
Used as a replacement for x_train, y_train for faster performance.
:param dataset_size: integer, the size of the dataset_train.
:return: True if model trained
|
[
"Run",
"(",
"optionally",
"multi",
"-",
"replica",
"synchronous",
")",
"training",
"to",
"minimize",
"loss",
":",
"param",
"sess",
":",
"TF",
"session",
"to",
"use",
"when",
"training",
"the",
"graph",
":",
"param",
"loss",
":",
"tensor",
"the",
"loss",
"to",
"minimize",
":",
"param",
"x_train",
":",
"numpy",
"array",
"with",
"training",
"inputs",
"or",
"tf",
"Dataset",
":",
"param",
"y_train",
":",
"numpy",
"array",
"with",
"training",
"outputs",
"or",
"tf",
"Dataset",
":",
"param",
"init_all",
":",
"(",
"boolean",
")",
"If",
"set",
"to",
"true",
"all",
"TF",
"variables",
"in",
"the",
"session",
"are",
"(",
"re",
")",
"initialized",
"otherwise",
"only",
"previously",
"uninitialized",
"variables",
"are",
"initialized",
"before",
"training",
".",
":",
"param",
"evaluate",
":",
"function",
"that",
"is",
"run",
"after",
"each",
"training",
"iteration",
"(",
"typically",
"to",
"display",
"the",
"test",
"/",
"validation",
"accuracy",
")",
".",
":",
"param",
"feed",
":",
"An",
"optional",
"dictionary",
"that",
"is",
"appended",
"to",
"the",
"feeding",
"dictionary",
"before",
"the",
"session",
"runs",
".",
"Can",
"be",
"used",
"to",
"feed",
"the",
"learning",
"phase",
"of",
"a",
"Keras",
"model",
"for",
"instance",
".",
":",
"param",
"args",
":",
"dict",
"or",
"argparse",
"Namespace",
"object",
".",
"Should",
"contain",
"nb_epochs",
"learning_rate",
"batch_size",
":",
"param",
"rng",
":",
"Instance",
"of",
"numpy",
".",
"random",
".",
"RandomState",
":",
"param",
"var_list",
":",
"Optional",
"list",
"of",
"parameters",
"to",
"train",
".",
":",
"param",
"fprop_args",
":",
"dict",
"extra",
"arguments",
"to",
"pass",
"to",
"fprop",
"(",
"loss",
"and",
"model",
")",
".",
":",
"param",
"optimizer",
":",
"Optimizer",
"to",
"be",
"used",
"for",
"training",
":",
"param",
"devices",
":",
"list",
"of",
"device",
"names",
"to",
"use",
"for",
"training",
"If",
"None",
"defaults",
"to",
":",
"all",
"GPUs",
"if",
"GPUs",
"are",
"available",
"all",
"devices",
"if",
"no",
"GPUs",
"are",
"available",
":",
"param",
"x_batch_preprocessor",
":",
"callable",
"Takes",
"a",
"single",
"tensor",
"containing",
"an",
"x_train",
"batch",
"as",
"input",
"Returns",
"a",
"single",
"tensor",
"containing",
"an",
"x_train",
"batch",
"as",
"output",
"Called",
"to",
"preprocess",
"the",
"data",
"before",
"passing",
"the",
"data",
"to",
"the",
"Loss",
":",
"param",
"use_ema",
":",
"bool",
"If",
"true",
"uses",
"an",
"exponential",
"moving",
"average",
"of",
"the",
"model",
"parameters",
":",
"param",
"ema_decay",
":",
"float",
"or",
"callable",
"The",
"decay",
"parameter",
"for",
"EMA",
"if",
"EMA",
"is",
"used",
"If",
"a",
"callable",
"rather",
"than",
"a",
"float",
"this",
"is",
"a",
"callable",
"that",
"takes",
"the",
"epoch",
"and",
"batch",
"as",
"arguments",
"and",
"returns",
"the",
"ema_decay",
"for",
"the",
"current",
"batch",
".",
":",
"param",
"loss_threshold",
":",
"float",
"Raise",
"an",
"exception",
"if",
"the",
"loss",
"exceeds",
"this",
"value",
".",
"This",
"is",
"intended",
"to",
"rapidly",
"detect",
"numerical",
"problems",
".",
"Sometimes",
"the",
"loss",
"may",
"legitimately",
"be",
"higher",
"than",
"this",
"value",
".",
"In",
"such",
"cases",
"raise",
"the",
"value",
".",
"If",
"needed",
"it",
"can",
"be",
"np",
".",
"inf",
".",
":",
"param",
"dataset_train",
":",
"tf",
"Dataset",
"instance",
".",
"Used",
"as",
"a",
"replacement",
"for",
"x_train",
"y_train",
"for",
"faster",
"performance",
".",
":",
"param",
"dataset_size",
":",
"integer",
"the",
"size",
"of",
"the",
"dataset_train",
".",
":",
"return",
":",
"True",
"if",
"model",
"trained"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/train.py#L38-L274
|
train
|
tensorflow/cleverhans
|
cleverhans/train.py
|
avg_grads
|
def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner list is over the gradient
calculation for each tower.
Returns:
List of pairs of (gradient, variable) where the gradient has been
averaged across all towers.
Modified from this tutorial: https://tinyurl.com/n3jr2vm
"""
if len(tower_grads) == 1:
return tower_grads[0]
average_grads = []
for grad_and_vars in zip(*tower_grads):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
grads = [g for g, _ in grad_and_vars]
# Average over the 'tower' dimension.
grad = tf.add_n(grads) / len(grads)
# Keep in mind that the Variables are redundant because they are shared
# across towers. So .. we will just return the first tower's pointer to
# the Variable.
v = grad_and_vars[0][1]
assert all(v is grad_and_var[1] for grad_and_var in grad_and_vars)
grad_and_var = (grad, v)
average_grads.append(grad_and_var)
return average_grads
|
python
|
def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner list is over the gradient
calculation for each tower.
Returns:
List of pairs of (gradient, variable) where the gradient has been
averaged across all towers.
Modified from this tutorial: https://tinyurl.com/n3jr2vm
"""
if len(tower_grads) == 1:
return tower_grads[0]
average_grads = []
for grad_and_vars in zip(*tower_grads):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
grads = [g for g, _ in grad_and_vars]
# Average over the 'tower' dimension.
grad = tf.add_n(grads) / len(grads)
# Keep in mind that the Variables are redundant because they are shared
# across towers. So .. we will just return the first tower's pointer to
# the Variable.
v = grad_and_vars[0][1]
assert all(v is grad_and_var[1] for grad_and_var in grad_and_vars)
grad_and_var = (grad, v)
average_grads.append(grad_and_var)
return average_grads
|
[
"def",
"avg_grads",
"(",
"tower_grads",
")",
":",
"if",
"len",
"(",
"tower_grads",
")",
"==",
"1",
":",
"return",
"tower_grads",
"[",
"0",
"]",
"average_grads",
"=",
"[",
"]",
"for",
"grad_and_vars",
"in",
"zip",
"(",
"*",
"tower_grads",
")",
":",
"# Note that each grad_and_vars looks like the following:",
"# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))",
"grads",
"=",
"[",
"g",
"for",
"g",
",",
"_",
"in",
"grad_and_vars",
"]",
"# Average over the 'tower' dimension.",
"grad",
"=",
"tf",
".",
"add_n",
"(",
"grads",
")",
"/",
"len",
"(",
"grads",
")",
"# Keep in mind that the Variables are redundant because they are shared",
"# across towers. So .. we will just return the first tower's pointer to",
"# the Variable.",
"v",
"=",
"grad_and_vars",
"[",
"0",
"]",
"[",
"1",
"]",
"assert",
"all",
"(",
"v",
"is",
"grad_and_var",
"[",
"1",
"]",
"for",
"grad_and_var",
"in",
"grad_and_vars",
")",
"grad_and_var",
"=",
"(",
"grad",
",",
"v",
")",
"average_grads",
".",
"append",
"(",
"grad_and_var",
")",
"return",
"average_grads"
] |
Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner list is over the gradient
calculation for each tower.
Returns:
List of pairs of (gradient, variable) where the gradient has been
averaged across all towers.
Modified from this tutorial: https://tinyurl.com/n3jr2vm
|
[
"Calculate",
"the",
"average",
"gradient",
"for",
"each",
"shared",
"variable",
"across",
"all",
"towers",
".",
"Note",
"that",
"this",
"function",
"provides",
"a",
"synchronization",
"point",
"across",
"all",
"towers",
".",
"Args",
":",
"tower_grads",
":",
"List",
"of",
"lists",
"of",
"(",
"gradient",
"variable",
")",
"tuples",
".",
"The",
"outer",
"list",
"is",
"over",
"individual",
"gradients",
".",
"The",
"inner",
"list",
"is",
"over",
"the",
"gradient",
"calculation",
"for",
"each",
"tower",
".",
"Returns",
":",
"List",
"of",
"pairs",
"of",
"(",
"gradient",
"variable",
")",
"where",
"the",
"gradient",
"has",
"been",
"averaged",
"across",
"all",
"towers",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/train.py#L277-L309
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/evaluator.py
|
create_adv_by_name
|
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs):
"""
Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless a different value is
given in kwargs.
:param model: an object of Model class
:param x: Symbolic input to the attack.
:param attack_type: A string that is the name of an attack.
:param sess: Tensorflow session.
:param dataset: The name of the dataset as a string to use for default
params.
:param y: (optional) a symbolic variable for the labels.
:param kwargs: (optional) additional parameters to be passed to the attack.
"""
# TODO: black box attacks
attack_names = {'FGSM': FastGradientMethod,
'MadryEtAl': MadryEtAl,
'MadryEtAl_y': MadryEtAl,
'MadryEtAl_multigpu': MadryEtAlMultiGPU,
'MadryEtAl_y_multigpu': MadryEtAlMultiGPU
}
if attack_type not in attack_names:
raise Exception('Attack %s not defined.' % attack_type)
attack_params_shared = {
'mnist': {'eps': .3, 'eps_iter': 0.01, 'clip_min': 0., 'clip_max': 1.,
'nb_iter': 40},
'cifar10': {'eps': 8./255, 'eps_iter': 0.01, 'clip_min': 0.,
'clip_max': 1., 'nb_iter': 20}
}
with tf.variable_scope(attack_type):
attack_class = attack_names[attack_type]
attack = attack_class(model, sess=sess)
# Extract feedable and structural keyword arguments from kwargs
fd_kwargs = attack.feedable_kwargs.keys() + attack.structural_kwargs
params = attack_params_shared[dataset].copy()
params.update({k: v for k, v in kwargs.items() if v is not None})
params = {k: v for k, v in params.items() if k in fd_kwargs}
if '_y' in attack_type:
params['y'] = y
logging.info(params)
adv_x = attack.generate(x, **params)
return adv_x
|
python
|
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs):
"""
Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless a different value is
given in kwargs.
:param model: an object of Model class
:param x: Symbolic input to the attack.
:param attack_type: A string that is the name of an attack.
:param sess: Tensorflow session.
:param dataset: The name of the dataset as a string to use for default
params.
:param y: (optional) a symbolic variable for the labels.
:param kwargs: (optional) additional parameters to be passed to the attack.
"""
# TODO: black box attacks
attack_names = {'FGSM': FastGradientMethod,
'MadryEtAl': MadryEtAl,
'MadryEtAl_y': MadryEtAl,
'MadryEtAl_multigpu': MadryEtAlMultiGPU,
'MadryEtAl_y_multigpu': MadryEtAlMultiGPU
}
if attack_type not in attack_names:
raise Exception('Attack %s not defined.' % attack_type)
attack_params_shared = {
'mnist': {'eps': .3, 'eps_iter': 0.01, 'clip_min': 0., 'clip_max': 1.,
'nb_iter': 40},
'cifar10': {'eps': 8./255, 'eps_iter': 0.01, 'clip_min': 0.,
'clip_max': 1., 'nb_iter': 20}
}
with tf.variable_scope(attack_type):
attack_class = attack_names[attack_type]
attack = attack_class(model, sess=sess)
# Extract feedable and structural keyword arguments from kwargs
fd_kwargs = attack.feedable_kwargs.keys() + attack.structural_kwargs
params = attack_params_shared[dataset].copy()
params.update({k: v for k, v in kwargs.items() if v is not None})
params = {k: v for k, v in params.items() if k in fd_kwargs}
if '_y' in attack_type:
params['y'] = y
logging.info(params)
adv_x = attack.generate(x, **params)
return adv_x
|
[
"def",
"create_adv_by_name",
"(",
"model",
",",
"x",
",",
"attack_type",
",",
"sess",
",",
"dataset",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: black box attacks",
"attack_names",
"=",
"{",
"'FGSM'",
":",
"FastGradientMethod",
",",
"'MadryEtAl'",
":",
"MadryEtAl",
",",
"'MadryEtAl_y'",
":",
"MadryEtAl",
",",
"'MadryEtAl_multigpu'",
":",
"MadryEtAlMultiGPU",
",",
"'MadryEtAl_y_multigpu'",
":",
"MadryEtAlMultiGPU",
"}",
"if",
"attack_type",
"not",
"in",
"attack_names",
":",
"raise",
"Exception",
"(",
"'Attack %s not defined.'",
"%",
"attack_type",
")",
"attack_params_shared",
"=",
"{",
"'mnist'",
":",
"{",
"'eps'",
":",
".3",
",",
"'eps_iter'",
":",
"0.01",
",",
"'clip_min'",
":",
"0.",
",",
"'clip_max'",
":",
"1.",
",",
"'nb_iter'",
":",
"40",
"}",
",",
"'cifar10'",
":",
"{",
"'eps'",
":",
"8.",
"/",
"255",
",",
"'eps_iter'",
":",
"0.01",
",",
"'clip_min'",
":",
"0.",
",",
"'clip_max'",
":",
"1.",
",",
"'nb_iter'",
":",
"20",
"}",
"}",
"with",
"tf",
".",
"variable_scope",
"(",
"attack_type",
")",
":",
"attack_class",
"=",
"attack_names",
"[",
"attack_type",
"]",
"attack",
"=",
"attack_class",
"(",
"model",
",",
"sess",
"=",
"sess",
")",
"# Extract feedable and structural keyword arguments from kwargs",
"fd_kwargs",
"=",
"attack",
".",
"feedable_kwargs",
".",
"keys",
"(",
")",
"+",
"attack",
".",
"structural_kwargs",
"params",
"=",
"attack_params_shared",
"[",
"dataset",
"]",
".",
"copy",
"(",
")",
"params",
".",
"update",
"(",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
")",
"params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
"if",
"k",
"in",
"fd_kwargs",
"}",
"if",
"'_y'",
"in",
"attack_type",
":",
"params",
"[",
"'y'",
"]",
"=",
"y",
"logging",
".",
"info",
"(",
"params",
")",
"adv_x",
"=",
"attack",
".",
"generate",
"(",
"x",
",",
"*",
"*",
"params",
")",
"return",
"adv_x"
] |
Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless a different value is
given in kwargs.
:param model: an object of Model class
:param x: Symbolic input to the attack.
:param attack_type: A string that is the name of an attack.
:param sess: Tensorflow session.
:param dataset: The name of the dataset as a string to use for default
params.
:param y: (optional) a symbolic variable for the labels.
:param kwargs: (optional) additional parameters to be passed to the attack.
|
[
"Creates",
"the",
"symbolic",
"graph",
"of",
"an",
"adversarial",
"example",
"given",
"the",
"name",
"of",
"an",
"attack",
".",
"Simplifies",
"creating",
"the",
"symbolic",
"graph",
"of",
"an",
"attack",
"by",
"defining",
"dataset",
"-",
"specific",
"parameters",
".",
"Dataset",
"-",
"specific",
"default",
"parameters",
"are",
"used",
"unless",
"a",
"different",
"value",
"is",
"given",
"in",
"kwargs",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L16-L66
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/evaluator.py
|
Evaluator.log_value
|
def log_value(self, tag, val, desc=''):
"""
Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed.
"""
logging.info('%s (%s): %.4f' % (desc, tag, val))
self.summary.value.add(tag=tag, simple_value=val)
|
python
|
def log_value(self, tag, val, desc=''):
"""
Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed.
"""
logging.info('%s (%s): %.4f' % (desc, tag, val))
self.summary.value.add(tag=tag, simple_value=val)
|
[
"def",
"log_value",
"(",
"self",
",",
"tag",
",",
"val",
",",
"desc",
"=",
"''",
")",
":",
"logging",
".",
"info",
"(",
"'%s (%s): %.4f'",
"%",
"(",
"desc",
",",
"tag",
",",
"val",
")",
")",
"self",
".",
"summary",
".",
"value",
".",
"add",
"(",
"tag",
"=",
"tag",
",",
"simple_value",
"=",
"val",
")"
] |
Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed.
|
[
"Log",
"values",
"to",
"standard",
"output",
"and",
"Tensorflow",
"summary",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L127-L136
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/evaluator.py
|
Evaluator.eval_advs
|
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
"""
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial example.
:param X_test: NumPy array of test set inputs.
:param Y_test: NumPy array of test set labels.
:param att_type: name of the attack.
"""
end = (len(X_test) // self.batch_size) * self.batch_size
if self.hparams.fast_tests:
end = 10*self.batch_size
acc = model_eval(self.sess, x, y, preds_adv, X_test[:end],
Y_test[:end], args=self.eval_params)
self.log_value('test_accuracy_%s' % att_type, acc,
'Test accuracy on adversarial examples')
return acc
|
python
|
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
"""
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial example.
:param X_test: NumPy array of test set inputs.
:param Y_test: NumPy array of test set labels.
:param att_type: name of the attack.
"""
end = (len(X_test) // self.batch_size) * self.batch_size
if self.hparams.fast_tests:
end = 10*self.batch_size
acc = model_eval(self.sess, x, y, preds_adv, X_test[:end],
Y_test[:end], args=self.eval_params)
self.log_value('test_accuracy_%s' % att_type, acc,
'Test accuracy on adversarial examples')
return acc
|
[
"def",
"eval_advs",
"(",
"self",
",",
"x",
",",
"y",
",",
"preds_adv",
",",
"X_test",
",",
"Y_test",
",",
"att_type",
")",
":",
"end",
"=",
"(",
"len",
"(",
"X_test",
")",
"//",
"self",
".",
"batch_size",
")",
"*",
"self",
".",
"batch_size",
"if",
"self",
".",
"hparams",
".",
"fast_tests",
":",
"end",
"=",
"10",
"*",
"self",
".",
"batch_size",
"acc",
"=",
"model_eval",
"(",
"self",
".",
"sess",
",",
"x",
",",
"y",
",",
"preds_adv",
",",
"X_test",
"[",
":",
"end",
"]",
",",
"Y_test",
"[",
":",
"end",
"]",
",",
"args",
"=",
"self",
".",
"eval_params",
")",
"self",
".",
"log_value",
"(",
"'test_accuracy_%s'",
"%",
"att_type",
",",
"acc",
",",
"'Test accuracy on adversarial examples'",
")",
"return",
"acc"
] |
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial example.
:param X_test: NumPy array of test set inputs.
:param Y_test: NumPy array of test set labels.
:param att_type: name of the attack.
|
[
"Evaluate",
"the",
"accuracy",
"of",
"the",
"model",
"on",
"adversarial",
"examples"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L138-L159
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/evaluator.py
|
Evaluator.eval_multi
|
def eval_multi(self, inc_epoch=True):
"""
Run the evaluation on multiple attacks.
"""
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summary = tf.Summary()
report = {}
# Evaluate on train set
subsample_factor = 100
X_train_subsampled = X_train[::subsample_factor]
Y_train_subsampled = Y_train[::subsample_factor]
acc_train = model_eval(sess, x, y, preds, X_train_subsampled,
Y_train_subsampled, args=self.eval_params)
self.log_value('train_accuracy_subsampled', acc_train,
'Clean accuracy, subsampled train')
report['train'] = acc_train
# Evaluate on the test set
acc = model_eval(sess, x, y, preds, X_test, Y_test,
args=self.eval_params)
self.log_value('test_accuracy_natural', acc,
'Clean accuracy, natural test')
report['test'] = acc
# Evaluate against adversarial attacks
if self.epoch % self.hparams.eval_iters == 0:
for att_type in self.attack_type_test:
_, preds_adv = self.attacks[att_type]
acc = self.eval_advs(x, y, preds_adv, X_test, Y_test, att_type)
report[att_type] = acc
if self.writer:
writer.add_summary(self.summary, self.epoch)
# Add examples of adversarial examples to the summary
if self.writer and self.epoch % 20 == 0 and self.sum_op is not None:
sm_val = self.sess.run(self.sum_op,
feed_dict={x: X_test[:self.batch_size],
y: Y_test[:self.batch_size]})
if self.writer:
writer.add_summary(sm_val)
self.epoch += 1 if inc_epoch else 0
return report
|
python
|
def eval_multi(self, inc_epoch=True):
"""
Run the evaluation on multiple attacks.
"""
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summary = tf.Summary()
report = {}
# Evaluate on train set
subsample_factor = 100
X_train_subsampled = X_train[::subsample_factor]
Y_train_subsampled = Y_train[::subsample_factor]
acc_train = model_eval(sess, x, y, preds, X_train_subsampled,
Y_train_subsampled, args=self.eval_params)
self.log_value('train_accuracy_subsampled', acc_train,
'Clean accuracy, subsampled train')
report['train'] = acc_train
# Evaluate on the test set
acc = model_eval(sess, x, y, preds, X_test, Y_test,
args=self.eval_params)
self.log_value('test_accuracy_natural', acc,
'Clean accuracy, natural test')
report['test'] = acc
# Evaluate against adversarial attacks
if self.epoch % self.hparams.eval_iters == 0:
for att_type in self.attack_type_test:
_, preds_adv = self.attacks[att_type]
acc = self.eval_advs(x, y, preds_adv, X_test, Y_test, att_type)
report[att_type] = acc
if self.writer:
writer.add_summary(self.summary, self.epoch)
# Add examples of adversarial examples to the summary
if self.writer and self.epoch % 20 == 0 and self.sum_op is not None:
sm_val = self.sess.run(self.sum_op,
feed_dict={x: X_test[:self.batch_size],
y: Y_test[:self.batch_size]})
if self.writer:
writer.add_summary(sm_val)
self.epoch += 1 if inc_epoch else 0
return report
|
[
"def",
"eval_multi",
"(",
"self",
",",
"inc_epoch",
"=",
"True",
")",
":",
"sess",
"=",
"self",
".",
"sess",
"preds",
"=",
"self",
".",
"preds",
"x",
"=",
"self",
".",
"x_pre",
"y",
"=",
"self",
".",
"y",
"X_train",
"=",
"self",
".",
"X_train",
"Y_train",
"=",
"self",
".",
"Y_train",
"X_test",
"=",
"self",
".",
"X_test",
"Y_test",
"=",
"self",
".",
"Y_test",
"writer",
"=",
"self",
".",
"writer",
"self",
".",
"summary",
"=",
"tf",
".",
"Summary",
"(",
")",
"report",
"=",
"{",
"}",
"# Evaluate on train set",
"subsample_factor",
"=",
"100",
"X_train_subsampled",
"=",
"X_train",
"[",
":",
":",
"subsample_factor",
"]",
"Y_train_subsampled",
"=",
"Y_train",
"[",
":",
":",
"subsample_factor",
"]",
"acc_train",
"=",
"model_eval",
"(",
"sess",
",",
"x",
",",
"y",
",",
"preds",
",",
"X_train_subsampled",
",",
"Y_train_subsampled",
",",
"args",
"=",
"self",
".",
"eval_params",
")",
"self",
".",
"log_value",
"(",
"'train_accuracy_subsampled'",
",",
"acc_train",
",",
"'Clean accuracy, subsampled train'",
")",
"report",
"[",
"'train'",
"]",
"=",
"acc_train",
"# Evaluate on the test set",
"acc",
"=",
"model_eval",
"(",
"sess",
",",
"x",
",",
"y",
",",
"preds",
",",
"X_test",
",",
"Y_test",
",",
"args",
"=",
"self",
".",
"eval_params",
")",
"self",
".",
"log_value",
"(",
"'test_accuracy_natural'",
",",
"acc",
",",
"'Clean accuracy, natural test'",
")",
"report",
"[",
"'test'",
"]",
"=",
"acc",
"# Evaluate against adversarial attacks",
"if",
"self",
".",
"epoch",
"%",
"self",
".",
"hparams",
".",
"eval_iters",
"==",
"0",
":",
"for",
"att_type",
"in",
"self",
".",
"attack_type_test",
":",
"_",
",",
"preds_adv",
"=",
"self",
".",
"attacks",
"[",
"att_type",
"]",
"acc",
"=",
"self",
".",
"eval_advs",
"(",
"x",
",",
"y",
",",
"preds_adv",
",",
"X_test",
",",
"Y_test",
",",
"att_type",
")",
"report",
"[",
"att_type",
"]",
"=",
"acc",
"if",
"self",
".",
"writer",
":",
"writer",
".",
"add_summary",
"(",
"self",
".",
"summary",
",",
"self",
".",
"epoch",
")",
"# Add examples of adversarial examples to the summary",
"if",
"self",
".",
"writer",
"and",
"self",
".",
"epoch",
"%",
"20",
"==",
"0",
"and",
"self",
".",
"sum_op",
"is",
"not",
"None",
":",
"sm_val",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"sum_op",
",",
"feed_dict",
"=",
"{",
"x",
":",
"X_test",
"[",
":",
"self",
".",
"batch_size",
"]",
",",
"y",
":",
"Y_test",
"[",
":",
"self",
".",
"batch_size",
"]",
"}",
")",
"if",
"self",
".",
"writer",
":",
"writer",
".",
"add_summary",
"(",
"sm_val",
")",
"self",
".",
"epoch",
"+=",
"1",
"if",
"inc_epoch",
"else",
"0",
"return",
"report"
] |
Run the evaluation on multiple attacks.
|
[
"Run",
"the",
"evaluation",
"on",
"multiple",
"attacks",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L161-L215
|
train
|
tensorflow/cleverhans
|
cleverhans/canary.py
|
run_canary
|
def run_canary():
"""
Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations.
"""
# Note: please do not edit this function unless you have access to a machine
# with GPUs suffering from the bug and can verify that the canary still
# crashes after your edits. Due to the transient nature of the GPU bug it is
# not possible to unit test the canary in our continuous integration system.
global last_run
current = time.time()
if last_run is None or current - last_run > 3600:
last_run = current
else:
# Run the canary at most once per hour
return
# Try very hard not to let the canary affect the graph for the rest of the
# python process
canary_graph = tf.Graph()
with canary_graph.as_default():
devices = infer_devices()
num_devices = len(devices)
if num_devices < 3:
# We have never observed GPU failure when less than 3 GPUs were used
return
v = np.random.RandomState([2018, 10, 16]).randn(2, 2)
# Try very hard not to let this Variable end up in any collections used
# by the rest of the python process
w = tf.Variable(v, trainable=False, collections=[])
loss = tf.reduce_sum(tf.square(w))
grads = []
for device in devices:
with tf.device(device):
grad, = tf.gradients(loss, w)
grads.append(grad)
sess = tf.Session()
sess.run(tf.variables_initializer([w]))
grads = sess.run(grads)
first = grads[0]
for grad in grads[1:]:
if not np.allclose(first, grad):
first_string = str(first)
grad_string = str(grad)
raise RuntimeError("Something is wrong with your GPUs or GPU driver."
"%(num_devices)d different GPUS were asked to "
"calculate the same 2x2 gradient. One returned "
"%(first_string)s and another returned "
"%(grad_string)s. This can usually be fixed by "
"rebooting the machine." %
{"num_devices" : num_devices,
"first_string" : first_string,
"grad_string" : grad_string})
sess.close()
|
python
|
def run_canary():
"""
Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations.
"""
# Note: please do not edit this function unless you have access to a machine
# with GPUs suffering from the bug and can verify that the canary still
# crashes after your edits. Due to the transient nature of the GPU bug it is
# not possible to unit test the canary in our continuous integration system.
global last_run
current = time.time()
if last_run is None or current - last_run > 3600:
last_run = current
else:
# Run the canary at most once per hour
return
# Try very hard not to let the canary affect the graph for the rest of the
# python process
canary_graph = tf.Graph()
with canary_graph.as_default():
devices = infer_devices()
num_devices = len(devices)
if num_devices < 3:
# We have never observed GPU failure when less than 3 GPUs were used
return
v = np.random.RandomState([2018, 10, 16]).randn(2, 2)
# Try very hard not to let this Variable end up in any collections used
# by the rest of the python process
w = tf.Variable(v, trainable=False, collections=[])
loss = tf.reduce_sum(tf.square(w))
grads = []
for device in devices:
with tf.device(device):
grad, = tf.gradients(loss, w)
grads.append(grad)
sess = tf.Session()
sess.run(tf.variables_initializer([w]))
grads = sess.run(grads)
first = grads[0]
for grad in grads[1:]:
if not np.allclose(first, grad):
first_string = str(first)
grad_string = str(grad)
raise RuntimeError("Something is wrong with your GPUs or GPU driver."
"%(num_devices)d different GPUS were asked to "
"calculate the same 2x2 gradient. One returned "
"%(first_string)s and another returned "
"%(grad_string)s. This can usually be fixed by "
"rebooting the machine." %
{"num_devices" : num_devices,
"first_string" : first_string,
"grad_string" : grad_string})
sess.close()
|
[
"def",
"run_canary",
"(",
")",
":",
"# Note: please do not edit this function unless you have access to a machine",
"# with GPUs suffering from the bug and can verify that the canary still",
"# crashes after your edits. Due to the transient nature of the GPU bug it is",
"# not possible to unit test the canary in our continuous integration system.",
"global",
"last_run",
"current",
"=",
"time",
".",
"time",
"(",
")",
"if",
"last_run",
"is",
"None",
"or",
"current",
"-",
"last_run",
">",
"3600",
":",
"last_run",
"=",
"current",
"else",
":",
"# Run the canary at most once per hour",
"return",
"# Try very hard not to let the canary affect the graph for the rest of the",
"# python process",
"canary_graph",
"=",
"tf",
".",
"Graph",
"(",
")",
"with",
"canary_graph",
".",
"as_default",
"(",
")",
":",
"devices",
"=",
"infer_devices",
"(",
")",
"num_devices",
"=",
"len",
"(",
"devices",
")",
"if",
"num_devices",
"<",
"3",
":",
"# We have never observed GPU failure when less than 3 GPUs were used",
"return",
"v",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"[",
"2018",
",",
"10",
",",
"16",
"]",
")",
".",
"randn",
"(",
"2",
",",
"2",
")",
"# Try very hard not to let this Variable end up in any collections used",
"# by the rest of the python process",
"w",
"=",
"tf",
".",
"Variable",
"(",
"v",
",",
"trainable",
"=",
"False",
",",
"collections",
"=",
"[",
"]",
")",
"loss",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"square",
"(",
"w",
")",
")",
"grads",
"=",
"[",
"]",
"for",
"device",
"in",
"devices",
":",
"with",
"tf",
".",
"device",
"(",
"device",
")",
":",
"grad",
",",
"=",
"tf",
".",
"gradients",
"(",
"loss",
",",
"w",
")",
"grads",
".",
"append",
"(",
"grad",
")",
"sess",
"=",
"tf",
".",
"Session",
"(",
")",
"sess",
".",
"run",
"(",
"tf",
".",
"variables_initializer",
"(",
"[",
"w",
"]",
")",
")",
"grads",
"=",
"sess",
".",
"run",
"(",
"grads",
")",
"first",
"=",
"grads",
"[",
"0",
"]",
"for",
"grad",
"in",
"grads",
"[",
"1",
":",
"]",
":",
"if",
"not",
"np",
".",
"allclose",
"(",
"first",
",",
"grad",
")",
":",
"first_string",
"=",
"str",
"(",
"first",
")",
"grad_string",
"=",
"str",
"(",
"grad",
")",
"raise",
"RuntimeError",
"(",
"\"Something is wrong with your GPUs or GPU driver.\"",
"\"%(num_devices)d different GPUS were asked to \"",
"\"calculate the same 2x2 gradient. One returned \"",
"\"%(first_string)s and another returned \"",
"\"%(grad_string)s. This can usually be fixed by \"",
"\"rebooting the machine.\"",
"%",
"{",
"\"num_devices\"",
":",
"num_devices",
",",
"\"first_string\"",
":",
"first_string",
",",
"\"grad_string\"",
":",
"grad_string",
"}",
")",
"sess",
".",
"close",
"(",
")"
] |
Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations.
|
[
"Runs",
"some",
"code",
"that",
"will",
"crash",
"if",
"the",
"GPUs",
"/",
"GPU",
"driver",
"are",
"suffering",
"from",
"a",
"common",
"bug",
".",
"This",
"helps",
"to",
"prevent",
"contaminating",
"results",
"in",
"the",
"rest",
"of",
"the",
"library",
"with",
"incorrect",
"calculations",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/canary.py#L13-L72
|
train
|
tensorflow/cleverhans
|
cleverhans/compat.py
|
_wrap
|
def _wrap(f):
"""
Wraps a callable `f` in a function that warns that the function is deprecated.
"""
def wrapper(*args, **kwargs):
"""
Issues a deprecation warning and passes through the arguments.
"""
warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflow. "
" This function was originally needed as a compatibility layer for old versions of tensorflow, "
" but support for those versions has now been dropped.")
return f(*args, **kwargs)
return wrapper
|
python
|
def _wrap(f):
"""
Wraps a callable `f` in a function that warns that the function is deprecated.
"""
def wrapper(*args, **kwargs):
"""
Issues a deprecation warning and passes through the arguments.
"""
warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflow. "
" This function was originally needed as a compatibility layer for old versions of tensorflow, "
" but support for those versions has now been dropped.")
return f(*args, **kwargs)
return wrapper
|
[
"def",
"_wrap",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Issues a deprecation warning and passes through the arguments.\n \"\"\"",
"warnings",
".",
"warn",
"(",
"str",
"(",
"f",
")",
"+",
"\" is deprecated. Switch to calling the equivalent function in tensorflow. \"",
"\" This function was originally needed as a compatibility layer for old versions of tensorflow, \"",
"\" but support for those versions has now been dropped.\"",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Wraps a callable `f` in a function that warns that the function is deprecated.
|
[
"Wraps",
"a",
"callable",
"f",
"in",
"a",
"function",
"that",
"warns",
"that",
"the",
"function",
"is",
"deprecated",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L14-L26
|
train
|
tensorflow/cleverhans
|
cleverhans/compat.py
|
reduce_function
|
def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param input_tensor: The tensor to reduce. Should have numeric type.
:param axis: The dimensions to reduce. If None (the default),
reduces all dimensions. Must be in the range
[-rank(input_tensor), rank(input_tensor)).
:param keepdims: If true, retains reduced dimensions with length 1.
:param name: A name for the operation (optional).
:param reduction_indices: The old (deprecated) name for axis.
:return: outputs same value as op_func.
"""
warnings.warn("`reduce_function` is deprecated and may be removed on or after 2019-09-08.")
out = op_func(input_tensor, axis=axis, keepdims=keepdims, name=name, reduction_indices=reduction_indices)
return out
|
python
|
def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param input_tensor: The tensor to reduce. Should have numeric type.
:param axis: The dimensions to reduce. If None (the default),
reduces all dimensions. Must be in the range
[-rank(input_tensor), rank(input_tensor)).
:param keepdims: If true, retains reduced dimensions with length 1.
:param name: A name for the operation (optional).
:param reduction_indices: The old (deprecated) name for axis.
:return: outputs same value as op_func.
"""
warnings.warn("`reduce_function` is deprecated and may be removed on or after 2019-09-08.")
out = op_func(input_tensor, axis=axis, keepdims=keepdims, name=name, reduction_indices=reduction_indices)
return out
|
[
"def",
"reduce_function",
"(",
"op_func",
",",
"input_tensor",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"None",
",",
"name",
"=",
"None",
",",
"reduction_indices",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`reduce_function` is deprecated and may be removed on or after 2019-09-08.\"",
")",
"out",
"=",
"op_func",
"(",
"input_tensor",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"keepdims",
",",
"name",
"=",
"name",
",",
"reduction_indices",
"=",
"reduction_indices",
")",
"return",
"out"
] |
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param input_tensor: The tensor to reduce. Should have numeric type.
:param axis: The dimensions to reduce. If None (the default),
reduces all dimensions. Must be in the range
[-rank(input_tensor), rank(input_tensor)).
:param keepdims: If true, retains reduced dimensions with length 1.
:param name: A name for the operation (optional).
:param reduction_indices: The old (deprecated) name for axis.
:return: outputs same value as op_func.
|
[
"This",
"function",
"used",
"to",
"be",
"needed",
"to",
"support",
"tf",
"1",
".",
"4",
"and",
"early",
"but",
"support",
"for",
"tf",
"1",
".",
"4",
"and",
"earlier",
"is",
"now",
"dropped",
".",
":",
"param",
"op_func",
":",
"expects",
"the",
"function",
"to",
"handle",
"eg",
":",
"tf",
".",
"reduce_sum",
".",
":",
"param",
"input_tensor",
":",
"The",
"tensor",
"to",
"reduce",
".",
"Should",
"have",
"numeric",
"type",
".",
":",
"param",
"axis",
":",
"The",
"dimensions",
"to",
"reduce",
".",
"If",
"None",
"(",
"the",
"default",
")",
"reduces",
"all",
"dimensions",
".",
"Must",
"be",
"in",
"the",
"range",
"[",
"-",
"rank",
"(",
"input_tensor",
")",
"rank",
"(",
"input_tensor",
"))",
".",
":",
"param",
"keepdims",
":",
"If",
"true",
"retains",
"reduced",
"dimensions",
"with",
"length",
"1",
".",
":",
"param",
"name",
":",
"A",
"name",
"for",
"the",
"operation",
"(",
"optional",
")",
".",
":",
"param",
"reduction_indices",
":",
"The",
"old",
"(",
"deprecated",
")",
"name",
"for",
"axis",
".",
":",
"return",
":",
"outputs",
"same",
"value",
"as",
"op_func",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L35-L54
|
train
|
tensorflow/cleverhans
|
cleverhans/compat.py
|
softmax_cross_entropy_with_logits
|
def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure that all arguments were passed as named arguments.
if sentinel is not None:
name = "softmax_cross_entropy_with_logits"
raise ValueError("Only call `%s` with "
"named arguments (labels=..., logits=..., ...)"
% name)
if labels is None or logits is None:
raise ValueError("Both labels and logits must be provided.")
try:
f = tf.nn.softmax_cross_entropy_with_logits_v2
except AttributeError:
raise RuntimeError("This version of TensorFlow is no longer supported. See cleverhans/README.md")
labels = tf.stop_gradient(labels)
loss = f(labels=labels, logits=logits, dim=dim)
return loss
|
python
|
def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure that all arguments were passed as named arguments.
if sentinel is not None:
name = "softmax_cross_entropy_with_logits"
raise ValueError("Only call `%s` with "
"named arguments (labels=..., logits=..., ...)"
% name)
if labels is None or logits is None:
raise ValueError("Both labels and logits must be provided.")
try:
f = tf.nn.softmax_cross_entropy_with_logits_v2
except AttributeError:
raise RuntimeError("This version of TensorFlow is no longer supported. See cleverhans/README.md")
labels = tf.stop_gradient(labels)
loss = f(labels=labels, logits=logits, dim=dim)
return loss
|
[
"def",
"softmax_cross_entropy_with_logits",
"(",
"sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"logits",
"=",
"None",
",",
"dim",
"=",
"-",
"1",
")",
":",
"# Make sure that all arguments were passed as named arguments.",
"if",
"sentinel",
"is",
"not",
"None",
":",
"name",
"=",
"\"softmax_cross_entropy_with_logits\"",
"raise",
"ValueError",
"(",
"\"Only call `%s` with \"",
"\"named arguments (labels=..., logits=..., ...)\"",
"%",
"name",
")",
"if",
"labels",
"is",
"None",
"or",
"logits",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Both labels and logits must be provided.\"",
")",
"try",
":",
"f",
"=",
"tf",
".",
"nn",
".",
"softmax_cross_entropy_with_logits_v2",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"\"This version of TensorFlow is no longer supported. See cleverhans/README.md\"",
")",
"labels",
"=",
"tf",
".",
"stop_gradient",
"(",
"labels",
")",
"loss",
"=",
"f",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"logits",
",",
"dim",
"=",
"dim",
")",
"return",
"loss"
] |
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
|
[
"Wrapper",
"around",
"tf",
".",
"nn",
".",
"softmax_cross_entropy_with_logits_v2",
"to",
"handle",
"deprecated",
"warning"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L56-L81
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
|
enforce_epsilon_and_compute_hash
|
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
"""Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with generated adversarial images
output_dir: directory where to copy result
epsilon: size of perturbation
Returns:
dictionary with mapping form image ID to hash.
"""
dataset_images = [f for f in os.listdir(dataset_batch_dir)
if f.endswith('.png')]
image_hashes = {}
resize_warning = False
for img_name in dataset_images:
if not os.path.exists(os.path.join(adv_dir, img_name)):
logging.warning('Image %s not found in the output', img_name)
continue
image = np.array(
Image.open(os.path.join(dataset_batch_dir, img_name)).convert('RGB'))
image = image.astype('int32')
image_max_clip = np.clip(image + epsilon, 0, 255).astype('uint8')
image_min_clip = np.clip(image - epsilon, 0, 255).astype('uint8')
# load and resize adversarial image if needed
adv_image = Image.open(os.path.join(adv_dir, img_name)).convert('RGB')
# Image.size is reversed compared to np.array.shape
if adv_image.size[::-1] != image.shape[:2]:
resize_warning = True
adv_image = adv_image.resize((image.shape[1], image.shape[0]),
Image.BICUBIC)
adv_image = np.array(adv_image)
clipped_adv_image = np.clip(adv_image,
image_min_clip,
image_max_clip)
Image.fromarray(clipped_adv_image).save(os.path.join(output_dir, img_name))
# compute hash
image_hashes[img_name[:-4]] = hashlib.sha1(
clipped_adv_image.view(np.uint8)).hexdigest()
if resize_warning:
logging.warning('One or more adversarial images had incorrect size')
return image_hashes
|
python
|
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
"""Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with generated adversarial images
output_dir: directory where to copy result
epsilon: size of perturbation
Returns:
dictionary with mapping form image ID to hash.
"""
dataset_images = [f for f in os.listdir(dataset_batch_dir)
if f.endswith('.png')]
image_hashes = {}
resize_warning = False
for img_name in dataset_images:
if not os.path.exists(os.path.join(adv_dir, img_name)):
logging.warning('Image %s not found in the output', img_name)
continue
image = np.array(
Image.open(os.path.join(dataset_batch_dir, img_name)).convert('RGB'))
image = image.astype('int32')
image_max_clip = np.clip(image + epsilon, 0, 255).astype('uint8')
image_min_clip = np.clip(image - epsilon, 0, 255).astype('uint8')
# load and resize adversarial image if needed
adv_image = Image.open(os.path.join(adv_dir, img_name)).convert('RGB')
# Image.size is reversed compared to np.array.shape
if adv_image.size[::-1] != image.shape[:2]:
resize_warning = True
adv_image = adv_image.resize((image.shape[1], image.shape[0]),
Image.BICUBIC)
adv_image = np.array(adv_image)
clipped_adv_image = np.clip(adv_image,
image_min_clip,
image_max_clip)
Image.fromarray(clipped_adv_image).save(os.path.join(output_dir, img_name))
# compute hash
image_hashes[img_name[:-4]] = hashlib.sha1(
clipped_adv_image.view(np.uint8)).hexdigest()
if resize_warning:
logging.warning('One or more adversarial images had incorrect size')
return image_hashes
|
[
"def",
"enforce_epsilon_and_compute_hash",
"(",
"dataset_batch_dir",
",",
"adv_dir",
",",
"output_dir",
",",
"epsilon",
")",
":",
"dataset_images",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"dataset_batch_dir",
")",
"if",
"f",
".",
"endswith",
"(",
"'.png'",
")",
"]",
"image_hashes",
"=",
"{",
"}",
"resize_warning",
"=",
"False",
"for",
"img_name",
"in",
"dataset_images",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"adv_dir",
",",
"img_name",
")",
")",
":",
"logging",
".",
"warning",
"(",
"'Image %s not found in the output'",
",",
"img_name",
")",
"continue",
"image",
"=",
"np",
".",
"array",
"(",
"Image",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dataset_batch_dir",
",",
"img_name",
")",
")",
".",
"convert",
"(",
"'RGB'",
")",
")",
"image",
"=",
"image",
".",
"astype",
"(",
"'int32'",
")",
"image_max_clip",
"=",
"np",
".",
"clip",
"(",
"image",
"+",
"epsilon",
",",
"0",
",",
"255",
")",
".",
"astype",
"(",
"'uint8'",
")",
"image_min_clip",
"=",
"np",
".",
"clip",
"(",
"image",
"-",
"epsilon",
",",
"0",
",",
"255",
")",
".",
"astype",
"(",
"'uint8'",
")",
"# load and resize adversarial image if needed",
"adv_image",
"=",
"Image",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"adv_dir",
",",
"img_name",
")",
")",
".",
"convert",
"(",
"'RGB'",
")",
"# Image.size is reversed compared to np.array.shape",
"if",
"adv_image",
".",
"size",
"[",
":",
":",
"-",
"1",
"]",
"!=",
"image",
".",
"shape",
"[",
":",
"2",
"]",
":",
"resize_warning",
"=",
"True",
"adv_image",
"=",
"adv_image",
".",
"resize",
"(",
"(",
"image",
".",
"shape",
"[",
"1",
"]",
",",
"image",
".",
"shape",
"[",
"0",
"]",
")",
",",
"Image",
".",
"BICUBIC",
")",
"adv_image",
"=",
"np",
".",
"array",
"(",
"adv_image",
")",
"clipped_adv_image",
"=",
"np",
".",
"clip",
"(",
"adv_image",
",",
"image_min_clip",
",",
"image_max_clip",
")",
"Image",
".",
"fromarray",
"(",
"clipped_adv_image",
")",
".",
"save",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"img_name",
")",
")",
"# compute hash",
"image_hashes",
"[",
"img_name",
"[",
":",
"-",
"4",
"]",
"]",
"=",
"hashlib",
".",
"sha1",
"(",
"clipped_adv_image",
".",
"view",
"(",
"np",
".",
"uint8",
")",
")",
".",
"hexdigest",
"(",
")",
"if",
"resize_warning",
":",
"logging",
".",
"warning",
"(",
"'One or more adversarial images had incorrect size'",
")",
"return",
"image_hashes"
] |
Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with generated adversarial images
output_dir: directory where to copy result
epsilon: size of perturbation
Returns:
dictionary with mapping form image ID to hash.
|
[
"Enforces",
"size",
"of",
"perturbation",
"on",
"images",
"and",
"compute",
"hashes",
"for",
"all",
"images",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L81-L124
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
|
download_dataset
|
def download_dataset(storage_client, image_batches, target_dir,
local_dataset_copy=None):
"""Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
target_dir: target directory, should exist and be empty
local_dataset_copy: directory with local dataset copy, if local copy is
available then images will be takes from there instead of Cloud Storage
Data in the target directory will be organized into subdirectories by batches,
thus path to each image will be "target_dir/BATCH_ID/IMAGE_ID.png"
where BATCH_ID - ID of the batch (key of image_batches.data),
IMAGE_ID - ID of the image (key of image_batches.data[batch_id]['images'])
"""
for batch_id, batch_value in iteritems(image_batches.data):
batch_dir = os.path.join(target_dir, batch_id)
os.mkdir(batch_dir)
for image_id, image_val in iteritems(batch_value['images']):
dst_filename = os.path.join(batch_dir, image_id + '.png')
# try to use local copy first
if local_dataset_copy:
local_filename = os.path.join(local_dataset_copy,
os.path.basename(image_val['image_path']))
if os.path.exists(local_filename):
shutil.copyfile(local_filename, dst_filename)
continue
# download image from cloud
cloud_path = ('gs://' + storage_client.bucket_name
+ '/' + image_val['image_path'])
if not os.path.exists(dst_filename):
subprocess.call(['gsutil', 'cp', cloud_path, dst_filename])
|
python
|
def download_dataset(storage_client, image_batches, target_dir,
local_dataset_copy=None):
"""Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
target_dir: target directory, should exist and be empty
local_dataset_copy: directory with local dataset copy, if local copy is
available then images will be takes from there instead of Cloud Storage
Data in the target directory will be organized into subdirectories by batches,
thus path to each image will be "target_dir/BATCH_ID/IMAGE_ID.png"
where BATCH_ID - ID of the batch (key of image_batches.data),
IMAGE_ID - ID of the image (key of image_batches.data[batch_id]['images'])
"""
for batch_id, batch_value in iteritems(image_batches.data):
batch_dir = os.path.join(target_dir, batch_id)
os.mkdir(batch_dir)
for image_id, image_val in iteritems(batch_value['images']):
dst_filename = os.path.join(batch_dir, image_id + '.png')
# try to use local copy first
if local_dataset_copy:
local_filename = os.path.join(local_dataset_copy,
os.path.basename(image_val['image_path']))
if os.path.exists(local_filename):
shutil.copyfile(local_filename, dst_filename)
continue
# download image from cloud
cloud_path = ('gs://' + storage_client.bucket_name
+ '/' + image_val['image_path'])
if not os.path.exists(dst_filename):
subprocess.call(['gsutil', 'cp', cloud_path, dst_filename])
|
[
"def",
"download_dataset",
"(",
"storage_client",
",",
"image_batches",
",",
"target_dir",
",",
"local_dataset_copy",
"=",
"None",
")",
":",
"for",
"batch_id",
",",
"batch_value",
"in",
"iteritems",
"(",
"image_batches",
".",
"data",
")",
":",
"batch_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"batch_id",
")",
"os",
".",
"mkdir",
"(",
"batch_dir",
")",
"for",
"image_id",
",",
"image_val",
"in",
"iteritems",
"(",
"batch_value",
"[",
"'images'",
"]",
")",
":",
"dst_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"batch_dir",
",",
"image_id",
"+",
"'.png'",
")",
"# try to use local copy first",
"if",
"local_dataset_copy",
":",
"local_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"local_dataset_copy",
",",
"os",
".",
"path",
".",
"basename",
"(",
"image_val",
"[",
"'image_path'",
"]",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"local_filename",
")",
":",
"shutil",
".",
"copyfile",
"(",
"local_filename",
",",
"dst_filename",
")",
"continue",
"# download image from cloud",
"cloud_path",
"=",
"(",
"'gs://'",
"+",
"storage_client",
".",
"bucket_name",
"+",
"'/'",
"+",
"image_val",
"[",
"'image_path'",
"]",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst_filename",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"'gsutil'",
",",
"'cp'",
",",
"cloud_path",
",",
"dst_filename",
"]",
")"
] |
Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
target_dir: target directory, should exist and be empty
local_dataset_copy: directory with local dataset copy, if local copy is
available then images will be takes from there instead of Cloud Storage
Data in the target directory will be organized into subdirectories by batches,
thus path to each image will be "target_dir/BATCH_ID/IMAGE_ID.png"
where BATCH_ID - ID of the batch (key of image_batches.data),
IMAGE_ID - ID of the image (key of image_batches.data[batch_id]['images'])
|
[
"Downloads",
"dataset",
"organize",
"it",
"by",
"batches",
"and",
"rename",
"images",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L127-L159
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
|
DatasetMetadata.save_target_classes_for_batch
|
def save_target_classes_for_batch(self,
filename,
image_batches,
batch_id):
"""Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of ImageBatchesBase with dataset batches
batch_id: dataset batch ID
"""
images = image_batches.data[batch_id]['images']
with open(filename, 'w') as f:
for image_id, image_val in iteritems(images):
target_class = self.get_target_class(image_val['dataset_image_id'])
f.write('{0}.png,{1}\n'.format(image_id, target_class))
|
python
|
def save_target_classes_for_batch(self,
filename,
image_batches,
batch_id):
"""Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of ImageBatchesBase with dataset batches
batch_id: dataset batch ID
"""
images = image_batches.data[batch_id]['images']
with open(filename, 'w') as f:
for image_id, image_val in iteritems(images):
target_class = self.get_target_class(image_val['dataset_image_id'])
f.write('{0}.png,{1}\n'.format(image_id, target_class))
|
[
"def",
"save_target_classes_for_batch",
"(",
"self",
",",
"filename",
",",
"image_batches",
",",
"batch_id",
")",
":",
"images",
"=",
"image_batches",
".",
"data",
"[",
"batch_id",
"]",
"[",
"'images'",
"]",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"image_id",
",",
"image_val",
"in",
"iteritems",
"(",
"images",
")",
":",
"target_class",
"=",
"self",
".",
"get_target_class",
"(",
"image_val",
"[",
"'dataset_image_id'",
"]",
")",
"f",
".",
"write",
"(",
"'{0}.png,{1}\\n'",
".",
"format",
"(",
"image_id",
",",
"target_class",
")",
")"
] |
Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of ImageBatchesBase with dataset batches
batch_id: dataset batch ID
|
[
"Saves",
"file",
"with",
"target",
"class",
"for",
"given",
"dataset",
"batch",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L63-L78
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.tf_min_eig_vec
|
def tf_min_eig_vec(self):
"""Function for min eigen vector using tf's full eigen decomposition."""
# Full eigen decomposition requires the explicit psd matrix M
_, matrix_m = self.dual_object.get_full_psd_matrix()
[eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
index = tf.argmin(eig_vals)
return tf.reshape(
eig_vectors[:, index], shape=[eig_vectors.shape[0].value, 1])
|
python
|
def tf_min_eig_vec(self):
"""Function for min eigen vector using tf's full eigen decomposition."""
# Full eigen decomposition requires the explicit psd matrix M
_, matrix_m = self.dual_object.get_full_psd_matrix()
[eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
index = tf.argmin(eig_vals)
return tf.reshape(
eig_vectors[:, index], shape=[eig_vectors.shape[0].value, 1])
|
[
"def",
"tf_min_eig_vec",
"(",
"self",
")",
":",
"# Full eigen decomposition requires the explicit psd matrix M",
"_",
",",
"matrix_m",
"=",
"self",
".",
"dual_object",
".",
"get_full_psd_matrix",
"(",
")",
"[",
"eig_vals",
",",
"eig_vectors",
"]",
"=",
"tf",
".",
"self_adjoint_eig",
"(",
"matrix_m",
")",
"index",
"=",
"tf",
".",
"argmin",
"(",
"eig_vals",
")",
"return",
"tf",
".",
"reshape",
"(",
"eig_vectors",
"[",
":",
",",
"index",
"]",
",",
"shape",
"=",
"[",
"eig_vectors",
".",
"shape",
"[",
"0",
"]",
".",
"value",
",",
"1",
"]",
")"
] |
Function for min eigen vector using tf's full eigen decomposition.
|
[
"Function",
"for",
"min",
"eigen",
"vector",
"using",
"tf",
"s",
"full",
"eigen",
"decomposition",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L56-L63
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.tf_smooth_eig_vec
|
def tf_smooth_eig_vec(self):
"""Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_vals, self.smooth_placeholder))
scaling_factor = tf.reduce_sum(exp_eig_vals)
# Multiplying each eig vector by exponential of corresponding eig value
# Scaling factor normalizes the vector to be unit norm
eig_vec_smooth = tf.divide(
tf.matmul(eig_vectors, tf.diag(tf.sqrt(exp_eig_vals))),
tf.sqrt(scaling_factor))
return tf.reshape(
tf.reduce_sum(eig_vec_smooth, axis=1),
shape=[eig_vec_smooth.shape[0].value, 1])
|
python
|
def tf_smooth_eig_vec(self):
"""Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_vals, self.smooth_placeholder))
scaling_factor = tf.reduce_sum(exp_eig_vals)
# Multiplying each eig vector by exponential of corresponding eig value
# Scaling factor normalizes the vector to be unit norm
eig_vec_smooth = tf.divide(
tf.matmul(eig_vectors, tf.diag(tf.sqrt(exp_eig_vals))),
tf.sqrt(scaling_factor))
return tf.reshape(
tf.reduce_sum(eig_vec_smooth, axis=1),
shape=[eig_vec_smooth.shape[0].value, 1])
|
[
"def",
"tf_smooth_eig_vec",
"(",
"self",
")",
":",
"_",
",",
"matrix_m",
"=",
"self",
".",
"dual_object",
".",
"get_full_psd_matrix",
"(",
")",
"# Easier to think in terms of max so negating the matrix",
"[",
"eig_vals",
",",
"eig_vectors",
"]",
"=",
"tf",
".",
"self_adjoint_eig",
"(",
"-",
"matrix_m",
")",
"exp_eig_vals",
"=",
"tf",
".",
"exp",
"(",
"tf",
".",
"divide",
"(",
"eig_vals",
",",
"self",
".",
"smooth_placeholder",
")",
")",
"scaling_factor",
"=",
"tf",
".",
"reduce_sum",
"(",
"exp_eig_vals",
")",
"# Multiplying each eig vector by exponential of corresponding eig value",
"# Scaling factor normalizes the vector to be unit norm",
"eig_vec_smooth",
"=",
"tf",
".",
"divide",
"(",
"tf",
".",
"matmul",
"(",
"eig_vectors",
",",
"tf",
".",
"diag",
"(",
"tf",
".",
"sqrt",
"(",
"exp_eig_vals",
")",
")",
")",
",",
"tf",
".",
"sqrt",
"(",
"scaling_factor",
")",
")",
"return",
"tf",
".",
"reshape",
"(",
"tf",
".",
"reduce_sum",
"(",
"eig_vec_smooth",
",",
"axis",
"=",
"1",
")",
",",
"shape",
"=",
"[",
"eig_vec_smooth",
".",
"shape",
"[",
"0",
"]",
".",
"value",
",",
"1",
"]",
")"
] |
Function that returns smoothed version of min eigen vector.
|
[
"Function",
"that",
"returns",
"smoothed",
"version",
"of",
"min",
"eigen",
"vector",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L65-L79
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.get_min_eig_vec_proxy
|
def get_min_eig_vec_proxy(self, use_tf_eig=False):
"""Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if use_tf_eig:
# If smoothness parameter is too small, essentially no smoothing
# Just output the eigen vector corresponding to min
return tf.cond(self.smooth_placeholder < 1E-8,
self.tf_min_eig_vec,
self.tf_smooth_eig_vec)
# Using autograph to automatically handle
# the control flow of minimum_eigen_vector
min_eigen_tf = autograph.to_graph(utils.minimum_eigen_vector)
def _vector_prod_fn(x):
return self.dual_object.get_psd_product(x)
estimated_eigen_vector = min_eigen_tf(
x=self.eig_init_vec_placeholder,
num_steps=self.eig_num_iter_placeholder,
learning_rate=self.params['eig_learning_rate'],
vector_prod_fn=_vector_prod_fn)
return estimated_eigen_vector
|
python
|
def get_min_eig_vec_proxy(self, use_tf_eig=False):
"""Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if use_tf_eig:
# If smoothness parameter is too small, essentially no smoothing
# Just output the eigen vector corresponding to min
return tf.cond(self.smooth_placeholder < 1E-8,
self.tf_min_eig_vec,
self.tf_smooth_eig_vec)
# Using autograph to automatically handle
# the control flow of minimum_eigen_vector
min_eigen_tf = autograph.to_graph(utils.minimum_eigen_vector)
def _vector_prod_fn(x):
return self.dual_object.get_psd_product(x)
estimated_eigen_vector = min_eigen_tf(
x=self.eig_init_vec_placeholder,
num_steps=self.eig_num_iter_placeholder,
learning_rate=self.params['eig_learning_rate'],
vector_prod_fn=_vector_prod_fn)
return estimated_eigen_vector
|
[
"def",
"get_min_eig_vec_proxy",
"(",
"self",
",",
"use_tf_eig",
"=",
"False",
")",
":",
"if",
"use_tf_eig",
":",
"# If smoothness parameter is too small, essentially no smoothing",
"# Just output the eigen vector corresponding to min",
"return",
"tf",
".",
"cond",
"(",
"self",
".",
"smooth_placeholder",
"<",
"1E-8",
",",
"self",
".",
"tf_min_eig_vec",
",",
"self",
".",
"tf_smooth_eig_vec",
")",
"# Using autograph to automatically handle",
"# the control flow of minimum_eigen_vector",
"min_eigen_tf",
"=",
"autograph",
".",
"to_graph",
"(",
"utils",
".",
"minimum_eigen_vector",
")",
"def",
"_vector_prod_fn",
"(",
"x",
")",
":",
"return",
"self",
".",
"dual_object",
".",
"get_psd_product",
"(",
"x",
")",
"estimated_eigen_vector",
"=",
"min_eigen_tf",
"(",
"x",
"=",
"self",
".",
"eig_init_vec_placeholder",
",",
"num_steps",
"=",
"self",
".",
"eig_num_iter_placeholder",
",",
"learning_rate",
"=",
"self",
".",
"params",
"[",
"'eig_learning_rate'",
"]",
",",
"vector_prod_fn",
"=",
"_vector_prod_fn",
")",
"return",
"estimated_eigen_vector"
] |
Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
|
[
"Computes",
"the",
"min",
"eigen",
"value",
"and",
"corresponding",
"vector",
"of",
"matrix",
"M",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L81-L109
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.get_scipy_eig_vec
|
def get_scipy_eig_vec(self):
"""Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if not self.params['has_conv']:
matrix_m = self.sess.run(self.dual_object.matrix_m)
min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR',
tol=1E-4)
min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1])
return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
else:
dim = self.dual_object.matrix_m_dimension
input_vector = tf.placeholder(tf.float32, shape=(dim, 1))
output_vector = self.dual_object.get_psd_product(input_vector)
def np_vector_prod_fn(np_vector):
np_vector = np.reshape(np_vector, [-1, 1])
output_np_vector = self.sess.run(output_vector, feed_dict={input_vector:np_vector})
return output_np_vector
linear_operator = LinearOperator((dim, dim), matvec=np_vector_prod_fn)
# Performing shift invert scipy operation when eig val estimate is available
min_eig_vec_val, estimated_eigen_vector = eigs(linear_operator,
k=1, which='SR', tol=1E-4)
min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1])
return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
|
python
|
def get_scipy_eig_vec(self):
"""Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if not self.params['has_conv']:
matrix_m = self.sess.run(self.dual_object.matrix_m)
min_eig_vec_val, estimated_eigen_vector = eigs(matrix_m, k=1, which='SR',
tol=1E-4)
min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1])
return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
else:
dim = self.dual_object.matrix_m_dimension
input_vector = tf.placeholder(tf.float32, shape=(dim, 1))
output_vector = self.dual_object.get_psd_product(input_vector)
def np_vector_prod_fn(np_vector):
np_vector = np.reshape(np_vector, [-1, 1])
output_np_vector = self.sess.run(output_vector, feed_dict={input_vector:np_vector})
return output_np_vector
linear_operator = LinearOperator((dim, dim), matvec=np_vector_prod_fn)
# Performing shift invert scipy operation when eig val estimate is available
min_eig_vec_val, estimated_eigen_vector = eigs(linear_operator,
k=1, which='SR', tol=1E-4)
min_eig_vec_val = np.reshape(np.real(min_eig_vec_val), [1, 1])
return np.reshape(estimated_eigen_vector, [-1, 1]), min_eig_vec_val
|
[
"def",
"get_scipy_eig_vec",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"params",
"[",
"'has_conv'",
"]",
":",
"matrix_m",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"dual_object",
".",
"matrix_m",
")",
"min_eig_vec_val",
",",
"estimated_eigen_vector",
"=",
"eigs",
"(",
"matrix_m",
",",
"k",
"=",
"1",
",",
"which",
"=",
"'SR'",
",",
"tol",
"=",
"1E-4",
")",
"min_eig_vec_val",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"real",
"(",
"min_eig_vec_val",
")",
",",
"[",
"1",
",",
"1",
"]",
")",
"return",
"np",
".",
"reshape",
"(",
"estimated_eigen_vector",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
",",
"min_eig_vec_val",
"else",
":",
"dim",
"=",
"self",
".",
"dual_object",
".",
"matrix_m_dimension",
"input_vector",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"(",
"dim",
",",
"1",
")",
")",
"output_vector",
"=",
"self",
".",
"dual_object",
".",
"get_psd_product",
"(",
"input_vector",
")",
"def",
"np_vector_prod_fn",
"(",
"np_vector",
")",
":",
"np_vector",
"=",
"np",
".",
"reshape",
"(",
"np_vector",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"output_np_vector",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"output_vector",
",",
"feed_dict",
"=",
"{",
"input_vector",
":",
"np_vector",
"}",
")",
"return",
"output_np_vector",
"linear_operator",
"=",
"LinearOperator",
"(",
"(",
"dim",
",",
"dim",
")",
",",
"matvec",
"=",
"np_vector_prod_fn",
")",
"# Performing shift invert scipy operation when eig val estimate is available",
"min_eig_vec_val",
",",
"estimated_eigen_vector",
"=",
"eigs",
"(",
"linear_operator",
",",
"k",
"=",
"1",
",",
"which",
"=",
"'SR'",
",",
"tol",
"=",
"1E-4",
")",
"min_eig_vec_val",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"real",
"(",
"min_eig_vec_val",
")",
",",
"[",
"1",
",",
"1",
"]",
")",
"return",
"np",
".",
"reshape",
"(",
"estimated_eigen_vector",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
",",
"min_eig_vec_val"
] |
Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
|
[
"Computes",
"scipy",
"estimate",
"of",
"min",
"eigenvalue",
"for",
"matrix",
"M",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L111-L138
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.prepare_for_optimization
|
def prepare_for_optimization(self):
"""Create tensorflow op for running one step of descent."""
if self.params['eig_type'] == 'TF':
self.eig_vec_estimate = self.get_min_eig_vec_proxy()
elif self.params['eig_type'] == 'LZS':
self.eig_vec_estimate = self.dual_object.m_min_vec
else:
self.eig_vec_estimate = tf.placeholder(tf.float32, shape=(self.dual_object.matrix_m_dimension, 1))
self.stopped_eig_vec_estimate = tf.stop_gradient(self.eig_vec_estimate)
# Eig value is v^\top M v, where v is eigen vector
self.eig_val_estimate = tf.matmul(
tf.transpose(self.stopped_eig_vec_estimate),
self.dual_object.get_psd_product(self.stopped_eig_vec_estimate))
# Penalizing negative of min eigen value because we want min eig value
# to be positive
self.total_objective = (
self.dual_object.unconstrained_objective
+ 0.5 * tf.square(
tf.maximum(-self.penalty_placeholder * self.eig_val_estimate, 0)))
global_step = tf.Variable(0, trainable=False)
# Set up learning rate as a placeholder
self.learning_rate = tf.placeholder(tf.float32, shape=[])
# Set up the optimizer
if self.params['optimizer'] == 'adam':
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
elif self.params['optimizer'] == 'adagrad':
self.optimizer = tf.train.AdagradOptimizer(learning_rate=self.learning_rate)
elif self.params['optimizer'] == 'momentum':
self.optimizer = tf.train.MomentumOptimizer(
learning_rate=self.learning_rate,
momentum=self.params['momentum_parameter'],
use_nesterov=True)
else:
self.optimizer = tf.train.GradientDescentOptimizer(
learning_rate=self.learning_rate)
# Write out the projection step
self.train_step = self.optimizer.minimize(
self.total_objective, global_step=global_step)
self.sess.run(tf.global_variables_initializer())
# Projecting the dual variables
proj_ops = []
for i in range(self.dual_object.nn_params.num_hidden_layers + 1):
# Lambda_pos is non negative for switch indices,
# Unconstrained for positive indices
# Zero for negative indices
proj_ops.append(self.dual_object.lambda_pos[i].assign(
tf.multiply(self.dual_object.positive_indices[i],
self.dual_object.lambda_pos[i])+
tf.multiply(self.dual_object.switch_indices[i],
tf.nn.relu(self.dual_object.lambda_pos[i]))))
proj_ops.append(self.dual_object.lambda_neg[i].assign(
tf.multiply(self.dual_object.negative_indices[i],
self.dual_object.lambda_neg[i])+
tf.multiply(self.dual_object.switch_indices[i],
tf.nn.relu(self.dual_object.lambda_neg[i]))))
# Lambda_quad is only non zero and positive for switch
proj_ops.append(self.dual_object.lambda_quad[i].assign(
tf.multiply(self.dual_object.switch_indices[i],
tf.nn.relu(self.dual_object.lambda_quad[i]))))
# Lambda_lu is always non negative
proj_ops.append(self.dual_object.lambda_lu[i].assign(
tf.nn.relu(self.dual_object.lambda_lu[i])))
self.proj_step = tf.group(proj_ops)
# Create folder for saving stats if the folder is not None
if (self.params.get('stats_folder') and
not tf.gfile.IsDirectory(self.params['stats_folder'])):
tf.gfile.MkDir(self.params['stats_folder'])
|
python
|
def prepare_for_optimization(self):
"""Create tensorflow op for running one step of descent."""
if self.params['eig_type'] == 'TF':
self.eig_vec_estimate = self.get_min_eig_vec_proxy()
elif self.params['eig_type'] == 'LZS':
self.eig_vec_estimate = self.dual_object.m_min_vec
else:
self.eig_vec_estimate = tf.placeholder(tf.float32, shape=(self.dual_object.matrix_m_dimension, 1))
self.stopped_eig_vec_estimate = tf.stop_gradient(self.eig_vec_estimate)
# Eig value is v^\top M v, where v is eigen vector
self.eig_val_estimate = tf.matmul(
tf.transpose(self.stopped_eig_vec_estimate),
self.dual_object.get_psd_product(self.stopped_eig_vec_estimate))
# Penalizing negative of min eigen value because we want min eig value
# to be positive
self.total_objective = (
self.dual_object.unconstrained_objective
+ 0.5 * tf.square(
tf.maximum(-self.penalty_placeholder * self.eig_val_estimate, 0)))
global_step = tf.Variable(0, trainable=False)
# Set up learning rate as a placeholder
self.learning_rate = tf.placeholder(tf.float32, shape=[])
# Set up the optimizer
if self.params['optimizer'] == 'adam':
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
elif self.params['optimizer'] == 'adagrad':
self.optimizer = tf.train.AdagradOptimizer(learning_rate=self.learning_rate)
elif self.params['optimizer'] == 'momentum':
self.optimizer = tf.train.MomentumOptimizer(
learning_rate=self.learning_rate,
momentum=self.params['momentum_parameter'],
use_nesterov=True)
else:
self.optimizer = tf.train.GradientDescentOptimizer(
learning_rate=self.learning_rate)
# Write out the projection step
self.train_step = self.optimizer.minimize(
self.total_objective, global_step=global_step)
self.sess.run(tf.global_variables_initializer())
# Projecting the dual variables
proj_ops = []
for i in range(self.dual_object.nn_params.num_hidden_layers + 1):
# Lambda_pos is non negative for switch indices,
# Unconstrained for positive indices
# Zero for negative indices
proj_ops.append(self.dual_object.lambda_pos[i].assign(
tf.multiply(self.dual_object.positive_indices[i],
self.dual_object.lambda_pos[i])+
tf.multiply(self.dual_object.switch_indices[i],
tf.nn.relu(self.dual_object.lambda_pos[i]))))
proj_ops.append(self.dual_object.lambda_neg[i].assign(
tf.multiply(self.dual_object.negative_indices[i],
self.dual_object.lambda_neg[i])+
tf.multiply(self.dual_object.switch_indices[i],
tf.nn.relu(self.dual_object.lambda_neg[i]))))
# Lambda_quad is only non zero and positive for switch
proj_ops.append(self.dual_object.lambda_quad[i].assign(
tf.multiply(self.dual_object.switch_indices[i],
tf.nn.relu(self.dual_object.lambda_quad[i]))))
# Lambda_lu is always non negative
proj_ops.append(self.dual_object.lambda_lu[i].assign(
tf.nn.relu(self.dual_object.lambda_lu[i])))
self.proj_step = tf.group(proj_ops)
# Create folder for saving stats if the folder is not None
if (self.params.get('stats_folder') and
not tf.gfile.IsDirectory(self.params['stats_folder'])):
tf.gfile.MkDir(self.params['stats_folder'])
|
[
"def",
"prepare_for_optimization",
"(",
"self",
")",
":",
"if",
"self",
".",
"params",
"[",
"'eig_type'",
"]",
"==",
"'TF'",
":",
"self",
".",
"eig_vec_estimate",
"=",
"self",
".",
"get_min_eig_vec_proxy",
"(",
")",
"elif",
"self",
".",
"params",
"[",
"'eig_type'",
"]",
"==",
"'LZS'",
":",
"self",
".",
"eig_vec_estimate",
"=",
"self",
".",
"dual_object",
".",
"m_min_vec",
"else",
":",
"self",
".",
"eig_vec_estimate",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"(",
"self",
".",
"dual_object",
".",
"matrix_m_dimension",
",",
"1",
")",
")",
"self",
".",
"stopped_eig_vec_estimate",
"=",
"tf",
".",
"stop_gradient",
"(",
"self",
".",
"eig_vec_estimate",
")",
"# Eig value is v^\\top M v, where v is eigen vector",
"self",
".",
"eig_val_estimate",
"=",
"tf",
".",
"matmul",
"(",
"tf",
".",
"transpose",
"(",
"self",
".",
"stopped_eig_vec_estimate",
")",
",",
"self",
".",
"dual_object",
".",
"get_psd_product",
"(",
"self",
".",
"stopped_eig_vec_estimate",
")",
")",
"# Penalizing negative of min eigen value because we want min eig value",
"# to be positive",
"self",
".",
"total_objective",
"=",
"(",
"self",
".",
"dual_object",
".",
"unconstrained_objective",
"+",
"0.5",
"*",
"tf",
".",
"square",
"(",
"tf",
".",
"maximum",
"(",
"-",
"self",
".",
"penalty_placeholder",
"*",
"self",
".",
"eig_val_estimate",
",",
"0",
")",
")",
")",
"global_step",
"=",
"tf",
".",
"Variable",
"(",
"0",
",",
"trainable",
"=",
"False",
")",
"# Set up learning rate as a placeholder",
"self",
".",
"learning_rate",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"[",
"]",
")",
"# Set up the optimizer",
"if",
"self",
".",
"params",
"[",
"'optimizer'",
"]",
"==",
"'adam'",
":",
"self",
".",
"optimizer",
"=",
"tf",
".",
"train",
".",
"AdamOptimizer",
"(",
"learning_rate",
"=",
"self",
".",
"learning_rate",
")",
"elif",
"self",
".",
"params",
"[",
"'optimizer'",
"]",
"==",
"'adagrad'",
":",
"self",
".",
"optimizer",
"=",
"tf",
".",
"train",
".",
"AdagradOptimizer",
"(",
"learning_rate",
"=",
"self",
".",
"learning_rate",
")",
"elif",
"self",
".",
"params",
"[",
"'optimizer'",
"]",
"==",
"'momentum'",
":",
"self",
".",
"optimizer",
"=",
"tf",
".",
"train",
".",
"MomentumOptimizer",
"(",
"learning_rate",
"=",
"self",
".",
"learning_rate",
",",
"momentum",
"=",
"self",
".",
"params",
"[",
"'momentum_parameter'",
"]",
",",
"use_nesterov",
"=",
"True",
")",
"else",
":",
"self",
".",
"optimizer",
"=",
"tf",
".",
"train",
".",
"GradientDescentOptimizer",
"(",
"learning_rate",
"=",
"self",
".",
"learning_rate",
")",
"# Write out the projection step",
"self",
".",
"train_step",
"=",
"self",
".",
"optimizer",
".",
"minimize",
"(",
"self",
".",
"total_objective",
",",
"global_step",
"=",
"global_step",
")",
"self",
".",
"sess",
".",
"run",
"(",
"tf",
".",
"global_variables_initializer",
"(",
")",
")",
"# Projecting the dual variables",
"proj_ops",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"dual_object",
".",
"nn_params",
".",
"num_hidden_layers",
"+",
"1",
")",
":",
"# Lambda_pos is non negative for switch indices,",
"# Unconstrained for positive indices",
"# Zero for negative indices",
"proj_ops",
".",
"append",
"(",
"self",
".",
"dual_object",
".",
"lambda_pos",
"[",
"i",
"]",
".",
"assign",
"(",
"tf",
".",
"multiply",
"(",
"self",
".",
"dual_object",
".",
"positive_indices",
"[",
"i",
"]",
",",
"self",
".",
"dual_object",
".",
"lambda_pos",
"[",
"i",
"]",
")",
"+",
"tf",
".",
"multiply",
"(",
"self",
".",
"dual_object",
".",
"switch_indices",
"[",
"i",
"]",
",",
"tf",
".",
"nn",
".",
"relu",
"(",
"self",
".",
"dual_object",
".",
"lambda_pos",
"[",
"i",
"]",
")",
")",
")",
")",
"proj_ops",
".",
"append",
"(",
"self",
".",
"dual_object",
".",
"lambda_neg",
"[",
"i",
"]",
".",
"assign",
"(",
"tf",
".",
"multiply",
"(",
"self",
".",
"dual_object",
".",
"negative_indices",
"[",
"i",
"]",
",",
"self",
".",
"dual_object",
".",
"lambda_neg",
"[",
"i",
"]",
")",
"+",
"tf",
".",
"multiply",
"(",
"self",
".",
"dual_object",
".",
"switch_indices",
"[",
"i",
"]",
",",
"tf",
".",
"nn",
".",
"relu",
"(",
"self",
".",
"dual_object",
".",
"lambda_neg",
"[",
"i",
"]",
")",
")",
")",
")",
"# Lambda_quad is only non zero and positive for switch",
"proj_ops",
".",
"append",
"(",
"self",
".",
"dual_object",
".",
"lambda_quad",
"[",
"i",
"]",
".",
"assign",
"(",
"tf",
".",
"multiply",
"(",
"self",
".",
"dual_object",
".",
"switch_indices",
"[",
"i",
"]",
",",
"tf",
".",
"nn",
".",
"relu",
"(",
"self",
".",
"dual_object",
".",
"lambda_quad",
"[",
"i",
"]",
")",
")",
")",
")",
"# Lambda_lu is always non negative",
"proj_ops",
".",
"append",
"(",
"self",
".",
"dual_object",
".",
"lambda_lu",
"[",
"i",
"]",
".",
"assign",
"(",
"tf",
".",
"nn",
".",
"relu",
"(",
"self",
".",
"dual_object",
".",
"lambda_lu",
"[",
"i",
"]",
")",
")",
")",
"self",
".",
"proj_step",
"=",
"tf",
".",
"group",
"(",
"proj_ops",
")",
"# Create folder for saving stats if the folder is not None",
"if",
"(",
"self",
".",
"params",
".",
"get",
"(",
"'stats_folder'",
")",
"and",
"not",
"tf",
".",
"gfile",
".",
"IsDirectory",
"(",
"self",
".",
"params",
"[",
"'stats_folder'",
"]",
")",
")",
":",
"tf",
".",
"gfile",
".",
"MkDir",
"(",
"self",
".",
"params",
"[",
"'stats_folder'",
"]",
")"
] |
Create tensorflow op for running one step of descent.
|
[
"Create",
"tensorflow",
"op",
"for",
"running",
"one",
"step",
"of",
"descent",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L140-L212
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.run_one_step
|
def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen computations
smooth_val: Value of smoothness parameter
penalty_val: Value of penalty for the current step
learning_rate_val: Value of learning rate
Returns:
found_cert: True is negative certificate is found, False otherwise
"""
# Running step
step_feed_dict = {self.eig_init_vec_placeholder: eig_init_vec_val,
self.eig_num_iter_placeholder: eig_num_iter_val,
self.smooth_placeholder: smooth_val,
self.penalty_placeholder: penalty_val,
self.learning_rate: learning_rate_val}
if self.params['eig_type'] == 'SCIPY':
current_eig_vector, self.current_eig_val_estimate = self.get_scipy_eig_vec()
step_feed_dict.update({
self.eig_vec_estimate: current_eig_vector
})
elif self.params['eig_type'] == 'LZS':
step_feed_dict.update({
self.dual_object.m_min_vec_ph: self.dual_object.m_min_vec_estimate
})
self.sess.run(self.train_step, feed_dict=step_feed_dict)
[
_, self.dual_object.m_min_vec_estimate, self.current_eig_val_estimate
] = self.sess.run([
self.proj_step,
self.eig_vec_estimate,
self.eig_val_estimate
], feed_dict=step_feed_dict)
if self.current_step % self.params['print_stats_steps'] == 0:
[self.current_total_objective, self.current_unconstrained_objective,
self.dual_object.m_min_vec_estimate,
self.current_eig_val_estimate,
self.current_nu] = self.sess.run(
[self.total_objective,
self.dual_object.unconstrained_objective,
self.eig_vec_estimate,
self.eig_val_estimate,
self.dual_object.nu], feed_dict=step_feed_dict)
stats = {
'total_objective':
float(self.current_total_objective),
'unconstrained_objective':
float(self.current_unconstrained_objective),
'min_eig_val_estimate':
float(self.current_eig_val_estimate)
}
tf.logging.info('Current inner step: %d, optimization stats: %s',
self.current_step, stats)
if self.params['stats_folder'] is not None:
stats = json.dumps(stats)
filename = os.path.join(self.params['stats_folder'],
str(self.current_step) + '.json')
with tf.gfile.Open(filename) as file_f:
file_f.write(stats)
# Project onto feasible set of dual variables
if self.current_step % self.params['projection_steps'] == 0 and self.current_unconstrained_objective < 0:
nu = self.sess.run(self.dual_object.nu)
dual_feed_dict = {
self.dual_object.h_min_vec_ph: self.dual_object.h_min_vec_estimate
}
_, min_eig_val_h_lz = self.dual_object.get_lanczos_eig(compute_m=False, feed_dict=dual_feed_dict)
projected_dual_feed_dict = {
self.dual_object.projected_dual.nu: nu,
self.dual_object.projected_dual.min_eig_val_h: min_eig_val_h_lz
}
if self.dual_object.projected_dual.compute_certificate(self.current_step, projected_dual_feed_dict):
return True
return False
|
python
|
def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen computations
smooth_val: Value of smoothness parameter
penalty_val: Value of penalty for the current step
learning_rate_val: Value of learning rate
Returns:
found_cert: True is negative certificate is found, False otherwise
"""
# Running step
step_feed_dict = {self.eig_init_vec_placeholder: eig_init_vec_val,
self.eig_num_iter_placeholder: eig_num_iter_val,
self.smooth_placeholder: smooth_val,
self.penalty_placeholder: penalty_val,
self.learning_rate: learning_rate_val}
if self.params['eig_type'] == 'SCIPY':
current_eig_vector, self.current_eig_val_estimate = self.get_scipy_eig_vec()
step_feed_dict.update({
self.eig_vec_estimate: current_eig_vector
})
elif self.params['eig_type'] == 'LZS':
step_feed_dict.update({
self.dual_object.m_min_vec_ph: self.dual_object.m_min_vec_estimate
})
self.sess.run(self.train_step, feed_dict=step_feed_dict)
[
_, self.dual_object.m_min_vec_estimate, self.current_eig_val_estimate
] = self.sess.run([
self.proj_step,
self.eig_vec_estimate,
self.eig_val_estimate
], feed_dict=step_feed_dict)
if self.current_step % self.params['print_stats_steps'] == 0:
[self.current_total_objective, self.current_unconstrained_objective,
self.dual_object.m_min_vec_estimate,
self.current_eig_val_estimate,
self.current_nu] = self.sess.run(
[self.total_objective,
self.dual_object.unconstrained_objective,
self.eig_vec_estimate,
self.eig_val_estimate,
self.dual_object.nu], feed_dict=step_feed_dict)
stats = {
'total_objective':
float(self.current_total_objective),
'unconstrained_objective':
float(self.current_unconstrained_objective),
'min_eig_val_estimate':
float(self.current_eig_val_estimate)
}
tf.logging.info('Current inner step: %d, optimization stats: %s',
self.current_step, stats)
if self.params['stats_folder'] is not None:
stats = json.dumps(stats)
filename = os.path.join(self.params['stats_folder'],
str(self.current_step) + '.json')
with tf.gfile.Open(filename) as file_f:
file_f.write(stats)
# Project onto feasible set of dual variables
if self.current_step % self.params['projection_steps'] == 0 and self.current_unconstrained_objective < 0:
nu = self.sess.run(self.dual_object.nu)
dual_feed_dict = {
self.dual_object.h_min_vec_ph: self.dual_object.h_min_vec_estimate
}
_, min_eig_val_h_lz = self.dual_object.get_lanczos_eig(compute_m=False, feed_dict=dual_feed_dict)
projected_dual_feed_dict = {
self.dual_object.projected_dual.nu: nu,
self.dual_object.projected_dual.min_eig_val_h: min_eig_val_h_lz
}
if self.dual_object.projected_dual.compute_certificate(self.current_step, projected_dual_feed_dict):
return True
return False
|
[
"def",
"run_one_step",
"(",
"self",
",",
"eig_init_vec_val",
",",
"eig_num_iter_val",
",",
"smooth_val",
",",
"penalty_val",
",",
"learning_rate_val",
")",
":",
"# Running step",
"step_feed_dict",
"=",
"{",
"self",
".",
"eig_init_vec_placeholder",
":",
"eig_init_vec_val",
",",
"self",
".",
"eig_num_iter_placeholder",
":",
"eig_num_iter_val",
",",
"self",
".",
"smooth_placeholder",
":",
"smooth_val",
",",
"self",
".",
"penalty_placeholder",
":",
"penalty_val",
",",
"self",
".",
"learning_rate",
":",
"learning_rate_val",
"}",
"if",
"self",
".",
"params",
"[",
"'eig_type'",
"]",
"==",
"'SCIPY'",
":",
"current_eig_vector",
",",
"self",
".",
"current_eig_val_estimate",
"=",
"self",
".",
"get_scipy_eig_vec",
"(",
")",
"step_feed_dict",
".",
"update",
"(",
"{",
"self",
".",
"eig_vec_estimate",
":",
"current_eig_vector",
"}",
")",
"elif",
"self",
".",
"params",
"[",
"'eig_type'",
"]",
"==",
"'LZS'",
":",
"step_feed_dict",
".",
"update",
"(",
"{",
"self",
".",
"dual_object",
".",
"m_min_vec_ph",
":",
"self",
".",
"dual_object",
".",
"m_min_vec_estimate",
"}",
")",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"train_step",
",",
"feed_dict",
"=",
"step_feed_dict",
")",
"[",
"_",
",",
"self",
".",
"dual_object",
".",
"m_min_vec_estimate",
",",
"self",
".",
"current_eig_val_estimate",
"]",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"[",
"self",
".",
"proj_step",
",",
"self",
".",
"eig_vec_estimate",
",",
"self",
".",
"eig_val_estimate",
"]",
",",
"feed_dict",
"=",
"step_feed_dict",
")",
"if",
"self",
".",
"current_step",
"%",
"self",
".",
"params",
"[",
"'print_stats_steps'",
"]",
"==",
"0",
":",
"[",
"self",
".",
"current_total_objective",
",",
"self",
".",
"current_unconstrained_objective",
",",
"self",
".",
"dual_object",
".",
"m_min_vec_estimate",
",",
"self",
".",
"current_eig_val_estimate",
",",
"self",
".",
"current_nu",
"]",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"[",
"self",
".",
"total_objective",
",",
"self",
".",
"dual_object",
".",
"unconstrained_objective",
",",
"self",
".",
"eig_vec_estimate",
",",
"self",
".",
"eig_val_estimate",
",",
"self",
".",
"dual_object",
".",
"nu",
"]",
",",
"feed_dict",
"=",
"step_feed_dict",
")",
"stats",
"=",
"{",
"'total_objective'",
":",
"float",
"(",
"self",
".",
"current_total_objective",
")",
",",
"'unconstrained_objective'",
":",
"float",
"(",
"self",
".",
"current_unconstrained_objective",
")",
",",
"'min_eig_val_estimate'",
":",
"float",
"(",
"self",
".",
"current_eig_val_estimate",
")",
"}",
"tf",
".",
"logging",
".",
"info",
"(",
"'Current inner step: %d, optimization stats: %s'",
",",
"self",
".",
"current_step",
",",
"stats",
")",
"if",
"self",
".",
"params",
"[",
"'stats_folder'",
"]",
"is",
"not",
"None",
":",
"stats",
"=",
"json",
".",
"dumps",
"(",
"stats",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"params",
"[",
"'stats_folder'",
"]",
",",
"str",
"(",
"self",
".",
"current_step",
")",
"+",
"'.json'",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"file_f",
":",
"file_f",
".",
"write",
"(",
"stats",
")",
"# Project onto feasible set of dual variables",
"if",
"self",
".",
"current_step",
"%",
"self",
".",
"params",
"[",
"'projection_steps'",
"]",
"==",
"0",
"and",
"self",
".",
"current_unconstrained_objective",
"<",
"0",
":",
"nu",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"dual_object",
".",
"nu",
")",
"dual_feed_dict",
"=",
"{",
"self",
".",
"dual_object",
".",
"h_min_vec_ph",
":",
"self",
".",
"dual_object",
".",
"h_min_vec_estimate",
"}",
"_",
",",
"min_eig_val_h_lz",
"=",
"self",
".",
"dual_object",
".",
"get_lanczos_eig",
"(",
"compute_m",
"=",
"False",
",",
"feed_dict",
"=",
"dual_feed_dict",
")",
"projected_dual_feed_dict",
"=",
"{",
"self",
".",
"dual_object",
".",
"projected_dual",
".",
"nu",
":",
"nu",
",",
"self",
".",
"dual_object",
".",
"projected_dual",
".",
"min_eig_val_h",
":",
"min_eig_val_h_lz",
"}",
"if",
"self",
".",
"dual_object",
".",
"projected_dual",
".",
"compute_certificate",
"(",
"self",
".",
"current_step",
",",
"projected_dual_feed_dict",
")",
":",
"return",
"True",
"return",
"False"
] |
Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen computations
smooth_val: Value of smoothness parameter
penalty_val: Value of penalty for the current step
learning_rate_val: Value of learning rate
Returns:
found_cert: True is negative certificate is found, False otherwise
|
[
"Run",
"one",
"step",
"of",
"gradient",
"descent",
"for",
"optimization",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L214-L296
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/optimization.py
|
Optimization.run_optimization
|
def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on = False
smooth_val = 0
learning_rate_val = self.params['init_learning_rate']
self.current_outer_step = 1
while self.current_outer_step <= self.params['outer_num_steps']:
tf.logging.info('Running outer step %d with penalty %f',
self.current_outer_step, penalty_val)
# Running inner loop of optimization with current_smooth_val,
# current_penalty as smoothness parameters and penalty respectively
self.current_step = 0
# Run first step with random eig initialization and large number of steps
found_cert = self.run_one_step(
self.dual_object.m_min_vec_estimate,
self.params['large_eig_num_steps'], smooth_val, penalty_val, learning_rate_val)
if found_cert:
return True
while self.current_step < self.params['inner_num_steps']:
self.current_step = self.current_step + 1
found_cert = self.run_one_step(self.dual_object.m_min_vec_estimate,
self.params['small_eig_num_steps'],
smooth_val, penalty_val,
learning_rate_val)
if found_cert:
return True
# Update penalty only if it looks like current objective is optimizes
if self.current_total_objective < UPDATE_PARAM_CONSTANT:
penalty_val = penalty_val * self.params['beta']
learning_rate_val = learning_rate_val*self.params['learning_rate_decay']
else:
# To get more accurate gradient estimate
self.params['small_eig_num_steps'] = (
1.5 * self.params['small_eig_num_steps'])
# If eigen values seem small enough, turn on smoothing
# useful only when performing full eigen decomposition
if np.abs(self.current_eig_val_estimate) < 0.01:
smooth_val = self.params['smoothness_parameter']
self.current_outer_step = self.current_outer_step + 1
return False
|
python
|
def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on = False
smooth_val = 0
learning_rate_val = self.params['init_learning_rate']
self.current_outer_step = 1
while self.current_outer_step <= self.params['outer_num_steps']:
tf.logging.info('Running outer step %d with penalty %f',
self.current_outer_step, penalty_val)
# Running inner loop of optimization with current_smooth_val,
# current_penalty as smoothness parameters and penalty respectively
self.current_step = 0
# Run first step with random eig initialization and large number of steps
found_cert = self.run_one_step(
self.dual_object.m_min_vec_estimate,
self.params['large_eig_num_steps'], smooth_val, penalty_val, learning_rate_val)
if found_cert:
return True
while self.current_step < self.params['inner_num_steps']:
self.current_step = self.current_step + 1
found_cert = self.run_one_step(self.dual_object.m_min_vec_estimate,
self.params['small_eig_num_steps'],
smooth_val, penalty_val,
learning_rate_val)
if found_cert:
return True
# Update penalty only if it looks like current objective is optimizes
if self.current_total_objective < UPDATE_PARAM_CONSTANT:
penalty_val = penalty_val * self.params['beta']
learning_rate_val = learning_rate_val*self.params['learning_rate_decay']
else:
# To get more accurate gradient estimate
self.params['small_eig_num_steps'] = (
1.5 * self.params['small_eig_num_steps'])
# If eigen values seem small enough, turn on smoothing
# useful only when performing full eigen decomposition
if np.abs(self.current_eig_val_estimate) < 0.01:
smooth_val = self.params['smoothness_parameter']
self.current_outer_step = self.current_outer_step + 1
return False
|
[
"def",
"run_optimization",
"(",
"self",
")",
":",
"penalty_val",
"=",
"self",
".",
"params",
"[",
"'init_penalty'",
"]",
"# Don't use smoothing initially - very inaccurate for large dimension",
"self",
".",
"smooth_on",
"=",
"False",
"smooth_val",
"=",
"0",
"learning_rate_val",
"=",
"self",
".",
"params",
"[",
"'init_learning_rate'",
"]",
"self",
".",
"current_outer_step",
"=",
"1",
"while",
"self",
".",
"current_outer_step",
"<=",
"self",
".",
"params",
"[",
"'outer_num_steps'",
"]",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"'Running outer step %d with penalty %f'",
",",
"self",
".",
"current_outer_step",
",",
"penalty_val",
")",
"# Running inner loop of optimization with current_smooth_val,",
"# current_penalty as smoothness parameters and penalty respectively",
"self",
".",
"current_step",
"=",
"0",
"# Run first step with random eig initialization and large number of steps",
"found_cert",
"=",
"self",
".",
"run_one_step",
"(",
"self",
".",
"dual_object",
".",
"m_min_vec_estimate",
",",
"self",
".",
"params",
"[",
"'large_eig_num_steps'",
"]",
",",
"smooth_val",
",",
"penalty_val",
",",
"learning_rate_val",
")",
"if",
"found_cert",
":",
"return",
"True",
"while",
"self",
".",
"current_step",
"<",
"self",
".",
"params",
"[",
"'inner_num_steps'",
"]",
":",
"self",
".",
"current_step",
"=",
"self",
".",
"current_step",
"+",
"1",
"found_cert",
"=",
"self",
".",
"run_one_step",
"(",
"self",
".",
"dual_object",
".",
"m_min_vec_estimate",
",",
"self",
".",
"params",
"[",
"'small_eig_num_steps'",
"]",
",",
"smooth_val",
",",
"penalty_val",
",",
"learning_rate_val",
")",
"if",
"found_cert",
":",
"return",
"True",
"# Update penalty only if it looks like current objective is optimizes",
"if",
"self",
".",
"current_total_objective",
"<",
"UPDATE_PARAM_CONSTANT",
":",
"penalty_val",
"=",
"penalty_val",
"*",
"self",
".",
"params",
"[",
"'beta'",
"]",
"learning_rate_val",
"=",
"learning_rate_val",
"*",
"self",
".",
"params",
"[",
"'learning_rate_decay'",
"]",
"else",
":",
"# To get more accurate gradient estimate",
"self",
".",
"params",
"[",
"'small_eig_num_steps'",
"]",
"=",
"(",
"1.5",
"*",
"self",
".",
"params",
"[",
"'small_eig_num_steps'",
"]",
")",
"# If eigen values seem small enough, turn on smoothing",
"# useful only when performing full eigen decomposition",
"if",
"np",
".",
"abs",
"(",
"self",
".",
"current_eig_val_estimate",
")",
"<",
"0.01",
":",
"smooth_val",
"=",
"self",
".",
"params",
"[",
"'smoothness_parameter'",
"]",
"self",
".",
"current_outer_step",
"=",
"self",
".",
"current_outer_step",
"+",
"1",
"return",
"False"
] |
Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
|
[
"Run",
"the",
"optimization",
"call",
"run_one_step",
"with",
"suitable",
"placeholders",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L298-L347
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py
|
load_target_class
|
def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2}
|
python
|
def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2}
|
[
"def",
"load_target_class",
"(",
"input_dir",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"'target_class.csv'",
")",
")",
"as",
"f",
":",
"return",
"{",
"row",
"[",
"0",
"]",
":",
"int",
"(",
"row",
"[",
"1",
"]",
")",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"f",
")",
"if",
"len",
"(",
"row",
")",
">=",
"2",
"}"
] |
Loads target classes.
|
[
"Loads",
"target",
"classes",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L53-L56
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py
|
save_images
|
def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to save images
"""
for i, filename in enumerate(filenames):
# Images for inception classifier are normalized to be in [-1, 1] interval,
# so rescale them back to [0, 1].
with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f:
imsave(f, (images[i, :, :, :] + 1.0) * 0.5, format='png')
|
python
|
def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to save images
"""
for i, filename in enumerate(filenames):
# Images for inception classifier are normalized to be in [-1, 1] interval,
# so rescale them back to [0, 1].
with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f:
imsave(f, (images[i, :, :, :] + 1.0) * 0.5, format='png')
|
[
"def",
"save_images",
"(",
"images",
",",
"filenames",
",",
"output_dir",
")",
":",
"for",
"i",
",",
"filename",
"in",
"enumerate",
"(",
"filenames",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# so rescale them back to [0, 1].",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"filename",
")",
",",
"'w'",
")",
"as",
"f",
":",
"imsave",
"(",
"f",
",",
"(",
"images",
"[",
"i",
",",
":",
",",
":",
",",
":",
"]",
"+",
"1.0",
")",
"*",
"0.5",
",",
"format",
"=",
"'png'",
")"
] |
Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to save images
|
[
"Saves",
"images",
"to",
"the",
"output",
"directory",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L92-L106
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py
|
main
|
def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
alpha = 2.0 * FLAGS.iter_alpha / 255.0
num_iter = FLAGS.num_iter
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
nb_classes = 1001
tf.logging.set_verbosity(tf.logging.INFO)
all_images_taget_class = load_target_class(FLAGS.input_dir)
with tf.Graph().as_default():
# Prepare graph
x_input = tf.placeholder(tf.float32, shape=batch_shape)
x_max = tf.clip_by_value(x_input + eps, -1.0, 1.0)
x_min = tf.clip_by_value(x_input - eps, -1.0, 1.0)
with slim.arg_scope(inception.inception_v3_arg_scope()):
inception.inception_v3(
x_input, num_classes=nb_classes, is_training=False)
x_adv = x_input
target_class_input = tf.placeholder(tf.int32, shape=[FLAGS.batch_size])
one_hot_target_class = tf.one_hot(target_class_input, nb_classes)
for _ in range(num_iter):
with slim.arg_scope(inception.inception_v3_arg_scope()):
logits, end_points = inception.inception_v3(
x_adv, num_classes=nb_classes, is_training=False, reuse=True)
cross_entropy = tf.losses.softmax_cross_entropy(one_hot_target_class,
logits,
label_smoothing=0.1,
weights=1.0)
cross_entropy += tf.losses.softmax_cross_entropy(one_hot_target_class,
end_points['AuxLogits'],
label_smoothing=0.1,
weights=0.4)
x_next = x_adv - alpha * tf.sign(tf.gradients(cross_entropy, x_adv)[0])
x_next = tf.clip_by_value(x_next, x_min, x_max)
x_adv = x_next
# Run computation
saver = tf.train.Saver(slim.get_model_variables())
session_creator = tf.train.ChiefSessionCreator(
scaffold=tf.train.Scaffold(saver=saver),
checkpoint_filename_with_path=FLAGS.checkpoint_path,
master=FLAGS.master)
with tf.train.MonitoredSession(session_creator=session_creator) as sess:
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
target_class_for_batch = (
[all_images_taget_class[n] for n in filenames]
+ [0] * (FLAGS.batch_size - len(filenames)))
adv_images = sess.run(x_adv,
feed_dict={
x_input: images,
target_class_input: target_class_for_batch
})
save_images(adv_images, filenames, FLAGS.output_dir)
|
python
|
def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
alpha = 2.0 * FLAGS.iter_alpha / 255.0
num_iter = FLAGS.num_iter
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
nb_classes = 1001
tf.logging.set_verbosity(tf.logging.INFO)
all_images_taget_class = load_target_class(FLAGS.input_dir)
with tf.Graph().as_default():
# Prepare graph
x_input = tf.placeholder(tf.float32, shape=batch_shape)
x_max = tf.clip_by_value(x_input + eps, -1.0, 1.0)
x_min = tf.clip_by_value(x_input - eps, -1.0, 1.0)
with slim.arg_scope(inception.inception_v3_arg_scope()):
inception.inception_v3(
x_input, num_classes=nb_classes, is_training=False)
x_adv = x_input
target_class_input = tf.placeholder(tf.int32, shape=[FLAGS.batch_size])
one_hot_target_class = tf.one_hot(target_class_input, nb_classes)
for _ in range(num_iter):
with slim.arg_scope(inception.inception_v3_arg_scope()):
logits, end_points = inception.inception_v3(
x_adv, num_classes=nb_classes, is_training=False, reuse=True)
cross_entropy = tf.losses.softmax_cross_entropy(one_hot_target_class,
logits,
label_smoothing=0.1,
weights=1.0)
cross_entropy += tf.losses.softmax_cross_entropy(one_hot_target_class,
end_points['AuxLogits'],
label_smoothing=0.1,
weights=0.4)
x_next = x_adv - alpha * tf.sign(tf.gradients(cross_entropy, x_adv)[0])
x_next = tf.clip_by_value(x_next, x_min, x_max)
x_adv = x_next
# Run computation
saver = tf.train.Saver(slim.get_model_variables())
session_creator = tf.train.ChiefSessionCreator(
scaffold=tf.train.Scaffold(saver=saver),
checkpoint_filename_with_path=FLAGS.checkpoint_path,
master=FLAGS.master)
with tf.train.MonitoredSession(session_creator=session_creator) as sess:
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
target_class_for_batch = (
[all_images_taget_class[n] for n in filenames]
+ [0] * (FLAGS.batch_size - len(filenames)))
adv_images = sess.run(x_adv,
feed_dict={
x_input: images,
target_class_input: target_class_for_batch
})
save_images(adv_images, filenames, FLAGS.output_dir)
|
[
"def",
"main",
"(",
"_",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# eps is a difference between pixels so it should be in [0, 2] interval.",
"# Renormalizing epsilon from [0, 255] to [0, 2].",
"eps",
"=",
"2.0",
"*",
"FLAGS",
".",
"max_epsilon",
"/",
"255.0",
"alpha",
"=",
"2.0",
"*",
"FLAGS",
".",
"iter_alpha",
"/",
"255.0",
"num_iter",
"=",
"FLAGS",
".",
"num_iter",
"batch_shape",
"=",
"[",
"FLAGS",
".",
"batch_size",
",",
"FLAGS",
".",
"image_height",
",",
"FLAGS",
".",
"image_width",
",",
"3",
"]",
"nb_classes",
"=",
"1001",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"INFO",
")",
"all_images_taget_class",
"=",
"load_target_class",
"(",
"FLAGS",
".",
"input_dir",
")",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"# Prepare graph",
"x_input",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"batch_shape",
")",
"x_max",
"=",
"tf",
".",
"clip_by_value",
"(",
"x_input",
"+",
"eps",
",",
"-",
"1.0",
",",
"1.0",
")",
"x_min",
"=",
"tf",
".",
"clip_by_value",
"(",
"x_input",
"-",
"eps",
",",
"-",
"1.0",
",",
"1.0",
")",
"with",
"slim",
".",
"arg_scope",
"(",
"inception",
".",
"inception_v3_arg_scope",
"(",
")",
")",
":",
"inception",
".",
"inception_v3",
"(",
"x_input",
",",
"num_classes",
"=",
"nb_classes",
",",
"is_training",
"=",
"False",
")",
"x_adv",
"=",
"x_input",
"target_class_input",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"int32",
",",
"shape",
"=",
"[",
"FLAGS",
".",
"batch_size",
"]",
")",
"one_hot_target_class",
"=",
"tf",
".",
"one_hot",
"(",
"target_class_input",
",",
"nb_classes",
")",
"for",
"_",
"in",
"range",
"(",
"num_iter",
")",
":",
"with",
"slim",
".",
"arg_scope",
"(",
"inception",
".",
"inception_v3_arg_scope",
"(",
")",
")",
":",
"logits",
",",
"end_points",
"=",
"inception",
".",
"inception_v3",
"(",
"x_adv",
",",
"num_classes",
"=",
"nb_classes",
",",
"is_training",
"=",
"False",
",",
"reuse",
"=",
"True",
")",
"cross_entropy",
"=",
"tf",
".",
"losses",
".",
"softmax_cross_entropy",
"(",
"one_hot_target_class",
",",
"logits",
",",
"label_smoothing",
"=",
"0.1",
",",
"weights",
"=",
"1.0",
")",
"cross_entropy",
"+=",
"tf",
".",
"losses",
".",
"softmax_cross_entropy",
"(",
"one_hot_target_class",
",",
"end_points",
"[",
"'AuxLogits'",
"]",
",",
"label_smoothing",
"=",
"0.1",
",",
"weights",
"=",
"0.4",
")",
"x_next",
"=",
"x_adv",
"-",
"alpha",
"*",
"tf",
".",
"sign",
"(",
"tf",
".",
"gradients",
"(",
"cross_entropy",
",",
"x_adv",
")",
"[",
"0",
"]",
")",
"x_next",
"=",
"tf",
".",
"clip_by_value",
"(",
"x_next",
",",
"x_min",
",",
"x_max",
")",
"x_adv",
"=",
"x_next",
"# Run computation",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
"slim",
".",
"get_model_variables",
"(",
")",
")",
"session_creator",
"=",
"tf",
".",
"train",
".",
"ChiefSessionCreator",
"(",
"scaffold",
"=",
"tf",
".",
"train",
".",
"Scaffold",
"(",
"saver",
"=",
"saver",
")",
",",
"checkpoint_filename_with_path",
"=",
"FLAGS",
".",
"checkpoint_path",
",",
"master",
"=",
"FLAGS",
".",
"master",
")",
"with",
"tf",
".",
"train",
".",
"MonitoredSession",
"(",
"session_creator",
"=",
"session_creator",
")",
"as",
"sess",
":",
"for",
"filenames",
",",
"images",
"in",
"load_images",
"(",
"FLAGS",
".",
"input_dir",
",",
"batch_shape",
")",
":",
"target_class_for_batch",
"=",
"(",
"[",
"all_images_taget_class",
"[",
"n",
"]",
"for",
"n",
"in",
"filenames",
"]",
"+",
"[",
"0",
"]",
"*",
"(",
"FLAGS",
".",
"batch_size",
"-",
"len",
"(",
"filenames",
")",
")",
")",
"adv_images",
"=",
"sess",
".",
"run",
"(",
"x_adv",
",",
"feed_dict",
"=",
"{",
"x_input",
":",
"images",
",",
"target_class_input",
":",
"target_class_for_batch",
"}",
")",
"save_images",
"(",
"adv_images",
",",
"filenames",
",",
"FLAGS",
".",
"output_dir",
")"
] |
Run the sample attack
|
[
"Run",
"the",
"sample",
"attack"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L109-L171
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/deep_fool.py
|
deepfool_batch
|
def deepfool_batch(sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_classes,
feed=None):
"""
Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The model's sorted symbolic output of logits, only the top
nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax layer)
:param grads: Symbolic gradients of the top nb_candidate classes, procuded
from gradient_graph
:param X: Numpy array with sample inputs
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for DeepFool
:param clip_min: Minimum value for components of the example returned
:param clip_max: Maximum value for components of the example returned
:param nb_classes: Number of model output classes
:return: Adversarial examples
"""
X_adv = deepfool_attack(
sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
feed=feed)
return np.asarray(X_adv, dtype=np_dtype)
|
python
|
def deepfool_batch(sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_classes,
feed=None):
"""
Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The model's sorted symbolic output of logits, only the top
nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax layer)
:param grads: Symbolic gradients of the top nb_candidate classes, procuded
from gradient_graph
:param X: Numpy array with sample inputs
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for DeepFool
:param clip_min: Minimum value for components of the example returned
:param clip_max: Maximum value for components of the example returned
:param nb_classes: Number of model output classes
:return: Adversarial examples
"""
X_adv = deepfool_attack(
sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
feed=feed)
return np.asarray(X_adv, dtype=np_dtype)
|
[
"def",
"deepfool_batch",
"(",
"sess",
",",
"x",
",",
"pred",
",",
"logits",
",",
"grads",
",",
"X",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"nb_classes",
",",
"feed",
"=",
"None",
")",
":",
"X_adv",
"=",
"deepfool_attack",
"(",
"sess",
",",
"x",
",",
"pred",
",",
"logits",
",",
"grads",
",",
"X",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"feed",
"=",
"feed",
")",
"return",
"np",
".",
"asarray",
"(",
"X_adv",
",",
"dtype",
"=",
"np_dtype",
")"
] |
Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The model's sorted symbolic output of logits, only the top
nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax layer)
:param grads: Symbolic gradients of the top nb_candidate classes, procuded
from gradient_graph
:param X: Numpy array with sample inputs
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for DeepFool
:param clip_min: Minimum value for components of the example returned
:param clip_max: Maximum value for components of the example returned
:param nb_classes: Number of model output classes
:return: Adversarial examples
|
[
"Applies",
"DeepFool",
"to",
"a",
"batch",
"of",
"inputs",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"The",
"input",
"placeholder",
":",
"param",
"pred",
":",
"The",
"model",
"s",
"sorted",
"symbolic",
"output",
"of",
"logits",
"only",
"the",
"top",
"nb_candidate",
"classes",
"are",
"contained",
":",
"param",
"logits",
":",
"The",
"model",
"s",
"unnormalized",
"output",
"tensor",
"(",
"the",
"input",
"to",
"the",
"softmax",
"layer",
")",
":",
"param",
"grads",
":",
"Symbolic",
"gradients",
"of",
"the",
"top",
"nb_candidate",
"classes",
"procuded",
"from",
"gradient_graph",
":",
"param",
"X",
":",
"Numpy",
"array",
"with",
"sample",
"inputs",
":",
"param",
"nb_candidate",
":",
"The",
"number",
"of",
"classes",
"to",
"test",
"against",
"i",
".",
"e",
".",
"deepfool",
"only",
"consider",
"nb_candidate",
"classes",
"when",
"attacking",
"(",
"thus",
"accelerate",
"speed",
")",
".",
"The",
"nb_candidate",
"classes",
"are",
"chosen",
"according",
"to",
"the",
"prediction",
"confidence",
"during",
"implementation",
".",
":",
"param",
"overshoot",
":",
"A",
"termination",
"criterion",
"to",
"prevent",
"vanishing",
"updates",
":",
"param",
"max_iter",
":",
"Maximum",
"number",
"of",
"iteration",
"for",
"DeepFool",
":",
"param",
"clip_min",
":",
"Minimum",
"value",
"for",
"components",
"of",
"the",
"example",
"returned",
":",
"param",
"clip_max",
":",
"Maximum",
"value",
"for",
"components",
"of",
"the",
"example",
"returned",
":",
"param",
"nb_classes",
":",
"Number",
"of",
"model",
"output",
"classes",
":",
"return",
":",
"Adversarial",
"examples"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L115-L165
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/deep_fool.py
|
deepfool_attack
|
def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
feed=None):
"""
TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax layer)
:param grads: Symbolic gradients of the top nb_candidate classes, procuded
from gradient_graph
:param sample: Numpy array with sample input
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for DeepFool
:param clip_min: Minimum value for components of the example returned
:param clip_max: Maximum value for components of the example returned
:return: Adversarial examples
"""
adv_x = copy.copy(sample)
# Initialize the loop variables
iteration = 0
current = utils_tf.model_argmax(sess, x, logits, adv_x, feed=feed)
if current.shape == ():
current = np.array([current])
w = np.squeeze(np.zeros(sample.shape[1:])) # same shape as original image
r_tot = np.zeros(sample.shape)
original = current # use original label as the reference
_logger.debug(
"Starting DeepFool attack up to %s iterations", max_iter)
# Repeat this main loop until we have achieved misclassification
while (np.any(current == original) and iteration < max_iter):
if iteration % 5 == 0 and iteration > 0:
_logger.info("Attack result at iteration %s is %s", iteration, current)
gradients = sess.run(grads, feed_dict={x: adv_x})
predictions_val = sess.run(predictions, feed_dict={x: adv_x})
for idx in range(sample.shape[0]):
pert = np.inf
if current[idx] != original[idx]:
continue
for k in range(1, nb_candidate):
w_k = gradients[idx, k, ...] - gradients[idx, 0, ...]
f_k = predictions_val[idx, k] - predictions_val[idx, 0]
# adding value 0.00001 to prevent f_k = 0
pert_k = (abs(f_k) + 0.00001) / np.linalg.norm(w_k.flatten())
if pert_k < pert:
pert = pert_k
w = w_k
r_i = pert * w / np.linalg.norm(w)
r_tot[idx, ...] = r_tot[idx, ...] + r_i
adv_x = np.clip(r_tot + sample, clip_min, clip_max)
current = utils_tf.model_argmax(sess, x, logits, adv_x, feed=feed)
if current.shape == ():
current = np.array([current])
# Update loop variables
iteration = iteration + 1
# need more revision, including info like how many succeed
_logger.info("Attack result at iteration %s is %s", iteration, current)
_logger.info("%s out of %s become adversarial examples at iteration %s",
sum(current != original),
sample.shape[0],
iteration)
# need to clip this image into the given range
adv_x = np.clip((1 + overshoot) * r_tot + sample, clip_min, clip_max)
return adv_x
|
python
|
def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
feed=None):
"""
TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax layer)
:param grads: Symbolic gradients of the top nb_candidate classes, procuded
from gradient_graph
:param sample: Numpy array with sample input
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for DeepFool
:param clip_min: Minimum value for components of the example returned
:param clip_max: Maximum value for components of the example returned
:return: Adversarial examples
"""
adv_x = copy.copy(sample)
# Initialize the loop variables
iteration = 0
current = utils_tf.model_argmax(sess, x, logits, adv_x, feed=feed)
if current.shape == ():
current = np.array([current])
w = np.squeeze(np.zeros(sample.shape[1:])) # same shape as original image
r_tot = np.zeros(sample.shape)
original = current # use original label as the reference
_logger.debug(
"Starting DeepFool attack up to %s iterations", max_iter)
# Repeat this main loop until we have achieved misclassification
while (np.any(current == original) and iteration < max_iter):
if iteration % 5 == 0 and iteration > 0:
_logger.info("Attack result at iteration %s is %s", iteration, current)
gradients = sess.run(grads, feed_dict={x: adv_x})
predictions_val = sess.run(predictions, feed_dict={x: adv_x})
for idx in range(sample.shape[0]):
pert = np.inf
if current[idx] != original[idx]:
continue
for k in range(1, nb_candidate):
w_k = gradients[idx, k, ...] - gradients[idx, 0, ...]
f_k = predictions_val[idx, k] - predictions_val[idx, 0]
# adding value 0.00001 to prevent f_k = 0
pert_k = (abs(f_k) + 0.00001) / np.linalg.norm(w_k.flatten())
if pert_k < pert:
pert = pert_k
w = w_k
r_i = pert * w / np.linalg.norm(w)
r_tot[idx, ...] = r_tot[idx, ...] + r_i
adv_x = np.clip(r_tot + sample, clip_min, clip_max)
current = utils_tf.model_argmax(sess, x, logits, adv_x, feed=feed)
if current.shape == ():
current = np.array([current])
# Update loop variables
iteration = iteration + 1
# need more revision, including info like how many succeed
_logger.info("Attack result at iteration %s is %s", iteration, current)
_logger.info("%s out of %s become adversarial examples at iteration %s",
sum(current != original),
sample.shape[0],
iteration)
# need to clip this image into the given range
adv_x = np.clip((1 + overshoot) * r_tot + sample, clip_min, clip_max)
return adv_x
|
[
"def",
"deepfool_attack",
"(",
"sess",
",",
"x",
",",
"predictions",
",",
"logits",
",",
"grads",
",",
"sample",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"feed",
"=",
"None",
")",
":",
"adv_x",
"=",
"copy",
".",
"copy",
"(",
"sample",
")",
"# Initialize the loop variables",
"iteration",
"=",
"0",
"current",
"=",
"utils_tf",
".",
"model_argmax",
"(",
"sess",
",",
"x",
",",
"logits",
",",
"adv_x",
",",
"feed",
"=",
"feed",
")",
"if",
"current",
".",
"shape",
"==",
"(",
")",
":",
"current",
"=",
"np",
".",
"array",
"(",
"[",
"current",
"]",
")",
"w",
"=",
"np",
".",
"squeeze",
"(",
"np",
".",
"zeros",
"(",
"sample",
".",
"shape",
"[",
"1",
":",
"]",
")",
")",
"# same shape as original image",
"r_tot",
"=",
"np",
".",
"zeros",
"(",
"sample",
".",
"shape",
")",
"original",
"=",
"current",
"# use original label as the reference",
"_logger",
".",
"debug",
"(",
"\"Starting DeepFool attack up to %s iterations\"",
",",
"max_iter",
")",
"# Repeat this main loop until we have achieved misclassification",
"while",
"(",
"np",
".",
"any",
"(",
"current",
"==",
"original",
")",
"and",
"iteration",
"<",
"max_iter",
")",
":",
"if",
"iteration",
"%",
"5",
"==",
"0",
"and",
"iteration",
">",
"0",
":",
"_logger",
".",
"info",
"(",
"\"Attack result at iteration %s is %s\"",
",",
"iteration",
",",
"current",
")",
"gradients",
"=",
"sess",
".",
"run",
"(",
"grads",
",",
"feed_dict",
"=",
"{",
"x",
":",
"adv_x",
"}",
")",
"predictions_val",
"=",
"sess",
".",
"run",
"(",
"predictions",
",",
"feed_dict",
"=",
"{",
"x",
":",
"adv_x",
"}",
")",
"for",
"idx",
"in",
"range",
"(",
"sample",
".",
"shape",
"[",
"0",
"]",
")",
":",
"pert",
"=",
"np",
".",
"inf",
"if",
"current",
"[",
"idx",
"]",
"!=",
"original",
"[",
"idx",
"]",
":",
"continue",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"nb_candidate",
")",
":",
"w_k",
"=",
"gradients",
"[",
"idx",
",",
"k",
",",
"...",
"]",
"-",
"gradients",
"[",
"idx",
",",
"0",
",",
"...",
"]",
"f_k",
"=",
"predictions_val",
"[",
"idx",
",",
"k",
"]",
"-",
"predictions_val",
"[",
"idx",
",",
"0",
"]",
"# adding value 0.00001 to prevent f_k = 0",
"pert_k",
"=",
"(",
"abs",
"(",
"f_k",
")",
"+",
"0.00001",
")",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"w_k",
".",
"flatten",
"(",
")",
")",
"if",
"pert_k",
"<",
"pert",
":",
"pert",
"=",
"pert_k",
"w",
"=",
"w_k",
"r_i",
"=",
"pert",
"*",
"w",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"w",
")",
"r_tot",
"[",
"idx",
",",
"...",
"]",
"=",
"r_tot",
"[",
"idx",
",",
"...",
"]",
"+",
"r_i",
"adv_x",
"=",
"np",
".",
"clip",
"(",
"r_tot",
"+",
"sample",
",",
"clip_min",
",",
"clip_max",
")",
"current",
"=",
"utils_tf",
".",
"model_argmax",
"(",
"sess",
",",
"x",
",",
"logits",
",",
"adv_x",
",",
"feed",
"=",
"feed",
")",
"if",
"current",
".",
"shape",
"==",
"(",
")",
":",
"current",
"=",
"np",
".",
"array",
"(",
"[",
"current",
"]",
")",
"# Update loop variables",
"iteration",
"=",
"iteration",
"+",
"1",
"# need more revision, including info like how many succeed",
"_logger",
".",
"info",
"(",
"\"Attack result at iteration %s is %s\"",
",",
"iteration",
",",
"current",
")",
"_logger",
".",
"info",
"(",
"\"%s out of %s become adversarial examples at iteration %s\"",
",",
"sum",
"(",
"current",
"!=",
"original",
")",
",",
"sample",
".",
"shape",
"[",
"0",
"]",
",",
"iteration",
")",
"# need to clip this image into the given range",
"adv_x",
"=",
"np",
".",
"clip",
"(",
"(",
"1",
"+",
"overshoot",
")",
"*",
"r_tot",
"+",
"sample",
",",
"clip_min",
",",
"clip_max",
")",
"return",
"adv_x"
] |
TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax layer)
:param grads: Symbolic gradients of the top nb_candidate classes, procuded
from gradient_graph
:param sample: Numpy array with sample input
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for DeepFool
:param clip_min: Minimum value for components of the example returned
:param clip_max: Maximum value for components of the example returned
:return: Adversarial examples
|
[
"TensorFlow",
"implementation",
"of",
"DeepFool",
".",
"Paper",
"link",
":",
"see",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1511",
".",
"04599",
".",
"pdf",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"The",
"input",
"placeholder",
":",
"param",
"predictions",
":",
"The",
"model",
"s",
"sorted",
"symbolic",
"output",
"of",
"logits",
"only",
"the",
"top",
"nb_candidate",
"classes",
"are",
"contained",
":",
"param",
"logits",
":",
"The",
"model",
"s",
"unnormalized",
"output",
"tensor",
"(",
"the",
"input",
"to",
"the",
"softmax",
"layer",
")",
":",
"param",
"grads",
":",
"Symbolic",
"gradients",
"of",
"the",
"top",
"nb_candidate",
"classes",
"procuded",
"from",
"gradient_graph",
":",
"param",
"sample",
":",
"Numpy",
"array",
"with",
"sample",
"input",
":",
"param",
"nb_candidate",
":",
"The",
"number",
"of",
"classes",
"to",
"test",
"against",
"i",
".",
"e",
".",
"deepfool",
"only",
"consider",
"nb_candidate",
"classes",
"when",
"attacking",
"(",
"thus",
"accelerate",
"speed",
")",
".",
"The",
"nb_candidate",
"classes",
"are",
"chosen",
"according",
"to",
"the",
"prediction",
"confidence",
"during",
"implementation",
".",
":",
"param",
"overshoot",
":",
"A",
"termination",
"criterion",
"to",
"prevent",
"vanishing",
"updates",
":",
"param",
"max_iter",
":",
"Maximum",
"number",
"of",
"iteration",
"for",
"DeepFool",
":",
"param",
"clip_min",
":",
"Minimum",
"value",
"for",
"components",
"of",
"the",
"example",
"returned",
":",
"param",
"clip_max",
":",
"Maximum",
"value",
"for",
"components",
"of",
"the",
"example",
"returned",
":",
"return",
":",
"Adversarial",
"examples"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L168-L252
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/deep_fool.py
|
DeepFool.generate
|
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
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):
"""deepfool function for py_func"""
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
|
python
|
def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
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):
"""deepfool function for py_func"""
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
|
[
"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",
")",
":",
"\"\"\"deepfool function for py_func\"\"\"",
"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"
] |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
|
[
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L48-L83
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/deep_fool.py
|
DeepFool.parse_params
|
def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
"""
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for deepfool
:param clip_min: Minimum component value for clipping
:param clip_max: Maximum component value for clipping
"""
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
|
python
|
def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
"""
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for deepfool
:param clip_min: Minimum component value for clipping
:param clip_max: Maximum component value for clipping
"""
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
|
[
"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"
] |
:param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confidence during implementation.
:param overshoot: A termination criterion to prevent vanishing updates
:param max_iter: Maximum number of iteration for deepfool
:param clip_min: Minimum component value for clipping
:param clip_max: Maximum component value for clipping
|
[
":",
"param",
"nb_candidate",
":",
"The",
"number",
"of",
"classes",
"to",
"test",
"against",
"i",
".",
"e",
".",
"deepfool",
"only",
"consider",
"nb_candidate",
"classes",
"when",
"attacking",
"(",
"thus",
"accelerate",
"speed",
")",
".",
"The",
"nb_candidate",
"classes",
"are",
"chosen",
"according",
"to",
"the",
"prediction",
"confidence",
"during",
"implementation",
".",
":",
"param",
"overshoot",
":",
"A",
"termination",
"criterion",
"to",
"prevent",
"vanishing",
"updates",
":",
"param",
"max_iter",
":",
"Maximum",
"number",
"of",
"iteration",
"for",
"deepfool",
":",
"param",
"clip_min",
":",
"Minimum",
"component",
"value",
"for",
"clipping",
":",
"param",
"clip_max",
":",
"Maximum",
"component",
"value",
"for",
"clipping"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L85-L112
|
train
|
tensorflow/cleverhans
|
cleverhans/utils_pytorch.py
|
_py_func_with_gradient
|
def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when stateful is True
:param name: Name of the PyFunction
:param grad: Custom Gradient Function
:return:
"""
# 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)
|
python
|
def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when stateful is True
:param name: Name of the PyFunction
:param grad: Custom Gradient Function
:return:
"""
# 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)
|
[
"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",
")"
] |
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when stateful is True
:param name: Name of the PyFunction
:param grad: Custom Gradient Function
:return:
|
[
"PyFunc",
"defined",
"as",
"given",
"by",
"Tensorflow",
":",
"param",
"func",
":",
"Custom",
"Function",
":",
"param",
"inp",
":",
"Function",
"Inputs",
":",
"param",
"Tout",
":",
"Ouput",
"Type",
"of",
"out",
"Custom",
"Function",
":",
"param",
"stateful",
":",
"Calculate",
"Gradients",
"when",
"stateful",
"is",
"True",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"PyFunction",
":",
"param",
"grad",
":",
"Custom",
"Gradient",
"Function",
":",
"return",
":"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L14-L38
|
train
|
tensorflow/cleverhans
|
cleverhans/utils_pytorch.py
|
convert_pytorch_model_to_tf
|
def convert_pytorch_model_to_tf(model, out_dims=None):
"""
Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
output of the model (tf.Tensor)
"""
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):
"""TODO: write this"""
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):
"""TODO: write this"""
_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):
"""TODO: write this"""
return tf.py_func(_bprop_fn, [op.inputs[0], grads_in],
Tout=[tf.float32])
def tf_model_fn(x_op):
"""TODO: write this"""
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
|
python
|
def convert_pytorch_model_to_tf(model, out_dims=None):
"""
Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
output of the model (tf.Tensor)
"""
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):
"""TODO: write this"""
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):
"""TODO: write this"""
_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):
"""TODO: write this"""
return tf.py_func(_bprop_fn, [op.inputs[0], grads_in],
Tout=[tf.float32])
def tf_model_fn(x_op):
"""TODO: write this"""
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
|
[
"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",
")",
":",
"\"\"\"TODO: write this\"\"\"",
"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",
")",
":",
"\"\"\"TODO: write this\"\"\"",
"_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",
")",
":",
"\"\"\"TODO: write this\"\"\"",
"return",
"tf",
".",
"py_func",
"(",
"_bprop_fn",
",",
"[",
"op",
".",
"inputs",
"[",
"0",
"]",
",",
"grads_in",
"]",
",",
"Tout",
"=",
"[",
"tf",
".",
"float32",
"]",
")",
"def",
"tf_model_fn",
"(",
"x_op",
")",
":",
"\"\"\"TODO: write this\"\"\"",
"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"
] |
Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
output of the model (tf.Tensor)
|
[
"Convert",
"a",
"pytorch",
"model",
"into",
"a",
"tensorflow",
"op",
"that",
"allows",
"backprop",
":",
"param",
"model",
":",
"A",
"pytorch",
"nn",
".",
"Module",
"object",
":",
"param",
"out_dims",
":",
"The",
"number",
"of",
"output",
"dimensions",
"(",
"classes",
")",
"for",
"the",
"model",
":",
"return",
":",
"A",
"model",
"function",
"that",
"maps",
"an",
"input",
"(",
"tf",
".",
"Tensor",
")",
"to",
"the",
"output",
"of",
"the",
"model",
"(",
"tf",
".",
"Tensor",
")"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L41-L94
|
train
|
tensorflow/cleverhans
|
cleverhans/utils_pytorch.py
|
clip_eta
|
def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
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
|
python
|
def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
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
|
[
"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"
] |
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
|
[
"PyTorch",
"implementation",
"of",
"the",
"clip_eta",
"in",
"utils_tf",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L97-L130
|
train
|
tensorflow/cleverhans
|
cleverhans/utils_pytorch.py
|
get_or_guess_labels
|
def get_or_guess_labels(model, x, **kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
:param model: PyTorch model. Do not add a softmax gate to the output.
:param x: Tensor, shape (N, d_1, ...).
:param y: (optional) Tensor, shape (N).
:param y_target: (optional) Tensor, shape (N).
"""
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
|
python
|
def get_or_guess_labels(model, x, **kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
:param model: PyTorch model. Do not add a softmax gate to the output.
:param x: Tensor, shape (N, d_1, ...).
:param y: (optional) Tensor, shape (N).
:param y_target: (optional) Tensor, shape (N).
"""
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
|
[
"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"
] |
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the label.
Otherwise, use the model's prediction as the label and perform an
untargeted attack.
:param model: PyTorch model. Do not add a softmax gate to the output.
:param x: Tensor, shape (N, d_1, ...).
:param y: (optional) Tensor, shape (N).
:param y_target: (optional) Tensor, shape (N).
|
[
"Get",
"the",
"label",
"to",
"use",
"in",
"generating",
"an",
"adversarial",
"example",
"for",
"x",
".",
"The",
"kwargs",
"are",
"fed",
"directly",
"from",
"the",
"kwargs",
"of",
"the",
"attack",
".",
"If",
"y",
"is",
"in",
"kwargs",
"then",
"assume",
"it",
"s",
"an",
"untargeted",
"attack",
"and",
"use",
"that",
"as",
"the",
"label",
".",
"If",
"y_target",
"is",
"in",
"kwargs",
"and",
"is",
"not",
"none",
"then",
"assume",
"it",
"s",
"a",
"targeted",
"attack",
"and",
"use",
"that",
"as",
"the",
"label",
".",
"Otherwise",
"use",
"the",
"model",
"s",
"prediction",
"as",
"the",
"label",
"and",
"perform",
"an",
"untargeted",
"attack",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L132-L156
|
train
|
tensorflow/cleverhans
|
cleverhans/utils_pytorch.py
|
optimize_linear
|
def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constraint region
:param ord: np.inf, 1, or 2. Order of norm constraint.
:returns: Tensor, shape (N, d_1, ...). Optimal perturbation
"""
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
|
python
|
def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constraint region
:param ord: np.inf, 1, or 2. Order of norm constraint.
:returns: Tensor, shape (N, d_1, ...). Optimal perturbation
"""
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
|
[
"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"
] |
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constraint region
:param ord: np.inf, 1, or 2. Order of norm constraint.
:returns: Tensor, shape (N, d_1, ...). Optimal perturbation
|
[
"Solves",
"for",
"the",
"optimal",
"input",
"to",
"a",
"linear",
"function",
"under",
"a",
"norm",
"constraint",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L159-L213
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/elastic_net_method.py
|
ElasticNetMethod.parse_params
|
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):
"""
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param beta: Trades off L2 distortion with L1 distortion: higher
produces examples with lower L1 distortion, at the
cost of higher L2 (and typically Linf) distortion
:param decision_rule: EN or L1. Select final adversarial example from
all successful examples based on the least
elastic-net or L1 distortion criterion.
:param confidence: Confidence of adversarial examples: higher produces
examples with larger l2 distortion, but more
strongly classified as adversarial.
:param batch_size: Number of attacks to run simultaneously.
:param learning_rate: The learning rate for the attack algorithm.
Smaller values produce better results but are
slower to converge.
:param binary_search_steps: The number of times we perform binary
search to find the optimal tradeoff-
constant between norm of the perturbation
and confidence of the classification. Set
'initial_const' to a large value and fix
this param to 1 for speed.
:param max_iterations: The maximum number of iterations. Setting this
to a larger value will produce lower distortion
results. Using only a few iterations requires
a larger learning rate, and will produce larger
distortion results.
:param abort_early: If true, allows early abort when the total
loss starts to increase (greatly speeds up attack,
but hurts performance, particularly on ImageNet)
:param initial_const: The initial tradeoff-constant to use to tune the
relative importance of size of the perturbation
and confidence of classification.
If binary_search_steps is large, the initial
constant is not important. A smaller value of
this constant gives lower distortion results.
For computational efficiency, fix
binary_search_steps to 1 and set this param
to a large value.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# 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
|
python
|
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):
"""
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param beta: Trades off L2 distortion with L1 distortion: higher
produces examples with lower L1 distortion, at the
cost of higher L2 (and typically Linf) distortion
:param decision_rule: EN or L1. Select final adversarial example from
all successful examples based on the least
elastic-net or L1 distortion criterion.
:param confidence: Confidence of adversarial examples: higher produces
examples with larger l2 distortion, but more
strongly classified as adversarial.
:param batch_size: Number of attacks to run simultaneously.
:param learning_rate: The learning rate for the attack algorithm.
Smaller values produce better results but are
slower to converge.
:param binary_search_steps: The number of times we perform binary
search to find the optimal tradeoff-
constant between norm of the perturbation
and confidence of the classification. Set
'initial_const' to a large value and fix
this param to 1 for speed.
:param max_iterations: The maximum number of iterations. Setting this
to a larger value will produce lower distortion
results. Using only a few iterations requires
a larger learning rate, and will produce larger
distortion results.
:param abort_early: If true, allows early abort when the total
loss starts to increase (greatly speeds up attack,
but hurts performance, particularly on ImageNet)
:param initial_const: The initial tradeoff-constant to use to tune the
relative importance of size of the perturbation
and confidence of classification.
If binary_search_steps is large, the initial
constant is not important. A smaller value of
this constant gives lower distortion results.
For computational efficiency, fix
binary_search_steps to 1 and set this param
to a large value.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
"""
# 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
|
[
"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"
] |
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param beta: Trades off L2 distortion with L1 distortion: higher
produces examples with lower L1 distortion, at the
cost of higher L2 (and typically Linf) distortion
:param decision_rule: EN or L1. Select final adversarial example from
all successful examples based on the least
elastic-net or L1 distortion criterion.
:param confidence: Confidence of adversarial examples: higher produces
examples with larger l2 distortion, but more
strongly classified as adversarial.
:param batch_size: Number of attacks to run simultaneously.
:param learning_rate: The learning rate for the attack algorithm.
Smaller values produce better results but are
slower to converge.
:param binary_search_steps: The number of times we perform binary
search to find the optimal tradeoff-
constant between norm of the perturbation
and confidence of the classification. Set
'initial_const' to a large value and fix
this param to 1 for speed.
:param max_iterations: The maximum number of iterations. Setting this
to a larger value will produce lower distortion
results. Using only a few iterations requires
a larger learning rate, and will produce larger
distortion results.
:param abort_early: If true, allows early abort when the total
loss starts to increase (greatly speeds up attack,
but hurts performance, particularly on ImageNet)
:param initial_const: The initial tradeoff-constant to use to tune the
relative importance of size of the perturbation
and confidence of classification.
If binary_search_steps is large, the initial
constant is not important. A smaller value of
this constant gives lower distortion results.
For computational efficiency, fix
binary_search_steps to 1 and set this param
to a large value.
:param clip_min: (optional float) Minimum input component value
:param clip_max: (optional float) Maximum input component value
|
[
":",
"param",
"y",
":",
"(",
"optional",
")",
"A",
"tensor",
"with",
"the",
"true",
"labels",
"for",
"an",
"untargeted",
"attack",
".",
"If",
"None",
"(",
"and",
"y_target",
"is",
"None",
")",
"then",
"use",
"the",
"original",
"labels",
"the",
"classifier",
"assigns",
".",
":",
"param",
"y_target",
":",
"(",
"optional",
")",
"A",
"tensor",
"with",
"the",
"target",
"labels",
"for",
"a",
"targeted",
"attack",
".",
":",
"param",
"beta",
":",
"Trades",
"off",
"L2",
"distortion",
"with",
"L1",
"distortion",
":",
"higher",
"produces",
"examples",
"with",
"lower",
"L1",
"distortion",
"at",
"the",
"cost",
"of",
"higher",
"L2",
"(",
"and",
"typically",
"Linf",
")",
"distortion",
":",
"param",
"decision_rule",
":",
"EN",
"or",
"L1",
".",
"Select",
"final",
"adversarial",
"example",
"from",
"all",
"successful",
"examples",
"based",
"on",
"the",
"least",
"elastic",
"-",
"net",
"or",
"L1",
"distortion",
"criterion",
".",
":",
"param",
"confidence",
":",
"Confidence",
"of",
"adversarial",
"examples",
":",
"higher",
"produces",
"examples",
"with",
"larger",
"l2",
"distortion",
"but",
"more",
"strongly",
"classified",
"as",
"adversarial",
".",
":",
"param",
"batch_size",
":",
"Number",
"of",
"attacks",
"to",
"run",
"simultaneously",
".",
":",
"param",
"learning_rate",
":",
"The",
"learning",
"rate",
"for",
"the",
"attack",
"algorithm",
".",
"Smaller",
"values",
"produce",
"better",
"results",
"but",
"are",
"slower",
"to",
"converge",
".",
":",
"param",
"binary_search_steps",
":",
"The",
"number",
"of",
"times",
"we",
"perform",
"binary",
"search",
"to",
"find",
"the",
"optimal",
"tradeoff",
"-",
"constant",
"between",
"norm",
"of",
"the",
"perturbation",
"and",
"confidence",
"of",
"the",
"classification",
".",
"Set",
"initial_const",
"to",
"a",
"large",
"value",
"and",
"fix",
"this",
"param",
"to",
"1",
"for",
"speed",
".",
":",
"param",
"max_iterations",
":",
"The",
"maximum",
"number",
"of",
"iterations",
".",
"Setting",
"this",
"to",
"a",
"larger",
"value",
"will",
"produce",
"lower",
"distortion",
"results",
".",
"Using",
"only",
"a",
"few",
"iterations",
"requires",
"a",
"larger",
"learning",
"rate",
"and",
"will",
"produce",
"larger",
"distortion",
"results",
".",
":",
"param",
"abort_early",
":",
"If",
"true",
"allows",
"early",
"abort",
"when",
"the",
"total",
"loss",
"starts",
"to",
"increase",
"(",
"greatly",
"speeds",
"up",
"attack",
"but",
"hurts",
"performance",
"particularly",
"on",
"ImageNet",
")",
":",
"param",
"initial_const",
":",
"The",
"initial",
"tradeoff",
"-",
"constant",
"to",
"use",
"to",
"tune",
"the",
"relative",
"importance",
"of",
"size",
"of",
"the",
"perturbation",
"and",
"confidence",
"of",
"classification",
".",
"If",
"binary_search_steps",
"is",
"large",
"the",
"initial",
"constant",
"is",
"not",
"important",
".",
"A",
"smaller",
"value",
"of",
"this",
"constant",
"gives",
"lower",
"distortion",
"results",
".",
"For",
"computational",
"efficiency",
"fix",
"binary_search_steps",
"to",
"1",
"and",
"set",
"this",
"param",
"to",
"a",
"large",
"value",
".",
":",
"param",
"clip_min",
":",
"(",
"optional",
"float",
")",
"Minimum",
"input",
"component",
"value",
":",
"param",
"clip_max",
":",
"(",
"optional",
"float",
")",
"Maximum",
"input",
"component",
"value"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L91-L162
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks/elastic_net_method.py
|
EAD.attack
|
def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
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)
|
python
|
def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
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)
|
[
"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",
")"
] |
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
|
[
"Perform",
"the",
"EAD",
"attack",
"on",
"the",
"given",
"instance",
"for",
"the",
"given",
"targets",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L374-L404
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py
|
print_in_box
|
def print_in_box(text):
"""
Prints `text` surrounded by a box made of *s
"""
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('')
|
python
|
def print_in_box(text):
"""
Prints `text` surrounded by a box made of *s
"""
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('')
|
[
"def",
"print_in_box",
"(",
"text",
")",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'*'",
"*",
"(",
"len",
"(",
"text",
")",
"+",
"6",
")",
")",
"print",
"(",
"'** '",
"+",
"text",
"+",
"' **'",
")",
"print",
"(",
"'*'",
"*",
"(",
"len",
"(",
"text",
")",
"+",
"6",
")",
")",
"print",
"(",
"''",
")"
] |
Prints `text` surrounded by a box made of *s
|
[
"Prints",
"text",
"surrounded",
"by",
"a",
"box",
"made",
"of",
"*",
"s"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L30-L38
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py
|
main
|
def main(args):
"""
Validates the submission.
"""
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])
|
python
|
def main(args):
"""
Validates the submission.
"""
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])
|
[
"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",
"]",
")"
] |
Validates the submission.
|
[
"Validates",
"the",
"submission",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L41-L62
|
train
|
tensorflow/cleverhans
|
scripts/make_confidence_report.py
|
main
|
def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
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)
|
python
|
def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
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)
|
[
"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",
")"
] |
Make a confidence report and save it to disk.
|
[
"Make",
"a",
"confidence",
"report",
"and",
"save",
"it",
"to",
"disk",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report.py#L56-L71
|
train
|
tensorflow/cleverhans
|
scripts/make_confidence_report_spsa.py
|
make_confidence_report_spsa
|
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):
"""
Load a saved model, gather its predictions, and save a confidence report.
This function works by running a single MaxConfidence attack on each example,
using SPSA as the underyling optimizer.
This is not intended to be a strong generic attack.
It is intended to be a test to uncover gradient masking.
:param filepath: path to model to evaluate
:param train_start: index of first training set example to use
:param train_end: index of last training set example to use
:param test_start: index of first test set example to use
:param test_end: index of last test set example to use
:param batch_size: size of evaluation batches
:param which_set: 'train' or 'test'
:param nb_iter: Number of iterations of PGD to run per class
:param spsa_samples: Number of samples for SPSA
"""
# 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)
|
python
|
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):
"""
Load a saved model, gather its predictions, and save a confidence report.
This function works by running a single MaxConfidence attack on each example,
using SPSA as the underyling optimizer.
This is not intended to be a strong generic attack.
It is intended to be a test to uncover gradient masking.
:param filepath: path to model to evaluate
:param train_start: index of first training set example to use
:param train_end: index of last training set example to use
:param test_start: index of first test set example to use
:param test_end: index of last test set example to use
:param batch_size: size of evaluation batches
:param which_set: 'train' or 'test'
:param nb_iter: Number of iterations of PGD to run per class
:param spsa_samples: Number of samples for SPSA
"""
# 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)
|
[
"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",
")"
] |
Load a saved model, gather its predictions, and save a confidence report.
This function works by running a single MaxConfidence attack on each example,
using SPSA as the underyling optimizer.
This is not intended to be a strong generic attack.
It is intended to be a test to uncover gradient masking.
:param filepath: path to model to evaluate
:param train_start: index of first training set example to use
:param train_end: index of last training set example to use
:param test_start: index of first test set example to use
:param test_end: index of last test set example to use
:param batch_size: size of evaluation batches
:param which_set: 'train' or 'test'
:param nb_iter: Number of iterations of PGD to run per class
:param spsa_samples: Number of samples for SPSA
|
[
"Load",
"a",
"saved",
"model",
"gather",
"its",
"predictions",
"and",
"save",
"a",
"confidence",
"report",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_spsa.py#L56-L133
|
train
|
tensorflow/cleverhans
|
scripts/make_confidence_report_spsa.py
|
main
|
def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
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)
|
python
|
def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
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)
|
[
"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",
")"
] |
Make a confidence report and save it to disk.
|
[
"Make",
"a",
"confidence",
"report",
"and",
"save",
"it",
"to",
"disk",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_spsa.py#L135-L150
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/attacks_multigpu.py
|
MadryEtAlMultiGPU.attack
|
def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor with the input image.
:param y_p: Ground truth label or predicted label.
:return: Two lists containing the input and output tensors of each GPU.
"""
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
|
python
|
def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor with the input image.
:param y_p: Ground truth label or predicted label.
:return: Two lists containing the input and output tensors of each GPU.
"""
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
|
[
"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"
] |
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor with the input image.
:param y_p: Ground truth label or predicted label.
:return: Two lists containing the input and output tensors of each GPU.
|
[
"This",
"method",
"creates",
"a",
"symoblic",
"graph",
"of",
"the",
"MadryEtAl",
"attack",
"on",
"multiple",
"GPUs",
".",
"The",
"graph",
"is",
"created",
"on",
"the",
"first",
"n",
"GPUs",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L42-L106
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/attacks_multigpu.py
|
MadryEtAlMultiGPU.generate_np
|
def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, 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']
|
python
|
def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, 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']
|
[
"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'",
"]"
] |
Facilitates testing this attack.
|
[
"Facilitates",
"testing",
"this",
"attack",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L108-L134
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/attacks_multigpu.py
|
MadryEtAlMultiGPU.parse_params
|
def parse_params(self, ngpu=1, **kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl attack.
"""
return_status = super(MadryEtAlMultiGPU, self).parse_params(**kwargs)
self.ngpu = ngpu
return return_status
|
python
|
def parse_params(self, ngpu=1, **kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl attack.
"""
return_status = super(MadryEtAlMultiGPU, self).parse_params(**kwargs)
self.ngpu = ngpu
return return_status
|
[
"def",
"parse_params",
"(",
"self",
",",
"ngpu",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"return_status",
"=",
"super",
"(",
"MadryEtAlMultiGPU",
",",
"self",
")",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"ngpu",
"=",
"ngpu",
"return",
"return_status"
] |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl attack.
|
[
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"applies",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L136-L149
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
accuracy
|
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return: a float with the accuracy value
"""
_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()
|
python
|
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return: a float with the accuracy value
"""
_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()
|
[
"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",
"(",
")"
] |
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return: a float with the accuracy value
|
[
"Compute",
"the",
"accuracy",
"of",
"a",
"TF",
"model",
"on",
"some",
"data",
":",
"param",
"sess",
":",
"TF",
"session",
"to",
"use",
"when",
"training",
"the",
"graph",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
"instance",
":",
"param",
"x",
":",
"numpy",
"array",
"containing",
"input",
"examples",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"x_test",
")",
":",
"param",
"y",
":",
"numpy",
"array",
"containing",
"example",
"labels",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"y_test",
")",
":",
"param",
"batch_size",
":",
"Number",
"of",
"examples",
"to",
"use",
"in",
"a",
"single",
"evaluation",
"batch",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"a",
"reasonable",
"guess",
"and",
"may",
"run",
"out",
"of",
"memory",
".",
"When",
"choosing",
"the",
"batch",
"size",
"keep",
"in",
"mind",
"that",
"the",
"batch",
"will",
"be",
"divided",
"up",
"evenly",
"among",
"available",
"devices",
".",
"If",
"you",
"can",
"fit",
"128",
"examples",
"in",
"memory",
"on",
"one",
"GPU",
"and",
"you",
"have",
"8",
"GPUs",
"you",
"probably",
"want",
"to",
"use",
"a",
"batch",
"size",
"of",
"1024",
"(",
"unless",
"a",
"different",
"batch",
"size",
"runs",
"faster",
"with",
"the",
"ops",
"you",
"are",
"using",
"etc",
".",
")",
":",
"param",
"devices",
":",
"An",
"optional",
"list",
"of",
"string",
"device",
"names",
"to",
"use",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"all",
"visible",
"GPUs",
".",
":",
"param",
"feed",
":",
"An",
"optional",
"dictionary",
"that",
"is",
"appended",
"to",
"the",
"feeding",
"dictionary",
"before",
"the",
"session",
"runs",
".",
"Can",
"be",
"used",
"to",
"feed",
"the",
"learning",
"phase",
"of",
"a",
"Keras",
"model",
"for",
"instance",
".",
":",
"param",
"attack",
":",
"cleverhans",
".",
"attack",
".",
"Attack",
"Optional",
".",
"If",
"no",
"attack",
"specified",
"evaluates",
"the",
"model",
"on",
"clean",
"data",
".",
"If",
"attack",
"is",
"specified",
"evaluates",
"the",
"model",
"on",
"adversarial",
"examples",
"created",
"by",
"the",
"attack",
".",
":",
"param",
"attack_params",
":",
"dictionary",
"If",
"attack",
"is",
"specified",
"this",
"dictionary",
"is",
"passed",
"to",
"attack",
".",
"generate",
"as",
"keyword",
"arguments",
".",
":",
"return",
":",
"a",
"float",
"with",
"the",
"accuracy",
"value"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L18-L60
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
class_and_confidence
|
def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing true labels
(Needed only if using an attack that avoids these labels)
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return:
an ndarray of ints indicating the class assigned to each example
an ndarray of probabilities assigned to the prediction for each example
"""
_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
|
python
|
def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing true labels
(Needed only if using an attack that avoids these labels)
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return:
an ndarray of ints indicating the class assigned to each example
an ndarray of probabilities assigned to the prediction for each example
"""
_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
|
[
"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"
] |
Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing true labels
(Needed only if using an attack that avoids these labels)
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return:
an ndarray of ints indicating the class assigned to each example
an ndarray of probabilities assigned to the prediction for each example
|
[
"Return",
"the",
"model",
"s",
"classification",
"of",
"the",
"input",
"data",
"and",
"the",
"confidence",
"(",
"probability",
")",
"assigned",
"to",
"each",
"example",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"x",
":",
"numpy",
"array",
"containing",
"input",
"examples",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"x_test",
")",
":",
"param",
"y",
":",
"numpy",
"array",
"containing",
"true",
"labels",
"(",
"Needed",
"only",
"if",
"using",
"an",
"attack",
"that",
"avoids",
"these",
"labels",
")",
":",
"param",
"batch_size",
":",
"Number",
"of",
"examples",
"to",
"use",
"in",
"a",
"single",
"evaluation",
"batch",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"a",
"reasonable",
"guess",
"and",
"may",
"run",
"out",
"of",
"memory",
".",
"When",
"choosing",
"the",
"batch",
"size",
"keep",
"in",
"mind",
"that",
"the",
"batch",
"will",
"be",
"divided",
"up",
"evenly",
"among",
"available",
"devices",
".",
"If",
"you",
"can",
"fit",
"128",
"examples",
"in",
"memory",
"on",
"one",
"GPU",
"and",
"you",
"have",
"8",
"GPUs",
"you",
"probably",
"want",
"to",
"use",
"a",
"batch",
"size",
"of",
"1024",
"(",
"unless",
"a",
"different",
"batch",
"size",
"runs",
"faster",
"with",
"the",
"ops",
"you",
"are",
"using",
"etc",
".",
")",
":",
"param",
"devices",
":",
"An",
"optional",
"list",
"of",
"string",
"device",
"names",
"to",
"use",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"all",
"visible",
"GPUs",
".",
":",
"param",
"feed",
":",
"An",
"optional",
"dictionary",
"that",
"is",
"appended",
"to",
"the",
"feeding",
"dictionary",
"before",
"the",
"session",
"runs",
".",
"Can",
"be",
"used",
"to",
"feed",
"the",
"learning",
"phase",
"of",
"a",
"Keras",
"model",
"for",
"instance",
".",
":",
"param",
"attack",
":",
"cleverhans",
".",
"attack",
".",
"Attack",
"Optional",
".",
"If",
"no",
"attack",
"specified",
"evaluates",
"the",
"model",
"on",
"clean",
"data",
".",
"If",
"attack",
"is",
"specified",
"evaluates",
"the",
"model",
"on",
"adversarial",
"examples",
"created",
"by",
"the",
"attack",
".",
":",
"param",
"attack_params",
":",
"dictionary",
"If",
"attack",
"is",
"specified",
"this",
"dictionary",
"is",
"passed",
"to",
"attack",
".",
"generate",
"as",
"keyword",
"arguments",
".",
":",
"return",
":",
"an",
"ndarray",
"of",
"ints",
"indicating",
"the",
"class",
"assigned",
"to",
"each",
"example",
"an",
"ndarray",
"of",
"probabilities",
"assigned",
"to",
"the",
"prediction",
"for",
"each",
"example"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L63-L126
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
correctness_and_confidence
|
def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return:
an ndarray of bools indicating whether each example is correct
an ndarray of probabilities assigned to the prediction for each example
"""
_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
|
python
|
def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return:
an ndarray of bools indicating whether each example is correct
an ndarray of probabilities assigned to the prediction for each example
"""
_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
|
[
"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"
] |
Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param attack: cleverhans.attack.Attack
Optional. If no attack specified, evaluates the model on clean data.
If attack is specified, evaluates the model on adversarial examples
created by the attack.
:param attack_params: dictionary
If attack is specified, this dictionary is passed to attack.generate
as keyword arguments.
:return:
an ndarray of bools indicating whether each example is correct
an ndarray of probabilities assigned to the prediction for each example
|
[
"Report",
"whether",
"the",
"model",
"is",
"correct",
"and",
"its",
"confidence",
"on",
"each",
"example",
"in",
"a",
"dataset",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"x",
":",
"numpy",
"array",
"containing",
"input",
"examples",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"x_test",
")",
":",
"param",
"y",
":",
"numpy",
"array",
"containing",
"example",
"labels",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"y_test",
")",
":",
"param",
"batch_size",
":",
"Number",
"of",
"examples",
"to",
"use",
"in",
"a",
"single",
"evaluation",
"batch",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"a",
"reasonable",
"guess",
"and",
"may",
"run",
"out",
"of",
"memory",
".",
"When",
"choosing",
"the",
"batch",
"size",
"keep",
"in",
"mind",
"that",
"the",
"batch",
"will",
"be",
"divided",
"up",
"evenly",
"among",
"available",
"devices",
".",
"If",
"you",
"can",
"fit",
"128",
"examples",
"in",
"memory",
"on",
"one",
"GPU",
"and",
"you",
"have",
"8",
"GPUs",
"you",
"probably",
"want",
"to",
"use",
"a",
"batch",
"size",
"of",
"1024",
"(",
"unless",
"a",
"different",
"batch",
"size",
"runs",
"faster",
"with",
"the",
"ops",
"you",
"are",
"using",
"etc",
".",
")",
":",
"param",
"devices",
":",
"An",
"optional",
"list",
"of",
"string",
"device",
"names",
"to",
"use",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"all",
"visible",
"GPUs",
".",
":",
"param",
"feed",
":",
"An",
"optional",
"dictionary",
"that",
"is",
"appended",
"to",
"the",
"feeding",
"dictionary",
"before",
"the",
"session",
"runs",
".",
"Can",
"be",
"used",
"to",
"feed",
"the",
"learning",
"phase",
"of",
"a",
"Keras",
"model",
"for",
"instance",
".",
":",
"param",
"attack",
":",
"cleverhans",
".",
"attack",
".",
"Attack",
"Optional",
".",
"If",
"no",
"attack",
"specified",
"evaluates",
"the",
"model",
"on",
"clean",
"data",
".",
"If",
"attack",
"is",
"specified",
"evaluates",
"the",
"model",
"on",
"adversarial",
"examples",
"created",
"by",
"the",
"attack",
".",
":",
"param",
"attack_params",
":",
"dictionary",
"If",
"attack",
"is",
"specified",
"this",
"dictionary",
"is",
"passed",
"to",
"attack",
".",
"generate",
"as",
"keyword",
"arguments",
".",
":",
"return",
":",
"an",
"ndarray",
"of",
"bools",
"indicating",
"whether",
"each",
"example",
"is",
"correct",
"an",
"ndarray",
"of",
"probabilities",
"assigned",
"to",
"the",
"prediction",
"for",
"each",
"example"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L129-L188
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
run_attack
|
def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param attack: cleverhans.attack.Attack
:param attack_params: dictionary
passed to attack.generate as keyword arguments.
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param pass_y: bool. If true pass 'y' to `attack.generate`
:return:
an ndarray of bools indicating whether each example is correct
an ndarray of probabilities assigned to the prediction for each example
"""
_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
|
python
|
def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param attack: cleverhans.attack.Attack
:param attack_params: dictionary
passed to attack.generate as keyword arguments.
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param pass_y: bool. If true pass 'y' to `attack.generate`
:return:
an ndarray of bools indicating whether each example is correct
an ndarray of probabilities assigned to the prediction for each example
"""
_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
|
[
"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"
] |
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param attack: cleverhans.attack.Attack
:param attack_params: dictionary
passed to attack.generate as keyword arguments.
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: An optional list of string device names to use.
If not specified, this function will use all visible GPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param pass_y: bool. If true pass 'y' to `attack.generate`
:return:
an ndarray of bools indicating whether each example is correct
an ndarray of probabilities assigned to the prediction for each example
|
[
"Run",
"attack",
"on",
"every",
"example",
"in",
"a",
"dataset",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"x",
":",
"numpy",
"array",
"containing",
"input",
"examples",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"x_test",
")",
":",
"param",
"y",
":",
"numpy",
"array",
"containing",
"example",
"labels",
"(",
"e",
".",
"g",
".",
"MNIST",
"()",
".",
"y_test",
")",
":",
"param",
"attack",
":",
"cleverhans",
".",
"attack",
".",
"Attack",
":",
"param",
"attack_params",
":",
"dictionary",
"passed",
"to",
"attack",
".",
"generate",
"as",
"keyword",
"arguments",
".",
":",
"param",
"batch_size",
":",
"Number",
"of",
"examples",
"to",
"use",
"in",
"a",
"single",
"evaluation",
"batch",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"a",
"reasonable",
"guess",
"and",
"may",
"run",
"out",
"of",
"memory",
".",
"When",
"choosing",
"the",
"batch",
"size",
"keep",
"in",
"mind",
"that",
"the",
"batch",
"will",
"be",
"divided",
"up",
"evenly",
"among",
"available",
"devices",
".",
"If",
"you",
"can",
"fit",
"128",
"examples",
"in",
"memory",
"on",
"one",
"GPU",
"and",
"you",
"have",
"8",
"GPUs",
"you",
"probably",
"want",
"to",
"use",
"a",
"batch",
"size",
"of",
"1024",
"(",
"unless",
"a",
"different",
"batch",
"size",
"runs",
"faster",
"with",
"the",
"ops",
"you",
"are",
"using",
"etc",
".",
")",
":",
"param",
"devices",
":",
"An",
"optional",
"list",
"of",
"string",
"device",
"names",
"to",
"use",
".",
"If",
"not",
"specified",
"this",
"function",
"will",
"use",
"all",
"visible",
"GPUs",
".",
":",
"param",
"feed",
":",
"An",
"optional",
"dictionary",
"that",
"is",
"appended",
"to",
"the",
"feeding",
"dictionary",
"before",
"the",
"session",
"runs",
".",
"Can",
"be",
"used",
"to",
"feed",
"the",
"learning",
"phase",
"of",
"a",
"Keras",
"model",
"for",
"instance",
".",
":",
"param",
"pass_y",
":",
"bool",
".",
"If",
"true",
"pass",
"y",
"to",
"attack",
".",
"generate",
":",
"return",
":",
"an",
"ndarray",
"of",
"bools",
"indicating",
"whether",
"each",
"example",
"is",
"correct",
"an",
"ndarray",
"of",
"probabilities",
"assigned",
"to",
"the",
"prediction",
"for",
"each",
"example"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L191-L228
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
batch_eval_multi_worker
|
def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
"""
Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker
device handling one batch of data. If you need multiple devices per
batch, use `batch_eval`.
The tensorflow graph for multiple workers is large, so the first few
runs of the graph will be very slow. If you expect to run the graph
few times (few calls to `batch_eval_multi_worker` that each run few
batches) the startup cost might dominate the runtime, and it might be
preferable to use the single worker `batch_eval` just because its
startup cost will be lower.
:param sess: tensorflow Session
:param graph_factory: callable
When called, returns (tf_inputs, tf_outputs) where:
tf_inputs is a list of placeholders to feed from the dataset
tf_outputs is a list of tf tensors to calculate
Example: tf_inputs is [x, y] placeholders, tf_outputs is [accuracy].
This factory must make new tensors when called, rather than, e.g.
handing out a reference to existing tensors.
This factory must make exactly equivalent expressions every time
it is called, otherwise the results of `batch_eval` will vary
depending on how work is distributed to devices.
This factory must respect "with tf.device()" context managers
that are active when it is called, otherwise work will not be
distributed to devices correctly.
:param numpy_inputs:
A list of numpy arrays defining the dataset to be evaluated.
The list should have the same length as tf_inputs.
Each array should have the same number of examples (shape[0]).
Example: numpy_inputs is [MNIST().x_test, MNIST().y_test]
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: List of devices to run on. If unspecified, uses all
available GPUs if any GPUS are available, otherwise uses CPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:returns: List of numpy arrays corresponding to the outputs produced by
the graph_factory
"""
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):
"""Pads an array with replicated examples to have `excess` more entries"""
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
|
python
|
def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
"""
Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker
device handling one batch of data. If you need multiple devices per
batch, use `batch_eval`.
The tensorflow graph for multiple workers is large, so the first few
runs of the graph will be very slow. If you expect to run the graph
few times (few calls to `batch_eval_multi_worker` that each run few
batches) the startup cost might dominate the runtime, and it might be
preferable to use the single worker `batch_eval` just because its
startup cost will be lower.
:param sess: tensorflow Session
:param graph_factory: callable
When called, returns (tf_inputs, tf_outputs) where:
tf_inputs is a list of placeholders to feed from the dataset
tf_outputs is a list of tf tensors to calculate
Example: tf_inputs is [x, y] placeholders, tf_outputs is [accuracy].
This factory must make new tensors when called, rather than, e.g.
handing out a reference to existing tensors.
This factory must make exactly equivalent expressions every time
it is called, otherwise the results of `batch_eval` will vary
depending on how work is distributed to devices.
This factory must respect "with tf.device()" context managers
that are active when it is called, otherwise work will not be
distributed to devices correctly.
:param numpy_inputs:
A list of numpy arrays defining the dataset to be evaluated.
The list should have the same length as tf_inputs.
Each array should have the same number of examples (shape[0]).
Example: numpy_inputs is [MNIST().x_test, MNIST().y_test]
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: List of devices to run on. If unspecified, uses all
available GPUs if any GPUS are available, otherwise uses CPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:returns: List of numpy arrays corresponding to the outputs produced by
the graph_factory
"""
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):
"""Pads an array with replicated examples to have `excess` more entries"""
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
|
[
"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",
")",
":",
"\"\"\"Pads an array with replicated examples to have `excess` more entries\"\"\"",
"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"
] |
Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker
device handling one batch of data. If you need multiple devices per
batch, use `batch_eval`.
The tensorflow graph for multiple workers is large, so the first few
runs of the graph will be very slow. If you expect to run the graph
few times (few calls to `batch_eval_multi_worker` that each run few
batches) the startup cost might dominate the runtime, and it might be
preferable to use the single worker `batch_eval` just because its
startup cost will be lower.
:param sess: tensorflow Session
:param graph_factory: callable
When called, returns (tf_inputs, tf_outputs) where:
tf_inputs is a list of placeholders to feed from the dataset
tf_outputs is a list of tf tensors to calculate
Example: tf_inputs is [x, y] placeholders, tf_outputs is [accuracy].
This factory must make new tensors when called, rather than, e.g.
handing out a reference to existing tensors.
This factory must make exactly equivalent expressions every time
it is called, otherwise the results of `batch_eval` will vary
depending on how work is distributed to devices.
This factory must respect "with tf.device()" context managers
that are active when it is called, otherwise work will not be
distributed to devices correctly.
:param numpy_inputs:
A list of numpy arrays defining the dataset to be evaluated.
The list should have the same length as tf_inputs.
Each array should have the same number of examples (shape[0]).
Example: numpy_inputs is [MNIST().x_test, MNIST().y_test]
:param batch_size: Number of examples to use in a single evaluation batch.
If not specified, this function will use a reasonable guess and
may run out of memory.
When choosing the batch size, keep in mind that the batch will
be divided up evenly among available devices. If you can fit 128
examples in memory on one GPU and you have 8 GPUs, you probably
want to use a batch size of 1024 (unless a different batch size
runs faster with the ops you are using, etc.)
:param devices: List of devices to run on. If unspecified, uses all
available GPUs if any GPUS are available, otherwise uses CPUs.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:returns: List of numpy arrays corresponding to the outputs produced by
the graph_factory
|
[
"Generic",
"computation",
"engine",
"for",
"evaluating",
"an",
"expression",
"across",
"a",
"whole",
"dataset",
"divided",
"into",
"batches",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L231-L411
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
batch_eval
|
def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops on specific devices
to implement model parallelism.
Most users probably prefer `batch_eval_multi_worker` which maps
a single-device expression to multiple devices in order to evaluate
faster by parallelizing across data.
:param sess: tf Session to use
:param tf_inputs: list of tf Placeholders to feed from the dataset
:param tf_outputs: list of tf tensors to calculate
:param numpy_inputs: list of numpy arrays defining the dataset
:param batch_size: int, batch size to use for evaluation
If not specified, this function will try to guess the batch size,
but might get an out of memory error or run the model with an
unsupported batch size, etc.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param args: dict or argparse `Namespace` object.
Deprecated and included only for backwards compatibility.
Should contain `batch_size`
"""
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
|
python
|
def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops on specific devices
to implement model parallelism.
Most users probably prefer `batch_eval_multi_worker` which maps
a single-device expression to multiple devices in order to evaluate
faster by parallelizing across data.
:param sess: tf Session to use
:param tf_inputs: list of tf Placeholders to feed from the dataset
:param tf_outputs: list of tf tensors to calculate
:param numpy_inputs: list of numpy arrays defining the dataset
:param batch_size: int, batch size to use for evaluation
If not specified, this function will try to guess the batch size,
but might get an out of memory error or run the model with an
unsupported batch size, etc.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param args: dict or argparse `Namespace` object.
Deprecated and included only for backwards compatibility.
Should contain `batch_size`
"""
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
|
[
"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"
] |
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops on specific devices
to implement model parallelism.
Most users probably prefer `batch_eval_multi_worker` which maps
a single-device expression to multiple devices in order to evaluate
faster by parallelizing across data.
:param sess: tf Session to use
:param tf_inputs: list of tf Placeholders to feed from the dataset
:param tf_outputs: list of tf tensors to calculate
:param numpy_inputs: list of numpy arrays defining the dataset
:param batch_size: int, batch size to use for evaluation
If not specified, this function will try to guess the batch size,
but might get an out of memory error or run the model with an
unsupported batch size, etc.
:param feed: An optional dictionary that is appended to the feeding
dictionary before the session runs. Can be used to feed
the learning phase of a Keras model for instance.
:param args: dict or argparse `Namespace` object.
Deprecated and included only for backwards compatibility.
Should contain `batch_size`
|
[
"A",
"helper",
"function",
"that",
"computes",
"a",
"tensor",
"on",
"numpy",
"inputs",
"by",
"batches",
".",
"This",
"version",
"uses",
"exactly",
"the",
"tensorflow",
"graph",
"constructed",
"by",
"the",
"caller",
"so",
"the",
"caller",
"can",
"place",
"specific",
"ops",
"on",
"specific",
"devices",
"to",
"implement",
"model",
"parallelism",
".",
"Most",
"users",
"probably",
"prefer",
"batch_eval_multi_worker",
"which",
"maps",
"a",
"single",
"-",
"device",
"expression",
"to",
"multiple",
"devices",
"in",
"order",
"to",
"evaluate",
"faster",
"by",
"parallelizing",
"across",
"data",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L414-L488
|
train
|
tensorflow/cleverhans
|
cleverhans/evaluation.py
|
_check_y
|
def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
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)))
|
python
|
def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
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)))
|
[
"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",
")",
")",
")"
] |
Makes sure a `y` argument is a vliad numpy dataset.
|
[
"Makes",
"sure",
"a",
"y",
"argument",
"is",
"a",
"vliad",
"numpy",
"dataset",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L726-L732
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py
|
load_images
|
def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be less than batch_size, in this case only
first few images of the result are elements of the minibatch.
images: array with all images from this batch
"""
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
|
python
|
def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be less than batch_size, in this case only
first few images of the result are elements of the minibatch.
images: array with all images from this batch
"""
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
|
[
"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.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be less than batch_size, in this case only
first few images of the result are elements of the minibatch.
images: array with all images from this batch
|
[
"Read",
"png",
"images",
"from",
"input",
"directory",
"in",
"batches",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L40-L68
|
train
|
tensorflow/cleverhans
|
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py
|
main
|
def main(_):
"""Run the sample attack"""
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)
|
python
|
def main(_):
"""Run the sample attack"""
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)
|
[
"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
|
[
"Run",
"the",
"sample",
"attack"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L86-L90
|
train
|
tensorflow/cleverhans
|
examples/multigpu_advtrain/utils.py
|
preprocess_batch
|
def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed input.
"""
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
|
python
|
def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed input.
"""
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
|
[
"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"
] |
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed input.
|
[
"Creates",
"a",
"preprocessing",
"graph",
"for",
"a",
"batch",
"given",
"a",
"function",
"that",
"processes",
"a",
"single",
"image",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/utils.py#L5-L25
|
train
|
tensorflow/cleverhans
|
cleverhans/model.py
|
Model.get_logits
|
def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
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`")
|
python
|
def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
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`")
|
[
"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`\"",
")"
] |
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
|
[
":",
"param",
"x",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"network",
"input",
":",
"return",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"output",
"logits",
"(",
"i",
".",
"e",
".",
"the",
"values",
"fed",
"as",
"inputs",
"to",
"the",
"softmax",
"layer",
")",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L59-L70
|
train
|
tensorflow/cleverhans
|
cleverhans/model.py
|
Model.get_predicted_class
|
def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1)
|
python
|
def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1)
|
[
"def",
"get_predicted_class",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tf",
".",
"argmax",
"(",
"self",
".",
"get_logits",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
",",
"axis",
"=",
"1",
")"
] |
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
|
[
":",
"param",
"x",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"network",
"input",
":",
"return",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"predicted",
"label"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L72-L77
|
train
|
tensorflow/cleverhans
|
cleverhans/model.py
|
Model.get_probs
|
def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
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.')
|
python
|
def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
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.')
|
[
"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.'",
")"
] |
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
|
[
":",
"param",
"x",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"network",
"input",
":",
"return",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"output",
"probabilities",
"(",
"i",
".",
"e",
".",
"the",
"output",
"values",
"produced",
"by",
"the",
"softmax",
"layer",
")",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L79-L100
|
train
|
tensorflow/cleverhans
|
cleverhans/model.py
|
Model.get_params
|
def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
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
|
python
|
def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
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
|
[
"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"
] |
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
|
[
"Provides",
"access",
"to",
"the",
"model",
"s",
"parameters",
".",
":",
"return",
":",
"A",
"list",
"of",
"all",
"Variables",
"defining",
"the",
"model",
"parameters",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L111-L150
|
train
|
tensorflow/cleverhans
|
cleverhans/model.py
|
Model.make_params
|
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 their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self, "_dummy_input"):
return
self._dummy_input = self.make_input_placeholder()
self.fprop(self._dummy_input)
|
python
|
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 their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self, "_dummy_input"):
return
self._dummy_input = self.make_input_placeholder()
self.fprop(self._dummy_input)
|
[
"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",
")"
] |
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 their params to be
created can set `needs_dummy_fprop=True` in the constructor.
|
[
"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",
"their",
"params",
"to",
"be",
"created",
"can",
"set",
"needs_dummy_fprop",
"=",
"True",
"in",
"the",
"constructor",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L152-L164
|
train
|
tensorflow/cleverhans
|
cleverhans/model.py
|
Model.get_layer
|
def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
"""
return self.fprop(x, **kwargs)[layer]
|
python
|
def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
"""
return self.fprop(x, **kwargs)[layer]
|
[
"def",
"get_layer",
"(",
"self",
",",
"x",
",",
"layer",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"[",
"layer",
"]"
] |
Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
|
[
"Return",
"a",
"layer",
"output",
".",
":",
"param",
"x",
":",
"tensor",
"the",
"input",
"to",
"the",
"network",
".",
":",
"param",
"layer",
":",
"str",
"the",
"name",
"of",
"the",
"layer",
"to",
"compute",
".",
":",
"param",
"**",
"kwargs",
":",
"dict",
"extra",
"optional",
"params",
"to",
"pass",
"to",
"self",
".",
"fprop",
".",
":",
"return",
":",
"the",
"content",
"of",
"layer",
"layer"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L170-L177
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
plot_reliability_diagram
|
def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the diagram
:return:
"""
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')
|
python
|
def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the diagram
:return:
"""
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')
|
[
"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'",
")"
] |
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the diagram
:return:
|
[
"Takes",
"in",
"confidence",
"values",
"for",
"predictions",
"and",
"correct",
"labels",
"for",
"the",
"data",
"plots",
"a",
"reliability",
"diagram",
".",
":",
"param",
"confidence",
":",
"nb_samples",
"x",
"nb_classes",
"(",
"e",
".",
"g",
".",
"output",
"of",
"softmax",
")",
":",
"param",
"labels",
":",
"vector",
"of",
"nb_samples",
":",
"param",
"filepath",
":",
"where",
"to",
"save",
"the",
"diagram",
":",
"return",
":"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L266-L333
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.init_lsh
|
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
# 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
|
python
|
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
# 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
|
[
"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"
] |
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
|
[
"Initializes",
"locality",
"-",
"sensitive",
"hashing",
"with",
"FALCONN",
"to",
"find",
"nearest",
"neighbors",
"in",
"training",
"data",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L88-L132
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.find_train_knns
|
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 the training data.
"""
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
|
python
|
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 the training data.
"""
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
|
[
"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"
] |
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
|
[
"Given",
"a",
"data_activation",
"dictionary",
"that",
"contains",
"a",
"np",
"array",
"with",
"activations",
"for",
"each",
"layer",
"find",
"the",
"knns",
"in",
"the",
"training",
"data",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L134-L168
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.nonconformity
|
def nonconformity(self, knns_labels):
"""
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label.
"""
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
|
python
|
def nonconformity(self, knns_labels):
"""
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label.
"""
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
|
[
"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"
] |
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label.
|
[
"Given",
"an",
"dictionary",
"of",
"nb_data",
"x",
"nb_classes",
"dimension",
"compute",
"the",
"nonconformity",
"of",
"each",
"candidate",
"label",
"for",
"each",
"data",
"point",
":",
"i",
".",
"e",
".",
"the",
"number",
"of",
"knns",
"whose",
"label",
"is",
"different",
"from",
"the",
"candidate",
"label",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L170-L190
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.preds_conf_cred
|
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, confidence and credibility.
"""
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
|
python
|
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, confidence and credibility.
"""
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
|
[
"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"
] |
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility.
|
[
"Given",
"an",
"array",
"of",
"nb_data",
"x",
"nb_classes",
"dimensions",
"use",
"conformal",
"prediction",
"to",
"compute",
"the",
"DkNN",
"s",
"prediction",
"confidence",
"and",
"credibility",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L192-L214
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.fprop_np
|
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_labels)
_, _, creds = self.preds_conf_cred(knns_not_in_class)
return creds
|
python
|
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_labels)
_, _, creds = self.preds_conf_cred(knns_not_in_class)
return creds
|
[
"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"
] |
Performs a forward pass through the DkNN on an numpy array of data.
|
[
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"DkNN",
"on",
"an",
"numpy",
"array",
"of",
"data",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L216-L227
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.fprop
|
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}
|
python
|
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}
|
[
"def",
"fprop",
"(",
"self",
",",
"x",
")",
":",
"logits",
"=",
"tf",
".",
"py_func",
"(",
"self",
".",
"fprop_np",
",",
"[",
"x",
"]",
",",
"tf",
".",
"float32",
")",
"return",
"{",
"self",
".",
"O_LOGITS",
":",
"logits",
"}"
] |
Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method.
|
[
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"DkNN",
"on",
"a",
"TF",
"tensor",
"by",
"wrapping",
"the",
"fprop_np",
"method",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L229-L235
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
|
DkNNModel.calibrate
|
def calibrate(self, cali_data, cali_labels):
"""
Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration 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.")
|
python
|
def calibrate(self, cali_data, cali_labels):
"""
Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration 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.")
|
[
"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.\"",
")"
] |
Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration labels.
|
[
"Runs",
"the",
"DkNN",
"on",
"holdout",
"data",
"to",
"calibrate",
"the",
"credibility",
"metric",
".",
":",
"param",
"cali_data",
":",
"np",
"array",
"of",
"calibration",
"data",
".",
":",
"param",
"cali_labels",
":",
"np",
"vector",
"of",
"calibration",
"labels",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L237-L263
|
train
|
tensorflow/cleverhans
|
cleverhans_tutorials/mnist_tutorial_pytorch.py
|
mnist_tutorial
|
def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
"""
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object
"""
# 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
|
python
|
def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
"""
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object
"""
# 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
|
[
"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"
] |
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object
|
[
"MNIST",
"cleverhans",
"tutorial",
":",
"param",
"nb_epochs",
":",
"number",
"of",
"epochs",
"to",
"train",
"model",
":",
"param",
"batch_size",
":",
"size",
"of",
"training",
"batches",
":",
"param",
"learning_rate",
":",
"learning",
"rate",
"for",
"training",
":",
"return",
":",
"an",
"AccuracyReport",
"object"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_pytorch.py#L68-L170
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks_tf.py
|
apply_perturbations
|
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:param increase: boolean; true if we are increasing pixels, false otherwise
:param theta: delta for each feature adjustment
:param clip_min: mininum value for a feature in our sample
:param clip_max: maximum value for a feature in our sample
: return: a perturbed input feature matrix for a target class
"""
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
|
python
|
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:param increase: boolean; true if we are increasing pixels, false otherwise
:param theta: delta for each feature adjustment
:param clip_min: mininum value for a feature in our sample
:param clip_max: maximum value for a feature in our sample
: return: a perturbed input feature matrix for a target class
"""
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
|
[
"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"
] |
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:param increase: boolean; true if we are increasing pixels, false otherwise
:param theta: delta for each feature adjustment
:param clip_min: mininum value for a feature in our sample
:param clip_max: maximum value for a feature in our sample
: return: a perturbed input feature matrix for a target class
|
[
"TensorFlow",
"implementation",
"for",
"apply",
"perturbations",
"to",
"input",
"features",
"based",
"on",
"salency",
"maps",
":",
"param",
"i",
":",
"index",
"of",
"first",
"selected",
"feature",
":",
"param",
"j",
":",
"index",
"of",
"second",
"selected",
"feature",
":",
"param",
"X",
":",
"a",
"matrix",
"containing",
"our",
"input",
"features",
"for",
"our",
"sample",
":",
"param",
"increase",
":",
"boolean",
";",
"true",
"if",
"we",
"are",
"increasing",
"pixels",
"false",
"otherwise",
":",
"param",
"theta",
":",
"delta",
"for",
"each",
"feature",
"adjustment",
":",
"param",
"clip_min",
":",
"mininum",
"value",
"for",
"a",
"feature",
"in",
"our",
"sample",
":",
"param",
"clip_max",
":",
"maximum",
"value",
"for",
"a",
"feature",
"in",
"our",
"sample",
":",
"return",
":",
"a",
"perturbed",
"input",
"feature",
"matrix",
"for",
"a",
"target",
"class"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L55-L79
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks_tf.py
|
saliency_map
|
def saliency_map(grads_target, grads_other, search_domain, increase):
"""
TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
derivatives over all non-target classes at that index
:param search_domain: the set of input indices that we are considering
:param increase: boolean; true if we are increasing pixels, false otherwise
:return: (i, j, search_domain) the two input indices selected and the
updated search domain
"""
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
|
python
|
def saliency_map(grads_target, grads_other, search_domain, increase):
"""
TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
derivatives over all non-target classes at that index
:param search_domain: the set of input indices that we are considering
:param increase: boolean; true if we are increasing pixels, false otherwise
:return: (i, j, search_domain) the two input indices selected and the
updated search domain
"""
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
|
[
"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"
] |
TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
derivatives over all non-target classes at that index
:param search_domain: the set of input indices that we are considering
:param increase: boolean; true if we are increasing pixels, false otherwise
:return: (i, j, search_domain) the two input indices selected and the
updated search domain
|
[
"TensorFlow",
"implementation",
"for",
"computing",
"saliency",
"maps",
":",
"param",
"grads_target",
":",
"a",
"matrix",
"containing",
"forward",
"derivatives",
"for",
"the",
"target",
"class",
":",
"param",
"grads_other",
":",
"a",
"matrix",
"where",
"every",
"element",
"is",
"the",
"sum",
"of",
"forward",
"derivatives",
"over",
"all",
"non",
"-",
"target",
"classes",
"at",
"that",
"index",
":",
"param",
"search_domain",
":",
"the",
"set",
"of",
"input",
"indices",
"that",
"we",
"are",
"considering",
":",
"param",
"increase",
":",
"boolean",
";",
"true",
"if",
"we",
"are",
"increasing",
"pixels",
"false",
"otherwise",
":",
"return",
":",
"(",
"i",
"j",
"search_domain",
")",
"the",
"two",
"input",
"indices",
"selected",
"and",
"the",
"updated",
"search",
"domain"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L82-L130
|
train
|
tensorflow/cleverhans
|
cleverhans/attacks_tf.py
|
jacobian
|
def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
"""
TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy array with sample input
:param nb_features: the number of features in the input
:return: matrix of forward derivatives flattened into vectors
"""
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
|
python
|
def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
"""
TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy array with sample input
:param nb_features: the number of features in the input
:return: matrix of forward derivatives flattened into vectors
"""
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
|
[
"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"
] |
TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy array with sample input
:param nb_features: the number of features in the input
:return: matrix of forward derivatives flattened into vectors
|
[
"TensorFlow",
"implementation",
"of",
"the",
"foward",
"derivative",
"/",
"Jacobian",
":",
"param",
"x",
":",
"the",
"input",
"placeholder",
":",
"param",
"grads",
":",
"the",
"list",
"of",
"TF",
"gradients",
"returned",
"by",
"jacobian_graph",
"()",
":",
"param",
"target",
":",
"the",
"target",
"misclassification",
"class",
":",
"param",
"X",
":",
"numpy",
"array",
"with",
"sample",
"input",
":",
"param",
"nb_features",
":",
"the",
"number",
"of",
"features",
"in",
"the",
"input",
":",
"return",
":",
"matrix",
"of",
"forward",
"derivatives",
"flattened",
"into",
"vectors"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L133-L164
|
train
|
tensorflow/cleverhans
|
cleverhans/future/torch/attacks/projected_gradient_descent.py
|
projected_gradient_descent
|
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):
"""
This class implements either the Basic Iterative Method
(Kurakin et al. 2016) when rand_init is set to 0. or the
Madry et al. (2017) method when rand_minmax is larger than 0.
Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf
Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor.
:param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.
:param eps_iter: step size for each attack iteration
:param nb_iter: Number of attack iterations.
:param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.
:param clip_min: (optional) float. Minimum float value for adversarial example components.
:param clip_max: (optional) float. Maximum float value for adversarial example components.
:param y: (optional) Tensor with true labels. If targeted is true, then provide the
target label. Otherwise, only provide this parameter if you'd like to use true
labels when crafting adversarial samples. Otherwise, model predictions are used
as labels to avoid the "label leaking" effect (explained in this paper:
https://arxiv.org/abs/1611.01236). Default is None.
:param targeted: (optional) bool. Is the attack targeted or untargeted?
Untargeted, the default, will try to make the label incorrect.
Targeted will instead try to move in the direction of being more like y.
:param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /
memory or for unit tests that intentionally pass strange input)
:return: a tensor for the adversarial example
"""
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
|
python
|
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):
"""
This class implements either the Basic Iterative Method
(Kurakin et al. 2016) when rand_init is set to 0. or the
Madry et al. (2017) method when rand_minmax is larger than 0.
Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf
Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor.
:param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.
:param eps_iter: step size for each attack iteration
:param nb_iter: Number of attack iterations.
:param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.
:param clip_min: (optional) float. Minimum float value for adversarial example components.
:param clip_max: (optional) float. Maximum float value for adversarial example components.
:param y: (optional) Tensor with true labels. If targeted is true, then provide the
target label. Otherwise, only provide this parameter if you'd like to use true
labels when crafting adversarial samples. Otherwise, model predictions are used
as labels to avoid the "label leaking" effect (explained in this paper:
https://arxiv.org/abs/1611.01236). Default is None.
:param targeted: (optional) bool. Is the attack targeted or untargeted?
Untargeted, the default, will try to make the label incorrect.
Targeted will instead try to move in the direction of being more like y.
:param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /
memory or for unit tests that intentionally pass strange input)
:return: a tensor for the adversarial example
"""
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
|
[
"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"
] |
This class implements either the Basic Iterative Method
(Kurakin et al. 2016) when rand_init is set to 0. or the
Madry et al. (2017) method when rand_minmax is larger than 0.
Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf
Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor.
:param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.
:param eps_iter: step size for each attack iteration
:param nb_iter: Number of attack iterations.
:param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.
:param clip_min: (optional) float. Minimum float value for adversarial example components.
:param clip_max: (optional) float. Maximum float value for adversarial example components.
:param y: (optional) Tensor with true labels. If targeted is true, then provide the
target label. Otherwise, only provide this parameter if you'd like to use true
labels when crafting adversarial samples. Otherwise, model predictions are used
as labels to avoid the "label leaking" effect (explained in this paper:
https://arxiv.org/abs/1611.01236). Default is None.
:param targeted: (optional) bool. Is the attack targeted or untargeted?
Untargeted, the default, will try to make the label incorrect.
Targeted will instead try to move in the direction of being more like y.
:param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /
memory or for unit tests that intentionally pass strange input)
:return: a tensor for the adversarial example
|
[
"This",
"class",
"implements",
"either",
"the",
"Basic",
"Iterative",
"Method",
"(",
"Kurakin",
"et",
"al",
".",
"2016",
")",
"when",
"rand_init",
"is",
"set",
"to",
"0",
".",
"or",
"the",
"Madry",
"et",
"al",
".",
"(",
"2017",
")",
"method",
"when",
"rand_minmax",
"is",
"larger",
"than",
"0",
".",
"Paper",
"link",
"(",
"Kurakin",
"et",
"al",
".",
"2016",
")",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1607",
".",
"02533",
".",
"pdf",
"Paper",
"link",
"(",
"Madry",
"et",
"al",
".",
"2017",
")",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1706",
".",
"06083",
".",
"pdf",
":",
"param",
"model_fn",
":",
"a",
"callable",
"that",
"takes",
"an",
"input",
"tensor",
"and",
"returns",
"the",
"model",
"logits",
".",
":",
"param",
"x",
":",
"input",
"tensor",
".",
":",
"param",
"eps",
":",
"epsilon",
"(",
"input",
"variation",
"parameter",
")",
";",
"see",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1412",
".",
"6572",
".",
":",
"param",
"eps_iter",
":",
"step",
"size",
"for",
"each",
"attack",
"iteration",
":",
"param",
"nb_iter",
":",
"Number",
"of",
"attack",
"iterations",
".",
":",
"param",
"ord",
":",
"Order",
"of",
"the",
"norm",
"(",
"mimics",
"NumPy",
")",
".",
"Possible",
"values",
":",
"np",
".",
"inf",
"1",
"or",
"2",
".",
":",
"param",
"clip_min",
":",
"(",
"optional",
")",
"float",
".",
"Minimum",
"float",
"value",
"for",
"adversarial",
"example",
"components",
".",
":",
"param",
"clip_max",
":",
"(",
"optional",
")",
"float",
".",
"Maximum",
"float",
"value",
"for",
"adversarial",
"example",
"components",
".",
":",
"param",
"y",
":",
"(",
"optional",
")",
"Tensor",
"with",
"true",
"labels",
".",
"If",
"targeted",
"is",
"true",
"then",
"provide",
"the",
"target",
"label",
".",
"Otherwise",
"only",
"provide",
"this",
"parameter",
"if",
"you",
"d",
"like",
"to",
"use",
"true",
"labels",
"when",
"crafting",
"adversarial",
"samples",
".",
"Otherwise",
"model",
"predictions",
"are",
"used",
"as",
"labels",
"to",
"avoid",
"the",
"label",
"leaking",
"effect",
"(",
"explained",
"in",
"this",
"paper",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1611",
".",
"01236",
")",
".",
"Default",
"is",
"None",
".",
":",
"param",
"targeted",
":",
"(",
"optional",
")",
"bool",
".",
"Is",
"the",
"attack",
"targeted",
"or",
"untargeted?",
"Untargeted",
"the",
"default",
"will",
"try",
"to",
"make",
"the",
"label",
"incorrect",
".",
"Targeted",
"will",
"instead",
"try",
"to",
"move",
"in",
"the",
"direction",
"of",
"being",
"more",
"like",
"y",
".",
":",
"param",
"sanity_checks",
":",
"bool",
"if",
"True",
"include",
"asserts",
"(",
"Turn",
"them",
"off",
"to",
"use",
"less",
"runtime",
"/",
"memory",
"or",
"for",
"unit",
"tests",
"that",
"intentionally",
"pass",
"strange",
"input",
")",
":",
"return",
":",
"a",
"tensor",
"for",
"the",
"adversarial",
"example"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/torch/attacks/projected_gradient_descent.py#L9-L100
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
|
_batch_norm
|
def _batch_norm(name, x):
"""Batch normalization."""
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)
|
python
|
def _batch_norm(name, x):
"""Batch normalization."""
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)
|
[
"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.
|
[
"Batch",
"normalization",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L224-L234
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
|
_residual
|
def _residual(x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
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
|
python
|
def _residual(x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
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
|
[
"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.
|
[
"Residual",
"unit",
"with",
"2",
"sub",
"layers",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L237-L269
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
|
_decay
|
def _decay():
"""L2 weight decay loss."""
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)
|
python
|
def _decay():
"""L2 weight decay loss."""
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)
|
[
"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.
|
[
"L2",
"weight",
"decay",
"loss",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L272-L278
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
|
_relu
|
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')
|
python
|
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')
|
[
"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.
|
[
"Relu",
"with",
"optional",
"leaky",
"support",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L292-L294
|
train
|
tensorflow/cleverhans
|
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
|
Input.set_input_shape
|
def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
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)
|
python
|
def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
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)
|
[
"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.
|
[
"Build",
"the",
"core",
"model",
"within",
"the",
"graph",
"."
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L118-L128
|
train
|
tensorflow/cleverhans
|
cleverhans/experimental/certification/dual_formulation.py
|
DualFormulation.create_projected_dual
|
def create_projected_dual(self):
"""Function to create variables for the projected dual object.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual
"""
# 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
|
python
|
def create_projected_dual(self):
"""Function to create variables for the projected dual object.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual
"""
# 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
|
[
"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.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual
|
[
"Function",
"to",
"create",
"variables",
"for",
"the",
"projected",
"dual",
"object",
".",
"Function",
"that",
"projects",
"the",
"input",
"dual",
"variables",
"onto",
"the",
"feasible",
"set",
".",
"Returns",
":",
"projected_dual",
":",
"Feasible",
"dual",
"solution",
"corresponding",
"to",
"current",
"dual"
] |
97488e215760547b81afc53f5e5de8ba7da5bd98
|
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L159-L203
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.