Skip to content

HighOrderLowRankOp ​

Use HighOrderLowRankOp to apply an MRI encoding model repeatedly without materializing its full sample-by-voxel phase matrix. It combines NFFT Fourier encoding with low-rank factors for the remaining phase. The default construction is Incremental Shared: local randomized SVD (rSVD) followed by incremental spatial sharing. See the low-rank derivation for the equations, approximation stages and references.

Readout index i runs over nDyn encoding profiles of the same image. Input coefficients have shape (nTerm,nSam,nDyn), and times have shape (nSam,nDyn). The single-readout constructor also accepts a coefficient matrix and a time vector. The generated API below gives the complete signatures, defaults and return layout.

Algorithm selection

Use method=:per_readout, :incremental_shared, or :direct_shared. Direct Shared selects strategy=:per_readout (default for that method) or :global; Global additionally requires epsilon_H. Construction settings are independent of execution and storage. Use the method guide for the implementation pages.

A complete CPU example ​

This example defines a small Cartesian grid, two readouts, two coils, a nonzero static field map and a varying second-order field term. It computes synthetic samples and an adjoint backprojection; it does not solve an inverse problem or test convergence on measured data.

julia
using HighOrderMRI
using LinearAlgebra

T = Float32
nX, nY = 8, 8
nSam, nDyn, nCha = nX * nY, 2, 2
grid = Grid(nX, nY, 1, T(1e-3), T(1e-3), T(1e-3))

# Metres, seconds, Hz; the phase coefficients use cycles and cycles/m^p.
kx = T.(-4:3) ./ (T(nX) * grid.Δx)
ky = T.(-4:3) ./ (T(nY) * grid.Δy)
times = repeat(reshape(T.(0:nSam-1) .* T(1e-5), :, 1), 1, nDyn)
kspha = zeros(T, 9, nSam, nDyn)
for i in 1:nDyn
    kspha[1, :, i] .= T(0.03) * T(i)
    kspha[2, :, i] .= repeat(kx, nY)
    ky_samples = repeat(ky; inner=nX)
    kspha[3, :, i] .= i == 1 ? ky_samples : reverse(ky_samples)
    kspha[5, :, i] .= T(i) .* range(T(-500), T(500); length=nSam)
end

fieldmap = reshape(collect(range(T(-15), T(15); length=nX*nY)), nX, nY, 1)
csm = ones(Complex{T}, nX, nY, 1, nCha)
csm[:, :, 1, 2] .= Complex{T}(T(0.8), T(0.2))
mask = trues(nX, nY, 1)
image = zeros(Complex{T}, nX, nY, 1)
image[3:6, 3:6, 1] .= Complex{T}(one(T), T(0.25))
image[4:5, 4:5, 1] .= Complex{T}(T(0.5), T(-0.2))

op = HighOrderLowRankOp(grid, kspha, times;
    fieldmap, csm, mask,
    arrayType=Array,
    method=:incremental_shared,
    normal_distribution=:single,
    L_rank=4,
    rsvd_oversample=4,
    rsvd_seed=1234,
    shared_rank_max=8,
    shared_basis_tol=T(1e-3),
)

signal, backprojection = try
    samples = reshape(op * vec(image), nSam, nDyn, nCha)
    adjoint_image = reshape(adjoint(op) * vec(samples), nX, nY, 1)
    samples, adjoint_image
finally
    close(op)
end

@assert size(signal) == (nSam, nDyn, nCha)
@assert norm(signal) > zero(T)

Samples vary fastest, then readouts, then coils. For reconstruction, preserve that ordering and form reshape(signal, nSam*nDyn, nCha) for recon_HOOp. The backprojection above is AHy, not a reconstructed solution. Rank and tolerance values in this small example are illustrative choices, not settings validated for a full brain.

Use the default centred Cartesian coordinates on the active NFFT axes. In 2D, only kx and ky enter the NFFT; kzz remains in the residual phase. Changing grid coordinate vectors alone does not change the NFFT geometry. See coordinate scope before applying permutations, reversals or offsets.

Incremental Shared construction ​

For each readout i, local rSVD retains L_rank factors of the residual phase matrix. The sketch must satisfy L_rank + rsvd_oversample <= min(nSam,count(mask)). Incremental sharing then combines those retained spatial factors. When the basis grows, earlier saved coefficient blocks are zero-padded; they are not recomputed as projections onto the completed basis. This procedure is not a global optimal SVD.

shared_basis_tol controls the incremental compression of retained local factors. It is not a bound on the original full phase matrix or image error. Optional global_basis_tol introduces a further error relative to the already shared representation. NFFT approximation and local rSVD truncation remain separate error sources.

Optional sampled construction and weighted compression ​

These additions are disabled by default. shared_readout_count=nothing uses every readout, shared_fit_samples=nothing keeps the original local temporal projection, and no new compression runs unless explicitly requested. Existing global_basis_tol calls keep the original unweighted path.

For shared rSVD, use shared_readout_count=64, shared_fit_samples=512 to train a spatial basis on representative readouts and fit coefficients for every original time sample. The numbers are configurable experiment settings, not general accuracy recommendations. Readout selection uses a sampled phase-geometry proxy; it is not a full-time coverage certificate. Supplying shared_basis_report=Ref{Any}() records selected readouts, training voxels, conditioning and phase checks, including a post-compression check.

global_basis_rank=18 selects a fixed final rank instead of global_basis_tol. With either selector, global_basis_weights=D uses real nonnegative sample weights already equal to abs2.(w); they are not squared again. global_basis_coil_weighting=true also uses summed CSM energy. The weights define the compression metric only. Reconstruction still receives its own original weights. This path uses blocked FP64 Grams and accounts for the actual spatial Gram. Its tail error concerns the existing factors, not the original phase matrix or reconstructed image. A fixed global_basis_rank is not an image-error target; inspect compressed_phase_check and complete reconstruction metrics before choosing it. Direct Shared retains its own validation and rejects these post-compression options.

Optional no-add check ​

shared_noadd_check affects basis construction, independently of the reconstruction distribution. It is disabled by default and requires the shared, voxel-distributed CUDA rSVD path with Gram finalization.

The update still performs both projection passes and forms the full residual. It accumulates residual energy in FP64 and, when a numerical guard places that energy safely below the tolerance allowance, skips the residual-Gram matrix and its eigendecomposition. Other cases use the original path. The check does not change the requested local rank or reconstruction sample batches. It does not establish a memory or runtime benefit for a particular measured dataset.

Independent readouts ​

method=:per_readout retains the local factors independently, without incremental sharing or final shared-basis recompression. The resident option stores those factors on the selected array backend. CUDA also supports host factor streaming (per_readout_storage=:cpu) and regeneration from retained Q/Z factors (:regenerate), with their additional setup and cache constraints listed in the generated API. These storage modes do not select the CG partition by themselves.

Choose setup and reconstruction execution separately ​

rsvd_distribution controls factor construction. normal_distribution controls operator execution during iterative reconstruction; its default is :single. For rank execution it also selects the direct forward and adjoint paths.

normal_distributionWork and persistent storage
:singleCPU with arrayType=Array, or the primary GPU with CuArray.
:channelCoil groups. In the shared layout, every worker retains the full temporal and spatial factors; coil-map storage is partitioned.
:rankShared factor columns and coil-map storage are partitioned. Complete factor and coil-map masters remain in host RAM.
:readoutIndependent readout groups, requiring method=:per_readout; every worker retains all coil maps.

The distributed reconstruction modes require CUDA and at least two unique GPU IDs. IDs are zero based within CUDA's visible device list, and first(gpus) is the primary GPU for solver vectors. Rank execution supports Incremental Shared with voxel-distributed Gram setup and the Direct Shared Global strategy. It does not support the Direct Shared Per-readout strategy. Its worker count is at most min(length(gpus), shared_rank, nCha), so selecting several devices does not guarantee they all participate.

The setup requirement is different: explicit rsvd_distribution=:voxel accepts one or more unique GPU IDs; the list must be nonempty and must not contain more devices than masked voxels. Automatic voxel setup requires multiple GPUs, the kernel backend and Gram finalization; chunked voxel setup requires explicit selection. The generated API gives the exact combinations. Use the multi-GPU guide for complete device configurations.

Optional batched CUDA execution ​

HighOrderMRINonuniformFFTsExt is an automatically loaded Julia package extension for HighOrderMRI and NonuniformFFTs. It adds methods for the existing NonuniformFFTs backend; it does not register an independent NUFFT backend or provide another backend value. Loading the extension alone leaves normal_method=:standard in effect. The selections have separate roles:

SettingRoleDefault
methodBuild Per-readout, Incremental Shared or Direct Shared factors.:incremental_shared
strategySelect Direct Shared's Per-readout or Global strategy.nothing, selecting Per-readout for Direct Shared
normal_distributionAssign the reconstruction work to devices.:single
normal_methodEvaluate completed factors with standard or batched kernels.:standard
AbstractNFFTs.set_active_backend!Choose the NUFFT library.Existing active backend.

normal_method=:standard keeps existing execution. normal_method=:batched opts into Julia CUDA kernels and batched cuFFT for 3D Float32 shared factors, with either Incremental Shared or Direct Shared construction. Load the optional backend first:

julia
using HighOrderMRI, CUDA, AbstractNFFTs, NonuniformFFTs
AbstractNFFTs.set_active_backend!(NonuniformFFTs.backend())

NonuniformFFTs itself activates its backend when imported, as it did before this extension; the explicit selection above makes the intended library clear. The HighOrderMRI extension does not switch backends. Check that it loaded with Base.get_extension(HighOrderMRI, :HighOrderMRINonuniformFFTsExt). For an updated path-tracked checkout, Pkg.resolve() in the active environment may be needed to refresh extension metadata; restart Julia afterward.

Then pass normal_method=:batched, normal_coil_batch_size=8 to HighOrderLowRankOp. Coil batches 2, 4 and 8 are supported, including a partial last batch. Larger batches use more memory. normal_distribution=:single uses one GPU; :channel retains the existing multi-GPU coil partition. CPU, 2D, Float64, independent-readout and rank-sharded evaluation continue to use the standard path. Explicitly requesting an unsupported batched configuration throws an error.

The extension is version-bound to the tested NonuniformFFTs 0.9.6 internals. It does not change the selected backend globally, trajectory nodes, logical FFT sizes, NUFFT support or factors. It uses no native CUDA binaries or VkFFT. The initial normal request owns its workspaces through the existing parent; close(op) releases them, including batched single-GPU execution. Bare adjoints never apply the normal weights again. Floating-point accumulation order may differ from the standard implementation. The parent's ordinary forward remains on its existing path; a bare adjoint reuses the batched workers only after the first normal request initializes them.

For existing 3D Float32 inputs, execution-only opt-in looks like:

julia
using LinearOperatorCollection: normalOperator

op = HighOrderLowRankOp(grid, kspha, times;
    fieldmap, csm, mask,
    arrayType=CuArray, gpus=[0, 1],
    normal_distribution=:channel,
    normal_method=:batched, normal_coil_batch_size=8,
)
try
    D = CuArray(abs2.(w))             # One WᴴW value per sample, not per coil.
    N = normalOperator(op, D)        # Initialize before a solver's bare adjoint.
    # Apply N or run the existing reconstruction workflow with the same settings.
finally
    close(op)
end

This leaves the factor-construction settings unchanged. Incremental Shared sampling, coefficient refitting and weighted compression in the earlier section are separate opt-ins that change the approximation. Direct Shared retains its own rank selection and checks; batching does not remove a high-B0 audit warning.

Experimental pruned FFT combination ​

normal_options=(;) retains the batched Julia kernels and cuFFT. Optional native build sources and instructions are in deps/pruned_fft/README.md. Set the documented build environment variables and explicitly run bash deps/pruned_fft/build.sh <output-directory> from the package root. After building local resources, the batched path also accepts:

julia
normal_options=(
    fft=:vkfft_pruned,
    native_ptx="/path/to/resources/highorder_native.ptx",
    vkfft_library="/path/to/resources/libhighorder_vkfft.so",
    coefficient_cache_bytes=1 << 30,
)

This experiment combines native scatter/unrolled gather, VkFFT pruning of known padding intervals, compact image padding and budgeted Float32 coefficient caching. The budget is per worker; zero disables the cache. Full weights, masked voxels, coils, factors and the logical NUFFT grid remain unchanged. The parent owns and closes each worker's foreign FFT plan and native module. Missing resources and unsupported configurations throw errors. The experiment requires local compiled resources; it is not a portable binary distribution. It is independent of factor construction and remains disabled by default.

Why rank execution must combine forward contributions ​

Coil groups contain independent observation rows, so their normal contributions can be summed. Rank groups instead contribute to the same samples. If A=∑gAg, then

AHWHWA=∑g∑hAgHWHWAh.

The implementation combines forward samples across rank workers before applying the weights and adjoint. Summing only AgHWHWAg would omit the cross-rank terms. The reductions and transfers use host staging buffers; GPU memory is not a single shared pool. Each rank worker evaluates all coils. If a coil map is absent from its local storage, the worker uploads that map from the host master.

Sample batching and data placement ​

normal_sample_batch_size limits the number of sample/readout points in each rank-mode batch. Its effective size is min(nSam*nDyn, normal_sample_batch_size). It bounds sample workspaces, not complete factor columns, coil maps, image grids, solver vectors, input/output data, host masters or setup buffers. The other reconstruction distributions do not use this parameter for batching.

With the current NFFT.jl 0.14.3 GPU backend, use a full batch or an exact divisor of nSam*nDyn: its node-update path does not support a shorter final output batch. See sample batching for the backend-specific limitation. Reducing a batch cap therefore is not sufficient to establish that the complete problem fits in GPU memory.

In rank mode, op.q, op.basis and op.csm are host matrices, while solver storage is on the primary GPU. Consequently, allocating op * x returns a host vector in this mode. Use mul! with an appropriately sized GPU output, or transfer the result before reconstruction. CUDA LowRank reconstruction requires the data matrix and raw weight vector on the primary GPU; recon_HOOp does not move them automatically. It returns a CPU image.

Release owned resources ​

Use try/finally and close(op) after the final direct forward, adjoint or normal use. recon_HOOp releases the distributed backend by default; if release_backend=false, the caller retains that responsibility.

The parent operator owns the workers. release_highorder_normal_backend!(op) releases that backend; close(op) also releases any source streaming or regeneration queue. Closing a derived normal view alone does not release the parent's workers. For distributed normal execution, release the existing backend before changing normal weights and obtain a fresh normal view. Host factor masters remain referenced until the parent and other references are dropped. See resource lifecycle before replacing a large operator.

API ​

The following source-generated reference separates the operator type, the single-readout convenience constructor and the multi-readout constructor.

Operator type ​

julia
HighOrderLowRankOp

Represent high-order MRI encoding with NFFT Fourier transforms and low-rank residual-phase factors. Its element type is Complex{T}, with real precision T as the first type parameter.

The zeroth-order coefficient supplies a temporal phase. In 3D, NFFT handles kx*x + ky*y + kz*z; in 2D it handles only kx*x + ky*y, leaving kz*z in the residual. Static off-resonance, selected higher-order terms, and optional concomitant terms also enter the residual. The forward phase uses exp(+2π * im * phase) and normalization 1/sqrt(nVox), where nVox is the number of masked voxels.

Incremental Shared (method=:incremental_shared, the default) builds local factors for each readout and merges their spatial directions. method=:per_readout retains independent factors from the same rSVD front end. Local truncation, incremental sharing, and optional final recompression introduce distinct approximation errors. Incremental sharing is not a global optimal SVD of all readouts.

Construct the operator with either the single-readout or multi-readout constructor below. The object owns mutable workspaces and optional GPU workers; it and its derived normal views must not be used concurrently. Use close(op) to release owned distributed resources and streaming caches. See Low-rank theory for the factorization and Resource ownership for reuse and cleanup.

Direct Shared (method=:direct_shared) uses strategy=:per_readout for snapshot-prefix selection with per-readout checks, or strategy=:global for all-time coefficient recompression and global H-error selection.

Source: src/EncodingOperator/HighOrderLowRankOp.jl

Single-readout constructor ​

julia
HighOrderLowRankOp(
    grid :: Grid{T} ,
    kspha :: AbstractArray{T, 2} ,
    times :: AbstractArray{T, 1} ;
    kwargs...
) where T <: AbstractFloat

Construct the operator for one readout by adding a singleton readout dimension and forwarding to the multi-readout constructor.

kspha has shape (nTerm, nSam) with 9 or 16 solid-harmonic coefficients, and times has shape (nSam,). Their real element type matches Grid{T}. Use seconds for times when fieldmap is in Hz. Keyword options, coordinate conventions, and resource ownership are those of the multi-readout constructor.

The default nominal trajectory is obtained after reshaping kspha. An explicit k_nominal keyword must still have shape (3, nSam, 1), because keyword arguments are forwarded unchanged. concomitant accepts either (4, nSam) or (4, nSam, 1) for this overload.

The result has dimensions (nSam*nCha, prod(grid.matrixSize)) and element type Complex{T}. The image vector covers the full grid; the forward ignores masked-out voxels and the adjoint fills those voxels with zero.

Source: src/EncodingOperator/HighOrderLowRankOp.jl

Multiple-readout constructor ​

julia
HighOrderLowRankOp(
grid              :: Grid{T}                                                             ,
kspha             :: AbstractArray{T, 3}                                                 ,
times             :: AbstractArray{T, 2}                                                 ;
method            :: Symbol                    = :incremental_shared                     ,
strategy          :: Union{Nothing,Symbol}     = nothing                                 ,
fieldmap          :: AbstractArray{T}          = zeros(T, grid.matrixSize...)            ,
csm               :: AbstractArray{Complex{T}} = ones(Complex{T}, grid.matrixSize..., 1) ,
mask              :: AbstractArray{Bool}       = trues(grid.matrixSize...)               ,
concomitant                                    = nothing                                 ,
recon_terms       :: Union{Nothing,AbstractString} = nothing                            ,
k_nominal         :: AbstractArray{T, 3}       = kspha[2:4, :, :]                        ,

arrayType         :: Type{<:AbstractArray}     = Array                                   ,
gpus              :: Vector{Int}               = [0]                                     ,
L_rank            :: Int                       = 15                                      ,
rsvd_seed         :: Int                       = 1234                                    ,
rsvd_chunk        :: Int                       = 4096                                    ,
rsvd_oversample   :: Int                       = 5                                       ,
rsvd_finalize     :: Symbol                    = :svd                                    ,
rsvd_backend      :: Symbol                    = :auto                                   ,
rsvd_distribution :: Symbol                    = :auto                                   ,
per_readout_storage:: Symbol                   = :gpu                                    ,
per_readout_cache_size:: Int                   = 5                                       ,
per_readout_gather:: Symbol                    = :pipeline                               ,
per_readout_host_cache_bytes:: Int             = 0                                       ,
shared_rank_max   :: Int                       = 128                                     ,
shared_basis_tol  :: T                         = T(1e-2)                                 ,
shared_noadd_check::Bool                       = false                                   ,
global_basis_tol  :: Union{Nothing,T}          = nothing                                 ,
global_basis_rank :: Union{Nothing,Int}         = nothing                                 ,
global_basis_weights                            = nothing                                 ,
global_basis_coil_weighting :: Bool              = false                                   ,
shared_readout_count :: Union{Nothing,Int}       = nothing                                 ,
shared_fit_samples :: Union{Nothing,Int}         = nothing                                 ,
shared_basis_report :: Union{Nothing,Ref}        = nothing                                 ,
epsilon_H         :: Union{Nothing,Real}        = nothing                                 ,
adaptive_options  :: NamedTuple                = (;)                                     ,
joint_snapshots   :: Int                       = 256                                     ,
joint_samples     :: Int                       = 512                                     ,
joint_roi_tol     :: Union{Nothing,T}          = nothing                                 ,
joint_basis_report:: Union{Nothing,Ref}        = nothing                                 ,
normal_distribution:: Symbol                   = :single                                 ,
normal_method     :: Symbol                    = :standard                               ,
normal_coil_batch_size :: Int                  = 8                                       ,
normal_options    :: NamedTuple                = (;)                                     ,
normal_sample_batch_size:: Int                 = 12_000_000                              ,
nfft_center_correction :: Bool                 = true                                    ,
verbose           :: Bool                      = false                                   ,
) where T <: AbstractFloat

Select method=:per_readout, :incremental_shared (default), or :direct_shared. Direct Shared uses strategy=:per_readout by default or :global with an explicit epsilon_H. Construction and execution options are independent.

Construct a low-rank encoding operator for nDyn readouts. The defaults use CPU arrays, local rSVD, a shared spatial basis, and single-device execution. The keyword normal_distribution selects reconstruction execution; rsvd_distribution independently selects how the factors are built.

method=:direct_shared, strategy=:global, epsilon_H=0.01 selects Direct Shared Global. It builds a stable snapshot master, fits all actual time rows, then uses blocked QR/small SVD and paired residual checks to select the final shared rank. K, J and the parent cap start at 128, 512 and 32; only a failed check triggers bounded expansion. shared_rank_max remains the hard parent cap. adaptive_options forwards resource and evaluation keywords to joint_adaptive_spatial_basis; rsvd_seed and rsvd_chunk provide its seed and chunk size. No NFFT setting changes.

The target is the global relative Frobenius error of the pure residual H over all readouts and masked voxels. It excludes k0, first-order NFFT, center phase, CSM, weights and normalization. The checks are empirical: sqrt(mean(loss)+4SE) is a heuristic, not a probability certificate or an image-error guarantee. joint_basis_report receives construction, empirical, external-audit and certification states without retaining factor arrays. Budget failure fills that report and throws instead of constructing an operator from partial factors. Existing shared_basis_tol and global_basis_tol retain their old meanings; Direct Shared Global requires global_basis_tol=nothing and does not impose joint_roi_tol.

The Per-readout strategy and its joint_* sampling controls remain available with their existing per-readout validation semantics.

Inputs and coordinate convention ​

  • grid: reconstruction grid with shape (nX,nY,nZ). NFFT assumes the centered regular coordinates implied by its dimensions and voxel spacings on the active Fourier axes. Arbitrarily transforming those coordinates is not accounted for by nfft_center_correction.
  • kspha: (nTerm,nSam,nDyn) time-integrated solid-harmonic coefficients, with nTerm=9 or 16. Readout index i selects kspha[:,:,i]. The basis ordering and normalization must match basisfunc_spha.
  • times: (nSam,nDyn) sample times. Use seconds with a field map in Hz; each coefficient times its spatial basis must likewise give phase in cycles.
  • fieldmap: real off-resonance map of shape (nX,nY,nZ); the default is zero. csm contains complex coil maps of shape (nX,nY,nZ,nCha) and defaults to one coil with unit sensitivity. mask is a Boolean grid mask, all true by default. For nZ==1, shapes (nX,nY) for fieldmap/mask and (nX,nY,nCha) for csm are accepted. Use consistent real precision T and complex precision Complex{T}.
  • concomitant=nothing: optional (4,nSam,nDyn) integrated coefficients for z², x²+y², xz, and yz. (4,nSam) is also accepted when nDyn==1. With coordinates in metres, coefficients are in cycles/m² in the same frame and origin. These terms enter the residual independently of recon_terms; they are already integrated and are not multiplied by times again.
  • recon_terms=nothing: resolve to "111" for 9 coefficients or "1111" for 16. The binary digits select zeroth-, first-, second-, and third-order terms. A zero removes the selected order except at first order, where it substitutes k_nominal. This substitution preserves nominal Fourier encoding rather than removing it. k_nominal has shape (3,nSam,nDyn), ordered kx,ky,kz; its default is the supplied first-order coefficients. First-order coefficients use cycles per coordinate-length unit.

In 2D, NFFT uses only kx,ky; any kz*z phase stays in the low-rank residual. In 3D all three linear terms enter NFFT. The nodes on each active axis are -k*Δ, with that axis's voxel spacing Δ. Keep nfft_center_correction=true to include the half-voxel phase on even-sized axes; odd-sized axes need no such phase. Zeroth-order phase, this correction, and 1/sqrt(nVox) are folded into q once.

Local rSVD and shared approximation ​

  • L_rank=15 is the local truncation rank for every readout, not the final shared rank. rsvd_oversample=5 sets the extra sketch width. Require L_rank>0, rsvd_oversample>=0, and L_rank+rsvd_oversample <= min(nSam,nVox), where nVox=sum(mask).
  • rsvd_seed=1234: readout i uses seed rsvd_seed+i-1. Repeatability requires the same backend and setup configuration; changing device count or numerical libraries is not a bitwise-reproducibility guarantee.
  • rsvd_backend=:auto chooses :chunked for Array and :kernel for CuArray. Explicit :kernel requires CUDA. rsvd_chunk=4096 must be positive and is capped at nVox; it controls voxel chunks for the chunked phase products. It is not a limit on all setup arrays or factor storage.
  • rsvd_finalize=:svd takes an SVD of the projected adjoint matrix. :gram uses a small Gram eigendecomposition to recover the retained factors. Both absorb the singular values into the spatial factors; finite-precision Gram calculations can lose accuracy in weak directions.
  • rsvd_distribution=:single builds on the selected CPU or primary GPU. Explicit :voxel requires CuArray, rsvd_finalize=:gram, and backend :kernel or :chunked. One GPU is accepted; multiple GPUs divide masked voxels. The current partitioning requires at least one voxel per selected setup GPU. :auto chooses voxel distribution only with CUDA, multiple GPUs, kernel products, and Gram finalization. Chunked voxel setup requires explicit :voxel.
  • method=:incremental_shared incrementally merges the local spatial factors. shared_rank_max=128 is a positive cap, clamped to min(nVox,L_rank*nDyn) for this path; exceeding it throws rather than silently relaxing the tolerance. shared_basis_tol=T(1e-2) controls the additional relative Frobenius residual of each local spatial factor V_i*Σ_i under the shared projection. It is not an error target for the original phase matrix or reconstructed image. Use a finite nonnegative tolerance below one. Earlier readout coefficients receive zero rows when the basis grows; they are not recomputed by a final global projection.
  • global_basis_tol=nothing preserves the incrementally shared factors. A nonnegative value of type T applies a final spectral recompression of that representation, introducing an additional error. This requires shared layout. Use a tolerance below one: the implementation accepts larger values, but its discarded-energy diagnostic is unreliable at global_basis_tol>=1 because it retains at least one direction.

Local truncation, shared projection, final recompression, and NFFT approximation are separate sources of error. A fixed L_rank does not certify a total phase-matrix or image error. See Low-rank theory for the factor definitions and references.

Optional no-add check ​

shared_noadd_check=false by default. Enabling it requires shared, voxel-distributed rSVD. Once a shared basis exists, the update keeps its two projection passes and forms the same explicit residual. It accumulates the residual energy in FP64 and applies a guard near the tolerance threshold. When that check accepts the existing basis, it skips the residual Gram matrix and eigendecomposition; otherwise it follows the usual update.

This option changes basis construction only. It does not select a CG execution strategy, reduce L_rank, change the tolerance, or remove the residual workspace. Its early-return diagnostic uses the full residual norm, which can differ from the ordinary diagnostic after tiny residual eigenvalues are discarded. That diagnostic difference is not fed back into the factors. The FP64 reduction does not make the preceding projection arithmetic FP64.

Independent factors and storage ​

method=:per_readout keeps each readout's local factors independently. The shared-rank cap and shared tolerance do not control those factors; global_basis_tol and shared_noadd_check=true are unsupported here.

  • per_readout_storage=:gpu materializes the spatial bank on arrayType. Despite the name, it uses CPU arrays with arrayType=Array.
  • :cpu requires CuArray execution and keeps the complete spatial bank in host RAM, transferring readout blocks into a bounded GPU cache.
  • :regenerate also requires CUDA and voxel-distributed kernel/Gram setup. It retains the original rSVD Q/Z and model maps, then generates uncached spatial blocks as (H_iᴴ*Q_i)*Z_i. It avoids materializing the full spatial bank, but retains metadata and regeneration workspaces and adds arithmetic. Regenerated factors are not promised to be bitwise identical to materialized factors.
  • per_readout_cache_size=5 is the positive number of resident readout slots per GPU, capped by the number of readouts. The streaming cache uses one pinned host staging buffer and completion events to protect reuse. With regeneration, one slot serializes production/use; multiple slots permit lookahead. These caches are used by forward, adjoint, and normal execution.
  • per_readout_gather=:pipeline overlaps voxel-distributed setup downloads and host writes using two pinned buffers per GPU. :synchronous uses a blocking gather. This choice does not change single-device setup.
  • per_readout_host_cache_bytes=0 is a nonnegative host budget for complete spatial blocks in regeneration mode. A fixed, evenly spaced subset of readouts is materialized during setup, shared by worker caches, and reused. Q/Z and model maps are additional storage outside this budget.

Execution, communication and sample batching ​

Use arrayType=Array for CPU execution or CuArray for CUDA. gpus=[0] contains unique zero-based CUDA-visible IDs; it must be nonempty. first(gpus) is the primary GPU for solver vectors. The public constructor has no separate primary_gpu keyword. Request at least two IDs for :channel, :readout, or :rank, all of which require CUDA:

  • normal_distribution=:single is the default CPU or primary-GPU path.
  • :channel divides coils, retaining complete shared factors on each active worker. Independent factors can instead use the selected per-readout storage scheme. This mode does not partition shared-rank columns.
  • :readout divides independent readouts and requires per-readout layout; each worker retains all coil maps. Workers sum contributions from disjoint observation rows.
  • :rank divides shared temporal/spatial columns and coil-map storage while retaining complete host master factors. It requires shared layout and either voxel-distributed ordinary rSVD with Gram finalization or adaptive global-H setup. At most min(length(gpus),shared_rank,nCha) workers are used. For each coil and sample batch, partial forward signals are copied to host buffers, summed, and broadcast to the workers before weighting and the adjoint. This retains the cross-rank terms of Aᴴ Wᴴ W A. Image contributions are also summed through host buffers. Channel/readout normal products likewise stage image broadcasts and reductions through the host.

Channel/readout workers initialize on the first normal request. Selected adjoint paths reuse them afterward; a standalone forward still uses the parent's single-device path. Rank workers initialize on the first forward, adjoint, or normal request. Allow at least one Julia default thread per active GPU worker, and a coordinator thread where possible.

normal_sample_batch_size=12_000_000 must be positive in every mode, but only rank execution uses it. Its effective size is min(nSam*nDyn,normal_sample_batch_size), in sample/readout points per coil. It bounds sample workspaces, not full temporal-factor columns, spatial factors, coil maps, image/NFFT grids, solver vectors, complete input/output data, or setup allocations. Smaller batches repeat transforms and transfers.

With the default NFFT.jl 0.14.3 GPU plans, use a full batch or a divisor of nSam*nDyn: the current node-update path does not update all output-shape metadata for a shorter final batch. The optional NonuniformFFTs backend supports variable-length nodes; select the backend before construction and keep it fixed while the operator is in use. See Multi-GPU execution for configuration and memory tradeoffs.

Result, weighting and resources ​

The result is a HighOrderLowRankOp with element type Complex{T} and shape (nSam*nDyn*nCha, prod(grid.matrixSize)). Forward data order matches vec(data) for data shaped (nSam,nDyn,nCha): samples vary fastest, then readouts, then coils. Image vectors cover the full grid; the forward ignores masked-out voxels and the adjoint sets them to zero.

For shared layout, q has shape (nSam*nDyn,shared_rank) and basis has shape (nVox,shared_rank). For per-readout layout, q has shape (nSam*nDyn,L_rank) and the logical spatial bank has shape (nVox,L_rank*nDyn). Regeneration stores that bank implicitly.

In rank mode, q, basis, and csm are host matrices, while solver storage is CUDA storage on the primary GPU. The allocating expression op*x follows q and therefore returns a host vector. mul! accepts a preallocated GPU output. For CUDA recon_HOOp, explicitly place data and raw weights on the primary GPU; that wrapper does not move them automatically.

recon_HOOp receives raw weights w and constructs Aᴴ diag(abs2(w)) A. A direct optimized normalOperator(op,D) instead expects real, nonnegative weights already representing WᴴW, identical for each coil. For :channel, :readout, or :rank, release the cached distributed backend before changing these normal weights and create a fresh view. Standard :single execution has no such owned backend; batched :single execution caches weights too. Positive semidefiniteness of the data normal alone does not establish the positive-definite conditions needed for the usual CG convergence guarantee.

The parent owns distributed workers, plans, and workspaces. By default, recon_HOOp releases that backend in finally; it retains the parent's factors and source cache. For direct use, or release_backend=false, call close(op) in a finally block. close(op) also closes the parent's streaming/regeneration cache; closing a derived normal view alone does not. Factor arrays and any parent-resident plan remain referenced by the parent, so closing is not equivalent to dropping the entire operator. Later use can rebuild owned resources; obtain fresh normal views after release.

The operator and its views share mutable workspaces and are not reentrant. When replacing a large operator, close it and drop old references before constructing the replacement; @rebuild_HOOp provides this sequence for a plain variable. See Resource ownership for details.

Additional construction options are disabled by default. Set shared_readout_count together with shared_fit_samples to train the shared space on representative readouts and refit coefficients for all original time samples. Setting only shared_fit_samples uses all readouts for training. shared_basis_report=Ref{Any}() records the selections, fit condition and sampled phase errors. The seven-time-point selection proxy and sampled audits do not certify full-time coverage or image error.

global_basis_rank selects a fixed final shared rank instead of global_basis_tol. Optional global_basis_weights are real nonnegative D = WᴴW, with length nSam*nDyn; they are not squared again. global_basis_coil_weighting=true additionally uses summed CSM energy. These weights define only the compression metric, not reconstruction weights. They use blocked FP64 Grams and the actual spatial Gram. Existing unweighted global_basis_tol calls retain their original implementation. Direct Shared methods reject post-validation compression and sampled rSVD options.

normal_method=:standard preserves existing execution. Opt into :batched for shared 3D Float32 CUDA factors with the optional NonuniformFFTs backend; normal_coil_batch_size may be 2, 4 or 8 (default 8). It uses Julia CUDA kernels and batched cuFFT, without native CUDA binaries or VkFFT. Both :single and :channel distributions are supported. This changes execution, not factors, FFT sizes or NUFFT support. Batch size trades memory for speed. normal_options=(;) keeps Julia kernels and cuFFT. The experimental normal_options=(fft=:vkfft_pruned, native_ptx=..., vkfft_library=..., coefficient_cache_bytes=...) explicitly selects native/pruned execution; resource files must already exist. The coefficient budget is per worker and zero disables caching. See deps/pruned_fft/README.md for local build and validation requirements. The parent owns this lazy backend even in :single mode; close(op) releases it. Bare adjoints still apply Aᴴ, with any weighting supplied by the caller.

verbose=false suppresses optional setup progress and diagnostic timing; some constructor information is still logged unconditionally. Execution cost and memory feasibility depend on the data, rank, backend and hardware.

Source: src/EncodingOperator/HighOrderLowRankOp.jl

HighOrderMRI.jl documentation · dev · code fa12c44 · docs fa12c44