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

Add rewrite for 1 ** x = 1 #1179

Merged
merged 6 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 29 additions & 1 deletion pytensor/tensor/rewriting/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

import pytensor.scalar.basic as ps
import pytensor.scalar.math as ps_math
from pytensor.graph.basic import Constant, Variable
from pytensor.graph import FunctionGraph
from pytensor.graph.basic import Apply, Constant, Variable
from pytensor.graph.rewriting.basic import (
NodeRewriter,
PatternNodeRewriter,
Expand Down Expand Up @@ -1914,6 +1915,33 @@ def local_pow_canonicalize(fgraph, node):
return [alloc_like(node.inputs[0], node.outputs[0], fgraph)]


@register_canonicalize
@node_rewriter([pt_pow])
def local_pow_canonicalize_base_1(
fgraph: FunctionGraph, node: Apply
) -> list[TensorVariable] | None:
"""
Replace `1 ** x` with 1, broadcast to the shape of the output.

Parameters
----------
fgraph: FunctionGraph
Full function graph being rewritten
node: Apply
Specific node being rewritten

Returns
-------
rewritten_output: list[TensorVariable] | None
Rewritten output of node, or None if no rewrite is possible
"""
Copy link
Member

Choose a reason for hiding this comment

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

I don't think we should add docstrings for rewrites, just adds lines to the codebase. Nobody will be calling this function manually

Copy link
Member Author

Choose a reason for hiding this comment

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

I suppose I agree w.r.t Parameters and Returns, but there should at least be a small explainer of what the rewrite does.

cst = get_underlying_scalar_constant_value(
node.inputs[0], only_process_constants=True, raise_not_constant=False
)
if cst == 1:
return [alloc_like(node.inputs[0], node.outputs[0], fgraph)]
Copy link
Member

Choose a reason for hiding this comment

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

This could make an infinite recursion if the ShapeOpt is not running, as it will default to alloc(1, *pow(1, x).shape).

You can do pt.broadcast_arrays(*node.inputs)[0] instead?

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, but does that mean we should also change local_canonicalize_pow ? Because I copied the return from there

Copy link
Member

Choose a reason for hiding this comment

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

Lines to that rewrite?

Copy link
Member

Choose a reason for hiding this comment

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

found it yes. Why don't you combine your changes with that rewrite?

Copy link
Member Author

Choose a reason for hiding this comment

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

check how it looks now? I had to set the dtype to the output as well, not sure if there's a better way



@register_specialize
@node_rewriter([mul])
def local_mul_to_sqr(fgraph, node):
Expand Down
19 changes: 19 additions & 0 deletions tests/tensor/rewriting/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -4571,3 +4571,22 @@ def test_log_kv_stabilization():
out.eval({x: 1000.0}, mode=mode),
-1003.2180912984705,
)


@pytest.mark.parametrize("shape", [(), (4, 5, 6)], ids=["scalar", "tensor"])
def test_pow_1_rewrite(shape):
x = pt.tensor("x", shape=shape)
z = 1**x

f1 = pytensor.function([x], z, mode=get_default_mode().excluding("canonicalize"))
assert debugprint(f1, file="str").count("Pow") == 1

x_val = np.random.random(shape).astype(config.floatX)
z_val_1 = f1(x_val)

f2 = pytensor.function([x], z)
assert debugprint(f2, file="str").count("Pow") == 0

z_val_2 = f2(x_val)

np.testing.assert_allclose(z_val_1, z_val_2)
Loading