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

Torch dispatch for scipy-like functions and Softplus #1066

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
17 changes: 15 additions & 2 deletions pytensor/link/pytorch/dispatch/scalar.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import importlib

import torch

from pytensor.link.pytorch.dispatch.basic import pytorch_funcify
from pytensor.scalar.basic import (
Cast,
ScalarOp,
)
from pytensor.scalar.math import Softplus


@pytorch_funcify.register(ScalarOp)
Expand All @@ -19,9 +22,14 @@ def pytorch_funcify_ScalarOp(op, node, **kwargs):
if nfunc_spec is None:
raise NotImplementedError(f"Dispatch not implemented for Scalar Op {op}")

func_name = nfunc_spec[0]
func_name = nfunc_spec[0].replace("scipy.", "")

pytorch_func = getattr(torch, func_name)
if "." in func_name:
loc = func_name.split(".")
mod = importlib.import_module(".".join(["torch", *loc[:-1]]))
pytorch_func = getattr(mod, loc[-1])
else:
pytorch_func = getattr(torch, func_name)

if len(node.inputs) > op.nfunc_spec[1]:
# Some Scalar Ops accept multiple number of inputs, behaving as a variadic function,
Expand Down Expand Up @@ -49,3 +57,8 @@ def cast(x):
return x.to(dtype=dtype)

return cast


@pytorch_funcify.register(Softplus)
def pytorch_funcify_Softplus(op, node, **kwargs):
return torch.nn.Softplus()
15 changes: 15 additions & 0 deletions tests/link/pytorch/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import numpy as np
import pytest

import pytensor.tensor as pt
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We prefer to use explicit imports as a policy. In your case import expit and softplus directly

import pytensor.tensor.basic as ptb
from pytensor.compile.builders import OpFromGraph
from pytensor.compile.function import function
Expand Down Expand Up @@ -343,3 +344,17 @@ def test_pytorch_OpFromGraph():

f = FunctionGraph([x, y, z], [out])
compare_pytorch_and_py(f, [xv, yv, zv])


def test_pytorch_scipy():
x = vector("a", shape=(3,))
out = pt.expit(x)
f = FunctionGraph([x], [out])
compare_pytorch_and_py(f, [np.random.rand(3)])


def test_pytorch_softplus():
x = vector("a", shape=(3,))
out = pt.softplus(x)
f = FunctionGraph([x], [out])
compare_pytorch_and_py(f, [np.random.rand(3)])
Loading