Skip to content

Use grad to compute jacobian when input shape is known to be (1,) #1454

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 2 commits into from
Jun 8, 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
4 changes: 2 additions & 2 deletions pytensor/gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -2069,13 +2069,13 @@ def jacobian(expression, wrt, consider_constant=None, disconnected_inputs="raise
else:
wrt = [wrt]

if expression.ndim == 0:
if all(expression.type.broadcastable):
# expression is just a scalar, use grad
return as_list_or_tuple(
using_list,
using_tuple,
grad(
expression,
expression.squeeze(),
wrt,
consider_constant=consider_constant,
disconnected_inputs=disconnected_inputs,
Expand Down
12 changes: 12 additions & 0 deletions tests/test_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from pytensor.graph.basic import Apply, graph_inputs
from pytensor.graph.null_type import NullType
from pytensor.graph.op import Op
from pytensor.scan.op import Scan
from pytensor.tensor.math import add, dot, exp, sigmoid, sqr, tanh
from pytensor.tensor.math import sum as pt_sum
from pytensor.tensor.random import RandomStream
Expand Down Expand Up @@ -1036,6 +1037,17 @@ def test_jacobian_scalar():
vx = np.asarray(rng.uniform(), dtype=pytensor.config.floatX)
assert np.allclose(f(vx), 2)

# test when input is a shape (1,) vector -- should still be treated as a scalar
Jx = jacobian(y[None], x)
f = pytensor.function([x], Jx)

# Ensure we hit the scalar grad case (doesn't use scan)
nodes = f.maker.fgraph.apply_nodes
assert not any(isinstance(node.op, Scan) for node in nodes)

vx = np.asarray(rng.uniform(), dtype=pytensor.config.floatX)
assert np.allclose(f(vx), 2)

# test when the jacobian is called with a tuple as wrt
Jx = jacobian(y, (x,))
assert isinstance(Jx, tuple)
Expand Down