Wrapping a graph in OpFromGraph breaks its gradient when it has an integer output

Open
#2,717 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@atishay-kasliwal is already working on this.

Since Nov 24, 2026.

  • #2718 by @atishay-kasliwal — open

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
22/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
python

Research direction

Start in pytensor/compile/builders.py at _build_and_cache_lop_op, where the cotangent placeholder is created from the output variable's own type — here an integer scalar — and the inner pytensor.grad call then rejects it. Reproduce with the snippet in the issue, then compare against the unwrapped graph to see how a float known_grad reaches the same inner grad. Read the linked discussion #2065 for the Scan case that sends zeros for an integer carry. Note an open pull request (#2718) already targets this, so check its state before starting; done means the wrapped graph differentiates and the float cotangent is handled for the integer output.

Written by the indexing model from the issue text.

Description

bug gradients OpFromGraph

pytensor.grad raises on an OpFromGraph with an integer output when that output receives a float cotangent, though the same graph without the wrapper differentiates. _build_and_cache_lop_op builds the placeholder for that cotangent with the output's integer type, and the inner grad call rejects it. Scan hits this whenever its step is an OpFromGraph with an integer carry, because it sends zeros for that carry, as discussed in #2065.

import pytensor
import pytensor.tensor as pt
from pytensor.compile.builders import OpFromGraph

x = pt.dvector("x")
k0 = pt.lscalar("k0")
known_grads = lambda c, k: {c: pt.ones_like(c), k: pt.zeros((), dtype="float64")}

c, k = x * 2, k0 + 1
pytensor.grad(None, x, known_grads=known_grads(c, k))  # works

ix, ik = x.type(), pt.lscalar()
c, k = OpFromGraph([ix, ik], [ix * 2, ik + 1])(x, k0)
pytensor.grad(None, x, known_grads=known_grads(c, k))
# TypeError: Gradients must always be NullType, DisconnectedType, or continuous,
# but grad was given a known_grad of type Scalar(int64, shape=())
Dominant language
Python
Stars
655
Forks
266
Avg merge
3d 23h
Merged PRs (30d)
43

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from pymc-devs/pytensor

All issues in pymc-devs/pytensor

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.