HighOrderKernelOp
Use this constructor for explicit CUDA encoding. Legacy mode partitions voxels and keeps solver vectors on the host. Resident modes partition sample rows and keep solver vectors on the primary GPU. Read the operator guide for the choice of implementation.
Backends and storage
:legacypreserves the original fused kernels and CPU solver storage. Multi-GPU execution partitions masked voxels.:directretains the direct CUDA encoding kernels with resident workspaces and GPU solver storage.:blockedgenerates a complex phase block, applies all coils, and reuses that block for both products of the weighted normal.:cachedretains the full complex phase matrix and applies it in sample blocks.:cached_fullretains the same full matrix and applies one complete GEMM per forward or adjoint; it also needs a full sample-by-coil workspace.
Both full-cache modes initialize the matrix in blocks. For ComplexF32, the full matrix alone requires 8 * nSam * count(mask) bytes per single-GPU problem. Include phase scratch, CSM, coil images, solver vectors, data, and library workspaces. A two-dimensional dataset does not necessarily fit.
For resident multi-GPU backends, each device stores all masked voxels and coils but only its contiguous sample range. Phase-cache feasibility must hold on each device. The resident implementation types are internal; use HighOrderKernelOp(...; gpus=...) for every backend.
Partial phase caching
With backend=:blocked, phase_cache_bytes retains a prefix of complex phase blocks and regenerates the rest. The budget counts cached complex entries only, rounds down to complete blocks, and applies to each GPU independently. It excludes the other workspaces and the allocator/library reserve. A positive budget therefore does not guarantee that construction fits available memory.
The budget is explicit; the constructor does not automatically choose a cache size from free memory. For full caching or a nonempty prefix cache, its allocation estimate includes model, scratch, and solver allowances and must be below 0.8 * CUDA.free_memory() on that worker. This leaves a 20% margin for libraries and allocator overhead, rather than an unconditional fit guarantee.
The default zero recomputes every block. Cache initialization belongs in one-shot reconstruction time. Partial caching preserves all samples, coils, mask voxels, and phase terms. It is separate from the complete-matrix :cached and :cached_full modes.
Matrix execution
The resident matrix backends store (block_samples,nVox), with entries phase_backend=:gemm, a real GEMM evaluates the prepared dynamic coefficient/basis product; the phase kernel adds times * fieldmap and evaluates the complex exponential. With :kernel, that kernel also evaluates the dynamic phase sum.
For a normal application, Z contains the masked image multiplied by every CSM. explicit_gpu_normal! computes Y = P_b * Z, applies the already squared diagonal weights to Y, and accumulates Q += P_b' * Y. The same P_b is reused for both products. Native cuBLAS uses transpose flags N,N and C,N, so it does not allocate a conjugate-transposed copy of P_b. After all blocks, the coil-reduction kernel multiplies by conjugated CSM, sums coils, and applies 1/nVox; scattering restores the full image shape. Standalone forward and adjoint each apply 1/sqrt(nVox).
The :direct backend instead calls the resident direct forward and adjoint kernels. It does not construct a phase matrix or use the matrix-block reuse described above.
Returns and lifecycle
A linear operator with nSam * nCha rows and prod(grid.matrixSize) columns. Resident input/output vectors must be CuArrays on first(gpus); supply host model arrays at construction. Pass GPU data and weights to recon_HOOp to keep CG vectors on that device. The returned image is a CPU array.
Operators and derived normals share mutable workspaces and are not reentrant. Call close(op) after their final use. The reconstruction wrapper does not automatically close resident explicit operators.
Weighted normal
using LinearOperatorCollection
N = explicit_gpu_normal(op; weights=weights_gpu) # raw square-root weights
D = abs2.(weights_gpu)
N_same = normalOperator(op, D) # already squared WᴴWexplicit_gpu_normal accepts one raw weight per sample or per sample and coil, and squares it once; nothing means unit weights. normalOperator(op, D) expects an already squared real nonnegative diagonal. normalOperator(W ∘ op) supplies that diagonal automatically. Regularization remains in the solver, outside these data normal operators.
Complete resident example
This synthetic example requires one CUDA GPU. It computes a weighted normal product, not an image reconstruction or a performance measurement.
using HighOrderMRI, CUDA
CUDA.functional() || error("CUDA is not functional")
CUDA.device!(0)
grid = Grid(8, 8, 1, 1f-3, 1f-3, 5f-3)
kspha = zeros(Float32, 9, 32)
kspha[2, :] .= range(-200f0, 200f0; length=32)
times = collect(range(0f0, 3f-3; length=32))
op = HighOrderKernelOp(grid, kspha, times;
gpus=[0], backend=:blocked, block_size=16, phase_cache_bytes=0)
image = try
x = CUDA.ones(ComplexF32, prod(grid.matrixSize))
weights = CUDA.ones(ComplexF32, size(op, 1))
normal = explicit_gpu_normal(op; weights)
Array(reshape(normal * x, grid.matrixSize))
finally
close(op)
endFor reconstruction, pass GPU data and weights to recon_HOOp. The default legacy Float64 adjoint can exceed its fixed CUDA launch's register budget. The resident direct Float64 cap does not apply to that legacy path. Derivative mode remains forward-only in the sense explained in the generated constructor reference.
Constructor API
Type
HighOrderKernelOpCUDA kernel implementation of the explicit MRI encoding model. Its ordinary forward/adjoint use the same phase, normalization, mask and sample/coil ordering as HighOrderOp. backend=:legacy keeps solver vectors on the host; resident backends keep them on the primary GPU and own reusable workspaces. See the constructor for backend-specific restrictions.
Source: src/EncodingOperator/HighOrderKernelOp.jl
Grid and trajectory constructor
HighOrderKernelOp(grid::Grid{T},
kspha::AbstractArray{T, 2},
times::AbstractVector{T};
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, 2} = kspha[2:4, :],
kspha_dt = nothing,
nBlock::Int64 = 50,
arrayType::Type{<:AbstractArray} = CuArray,
gpus::Vector{Int} = [0],
backend::Symbol = :legacy,
block_size::Int = 320,
phase_backend::Symbol = :kernel,
gemm_backend::Symbol = :cublas,
phase_cache_bytes::Integer = 0,
forward_threads::Int = 256,
adjoint_threads::Int = 512,
verbose::Bool = false) where T <: AbstractFloatDescription
Construct a HighOrderKernelOp that explicitly evaluates the MRI high-order Fourier encoding operator.
Arguments
grid::Grid{T}- Cartesian reconstruction grid.kspha::AbstractArray{T, 2}- [nTerm, nSam], coefficients of field dynamics.nTermmust be9(up to second order) or16(up to third order).times::AbstractVector{T}- [nSam], sampling time points.
Keywords
fieldmap::AbstractArray{T}- [nX, nY, nZ], off-resonance map. [nX, nY] is accepted whennZ == 1.csm::AbstractArray{Complex{T}}- [nX, nY, nZ, nCha], complex coil sensitivity maps. [nX, nY, nCha] is accepted whennZ == 1.mask::AbstractArray{Bool}- [nX, nY, nZ], reconstruction mask. [nX, nY] is accepted whennZ == 1.concomitant- Optional [4, nSam] time-integrated phase coefficients in cycles/m² forz²,x²+y²,xz, andyz. Coordinates are in metres in the same frame and origin as the coefficients. The default isnothing. Independent ofrecon_terms; ignored whenkspha_dtis supplied for delay estimation.recon_terms::Union{Nothing, AbstractString}- Binary order-selection string. Use three digits fornTerm == 9and four digits fornTerm == 16; the digits select zeroth-, first-, second-, and third-order terms. The default is"111"or"1111".k_nominal::AbstractArray{T, 2}- [3, nSam], nominal first-order trajectory ordered as [kx, ky, kz]. It replaces the measured first-order coefficients when first-order error is disabled byrecon_terms.kspha_dt- [nTerm, nSam], optional time derivative of the field-dynamic coefficients.nBlock::Int64- Number of trajectory blocks used by the derivative path to limit temporary memory.arrayType::Type{<:AbstractArray}- Compute backend. The kernel implementation requiresCuArray(the default); solver vectors stay on the CPU withbackend=:legacyand on the first selected GPU with resident backends.gpus::Vector{Int}- Zero-based CUDA device IDs. One ID selects single-GPU execution; multiple IDs select multi-GPU execution. IDs are relative toCUDA_VISIBLE_DEVICESwhen it filters the device list.backend::Symbol-:legacy(default) preserves the original voxel-distributed kernels and CPU solver storage.:direct,:blocked,:cached, and:cached_fulluse persistent GPU solver storage; multiple GPUs split sample rows.:blockedreuses one phase block in both products of the weighted normal. Cached modes retain all local phase rows;:cached_fullalso applies them in a single GEMM per forward/adjoint.block_size::Int- Sample rows per resident phase block; default320. UnlikenBlock, this is a block size, not a block count.phase_backend::Symbol-:kernel(default) fuses phase and complex exponential;:gemmuses real GEMM followed by the exponential.gemm_backend::Symbol-:cublas(default) explicitly calls cuBLAS;:autoretains genericmul!dispatch for comparison.phase_cache_bytes::Integer- Per-GPU complex phase cache budget withbackend=:blocked; default0disables caching. Complete sample blocks are cached up to the budget. Other model, scratch, solver, and library storage is additional. Insufficient memory raises an error without resizing.forward_threads,adjoint_threads- Resident direct-kernel thread counts; defaults256and512. Float64 adjoints are capped at128.verbose::Bool- Print progress information; default isfalse.
The ordinary operator has size (nSam*nCha, prod(grid.matrixSize)) and complex element type Complex{T}. Use metres, seconds, Hz and integrated cycles/m^p coefficients, as for HighOrderOp.
With kspha_dt, only the forward callback evaluates the derivative model; the adjoint remains the ordinary encoding adjoint. Do not use that object for adjoint-based solves or normal products. The legacy Float64 adjoint can exceed the CUDA register budget with its fixed launch configuration; resident direct Float64 adjoints use the stated 128-thread cap. This is a current implementation limitation, not a guarantee that legacy Float64 works on every GPU.
Resident backends accept host model inputs. Pass GPU data and weights to recon_HOOp; the first entry of gpus owns the solver vectors. Call close(op) after all derived normal operators are no longer used. The workspaces are not reentrant. kspha_dt requires backend=:legacy.
Source: src/EncodingOperator/HighOrderKernelOp.jl
Internal operator adapter
HighOrderKernelOp(op::HOOp{T}) where TWrap an existing internal high-order operator, delegating forward, adjoint, normal construction and resource release to it. This is the adapter used by the resident constructors; ordinary callers should use the grid/trajectory constructor. The wrapper shares its operand's storage and lifetime.
Source: src/EncodingOperator/HighOrderKernelOp.jl
Weighted normal API
Resident public wrapper
explicit_gpu_normal(op::HighOrderKernelOp{T, F1, F2, S, O};
weights = nothing) where {T, F1, F2, S, O <: HOOp}Construct the resident wrapped operator's data normal Aᴴ D A, where D = abs2.(weights) and nothing means unit weights. The wrapper must own a resident backend. Raw weights may be sample-wise or sample-and-coil-wise. The result shares its parent's workspace and lifetime; regularization remains the solver's responsibility. normalOperator(op, D) instead accepts the already squared real nonnegative diagonal.
Source: src/EncodingOperator/Explicit/explicit_gpu_operator.jl
Internal single GPU
explicit_gpu_normal(op::ExplicitGPUOp;
weights = nothing)Create the data normal operator Aᴴ * D * A for a resident HighOrderKernelOp (backend=:direct, :blocked, :cached, or :cached_full), with D = abs2.(weights). Raw sample weights may have one entry per sample or per sample and coil; nothing means unit weights.
In contrast, normalOperator(op, D) accepts an already squared, real nonnegative diagonal. normalOperator(W ∘ op) also supplies that squared diagonal automatically. Regularization is applied separately by the solver. The result shares the operator's mutable workspaces and lifetime.
Source: src/EncodingOperator/Explicit/explicit_gpu_operator.jl
Internal multiple GPU
explicit_gpu_normal(op::ExplicitMultiGPUOp;
weights = nothing)Construct the sample-distributed explicit GPU data normal Aᴴ D A, with D = abs2.(weights). nothing selects unit weights. Raw weights have one entry per sample or per sample and coil. Workers operate on disjoint sample rows and their image contributions are summed. The result shares the parent operator's workers and workspaces; finish using it before close(op). Regularization is applied separately by the solver.