Skip to content

Krylov: support an ArrayPartition right-hand side - #1206

Merged
ChrisRackauckas merged 7 commits into
SciML:mainfrom
AJ0070:feat/384-arraypartition-krylov
Aug 14, 2026
Merged

ChrisRackauckas merged 7 commits into
SciML:mainfrom
AJ0070:feat/384-arraypartition-krylov

Conversation

@AJ0070

@AJ0070 AJ0070 commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Checklist

  • Appropriate tests were added
  • Any code changes were done in a way that does not break public API
  • All documentation related to code changes were updated
  • The new code follows the
    contributor guidelines, in particular the SciML Style Guide and
    COLPRAC.
  • Any new documentation only uses public API

Additional context

  • Closes RecursiveArrayTools.jl Support #384. KrylovJL_* on an ArrayPartition right-hand side failed before any iteration ran, which is what the issue's KenCarp47(linsolve = KrylovJL_GMRES()) example hits. The factorization algorithms already worked.
  • Krylov.jl allocates its workspace as S(undef, n) with S = typeof(b), which an ArrayPartition cannot provide: it is stored as several separate arrays, so there is no way to know how to split n across them.
  • Krylov.KrylovConstructor builds the workspace with similar instead, so the solve runs on the partitioned vectors directly: no flattening, no copying, and u comes back in the type it went in as. Pointed out by @amontoison. It is present in every Krylov 0.10.x, so the existing compat bound already covers it and this PR adds no dependency and changes no Project.toml entry.
  • solve! needs no specialization: the workspace holds the caller's array type throughout, so the generic path writes the answer straight into it.
  • There was already a method meant to dodge this, but it declared no zeroinit, so the solve! path (which always passes zeroinit = false) never reached it. Adding the keyword alone would not have been enough: solve! hands the cacheval straight to Krylov as the workspace, so returning nothing just fails later.
  • Tests cover five Krylov algorithms, three uneven partitions, cached re-solves picking up a new b and a new A, and that the partitioned shape survives. They were confirmed to fail without the fix, with the original error from the issue.
  • The FAQ says what the requirement actually is: similar support, rather than any particular interface.
  • Core and QA groups pass locally, on Julia 1.10 and 1.12.

Comment thread src/iterative_wrappers.jl Outdated
# The previous method here returned `nothing` to dodge the workspace allocation, but
# it declared no `zeroinit`, so the `solve!` path below (which always passes
# `zeroinit = false`) never reached it and hit the error anyway.
_krylov_flat(x::RecursiveArrayTools.ArrayPartition) = copyto!(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of a special new function here, it should use the ArrayInterface.jl primitive for vector flattening.

@AJ0070 AJ0070 Aug 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ChrisRackauckas second one applied, restructure is better than the copyto! here.

On the first: safevec returns an AbstractVector unchanged (safevec(v::AbstractVector) = v), and ArrayPartition is one, so it does not flatten and cannot build the workspace Krylov needs. There is no RecursiveArrayTools extension in ArrayInterface adding a method either.

Did you have a different primitive in mind? Otherwise the options are Vector(b), which forces a CPU array and would break GPU-backed partitions, or the current similar(first(b.x), length(b)) form which keeps the backing type. Happy to inline it rather than name it if the objection is to the helper itself.

Blocked on this one, the rest of the PR is green.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this is a better fit to SciMLStructures.jl and its canonicalize framework.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this. canonicalize(::Tunable, p::AbstractArray) = vec(p), ArrayRepack(p), true, and vec of an ArrayPartition returns the same ArrayPartition, so the buffer comes back unflattened. The repack half then errors:

The original type ArrayPartition{...} does not support the SciMLStructures interface via
the AbstractArray `repack` rules. No method exists to take in a regular array and construct
the parent type back. Please define the SciMLStructures interface for this type.

RecursiveArrayTools does not define canonicalize for ArrayPartition, so it falls back to the generic array method that assumes vec flattens. ArrayRepack itself calls ArrayInterface.restructure, which is what this PR already uses for the write-back.

Happy to add the SciMLStructures interface for ArrayPartition in RecursiveArrayTools and then simplify this to a canonicalize/repack pair. Should that land first, or go with the flat cache here and switch over once it does?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to add the SciMLStructures interface for ArrayPartition in RecursiveArrayTools and then simplify this to a canonicalize/repack pair. Should that land first, or go with the flat cache here and switch over once it does?

Yes let's do that. And then we should document that any type that wants to be compatible with this should define the SciMLStructures.jl interface. That makes it a general solution.

Comment thread src/iterative_wrappers.jl Outdated
flat.abstol, flat.reltol, flat.maxiters = cache.abstol, cache.reltol, cache.maxiters

sol = SciMLBase.solve!(flat, alg; kwargs...)
copyto!(cache.u, sol.u)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is making too strong of an assumption. It should use an ArrayInterface.restructure

@amontoison

Copy link
Copy Markdown
Contributor

A few months ago, I added this constructor in Krylov.jl such that we can use similar instead of S(undef, n) during the creation of the workspace:
https://jso.dev/Krylov.jl/dev/inplace/#Krylov.KrylovConstructor

AJ0070 added 5 commits August 13, 2026 10:16
Krylov.jl allocates its workspace as `S(undef, n)` with `S = typeof(b)`,
and `ArrayPartition(undef, n)` is defined only for a single partition,
since there is no way to know how to split `n` across several. Krylov
also requires `ktypeof(b)` to match the workspace storage, so giving it
plain `Vector` storage next to a partitioned right-hand side is rejected
too.

There was already a method here meant to dodge this, but it declared no
`zeroinit`, so the `solve!` path (which always passes `zeroinit = false`)
never reached it and hit the error anyway. Returning `nothing` would not
have been enough either: `solve!` hands the cacheval straight to Krylov
as the workspace.

The cacheval is now the flat cache the solve runs on, built once and
reused, with the answer copied back into the partitioned `u`. `A` needs
no wrapping: an `ArrayPartition` and the vector it flattens to have the
same length, so a matrix or operator sized for one multiplies the other
unchanged.

Closes SciML#384.
Review feedback: writing the flat result back with `copyto!` assumes `u`
is writable and laid out to receive it. `ArrayInterface.restructure`
rebuilds the partitioned shape without that assumption.
Review feedback: the flattening and the way back belong to the
SciMLStructures canonicalize framework rather than to a helper here.
`canonicalize(Tunable(), b)` gives the flat buffer, and its own `repack`
rebuilds the container, replacing both the hand-rolled flatten and the
`ArrayInterface.restructure` call.

`ArrayPartition` gained the interface in RecursiveArrayTools 4.4, so the
compat bound moves up to it.

The body is split into `_init_flat_krylov_cacheval` and
`_solve_flat_krylov!`, so another right-hand side type Krylov cannot
allocate for opts in with two forwarding methods rather than a copy of
the logic. Documented in the FAQ, since that is the general answer: a
type works here if it implements the SciMLStructures interface.
Krylov.jl has a `KrylovConstructor` that allocates the workspace with
`similar` rather than `S(undef, n)`, which is exactly what an
`ArrayPartition` cannot provide. Using it, the solve runs on the
partitioned vectors directly: no flattening, no copying, and `u` comes
back in the type it went in as.

That drops the flat cache, the SciMLStructures dependency, the
RecursiveArrayTools compat bump, and the `solve!` specialization, since
the workspace now holds the caller's array type throughout and the
generic path writes straight into it.

The FAQ says what the real requirement is: `similar` support, rather
than the SciMLStructures interface.

Pointed out by @amontoison on the PR.
A local workaround for a stale registry leaked into the previous commit.
@AJ0070
AJ0070 force-pushed the feat/384-arraypartition-krylov branch from 235ab4c to 676b5ab Compare August 13, 2026 05:39
@AJ0070

AJ0070 commented Aug 13, 2026 •

Copy link
Copy Markdown
Member Author

@amontoison thanks, that is much better than what this had. Rewritten to build the workspace with KrylovConstructor, so the solve runs on the partitioned vectors directly: no flattening, no copying, and u comes back in the type it went in as. It is present in every 0.10.x, so the existing Krylov = "0.10" compat already covers it.

@ChrisRackauckas this replaces the SciMLStructures approach. That version canonicalized to a flat buffer and repacked, which worked but copied twice per solve and needed a SciMLStructures dependency plus a RecursiveArrayTools 4.4 bound. The Krylov constructor needs neither, so the diff is now four files with no Project.toml change at all.

SciML/RecursiveArrayTools.jl#643 still stands on its own: ArrayPartition genuinely lacked the SciMLStructures interface and the generic repack errored for it. It just turned out not to be what this needed.

The FAQ entry changed accordingly: the requirement is similar support rather than a particular interface, which is both simpler and broader.

@amontoison

amontoison commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

It is better to use S(undef, n) when it is supported because we avoid (in Krylov.jl) to allocate "optional" vectors that are needed for regularization, warm-start or preconditioners with S(undef, 0). We allocate these additional vectors on-the-fly in the workspace if we need them.

Another advantage is that I have an internal ktypeof(b) and if b is a sparse vector, I detect it and allocate the KrylovWorkspace with the most relevant dense vector type.
The most common case is b isa SparseMatrixVector.

I will not suggest to use KrylovConstructor by default for all array types. I added for advanced users that are sure that they don't have alternatives with their array types and require similar.

One constructor is for performance while the other one is for portability.

@AJ0070

AJ0070 commented Aug 13, 2026

Copy link
Copy Markdown
Member Author

That matches what this does. KrylovConstructor is used only for b::ArrayPartition, where S(undef, n) has no valid answer, since the partitions are separate arrays and there is no way to know how to split n across them. The generic init_cacheval is untouched, so Vector, a sparse b, and everything else keep the KS(A, b) path with ktypeof picking the storage and the optional vectors staying zero length.

Three methods now: the generic one, the batched matrix one, and the ArrayPartition one. So it is the portability constructor only where there is no alternative, as you describe, and the ArrayPartition case does give up the on-the-fly optional vectors in exchange for working at all.

@amontoison

Copy link
Copy Markdown
Contributor

Great! I think it is the current best solution.

@ChrisRackauckas

Copy link
Copy Markdown
Member

@ChrisRackauckas this replaces the SciMLStructures approach. That version canonicalized to a flat buffer and repacked, which worked but copied twice per solve and needed a SciMLStructures dependency plus a RecursiveArrayTools 4.4 bound. The Krylov constructor needs neither, so the diff is now four files with no Project.toml change at all.

It shouldn't allocate at all. You only do it once in the init phase, and then in the solve you only use replace!. Then it's non-allocating.

Another advantage is that I have an internal ktypeof(b) and if b is a sparse vector, I detect it and allocate the KrylovWorkspace with the most relevant dense vector type.
The most common case is b isa SparseMatrixVector.

This does not seem equivalent at all. What does it do on an MTKParameters object? @AJ0070 test it with this object: https://sciml.github.io/SciMLStructures.jl/stable/example/ . The SubproblemParameters is the kind of thing we'd want to support for adjoints, and I am not sure this is going to work because Krylov.jl does not do the destructuring.

@ChrisRackauckas

Copy link
Copy Markdown
Member

That matches what this does. KrylovConstructor is used only for b::ArrayPartition, where S(undef, n) has no valid answer, since the partitions are separate arrays and there is no way to know how to split n across them. The generic init_cacheval is untouched, so Vector, a sparse b, and everything else keep the KS(A, b) path with ktypeof picking the storage and the optional vectors staying zero length.

You mean an Array path, AbstractArray path, and a isscimlstructures path? That's what I'd expect this to land on.

Comment thread src/iterative_wrappers.jl Outdated
Comment on lines +358 to +360
# than guessing. `Krylov.KrylovConstructor` builds the workspace with `similar`
# instead, which such a type does support, so the solve runs on the partitioned
# vectors directly with no flattening and no copying.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The general type does not support similar

@AJ0070

AJ0070 commented Aug 13, 2026

Copy link
Copy Markdown
Member Author

Tested the Parameters object from the docs example. You were right, and my "replaces" framing was wrong.

similar(p)                               MethodError
length(p)                                MethodError
GmresWorkspace(KrylovConstructor(p, p))  MethodError: no method matching zero(::Type{Any})
canonicalize -> solve flat -> repack     works, repacks with subparams and coeffs intact

KrylovConstructor needs similar and the array interface, so it covers ArrayPartition but not a non-array structure. The two are complementary rather than alternatives. Fair on the allocation too: canonicalizing once in init and using replace! in the solve is non-allocating, and my earlier version copying per solve was my mistake rather than the approach's. I have corrected the comment that claimed similar support in general.

One thing worth deciding before I build the third path. It cannot be an init_cacheval method next to the other two, because init fails before any algorithm dispatch:

zero(::Type{Any})  <-  real(T::Type)  <-  __init(...)

eltype(p) is Any, so real(eltype(b)) throws while computing tolerances, well before init_cacheval is reached. So the structure path has to canonicalize at the top of __init, carry the repack on the cache, and repack when the solution is built. That is core common.jl work affecting every algorithm, not just KrylovJL, which is arguably the right place since a structured b is broken for all of them today, not only Krylov.

So the three paths are not the same shape: Array and AbstractArray are init_cacheval methods, the structure one is an init-level change.

Do you want that in this PR, or land the two array paths here for #384 and do the structure path separately? Happy either way, just checking since it widens the blast radius from the Krylov wrapper to the shared init path.

@ChrisRackauckas

Copy link
Copy Markdown
Member

I also don't think this is something Krylov specific at all: it should be done at a higher level. At least the SciMLStructures interfacing. So it's probably fine to finish this PR as a limited Krylov-specific abstractarray thing, but we should then bubble through more general structure support.

Review feedback: the comment claimed `similar` support in general. It is
an `ArrayPartition` property. A right-hand side that is not an array at
all, such as a parameter object implementing the SciMLStructures
interface, supports neither `S(undef, n)` nor `similar` and needs
canonicalizing instead, which this does not handle.
Review asked that the docs say a type wanting to work here should
implement the SciMLStructures interface, which is the general solution.
The entry said only that `similar` is needed, which is true of what this
PR implements but drops that direction, and it advised writing an
`init_cacheval` method, which is not something a caller can do from
outside the package.

Says what works today, and points at the interface and SciML#1208 for the
non-array case.
@AJ0070

AJ0070 commented Aug 14, 2026 •

Copy link
Copy Markdown
Member Author

@ChrisRackauckas this is at the scope you described, a Krylov-specific AbstractArray fix, with the general structure support tracked separately in #1208.

Everything raised is in:

  • KrylovConstructor only for b::ArrayPartition. The generic init_cacheval is untouched, so Vector, a sparse b and batched matrices keep the KS(A, b) path with ktypeof picking the storage.
  • The comment no longer claims similar support in general.
  • The FAQ names the SciMLStructures interface as the general answer for a right-hand side that is not an array, pointing at Support SciMLStructures right-hand sides at the init level #1208, rather than only mentioning similar.

Could you clear the changes-requested when you get a chance?

@ChrisRackauckas
ChrisRackauckas merged commit b45ec89 into SciML:main Aug 14, 2026
57 of 62 checks passed
@AJ0070

AJ0070 commented Aug 14, 2026

Copy link
Copy Markdown
Member Author

Thanks @ChrisRackauckas and @amontoison for the reviews on this one.

The result ended up a good deal smaller than where it started. @amontoison pointing at KrylovConstructor removed the flattening and the copying entirely, and the earlier push toward SciMLStructures turned up two things worth having on their own: SciML/RecursiveArrayTools.jl#643, since ArrayPartition genuinely lacked the interface, and SciML/SciMLStructures.jl#79, where isscimlstructure opts in numeric arrays whose repack then errors.

Also useful was the request to test an MTKParameters-shaped object, which is what established that the array and structure cases need different routes rather than one replacing the other. That is now #1208, and I have a working implementation of it in progress.

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.

RecursiveArrayTools.jl Support

3 participants