Skip to content
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

Support wrapping PyTorch builtin functions #118

Merged
merged 1 commit into from
Apr 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions funsor/six.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import absolute_import, division, print_function

import inspect
import re

import six

Expand Down Expand Up @@ -44,11 +45,30 @@ def decorator(fn):


def getargspec(fn):
"""wrapper to remove annoying DeprecationWarning for inspect.getargspec in Py3"""
if six.PY3:
args, vargs, kwargs, defaults, _, _, _ = inspect.getfullargspec(fn)
else:
args, vargs, kwargs, defaults = inspect.getargspec(fn)
"""
Similar to Python 2's :py:func:`inspect.getargspec` but:
- In Python 3 uses ``getfullargspec`` to avoid ``DeprecationWarning``.
- For builtin functions like ``torch.matmul``, falls back to attmpting
to parse the function docstring, assuming torch-style.
"""
assert callable(fn)
try:
if six.PY3:
args, vargs, kwargs, defaults, _, _, _ = inspect.getfullargspec(fn)
else:
args, vargs, kwargs, defaults = inspect.getargspec(fn)
except TypeError:
# Fall back to attmpting to parse a PyTorch-style docstring.
match = re.match(r"\s{}\(([^)]*)\)".format(fn.__name__), fn.__doc__)
if match is None:
raise
parts = match.group(1).split(", ")
args = [a.split("=")[0] for a in parts]
if not all(re.match(r"^[^\d\W]\w*\Z", arg) for arg in args):
raise
vargs = None
kwargs = None
defaults = () # Ignore defaults.
return args, vargs, kwargs, defaults


Expand Down
9 changes: 9 additions & 0 deletions test/test_torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,15 @@ def max_and_argmax(x):
assert_close(actual_argmax, expected_argmax)


def test_function_of_torch_tensor():
x = torch.randn(4, 3)
y = torch.randn(3, 2)
f = funsor.torch.function(reals(4, 3), reals(3, 2), reals(4, 2))(torch.matmul)
actual = f(x, y)
expected = f(Tensor(x), Tensor(y))
assert_close(actual, expected)


def test_align():
x = Tensor(torch.randn(2, 3, 4), OrderedDict([
('i', bint(2)),
Expand Down