signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def _put_filename(self, key, filename):
|
with open(filename, '<STR_LIT:rb>') as source:<EOL><INDENT>return self._put_file(key, source)<EOL><DEDENT>
|
Store data from file in key. Either this method or
:meth:`~simplekv.KeyValueStore._put_file` will be called by
:meth:`~simplekv.KeyValueStore.put_file`. Note that this method does
not accept strings.
The default implementation will open the file in ``rb`` mode, then call
:meth:`~simplekv.KeyValueStore._put_file`.
:param key: Key under which data should be stored
:param file: Filename of file to store
|
f3993:c0:m19
|
def url_for(self, key):
|
self._check_valid_key(key)<EOL>return self._url_for(key)<EOL>
|
Returns a full external URL that can be used to retrieve *key*.
Does not perform any checks (such as if a key exists), other than
whether or not *key* is a valid key.
:param key: The key for which the url is to be generated
:raises exceptions.ValueError: If the key is not valid.
:return: A string containing a URL to access key
|
f3993:c1:m0
|
def put(self, key, data, ttl_secs=None):
|
self._check_valid_key(key)<EOL>if not isinstance(data, bytes):<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>return self._put(key, data, self._valid_ttl(ttl_secs))<EOL>
|
Like :meth:`~simplekv.KeyValueStore.put`, but with an additional
parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs`` is invalid.
:raises exceptions.IOError: If storing failed or the file could not
be read
|
f3993:c2:m1
|
def put_file(self, key, file, ttl_secs=None):
|
if ttl_secs is None:<EOL><INDENT>ttl_secs = self.default_ttl_secs<EOL><DEDENT>self._check_valid_key(key)<EOL>if isinstance(file, str):<EOL><INDENT>return self._put_filename(key, file, self._valid_ttl(ttl_secs))<EOL><DEDENT>else:<EOL><INDENT>return self._put_file(key, file, self._valid_ttl(ttl_secs))<EOL><DEDENT>
|
Like :meth:`~simplekv.KeyValueStore.put_file`, but with an
additional parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs`` is invalid.
|
f3993:c2:m2
|
def copy(self, source, dest):
|
self._check_valid_key(source)<EOL>self._check_valid_key(dest)<EOL>return self._copy(source, dest)<EOL>
|
Copies a key. The destination is overwritten if does exist.
:param source: The source key to copy
:param dest: The destination for the copy
:returns: The destination key
:raises: exceptions.ValueError: If the source or target key are not valid
:raises: exceptions.KeyError: If the source key was not found
|
f3993:c4:m0
|
def __init__(self, root, perm=None, **kwargs):
|
super(FilesystemStore, self).__init__(**kwargs)<EOL>self.root = text_type(root)<EOL>self.perm = perm<EOL>self.bufsize = <NUM_LIT> * <NUM_LIT><EOL>
|
Initialize new FilesystemStore
When files are created, they will receive permissions depending on the
current umask if *perm* is `None`. Otherwise, permissions are set
expliicitly.
Note that when using :func:`put_file` with a filename, an attempt to
move the file will be made. Permissions and ownership of the file will
be preserved that way. If *perm* is set, permissions will be changed.
:param root: the base directory for the store
:param perm: the permissions for files in the filesystem store
|
f3994:c0:m0
|
def __init__(self, root, url_prefix, **kwargs):
|
super(WebFilesystemStore, self).__init__(root, **kwargs)<EOL>self.url_prefix = url_prefix<EOL>
|
Initialize new WebFilesystemStore.
:param root: see :func:`simplekv.FilesystemStore.__init__`
:param url_prefix: will get prepended to every url generated with
url_for.
|
f3994:c1:m0
|
def shell(cmd, output=None, mode='<STR_LIT:w>', cwd=None, shell=False):
|
if not output:<EOL><INDENT>output = os.devnull<EOL><DEDENT>else:<EOL><INDENT>folder = os.path.dirname(output)<EOL>if folder and not os.path.isdir(folder):<EOL><INDENT>os.makedirs(folder)<EOL><DEDENT><DEDENT>if not isinstance(cmd, (list, tuple)) and not shell:<EOL><INDENT>cmd = shlex.split(cmd)<EOL><DEDENT>def run_shell():<EOL><INDENT>try:<EOL><INDENT>p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd,<EOL>shell=shell)<EOL><DEDENT>except OSError as e:<EOL><INDENT>logger.error(e)<EOL>if e.errno == os.errno.ENOENT: <EOL><INDENT>logger.error("<STR_LIT>", cmd[<NUM_LIT:0>])<EOL><DEDENT>return e<EOL><DEDENT>stdout, stderr = p.communicate()<EOL>if stderr:<EOL><INDENT>logger.error(stderr)<EOL>return stderr<EOL><DEDENT>if PY3:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>with open(output, mode) as f:<EOL><INDENT>f.write(stdout)<EOL><DEDENT><DEDENT>return run_shell<EOL>
|
Execute a shell command.
You can add a shell command::
server.watch(
'style.less', shell('lessc style.less', output='style.css')
)
:param cmd: a shell command, string or list
:param output: output stdout to the given file
:param mode: only works with output, mode ``w`` means write,
mode ``a`` means append
:param cwd: set working directory before command is executed.
:param shell: if true, on Unix the executable argument specifies a
replacement shell for the default ``/bin/sh``.
|
f4019:m0
|
def ignore_file_extension(self, extension):
|
logger.info('<STR_LIT>'.format(extension))<EOL>self.watcher.ignore_file_extension(extension)<EOL>
|
Configure a file extension to be ignored.
:param extension: file extension to be ignored
(ex. .less, .scss, etc)
|
f4019:c0:m1
|
def watch(self, filepath, func=None, delay=None):
|
if isinstance(func, string_types):<EOL><INDENT>func = shell(func)<EOL><DEDENT>self.watcher.watch(filepath, func, delay)<EOL>
|
Add the given filepath for watcher list.
Once you have intialized a server, watch file changes before
serve the server::
server.watch('static/*.stylus', 'make static')
def alert():
print('foo')
server.watch('foo.txt', alert)
server.serve()
:param filepath: files to be watched, it can be a filepath,
a directory, or a glob pattern
:param func: the function to be called, it can be a string of
shell command, or any callable object without
parameters
:param delay: Delay sending the reload message. Use 'forever' to
not send it. This is useful to compile sass files to
css, but reload on changed css files then only.
|
f4019:c0:m2
|
def serve(self, liveport=None, host=None, restart_delay=<NUM_LIT:2>):
|
host = host or '<STR_LIT:127.0.0.1>'<EOL>logger.info('<STR_LIT>' % (host, liveport))<EOL>self.application(host, liveport=liveport)<EOL>try:<EOL><INDENT>self.watcher._changes.append(('<STR_LIT>', restart_delay))<EOL>LiveReloadHandler.start_tasks()<EOL>IOLoop.instance().start()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>logger.info('<STR_LIT>')<EOL><DEDENT>
|
Start serve the server with the given port.
:param liveport: live reload on this port
:param host: serve on this hostname, default is 127.0.0.1
:param open_url_delay: open webbrowser after the delay seconds
|
f4019:c0:m4
|
def on_message(self, message):
|
message = ObjectDict(escape.json_decode(message))<EOL>if message.command == '<STR_LIT:hello>':<EOL><INDENT>handshake = {<EOL>'<STR_LIT>': '<STR_LIT:hello>',<EOL>'<STR_LIT>': [<EOL>'<STR_LIT>',<EOL>],<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>self.send_message(handshake)<EOL><DEDENT>if message.command == '<STR_LIT:info>' and '<STR_LIT:url>' in message:<EOL><INDENT>logger.info('<STR_LIT>' % message.url)<EOL>LiveReloadHandler.waiters.add(self)<EOL><DEDENT>
|
Handshake with livereload.js
1. client send 'hello'
2. server reply 'hello'
3. client send 'info'
|
f4021:c0:m7
|
def livereload_request(self, **options):
|
style = color_style()<EOL>verbosity = int(options['<STR_LIT>'])<EOL>host = '<STR_LIT>' % (<EOL>options['<STR_LIT>'],<EOL>options['<STR_LIT>'],<EOL>)<EOL>try:<EOL><INDENT>urlopen('<STR_LIT>' % host)<EOL>self.message('<STR_LIT>',<EOL>verbosity, style.HTTP_INFO)<EOL><DEDENT>except IOError:<EOL><INDENT>pass<EOL><DEDENT>
|
Performs the LiveReload request.
|
f4023:c0:m2
|
def get_handler(self, *args, **options):
|
handler = super(Command, self).get_handler(*args, **options)<EOL>if options['<STR_LIT>']:<EOL><INDENT>threading.Timer(<NUM_LIT:1>, self.livereload_request, kwargs=options).start()<EOL><DEDENT>return handler<EOL>
|
Entry point to plug the LiveReload feature.
|
f4023:c0:m3
|
def should_ignore(self, filename):
|
_, ext = os.path.splitext(filename)<EOL>return ext in self.ignored_file_extensions<EOL>
|
Should ignore a given filename?
|
f4026:c0:m1
|
def watch(self, path, func=None, delay=<NUM_LIT:0>, ignore=None):
|
self._tasks[path] = {<EOL>'<STR_LIT>': func,<EOL>'<STR_LIT>': delay,<EOL>'<STR_LIT:ignore>': ignore,<EOL>}<EOL>
|
Add a task to watcher.
:param path: a filepath or directory path or glob pattern
:param func: the function to be executed when file changed
:param delay: Delay sending the reload message. Use 'forever' to
not send it. This is useful to compile sass files to
css, but reload on changed css files then only.
:param ignore: A function return True to ignore a certain pattern of
filepath.
|
f4026:c0:m3
|
def start(self, callback):
|
return False<EOL>
|
Start the watcher running, calling callback when changes are
observed. If this returns False, regular polling will be used.
|
f4026:c0:m4
|
def examine(self):
|
if self._changes:<EOL><INDENT>return self._changes.pop()<EOL><DEDENT>self.filepath = None<EOL>delays = set([<NUM_LIT:0>])<EOL>for path in self._tasks:<EOL><INDENT>item = self._tasks[path]<EOL>if self.is_changed(path, item['<STR_LIT:ignore>']):<EOL><INDENT>func = item['<STR_LIT>']<EOL>func and func()<EOL>delay = item['<STR_LIT>']<EOL>if delay:<EOL><INDENT>delays.add(delay)<EOL><DEDENT><DEDENT><DEDENT>if '<STR_LIT>' in delays:<EOL><INDENT>delay = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>delay = max(delays)<EOL><DEDENT>return self.filepath, delay<EOL>
|
Check if there are changes, if true, run the given task.
|
f4026:c0:m5
|
def includeme(config):
|
<EOL>settings = config.get_settings()<EOL>authz_class = settings.get("<STR_LIT>",<EOL>"<STR_LIT>")<EOL>authz_policy = config.maybe_dotted(authz_class)()<EOL>config.set_authorization_policy(authz_policy)<EOL>groupfinder = settings.get("<STR_LIT>", None)<EOL>groupfinder = config.maybe_dotted(groupfinder)<EOL>policy_definitions = get_policy_definitions(settings)<EOL>policy_factories = []<EOL>policy_names = settings.get("<STR_LIT>", "<STR_LIT>").split()<EOL>for policy_name in reversed(policy_names):<EOL><INDENT>if policy_name in policy_definitions:<EOL><INDENT>definition = policy_definitions[policy_name]<EOL>factory = config.maybe_dotted(definition.pop("<STR_LIT>"))<EOL>policy_factories.append((factory, policy_name, definition))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>factory = policy_factory_from_module(config, policy_name)<EOL><DEDENT>except ImportError:<EOL><INDENT>err = "<STR_LIT>""<STR_LIT>" % (policy_name,)<EOL>raise ValueError(err)<EOL><DEDENT>policy_factories.append((factory, policy_name, {}))<EOL><DEDENT><DEDENT>policies = []<EOL>def grab_policies():<EOL><INDENT>for factory, name, kwds in policy_factories:<EOL><INDENT>policy = factory(**kwds)<EOL>if policy:<EOL><INDENT>policy._pyramid_multiauth_name = name<EOL>if not policies or policy is not policies[<NUM_LIT:0>]:<EOL><INDENT>policies.insert(<NUM_LIT:0>, policy)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>config.action(None, grab_policies, order=PHASE2_CONFIG)<EOL>authn_policy = MultiAuthenticationPolicy(policies, groupfinder)<EOL>config.set_authentication_policy(authn_policy)<EOL>
|
Include pyramid_multiauth into a pyramid configurator.
This function provides a hook for pyramid to include the default settings
for auth via pyramid_multiauth. Activate it like so:
config.include("pyramid_multiauth")
This will pull the list of registered authn policies from the deployment
settings, and configure and install each policy in order. The policies to
use can be specified in one of two ways:
* as the name of a module to be included.
* as the name of a callable along with a set of parameters.
Here's an example suite of settings:
multiauth.policies = ipauth1 ipauth2 pyramid_browserid
multiauth.policy.ipauth1.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth1.ipaddrs = 123.123.0.0/16
multiauth.policy.ipauth1.userid = local1
multiauth.policy.ipauth2.use = pyramid_ipauth.IPAuthentictionPolicy
multiauth.policy.ipauth2.ipaddrs = 124.124.0.0/16
multiauth.policy.ipauth2.userid = local2
This will configure a MultiAuthenticationPolicy with three policy objects.
The first two will be IPAuthenticationPolicy objects created by passing
in the specified keyword arguments. The third will be a BrowserID
authentication policy just like you would get from executing:
config.include("pyramid_browserid")
As a side-effect, the configuration will also get the additional views
that pyramid_browserid sets up by default.
The *group finder function* and the *authorization policy* are also read
from configuration if specified:
multiauth.authorization_policy = mypyramidapp.acl.Custom
multiauth.groupfinder = mypyramidapp.acl.groupfinder
|
f4028:m0
|
def policy_factory_from_module(config, module):
|
<EOL>orig_policy = config.registry.queryUtility(IAuthenticationPolicy)<EOL>config.include(module)<EOL>policy = config.registry.queryUtility(IAuthenticationPolicy)<EOL>if policy is not None and policy is not orig_policy:<EOL><INDENT>return lambda: policy<EOL><DEDENT>for action in reversed(config.action_state.actions):<EOL><INDENT>try:<EOL><INDENT>discriminator = action["<STR_LIT>"]<EOL>callable = action["<STR_LIT>"]<EOL><DEDENT>except TypeError: <EOL><INDENT>discriminator = action[<NUM_LIT:0>] <EOL>callable = action[<NUM_LIT:1>] <EOL><DEDENT>if discriminator is not IAuthenticationPolicy:<EOL><INDENT>continue<EOL><DEDENT>def grab_policy(register=callable):<EOL><INDENT>old_policy = config.registry.queryUtility(IAuthenticationPolicy)<EOL>register()<EOL>new_policy = config.registry.queryUtility(IAuthenticationPolicy)<EOL>config.registry.registerUtility(old_policy, IAuthenticationPolicy)<EOL>return new_policy<EOL><DEDENT>return grab_policy<EOL><DEDENT>return lambda: None<EOL>
|
Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. It's complicated by pyramid's delayed-
commit system, which means we have to do the work via callbacks.
|
f4028:m1
|
def get_policy_definitions(settings):
|
policy_definitions = {}<EOL>for name in settings:<EOL><INDENT>if not name.startswith("<STR_LIT>"):<EOL><INDENT>continue<EOL><DEDENT>value = settings[name]<EOL>name = name[len("<STR_LIT>"):]<EOL>policy_name, setting_name = name.split("<STR_LIT:.>", <NUM_LIT:1>)<EOL>if policy_name not in policy_definitions:<EOL><INDENT>policy_definitions[policy_name] = {}<EOL><DEDENT>policy_definitions[policy_name][setting_name] = value<EOL><DEDENT>return policy_definitions<EOL>
|
Find all multiauth policy definitions from the settings dict.
This function processes the paster deployment settings looking for items
that start with "multiauth.policy.<policyname>.". It pulls them all out
into a dict indexed by the policy name.
|
f4028:m2
|
def authenticated_userid(self, request):
|
userid = None<EOL>for policy in self._policies:<EOL><INDENT>userid = policy.authenticated_userid(request)<EOL>if userid is not None:<EOL><INDENT>request.registry.notify(MultiAuthPolicySelected(policy,<EOL>request,<EOL>userid))<EOL>if self._callback is None:<EOL><INDENT>break<EOL><DEDENT>if self._callback(userid, request) is not None:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>userid = None<EOL><DEDENT><DEDENT><DEDENT>return userid<EOL>
|
Find the authenticated userid for this request.
This method delegates to each authn policy in turn, taking the
userid from the first one that doesn't return None. If a
groupfinder callback is configured, it is also used to validate
the userid before returning.
|
f4028:c1:m1
|
def unauthenticated_userid(self, request):
|
userid = None<EOL>for policy in self._policies:<EOL><INDENT>userid = policy.unauthenticated_userid(request)<EOL>if userid is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return userid<EOL>
|
Find the unauthenticated userid for this request.
This method delegates to each authn policy in turn, taking the
userid from the first one that doesn't return None.
|
f4028:c1:m2
|
def effective_principals(self, request):
|
principals = set((Everyone,))<EOL>for policy in self._policies:<EOL><INDENT>principals.update(policy.effective_principals(request))<EOL><DEDENT>if self._callback is not None:<EOL><INDENT>principals.discard(Authenticated)<EOL>groups = None<EOL>for policy in self._policies:<EOL><INDENT>userid = policy.authenticated_userid(request)<EOL>if userid is None:<EOL><INDENT>continue<EOL><DEDENT>request.registry.notify(MultiAuthPolicySelected(policy,<EOL>request,<EOL>userid))<EOL>groups = self._callback(userid, request)<EOL>if groups is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if groups is not None:<EOL><INDENT>principals.add(userid)<EOL>principals.add(Authenticated)<EOL>principals.update(groups)<EOL><DEDENT><DEDENT>return list(principals)<EOL>
|
Get the list of effective principals for this request.
This method returns the union of the principals returned by each
authn policy. If a groupfinder callback is registered, its output
is also added to the list.
|
f4028:c1:m3
|
def remember(self, request, principal, **kw):
|
headers = []<EOL>for policy in self._policies:<EOL><INDENT>headers.extend(policy.remember(request, principal, **kw))<EOL><DEDENT>return headers<EOL>
|
Remember the authenticated userid.
This method returns the concatentation of the headers returned by each
authn policy.
|
f4028:c1:m4
|
def forget(self, request):
|
headers = []<EOL>for policy in self._policies:<EOL><INDENT>headers.extend(policy.forget(request))<EOL><DEDENT>return headers<EOL>
|
Forget a previusly remembered userid.
This method returns the concatentation of the headers returned by each
authn policy.
|
f4028:c1:m5
|
def get_policies(self):
|
return [(getattr(policy, "<STR_LIT>", None), policy)<EOL>for policy in self._policies]<EOL>
|
Get the list of contained authentication policies, as tuple of
name and instances.
This may be useful to instrospect the configured policies, and their
respective name defined in configuration.
|
f4028:c1:m6
|
def get_policy(self, name_or_class):
|
for policy in self._policies:<EOL><INDENT>if isinstance(name_or_class, basestring):<EOL><INDENT>policy_name = getattr(policy, "<STR_LIT>", None)<EOL>if policy_name == name_or_class:<EOL><INDENT>return policy<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(policy, name_or_class):<EOL><INDENT>return policy<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>
|
Get one of the contained authentication policies, by name or class.
This method can be used to obtain one of the subpolicies loaded
by this policy object. The policy can be looked up either by the
name given to it in the config settings, or or by its class. If
no policy is found matching the given query, None is returned.
This may be useful if you need to access non-standard methods or
properties on one of the loaded policy objects.
|
f4028:c1:m7
|
def raiseforbidden(request):
|
raise Forbidden()<EOL>
|
View that always just raises Forbidden.
|
f4029:m4
|
def example_handler(self, context):
|
self.called = True<EOL>
|
Test Doc String
|
f4038:c1:m1
|
def get_real_last_traceback(exception):
|
traceback_blocks = []<EOL>_n, _n, exc_traceback = sys.exc_info()<EOL>tb_list = get_all_tracebacks(exc_traceback)[<NUM_LIT:1>:]<EOL>tb_list = [tb for tb in tb_list if tb not in CAPTURED_TRACEBACKS]<EOL>CAPTURED_TRACEBACKS.extend(tb_list)<EOL>for traceback in tb_list:<EOL><INDENT>lines, path, line_num = get_source_from_frame(traceback.tb_frame)<EOL>traceback_lines = get_numbered_source(lines, traceback.tb_lineno,<EOL>line_num)<EOL>traceback_lines.insert(<NUM_LIT:0>, '<STR_LIT>'.format(path))<EOL>traceback_lines.insert(<NUM_LIT:1>, '<STR_LIT>')<EOL>traceback_lines.append('<STR_LIT>')<EOL>traceback_blocks.append(traceback_lines)<EOL><DEDENT>traced_lines = ['<STR_LIT>']<EOL>traced_lines.extend(itertools.chain.from_iterable(traceback_blocks))<EOL>traced_lines.append('<STR_LIT>'.format(<EOL>type(exception).__name__, exception))<EOL>return traced_lines<EOL>
|
An unfortunate evil... All because Python's traceback cannot
determine where my executed code is coming from...
|
f4040:m5
|
def print_error(self, wrapper):
|
level = <NUM_LIT:0><EOL>parent = wrapper.parent<EOL>while parent:<EOL><INDENT>print_test_msg(parent.name, level, TestStatus.FAIL, self.use_color)<EOL>level += <NUM_LIT:1><EOL>parent = parent.parent<EOL><DEDENT>print_test_msg(wrapper.name, level, TestStatus.FAIL, self.use_color)<EOL>print_test_args(wrapper.execute_kwargs, level, TestStatus.FAIL,<EOL>self.use_color)<EOL>if wrapper.error:<EOL><INDENT>for line in wrapper.error:<EOL><INDENT>print_test_msg(<EOL>line,<EOL>level + <NUM_LIT:2>,<EOL>TestStatus.FAIL,<EOL>self.use_color<EOL>)<EOL><DEDENT><DEDENT>print_expects(wrapper, level, use_color=self.use_color)<EOL>
|
A crude way of output the errors for now. This needs to be
cleaned up into something better.
|
f4041:c0:m4
|
def output(self, msg, indent, status=None):
|
color = None<EOL>if self.use_color:<EOL><INDENT>color = get_color_from_status(status)<EOL><DEDENT>print_indent_msg(msg, indent, color)<EOL>
|
Alias for print_indent_msg with color determined by status.
|
f4042:c0:m10
|
def subscribe_all_to_spec(self, spec):
|
for reporter in self.reporters:<EOL><INDENT>if self.can_use_reporter(reporter, self.parallel):<EOL><INDENT>reporter.subscribe_to_spec(spec)<EOL><DEDENT><DEDENT>
|
Will automatically not subscribe reporters that are not parallel
or serial depending on the current mode.
|
f4044:c4:m5
|
def run(self):
|
last_time = time()<EOL>completed = []<EOL>if self.coverage:<EOL><INDENT>self.coverage.start()<EOL><DEDENT>while True:<EOL><INDENT>case_wrapper = self.work_queue.get()<EOL>if case_wrapper == '<STR_LIT>':<EOL><INDENT>if len(completed) > <NUM_LIT:0>:<EOL><INDENT>self.pipe.send(completed)<EOL>self.completed = []<EOL><DEDENT>self.pipe.send(None)<EOL>if self.coverage:<EOL><INDENT>self.coverage.stop()<EOL>self.coverage.save()<EOL><DEDENT>return<EOL><DEDENT>case_wrapper.case_func = self.all_cases[case_wrapper.case_func]<EOL>case_wrapper.parent = self.all_parents[case_wrapper.parent]<EOL>case_wrapper.parent._state.before_each()<EOL>case_wrapper.execute(case_wrapper.parent._state)<EOL>case_wrapper.parent._state.after_each()<EOL>self.worked.value += <NUM_LIT:1><EOL>completed.append(case_wrapper)<EOL>if completed and time() >= (last_time + <NUM_LIT>):<EOL><INDENT>self.pipe.send(completed)<EOL>completed = []<EOL>last_time = time()<EOL><DEDENT><DEDENT>
|
Note: CI Coverage is turned off due to it not showing covered
even with there being tests that run this function.
|
f4047:c0:m1
|
def fixture(cls):
|
setattr(cls, '<STR_LIT>', True)<EOL>return cls<EOL>
|
A simple decorator to set the fixture flag on the class.
|
f4048:m1
|
def serialize(self):
|
expects = [exp.serialize() for exp in self.expects]<EOL>converted_dict = {<EOL>'<STR_LIT:id>': self.id,<EOL>'<STR_LIT:name>': self.pretty_name,<EOL>'<STR_LIT>': self.name,<EOL>'<STR_LIT>': self.doc,<EOL>'<STR_LIT:error>': self.error,<EOL>'<STR_LIT>': self.skipped,<EOL>'<STR_LIT>': self.skip_reason,<EOL>'<STR_LIT>': self.safe_execute_kwargs,<EOL>'<STR_LIT>': self.metadata,<EOL>'<STR_LIT:start>': self.start_time,<EOL>'<STR_LIT:end>': self.end_time,<EOL>'<STR_LIT>': expects,<EOL>'<STR_LIT:success>': self.success<EOL>}<EOL>return remove_empty_entries_from_dict(converted_dict)<EOL>
|
Serializes the CaseWrapper object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
|
f4048:c1:m1
|
def serialize(self):
|
cases = [case.serialize() for key, case in six.iteritems(self.cases)]<EOL>specs = [spec.serialize() for spec in self.describes]<EOL>converted_dict = {<EOL>'<STR_LIT:id>': self.id,<EOL>'<STR_LIT:name>': self.name,<EOL>'<STR_LIT>': self.real_class_path,<EOL>'<STR_LIT>': self.doc,<EOL>'<STR_LIT>': cases,<EOL>'<STR_LIT>': specs<EOL>}<EOL>return converted_dict<EOL>
|
Serializes the Spec/Describe object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
|
f4048:c2:m15
|
def _run_hooks(self):
|
for hook in self.hooks:<EOL><INDENT>getattr(self, hook)(self._state)<EOL><DEDENT>
|
Calls any registered hooks providing the current state.
|
f4048:c2:m16
|
def __create_state_obj__(self):
|
stops = [Describe, Spec, DataDescribe, EventDispatcher]<EOL>mros = [mro for mro in inspect.getmro(type(self)) if mro not in stops]<EOL>mros.reverse()<EOL>class GenericStateObj(object):<EOL><INDENT>def before_all(self):<EOL><INDENT>pass<EOL><DEDENT>def after_all(self):<EOL><INDENT>pass<EOL><DEDENT>def before_each(self):<EOL><INDENT>pass<EOL><DEDENT>def after_each(self):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>chain = [GenericStateObj]<EOL>for mro in mros:<EOL><INDENT>cls_name = '<STR_LIT>'.format(mro.__name__)<EOL>cls = type(cls_name, (chain[-<NUM_LIT:1>:][<NUM_LIT:0>],), dict(mro.__dict__))<EOL>cls.__spec__ = self<EOL>chain.append(cls)<EOL><DEDENT>chain.pop(<NUM_LIT:0>)<EOL>state_cls = chain[-<NUM_LIT:1>:][<NUM_LIT:0>]<EOL>return state_cls()<EOL>
|
Generates the clean state object magic. Here be dragons!
|
f4048:c2:m17
|
def decompile(ast, indentation=<NUM_LIT:4>, line_length=<NUM_LIT:100>, starting_indentation=<NUM_LIT:0>):
|
decompiler = Decompiler(<EOL>indentation=indentation,<EOL>line_length=line_length,<EOL>starting_indentation=starting_indentation,<EOL>)<EOL>return decompiler.run(ast)<EOL>
|
Decompiles an AST into Python code.
Arguments:
- ast: code to decompile, using AST objects as generated by the standard library ast module
- indentation: indentation level of lines
- line_length: if lines become longer than this length, ast_decompiler will try to break them up
(but it will not necessarily succeed in all cases)
- starting_indentation: indentation level at which to start producing code
|
f4050:m0
|
def write_expression_list(self, nodes, separator='<STR_LIT:U+002CU+0020>', allow_newlines=True, need_parens=True,<EOL>final_separator_if_multiline=True):
|
first = True<EOL>last_line = len(self.lines)<EOL>current_line = list(self.current_line)<EOL>for node in nodes:<EOL><INDENT>if first:<EOL><INDENT>first = False<EOL><DEDENT>else:<EOL><INDENT>self.write(separator)<EOL><DEDENT>self.visit(node)<EOL>if allow_newlines and (self.current_line_length() > self.max_line_length or<EOL>last_line != len(self.lines)):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return <EOL><DEDENT>del self.lines[last_line:]<EOL>self.current_line = current_line<EOL>separator = separator.rstrip()<EOL>if need_parens:<EOL><INDENT>self.write('<STR_LIT:(>')<EOL><DEDENT>self.write_newline()<EOL>with self.add_indentation():<EOL><INDENT>num_nodes = len(nodes)<EOL>for i, node in enumerate(nodes):<EOL><INDENT>self.write_indentation()<EOL>self.visit(node)<EOL>if final_separator_if_multiline or i < num_nodes - <NUM_LIT:1>:<EOL><INDENT>self.write(separator)<EOL><DEDENT>self.write_newline()<EOL><DEDENT><DEDENT>self.write_indentation()<EOL>if need_parens:<EOL><INDENT>self.write('<STR_LIT:)>')<EOL><DEDENT>
|
Writes a list of nodes, separated by separator.
If allow_newlines, will write the expression over multiple lines if necessary to say within
max_line_length. If need_parens, will surround the expression with parentheses in this case.
If final_separator_if_multiline, will write a separator at the end of the list if it is
divided over multiple lines.
|
f4050:c1:m9
|
def _(msg):
|
return gettext.gettext(msg)<EOL>
|
Dealing with pylint problems.
|
f4051:m0
|
def combine_coverage_reports(self, omit, parallel):
|
tmp_cov = coverage.coverage(omit=omit, data_suffix=parallel)<EOL>tmp_cov.load()<EOL>tmp_cov.combine()<EOL>tmp_cov.save()<EOL>
|
Method to force the combination of parallel coverage reports.
|
f4052:c0:m4
|
def expect(obj, caller_args=[]):
|
line, module = get_module_and_line('<STR_LIT>')<EOL>src_params = ExpectParams(line, module)<EOL>expect_obj = ExpectAssert(<EOL>obj,<EOL>src_params=src_params,<EOL>caller_args=caller_args<EOL>)<EOL>_add_expect_to_wrapper(expect_obj)<EOL>return expect_obj<EOL>
|
Primary method for test assertions in Specter
:param obj: The evaluated target object
:param caller_args: Is only used when using expecting a raised Exception
|
f4054:m1
|
def require(obj, caller_args=[]):
|
line, module = get_module_and_line('<STR_LIT>')<EOL>src_params = ExpectParams(line, module)<EOL>require_obj = RequireAssert(<EOL>obj,<EOL>src_params=src_params,<EOL>caller_args=caller_args<EOL>)<EOL>_add_expect_to_wrapper(require_obj)<EOL>return require_obj<EOL>
|
Primary method for test assertions in Specter
:param obj: The evaluated target object
:param caller_args: Is only used when using expecting a raised Exception
|
f4054:m2
|
def skip(reason):
|
def decorator(test_func):<EOL><INDENT>if not isinstance(test_func, (type, ClassObjType)):<EOL><INDENT>func_data = None<EOL>if test_func.__name__ == '<STR_LIT>':<EOL><INDENT>func_data = test_func()<EOL><DEDENT>@functools.wraps(test_func)<EOL>def skip_wrapper(*args, **kwargs):<EOL><INDENT>other_data = {<EOL>'<STR_LIT>': func_data[<NUM_LIT:0>] if func_data else test_func,<EOL>'<STR_LIT>': func_data[<NUM_LIT:1>] if func_data else None<EOL>}<EOL>raise TestSkippedException(test_func, reason, other_data)<EOL><DEDENT>test_func = skip_wrapper<EOL><DEDENT>return test_func<EOL><DEDENT>return decorator<EOL>
|
The skip decorator allows for you to always bypass a test.
:param reason: Expects a string
|
f4054:m3
|
def skip_if(condition, reason=None):
|
if condition:<EOL><INDENT>return skip(reason)<EOL><DEDENT>def wrapper(func):<EOL><INDENT>return func<EOL><DEDENT>return wrapper<EOL>
|
The skip_if decorator allows for you to bypass a test on conditions
:param condition: Expects a boolean
:param reason: Expects a string
|
f4054:m4
|
def metadata(**key_value_pairs):
|
def onTestFunc(func):<EOL><INDENT>def DECORATOR_ONCALL(*args, **kwargs):<EOL><INDENT>return (func, key_value_pairs)<EOL><DEDENT>return DECORATOR_ONCALL<EOL><DEDENT>return onTestFunc<EOL>
|
The metadata decorator allows for you to tag specific tests with
key/value data for run-time processing or reporting. The common use case
is to use metadata to tag a test as a positive or negative test type.
.. code-block:: python
# Example of using the metadata decorator
@metadata(type='negative')
def it_shouldnt_do_something(self):
pass
|
f4054:m6
|
def serialize(self):
|
converted_dict = {<EOL>'<STR_LIT:success>': self.success,<EOL>'<STR_LIT>': str(self),<EOL>'<STR_LIT>': self.required<EOL>}<EOL>return converted_dict<EOL>
|
Serializes the ExpectAssert object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
|
f4054:c0:m3
|
def anf_lines(f):
|
return quoting.unquote(anf.anf(quoting.parse_function(f))).split('<STR_LIT:\n>')<EOL>
|
Return the ANF transformed source code as lines.
|
f4058:m0
|
def register_parametrizations(metafunc, short):
|
for arg in ['<STR_LIT:t>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if tf:<EOL><INDENT>vectors = [<EOL>np.random.randn(i)<EOL>for i in (<EOL>(<NUM_LIT:3>,) if short else (<NUM_LIT:3>, <NUM_LIT:5>, <NUM_LIT:10>))]<EOL>tensors = [tf.constant(v, dtype=tf.float32) for v in vectors]<EOL><DEDENT>else:<EOL><INDENT>tensors = [pytest.mark.skip(None, reason='<STR_LIT>')(None)]<EOL><DEDENT>if arg in metafunc.fixturenames:<EOL><INDENT>metafunc.parametrize(arg, tensors)<EOL><DEDENT><DEDENT>for arg in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if tf:<EOL><INDENT>matrices = [<EOL>np.random.randn(*i)<EOL>for i in (<EOL>((<NUM_LIT:3>, <NUM_LIT:3>),) if short else (<EOL>(<NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:3>, <NUM_LIT:3>),<EOL>(<NUM_LIT:5>, <NUM_LIT:5>)))]<EOL>tensors = [tf.constant(m, dtype=tf.float32) for m in matrices]<EOL><DEDENT>else:<EOL><INDENT>tensors = [pytest.mark.skip(None, reason='<STR_LIT>')(None)]<EOL><DEDENT>if arg in metafunc.fixturenames:<EOL><INDENT>metafunc.parametrize(arg, tensors)<EOL><DEDENT><DEDENT>if '<STR_LIT:s>' in metafunc.fixturenames:<EOL><INDENT>if tf:<EOL><INDENT>if short:<EOL><INDENT>scalars = [tf.constant(<NUM_LIT:1.0>)]<EOL><DEDENT>else:<EOL><INDENT>scalars = [tf.constant(c) for c in (<NUM_LIT:0.0>, <NUM_LIT:1.0>, <NUM_LIT>)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>scalars = [pytest.mark.skip(reason='<STR_LIT>')(None)]<EOL><DEDENT>metafunc.parametrize('<STR_LIT:s>', scalars)<EOL><DEDENT>for arg in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if arg in metafunc.fixturenames:<EOL><INDENT>if tf:<EOL><INDENT>images = [<EOL>np.random.randn(*i)<EOL>for i in (<EOL>((<NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>),) if short else (<EOL>(<NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:3>),<EOL>(<NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>),<EOL>(<NUM_LIT:2>, <NUM_LIT:5>, <NUM_LIT:5>, <NUM_LIT:3>),<EOL>))<EOL>]<EOL>timages = [tf.constant(v, dtype=tf.float32) for v in images]<EOL><DEDENT>else:<EOL><INDENT>timages = [pytest.mark.skip(reason='<STR_LIT>')(None)]<EOL><DEDENT>metafunc.parametrize(arg, timages)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in metafunc.fixturenames:<EOL><INDENT>if tf:<EOL><INDENT>kernels = [<EOL>np.random.randn(*i)<EOL>for i in (<EOL>((<NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:1>),) if short else (<EOL>(<NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:1>),<EOL>(<NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:2>),<EOL>(<NUM_LIT:5>, <NUM_LIT:5>, <NUM_LIT:3>, <NUM_LIT:3>),<EOL>))<EOL>]<EOL>tkernels = [tf.constant(v, dtype=tf.float32) for v in kernels]<EOL><DEDENT>else:<EOL><INDENT>tkernels = [pytest.mark.skip(reason='<STR_LIT>')(None)]<EOL><DEDENT>metafunc.parametrize('<STR_LIT>', tkernels)<EOL><DEDENT>if '<STR_LIT>' in metafunc.fixturenames:<EOL><INDENT>strides = [(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>)] if short else [<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>),<EOL>]<EOL>metafunc.parametrize('<STR_LIT>', strides)<EOL><DEDENT>if '<STR_LIT>' in metafunc.fixturenames:<EOL><INDENT>sizes = [(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>)] if short else [<EOL>(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>),<EOL>(<NUM_LIT:1>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:1>),<EOL>]<EOL>metafunc.parametrize('<STR_LIT>', sizes)<EOL><DEDENT>
|
Create additional parametrizations required for TF tests.
|
f4062:m0
|
def as_numpy_sig(func):
|
def wrapped(*args):<EOL><INDENT>np_args = [tf.constant(a) if isinstance(a, np.ndarray) else a for a in args]<EOL>return tensors_to_numpy(func(*np_args))<EOL><DEDENT>return wrapped<EOL>
|
Wrap a TF Eager function into a signature that uses NumPy arrays.
|
f4062:m2
|
def _wrap(body):
|
def f():<EOL><INDENT>pass<EOL><DEDENT>tree = quoting.parse_function(f)<EOL>tree.body[<NUM_LIT:0>].body = body<EOL>return tree<EOL>
|
Take a list of statements and wrap them in a function to compile.
|
f4070:m0
|
def assert_result_matches_reference(<EOL>tangent_func,<EOL>reference_func,<EOL>backup_reference_func,<EOL>tolerance=<NUM_LIT>):
|
tangent_value = tangent_func()<EOL>try:<EOL><INDENT>reference_value = reference_func()<EOL><DEDENT>except (ImportError, TypeError) as e:<EOL><INDENT>if __debug__:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>' % e)<EOL><DEDENT>reference_value = backup_reference_func()<EOL><DEDENT>_assert_allclose(tangent_value, reference_value, tolerance)<EOL>
|
Test Tangent functionality against reference implementation.
Args:
tangent_func: Returns the Tangent derivative.
reference_func: Returns the derivative calculated by the reference
implementation.
backup_reference_func: Returns the derivative calculated by a catch-all
implementation, should the reference be unavailable.
tolerance: Absolute tolerance override for FP comparisons.
|
f4071:m2
|
def numeric_grad(func, eps=<NUM_LIT>):
|
def g(x, *args):<EOL><INDENT>fd_grad, unflatten_fd = flatten(tangent.init_grad(x))<EOL>y = func(deepcopy(x), *args)<EOL>seed = np.ones_like(y)<EOL>for d in range(fd_grad.size):<EOL><INDENT>x_flat, unflatten_x = flatten(deepcopy(x))<EOL>x_flat[d] += eps / <NUM_LIT:2><EOL>a = np.array(func(unflatten_x(x_flat), *args))<EOL>x_flat, unflatten_x = flatten(deepcopy(x))<EOL>x_flat[d] -= eps / <NUM_LIT:2><EOL>b = np.array(func(unflatten_x(x_flat), *args))<EOL>fd_grad[d] = np.dot((a - b) / eps, seed)<EOL><DEDENT>return unflatten_fd(fd_grad)<EOL><DEDENT>return g<EOL>
|
Generate a finite-differences gradient of function `f`.
def f(x, *args):
...
return scalar
g = numeric_grad(f, eps=1e-4)
finite_difference_grad_of_x = g(x, *args)
Adapted from github.com/hips/autograd
|
f4071:m3
|
def unbroadcast_tfe_to(tensor, shape):
|
axis = utils.create_unbroadcast_axis(shape, shape_as_list(tensor))<EOL>return tf.reshape(tf.reduce_sum(tensor, axis=axis), shape)<EOL>
|
Reverse the broadcasting operation.
See utils.py.
Args:
tensor: A Tensor.
shape: A shape that could have been broadcasted to the shape of tensor.
Returns:
Tensor with dimensions summed to match `shape`.
|
f4074:m4
|
def unbroadcast_tensor(tensor, like):
|
return unbroadcast_tfe_to(tensor, shape_as_list(like))<EOL>
|
Reverse the broadcasting operation.
See utils.py.
Args:
tensor: A Tensor.
like: A Tensor that could have been broadcasted to the shape of tensor.
Returns:
Tensor with certain dimensions summed to match the shape of `like`.
|
f4074:m5
|
def unreduce_tensor(tensor, shape, axis, keepdims):
|
if not keepdims:<EOL><INDENT>if axis is None:<EOL><INDENT>axis = range(len(shape))<EOL><DEDENT>elif isinstance(axis, int):<EOL><INDENT>axis = axis,<EOL><DEDENT>for ax in sorted(axis):<EOL><INDENT>tensor = tf.expand_dims(tensor, ax)<EOL><DEDENT><DEDENT>tile_shape = np.array(shape) / np.array(shape_as_list(tensor))<EOL>return tf.tile(tensor, tile_shape)<EOL>
|
Reverse summing over a dimension.
See utils.py.
Args:
tensor: The tensor that was reduced.
shape: A list, the original shape of the tensor before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton axes.
Returns:
A tensor with axes broadcast to match the shape of the original tensor.
|
f4074:m6
|
def matmul_adjoint_x(dz, x, y, transpose_a, transpose_b):
|
if not transpose_a and not transpose_b:<EOL><INDENT>return tf.matmul(dz, y, transpose_b=True)<EOL><DEDENT>elif not transpose_a and transpose_b:<EOL><INDENT>return tf.matmul(dz, y)<EOL><DEDENT>elif transpose_a and not transpose_b:<EOL><INDENT>return tf.matmul(y, dz, transpose_b=True)<EOL><DEDENT>else: <EOL><INDENT>return tf.matmul(y, dz, transpose_a=True, transpose_b=True)<EOL><DEDENT>
|
Implementation of dtfmatmul wrt x, separate for readability.
|
f4074:m7
|
def matmul_adjoint_y(dz, x, y, transpose_a, transpose_b):
|
if not transpose_a and not transpose_b:<EOL><INDENT>return tf.matmul(x, dz, transpose_a=True)<EOL><DEDENT>elif not transpose_a and transpose_b:<EOL><INDENT>return tf.matmul(dz, x, transpose_a=True)<EOL><DEDENT>elif transpose_a and not transpose_b:<EOL><INDENT>return tf.matmul(x, dz)<EOL><DEDENT>else: <EOL><INDENT>return tf.matmul(dz, x, transpose_a=True, transpose_b=True)<EOL><DEDENT>
|
Implementation of dtfmatmul, separate for readability.
|
f4074:m8
|
def create_grad(node, namer, tangent=False):
|
if not isinstance(node, (gast.Subscript, gast.Name, gast.Str)):<EOL><INDENT>raise TypeError<EOL><DEDENT>if anno.hasanno(node, '<STR_LIT>'):<EOL><INDENT>return create_grad(anno.getanno(node, '<STR_LIT>'), namer, tangent)<EOL><DEDENT>def _name_grad(node):<EOL><INDENT>if not isinstance(node, gast.Name):<EOL><INDENT>raise TypeError<EOL><DEDENT>varname = node.id<EOL>name = namer.grad(varname, tangent)<EOL>grad_node = gast.Name(<EOL>id=name, ctx=None, annotation=None)<EOL>anno.setanno(grad_node, '<STR_LIT>', node)<EOL>return grad_node<EOL><DEDENT>if isinstance(node, gast.Subscript):<EOL><INDENT>grad_node = create_grad(node.value, namer, tangent=tangent)<EOL>grad_node.ctx = gast.Load()<EOL>return gast.Subscript(value=grad_node, slice=node.slice, ctx=None)<EOL><DEDENT>elif isinstance(node, gast.Str):<EOL><INDENT>grad_node = create_grad(<EOL>gast.Name(id=node.s, ctx=None, annotation=None), namer, tangent=tangent)<EOL>return gast.Str(grad_node.id)<EOL><DEDENT>else:<EOL><INDENT>return _name_grad(node)<EOL><DEDENT>
|
Given a variable, create a variable for the gradient.
Args:
node: A node to create a gradient for, can be a normal variable (`x`) or a
subscript (`x[i]`).
namer: The namer object which will determine the name to use for the
gradient.
tangent: Whether a tangent (instead of adjoint) is created.
Returns:
node: A node representing the gradient with the correct name e.g. the
gradient of `x[i]` is `dx[i]`.
Note that this returns an invalid node, with the `ctx` attribute
missing. It is assumed that this attribute is filled in later.
Node has an `adjoint_var` annotation referring to the node it is an
adjoint of.
|
f4075:m0
|
def create_temp_grad(node, namer, tangent=False):
|
if not isinstance(node, (gast.Subscript, gast.Name)):<EOL><INDENT>raise TypeError<EOL><DEDENT>def _name_temp_grad(node):<EOL><INDENT>name = namer.temp_grad(node.id, tangent)<EOL>temp_node = gast.Name(id=name, annotation=None, ctx=None)<EOL>return temp_node<EOL><DEDENT>if isinstance(node, gast.Subscript):<EOL><INDENT>temp_node = _name_temp_grad(node.value)<EOL><DEDENT>else:<EOL><INDENT>temp_node = _name_temp_grad(node)<EOL><DEDENT>anno.setanno(temp_node, '<STR_LIT>', node)<EOL>return temp_node<EOL>
|
Create a variable to store partial gradients.
Args:
node: See `create_grad`.
namer: See `create_grad`.
tangent: See `create_grad`.
Returns:
node: See `create_grad`. Returns a node representing the partial gradient.
Note that this is always a simple variable e.g. the temporary partial
of `x[i]` can be something like `_dxi`.
Nodes are given an annotation `temp_adjoint_var`.
|
f4075:m1
|
def create_temp(node, namer):
|
if isinstance(node, gast.Name):<EOL><INDENT>name = node.id<EOL><DEDENT>elif isinstance(node, (gast.Attribute, gast.Subscript)):<EOL><INDENT>name = node.value.id<EOL><DEDENT>else:<EOL><INDENT>raise TypeError<EOL><DEDENT>temp_node = gast.Name(id=namer.temp(name), annotation=None, ctx=None)<EOL>anno.setanno(temp_node, '<STR_LIT>', node)<EOL>return temp_node<EOL>
|
Create a temporary variable.
Args:
node: Create a temporary variable to store this variable in.
namer: A naming object that guarantees the names are unique.
Returns:
node: See `create_grad`. Returns a temporary variable, which is always a
simple variable annotated with `temp_var`.
|
f4075:m2
|
def autodiff_ast(func, wrt, motion, mode, preserve_result, check_dims, verbose):
|
node = annotate.resolve_calls(func)<EOL>node = desugar.explicit_loop_indexes(node)<EOL>fence.validate(node, inspect.getsource(func))<EOL>node = anf_.anf(node)<EOL>if verbose >= <NUM_LIT:2>:<EOL><INDENT>print('<STR_LIT>')<EOL>print(quoting.to_source(node))<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>node, required, stack = reverse_ad.reverse_ad(node.body[<NUM_LIT:0>], wrt,<EOL>preserve_result, check_dims)<EOL>if verbose >= <NUM_LIT:2>:<EOL><INDENT>print('<STR_LIT>')<EOL>print(quoting.to_source(node))<EOL><DEDENT>if motion == '<STR_LIT>':<EOL><INDENT>node = reverse_ad.split(node, stack)<EOL><DEDENT>else:<EOL><INDENT>node = reverse_ad.joint(node)<EOL><DEDENT>if verbose >= <NUM_LIT:2>:<EOL><INDENT>print('<STR_LIT>')<EOL>print(quoting.to_source(node))<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>node, required = forward_ad.forward_ad(node.body[<NUM_LIT:0>], wrt, preserve_result,<EOL>check_dims)<EOL><DEDENT>return node, required<EOL>
|
Perform AD on a single function and return the AST.
Args:
See `grad`.
Returns:
node: The AST of a module containing the adjoint and primal function
definitions.
required: A list of non-built in functions that this function called, and
of which the primals and adjoints need to be made available in order
for the returned function to run.
|
f4076:m0
|
def autodiff_tree(func, wrt, motion, mode, preserve_result, check_dims,<EOL>verbose):
|
<EOL>import tangent<EOL>namespace = {'<STR_LIT>': tangent, '<STR_LIT>': numpy}<EOL>done = set()<EOL>final = gast.Module(body=[])<EOL>namespace.update(six.get_function_globals(func))<EOL>node, required = autodiff_ast(func, wrt, motion, mode, preserve_result,<EOL>check_dims, verbose)<EOL>final.body.extend(node.body)<EOL>to_do = set(required)<EOL>if motion == '<STR_LIT>' and mode == '<STR_LIT>':<EOL><INDENT>done.add((func, wrt))<EOL>to_do -= done<EOL><DEDENT>while to_do:<EOL><INDENT>func, wrt = to_do.pop()<EOL>namespace.update(six.get_function_globals(func))<EOL>node, required = autodiff_ast(<EOL>func=func,<EOL>wrt=wrt,<EOL>motion='<STR_LIT>',<EOL>mode=mode,<EOL>preserve_result=True,<EOL>check_dims=False,<EOL>verbose=verbose)<EOL>final.body.extend(node.body)<EOL>done.add((func, wrt))<EOL>to_do.update(required)<EOL>to_do -= done<EOL><DEDENT>return final, namespace<EOL>
|
Perform AD on all functions in a call tree.
This function walks the call tree and differentiates each function in it. It
also ensures that the global namespaces that each function in the call tree
was in are merged.
The `tangent` and `numpy` packages are added to the namespace here, so that
the gradient templates can assume that they are present.
Args:
See `grad`.
Returns:
final: A single module which contains the primals and adjoints of all the
functions in the call tree.
namespace: A merged dictionary with all the variables in the global
namespaces of each function. The primals and adjoints need access to
these in order to execute.
|
f4076:m1
|
def vjp(func,<EOL>wrt=(<NUM_LIT:0>,),<EOL>optimized=True,<EOL>check_dims=True,<EOL>preserve_result=False,<EOL>verbose=<NUM_LIT:0>):
|
return autodiff(<EOL>func,<EOL>wrt=wrt,<EOL>motion='<STR_LIT>',<EOL>mode='<STR_LIT>',<EOL>optimized=optimized,<EOL>preserve_result=preserve_result,<EOL>input_derivative=INPUT_DERIVATIVE.Required,<EOL>check_dims=check_dims,<EOL>verbose=verbose)<EOL>
|
Convenience function to produce vector-Jacobian products.
See `autodiff` for function arguments.
Uses reverse-mode joint-motion autodiff to produce the VJP.
|
f4076:m2
|
def jvp(func,<EOL>wrt=(<NUM_LIT:0>,),<EOL>optimized=True,<EOL>check_dims=True,<EOL>preserve_result=False,<EOL>verbose=<NUM_LIT:0>):
|
return autodiff(<EOL>func,<EOL>wrt=wrt,<EOL>mode='<STR_LIT>',<EOL>optimized=optimized,<EOL>preserve_result=preserve_result,<EOL>input_derivative=INPUT_DERIVATIVE.Required,<EOL>check_dims=check_dims,<EOL>verbose=verbose)<EOL>
|
Convenience function to produce Jacobian-vector products.
See `autodiff` for function arguments.
Uses forward-mode autodiff to produce the JVP.
|
f4076:m3
|
def autodiff(func,<EOL>wrt=(<NUM_LIT:0>,),<EOL>optimized=True,<EOL>motion='<STR_LIT>',<EOL>mode='<STR_LIT>',<EOL>preserve_result=False,<EOL>check_dims=True,<EOL>input_derivative=INPUT_DERIVATIVE.Required,<EOL>verbose=<NUM_LIT:0>):
|
<EOL>func = getattr(func, '<STR_LIT>', func)<EOL>node, namespace = autodiff_tree(func, wrt, motion, mode, preserve_result,<EOL>check_dims, verbose)<EOL>if mode == '<STR_LIT>' and motion == '<STR_LIT>':<EOL><INDENT>node.body[<NUM_LIT:0>] = _create_joint(node.body[<NUM_LIT:0>], func, wrt, input_derivative)<EOL>if verbose >= <NUM_LIT:2>:<EOL><INDENT>print('<STR_LIT>')<EOL>print(quoting.to_source(node))<EOL><DEDENT><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>node = _create_forward(node)<EOL><DEDENT>if optimized:<EOL><INDENT>node = optimization.optimize(node)<EOL><DEDENT>node = comments.remove_repeated_comments(node)<EOL>if verbose >= <NUM_LIT:1>:<EOL><INDENT>print(quoting.to_source(node))<EOL><DEDENT>module = compile_.compile_file(node, namespace)<EOL>if mode == '<STR_LIT>' or motion == '<STR_LIT>':<EOL><INDENT>return getattr(module, node.body[<NUM_LIT:0>].name)<EOL><DEDENT>else:<EOL><INDENT>forward = getattr(module, node.body[<NUM_LIT:0>].name)<EOL>backward = getattr(module, node.body[<NUM_LIT:1>].name)<EOL>import tangent<EOL>def df(*args, **kwargs):<EOL><INDENT>_stack = tangent.Stack()<EOL>init_grad = kwargs.pop('<STR_LIT>', <NUM_LIT:1.0>)<EOL>forward(_stack, *args, **kwargs)<EOL>dx = backward(_stack, init_grad, *args, **kwargs)<EOL>if len(dx) == <NUM_LIT:1>:<EOL><INDENT>dx, = dx<EOL><DEDENT>return dx<EOL><DEDENT>return df<EOL><DEDENT>
|
Build the vector-Jacobian or Jacobian-vector product of a function `func`.
For a vector-Jacobian product (reverse-mode autodiff):
This function proceeds by finding the primals and adjoints of all the
functions in the call tree.
For a Jacobian-vector product (forward-mode autodiff):
We first find the primals and tangents of all functions in the call tree.
It then wraps the top level function (i.e. the
one passed as `func`) in a slightly more user-friendly interface. It then
compiles the function and attaches to it the global namespace it needs to
run.
Args:
func: The function to take the gradient of.
wrt: A tuple of argument indices to differentiate with respect to. By
default the derivative is taken with respect to the first argument.
optimized: Whether to optimize the gradient function (`True` by default).
motion: Either 'split' (separate functions for forward and backward pass)
or 'joint' motion (a single combined function). Joint mode is the
default.
mode: Either 'forward' or 'reverse' mode. Forward mode is more efficient
when the input dimensionality is lower than the output dimensionality,
whereas it is the opposite for reverse mode.
input_derivative: An enum indicating whether the user must supply an input
derivative, and if not, what the default value is. See the
possible values of INPUT_DERIVATIVE in this file.
preserve_result: A boolean indicating whether or not the generated gradient
function should also return the output of the original function.
If False, the return signature of the input and output functions will be
> val = func(*args)
> df = grad(func,preserve_result=False)
> gradval = df(*args)
If True,
> val = func(*args)
> df = grad(func,preserve_result=True)
> gradval, val = df(*args)
Note that if taking gradients with respect to multiple arguments,
the primal value will be appended to the return signature. Ex:
> val = func(x,y)
> df = grad(func,wrt=(0,1),preserve_result=True)
> dx,dy,val = df(x,y)
verbose: If 1 the source code of the generated functions will be
output to stdout at various stages of the process for debugging
purposes. If > 1, all intermediate code generation steps will print.
Returns:
df: A function that calculates a derivative (see file-level documentation
above
for the kinds of derivatives available) with respect to arguments
specified in `wrt`, using forward or reverse mode according to `mode`.
If using reverse mode, the gradient is calculated in either split
or joint motion according to the value passed in `motion`. If
`preserve_result` is True, the function will also return the original
result of `func`.
|
f4076:m4
|
def grad(func,<EOL>wrt=(<NUM_LIT:0>,),<EOL>optimized=True,<EOL>preserve_result=False,<EOL>check_dims=True,<EOL>verbose=<NUM_LIT:0>):
|
return autodiff(<EOL>func,<EOL>wrt=wrt,<EOL>motion='<STR_LIT>',<EOL>mode='<STR_LIT>',<EOL>optimized=optimized,<EOL>preserve_result=preserve_result,<EOL>check_dims=check_dims,<EOL>input_derivative=INPUT_DERIVATIVE.DefaultOne,<EOL>verbose=verbose)<EOL>
|
Return the gradient of a function `func`.
Args:
func: The function to take the gradient of.
wrt: A tuple of argument indices to differentiate with respect to. By
default the derivative is taken with respect to the first argument.
optimized: Whether to optimize the gradient function (`True` by default).
preserve_result: A boolean indicating whether or not the generated gradient
function should also return the output of the original function.
If False, the return signature of the input and output functions will be
> val = func(*args)
> df = grad(func,preserve_result=False)
> gradval = df(*args)
If True,
> val = func(*args)
> df = grad(func,preserve_result=True)
> gradval, val = df(*args)
Note that if taking gradients with respect to multiple arguments,
the primal value will be appended to the return signature. Ex:
> val = func(x,y)
> df = grad(func,wrt=(0,1),preserve_result=True)
> dx,dy,val = df(x,y)
check_dims: A boolean (`True` by default) indicating whether to check
that the result of the original function `func` is a scalar, raising
an error if it is not.
Gradients are only valid for scalar-valued outputs, so we check
this by defualt.
verbose: If 1 the source code of the generated functions will be
output to stdout at various stages of the process for debugging
purposes. If > 1, all intermediate code generation steps will print.
Returns:
df: A function that calculates the gradient with respect to arguments
specified in `wrt`, using forward or reverse mode according to `mode`.
If using reverse mode, the gradient is calculated in either split
or joint motion according to the value passed in `motion`. If
`preserve_result` is True, the function will also return the original
result of `func`.
|
f4076:m5
|
def _create_joint(fwdbwd, func, wrt, input_derivative):
|
<EOL>retval = fwdbwd.body[-<NUM_LIT:1>]<EOL>if len(retval.value.elts) == <NUM_LIT:1>:<EOL><INDENT>retval.value = retval.value.elts[<NUM_LIT:0>]<EOL><DEDENT>init_stack = quoting.quote('<STR_LIT>' % fwdbwd.args.args[<NUM_LIT:0>].id)<EOL>init_stack = comments.add_comment(init_stack, '<STR_LIT>')<EOL>fwdbwd.body = [init_stack] + fwdbwd.body<EOL>grad_name = fwdbwd.args.args[<NUM_LIT:1>].id<EOL>fwdbwd.args = quoting.parse_function(func).body[<NUM_LIT:0>].args<EOL>fwdbwd.name = naming.joint_name(func, wrt)<EOL>fwdbwd = ast_.append_args(fwdbwd, [grad_name])<EOL>if input_derivative == INPUT_DERIVATIVE.DefaultOne:<EOL><INDENT>fwdbwd.args.defaults.append(quoting.quote('<STR_LIT:1.0>'))<EOL><DEDENT>return fwdbwd<EOL>
|
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tuple, even if the
gradient of only one input was required. We unpack the tuple if it is of
length one.
Args:
fwdbwd: An AST. The function definition of the joint primal and adjoint.
func: A function handle. The original function that was differentiated.
wrt: A tuple of integers. The arguments with respect to which we differentiated.
Returns:
The function definition of the new function.
|
f4076:m6
|
def _create_forward(out_node):
|
retval = out_node.body[<NUM_LIT:0>].body[-<NUM_LIT:1>]<EOL>if len(retval.value.elts) == <NUM_LIT:1>:<EOL><INDENT>retval.value = retval.value.elts[<NUM_LIT:0>]<EOL><DEDENT>return out_node<EOL>
|
Create a user-friendly forward function.
Ensures that a single value instead of a tuple is returned if the user asked
for the gradient with respect to only one input.
Args:
out_node: The function definition AST.
Returns:
The function definition with potentially changed return statement.
|
f4076:m7
|
def get_push_pop():
|
push = copy.deepcopy(PUSH)<EOL>pop = copy.deepcopy(POP)<EOL>anno.setanno(push, '<STR_LIT>', pop)<EOL>anno.setanno(push, '<STR_LIT>', True)<EOL>anno.setanno(pop, '<STR_LIT>', push)<EOL>op_id = _generate_op_id()<EOL>return push, pop, op_id<EOL>
|
Create pop and push nodes that are linked.
Returns:
A push and pop node which have `push_func` and `pop_func` annotations
respectively, identifying them as such. They also have a `pop` and
`push` annotation respectively, which links the push node to the pop
node and vice versa.
|
f4077:m1
|
def get_push_pop_stack():
|
push = copy.deepcopy(PUSH_STACK)<EOL>pop = copy.deepcopy(POP_STACK)<EOL>anno.setanno(push, '<STR_LIT>', pop)<EOL>anno.setanno(push, '<STR_LIT>', True)<EOL>anno.setanno(pop, '<STR_LIT>', push)<EOL>op_id = _generate_op_id()<EOL>return push, pop, op_id<EOL>
|
Create pop and push nodes for substacks that are linked.
Returns:
A push and pop node which have `push_func` and `pop_func` annotations
respectively, identifying them as such. They also have a `pop` and
`push` annotation respectively, which links the push node to the pop
node and vice versa.
|
f4077:m2
|
def reverse_ad(node, wrt, preserve_result, check_dims):
|
if not isinstance(node, gast.FunctionDef):<EOL><INDENT>raise TypeError<EOL><DEDENT>cfg.forward(node, cfg.Active(wrt))<EOL>ad = ReverseAD(wrt, preserve_result, check_dims)<EOL>pri, adj = ad.visit(node)<EOL>mod = gast.Module(body=[pri, adj])<EOL>mod = annotate.find_stacks(mod)<EOL>return mod, ad.required, ad.stack<EOL>
|
Perform reverse-mode AD on an AST.
This function analyses the AST to determine which variables are active and
proceeds by taking the naive derivative. Before returning the primal and
adjoint it annotates push and pop statements as such.
Args:
node: A `FunctionDef` AST node.
wrt: A tuple of argument indices with respect to which we take the
derivative.
preserve_result: A boolean indicating whether the generated
derivative function should also return the original return value.
check_dims: A boolean indicating whether the seed derivatives should have
their dimensions checked to match their primal counterpart.
Returns:
mod: A `Module` node containing the naive primal and adjoint of the
function which can be fed to the `split` and `joint` functions.
required: A list of tuples of functions and argument indices. These
functions were called by the function but did not have an adjoint.
|
f4077:m3
|
def store_state(node, reaching, defined, stack):
|
defs = [def_ for def_ in reaching if not isinstance(def_[<NUM_LIT:1>], gast.arguments)]<EOL>if not len(defs):<EOL><INDENT>return node<EOL><DEDENT>reaching, original_defs = zip(*defs)<EOL>assignments = []<EOL>for id_ in set(reaching) - defined:<EOL><INDENT>assignments.append(quoting.quote('<STR_LIT>'.format(id_)))<EOL><DEDENT>store = []<EOL>load = []<EOL>for id_, def_ in zip(reaching, original_defs):<EOL><INDENT>if isinstance(<EOL>def_, gast.Assign) and '<STR_LIT>' in quoting.unquote(def_.value):<EOL><INDENT>push, pop, op_id = get_push_pop_stack()<EOL><DEDENT>else:<EOL><INDENT>push, pop, op_id = get_push_pop()<EOL><DEDENT>store.append(<EOL>template.replace(<EOL>'<STR_LIT>',<EOL>push=push,<EOL>val=id_,<EOL>_stack=stack,<EOL>op_id=op_id))<EOL>load.append(<EOL>template.replace(<EOL>'<STR_LIT>',<EOL>pop=pop,<EOL>val=id_,<EOL>_stack=stack,<EOL>op_id=op_id))<EOL><DEDENT>body, return_ = node.body[<NUM_LIT:0>].body[:-<NUM_LIT:1>], node.body[<NUM_LIT:0>].body[-<NUM_LIT:1>]<EOL>node.body[<NUM_LIT:0>].body = assignments + body + store + [return_]<EOL>node.body[<NUM_LIT:1>].body = load[::-<NUM_LIT:1>] + node.body[<NUM_LIT:1>].body<EOL>return node<EOL>
|
Push the final state of the primal onto the stack for the adjoint.
Python's scoping rules make it possible for variables to not be defined in
certain blocks based on the control flow path taken at runtime. In order to
make sure we don't try to push non-existing variables onto the stack, we
defined these variables explicitly (by assigning `None` to them) at the
beginning of the function.
All the variables that reach the return statement are pushed onto the
stack, and in the adjoint they are popped off in reverse order.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
reaching: The variable definitions that reach the end of the primal.
defined: The variables defined at the end of the primal.
stack: The stack node to use for storing and restoring state.
Returns:
node: A node with the requisite pushes and pops added to make sure that
state is transferred between primal and adjoint split motion calls.
|
f4077:m4
|
def split(node, stack):
|
node, defined, reaching = _fix(node)<EOL>node = store_state(node, reaching, defined, stack)<EOL>anno.clearanno(node)<EOL>return node<EOL>
|
Carry over the state from the primal to the adjoint.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
stack: The stack node to use for storing and restoring state.
Returns:
func: A `Module` node with two function definitions containing the primal
and adjoint respectively.
|
f4077:m5
|
def joint(node):
|
node, _, _ = _fix(node)<EOL>body = node.body[<NUM_LIT:0>].body[:-<NUM_LIT:1>] + node.body[<NUM_LIT:1>].body<EOL>func = gast.Module(body=[gast.FunctionDef(<EOL>name=node.body[<NUM_LIT:0>].name, args=node.body[<NUM_LIT:1>].args, body=body,<EOL>decorator_list=[], returns=None)])<EOL>anno.clearanno(func)<EOL>return func<EOL>
|
Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoint.
|
f4077:m6
|
def _fix(node):
|
<EOL>pri_cfg = cfg.CFG.build_cfg(node.body[<NUM_LIT:0>])<EOL>defined = cfg.Defined()<EOL>defined.visit(pri_cfg.entry)<EOL>reaching = cfg.ReachingDefinitions()<EOL>reaching.visit(pri_cfg.entry)<EOL>cfg.forward(node.body[<NUM_LIT:1>], cfg.Defined())<EOL>cfg.forward(node.body[<NUM_LIT:1>], cfg.ReachingDefinitions())<EOL>fixes.CleanStack().visit(node)<EOL>fixes.FixStack().visit(node.body[<NUM_LIT:0>])<EOL>fixes.CleanGrad().visit(node.body[<NUM_LIT:1>])<EOL>fixes.FixGrad().visit(node.body[<NUM_LIT:1>])<EOL>return node, defined.exit, reaching.exit<EOL>
|
Fix the naive construction of the adjont.
See `fixes.py` for details.
This function also returns the result of reaching definitions analysis so
that `split` mode can use this to carry over the state from primal to
adjoint.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
node: A module with the primal and adjoint function with additional
variable definitions and such added so that pushes onto the stack and
gradient accumulations are all valid.
defined: The variables defined at the end of the primal.
reaching: The variable definitions that reach the end of the primal.
|
f4077:m7
|
def visit(self, node):
|
method = '<STR_LIT>' + node.__class__.__name__<EOL>if not hasattr(self, method):<EOL><INDENT>raise ValueError('<STR_LIT>' % node.__class__.__name__)<EOL><DEDENT>visitor = getattr(self, method)<EOL>if anno.hasanno(node, '<STR_LIT>'):<EOL><INDENT>self.active_variables = anno.getanno(node, '<STR_LIT>')<EOL><DEDENT>pri, adj = visitor(node)<EOL>if isinstance(pri, gast.AST):<EOL><INDENT>anno.setdefaultanno(pri, '<STR_LIT>', adj)<EOL><DEDENT>else:<EOL><INDENT>for node in pri:<EOL><INDENT>anno.setdefaultanno(node, '<STR_LIT>', adj)<EOL><DEDENT><DEDENT>if isinstance(adj, gast.AST):<EOL><INDENT>anno.setdefaultanno(adj, '<STR_LIT>', pri)<EOL><DEDENT>else:<EOL><INDENT>for node in adj:<EOL><INDENT>anno.setdefaultanno(node, '<STR_LIT>', pri)<EOL><DEDENT><DEDENT>return pri, adj<EOL>
|
Visit a node.
This method is largely modelled after the ast.NodeTransformer class.
Args:
node: The node to visit.
Returns:
A tuple of the primal and adjoint, each of which is a node or a list of
nodes.
|
f4077:c0:m1
|
def is_active(self, node):
|
<EOL>if (isinstance(node.value, gast.Call) and<EOL>anno.getanno(node.value, '<STR_LIT>', False) == utils.pop):<EOL><INDENT>return True<EOL><DEDENT>for succ in gast.walk(node.value):<EOL><INDENT>if (isinstance(succ, gast.Name) and isinstance(succ.ctx, gast.Load) and<EOL>succ.id in self.active_variables):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Checks whether a statement is active.
An assignment is active when its right hand side contains active
variables.
Args:
node: an instance of gast.Assign
Returns:
Whether the statement is active.
|
f4077:c0:m4
|
def visit_statements(self, nodes):
|
primals, adjoints = [], collections.deque()<EOL>for node in nodes:<EOL><INDENT>primal, adjoint = self.visit(node)<EOL>if not isinstance(primal, list):<EOL><INDENT>primal = [primal]<EOL><DEDENT>if not isinstance(adjoint, list):<EOL><INDENT>adjoint = [adjoint]<EOL><DEDENT>primals.extend(filter(None, primal))<EOL>adjoints.extendleft(filter(None, adjoint[::-<NUM_LIT:1>]))<EOL><DEDENT>return primals, list(adjoints)<EOL>
|
Generate the adjoint of a series of statements.
|
f4077:c0:m6
|
def visit_With(self, node):
|
if ast_.is_insert_grad_of_statement(node):<EOL><INDENT>primal = []<EOL>adjoint = node.body<EOL>if isinstance(adjoint[<NUM_LIT:0>], gast.With):<EOL><INDENT>_, adjoint = self.visit(adjoint[<NUM_LIT:0>])<EOL><DEDENT>node.body[<NUM_LIT:0>] = comments.add_comment(node.body[<NUM_LIT:0>], '<STR_LIT>')<EOL>replacements = {}<EOL>for item in node.items:<EOL><INDENT>if (not isinstance(item.context_expr.args[<NUM_LIT:0>], gast.Name) or<EOL>not isinstance(item.optional_vars, gast.Name)):<EOL><INDENT>raise ValueError<EOL><DEDENT>replacements[item.optional_vars.id] = create.create_grad(<EOL>item.context_expr.args[<NUM_LIT:0>], self.namer)<EOL><DEDENT>template.ReplaceTransformer(replacements).visit(node)<EOL>return primal, adjoint<EOL><DEDENT>else:<EOL><INDENT>return node, []<EOL><DEDENT>
|
Deal with the special with insert_grad_of(x) statement.
|
f4077:c0:m9
|
def visit_Assign(self, node):
|
if len(node.targets) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if anno.hasanno(node, '<STR_LIT>'):<EOL><INDENT>orig_src = anno.getanno(node, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>orig_src = quoting.unquote(node)<EOL><DEDENT>self.orig_target = ast_.copy_node(node.targets[<NUM_LIT:0>])<EOL>if isinstance(node.value, gast.Call) andanno.hasanno(node.value, '<STR_LIT>') andanno.getanno(node.value, '<STR_LIT>') in (utils.Stack, utils.pop_stack):<EOL><INDENT>push, pop, op_id = get_push_pop_stack()<EOL><DEDENT>else:<EOL><INDENT>push, pop, op_id = get_push_pop()<EOL><DEDENT>push_stack, pop_stack, op_id_stack = get_push_pop_stack()<EOL>store = template.replace(<EOL>'<STR_LIT>',<EOL>push=push,<EOL>y=self.orig_target,<EOL>_stack=self.stack,<EOL>op_id=op_id)<EOL>create_substack = template.replace(<EOL>'<STR_LIT>', substack=self.substack)<EOL>store_substack = template.replace(<EOL>'<STR_LIT>',<EOL>push=push_stack,<EOL>stack=self.stack,<EOL>substack=self.substack,<EOL>op_id=op_id_stack)<EOL>restore = template.replace(<EOL>'<STR_LIT>',<EOL>_stack=self.stack,<EOL>pop=pop,<EOL>y=ast_.copy_node(self.orig_target),<EOL>op_id=op_id)<EOL>restore_substack = template.replace(<EOL>'<STR_LIT>',<EOL>pop=pop_stack,<EOL>stack=self.stack,<EOL>substack=self.substack,<EOL>op_id=op_id_stack)<EOL>reset = template.replace(<EOL>'<STR_LIT>',<EOL>y=self.orig_target,<EOL>init_grad=utils.INIT_GRAD,<EOL>namer=self.namer,<EOL>replace_grad=template.Replace.FULL)<EOL>if not self.is_active(node):<EOL><INDENT>return [store, node], [restore, reset]<EOL><DEDENT>self.target = create.create_temp(self.orig_target, self.namer)<EOL>create_tmp = template.replace(<EOL>'<STR_LIT>', tmp=self.target, y=self.orig_target)<EOL>try:<EOL><INDENT>fx, adjoint_rhs = self.visit(node.value)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>context = [t.id if hasattr(t, '<STR_LIT:id>') else t for t in node.targets]<EOL>raise ValueError(<EOL>'<STR_LIT>' % (context, e))<EOL><DEDENT>if not isinstance(adjoint_rhs, list):<EOL><INDENT>adjoint_rhs = [adjoint_rhs]<EOL><DEDENT>accumulations = []<EOL>for n in adjoint_rhs:<EOL><INDENT>for succ in gast.walk(n):<EOL><INDENT>if anno.hasanno(succ, '<STR_LIT>'):<EOL><INDENT>xi = anno.getanno(succ, '<STR_LIT>')<EOL>dxi_partial = ast_.copy_node(succ)<EOL>accumulations.append(template.replace(<EOL>'<STR_LIT>',<EOL>namer=self.namer, replace_grad=template.Replace.FULL,<EOL>xi=xi, dxi_partial=dxi_partial, add_grad=utils.ADD_GRAD))<EOL><DEDENT><DEDENT><DEDENT>if isinstance(fx, gast.Assign):<EOL><INDENT>assign = [fx]<EOL><DEDENT>elif (isinstance(fx, list) and<EOL>any([isinstance(ifx, gast.Assign) for ifx in fx])):<EOL><INDENT>assign = fx<EOL><DEDENT>else:<EOL><INDENT>assign = template.replace(<EOL>'<STR_LIT>', y=ast_.copy_node(self.orig_target), fx=fx)<EOL>assign = [assign]<EOL><DEDENT>primal = [store, create_substack, store_substack] + assign<EOL>adjoint = [create_tmp, restore_substack, restore<EOL>] + adjoint_rhs + [reset] + accumulations<EOL>if (isinstance(self.orig_target, gast.Subscript) and<EOL>isinstance(self.orig_target.slice.value, gast.Name)):<EOL><INDENT>push, pop, op_id = get_push_pop()<EOL>i = self.orig_target.slice.value<EOL>push_index = template.replace(<EOL>'<STR_LIT>',<EOL>push=push,<EOL>i=i,<EOL>_stack=self.stack,<EOL>op_id=op_id)<EOL>pop_index = template.replace(<EOL>'<STR_LIT>',<EOL>pop=pop,<EOL>i=i,<EOL>_stack_=self.stack,<EOL>op_id=op_id)<EOL>primal.insert(len(primal), push_index)<EOL>adjoint.insert(<NUM_LIT:0>, pop_index)<EOL><DEDENT>for i, adj in enumerate(adjoint):<EOL><INDENT>adjoint[i] = comments.add_comment(adj, '<STR_LIT>' % orig_src)<EOL><DEDENT>return primal, adjoint<EOL>
|
Visit assignment statement.
|
f4077:c0:m13
|
def primal_and_adjoint_for_tracing(self, node):
|
primal_template = grads.primals[tracing.Traceable]<EOL>adjoint_template = grads.adjoints[tracing.Traceable]<EOL>to_pack = node.args<EOL>target = ast_.copy_node(self.orig_target)<EOL>vjp = quoting.quote(self.namer.unique('<STR_LIT>' % node.func.id))<EOL>tmp = create.create_temp(quoting.quote('<STR_LIT>'), self.namer)<EOL>assert len(node.keywords) == <NUM_LIT:0><EOL>primal = template.replace(<EOL>primal_template,<EOL>namer=self.namer,<EOL>result=target,<EOL>fn=node.func,<EOL>tmp=tmp,<EOL>vjp=vjp,<EOL>args=gast.Tuple(elts=to_pack, ctx=gast.Load()))<EOL>dto_pack = gast.Tuple(<EOL>elts=[create.create_temp_grad(arg, self.namer) for arg in to_pack],<EOL>ctx=gast.Store())<EOL>adjoint = template.replace(<EOL>adjoint_template,<EOL>namer=self.namer,<EOL>result=target,<EOL>vjp=vjp,<EOL>dargs=dto_pack)<EOL>return primal, adjoint<EOL>
|
Build the primal and adjoint of a traceable function.
Args:
node: ast.Call node of a function we wish to trace, instead of transform
Returns:
primal: new ast.Assign node to replace the original primal call
adjoint: new ast.Assign node using the VJP generated in primal to
calculate the adjoint.
|
f4077:c0:m26
|
def visit_Call(self, node):
|
<EOL>func = anno.getanno(node, '<STR_LIT>')<EOL>if func in non_differentiable.NON_DIFFERENTIABLE:<EOL><INDENT>return node, []<EOL><DEDENT>if func == tracing.Traceable:<EOL><INDENT>return self.primal_and_adjoint_for_tracing(node)<EOL><DEDENT>if func in grads.UNIMPLEMENTED_ADJOINTS:<EOL><INDENT>raise errors.ReverseNotImplementedError(func)<EOL><DEDENT>if func not in grads.adjoints:<EOL><INDENT>active_args = tuple(i for i, arg in enumerate(node.args)<EOL>if arg.id in self.active_variables)<EOL>already_counted = False<EOL>for f, a in self.required:<EOL><INDENT>if f.__name__ == func.__name__ and set(a) == set(active_args):<EOL><INDENT>already_counted = True<EOL>break<EOL><DEDENT><DEDENT>if not already_counted:<EOL><INDENT>self.required.append((func, active_args))<EOL><DEDENT>pri_name = naming.primal_name(func, active_args)<EOL>pri_call = gast.Call(<EOL>func=gast.Name(id=pri_name, ctx=gast.Load(), annotation=None),<EOL>args=[self.substack] + node.args,<EOL>keywords=node.keywords)<EOL>anno.setanno(pri_call, '<STR_LIT>', True)<EOL>dy = create.create_grad(self.target, self.namer)<EOL>dy.ctx = gast.Load()<EOL>dx = create.create_grad(node.args[<NUM_LIT:0>], self.namer)<EOL>dx.ctx = gast.Store()<EOL>adj_name = naming.adjoint_name(func, active_args)<EOL>adj_call = gast.Call(<EOL>func=gast.Name(id=adj_name, ctx=gast.Load(), annotation=None),<EOL>args=[self.substack, dy] + node.args,<EOL>keywords=node.keywords)<EOL>anno.setanno(adj_call, '<STR_LIT>', True)<EOL>adjoint = [template.replace('<STR_LIT>', namer=self.namer, dfx=adj_call)]<EOL>for j, i in enumerate(active_args):<EOL><INDENT>adjoint.append(template.replace('<STR_LIT>', namer=self.namer,<EOL>x=node.args[i].id, i=gast.Num(n=j)))<EOL><DEDENT>return pri_call, adjoint<EOL><DEDENT>template_ = grads.adjoints[func]<EOL>sig = funcsigs.signature(template_)<EOL>sig = sig.replace(parameters=list(sig.parameters.values())[<NUM_LIT:1>:])<EOL>kwargs = dict((keyword.arg, keyword.value) for keyword in node.keywords)<EOL>bound_args = sig.bind(*node.args, **kwargs)<EOL>args = quoting.parse_function(template_).body[<NUM_LIT:0>].args<EOL>kwargs = dict(zip(*map(reversed, [args.args, args.defaults])))<EOL>kwargs.update(dict(zip(args.kwonlyargs, args.kw_defaults)))<EOL>for arg, val in kwargs.items():<EOL><INDENT>if arg.id not in bound_args.arguments:<EOL><INDENT>bound_args.arguments[arg.id] = val<EOL><DEDENT><DEDENT>output_name = six.get_function_code(template_).co_varnames[<NUM_LIT:0>]<EOL>arg_replacements = {output_name: ast_.copy_node(self.target)}<EOL>arg_replacements.update(bound_args.arguments)<EOL>packing = []<EOL>flags = six.get_function_code(template_).co_flags<EOL>if flags & inspect.CO_VARARGS:<EOL><INDENT>to_pack = node.args[six.get_function_code(template_).co_argcount - <NUM_LIT:1>:]<EOL>vararg_name = six.get_function_code(template_).co_varnames[-<NUM_LIT:1>]<EOL>target = gast.Name(annotation=None, id=vararg_name, ctx=gast.Store())<EOL>value = gast.Tuple(elts=to_pack, ctx=gast.Load())<EOL>packing = [gast.Assign(targets=[target], value=value)]<EOL>arg_replacements[six.get_function_code(<EOL>template_).co_varnames[-<NUM_LIT:1>]] = target<EOL><DEDENT>adjoint = template.replace(template_, namer=self.namer, **arg_replacements)<EOL>unpacking = []<EOL>if flags & inspect.CO_VARARGS:<EOL><INDENT>dto_pack = [create.create_temp_grad(arg, self.namer)<EOL>for arg in to_pack]<EOL>value = create.create_grad(target, self.namer)<EOL>target = gast.Tuple(elts=dto_pack, ctx=gast.Store())<EOL>unpacking = [gast.Assign(targets=[target], value=value)]<EOL><DEDENT>return node, packing + adjoint + unpacking<EOL>
|
Create adjoint for call.
We don't allow unpacking of parameters, so we know that each argument
gets passed in explicitly, allowing us to create partials for each.
However, templates might perform parameter unpacking (for cases where
the number of arguments is variable) and express their gradient as a
tuple. In this case, we have to unpack this tuple of partials.
|
f4077:c0:m27
|
def anf(node):
|
ANF().visit(node)<EOL>return node<EOL>
|
Turn an AST into ANF-like form.
|
f4078:m0
|
def to_source(node, indentation='<STR_LIT:U+0020>' * <NUM_LIT:4>):
|
if isinstance(node, gast.AST):<EOL><INDENT>node = gast.gast_to_ast(node)<EOL><DEDENT>generator = SourceWithCommentGenerator(indentation, False,<EOL>astor.string_repr.pretty_string)<EOL>generator.visit(node)<EOL>generator.result.append('<STR_LIT:\n>')<EOL>return astor.source_repr.pretty_source(generator.result).lstrip()<EOL>
|
Return source code of a given AST.
|
f4079:m0
|
def parse_function(fn):
|
try:<EOL><INDENT>return parse_string(inspect.getsource(fn))<EOL><DEDENT>except (IOError, OSError) as e:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % e)<EOL><DEDENT>
|
Get the source of a function and return its AST.
|
f4079:m1
|
def parse_string(src):
|
return gast.parse(textwrap.dedent(src))<EOL>
|
Parse a string into an AST.
|
f4079:m2
|
def quote(src_string, return_expr=False):
|
node = parse_string(src_string)<EOL>body = node.body<EOL>if len(body) == <NUM_LIT:1>:<EOL><INDENT>if isinstance(body[<NUM_LIT:0>], gast.Expr) and not return_expr:<EOL><INDENT>out = body[<NUM_LIT:0>].value<EOL><DEDENT>else:<EOL><INDENT>out = body[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>out = node<EOL><DEDENT>return out<EOL>
|
Go from source code to AST nodes.
This function returns a tree without enclosing `Module` or `Expr` nodes.
Args:
src_string: The source code to parse.
return_expr: Whether or not to return a containing expression. This can be
set to `True` if the result is to be part of a series of statements.
Returns:
An AST of the given source code.
|
f4079:m3
|
def unquote(node):
|
return to_source(node).strip()<EOL>
|
Go from an AST to source code.
|
f4079:m4
|
def primal_name(func, wrt):
|
if not isinstance(func, types.FunctionType):<EOL><INDENT>raise TypeError(func)<EOL><DEDENT>varnames = six.get_function_code(func).co_varnames<EOL>return PRIMAL_NAME.format(func.__name__, '<STR_LIT>'.join(varnames[i] for i in wrt))<EOL>
|
Name for the primal of a function.
|
f4080:m0
|
def joint_name(func, wrt):
|
return _adjoint_name(func, wrt, JOINT_NAME)<EOL>
|
Name for a function in joint mode.
|
f4080:m2
|
def adjoint_name(func, wrt):
|
return _adjoint_name(func, wrt, ADJOINT_NAME)<EOL>
|
Name for the adjoint of a function.
|
f4080:m3
|
def tangent_name(func, wrt):
|
return _adjoint_name(func, wrt, TANGENT_NAME)<EOL>
|
Name for a function in forward mode.
|
f4080:m4
|
def get_names(node):
|
names = Names()<EOL>names.visit(node)<EOL>return names.names<EOL>
|
Find the arguments and variables assigned to in a certain node.
|
f4080:m5
|
def uniqify(func):
|
@six.wraps(func)<EOL>def unique(self, *args, **kwargs):<EOL><INDENT>return self.unique(func(self, *args, **kwargs))<EOL><DEDENT>return unique<EOL>
|
Make sure that a method returns a unique name.
|
f4080:m6
|
def uniqify_once(func):
|
@six.wraps(func)<EOL>def unique_once(self, *args, **kwargs):<EOL><INDENT>return self.unique_once(func(self, *args, **kwargs))<EOL><DEDENT>return unique_once<EOL>
|
Make sure that a method returns a unique name.
|
f4080:m7
|
@classmethod<EOL><INDENT>def build(cls, node):<DEDENT>
|
if not isinstance(node, gast.FunctionDef):<EOL><INDENT>raise ValueError<EOL><DEDENT>namer = cls()<EOL>namer.names.update(get_names(node))<EOL>return namer<EOL>
|
Construct a namer object for a given function scope.
|
f4080:c1:m1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.