Skip to content

v3: NeuralNetworkBlock uses StatelessApplyWrapper; default chains are Enzyme-constant - #168

Open
SebastianM-C wants to merge 12 commits into
mainfrom
nnblock-stateless-wrapper
Open

SebastianM-C wants to merge 12 commits into
mainfrom
nnblock-stateless-wrapper

Conversation

@SebastianM-C

@SebastianM-C SebastianM-C commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Breaking release (v3.0.0): NeuralNetworkBlock now stores the Lux model like SymbolicNeuralNetwork does, in a StatelessApplyWrapper parameter, and multi_layer_feed_forward chains become constant for Enzyme.

Breaking: the block's parameters are now p and lux_apply, with outputs ~ lux_apply(inputs, p). The lux_model and T parameters are removed. Use sol.ps[sys.nn.lux_apply](input, p) to evaluate the network, or get_nn_chain(sys.nn.lux_apply) to get the Lux model. The positional NeuralNetworkBlock(n_input, n_output; ...) method is removed; pass both as keywords.

Also:

  • multi_layer_feed_forward's init closure captured the scale as a Float64, so Enzyme treated the whole chain as possibly active and rebuilt its shadow on every make_zero. It is replaced by a ScaledInit struct marked EnzymeRules.inactive_type (sound: it is only called by initialparameters). Every field of these chains is now inactive, so the chain and wrapper are guaranteed_const without declaring the wrapper itself inactive, which would be unsound for user models that hold data used in the forward pass. Initial weights are unchanged.
  • The block gets the device-generic parameter handling from Make StatelessApplyWrapper device-generic when rebuilding parameters #162, and get_nn_chain now works on a block.
  • When Lux's outputsize fails, e.g. for ToSimpleChainsAdaptor models, the block evaluates the network once to check n_output. A wrong n_input cannot be detected in general; the docstring now says so.
  • Lux floor raised to 1.31.5, the first release that allows SimpleChains 0.5; SimpleChains 0.5 is now a test dependency and the block is tested with a real ToSimpleChainsAdaptor model.

Performance, for loss + gradient of a 68-parameter UDE (GaussAdjoint + EnzymeVJP, single thread, i9-14900K):

gradient (median) allocations
v2.8.1 ~237 ms 6.29 M
this PR ~204 ms 5.72 M
this PR + SimpleChains 0.5 and LuxDL/Lux.jl#1792 ~92 ms 1.56 M

Tests: updated block metadata tests, NeuralNetworkBlock device tests (JLArrays and CUDA), and regression tests for the outputsize fallback, including wrong n_output with a real SimpleChains model, and an explicit EnzymeVJP UDE gradient check against ForwardDiff plus a check that the default chain stays constant for Enzyme (make_zero(wrapper) === wrapper). The All group passes locally on Julia 1.10, 1.12 and 1.13 at the current head; CUDA (RTX 4080 SUPER) passed before the last commits, which don't touch device code. The docs build is left to CI.

Independent review: codex gpt-6.2-sol · 8 findings on the review reply and its benchmark · 2 fixed in code (bare Dense n_input docs, multidimensional outputs), 6 fixed in the reply wording

🤖 Generated with Claude Code · model: claude-opus-5-5
Review: skimmed

SebastianM-C and others added 3 commits October 28, 2026 00:50
…Enzyme-constant

NeuralNetworkBlock now stores the Lux model in a single callable parameter,
`lux_apply`, like SymbolicNeuralNetwork. This removes the `lux_model` and `T`
parameters (breaking, hence v3.0.0) and gives the block the device-generic
ComponentArray reconstruction from #162. `get_nn_chain` now works on the
block's `lux_apply` parameter instead of throwing a MethodError.

The `multi_layer_feed_forward` init closure captured `initial_scaling_factor`
as a Float64, which made the chain (stored in the model's parameter object)
non-`guaranteed_const` for Enzyme, so Enzyme rebuilt its shadow on every
`make_zero`. The closure is replaced by a `ScaledInit` callable struct marked
with `EnzymeRules.inactive_type`; that is sound because it is only called by
`initialparameters`, never in the differentiated forward pass. All fields of
the default chains are now inactive, so the chain and its wrapper are constant
for Enzyme without declaring the wrapper itself inactive (which would be
unsound for user models holding data that feeds the forward pass). Initial
weights are unchanged.

EnzymeCore is added as a direct dependency; Lux already depends on it. The QA
ExplicitImports checks ignore `EnzymeRules`/`inactive_type`, which are Enzyme's
documented API but not declared public in EnzymeCore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The block now uses StatelessApplyWrapper, so check that its callable keeps
CuArray/JLArray inputs and parameters on the device, like SymbolicNeuralNetwork.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Lux's `outputsize` propagates nil arrays through the model, which fails for
layers that need real memory, such as `SimpleChainsLayer` from
`ToSimpleChainsAdaptor` ("conversion to pointer not defined for NilArray").
The size is only used for a clearer error message, so skip the check when it
cannot be computed instead of failing construction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@SebastianM-C
SebastianM-C force-pushed the nnblock-stateless-wrapper branch from 0cee56b to 9e95e0c Compare October 27, 2026 22:50
@SebastianM-C SebastianM-C changed the title v3: NeuralNetworkBlock uses StatelessApplyWrapper, marked inactive for Enzyme v3: NeuralNetworkBlock uses StatelessApplyWrapper; default chains are Enzyme-constant Oct 27, 2026
@Saswatsusmoy

Copy link
Copy Markdown

The bare catch in _try_outputsize also swallows the DimensionMismatch for a wrong n_input. On main, NeuralNetworkBlock(3, 2; chain = multi_layer_feed_forward(2, 2), name = :nn) errors at construction. Here it only fails in solve. Would rethrowing DimensionMismatch work? SimpleChains still constructs with that. Would a test for the n_input case make sense too?

Smaller things:

  • Should the get_network/get_nn_chain docstrings, the README and the CHANGELOG mention the block's lux_apply, v3 and the EnzymeCore dependency?
  • QA doesn't seem to run in CI, since there's no [QA] group in test_groups.toml. Is that intended?
  • Would a gradient benchmark help lock in the perf win? The LV test's Int scale was already Enzyme-constant before this PR.
  • Is there a public way to swap the network now that lux_model is gone?

SebastianM-C and others added 3 commits October 29, 2026 02:39
The bare catch also swallowed real model errors, so a wrong n_input
(DimensionMismatch for Dense, ArgumentError for SimpleChains) only
failed in solve instead of at construction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018GADJP8tjsBJuvPS8KpGin
SciMLTesting never runs QA as part of the All group, so QA needs its
own group in test_groups.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018GADJP8tjsBJuvPS8KpGin
@SebastianM-C

Copy link
Copy Markdown
Member Author

addressed the comments, QA works now and added docs. The benchmark would be separate.
On swapping the network, that was not possible anyway. If a different network is needed the system has to be recreated, so the NNBlock construction would be called again

…ns model

Lux 1.31.5 is the first release whose compat admits SimpleChains 0.5
(LuxDL/Lux.jl#1748). SimpleChains 0.5 adds an Enzyme reverse rule for
SimpleChain. With SimpleChains 0.5 as a test dependency, the downgrade job
would not resolve with the old Lux 1.14 floor, which only allows
SimpleChains 0.4.

The new test builds a NeuralNetworkBlock from ToSimpleChainsAdaptor and
checks it against the adapted Lux model. It also checks that a wrong
n_input still fails at construction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #168

Reviewed head: e12ba39
Raw SHA-256: 92895edac70004a61d55f86eb71437153c5e5463aa0ae1ca87448295be44838b
Source SHA-256: 54267d2e1708da7e1574b9d829731eddb370e31bbd3fb95929bf72a355fdc856
Source: standard-review-v1 (harness-log)
Reviewer session: 01a1ffa6-c34e-7f50-b9eb-e2806115ab23
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: high (H1)
  • Verdict: CHANGES
  • Reviewed head: e12ba39

Review report

VERDICT: CHANGES
Round: 1
Head: e12ba39
Slot: 1
CI: green
Session: 01a1ffa6-c34e-7f50-b9eb-e2806115ab23
Reviewer: codex-cli 0.170.0; model: gpt-6.2-sol

Risk

high (H1: removes the documented lux_model and T parameters and changes the lux_apply call signature)

Blocking findings

  • Blocking priorities: P1, P2, P2
  • [P1] The shape fallback permits a successful solve with missing or discarded outputs. src/ModelingToolkitNeuralNets.jl:85, src/ModelingToolkitNeuralNets.jl:102. I compiled a block built from Lux.Chain(Lux.WrappedFunction(x -> (pointer(x); x)), Lux.Dense(2 => 2)). With weights [2.0 -1.0; -3.0 4.0], bias [0.5, 2.0], and input [0.25, 0.5], its callable returned [0.5, 3.25]. I integrated the sum of the declared outputs for one time unit from zero. With n_output=2 the solve reached 3.7499999999999996. With n_output=1 it reported Success and reached 0.5, discarding the second channel. With n_output=3 it also reported Success while the callable still returned two values. A real SimpleChains model reproduced both invalid-output successes. The pointer layer also let n_input=3 through construction, with a DimensionMismatch at evaluation, contradicting CHANGELOG.md:23. Narrow the catch to the intended sizing failure, validate dimensions with a concrete sizing path when possible, and enforce the returned shape before the generated system can index unchecked outputs. Add negative tests through the compiled system for too few and too many declared outputs and test the wrong input on a chain that takes the fallback.
  • [P2] The Enzyme rule relies on names the owning package does not declare public. src/ModelingToolkitNeuralNets.jl:10, src/utils.jl:66, test/qa/qa.jl:3. With EnzymeCore 0.8.28, Base.ispublic returned false for both EnzymeCore.EnzymeRules and EnzymeCore.EnzymeRules.inactive_type. The QA exclusions explain the missing declarations but give no reason an exception is irreducible. Use an upstream public declaration for both names, or defer the rule until that API is available.
  • [P2] The Enzyme activity change has no regression assertion in the suite. src/utils.jl:66. My probe observed that Enzyme.make_zero preserves the final initializer on the head and changes it on the base. Both revisions produced the same analytic forward-pass parameter gradient. Add a test that discriminates on the shadow behavior and checks that a differentiated forward pass still yields the expected gradient.

Non-blocking findings

  • test/test_groups.toml:8 adds an independently reviewable CI matrix change. The standalone QA command passed 20 checks. Move the matrix change to its own PR so it can be reviewed independently of the v3 behavior changes.

What I ran

  • GROUP=All julia --project -e 'using Pkg; Pkg.test()' on Julia 1.12.4. The suite exited 0 with 126 passes and two existing broken assertions in Basic. The metadata and reported-issues testsets passed 52 and 23 checks respectively. Direct runs of test/reported_issues.jl and test/nn_ps_accessors.jl also exited 0.
  • GROUP=QA julia --project -e 'using Pkg; Pkg.test()' exited 0 with QA | 20 20. Runic check mode, typos on changed files, and git diff --check origin/main...HEAD exited 0.
  • julia --project=docs -e 'using Pkg; Pkg.instantiate()' followed by julia --project=docs docs/make.jl exited 0 and rendered five HTML pages.
  • julia --project=probe-head dimensions.jl and julia --project=probe-base dimensions.jl used identical resolved dependencies, including Lux 1.32.2 and SimpleChains 0.5.0. The valid models solved on the head, and the callable was accessible from sol.ps. The base rejected both valid models with conversion to pointer not defined for Lux.NilSizePropagation.NilArray{1}. The invalid-dimension results are above.
  • enzyme.jl, ad_regression.jl, and enzyme_runtime.jl ran in each probe environment with Enzyme 0.13.221. Seeded initialization matched the reference closure exactly. The reverse-mode probe with runtime activity reported loss=151.0 gradient=[10.0, 12.0, 15.0, 18.0, 11.0, 16.0] on each revision. I confirmed that EnzymeCore carries an MIT license.
  • uv run --locked python --version reported Python 3.13.13 and warned that --locked has no effect outside a project. This is a Julia repository without a Python lockfile.

What I did not verify

  • CUDA execution. The build host had no NVIDIA device available.
  • The Enzyme allocation or timing improvement, other Julia versions, and downstream packages.

AUTHOR_GRADE: {"task":"feature","score":2,"difficulty":3,"rounds":1,"author_harness":"unknown","author_model":"unknown","note":"The CPU suite and docs passed, and valid SimpleChains blocks solved. Invalid output declarations also returned Success and silently discarded a channel."}

Head link: e12ba39


🤖 Posted by an AI agent — harness: codex-cli 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a1ffa6-c34e-7f50-b9eb-e2806115ab23 (no session URL)

SebastianM-C and others added 3 commits November 30, 2026 01:39
…utputsize fails

Lux's outputsize cannot propagate nil arrays through layers that need real
memory, such as SimpleChainsLayer, and the block used to skip the n_output
check for them. A wrong n_output then solved silently with dropped outputs.
Now any outputsize failure falls back to one evaluation of the network, so
n_output is always checked at construction.

n_input cannot be checked for arbitrary layers; document that as a
limitation. A wrong n_input still errors when the network rejects it, but the
error type depends on the matmul backend (LoopVectorization throws an
ErrorException), so the test only checks that it errors.

Also remove the positional NeuralNetworkBlock(n_input, n_output; kwargs...)
method, since v3 is breaking anyway, and use keywords everywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Apply `only` to the size from either path, so a network whose output has
`n_output` elements but more than one dimension is rejected again, as on main.

`outputsize` of a bare `Lux.Dense` does not depend on the input, so a wrong
`n_input` is not caught for it. Say so in the docstring instead of naming
`Dense` as an example that is caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…zyme-constant

Add Enzyme as a test dependency (it is already installed through
SciMLSensitivity) and differentiate the Lotka-Volterra loss with
GaussAdjoint(autojacvec = EnzymeVJP()) explicitly. The Zygote comparison with
ForwardDiff was marked broken, but only missed the default isapprox tolerance
(relative error ~2e-8), so it now uses rtol = 1e-6.

Also check that `Enzyme.make_zero` returns the block's wrapper itself, which
holds as long as `ScaledInit` keeps the default chain constant for Enzyme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@SebastianM-C

Copy link
Copy Markdown
Member Author

Thanks for the review. Addressed in the latest commits:

  • [P1] output size: when outputsize fails (e.g. for SimpleChains models), the block now evaluates the network once at construction and checks n_output, so a wrong n_output fails at construction instead of the check being skipped. I'd rather keep this one check at construction than check the output on every call as Validate NeuralNetworkBlock output sizes · 🤖 AI agent · gpt-6.2-sol · unreviewed #171 does.

  • Wrong n_input: this can't be checked for arbitrary Lux layers, so the docstring now documents it as a limitation, and the CHANGELOG claim is fixed. It is still caught at construction when computing the output size or evaluating the network fails, e.g. for a Chain of Dense layers or a SimpleChains model, but not for a bare Dense, whose outputsize ignores the input.

  • [P2] EnzymeCore public API: inactive_type is used here mainly as a workaround for the cost of make_zero/remake_zero! (see remake_zero! allocates a lot and can be a performance bottleneck EnzymeAD/Enzyme.jl#2489 (comment)). With the old initializer closure, the captured Float64 scale means the wrapper holding the Lux chain is not guaranteed_const for Enzyme. Marking ScaledInit inactive makes it guaranteed_const. Until EnzymeCore declares inactive_type public, I'd keep the QA exclusion rather than lose this. Toggling the rule on this branch, for a Lotka–Volterra UDE with 114 tunables:

    ScaledInit inactive not inactive
    adjoint_sensitivities, GaussAdjoint(autojacvec = EnzymeVJP()) 2.55 ms, 86k allocs 3.96 ms, 143k allocs
    make_zero of the parameter object 0.64 μs, 31 allocs 1.62 μs, 84 allocs
    remake_zero! of its shadow 0.38 μs, 8 allocs 1.19 μs, 48 allocs

    Times are medians, averaged over two runs per variant, each in a fresh process; allocation counts are as reported by BenchmarkTools. The gradients (du0 and dp) are bitwise identical. The "not inactive" variant redefines inactive_type(::Type{<:ScaledInit}) to false before anything is differentiated; like the old closure, it is then not guaranteed_const. This measures the rule on the current branch, not this PR against main. Julia 1.12.7, Enzyme 0.13.221, SciMLSensitivity 7.119.14, ModelingToolkit 11.47.0, Lux 1.32.17, single thread, i9-14900K.

    Benchmark script
    # usage: RULE=1|0 julia +1.12 --startup=no --threads=1 --project=. bench.jl
    # A/B for `EnzymeRules.inactive_type(::Type{<:ScaledInit})` in ModelingToolkitNeuralNets.
    # RULE=0 redefines it to `false` before anything is differentiated, which restores the
    # behavior of the closure initializer (Enzyme sees a possibly active Float64 in the chain).
    using ModelingToolkitNeuralNets, ModelingToolkit, Lux, Enzyme, SciMLSensitivity, SciMLBase
    using OrdinaryDiffEqTsit5, BenchmarkTools, StableRNGs, Printf
    using ModelingToolkit: t_nounits as t, D_nounits as D
    const MTKNN = ModelingToolkitNeuralNets
    
    rule = get(ENV, "RULE", "1") == "1"
    if !rule
        @eval MTKNN.EnzymeRules.inactive_type(::Type{<:MTKNN.ScaledInit}) = false
    end
    
    chain = multi_layer_feed_forward(2, 2; width = 8, depth = 1)
    @named nn = NeuralNetworkBlock(; n_input = 2, n_output = 2, chain, rng = StableRNG(42))
    @variables x(t) = 3.1 y(t) = 1.5
    @parameters α = 1.3 [tunable = false] δ = 1.8 [tunable = false]
    eqs = [
        D(x) ~ α * x + nn.outputs[1],
        D(y) ~ -δ * y + nn.outputs[2],
        nn.inputs[1] ~ x,
        nn.inputs[2] ~ y,
    ]
    @named ude = System(eqs, t; systems = [nn])
    sys = mtkcompile(ude)
    prob = ODEProblem{true, SciMLBase.FullSpecialize}(sys, [], (0.0, 5.0))
    ts = collect(0.0:0.1:5.0)
    sol = solve(prob, Tsit5(); abstol = 1.0e-8, reltol = 1.0e-8)
    
    wrapper = prob.ps[sys.nn.lux_apply]
    n_tunables = length(prob.ps[sys.nn.p])
    dgdu!(out, u, p, t, i) = (out .= 1.0)
    sensealg = GaussAdjoint(autojacvec = EnzymeVJP())
    grad() = adjoint_sensitivities(
        sol, Tsit5(); sensealg, t = ts, dgdu_discrete = dgdu!, abstol = 1.0e-8, reltol = 1.0e-8
    )
    _, dp = grad()
    
    shadow = Enzyme.make_zero(prob.p)
    b_make = @benchmark Enzyme.make_zero($(prob.p))
    b_remake = @benchmark Enzyme.remake_zero!($shadow)
    b_grad = @benchmark grad() seconds = 30
    
    fmt(b) = @sprintf("%10.3f μs  %7d allocs", median(b).time / 1.0e3, b.allocs)
    println("RULE = $rule, guaranteed_const(wrapper) = ", Enzyme.Compiler.guaranteed_const(typeof(wrapper)))
    println("tunables = $n_tunables, solution steps = $(length(sol.t)), sum|dp| = ", sum(abs, dp))
    println("make_zero(p)            ", fmt(b_make))
    println("remake_zero!(shadow)    ", fmt(b_remake))
    println("adjoint_sensitivities   ", fmt(b_grad), "  ($(length(b_grad.times)) samples)")
  • [P2] Enzyme regression test: added. The Lotka–Volterra UDE test now differentiates the loss with GaussAdjoint(autojacvec = EnzymeVJP()) explicitly and compares it with ForwardDiff (that comparison was marked broken, but only missed the default isapprox tolerance), and checks that Enzyme.make_zero returns the block's wrapper itself, which fails if the default chain stops being constant for Enzyme.

posted by Claude claude-opus-5-5 on behalf of Sebastian

SebastianM-C and others added 2 commits November 30, 2026 03:23
Finite differences agree with ForwardDiff to a relative error of about 1.4e-4,
just above the old rtol of 1e-4, so the test was marked broken (with a
`broken -= true` typo). Use rtol = 1e-3 instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A DimensionMismatch from outputsize means a wrong n_input, so falling back
to evaluating the network hides it whenever the evaluation does not check
sizes. On Julia 1.10, LuxLib's LoopVectorization matmul (active once
SimpleChains is loaded) skips that check, so a Chain of Dense layers with a
wrong n_input was accepted. Other outputsize errors, such as the NilArray
pointer error of SimpleChains models, still use the fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants