Skip to content
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
7 changes: 5 additions & 2 deletions pytensor/tensor/rewriting/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
deg2rad,
digamma,
dot,
eq,
erf,
erfc,
exp,
Expand Down Expand Up @@ -3812,12 +3813,14 @@ def logmexpm1_to_log1mexp(fgraph, node):


# log(exp(a) - exp(b)) -> a + log1mexp(b - a)
# special care is taken for a == b == -inf, by wrapping -> switch(b == -inf, a, ...)
logdiffexp_to_log1mexpdiff = PatternNodeRewriter(
(log, (sub, (exp, "x"), (exp, "y"))),
(add, "x", (log1mexp, (sub, "y", "x"))),
(switch, (eq, "y", -np.inf), "x", (add, "x", (log1mexp, (sub, "y", "x")))),
allow_multiple_clients=True,
name="logdiffexp_to_log1mexpdiff",
)
register_stabilize(logdiffexp_to_log1mexpdiff, name="logdiffexp_to_log1mexpdiff")
register_stabilize(logdiffexp_to_log1mexpdiff)

# log(sigmoid(x) / (1 - sigmoid(x))) -> x
# i.e logit(sigmoid(x)) -> x
Expand Down
7 changes: 6 additions & 1 deletion tests/tensor/rewriting/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -4581,7 +4581,7 @@ def test_log1mexp_stabilization(op_name):
)


def test_logdiffexp():
def test_logdiffexp_stabilization():
rng = np.random.default_rng(3559)
mode = Mode("py").including("stabilize").excluding("fusion")

Expand Down Expand Up @@ -4618,6 +4618,11 @@ def test_logdiffexp():
np.testing.assert_almost_equal(
f(x_test, y_test), np.log(np.exp(x_test) - np.exp(y_test))
)
# Test edge cases
np.testing.assert_array_equal(
f([[-np.inf, -np.inf, -1]], [[-1, -np.inf, -np.inf]]),
[[np.nan, -np.inf, -1]],
)


def test_polygamma_specialization():
Expand Down
Loading