Skip to content

Add rewrite for log(sqrt(x)) #1555

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 11 commits into from
Jul 28, 2025
Merged
Show file tree
Hide file tree
Changes from 10 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
23 changes: 23 additions & 0 deletions pytensor/tensor/rewriting/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,29 @@ def local_sqrt_sqr(fgraph, node):
return [new_out]


@register_specialize
@node_rewriter([log])
def local_log_sqrt(fgraph, node):
x = node.inputs[0]

if (
not x.owner
or not isinstance(x.owner.op, Elemwise)
or not isinstance(x.owner.op.scalar_op, ps.Sqrt)
):
return

# Case for log(sqrt(x)) -> 0.5 * log(x)
x = x.owner.inputs[0]
old_out = node.outputs[0]
new_out = mul(0.5, log(x))
if new_out.dtype != old_out.dtype:
new_out = cast(new_out, old_out.dtype)

copy_stack_trace(node.out, new_out)
return [new_out]


@register_specialize
@node_rewriter([exp, expm1])
def local_exp_log_nan_switch(fgraph, node):
Expand Down
12 changes: 12 additions & 0 deletions tests/tensor/rewriting/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -1989,6 +1989,18 @@ def test_exp_log_nested(self, nested_expression, expected_switches):
assert len(ops_graph) == expected_switches


def test_log_sqrt() -> None:
x = pt.tensor("x", shape=(None, None))
out = log(sqrt(x))

out = rewrite_graph(out, include=["specialize"])

assert equal_computations(
[out],
[mul(pt.as_tensor_variable([[0.5]]), log(x))],
)


class TestSqrSqrt:
def setup_method(self):
mode = get_default_mode()
Expand Down
Loading