Skip to content

Speedup scalar Op python implementations #1169

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

Merged
merged 4 commits into from
Feb 12, 2025
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
33 changes: 16 additions & 17 deletions pytensor/scalar/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
from pytensor.utils import (
apply_across_args,
difference,
from_return_values,
to_return_values,
)

Expand Down Expand Up @@ -1081,6 +1080,16 @@
return (type,)


def _cast_to_promised_scalar_dtype(x, dtype):
try:
return x.astype(dtype)
except AttributeError:
if dtype == "bool":
return np.bool_(x)
else:
return getattr(np, dtype)(x)


class ScalarOp(COp):
nin = -1
nout = 1
Expand Down Expand Up @@ -1134,28 +1143,18 @@
else:
raise NotImplementedError(f"Cannot calculate the output types for {self}")

@staticmethod
def _cast_scalar(x, dtype):
if hasattr(x, "astype"):
return x.astype(dtype)
elif dtype == "bool":
return np.bool_(x)
else:
return getattr(np, dtype)(x)

def perform(self, node, inputs, output_storage):
if self.nout == 1:
dtype = node.outputs[0].dtype
output_storage[0][0] = self._cast_scalar(self.impl(*inputs), dtype)
output_storage[0][0] = _cast_to_promised_scalar_dtype(
self.impl(*inputs),
node.outputs[0].dtype,
)
else:
variables = from_return_values(self.impl(*inputs))
assert len(variables) == len(output_storage)
# strict=False because we are in a hot loop
for out, storage, variable in zip(
node.outputs, output_storage, variables, strict=False
node.outputs, output_storage, self.impl(*inputs), strict=False
):
dtype = out.dtype
storage[0] = self._cast_scalar(variable, dtype)
storage[0] = _cast_to_promised_scalar_dtype(variable, out.dtype)

Check warning on line 1157 in pytensor/scalar/basic.py

View check run for this annotation

Codecov / codecov/patch

pytensor/scalar/basic.py#L1157

Added line #L1157 was not covered by tests

def impl(self, *inputs):
raise MethodNotDefined("impl", type(self), self.__class__.__name__)
Expand Down
Loading