New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement shared_intermediates context manager #43
Merged
Merged
Changes from 14 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
dd6b34a
WIP Attempt to fix sharing
fritzo 560726e
Cache tensor inputs to avoid id clash
fritzo 589950b
Address review comments
fritzo 5ff111f
Refactor to use function wrappers
fritzo 72b9ef8
Memoize conversions to backend
fritzo d208e3d
Make tests more idiomatic
fritzo f5b53fc
Fix failing test
fritzo 472dbff
Add count_cached_ops method for profiling
fritzo 4fb5ae5
Add test of commutativity
fritzo e771973
Add test of reused cache
fritzo 632c266
Support full equation syntax in sharing
fritzo b3f2394
Move decorators to contract.py
fritzo f0bebe5
Add copyright line to LICENSE
fritzo a6983c6
Add test for nested sharing
fritzo e96a8e4
Add docs
fritzo 911eca4
Move alpha_canonicalize to parser.py
fritzo 86d4550
Add test of sharing with constants
fritzo 0139c75
Add bullet point to readme
fritzo e43d68b
Address review comments
fritzo File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
import contextlib | ||
import functools | ||
import numbers | ||
from collections import Counter, OrderedDict | ||
|
||
from .parser import get_symbol, parse_einsum_input | ||
|
||
_SHARING_STACK = [] | ||
|
||
|
||
@contextlib.contextmanager | ||
def shared_intermediates(cache=None): | ||
"""Context in which contract intermediate results are shared. | ||
|
||
Note that intermediate computations will not be garbage collected until | ||
1. this context exits, and | ||
2. the yielded cache is garbage collected (if it was captured). | ||
|
||
Parameters | ||
---------- | ||
cache : dict | ||
If specified, a user-stored dict in which intermediate results will | ||
be stored. This can be used to interleave sharing contexts. | ||
|
||
Returns | ||
------- | ||
cache : dict | ||
A dictionary in which sharing results are stored. If ignored, | ||
sharing results will be garbage collected when this context is | ||
exited. This dict can be passed to another context to resume | ||
sharing. | ||
""" | ||
if cache is None: | ||
cache = {} | ||
try: | ||
_SHARING_STACK.append(cache) | ||
yield cache | ||
finally: | ||
_SHARING_STACK.pop() | ||
|
||
|
||
def count_cached_ops(cache): | ||
"""Returns a counter of the types of each op in the cache. | ||
This is useful for profiling to increase sharing. | ||
""" | ||
return Counter(key[0] for key in cache.keys()) | ||
|
||
|
||
def _alpha_canonicalize(equation): | ||
"""Alpha convert in an order-independent canonical way. | ||
""" | ||
rename = OrderedDict() | ||
for name in equation: | ||
if name in ',->': | ||
continue | ||
if name not in rename: | ||
rename[name] = get_symbol(len(rename)) | ||
return ''.join(rename.get(x, x) for x in equation) | ||
|
||
|
||
def _save_tensors(*tensors): | ||
"""Save tensors in the cache to prevent their ids from being recycled. | ||
This is needed to prevent false cache lookups. | ||
""" | ||
cache = _SHARING_STACK[-1] | ||
for tensor in tensors: | ||
cache['tensor', id(tensor)] = tensor | ||
|
||
|
||
def _memoize(key, fn, *args, **kwargs): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we add docstrings on the next 4 functions? Not a lot, but just something to indicate their use. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done. |
||
cache = _SHARING_STACK[-1] | ||
if key in cache: | ||
return cache[key] | ||
result = fn(*args, **kwargs) | ||
cache[key] = result | ||
return result | ||
|
||
|
||
def transpose_cache_wrap(transpose): | ||
|
||
@functools.wraps(transpose) | ||
def cached_transpose(a, axes, backend='numpy'): | ||
if not _SHARING_STACK: | ||
return transpose(a, axes, backend=backend) | ||
|
||
# hash by axes | ||
_save_tensors(a) | ||
axes = tuple(axes) | ||
key = 'transpose', backend, id(a), axes | ||
return _memoize(key, transpose, a, axes, backend=backend) | ||
|
||
return cached_transpose | ||
|
||
|
||
def tensordot_cache_wrap(tensordot): | ||
|
||
@functools.wraps(tensordot) | ||
def cached_tensordot(x, y, axes=2, backend='numpy'): | ||
if not _SHARING_STACK: | ||
return tensordot(x, y, axes, backend=backend) | ||
|
||
# hash based on the (axes_x,axes_y) form of axes | ||
_save_tensors(x, y) | ||
if isinstance(axes, numbers.Number): | ||
axes = list(range(len(x.shape)))[len(x.shape) - axes:], list(range(len(y.shape)))[:axes] | ||
axes = tuple(axes[0]), tuple(axes[1]) | ||
key = 'tensordot', backend, id(x), id(y), axes | ||
return _memoize(key, tensordot, x, y, axes, backend=backend) | ||
|
||
return cached_tensordot | ||
|
||
|
||
def einsum_cache_wrap(einsum): | ||
|
||
@functools.wraps(einsum) | ||
def cached_einsum(*args, **kwargs): | ||
if not _SHARING_STACK: | ||
return einsum(*args, **kwargs) | ||
|
||
# hash modulo commutativity by computing a canonical ordering and names | ||
backend = kwargs.pop('backend', 'numpy') | ||
equation = args[0] | ||
inputs, output, operands = parse_einsum_input(args) | ||
inputs = inputs.split(',') | ||
_save_tensors(*operands) | ||
canonical = sorted(zip(inputs, map(id, operands)), key=lambda x: x[1]) | ||
canonical_ids = tuple(id_ for _, id_ in canonical) | ||
canonical_inputs = ','.join(input_ for input_, _ in canonical) | ||
canonical_equation = _alpha_canonicalize('{}->{}'.format(canonical_inputs, output)) | ||
key = 'einsum', backend, canonical_equation, canonical_ids | ||
return _memoize(key, einsum, equation, *operands, backend=backend) | ||
|
||
return cached_einsum | ||
|
||
|
||
def to_backend_cache_wrap(to_backend): | ||
|
||
@functools.wraps(to_backend) | ||
def cached_to_backend(array): | ||
if not _SHARING_STACK: | ||
return to_backend(array) | ||
|
||
# hash by id | ||
key = to_backend.__name__, id(array) | ||
return _memoize(key, to_backend, array) | ||
|
||
return cached_to_backend |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@dgasmith my employer requires me to add a copyright line somewhere. Is it ok here, or would you like me to move it to sharing.py or somewhere else?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yea, could we move this to
sharing.py
? We should probably look at changing the copyright to the "opt_einsum developers" in the future. I need to look into this angle of things a bit more.