Skip to content

Commit e7f18de

Browse files
yebaiclaude
andcommitted
Fold AD output-shape checks into prepare's dispatch
Replace `_assert_supported_output` / `_assert_jacobian_output` with an `if y isa Number / elseif y isa AbstractVector / else throw` cascade. The jacobian assertion was unreachable after the scalar branch, and the supported-output helper had a single call site; inlining the remaining check as the `else` arm is clearer than two named helpers. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 3a604ec commit e7f18de

1 file changed

Lines changed: 7 additions & 21 deletions

File tree

ext/AbstractPPLDifferentiationInterfaceExt.jl

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,6 @@ using AbstractPPL.Evaluators: Prepared, VectorEvaluator
55
using ADTypes: ADTypes, AbstractADType, AutoReverseDiff
66
using DifferentiationInterface: DifferentiationInterface as DI
77

8-
function _assert_supported_output(y)
9-
(y isa Number || y isa AbstractVector) || throw(
10-
ArgumentError(
11-
"A prepared AD evaluator must return a scalar or AbstractVector; got $(typeof(y)).",
12-
),
13-
)
14-
return nothing
15-
end
16-
17-
function _assert_jacobian_output(y)
18-
y isa AbstractVector || throw(
19-
ArgumentError(
20-
"`value_and_jacobian!!` requires the prepared function to return an AbstractVector; got $(typeof(y)).",
21-
),
22-
)
23-
return nothing
24-
end
25-
268
# Differentiate only `x`; the evaluator is passed as a `DI.Constant` context so
279
# that in DynamicPPL the model and other evaluator state stay constant.
2810
@inline _call_evaluator(x, evaluator) = evaluator(x)
@@ -58,20 +40,24 @@ function AbstractPPL.prepare(
5840
length(x) == 0 &&
5941
return Prepared(adtype, evaluator, DICache(_call_evaluator, nothing, nothing, true))
6042
y = evaluator(x)
61-
_assert_supported_output(y)
6243
if y isa Number
6344
target, gradient_prep, use_context = _prepare_gradient(adtype, x, evaluator)
6445
return Prepared(
6546
adtype, evaluator, DICache(target, gradient_prep, nothing, use_context)
6647
)
67-
else
68-
_assert_jacobian_output(y)
48+
elseif y isa AbstractVector
6949
jacobian_prep = DI.prepare_jacobian(
7050
_call_evaluator, adtype, x, DI.Constant(evaluator)
7151
)
7252
return Prepared(
7353
adtype, evaluator, DICache(_call_evaluator, nothing, jacobian_prep, true)
7454
)
55+
else
56+
throw(
57+
ArgumentError(
58+
"A prepared AD evaluator must return a scalar or AbstractVector; got $(typeof(y)).",
59+
),
60+
)
7561
end
7662
end
7763

0 commit comments

Comments
 (0)