2018-11-17 18:03:33 -08:00
|
|
|
# Copyright 2018 Google LLC
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# https://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2019-03-12 15:07:52 -04:00
|
|
|
"""
|
2020-01-05 04:35:34 +01:00
|
|
|
Utilities for defining functions composed with transformations.
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
For example,
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
from jax import linear_util as lu
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
wf = lu.wrap_init(f) # Produce a WrappedFun for applying transformations on `f`
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
A `WrappedFun` object represents a function `f`, together with a sequence of
|
|
|
|
nested transformations that are to be applied to the positional and keyword
|
|
|
|
arguments at call time and function return values at return time.
|
|
|
|
A transformation can take some static positional arguments that are given
|
|
|
|
at the wrapping time, and may also return some auxiliary output:
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
wf, aux_out_thunk = trans1(wf, static_arg)
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
We can call the transformed function. First, the transformation is applied
|
|
|
|
to the dynamic args and keyword args to produce new dynamic and keyword args.
|
|
|
|
Then the underlying function is called and the transformation is applied to
|
|
|
|
the results.
|
|
|
|
If there are multiple transformations, they form a stack. The arguments are
|
|
|
|
transformed first with the last applied transformation; the results are
|
|
|
|
transformed first with the first applied transformation.
|
|
|
|
|
|
|
|
res = wf.call_wrapped(dynamic_args, kwargs)
|
|
|
|
# Now `aux_out_thunk()` is the auxiliary output.
|
|
|
|
|
|
|
|
A transformation is written as a generator function that takes zero or more
|
|
|
|
static positional arguments (given when the transformation is instantiated),
|
|
|
|
along with positional and keyword arguments to be transformed.
|
|
|
|
The generator will yield twice:
|
|
|
|
|
|
|
|
@lu.transformation_with_aux
|
|
|
|
def trans1(static_arg, *dynamic_args, **kwargs):
|
|
|
|
...
|
|
|
|
# First yield: pair of transformed (args, kwargs). Get back the results.
|
|
|
|
results = yield (new_dynamic_args, new_kwargs)
|
|
|
|
...
|
|
|
|
# Second yield: pair of (transformed results, and auxiliary output)
|
|
|
|
yield new_results, auxiliary_output
|
2019-03-12 15:07:52 -04:00
|
|
|
|
|
|
|
|
|
|
|
`WrappedFun` objects explicitly represent the set of transformations so that
|
|
|
|
they can be used as dictionary keys for memoization. `WrappedFun` objects
|
2020-01-05 04:35:34 +01:00
|
|
|
compare as equal only if they compute the same function. The static and the
|
|
|
|
dynamic positional arguments for the generators, and also the auxiliary output
|
|
|
|
data must be immutable, because it will be stored in function memoization tables.
|
2019-03-12 15:07:52 -04:00
|
|
|
"""
|
|
|
|
|
2020-10-07 11:14:32 -07:00
|
|
|
import threading
|
2021-01-19 18:38:53 -08:00
|
|
|
from functools import partial
|
2020-07-30 12:59:36 -07:00
|
|
|
from typing import Any, Tuple, Callable
|
2019-10-30 14:57:00 -07:00
|
|
|
import weakref
|
2019-07-22 17:24:10 -04:00
|
|
|
|
2021-01-19 18:38:53 -08:00
|
|
|
from . import core
|
2021-01-11 14:20:32 -08:00
|
|
|
from ._src.util import curry
|
2021-01-19 18:38:53 -08:00
|
|
|
from .tree_util import tree_map
|
2018-11-17 18:03:33 -08:00
|
|
|
|
2020-11-04 09:01:18 -08:00
|
|
|
from ._src import traceback_util
|
2021-01-25 13:23:15 -08:00
|
|
|
|
2021-02-04 09:48:22 -08:00
|
|
|
from .config import config
|
2021-01-25 13:23:15 -08:00
|
|
|
|
2020-10-26 10:03:06 -07:00
|
|
|
traceback_util.register_exclusion(__file__)
|
|
|
|
|
|
|
|
|
2018-11-17 18:03:33 -08:00
|
|
|
class StoreException(Exception): pass
|
|
|
|
|
2019-08-13 09:49:27 -04:00
|
|
|
|
|
|
|
class EmptyStoreValue(object): pass
|
|
|
|
_EMPTY_STORE_VALUE = EmptyStoreValue()
|
|
|
|
|
2018-11-17 18:03:33 -08:00
|
|
|
class Store(object):
|
2020-01-05 04:35:34 +01:00
|
|
|
"""Storage for a value, with checks for overwriting or reading empty store."""
|
2019-08-13 09:49:27 -04:00
|
|
|
__slots__ = ("_val",)
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._val = _EMPTY_STORE_VALUE
|
|
|
|
|
2018-11-17 18:03:33 -08:00
|
|
|
def store(self, val):
|
2020-01-15 15:00:38 -08:00
|
|
|
if self._val is not _EMPTY_STORE_VALUE:
|
|
|
|
raise StoreException("Store occupied")
|
2018-11-17 18:03:33 -08:00
|
|
|
self._val = val
|
|
|
|
|
2020-10-07 12:17:24 -07:00
|
|
|
def reset(self):
|
|
|
|
# This should only be called in exceptional circumstances (e.g. debugging).
|
|
|
|
self._val = _EMPTY_STORE_VALUE
|
|
|
|
|
2018-11-17 18:03:33 -08:00
|
|
|
@property
|
|
|
|
def val(self):
|
|
|
|
if not self:
|
|
|
|
raise StoreException("Store empty")
|
|
|
|
return self._val
|
|
|
|
|
|
|
|
def __nonzero__(self):
|
2019-08-13 09:49:27 -04:00
|
|
|
return self._val is not _EMPTY_STORE_VALUE
|
2018-11-17 18:03:33 -08:00
|
|
|
|
2018-11-21 13:20:44 -08:00
|
|
|
__bool__ = __nonzero__
|
|
|
|
|
2018-11-17 18:03:33 -08:00
|
|
|
|
|
|
|
class WrappedFun(object):
|
2019-03-12 15:28:07 -04:00
|
|
|
"""Represents a function `f` to which `transforms` are to be applied.
|
2019-03-12 15:07:52 -04:00
|
|
|
|
2021-01-15 11:49:19 +11:00
|
|
|
Args:
|
2019-03-12 15:07:52 -04:00
|
|
|
f: the function to be transformed.
|
2020-01-05 04:35:34 +01:00
|
|
|
transforms: a list of `(gen, gen_static_args)` tuples representing
|
|
|
|
transformations to apply to `f.` Here `gen` is a generator function
|
|
|
|
and `gen_static_args` is a tuple of static arguments for the generator. See
|
|
|
|
description at the start of this module for the expected behavior of the
|
|
|
|
generator.
|
|
|
|
stores: a list of out_store for the auxiliary output of the `transforms`.
|
|
|
|
params: extra parameters to pass as keyword arguments to `f`, along with the
|
|
|
|
transformed keyword arguments.
|
2019-03-12 15:07:52 -04:00
|
|
|
"""
|
2019-08-13 09:49:27 -04:00
|
|
|
__slots__ = ("f", "transforms", "stores", "params")
|
|
|
|
|
|
|
|
def __init__(self, f, transforms, stores, params):
|
2018-11-17 18:03:33 -08:00
|
|
|
self.f = f
|
|
|
|
self.transforms = transforms
|
2019-08-13 09:49:27 -04:00
|
|
|
self.stores = stores
|
2019-04-10 22:09:14 -07:00
|
|
|
self.params = params
|
2018-11-17 18:03:33 -08:00
|
|
|
|
2019-08-23 08:17:41 -07:00
|
|
|
@property
|
|
|
|
def __name__(self):
|
|
|
|
return getattr(self.f, '__name__', '<unnamed wrapped function>')
|
|
|
|
|
2020-03-09 20:41:01 +01:00
|
|
|
def wrap(self, gen, gen_static_args, out_store) -> 'WrappedFun':
|
2020-01-05 04:35:34 +01:00
|
|
|
"""Add another transform and its store."""
|
|
|
|
return WrappedFun(self.f, ((gen, gen_static_args),) + self.transforms,
|
2019-08-13 09:49:27 -04:00
|
|
|
(out_store,) + self.stores, self.params)
|
2018-11-17 18:03:33 -08:00
|
|
|
|
2019-10-30 14:57:00 -07:00
|
|
|
def populate_stores(self, stores):
|
2020-01-05 04:35:34 +01:00
|
|
|
"""Copy the values from the `stores` into `self.stores`."""
|
2019-10-30 14:57:00 -07:00
|
|
|
for self_store, other_store in zip(self.stores, stores):
|
2018-11-17 18:03:33 -08:00
|
|
|
if self_store is not None:
|
|
|
|
self_store.store(other_store.val)
|
|
|
|
|
2019-04-10 22:09:14 -07:00
|
|
|
def call_wrapped(self, *args, **kwargs):
|
2020-01-05 04:35:34 +01:00
|
|
|
"""Calls the underlying function, applying the transforms.
|
|
|
|
|
|
|
|
The positional `args` and keyword `kwargs` are passed to the first
|
|
|
|
transformation generator.
|
|
|
|
"""
|
2018-11-17 18:03:33 -08:00
|
|
|
stack = []
|
2020-01-05 04:35:34 +01:00
|
|
|
for (gen, gen_static_args), out_store in zip(self.transforms, self.stores):
|
|
|
|
gen = gen(*(gen_static_args + tuple(args)), **kwargs)
|
2019-04-10 22:09:14 -07:00
|
|
|
args, kwargs = next(gen)
|
2018-11-17 18:03:33 -08:00
|
|
|
stack.append((gen, out_store))
|
2021-01-19 18:38:53 -08:00
|
|
|
gen = gen_static_args = out_store = None
|
2018-11-17 18:03:33 -08:00
|
|
|
|
Interrupt lu transformation generators whenever an exception occurs
This fixes some errors that have been appearing in our CI from time to
time. All transformations are implemented as generators, but they
haven't been explicitly aborted when an exception has been raised.
Instead, they only got closed when they got garbage collected, which
could happen at an unspecified later time, potentially leading to a
corruption of global state, which could have been modified after the
exception was handled.
Note that this implementation doesn't propagate the original exception
into the argument transformations, and doesn't allow them to handle the
error either. Such an extension would be possible, but throwing an
exception into a generator mutates the exception object, clobbering
the nice traceback that we would usually carry. One can work around
those issues, but it feels really hacky and we don't need it right now
anyway, so I figured we'll be better off with the simple thing for the
time being.
2020-09-08 16:10:35 +00:00
|
|
|
try:
|
|
|
|
ans = self.f(*args, **dict(self.params, **kwargs))
|
|
|
|
except:
|
|
|
|
# Some transformations yield from inside context managers, so we have to
|
|
|
|
# interrupt them before reraising the exception. Otherwise they will only
|
|
|
|
# get garbage-collected at some later time, running their cleanup tasks only
|
|
|
|
# after this exception is handled, which can corrupt the global state.
|
|
|
|
while stack:
|
|
|
|
stack.pop()[0].close()
|
|
|
|
raise
|
|
|
|
|
2021-01-19 18:38:53 -08:00
|
|
|
args = kwargs = None
|
2018-11-17 18:03:33 -08:00
|
|
|
while stack:
|
|
|
|
gen, out_store = stack.pop()
|
|
|
|
ans = gen.send(ans)
|
|
|
|
if out_store is not None:
|
|
|
|
ans, side = ans
|
|
|
|
out_store.store(side)
|
|
|
|
|
|
|
|
return ans
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
def transform_to_str(x):
|
2019-08-13 09:49:27 -04:00
|
|
|
i, (gen, args) = x
|
2018-11-17 18:03:33 -08:00
|
|
|
return "{} : {} {}".format(i, fun_name(gen), fun_name(args))
|
|
|
|
transformation_stack = map(transform_to_str, enumerate(self.transforms))
|
|
|
|
return "Wrapped function:\n" + '\n'.join(transformation_stack) + '\nCore: ' + fun_name(self.f) + '\n'
|
|
|
|
|
|
|
|
def __hash__(self):
|
2019-08-13 09:49:27 -04:00
|
|
|
return hash((self.f, self.transforms, self.params))
|
2018-11-17 18:03:33 -08:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
2019-08-13 09:49:27 -04:00
|
|
|
return (self.f == other.f and self.transforms == other.transforms and
|
|
|
|
self.params == other.params)
|
2018-11-17 18:03:33 -08:00
|
|
|
|
|
|
|
@curry
|
2020-03-09 20:41:01 +01:00
|
|
|
def transformation(gen, fun: WrappedFun, *gen_static_args) -> WrappedFun:
|
2020-01-05 04:35:34 +01:00
|
|
|
"""Adds one more transformation to a WrappedFun.
|
|
|
|
Args:
|
|
|
|
gen: the transformation generator function
|
|
|
|
fun: a WrappedFun on which to apply the transformation
|
|
|
|
gen_static_args: static args for the generator function
|
|
|
|
"""
|
|
|
|
return fun.wrap(gen, gen_static_args, None)
|
2018-11-17 18:03:33 -08:00
|
|
|
|
|
|
|
@curry
|
2020-03-09 20:41:01 +01:00
|
|
|
def transformation_with_aux(gen, fun: WrappedFun, *gen_static_args) -> Tuple[WrappedFun, Any]:
|
2020-01-05 04:35:34 +01:00
|
|
|
"""Adds one more transformation with auxiliary output to a WrappedFun."""
|
2018-11-17 18:03:33 -08:00
|
|
|
out_store = Store()
|
|
|
|
out_thunk = lambda: out_store.val
|
2020-01-05 04:35:34 +01:00
|
|
|
return fun.wrap(gen, gen_static_args, out_store), out_thunk
|
2018-11-17 18:03:33 -08:00
|
|
|
|
|
|
|
def fun_name(f):
|
|
|
|
try:
|
|
|
|
return f.__name__
|
|
|
|
except:
|
|
|
|
return str(f)
|
|
|
|
|
2021-10-04 17:54:18 -07:00
|
|
|
def wrap_init(f, params=None) -> WrappedFun:
|
2019-03-12 15:07:52 -04:00
|
|
|
"""Wraps function `f` as a `WrappedFun`, suitable for transformation."""
|
2021-10-04 17:54:18 -07:00
|
|
|
return WrappedFun(f, (), (),
|
|
|
|
() if params is None else tuple(sorted(params.items())))
|
2018-11-17 18:03:33 -08:00
|
|
|
|
|
|
|
|
2020-10-07 15:35:58 -07:00
|
|
|
class _CacheLocalContext(threading.local):
|
|
|
|
|
|
|
|
def __init__(self):
|
2021-08-05 13:11:07 -07:00
|
|
|
super().__init__()
|
2020-10-07 15:35:58 -07:00
|
|
|
self.most_recent_entry = None
|
|
|
|
|
|
|
|
|
2020-07-30 12:59:36 -07:00
|
|
|
def cache(call: Callable):
|
|
|
|
"""Memoization decorator for functions taking a WrappedFun as first argument.
|
|
|
|
|
2020-01-05 04:35:34 +01:00
|
|
|
Args:
|
2020-07-30 12:59:36 -07:00
|
|
|
call: a Python callable that takes a WrappedFun as its first argument. The
|
|
|
|
underlying transforms and params on the WrappedFun are used as part of the
|
|
|
|
memoization cache key.
|
2020-01-05 04:35:34 +01:00
|
|
|
|
|
|
|
Returns:
|
2020-07-30 12:59:36 -07:00
|
|
|
A memoized version of ``call``.
|
2020-01-05 04:35:34 +01:00
|
|
|
"""
|
2020-07-30 12:59:36 -07:00
|
|
|
fun_caches: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
|
2020-10-07 15:35:58 -07:00
|
|
|
thread_local: threading.local = _CacheLocalContext()
|
2019-12-19 11:19:58 -08:00
|
|
|
|
2020-03-09 20:41:01 +01:00
|
|
|
def memoized_fun(fun: WrappedFun, *args):
|
2019-10-31 16:21:02 -07:00
|
|
|
cache = fun_caches.setdefault(fun.f, {})
|
2021-03-19 13:49:38 -07:00
|
|
|
if config.jax_check_tracer_leaks:
|
2021-04-21 06:36:08 -07:00
|
|
|
key = (_copy_main_traces(fun.transforms), fun.params, args,
|
|
|
|
config.x64_enabled, config._trace_context())
|
2021-01-19 18:38:53 -08:00
|
|
|
else:
|
2021-04-21 06:36:08 -07:00
|
|
|
key = (fun.transforms, fun.params, args, config.x64_enabled,
|
|
|
|
config._trace_context())
|
2019-10-31 16:21:02 -07:00
|
|
|
result = cache.get(key, None)
|
|
|
|
if result is not None:
|
|
|
|
ans, stores = result
|
|
|
|
fun.populate_stores(stores)
|
2019-10-30 14:57:00 -07:00
|
|
|
else:
|
2019-10-31 16:21:02 -07:00
|
|
|
ans = call(fun, *args)
|
|
|
|
cache[key] = (ans, fun.stores)
|
2020-10-07 11:14:32 -07:00
|
|
|
|
|
|
|
thread_local.most_recent_entry = weakref.ref(ans)
|
2018-11-17 18:03:33 -08:00
|
|
|
return ans
|
2019-12-19 11:19:58 -08:00
|
|
|
|
2020-10-07 11:14:32 -07:00
|
|
|
def _most_recent_entry():
|
|
|
|
most_recent_entry = thread_local.most_recent_entry
|
|
|
|
if most_recent_entry is not None:
|
|
|
|
result = most_recent_entry()
|
|
|
|
thread_local.most_recent_entry = None
|
|
|
|
return result
|
|
|
|
|
2020-10-07 12:27:11 -07:00
|
|
|
memoized_fun.most_recent_entry = _most_recent_entry # type: ignore
|
2020-07-30 12:59:36 -07:00
|
|
|
memoized_fun.cache_clear = fun_caches.clear # type: ignore
|
2020-10-07 11:14:32 -07:00
|
|
|
|
2019-10-30 14:57:00 -07:00
|
|
|
return memoized_fun
|
2019-11-26 07:56:48 -08:00
|
|
|
|
2021-01-19 18:38:53 -08:00
|
|
|
@partial(partial, tree_map)
|
|
|
|
def _copy_main_traces(x):
|
|
|
|
if isinstance(x, core.MainTrace):
|
|
|
|
return core.MainTrace(x.level, x.trace_type, **x.payload)
|
|
|
|
else:
|
|
|
|
return x
|
|
|
|
|
2020-10-07 11:14:32 -07:00
|
|
|
|
2019-11-26 07:56:48 -08:00
|
|
|
@transformation
|
|
|
|
def hashable_partial(x, *args):
|
|
|
|
ans = yield (x,) + args, {}
|
|
|
|
yield ans
|
2020-03-28 14:15:46 -07:00
|
|
|
|
|
|
|
|
|
|
|
def merge_linear_aux(aux1, aux2):
|
|
|
|
try:
|
|
|
|
out1 = aux1()
|
|
|
|
except StoreException:
|
|
|
|
# store 1 was not occupied, so store 2 better be
|
|
|
|
try:
|
|
|
|
out2 = aux2()
|
|
|
|
except StoreException:
|
2020-09-30 01:20:00 +09:00
|
|
|
raise StoreException("neither store occupied") from None
|
2020-03-28 14:15:46 -07:00
|
|
|
else:
|
|
|
|
return False, out2
|
|
|
|
else:
|
|
|
|
# store 1 was occupied, so let's check store 2 is not occupied
|
|
|
|
try:
|
|
|
|
out2 = aux2()
|
|
|
|
except StoreException:
|
|
|
|
return True, out1
|
|
|
|
else:
|
|
|
|
raise StoreException("both stores occupied")
|