Skip to content

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 ​

  • :legacy preserves the original fused kernels and CPU solver storage. Multi-GPU execution partitions masked voxels.
  • :direct retains the direct CUDA encoding kernels with resident workspaces and GPU solver storage.
  • :blocked generates a complex phase block, applies all coils, and reuses that block for both products of the weighted normal.
  • :cached retains the full complex phase matrix and applies it in sample blocks.
  • :cached_full retains 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 Pb as (block_samples,nVox), with entries exp⁡(+i2πϕjv). With 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 ​

julia
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ᴴW

explicit_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.

julia
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)
end

For 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 ​

julia
HighOrderKernelOp

CUDA 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 ​

julia
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 <: AbstractFloat

Description ​

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. nTerm must be 9 (up to second order) or 16 (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 when nZ == 1.
  • csm::AbstractArray{Complex{T}} - [nX, nY, nZ, nCha], complex coil sensitivity maps. [nX, nY, nCha] is accepted when nZ == 1.
  • mask::AbstractArray{Bool} - [nX, nY, nZ], reconstruction mask. [nX, nY] is accepted when nZ == 1.
  • concomitant - Optional [4, nSam] time-integrated phase coefficients in cycles/m² for z², x²+y², xz, and yz. Coordinates are in metres in the same frame and origin as the coefficients. The default is nothing. Independent of recon_terms; ignored when kspha_dt is supplied for delay estimation.
  • recon_terms::Union{Nothing, AbstractString} - Binary order-selection string. Use three digits for nTerm == 9 and four digits for nTerm == 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 by recon_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 requires CuArray (the default); solver vectors stay on the CPU with backend=:legacy and 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 to CUDA_VISIBLE_DEVICES when it filters the device list.
  • backend::Symbol - :legacy (default) preserves the original voxel-distributed kernels and CPU solver storage. :direct, :blocked, :cached, and :cached_full use persistent GPU solver storage; multiple GPUs split sample rows. :blocked reuses one phase block in both products of the weighted normal. Cached modes retain all local phase rows; :cached_full also applies them in a single GEMM per forward/adjoint.
  • block_size::Int - Sample rows per resident phase block; default 320. Unlike nBlock, this is a block size, not a block count.
  • phase_backend::Symbol - :kernel (default) fuses phase and complex exponential; :gemm uses real GEMM followed by the exponential.
  • gemm_backend::Symbol - :cublas (default) explicitly calls cuBLAS; :auto retains generic mul! dispatch for comparison.
  • phase_cache_bytes::Integer - Per-GPU complex phase cache budget with backend=:blocked; default 0 disables 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; defaults 256 and 512. Float64 adjoints are capped at 128.
  • verbose::Bool - Print progress information; default is false.

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 ​

julia
HighOrderKernelOp(op::HOOp{T}) where T

Wrap 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 ​

julia
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 ​

julia
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 ​

julia
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.

Source: src/EncodingOperator/Explicit/multi_gpu_operator.jl

HighOrderMRI.jl documentation · v0.1.1 · code 5d6ac72 · docs 5d6ac72