| Title: | Backend-Agnostic Matrix Extensions |
|---|---|
| Description: | Matrix-compatible S4 classes with backend-dispatch hooks for accelerated execution and predictable CPU fallback. |
| Authors: | Brad Buchsbaum [aut, cre] |
| Maintainer: | Brad Buchsbaum <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0 |
| Built: | 2026-07-02 15:14:41 UTC |
| Source: | https://github.com/bbuchsbaum/amatrix |
Dispatches %*% through the amatrix backend for sparse
adgCMatrix objects on the left-hand side, preserving GPU
residency metadata across the operation.
## S4 method for signature 'adgCMatrix,ANY' x %*% y ## S4 method for signature 'adgCMatrix,matrix' x %*% y ## S4 method for signature 'adgCMatrix,Matrix' x %*% y ## S4 method for signature 'adgCMatrix,dgeMatrix' x %*% y ## S4 method for signature 'adgCMatrix,dgCMatrix' x %*% y ## S4 method for signature 'adgCMatrix,adgeMatrix' x %*% y ## S4 method for signature 'adgCMatrix,adgCMatrix' x %*% y## S4 method for signature 'adgCMatrix,ANY' x %*% y ## S4 method for signature 'adgCMatrix,matrix' x %*% y ## S4 method for signature 'adgCMatrix,Matrix' x %*% y ## S4 method for signature 'adgCMatrix,dgeMatrix' x %*% y ## S4 method for signature 'adgCMatrix,dgCMatrix' x %*% y ## S4 method for signature 'adgCMatrix,adgeMatrix' x %*% y ## S4 method for signature 'adgCMatrix,adgCMatrix' x %*% y
x |
An |
y |
A matrix-like object: |
An adgeMatrix or adgCMatrix containing the
product, with backend metadata inherited from x.
sp <- as(matrix(c(1, 0, 0, 2), 2, 2), "dgCMatrix") A <- adgCMatrix(sp) B <- matrix(1:4, 2, 2) A %*% Bsp <- as(matrix(c(1, 0, 0, 2), 2, 2), "dgCMatrix") A <- adgCMatrix(sp) B <- matrix(1:4, 2, 2) A %*% B
Scaled matrix multiply with optional bias: alpha*(A%*%B) + beta*C
addmm(A, B, C = NULL, alpha = 1, beta = 1)addmm(A, B, C = NULL, alpha = 1, beta = 1)
A |
n×p |
B |
p×k numeric matrix. |
C |
n×k numeric matrix or |
alpha |
Scalar multiplier for |
beta |
Scalar multiplier for |
adgeMatrix if A is resident, otherwise plain matrix.
Converts a sparse or dense matrix to an adgCMatrix with the
specified backend, policy, and precision. This is the primary
user-facing constructor for sparse amatrix objects.
adgCMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )adgCMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )
x |
A |
mode |
Single string shortcut passed to
|
backend |
Alias for |
preferred_backend |
Single string naming the preferred compute backend. |
policy |
Single string; one of |
precision |
Single string; |
An adgCMatrix with the data from x and the
requested backend metadata.
m <- matrix(c(1, 0, 0, 2), nrow = 2) S <- adgCMatrix(m) Sm <- matrix(c(1, 0, 0, 2), nrow = 2) S <- adgCMatrix(m) S
adgCMatrix extends both aMatrix and
Matrix::dgCMatrix, adding backend-dispatch slots to a
compressed-column sparse double-precision matrix.
adgCMatrix for the user-facing constructor,
adgeMatrix-class for the dense counterpart
Converts a base R matrix or Matrix::dgeMatrix to an
adgeMatrix with the specified backend, policy, and precision.
This is the primary user-facing constructor for dense amatrix
objects.
adgeMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )adgeMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )
x |
A base R |
mode |
Single string shortcut accepted by
|
backend |
Alias for |
preferred_backend |
Single string naming the preferred compute
backend, e.g. |
policy |
Single string; one of |
precision |
Single string; |
An adgeMatrix with the data from x and the
requested backend metadata.
m <- matrix(1:6, nrow = 2) A <- adgeMatrix(m) Am <- matrix(1:6, nrow = 2) A <- adgeMatrix(m) A
adgeMatrix extends both aMatrix and
Matrix::dgeMatrix, adding backend-dispatch slots to a
column-major dense double-precision matrix. All arithmetic
generics dispatch through the amatrix backend system rather than
directly to BLAS.
adgeMatrix for the user-facing constructor,
adgCMatrix for the sparse counterpart
adlgCMatrix extends both aMatrix and
Matrix::lgCMatrix, adding backend-dispatch slots to a
compressed-column sparse logical matrix.
adlgeMatrix extends both aMatrix and
Matrix::lgeMatrix, adding backend-dispatch slots to a
column-major dense logical matrix.
Return the index of the maximum or minimum value in each row or column.
am_rowargmax(x) am_rowargmin(x) am_colargmax(x) am_colargmin(x)am_rowargmax(x) am_rowargmin(x) am_colargmax(x) am_colargmin(x)
x |
A numeric matrix or |
An integer vector of indices.
Applies an elementwise arithmetic operation between the handle's resident matrix and either a scalar or another resident handle, replacing the handle's device buffer with the result.
am_ewise_inplace(h, rhs, op)am_ewise_inplace(h, rhs, op)
h |
A |
rhs |
A length-1 numeric scalar, or a |
op |
Character string. Arithmetic operator: |
h, invisibly. The handle is modified in place.
am_sweep_inplace, resident_handle
# requires a backend with residency support (e.g. MLX, OpenCL)# requires a backend with residency support (e.g. MLX, OpenCL)
Computes the QR decomposition of a matrix or aMatrix, routing to
a backend-specific implementation when available.
am_qr(x, ...)am_qr(x, ...)
x |
A matrix or |
... |
Additional arguments passed to the underlying QR routine. |
An object of class amDenseQR (or a wrapped sparse QR
for adgCMatrix input) containing the factorisation components.
m <- adgeMatrix(matrix(rnorm(12), 4, 3)) qr_obj <- am_qr(m) qr.R(qr_obj)m <- adgeMatrix(matrix(rnorm(12), 4, 3)) qr_obj <- am_qr(m) qr.R(qr_obj)
Compute the mean of rows of x grouped by integer labels.
am_scatter_mean(x, labels, K)am_scatter_mean(x, labels, K)
x |
A numeric matrix or |
labels |
Integer vector of group labels (1-based). |
K |
Number of groups. |
A K-by-ncol(x) matrix of group means.
Apply a function to each row or column of a matrix, dispatching to the preferred GPU backend when available.
am_sweep(x, MARGIN, STATS, FUN = "+")am_sweep(x, MARGIN, STATS, FUN = "+")
x |
A numeric matrix or |
MARGIN |
1 for rows, 2 for columns. |
STATS |
Numeric vector of statistics to apply. |
FUN |
Operation: |
A matrix of the same dimensions as x.
Applies a row-wise or column-wise arithmetic operation between the
resident matrix and a statistics vector, mutating the handle in
place. Equivalent to sweep(as.matrix(h), MARGIN, STATS, FUN)
but avoids downloading the matrix to host.
am_sweep_inplace(h, MARGIN, STATS, FUN = "+")am_sweep_inplace(h, MARGIN, STATS, FUN = "+")
h |
A |
MARGIN |
Integer. |
STATS |
Numeric vector of length equal to the number of rows or
columns selected by |
FUN |
Character string. Arithmetic operator to apply:
|
h, invisibly. The handle is modified in place; the
underlying device buffer is replaced with the sweep result.
resident_handle, am_ewise_inplace
# requires a backend with residency support (e.g. MLX, OpenCL)# requires a backend with residency support (e.g. MLX, OpenCL)
Returns the unique capability strings advertised by the named backend,
as reported by its capabilities() function.
amatrix_backend_capabilities(name)amatrix_backend_capabilities(name)
name |
Character string. Name of a registered backend. |
Character vector of capability identifiers (e.g.
"matmul", "svd").
amatrix_backend_features,
amatrix_backend_status
amatrix_backend_capabilities("cpu")amatrix_backend_capabilities("cpu")
Returns the unique feature strings advertised by the named backend,
as reported by its features() function. Features describe
optional capabilities such as sparse residency or deferred execution.
amatrix_backend_features(name)amatrix_backend_features(name)
name |
Character string. Name of a registered backend. |
Character vector of feature identifiers.
amatrix_backend_capabilities,
amatrix_backend_status
amatrix_backend_features("cpu")amatrix_backend_features("cpu")
Executes a small matmul round-trip against the named backend and
compares the result to the base R reference. On success the backend
is marked healthy; on failure it is marked
unhealthy:<reason>. Subsequent calls to
amatrix_backend_status() reflect the recorded health.
amatrix_backend_health_probe(name, tol = NULL)amatrix_backend_health_probe(name, tol = NULL)
name |
Character string. Name of a registered backend. |
tol |
Numeric. Residual tolerance for the probe, default
|
The probe is intentionally tiny (10x10 double-precision matmul) so it completes in milliseconds even on cold GPU. It is not a benchmark; it is a liveness check.
Invisibly, the health record as a list with elements
status, reason, timestamp.
amatrix_backend_status,
amatrix_fallback_log
amatrix_backend_health_probe("cpu")amatrix_backend_health_probe("cpu")
Runs amatrix_backend_plan for each requested operation
and returns the results as a single data.frame, one row per
operation. Useful for inspecting which backend will be used across an
entire workload.
amatrix_backend_matrix( x, ops = c("matmul", "crossprod", "tcrossprod", "ewise", "rowSums", "colSums", "solve", "chol", "qr", "svd", "eigen", "diag"), y_map = list() )amatrix_backend_matrix( x, ops = c("matmul", "crossprod", "tcrossprod", "ewise", "rowSums", "colSums", "solve", "chol", "qr", "svd", "eigen", "diag"), y_map = list() )
x |
An |
ops |
Character vector of operation names. Defaults to the twelve standard operations. |
y_map |
Named list mapping operation names to right-hand-side
objects. Use to supply a |
A data.frame with one row per operation and columns:
Character. Operation name.
Character. Precision mode.
Character. Backend to which x is
GPU-resident, or NA.
Character. Preference order string.
Character. Selected backend.
Character. "resident" or
"cold".
Logical. Whether the resident path is active.
Logical. Whether CPU was chosen despite not being first preference.
Character. Compact flag string for all candidates.
amatrix_backend_plan,
amatrix_execution_info
m <- adgeMatrix(matrix(1:6, 2, 3)) amatrix_backend_matrix(m, ops = c("matmul", "crossprod"))m <- adgeMatrix(matrix(1:6, 2, 3)) amatrix_backend_matrix(m, ops = c("matmul", "crossprod"))
Returns the names of every backend currently in the session registry. When optional backends are enabled (the default), this also attempts to auto-register any installed optional backend packages before returning the list.
amatrix_backend_names()amatrix_backend_names()
Character vector of registered backend names, sorted
alphabetically. Always includes at least "cpu".
amatrix_backend_status,
amatrix_register_backend
amatrix_backend_names()amatrix_backend_names()
Evaluates each candidate backend in preference order and returns a structured plan describing which backend was chosen and why each candidate was accepted or rejected. The plan respects GPU residency, precision compatibility, and calibration thresholds.
amatrix_backend_plan(x, op, y = NULL)amatrix_backend_plan(x, op, y = NULL)
x |
An |
op |
Character string naming the operation, e.g.
|
y |
Right-hand-side |
A named list with elements:
Character. The requested operation.
Character or NULL. Backend to which
x is currently GPU-resident.
Character vector. Backends evaluated in order.
Character. Precision mode of x.
Character. Name of the chosen backend.
Character. Either "resident" or
"cold".
List of per-candidate evaluation records, each
a named list with logical flags for registered,
available, precision_compatible,
supported_cold, supported_resident,
calibration_ok, supported, and chosen.
amatrix_backend_matrix,
amatrix_explain,
amatrix_execution_info
m <- adgeMatrix(matrix(1:6, 2, 3)) amatrix_backend_plan(m, "matmul")m <- adgeMatrix(matrix(1:6, 2, 3)) amatrix_backend_plan(m, "matmul")
Returns the precision mode strings advertised by the named backend.
Valid values are "strict" (double precision) and "fast"
(single/mixed precision).
amatrix_backend_precision_modes(name)amatrix_backend_precision_modes(name)
name |
Character string. Name of a registered backend. |
Character vector of precision mode identifiers, a subset of
c("strict", "fast").
amatrix_backend_capabilities,
amatrix_backend_status
amatrix_backend_precision_modes("cpu")amatrix_backend_precision_modes("cpu")
Returns a data.frame with one row per backend describing its availability, supported precision modes, features, capabilities, and whether it supports GPU residency.
amatrix_backend_status(names = NULL)amatrix_backend_status(names = NULL)
names |
Character vector of backend names to query. When
|
A data.frame with columns:
Character. Backend identifier.
Logical. Whether the backend reports itself as available on this machine.
Character. Comma-separated precision
modes ("strict", "fast").
Character. Comma-separated feature strings.
Logical. Whether the backend supports GPU-resident matrix storage.
Character. Comma-separated operation capability strings.
amatrix_backend_names,
amatrix_register_backend
amatrix_backend_status() amatrix_backend_status("cpu")amatrix_backend_status() amatrix_backend_status("cpu")
Reads a machine-local benchmark baseline CSV (a table of recorded per-op cold and warm timings), if one is present, together with the cached calibration in the user cache directory, and returns a structured data.frame surfacing per-op cold vs warm timings and the currently-calibrated dispatch thresholds.
amatrix_benchmark_report(baseline_path = file.path("tools", "baseline.csv"))amatrix_benchmark_report(baseline_path = file.path("tools", "baseline.csv"))
baseline_path |
Path to a benchmark baseline CSV of recorded
per-op timings. Defaults to a |
This is the user-facing honesty surface for Track 4's speed contract: users can see (a) which backends are calibrated on their machine, (b) cold-start vs warm-run ratios per op, and (c) where the dispatcher will currently route.
A list with two elements:
data.frame with columns op, size,
backend, cold_ms, warm_ms,
warm_vs_cold_ratio, speedup_vs_cpu. Rows with
missing cold OR warm data use NA for the missing variant.
Empty when the baseline file is absent.
data.frame with columns backend, op,
threshold_elements, gpu_wins. Rows come from the
cached calibration; empty when no calibration is available.
amatrix_calibrate,
amatrix_calibration_info
## Not run: rep <- amatrix_benchmark_report() head(rep$baseline) head(rep$calibration) ## End(Not run)## Not run: rep <- amatrix_benchmark_report() head(rep$baseline) head(rep$calibration) ## End(Not run)
Upload a dense or sparse matrix to a residency-capable backend and return the
corresponding aMatrix object with a live resident binding. This is
primarily useful for repeated GPU work where paying the upload cost once is
preferable to relying on cold-path dispatch.
amatrix_bind_resident(x, backend = NULL, op = NULL, y = NULL)amatrix_bind_resident(x, backend = NULL, op = NULL, y = NULL)
x |
An |
backend |
Backend name, |
op |
Optional operation name such as |
y |
Optional rhs object used when checking resident-op support for automatic backend selection. |
An adgeMatrix or adgCMatrix with a live resident
binding on backend. When no suitable accelerator backend is
available in automatic mode, returns x unchanged.
amatrix_cache_max_size returns the current limit.
amatrix_set_cache_max_size changes the limit and immediately
evicts the least-recently-used entries if the cache exceeds the new
bound. When max_size is Inf (the default) the cache
grows without bound.
amatrix_cache_max_size() amatrix_set_cache_max_size(max_size)amatrix_cache_max_size() amatrix_set_cache_max_size(max_size)
max_size |
Positive numeric scalar or |
amatrix_cache_max_size returns a length-1 numeric
giving the current limit. amatrix_set_cache_max_size
returns the new limit invisibly.
old <- amatrix_cache_max_size() amatrix_set_cache_max_size(10) amatrix_cache_max_size() amatrix_set_cache_max_size(old)old <- amatrix_cache_max_size() amatrix_set_cache_max_size(10) amatrix_cache_max_size() amatrix_set_cache_max_size(old)
Runs micro-benchmarks for each (op, backend, size) combination and derives the minimum matrix element count at which each GPU backend reliably outperforms CPU. Results are stored in the current session and optionally persisted to disk for reuse in future sessions.
amatrix_calibrate( backend = NULL, ops = c("gemm", "gemv", "crossprod", "rowSums", "colSums", "qr", "chol", "solve", "svd"), sizes = list(c(64L, 32L), c(128L, 64L), c(256L, 128L), c(512L, 256L), c(1024L, 512L)), sparse_densities = c(0.01, 0.05, 0.2), n_reps = 10L, margin = 0.1, persist = TRUE, quiet = FALSE )amatrix_calibrate( backend = NULL, ops = c("gemm", "gemv", "crossprod", "rowSums", "colSums", "qr", "chol", "solve", "svd"), sizes = list(c(64L, 32L), c(128L, 64L), c(256L, 128L), c(512L, 256L), c(1024L, 512L)), sparse_densities = c(0.01, 0.05, 0.2), n_reps = 10L, margin = 0.1, persist = TRUE, quiet = FALSE )
backend |
Character vector of backend names to benchmark.
Defaults to all registered non-CPU backends that report
|
ops |
Character vector of operations to benchmark. Supported
values: |
sizes |
List of integer vectors of length 2 giving
|
sparse_densities |
Numeric vector of target fill densities used
when benchmarking |
n_reps |
Positive integer. Number of timed repetitions per benchmark cell, after 2 warm-up repetitions. |
margin |
Non-negative numeric less than 1. Fraction by which
GPU median time must beat CPU to count as a GPU win (default
|
persist |
Logical. If |
quiet |
Logical. Suppress progress messages. |
Invisibly, a list with elements version,
calibrated_at (POSIXct), thresholds (nested list
keyed by backend then op), and results (data.frame of all
benchmark measurements).
amatrix_calibration_info,
amatrix_backend_plan
Returns the calibration data stored in the current session. If no
calibration has been run yet, the function attempts to load a
previously persisted calibration from the user cache directory.
Returns NULL when no calibration is available.
amatrix_calibration_info()amatrix_calibration_info()
A list as returned by amatrix_calibrate, or
NULL if no calibration data exists for this session.
cal <- amatrix_calibration_info() is.null(cal) # TRUE when no calibration has been runcal <- amatrix_calibration_info() is.null(cal) # TRUE when no calibration has been run
Prepares a fixed left operand for repeated products, choosing and binding a resident accelerator backend when beneficial. The returned object is a callable function, so repeated right-hand sides can be applied without rethinking backend selection each time.
amatrix_compile_product( x, op = c("matmul", "crossprod", "tcrossprod"), backend = "auto", precision = amatrix_default_precision(), policy = amatrix_default_policy() )amatrix_compile_product( x, op = c("matmul", "crossprod", "tcrossprod"), backend = "auto", precision = amatrix_default_precision(), policy = amatrix_default_policy() )
x |
Fixed left operand. |
op |
Product primitive: |
backend |
Backend name or |
precision |
Precision to use when wrapping base matrices. |
policy |
Policy to use when wrapping base matrices. |
A callable am_product_plan. Calling the plan with
materialize = "matrix" returns a base matrix directly, which is
useful for internal algorithms that immediately need host matrix data.
Returns the dispatch policy used when an aMatrix object does
not specify its own policy. The policy controls which backend is
preferred for operations on new matrices.
amatrix_default_policy()amatrix_default_policy()
Character string, one of "auto", "cpu",
"mlx", "metal", "arrayfire", or
"opencl".
amatrix_set_default_policy,
amatrix_default_precision
amatrix_default_policy()amatrix_default_policy()
Returns the precision mode used when constructing new aMatrix
objects that do not specify their own precision.
amatrix_default_precision()amatrix_default_precision()
Character string, either "strict" (double precision)
or "fast" (single/mixed precision).
amatrix_set_default_precision,
amatrix_default_policy
amatrix_default_precision()amatrix_default_precision()
Resolves the best available backend for op on x,
attempts the GPU-resident path when applicable, and falls back to
the cold path (materializing x to host) if needed. If the
chosen backend does not implement method, the fallback
function is called instead.
amatrix_dispatch_op(x, op, method = op, y = NULL, args = list(), fallback)amatrix_dispatch_op(x, op, method = op, y = NULL, args = list(), fallback)
x |
An |
op |
Character string. Operation key used for backend selection
(e.g. |
method |
Character string. Name of the backend list element to
call. Defaults to |
y |
Right-hand-side |
args |
Named list of additional arguments forwarded to the backend method on the cold path. |
fallback |
Zero-argument function called when the chosen
backend does not implement |
The result of the backend method, or the result of
fallback() if the method is unavailable.
amatrix_backend_plan,
amatrix_materialize_host
Returns a snapshot of the dispatch state for an aMatrix,
including residency, preferred backend, policy, precision, and the
per-operation dispatch matrix for a set of operations.
amatrix_execution_info( x, ops = c("matmul", "crossprod", "tcrossprod", "ewise", "rowSums", "colSums"), y_map = list() )amatrix_execution_info( x, ops = c("matmul", "crossprod", "tcrossprod", "ewise", "rowSums", "colSums"), y_map = list() )
x |
An |
ops |
Character vector of operation names to include in the dispatch matrix. Default covers the six core operations. |
y_map |
Named list mapping operation names to right-hand-side
objects used when planning binary operations such as
|
A named list with elements:
Character. Internal object identifier.
Character. Preferred backend slot value.
Character or NULL. Backend to which
the object is currently GPU-resident.
Character. Dispatch policy slot value.
Character. Precision mode ("strict" or
"fast").
data.frame. Output of
amatrix_residency_info.
data.frame. Output of
amatrix_backend_matrix.
amatrix_backend_plan,
amatrix_backend_matrix,
amatrix_explain
Prints a human-readable diagnostic showing which backend was chosen
for op on x, the accept/reject status of every
candidate backend, and actionable suggestions for improving
performance.
amatrix_explain(x, op, y = NULL)amatrix_explain(x, op, y = NULL)
x |
An |
op |
Character string. Operation to explain, e.g.
|
y |
Right-hand-side |
Invisibly, the dispatch plan list from
amatrix_backend_plan. Called primarily for its
printed output.
amatrix_backend_plan,
amatrix_backend_matrix,
amatrix_execution_info
m <- adgeMatrix(matrix(1:12, 3, 4)) amatrix_explain(m, "matmul")m <- adgeMatrix(matrix(1:12, 3, 4)) amatrix_explain(m, "matmul")
The fallback log records every runtime fall-through from a preferred backend to the CPU reference path. A non-empty log after a clean conformance run is a stop-ship condition: it means a backend claimed support for an op it cannot actually execute, so the result silently came from a different backend than the one that was requested.
amatrix_fallback_log()amatrix_fallback_log()
A data.frame with columns timestamp, op,
from_backend, to_backend, reason. Zero rows
means no fallbacks have been recorded.
amatrix_fallback_log_reset,
amatrix_backend_health_probe
amatrix_fallback_log() amatrix_fallback_log_reset()amatrix_fallback_log() amatrix_fallback_log_reset()
Resets the fallback log to empty. Typically called at the start of a test block to isolate the assertion that the log is empty after a clean run.
amatrix_fallback_log_reset()amatrix_fallback_log_reset()
Invisibly, NULL.
Scans the residency registry and removes entries whose backend no longer reports the associated device buffer as present. Such stale entries arise when a backend is unloaded or the device is reset between sessions. Optionally flushes all cached matrix factors (QR, Cholesky, SVD) from the session model cache.
amatrix_gc(cache = FALSE)amatrix_gc(cache = FALSE)
cache |
Logical. If |
Invisibly, a list with two integer elements:
Number of stale residency slots removed.
Number of model-cache entries
flushed (0 when cache = FALSE).
amatrix_memory_stats,
amatrix_residency_info
amatrix_gc() amatrix_gc(cache = TRUE)amatrix_gc() amatrix_gc(cache = TRUE)
One row per known GPU backend with the state of every gate between "installed" and "computing on the GPU": package installed, backend registered, device available, health, and the registry's recorded reason when something is off.
amatrix_gpu_status()amatrix_gpu_status()
A data frame with columns backend, package,
installed, registered, available,
health, and reason.
amatrix_use_gpu,
amatrix_backend_status, amatrix_explain
amatrix_gpu_status()amatrix_gpu_status()
Downloads any GPU-resident data and returns a standard
Matrix-package object on the host. For adgeMatrix
inputs the result is a dgeMatrix; for adgCMatrix
inputs the result is a dgCMatrix; for aTransposeView
the transposed dense host matrix is returned. Host-only objects are
returned unchanged.
amatrix_materialize_host(x)amatrix_materialize_host(x)
x |
An |
A dgeMatrix, dgCMatrix, or the original object
if no materialization is needed.
amatrix_residency_info,
amatrix_gc
m <- adgeMatrix(matrix(1:6, 2, 3)) host <- amatrix_materialize_host(m) class(host)m <- adgeMatrix(matrix(1:6, 2, 3)) host <- amatrix_materialize_host(m) class(host)
Returns a snapshot of GPU device memory usage and model cache
occupancy for the current session. Backends that expose a
memory_usage() method contribute device byte counts;
backends without that method show NA for byte fields.
amatrix_memory_stats()amatrix_memory_stats()
An object of class amatrix_memory_stats, which is a
list with two components:
data.frame with one row per registered backend
and columns backend (character), resident_objects
(integer count of GPU-resident R objects), bytes_used
(numeric, device bytes in use, or NA), and
bytes_total (numeric, total device capacity, or
NA).
List with n_entries (integer, number
of cached matrix factors) and max_size (integer or
Inf, the cache size limit).
amatrix_gc, amatrix_residency_info
stats <- amatrix_memory_stats() print(stats)stats <- amatrix_memory_stats() print(stats)
Converts inputs to amatrix wrappers when needed, chooses a
residency-capable accelerator backend in automatic mode, and binds the
operands so repeated products reuse the resident fast path.
amatrix_prepare_operands( x, y, op = c("matmul", "crossprod", "tcrossprod"), backend = "auto", precision = amatrix_default_precision(), policy = amatrix_default_policy() )amatrix_prepare_operands( x, y, op = c("matmul", "crossprod", "tcrossprod"), backend = "auto", precision = amatrix_default_precision(), policy = amatrix_default_policy() )
x |
Left operand. |
y |
Right operand. |
op |
Product primitive: |
backend |
Backend name or |
precision |
Precision to use when wrapping base matrices. |
policy |
Policy to use when wrapping base matrices. |
A list with elements x, y, and backend.
Adds a named backend to the session backend registry. The backend
must be a named list containing all required callable fields. Once
registered, the backend is available for dispatch by any
aMatrix object whose preferred_backend or policy
slot names it.
amatrix_register_backend(name, backend, overwrite = FALSE)amatrix_register_backend(name, backend, overwrite = FALSE)
name |
Character string. Unique identifier for the backend
(e.g. |
backend |
Named list implementing the backend contract. Required
fields: |
overwrite |
Logical. Allow replacement of an existing registration
with the same |
Invisibly, name.
amatrix_backend_names,
amatrix_backend_status
# Minimal no-op backend for illustration only noop <- list( capabilities = function() character(), features = function() character(), precision_modes = function() "strict", available = function() FALSE, supports = function(op, x, y = NULL) FALSE, matmul = function(x, y) x, crossprod = function(x, y = NULL) x, tcrossprod = function(x, y = NULL) x, ewise = function(x, y, op) x, rowSums = function(x) numeric(nrow(x)), colSums = function(x) numeric(ncol(x)) ) amatrix_register_backend("noop_test", noop, overwrite = TRUE)# Minimal no-op backend for illustration only noop <- list( capabilities = function() character(), features = function() character(), precision_modes = function() "strict", available = function() FALSE, supports = function(op, x, y = NULL) FALSE, matmul = function(x, y) x, crossprod = function(x, y = NULL) x, tcrossprod = function(x, y = NULL) x, ewise = function(x, y, op) x, rowSums = function(x) numeric(nrow(x)), colSums = function(x) numeric(ncol(x)) ) amatrix_register_backend("noop_test", noop, overwrite = TRUE)
Frees any device-resident buffer associated with x and drops its
residency-registry binding, leaving the host copy as the authoritative
storage. This gives long-lived GPU pipelines explicit control over device
memory instead of waiting for garbage collection to reclaim resident
handles.
amatrix_release_resident(x)amatrix_release_resident(x)
x |
An |
The object remains fully usable afterwards: its data is served from the host copy and is re-uploaded to the device on the next GPU operation if needed. On CPU-only sessions, or for any object that currently holds no device buffer, this is a safe no-op.
Invisibly, TRUE if a resident binding was released, and
FALSE otherwise (including the CPU-only no-op case).
A <- adgeMatrix(matrix(1:6, 2, 3)) # On a CPU-only session there is no device buffer, so this is a no-op: released <- amatrix_release_resident(A) releasedA <- adgeMatrix(matrix(1:6, 2, 3)) # On a CPU-only session there is no device buffer, so this is a no-op: released <- amatrix_release_resident(A) released
Returns a single-row data.frame describing whether x is
currently uploaded to a GPU backend and, if so, which backend holds
it and whether that binding is still live (the device buffer still
exists).
amatrix_residency_info(x)amatrix_residency_info(x)
x |
An |
A data.frame with one row and columns:
Character. Backend name, or NA when not
resident.
Character. Internal device buffer key, or
NA.
Character. Backend name when the binding
is confirmed live, otherwise NA.
Logical. TRUE when the backend still holds
the buffer identified by resident_key.
amatrix_materialize_host,
amatrix_memory_stats
m <- adgeMatrix(matrix(1:4, 2, 2)) amatrix_residency_info(m)m <- adgeMatrix(matrix(1:4, 2, 2)) amatrix_residency_info(m)
Returns the first available non-CPU backend that can keep x resident
for the requested operation. This is intended for package authors who want
repeated work to stay on the fastest available accelerator without hardcoding
backend names such as "metal" or "mlx".
amatrix_resident_backend_for(x, op = NULL, y = NULL)amatrix_resident_backend_for(x, op = NULL, y = NULL)
x |
An |
op |
Optional operation name such as |
y |
Optional rhs object used when checking resident-op support. |
A backend name, or NULL when no residency-capable accelerator
is available for the requested operation.
Sets the dispatch policy applied to new aMatrix objects that
do not specify their own policy. The change affects all subsequent
matrix constructions in the current session.
amatrix_set_default_policy(policy)amatrix_set_default_policy(policy)
policy |
Character string. Must be one of |
Invisibly, policy.
amatrix_default_policy,
amatrix_set_default_precision
old <- amatrix_default_policy() amatrix_set_default_policy("auto") amatrix_set_default_policy(old) # restoreold <- amatrix_default_policy() amatrix_set_default_policy("auto") amatrix_set_default_policy(old) # restore
Sets the precision mode applied to new aMatrix objects that
do not specify their own precision. Use "strict" for
reproducible double-precision results and "fast" for maximum
GPU throughput with single/mixed precision.
amatrix_set_default_precision(precision)amatrix_set_default_precision(precision)
precision |
Character string. Must be one of |
Invisibly, precision.
amatrix_default_precision,
amatrix_set_default_policy
old <- amatrix_default_precision() amatrix_set_default_precision("strict") amatrix_set_default_precision(old) # restoreold <- amatrix_default_precision() amatrix_set_default_precision("strict") amatrix_set_default_precision(old) # restore
Finds, enables, and health-checks an installed GPU backend, then
adopts it as the session default for "fast"-precision work.
On Apple Silicon with amatrix.mlx installed this is usually
unnecessary: MLX probing is on by default and activates on first
use. Call this for the opt-in backends (amatrix.opencl,
amatrix.arrayfire, amatrix.metal), to force a specific
backend, or to get an explicit confirmation line.
amatrix_use_gpu(backend = NULL, quiet = FALSE)amatrix_use_gpu(backend = NULL, quiet = FALSE)
backend |
Optional backend name ( |
quiet |
Logical; suppress the status messages. Default
|
GPU backends compute in float32 ("fast" precision, conformance
tolerance ~1e-4); "strict" float64 work always stays on the
CPU reference backend regardless of this setting.
Side effect: on success this sets the session default precision to
"fast" (and, when backend is given explicitly, the
session default policy to that backend) so subsequent matrices route
to the GPU without per-object arguments. Undo with
amatrix_set_default_precision("strict") /
amatrix_set_default_policy("auto").
Invisibly, the name of the enabled backend, or FALSE
if no GPU backend could be enabled.
amatrix_gpu_status,
amatrix_backend_status,
amatrix_set_default_precision
status <- amatrix_gpu_status() if (interactive()) amatrix_use_gpu()status <- amatrix_gpu_status() if (interactive()) amatrix_use_gpu()
Pre-compiles GPU kernels by running tiny dummy operations through each requested backend. Call once before timed work to pay JIT compilation costs upfront. Errors are silently swallowed; warming never alters numerical state.
amatrix_warm( backend = NULL, ops = c("matmul", "crossprod", "qr", "chol"), size = c(64L, 64L), quiet = FALSE )amatrix_warm( backend = NULL, ops = c("matmul", "crossprod", "qr", "chol"), size = c(64L, 64L), quiet = FALSE )
backend |
Character vector of backend names to warm, or
|
ops |
Character vector of operation names to trigger.
Recognised values: |
size |
Integer vector of length 2 giving the dimensions
|
quiet |
Logical; suppress progress messages when |
An invisible named list, one entry per backend, each a list
with elements warmed (logical) and elapsed_ms
(numeric milliseconds, or NA when unavailable).
results <- amatrix_warm(quiet = TRUE)results <- amatrix_warm(quiet = TRUE)
aMatrix is the abstract base from which all concrete amatrix
classes inherit. It carries backend-dispatch metadata that controls
which compute backend (CPU, GPU, etc.) is used for operations on the
matrix.
preferred_backendSingle string naming the preferred compute
backend; one of "cpu", "mlx", "metal",
or "arrayfire".
policySingle string controlling dispatch policy; one of
"auto", "cpu", "mlx", "metal",
or "arrayfire".
precisionSingle string; either "strict" (double
precision, exact results) or "fast" (backend may use
lower precision).
object_idNon-empty string uniquely identifying this object within the session; used for caching and residency tracking.
src_idString recording the object_id of the object
this was derived from, or "" for originals.
finalizer_envEnvironment used to manage GPU-resident memory and deferred host-copy state.
Stores the upper-triangular Cholesky factor R of a
symmetric positive-definite adgeMatrix, as returned by
chol_factor. When the factor is resident on a GPU
backend the host-side @factor slot may be an empty
zero-row matrix; use chol_solve rather than
accessing slots directly.
factorNumeric matrix; the upper-triangular factor R
such that t(R) %*% R equals the source matrix.
May be matrix(numeric(0), 0, 0) when the factor lives
only on the device.
factor_objEither an adgeMatrix holding the
GPU-resident factor, or NULL for CPU-only factors.
source_idCharacter string; the object_id of the
source adgeMatrix.
precisionCharacter string; "strict" or "fast".
backendCharacter string; the backend that computed the factorization.
chol_factor, chol_solve,
chol_logdet
Stores the original square matrix for use with LAPACK's
DGESV routine. Unlike amChol, which
caches the explicit triangular factor, amLU retains
A and delegates factorization to base::solve at
solve time.
ANumeric square matrix; the original matrix passed to
lu_factor.
source_idCharacter string; the object_id of the
source adgeMatrix, or NA for base matrices.
precisionCharacter string; "strict" or "fast",
or NA for base matrices.
backendCharacter string; the preferred backend of the source
object, or NA for base matrices.
Stores the rank-k truncated singular value decomposition of
an aMatrix as returned by svd_factor. Left and
right singular vectors are kept as base R matrices so they are
always host-accessible; optional adgeMatrix copies of
t(u) and v may be present for GPU-accelerated
projection.
uNumeric matrix of left singular vectors; nrow(u)
equals the number of rows of the source matrix and ncol(u)
equals k.
dNumeric vector of singular values of length k, in
descending order.
vNumeric matrix of right singular vectors; nrow(v)
equals the number of columns of the source matrix and
ncol(v) equals k.
kInteger; the requested rank.
methodCharacter string; one of "exact",
"rsvd", or "subspace".
engineCharacter string identifying the low-level solver used
(e.g., "exact_svd", "irlba_svdr",
"backend_rsvd").
source_idCharacter string; the object_id of the
source aMatrix.
precisionCharacter string; "strict" or "fast".
backendCharacter string; the backend that computed the SVD.
ut_amEither an adgeMatrix holding t(u) for
GPU matrix-multiply routing, or NULL on CPU paths.
v_amEither an adgeMatrix holding v for GPU
matrix-multiply routing, or NULL on CPU paths.
svd_factor, svd_project,
svd_reconstruct
Wraps many_lm to accept a response Y with more than
two dimensions (e.g. a 3-D array). The trailing dimensions are collapsed
into columns for fitting and optionally restored in the output.
array_lm( X, Y, weights = NULL, intercept = FALSE, include_fitted = FALSE, include_residuals = FALSE, cache = TRUE, method = c("normal", "qr"), restore_array = TRUE )array_lm( X, Y, weights = NULL, intercept = FALSE, include_fitted = FALSE, include_residuals = FALSE, cache = TRUE, method = c("normal", "qr"), restore_array = TRUE )
X |
Numeric matrix or |
Y |
Numeric array or matrix of responses. The first dimension must
equal |
weights |
Optional numeric vector of length |
intercept |
Logical. When |
include_fitted |
Logical. When |
include_residuals |
Logical. When |
cache |
Logical. When |
method |
Solver: |
restore_array |
Logical. When |
An object of class "am_array_lm_fit", a named list
containing the same fields as many_lm plus:
Integer vector of trailing dimensions of Y.
Array or vector of residual sums of squares.
Array or vector of residual variances.
X <- matrix(rnorm(50), nrow = 10) Y <- array(rnorm(10 * 3 * 4), dim = c(10, 3, 4)) fit <- array_lm(X, Y) dim(fit$sigma2)X <- matrix(rnorm(50), nrow = 10) Y <- array(rnorm(10 * 3 * 4), dim = c(10, 3, 4)) fit <- array_lm(X, Y) dim(fit$sigma2)
Converts a sparse or dense matrix-like object to an
adgCMatrix with the requested backend metadata.
as_adgCMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )as_adgCMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )
x |
A |
mode |
Single string shortcut; see |
backend |
Alias for |
preferred_backend |
Single string; preferred compute backend. |
policy |
Single string dispatch policy. |
precision |
Single string; |
An adgCMatrix.
Converts a matrix-like object or a resident_handle to an
adgeMatrix. When x is a resident_handle,
ownership of the GPU-resident buffer is transferred to the new
adgeMatrix.
as_adgeMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )as_adgeMatrix( x, mode = NULL, backend = NULL, preferred_backend = NULL, policy = NULL, precision = NULL )
x |
A |
mode |
Single string shortcut; see |
backend |
Alias for |
preferred_backend |
Single string; preferred compute backend. |
policy |
Single string dispatch policy. |
precision |
Single string; |
An adgeMatrix.
m <- matrix(1:6, nrow = 2) A <- as_adgeMatrix(m) dim(A)m <- matrix(1:6, nrow = 2) A <- as_adgeMatrix(m) dim(A)
Creates an adgeMatrix with the resident key still bound. By default the
GPU data is materialized to a host copy. If defer_host = TRUE, the
host copy is not materialized until first host access.
as_adgeMatrix.resident_handle(h, ..., defer_host = FALSE)as_adgeMatrix.resident_handle(h, ..., defer_host = FALSE)
h |
A |
... |
Reserved for future use. |
defer_host |
When |
An adgeMatrix.
Convert adgeMatrix, adgCMatrix, or aTransposeView
objects to base R matrix, numeric vector, or array by
materializing the host copy.
## S4 method for signature 'adgeMatrix' as.matrix(x, ...) ## S3 method for class 'adgeMatrix' as.matrix(x, ...) ## S4 method for signature 'adgCMatrix' as.matrix(x, ...) ## S3 method for class 'adgCMatrix' as.matrix(x, ...) ## S4 method for signature 'aTransposeView' as.matrix(x, ...) ## S3 method for class 'aTransposeView' as.matrix(x, ...) ## S4 method for signature 'amChol' as.matrix(x, ...) ## S4 method for signature 'KronMatrix' as.matrix(x, ...) ## S4 method for signature 'adgeMatrix' as.numeric(x, ...) ## S4 method for signature 'adgeMatrix' as.vector(x, mode = "any") ## S4 method for signature 'adgeMatrix' as.array(x, ...) ## S4 method for signature 'adgCMatrix' as.array(x, ...)## S4 method for signature 'adgeMatrix' as.matrix(x, ...) ## S3 method for class 'adgeMatrix' as.matrix(x, ...) ## S4 method for signature 'adgCMatrix' as.matrix(x, ...) ## S3 method for class 'adgCMatrix' as.matrix(x, ...) ## S4 method for signature 'aTransposeView' as.matrix(x, ...) ## S3 method for class 'aTransposeView' as.matrix(x, ...) ## S4 method for signature 'amChol' as.matrix(x, ...) ## S4 method for signature 'KronMatrix' as.matrix(x, ...) ## S4 method for signature 'adgeMatrix' as.numeric(x, ...) ## S4 method for signature 'adgeMatrix' as.vector(x, mode = "any") ## S4 method for signature 'adgeMatrix' as.array(x, ...) ## S4 method for signature 'adgCMatrix' as.array(x, ...)
x |
An |
... |
Further arguments passed to the corresponding base R coercion function. |
mode |
Storage mode string passed to |
A plain R matrix, numeric vector, or array
containing the materialized host data.
A <- adgeMatrix(matrix(1:6, 2, 3)) as.matrix(A)A <- adgeMatrix(matrix(1:6, 2, 3)) as.matrix(A)
aTransposeView is a zero-copy structural view representing
the transpose of an adgeMatrix. It carries no independent
dense host storage; the underlying data lives in source.
The transposed matrix is materialized on demand via
as.matrix() or amatrix_materialize_host().
sourceThe originating adgeMatrix; kept alive by this
reference.
DimInteger vector of length 2 giving the transposed
dimensions c(ncol_src, nrow_src).
DimnamesList of length 2 with transposed dimnames.
Factorize B symmetric positive-definite matrices in parallel. Each matrix
is dispatched through the same backend as chol_factor, so MLX
GPU acceleration applies to every element when available.
batch_chol(A)batch_chol(A)
A |
A list of square numeric matrices, or a 3-D array |
A list of amChol objects, one per input matrix.
Compute t(A_b) %*% A_b for each matrix in a batch.
batch_crossprod(A)batch_crossprod(A)
A |
A list of numeric matrices, or a 3-D array |
A list of p x p crossproduct matrices.
Solve B linear systems A_b x_b = B_b where each A_b is
represented by its Cholesky factor from batch_chol.
batch_solve(Ls, B)batch_solve(Ls, B)
Ls |
A list of |
B |
A list of right-hand-side matrices/vectors, or a 3-D array
|
A list of solution matrices (or vectors when each rhs is a vector).
Computes a truncated SVD using a block Lanczos bidiagonalization. Each Krylov step issues one GPU GEMM per block rather than sequential GEMVs, significantly reducing kernel-launch overhead on accelerated backends.
block_lanczos( A, nv = 5L, nu = nv, block_size = NULL, n_steps = NULL, mode = "fast", backend = NULL ) block_svd( A, k, block_size = NULL, n_steps = NULL, mode = "fast", backend = NULL )block_lanczos( A, nv = 5L, nu = nv, block_size = NULL, n_steps = NULL, mode = "fast", backend = NULL ) block_svd( A, k, block_size = NULL, n_steps = NULL, mode = "fast", backend = NULL )
A |
Numeric matrix, |
nv |
Number of right singular vectors to return. |
nu |
Number of left singular vectors to return. Defaults to |
block_size |
Integer block width for the Krylov iteration. When
|
n_steps |
Number of Krylov steps. When |
mode |
Execution mode passed to |
backend |
Backend name passed to |
k |
Number of singular values/vectors. Alias for |
A named list with components:
Numeric matrix [m, nu]: left singular vectors.
Numeric vector of length min(nu, nv): singular values
in decreasing order.
Numeric matrix [n, nv]: right singular vectors.
Integer: number of Krylov steps performed.
Integer: total matrix-vector products issued.
A <- matrix(rnorm(200), nrow = 20) res <- block_lanczos(A, nv = 3L) length(res$d)A <- matrix(rnorm(200), nrow = 20) res <- block_lanczos(A, nv = 3L) length(res$d)
Returns the diagonal of the upper-triangular matrix R stored
in an amChol object.
chol_diag(factor)chol_diag(factor)
factor |
An |
Numeric vector of length equal to the matrix dimension.
m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) chol_diag(fac)m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) chol_diag(fac)
Computes the upper-triangular Cholesky factor R of a
symmetric positive-definite adgeMatrix X such that
t(R) %*% R == X. Results are cached by object_id;
repeated calls with the same object return the cached factor.
chol_factor(X)chol_factor(X)
X |
An |
An amChol object.
m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) facm <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) fac
Computes log(det(X)) from the Cholesky factor of a
symmetric positive-definite matrix X as
2 * sum(log(diag(R))), which avoids forming the full
determinant and is numerically stable.
chol_logdet(factor)chol_logdet(factor)
factor |
An |
Scalar double; the log-determinant of the source matrix.
m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) chol_logdet(fac)m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) chol_logdet(fac)
Solves X %*% x = B where X is the symmetric
positive-definite matrix whose Cholesky factorization is stored in
factor. Dispatches to a GPU backend when the factor was
computed in "fast" precision and a device-resident factor
is available.
chol_solve(factor, B)chol_solve(factor, B)
factor |
An |
B |
Numeric vector or matrix; the right-hand side. The number of rows must equal the dimension of the factor. |
Numeric vector or matrix x satisfying
X %*% x == B. Returns a vector when B is a
vector.
m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) b <- rnorm(4) x <- chol_solve(fac, b)m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) b <- rnorm(4) x <- chol_solve(fac, b)
This is the same operation as repeatedly calling
chol_solve(factor, B[[i]]), but it packs all RHS batches into one
wide solve and then splits the result. BLAS/GPU backends generally amortize
launch and dispatch overhead much better on one wide RHS than on many small
independent solves.
chol_solve_batches(factor, B)chol_solve_batches(factor, B)
factor |
An |
B |
A list of RHS vectors/matrices, or a 3-D array |
A list of solution vectors/matrices.
Compute the Cholesky factorization of a sparse symmetric
positive-definite adgCMatrix.
## S4 method for signature 'adgCMatrix' chol(x, ...)## S4 method for signature 'adgCMatrix' chol(x, ...)
x |
A symmetric positive-definite |
... |
Further arguments passed to |
An adgCMatrix or sparse Cholesky factor object.
Compute the Cholesky factor of a symmetric positive-definite
adgeMatrix, dispatching through the amatrix backend.
## S4 method for signature 'adgeMatrix' chol(x, ...)## S4 method for signature 'adgeMatrix' chol(x, ...)
x |
A symmetric positive-definite |
... |
Further arguments passed to the backend. |
An adgeMatrix containing the upper triangular Cholesky
factor.
S <- adgeMatrix(crossprod(matrix(rnorm(9), 3, 3)) + 3 * diag(3)) R <- chol(S)S <- adgeMatrix(crossprod(matrix(rnorm(9), 3, 3)) + 3 * diag(3)) R <- chol(S)
Computes the sample correlation matrix of the columns of X,
optionally with observation weights and column-blocked covariance
accumulation.
correlation(X, center = TRUE, weights = NULL, block_size = NULL)correlation(X, center = TRUE, weights = NULL, block_size = NULL)
X |
Numeric matrix or |
center |
Logical; when |
weights |
Numeric vector of length |
block_size |
Positive integer or |
An adgeMatrix of shape [p, p]: the sample
correlation matrix with diagonal entries set to 1.
X <- matrix(rnorm(50), nrow = 10) R <- correlation(X) round(diag(as.matrix(R)), 6)X <- matrix(rnorm(50), nrow = 10) R <- correlation(X) round(diag(as.matrix(R)), 6)
Bridge cov2cor() through Matrix's covariance-to-correlation methods
so standard workflows such as cov2cor(crossprod(X)) keep working
when crossprod() preserves an amatrix class.
## S4 method for signature 'adgeMatrix' cov2cor(V) ## S4 method for signature 'adgCMatrix' cov2cor(V)## S4 method for signature 'adgeMatrix' cov2cor(V) ## S4 method for signature 'adgCMatrix' cov2cor(V)
V |
A square |
A base R correlation matrix, matching stats::cov2cor() on
the corresponding host matrix.
X <- adgeMatrix(matrix(1:9 + 0, 3, 3)) cov2cor(crossprod(X))X <- adgeMatrix(matrix(1:9 + 0, 3, 3)) cov2cor(crossprod(X))
Computes the (possibly weighted) sample or population covariance matrix of
X. Sparse inputs use a memory-efficient path; dense inputs use a
fused GPU kernel when available, otherwise fall back to CPU centering
followed by a GPU cross-product.
covariance(X, center = TRUE, sample = TRUE, weights = NULL, block_size = NULL)covariance(X, center = TRUE, sample = TRUE, weights = NULL, block_size = NULL)
X |
Numeric matrix, |
center |
Logical. When |
sample |
Logical. When |
weights |
Optional numeric vector of length |
block_size |
Optional integer. When set, the cross-product is computed in column-blocks of this size to limit peak memory. Ignored for sparse inputs. |
An adgeMatrix of shape [p, p].
X <- matrix(rnorm(200), nrow = 40) C <- covariance(X) dim(C)X <- matrix(rnorm(200), nrow = 40) C <- covariance(X) dim(C)
Computes (scalar lambda) or
(vector lambda) in a
single fused call.
crossprod_add_diag(X, lambda)crossprod_add_diag(X, lambda)
X |
Numeric matrix or |
lambda |
Scalar or numeric vector of length |
An adgeMatrix of shape [p, p]: the perturbed
cross-product.
X <- matrix(rnorm(20), nrow = 5) crossprod_add_diag(X, lambda = 0.1)X <- matrix(rnorm(20), nrow = 5) crossprod_add_diag(X, lambda = 0.1)
Computes , a p x p weighted
cross-product. A GPU-resident fast path is used when available.
crossprod_weighted(X, w)crossprod_weighted(X, w)
X |
Numeric matrix or |
w |
Positive numeric vector of length |
An adgeMatrix of shape [p, p].
tcrossprod_weighted, xty_weighted
X <- matrix(rnorm(20), nrow = 5) w <- runif(5) crossprod_weighted(X, w)X <- matrix(rnorm(20), nrow = 5) w <- runif(5) crossprod_weighted(X, w)
Compute (crossprod) or
(tcrossprod) for sparse adgCMatrix
objects, dispatching through the amatrix backend.
## S4 method for signature 'adgCMatrix,missing' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,ANY' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,matrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,Matrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgeMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgCMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgeMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgCMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,missing' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,ANY' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,matrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,Matrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgeMatrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgCMatrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgeMatrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgCMatrix' tcrossprod(x, y = NULL, ...)## S4 method for signature 'adgCMatrix,missing' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,ANY' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,matrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,Matrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgeMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgCMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgeMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgCMatrix' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,missing' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,ANY' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,matrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,Matrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgeMatrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,dgCMatrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgeMatrix' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgCMatrix,adgCMatrix' tcrossprod(x, y = NULL, ...)
x |
An |
y |
A matrix-like object or |
... |
Further arguments passed to the backend. |
An adgeMatrix or adgCMatrix containing the result.
sp <- as(matrix(c(1, 0, 0, 2, 1, 0), 3, 2), "dgCMatrix") A <- adgCMatrix(sp) crossprod(A)sp <- as(matrix(c(1, 0, 0, 2, 1, 0), 3, 2), "dgCMatrix") A <- adgCMatrix(sp) crossprod(A)
Compute (crossprod) or
(tcrossprod) for adgeMatrix objects,
dispatching through the amatrix backend to preserve GPU residency.
## S4 method for signature 'adgeMatrix,ANY' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgeMatrix,missing' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgeMatrix,ANY' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgeMatrix,missing' tcrossprod(x, y = NULL, ...)## S4 method for signature 'adgeMatrix,ANY' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgeMatrix,missing' crossprod(x, y = NULL, ...) ## S4 method for signature 'adgeMatrix,ANY' tcrossprod(x, y = NULL, ...) ## S4 method for signature 'adgeMatrix,missing' tcrossprod(x, y = NULL, ...)
x |
An |
y |
A matrix-like object, or |
... |
Further arguments passed to the underlying backend operation. |
An adgeMatrix containing the result.
A <- adgeMatrix(matrix(rnorm(12), 4, 3)) crossprod(A) tcrossprod(A)A <- adgeMatrix(matrix(rnorm(12), 4, 3)) crossprod(A) tcrossprod(A)
Computes the pairwise distance matrix between rows of X and Y.
The dominant cost (row inner-products via am_tcrossprod) is dispatched to the
active GPU backend (ArrayFire or MLX); norm computation and final transforms
run on CPU where they are O(mp + np) — negligible versus the O(mnp) GEMM.
dist_matrix( X, Y = NULL, method = c("euclidean", "sqeuclidean", "cosine"), tile_size = NULL )dist_matrix( X, Y = NULL, method = c("euclidean", "sqeuclidean", "cosine"), tile_size = NULL )
X |
Numeric matrix or |
Y |
Numeric matrix or |
method |
One of |
tile_size |
Integer row-block size for tiled computation, or |
Numeric matrix [m, n] of pairwise distances.
X <- matrix(rnorm(30), nrow = 6) D <- dist_matrix(X) dim(D)X <- matrix(rnorm(30), nrow = 6) D <- dist_matrix(X) dim(D)
Computes the element-wise inner product sum(x * y), equivalent to
as.numeric(t(x) %*% y) for vectors.
dot(x, y)dot(x, y)
x |
A numeric vector, matrix, or |
y |
A numeric vector, matrix, or |
A single numeric scalar.
dot(1:4, 4:1)dot(1:4, 4:1)
Compute eigenvalues and eigenvectors of a sparse adgCMatrix,
dispatching through the amatrix backend.
## S4 method for signature 'adgCMatrix' eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)## S4 method for signature 'adgCMatrix' eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)
x |
An |
symmetric |
Logical; whether |
only.values |
Logical; if |
EISPACK |
Ignored; retained for signature compatibility. |
A list with components values and vectors.
Compute eigenvalues and eigenvectors of an adgeMatrix,
dispatching through the amatrix backend for symmetric matrices when
GPU acceleration is available. A fallback method for plain matrix
preserves base R behaviour after the generic is promoted to S4.
## S4 method for signature 'adgeMatrix' eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)## S4 method for signature 'adgeMatrix' eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)
x |
An |
symmetric |
Logical indicating whether |
only.values |
Logical; if |
EISPACK |
Ignored; retained for signature compatibility. |
A list with components values (numeric vector) and
vectors (matrix, omitted when only.values = TRUE).
S <- adgeMatrix(crossprod(matrix(rnorm(9), 3, 3))) ev <- eigen(S, symmetric = TRUE) length(ev$values)S <- adgeMatrix(crossprod(matrix(rnorm(9), 3, 3))) ev <- eigen(S, symmetric = TRUE) length(ev$values)
Computes eigenvalues and eigenvectors of a real symmetric matrix by
dispatching to the active backend via eigen with
symmetric = TRUE.
eigh(x)eigh(x)
x |
A real symmetric numeric matrix, |
A list with components values (numeric vector of eigenvalues
in ascending order) and vectors (numeric matrix whose columns are
the corresponding eigenvectors).
S <- crossprod(matrix(rnorm(25), nrow = 5)) ev <- eigh(adgeMatrix(S)) length(ev$values)S <- crossprod(matrix(rnorm(25), nrow = 5)) ev <- eigh(adgeMatrix(S)) length(ev$values)
Apply an element-wise arithmetic operation to one or two matrices, dispatching to the preferred GPU backend when available.
ewise(op, e1, e2 = NULL)ewise(op, e1, e2 = NULL)
op |
Character string: |
e1 |
A numeric matrix or |
e2 |
A numeric matrix, |
A matrix of the same dimensions as e1.
Computes alpha * op(A) %*% op(B) + beta * C, where
op(X) = t(X) when the corresponding trans flag is
TRUE. Routes internally to the most efficient resident
operation for the chosen transpose combination.
gemm(A, B, C = NULL, alpha = 1, beta = 1, transA = FALSE, transB = FALSE)gemm(A, B, C = NULL, alpha = 1, beta = 1, transA = FALSE, transB = FALSE)
A |
A matrix or |
B |
A matrix or |
C |
Optional matrix or |
alpha |
Numeric scalar multiplier for |
beta |
Numeric scalar multiplier for |
transA |
Logical; transpose |
transB |
Logical; transpose |
A matrix of dimensions nrow(op(A)) by
ncol(op(B)).
A <- adgeMatrix(matrix(1:6, 2, 3)) B <- adgeMatrix(matrix(1:6, 2, 3)) gemm(A, B, transA = TRUE) # t(A) %*% B gemm(A, B, transB = TRUE) # A %*% t(B)A <- adgeMatrix(matrix(1:6, 2, 3)) B <- adgeMatrix(matrix(1:6, 2, 3)) gemm(A, B, transA = TRUE) # t(A) %*% B gemm(A, B, transB = TRUE) # A %*% t(B)
Wraps irlba::irlba() with an adgeMatrix input so that every
Lanczos matrix-vector product routes through the amatrix GPU dispatch path.
The matrix A is kept resident on device; consecutive matvecs in the
Lanczos loop avoid host round-trips.
irlba( A, nv = 5, nu = nv, ..., mode = "fast", backend = NULL, implementation = c("compat", "block"), block_size = NULL, n_steps = NULL )irlba( A, nv = 5, nu = nv, ..., mode = "fast", backend = NULL, implementation = c("compat", "block"), block_size = NULL, n_steps = NULL )
A |
A matrix, |
nv |
Number of right singular vectors. |
nu |
Number of left singular vectors. Defaults to |
... |
Additional arguments forwarded to |
mode |
Execution mode passed to |
backend |
Backend name (e.g. |
implementation |
Lanczos implementation to use. |
block_size |
Block size passed to |
n_steps |
Number of block Krylov steps passed to
|
The hot loop in irlba is two matrix-vector products per Lanczos step:
A %*% v and w %*% A. Both route through am_matmul()
when A is an adgeMatrix, giving GPU acceleration on the dominant
cost. Orthogonalization, svd(B), and convergence tests remain on CPU
where they belong (the subspace dimension work is always small).
Do not pass mult= — it is deprecated in irlba and forces a
non-standard dispatch path. Pass an adgeMatrix instead.
Same structure as irlba::irlba(): a list with components
d, u, v, iter, mprod.
Implements Golub-Kahan Lanczos bidiagonalization directly in ArrayFire C, keeping all matvecs and CGS2 reorthogonalization on the GPU. Only 2*work scalars and the final basis matrices cross PCIe per restart; no per-step host transfers.
irlba_native( A, nv = 5L, nu = nv, tol = sqrt(.Machine$double.eps), maxit = 100L, work = max(nv + 20L, 3L * nv), v0 = NULL, mode = "fast", backend = NULL )irlba_native( A, nv = 5L, nu = nv, tol = sqrt(.Machine$double.eps), maxit = 100L, work = max(nv + 20L, 3L * nv), v0 = NULL, mode = "fast", backend = NULL )
A |
A matrix or |
nv |
Number of singular values/vectors to compute. |
nu |
Number of left singular vectors (default = |
tol |
Convergence tolerance. |
maxit |
Maximum number of restarts. |
work |
Size of the Lanczos subspace per restart. Larger values
converge in fewer restarts at the cost of more memory and work per
restart. Default is |
v0 |
Optional starting vector (length |
mode, backend
|
Passed to |
Compared to am_irlba, which routes each Lanczos matvec through S4
dispatch, this function:
eliminates S4 overhead on the hot path
replaces k sequential GEMVs for reorthogonalization with one GEMM
uploads A once and never re-uploads it across restarts
A list with components d, u, v, iter,
mprod, compatible with irlba::irlba().
Computes the pairwise kernel matrix between rows of X and Y.
The expensive am_tcrossprod is GPU-dispatched; element-wise transforms (exp,
sqrt, pow) run on CPU.
kernel_matrix( X, Y = NULL, kernel = c("linear", "rbf", "polynomial", "cosine", "laplacian"), sigma = 1, degree = 2L, coef = 0, preferred_backend = NULL, zero_diag = FALSE )kernel_matrix( X, Y = NULL, kernel = c("linear", "rbf", "polynomial", "cosine", "laplacian"), sigma = 1, degree = 2L, coef = 0, preferred_backend = NULL, zero_diag = FALSE )
X |
Numeric matrix or |
Y |
Numeric matrix or |
kernel |
Kernel type string (see Details). |
sigma |
Bandwidth for |
degree |
Polynomial degree for |
coef |
Constant term for |
preferred_backend |
Optional backend name to override the default
dispatch (e.g., |
zero_diag |
When |
Kernels:
Numeric matrix [m, n] of kernel values.
Computes the Kronecker product and returns the result as an adgeMatrix.
Accepts plain matrices or any aMatrix subclass.
For a lazy variant that avoids forming the full product see
kron_matrix.
kron(A, B)kron(A, B)
A, B
|
Matrices or |
An adgeMatrix of dimension (nrow(A)*nrow(B)) x (ncol(A)*ncol(B)).
Creates a KronMatrix that stores the factor
matrices A and B without materializing the full
Kronecker product. Standard operations such as %*%,
crossprod, solve, and determinant are
available and exploit the Kronecker structure.
kron_matrix(A, B)kron_matrix(A, B)
A |
Numeric matrix or object coercible via |
B |
Numeric matrix or object coercible via |
A KronMatrix of implicit dimensions
c(nrow(A) * nrow(B), ncol(A) * ncol(B)).
A <- matrix(1:4, 2, 2) B <- diag(3) K <- kron_matrix(A, B) dim(K) as.matrix(K)A <- matrix(1:4, 2, 2) B <- diag(3) K <- kron_matrix(A, B) dim(K) as.matrix(K)
S4 methods for kronecker and the %x% operator
that keep the result as an amatrix. Without them, kronecker(A, B) and
A %x% B dispatch to the Matrix methods for the parent
dgeMatrix / dgCMatrix classes and silently demote to a plain
(non-amatrix) result, discarding backend-dispatch metadata.
## S4 method for signature 'adgeMatrix,adgeMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgeMatrix,adgCMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgCMatrix,adgeMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgCMatrix,adgCMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgeMatrix,matrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'matrix,adgeMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgCMatrix,matrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'matrix,adgCMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...)## S4 method for signature 'adgeMatrix,adgeMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgeMatrix,adgCMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgCMatrix,adgeMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgCMatrix,adgCMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgeMatrix,matrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'matrix,adgeMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'adgCMatrix,matrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...) ## S4 method for signature 'matrix,adgCMatrix' kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...)
X, Y
|
Kronecker factors. At least one is an |
FUN |
Function (or its name) applied to the outer products; passed to
the underlying Matrix method. Defaults to |
make.dimnames |
Logical; construct dimnames from the factors. Passed to the underlying method. |
... |
Further arguments passed to the underlying method. |
The product itself is computed by Matrix's own Kronecker methods on the
materialized host contents, so values are identical to
base::kronecker() on the dense contents. The result is re-wrapped as
an adgCMatrix when it is sparse and an
adgeMatrix otherwise, inheriting the preferred backend,
policy, and precision of the first amatrix operand.
An adgeMatrix (dense) or
adgCMatrix (sparse).
A <- adgeMatrix(matrix(1:4, 2, 2)) B <- adgeMatrix(diag(2)) kronecker(A, B) A %x% BA <- adgeMatrix(matrix(1:4, 2, 2)) B <- adgeMatrix(diag(2)) kronecker(A, B) A %x% B
KronMatrix stores the two factor matrices A (m x n)
and B (p x q) without forming the full (mp x nq) Kronecker
product. Matrix-vector and matrix-matrix products are evaluated
using the vec-permutation identity
(A x B) vec(X) = vec(B X t(A)), keeping memory use at
O(mn + pq) rather than O(mnpq).
ANumeric matrix; the left factor of the Kronecker product.
BNumeric matrix; the right factor of the Kronecker product.
Solves the ordinary least-squares problem for a
single design matrix X and one or more response columns Y.
lm_fit( X, Y, intercept = FALSE, include_fitted = TRUE, include_residuals = TRUE, cache = TRUE, method = c("normal", "qr") )lm_fit( X, Y, intercept = FALSE, include_fitted = TRUE, include_residuals = TRUE, cache = TRUE, method = c("normal", "qr") )
X |
Numeric matrix or |
Y |
Numeric matrix, vector, or |
intercept |
Logical. When |
include_fitted |
Logical. When |
include_residuals |
Logical. When |
cache |
Logical. When |
method |
Solver method: |
An object of class "lm_fit", a named list containing:
adgeMatrix of shape [p, q].
adgeMatrix of shape [n, q], or
NULL when include_fitted = FALSE.
adgeMatrix of shape [n, q], or
NULL when include_residuals = FALSE.
Integer model rank.
Residual degrees of freedom.
X <- matrix(rnorm(50), nrow = 10) y <- rnorm(10) fit <- lm_fit(X, y) coef(fit)X <- matrix(rnorm(50), nrow = 10) y <- rnorm(10) fit <- lm_fit(X, y) coef(fit)
Computes exact leave-one-out (LOO) prediction errors by refitting the
model n times, each time dropping one observation. Uses
qr_downdate internally to avoid recomputing the full
factorization from scratch.
lm_loo_cv(X, y, method = "qr", ...)lm_loo_cv(X, y, method = "qr", ...)
X |
Numeric matrix or |
y |
Numeric vector or single-column matrix of responses, length
|
method |
Character string passed to |
... |
Additional arguments forwarded to |
A named list with two elements:
Numeric vector of length n: LOO prediction
errors .
Scalar mean squared LOO error.
## Not run: X <- adgeMatrix(matrix(rnorm(50), nrow = 10)) y <- rnorm(10) cv <- lm_loo_cv(X, y) cv$mse ## End(Not run)## Not run: X <- adgeMatrix(matrix(rnorm(50), nrow = 10)) y <- rnorm(10) cv <- lm_loo_cv(X, y) cv$mse ## End(Not run)
Wraps a square numeric matrix or adgeMatrix in an
amLU object. The actual LU decomposition is
performed by base::solve at solve time via LAPACK's
DGESV.
lu_factor(A)lu_factor(A)
A |
A square numeric matrix or |
An amLU object.
m <- matrix(c(2, 1, 5, 3), nrow = 2) fac <- lu_factor(m) facm <- matrix(c(2, 1, 5, 3), nrow = 2) fac <- lu_factor(m) fac
Solves A %*% x = B where A is the square matrix
stored in factor, delegating to base::solve (LAPACK
DGESV).
lu_solve(factor, B)lu_solve(factor, B)
factor |
|
B |
Numeric vector or matrix; the right-hand side. The number
of rows must equal the dimension of |
Numeric vector or matrix x satisfying
A %*% x == B. Returns a vector when B is a
vector or single-column matrix.
m <- matrix(c(2, 1, 5, 3), nrow = 2) fac <- lu_factor(m) b <- c(1, 2) lu_solve(fac, b)m <- matrix(c(2, 1, 5, 3), nrow = 2) fac <- lu_factor(m) b <- c(1, 2) lu_solve(fac, b)
The flagship batch regression function. Solves where
Y is a matrix whose columns are independent response variables.
When no GPU backend is active the normal-equations or QR path runs on CPU.
With an active GPU backend the QR path dispatches the factorization to the
device and keeps intermediate results resident to minimise host round-trips.
many_lm( X, Y, weights = NULL, intercept = FALSE, include_fitted = FALSE, include_residuals = FALSE, cache = TRUE, method = c("normal", "qr") )many_lm( X, Y, weights = NULL, intercept = FALSE, include_fitted = FALSE, include_residuals = FALSE, cache = TRUE, method = c("normal", "qr") )
X |
Numeric matrix or |
Y |
Numeric matrix or |
weights |
Optional numeric vector of length |
intercept |
Logical. When |
include_fitted |
Logical. When |
include_residuals |
Logical. When |
cache |
Logical. When |
method |
Solver: |
An object of class "am_many_lm_fit", a named list
containing:
adgeMatrix of shape [p, q].
adgeMatrix [n, q] or NULL.
adgeMatrix [n, q] or NULL.
Numeric vector of length q: residual sums of squares.
Numeric vector of length q: residual variances.
Integer model rank.
Residual degrees of freedom.
X <- matrix(rnorm(100), nrow = 20) Y <- matrix(rnorm(60), nrow = 20) fit <- many_lm(X, Y, method = "qr") dim(coef(fit))X <- matrix(rnorm(100), nrow = 20) Y <- matrix(rnorm(60), nrow = 20) fit <- many_lm(X, Y, method = "qr") dim(coef(fit))
Apply an elementwise function to the eigenvalues of a symmetric
positive definite matrix and reconstruct the result:
.
mat_sqrt(X) mat_pow(X, p) mat_log(X)mat_sqrt(X) mat_pow(X, p) mat_log(X)
X |
Symmetric positive definite numeric matrix or
|
p |
Numeric scalar exponent (used by |
An adgeMatrix of shape [p, p]: the matrix
function applied to X.
S <- crossprod(matrix(rnorm(16), 4)) + diag(4) mat_sqrt(S) mat_log(S) mat_pow(S, -1)S <- crossprod(matrix(rnorm(16), 4)) + diag(4) mat_sqrt(S) mat_log(S) mat_pow(S, -1)
Multiplies two matrices, routing to an accelerated backend when available.
Plain numeric vectors supplied as y are promoted to a column matrix
and the result is dropped back to a vector.
matmul(x, y)matmul(x, y)
x |
A matrix or |
y |
A matrix, |
A matrix (or numeric vector when y was a vector) of
dimensions nrow(x) by ncol(y).
A <- adgeMatrix(matrix(1:6, 2, 3)) B <- adgeMatrix(matrix(1:6, 3, 2)) matmul(A, B)A <- adgeMatrix(matrix(1:6, 2, 3)) B <- adgeMatrix(matrix(1:6, 3, 2)) matmul(A, B)
Dispatches %*% through the amatrix backend for dense
adgeMatrix objects on the left-hand side, preserving GPU
residency across the operation.
## S4 method for signature 'adgeMatrix,matrix' x %*% y ## S4 method for signature 'adgeMatrix,Matrix' x %*% y ## S4 method for signature 'adgeMatrix,dgeMatrix' x %*% y ## S4 method for signature 'adgeMatrix,dgCMatrix' x %*% y ## S4 method for signature 'adgeMatrix,adgeMatrix' x %*% y ## S4 method for signature 'adgeMatrix,adgCMatrix' x %*% y ## S4 method for signature 'numeric,adgeMatrix' x %*% y## S4 method for signature 'adgeMatrix,matrix' x %*% y ## S4 method for signature 'adgeMatrix,Matrix' x %*% y ## S4 method for signature 'adgeMatrix,dgeMatrix' x %*% y ## S4 method for signature 'adgeMatrix,dgCMatrix' x %*% y ## S4 method for signature 'adgeMatrix,adgeMatrix' x %*% y ## S4 method for signature 'adgeMatrix,adgCMatrix' x %*% y ## S4 method for signature 'numeric,adgeMatrix' x %*% y
x |
An |
y |
A matrix-like object: |
An adgeMatrix (or numeric vector when y
is a vector and x is adgeMatrix), with the same backend
metadata as x.
A <- adgeMatrix(matrix(1:6, 2, 3)) B <- matrix(1:3, 3, 1) A %*% BA <- adgeMatrix(matrix(1:6, 2, 3)) B <- matrix(1:3, 3, 1) A %*% B
Computes and
returns for each row , 1-indexed.
GPU path avoids host round-trips by chaining resident operations.
pairwise_sqdist_argmin(X, Ct, x_norms = NULL, c_norms = NULL)pairwise_sqdist_argmin(X, Ct, x_norms = NULL, c_norms = NULL)
X |
n×p |
Ct |
p×K numeric matrix holding the centroids transposed:
|
x_norms |
Optional n-vector of precomputed |
c_norms |
Optional K-vector of precomputed |
Integer vector of length n, 1-indexed nearest centroid per row.
Convenience wrapper that calls svd_project followed
by svd_reconstruct, yielding the rank-k
least-squares approximation of Y in the column space of
the original matrix.
pca_coef(factor, Y)pca_coef(factor, Y)
factor |
An |
Y |
Numeric matrix or vector to project and reconstruct.
Must have |
Numeric matrix with the same dimensions as Y,
containing the rank-k approximation.
m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 2L) approx <- pca_coef(fac, m)m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 2L) approx <- pca_coef(fac, m)
Updates a QR factorization to reflect the removal of a single row from the original matrix. The current implementation refits from the reduced matrix; a Givens-rotation path is planned for a future release.
qr_downdate(qr_factor, row_idx, X = NULL)qr_downdate(qr_factor, row_idx, X = NULL)
qr_factor |
An |
row_idx |
Positive integer index of the row to remove. |
X |
The original numeric matrix or |
An updated amQR factor with row row_idx
excluded.
## Not run: X <- adgeMatrix(matrix(rnorm(40), nrow = 8)) qf <- am_qr(X) qf2 <- qr_downdate(qf, row_idx = 3L, X = X) qr_info(qf2)$dim ## End(Not run)## Not run: X <- adgeMatrix(matrix(rnorm(40), nrow = 8)) qf <- am_qr(X) qf2 <- qr_downdate(qf, row_idx = 3L, X = X) qr_info(qf2)$dim ## End(Not run)
Returns a named list of metadata fields describing an amQR
factor produced by am_qr().
qr_info(qr)qr_info(qr)
qr |
An |
A named list with the following elements:
Integer effective rank of the factored matrix.
Integer vector of length 2: c(nrow, ncol) of
the source matrix.
Logical; TRUE when a thin (economy) QR was
computed.
Logical; TRUE when column pivoting was
used.
Integer permutation vector, or NULL when
unpivoted.
Character string describing the internal storage format.
Character string naming the backend that owns
any resident buffers, or NULL.
Character string: the preferred backend.
Character string: "strict" or
"fast".
Character string: QR algorithm used.
Logical.
Character string or NULL.
Logical.
Logical.
Logical.
X <- adgeMatrix(matrix(rnorm(30), nrow = 6)) qf <- am_qr(X) info <- qr_info(qf) info$rankX <- adgeMatrix(matrix(rnorm(30), nrow = 6)) qf <- am_qr(X) info <- qr_info(qf) info$rank
Computes t(v) %*% solve(X) %*% v (for a vector
v) or t(V) %*% solve(X) %*% V (for a matrix
V) efficiently via the Cholesky factor of X, without
forming the inverse.
quad_form(factor, v)quad_form(factor, v)
factor |
An |
v |
Numeric vector or matrix. For a vector, the result is a
scalar; for a matrix with |
Scalar double (when v is a vector) or numeric matrix
of dimensions ncol(v) x ncol(v) containing the quadratic
form.
m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) v <- rnorm(4) quad_form(fac, v)m <- crossprod(matrix(rnorm(16), 4, 4)) + diag(4) A <- adgeMatrix(m) fac <- chol_factor(A) v <- rnorm(4) quad_form(fac, v)
Wraps an adgeMatrix or plain matrix in a lightweight mutable
environment that holds a GPU-resident buffer key. Unlike
adgeMatrix, the handle can be updated in place, making it
suitable for iterative algorithms that would otherwise incur per-step
S4 object allocation overhead. The handle owns its resident key and
releases the device buffer when garbage collected.
resident_handle(x, backend = NULL)resident_handle(x, backend = NULL)
x |
An |
backend |
Character string. Name of the backend to use.
Defaults to |
A resident_handle environment with fields
backend_name, resident_key, dim,
dimnames, policy, precision, and
active.
am_sweep_inplace, rh_rowSums,
rh_colSums
m <- adgeMatrix(matrix(runif(12), 3, 4), preferred_backend = "cpu") # resident_handle requires a backend with residency support (e.g. MLX, OpenCL)m <- adgeMatrix(matrix(runif(12), 3, 4), preferred_backend = "cpu") # resident_handle requires a backend with residency support (e.g. MLX, OpenCL)
Computes column sums of the matrix stored in a
resident_handle, using a GPU-resident reduction when the
backend supports it. Falls back to base::colSums on the
materialized matrix when no resident reduction is available.
rh_colSums(h)rh_colSums(h)
h |
A |
Numeric vector of length ncol(h).
# requires a backend with residency support (e.g. MLX, OpenCL)# requires a backend with residency support (e.g. MLX, OpenCL)
Computes row sums of the matrix stored in a resident_handle,
using a GPU-resident reduction when the backend supports it to avoid
a round-trip download. Falls back to base::rowSums on the
materialized matrix when no resident reduction is available.
rh_rowSums(h)rh_rowSums(h)
h |
A |
Numeric vector of length nrow(h).
# requires a backend with residency support (e.g. MLX, OpenCL)# requires a backend with residency support (e.g. MLX, OpenCL)
Solves the penalized least-squares problem
for a
single penalty value lambda.
ridge_fit( X, Y, lambda, intercept = FALSE, penalize_intercept = FALSE, include_fitted = TRUE, include_residuals = TRUE, cache = TRUE )ridge_fit( X, Y, lambda, intercept = FALSE, penalize_intercept = FALSE, include_fitted = TRUE, include_residuals = TRUE, cache = TRUE )
X |
Numeric matrix or |
Y |
Numeric matrix, vector, or |
lambda |
Non-negative scalar ridge penalty. |
intercept |
Logical; when |
penalize_intercept |
Logical; when |
include_fitted |
Logical; include fitted values in the result. |
include_residuals |
Logical; include residuals in the result. |
cache |
Logical; cache |
An object of class "ridge_fit", a named list
containing:
adgeMatrix of shape [p, q].
adgeMatrix of shape [n, q],
or NULL when include_fitted = FALSE.
adgeMatrix of shape [n, q], or
NULL when include_residuals = FALSE.
The penalty value used.
Integer model rank.
Residual degrees of freedom.
X <- matrix(rnorm(50), nrow = 10) y <- rnorm(10) fit <- ridge_fit(X, y, lambda = 1) coef(fit)X <- matrix(rnorm(50), nrow = 10) y <- rnorm(10) fit <- ridge_fit(X, y, lambda = 1) coef(fit)
Fits ridge regression for every penalty value in lambdas via a
single thin SVD of X, returning coefficients for all penalties
at once.
ridge_path(X, Y, lambdas, k = NULL, ...)ridge_path(X, Y, lambdas, k = NULL, ...)
X |
Numeric matrix or |
Y |
Numeric matrix, vector, or |
lambdas |
Positive numeric vector of ridge penalty values.
Must satisfy |
k |
Integer or |
... |
Additional arguments forwarded to |
An object of class "ridge_path", a named list
containing:
Numeric array of shape [p, q, length(lambdas)];
coefficient matrix for each penalty.
The input penalty vector.
The amSVD factor object used internally.
Integer number of singular values actually used.
X <- matrix(rnorm(60), nrow = 15) y <- rnorm(15) path <- ridge_path(X, y, lambdas = c(0.1, 1, 10)) dim(path$coef)X <- matrix(rnorm(60), nrow = 15) y <- rnorm(15) path <- ridge_path(X, y, lambdas = c(0.1, 1, 10)) dim(path$coef)
Compute row or column means of a matrix or aMatrix, dispatching
to an accelerated backend when one is available.
rowmeans(x, na.rm = FALSE) colmeans(x, na.rm = FALSE)rowmeans(x, na.rm = FALSE) colmeans(x, na.rm = FALSE)
x |
A matrix or |
na.rm |
Logical; if |
A numeric vector of length nrow(x) (rowmeans) or
ncol(x) (colmeans).
m <- matrix(1:12, 3, 4) rowmeans(m) colmeans(m)m <- matrix(1:12, 3, 4) rowmeans(m) colmeans(m)
Scale each row or column of a matrix by a numeric vector, equivalent to
left- or right-multiplying by a diagonal matrix.
rowscale computes diag(d) %*% X (row scaled by
d[i]); colscale computes X %*% diag(d) (column
scaled by d[j]).
rowscale(X, d) colscale(X, d)rowscale(X, d) colscale(X, d)
X |
A matrix or |
d |
Numeric vector of scale factors. Length must equal |
A matrix or aMatrix of the same dimensions as X.
m <- matrix(1:6, 2, 3) rowscale(m, c(2, 0.5)) colscale(m, c(1, 2, 3))m <- matrix(1:6, 2, 3) rowscale(m, c(2, 0.5)) colscale(m, c(1, 2, 3))
Compute row or column sums of a matrix or aMatrix, dispatching
to an accelerated backend when one is available.
rowsums(x, na.rm = FALSE, dims = 1L) colsums(x, na.rm = FALSE, dims = 1L)rowsums(x, na.rm = FALSE, dims = 1L) colsums(x, na.rm = FALSE, dims = 1L)
x |
A matrix or |
na.rm |
Logical; if |
dims |
Integer; the number of dimensions to regard as rows
(for |
A numeric vector of length nrow(x) (rowsums) or
ncol(x) (colsums).
m <- adgeMatrix(matrix(1:12, 3, 4)) rowsums(m) colsums(m)m <- adgeMatrix(matrix(1:12, 3, 4)) rowsums(m) colsums(m)
Compute row or column sums and means for a sparse adgCMatrix,
dispatching through the amatrix backend when GPU acceleration is
available.
## S4 method for signature 'adgCMatrix' rowSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgCMatrix' colSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgCMatrix' rowMeans(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgCMatrix' colMeans(x, na.rm = FALSE, dims = 1L)## S4 method for signature 'adgCMatrix' rowSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgCMatrix' colSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgCMatrix' rowMeans(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgCMatrix' colMeans(x, na.rm = FALSE, dims = 1L)
x |
An |
na.rm |
Logical; if |
dims |
Integer; dimensions to sum over (passed to the backend). |
A numeric vector of length equal to the number of rows or columns.
sp <- as(matrix(c(1, 0, 2, 0, 3, 0), 2, 3), "dgCMatrix") A <- adgCMatrix(sp) rowSums(A) colMeans(A)sp <- as(matrix(c(1, 0, 2, 0, 3, 0), 2, 3), "dgCMatrix") A <- adgCMatrix(sp) rowSums(A) colMeans(A)
Compute row or column sums and means for an adgeMatrix, dispatching
through the amatrix backend when GPU acceleration is available.
## S4 method for signature 'adgeMatrix' rowSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgeMatrix' colSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgeMatrix' rowMeans(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgeMatrix' colMeans(x, na.rm = FALSE, dims = 1L)## S4 method for signature 'adgeMatrix' rowSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgeMatrix' colSums(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgeMatrix' rowMeans(x, na.rm = FALSE, dims = 1L) ## S4 method for signature 'adgeMatrix' colMeans(x, na.rm = FALSE, dims = 1L)
x |
An |
na.rm |
Logical; if |
dims |
Integer; dimensions to sum over (passed to the backend). |
A numeric vector of length equal to the number of rows or columns.
A <- adgeMatrix(matrix(1:12, 3, 4)) rowSums(A) colMeans(A)A <- adgeMatrix(matrix(1:12, 3, 4)) rowSums(A) colMeans(A)
Computes a truncated SVD via randomized projection entirely on the GPU.
All QR, matmul, and SVD steps stay on device; a single mlx_eval
materializes the results. Falls back to irlba::svdr on CPU if no
GPU backend with rsvd support is active.
rsvd(x, k, n_oversamples = 10L, n_iter = 2L, ...)rsvd(x, k, n_oversamples = 10L, n_iter = 2L, ...)
x |
An |
k |
Number of singular values/vectors to compute. |
n_oversamples |
Extra columns for the random projection (default 10). Increasing this improves accuracy at modest cost. |
n_iter |
Number of power-iteration passes (default 2). More passes give better accuracy for matrices with slowly decaying spectra. |
... |
Ignored (for forward compatibility). |
A list with components u (m x k), d (length-k
singular values, decreasing), and v (n x k).
Halko, N., Martinsson, P. G., & Tropp, J. A. (2011). Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions. SIAM Review, 53(2), 217-288.
A <- matrix(rnorm(200), nrow = 20) res <- rsvd(A, k = 3L) length(res$d)A <- matrix(rnorm(200), nrow = 20) res <- rsvd(A, k = 3L) length(res$d)
Compute the mean of rows of x grouped by integer labels,
dispatching to GPU when available.
segment_mean(x, labels, K)segment_mean(x, labels, K)
x |
A numeric matrix or |
labels |
Integer vector of group labels (1-based). |
K |
Number of groups. |
A K-by-ncol(x) matrix of group means.
Sum rows of x grouped by integer labels, dispatching to
GPU when available.
segment_sum(x, labels, K)segment_sum(x, labels, K)
x |
A numeric matrix or |
labels |
Integer vector of group labels (1-based). |
K |
Number of groups. |
A K-by-ncol(x) matrix of group sums.
Alternates row and column normalization until the matrix is approximately
doubly stochastic. When the chosen backend supports resident broadcast and
reduction kernels, the hot loop stays on device via resident_handle
and returns a deferred adgeMatrix bound to the resident result.
sinkhorn( A, max_iter = 200L, tol = 1e-08, check_every = 5L, eps = 1e-15, mode = "fast", backend = NULL, return_info = FALSE )sinkhorn( A, max_iter = 200L, tol = 1e-08, check_every = 5L, eps = 1e-15, mode = "fast", backend = NULL, return_info = FALSE )
A |
A dense numeric matrix or |
max_iter |
Maximum number of Sinkhorn iterations. |
tol |
Convergence tolerance on the maximum row/column sum error. |
check_every |
Check convergence every |
eps |
Floor applied to row/column sums before division. |
mode |
Execution mode used when coercing a plain matrix. Default
|
backend |
Backend name used when coercing a plain matrix. Ignored when
|
return_info |
When |
By default, an adgeMatrix. With return_info = TRUE, a
list containing result, iterations, converged,
row_error, col_error, backend, and method.
A <- abs(matrix(rnorm(16), nrow = 4)) + 0.1 S <- sinkhorn(A, max_iter = 50L) # Row sums should be close to 1 rowSums(as.matrix(S))A <- abs(matrix(rnorm(16), nrow = 4)) + 0.1 S <- sinkhorn(A, max_iter = 50L) # Row sums should be close to 1 rowSums(as.matrix(S))
Solves R %*% x = B (or t(R) %*% x = B when
lower = TRUE) for x, where R is a triangular
matrix. Dispatches to a GPU backend when R is an
amChol or adgeMatrix with a live
resident key and a capable backend.
solve_triangular(R, B, lower = FALSE)solve_triangular(R, B, lower = FALSE)
R |
An |
B |
Numeric vector or matrix; the right-hand side. |
lower |
Logical scalar; |
Numeric vector or matrix x satisfying
R %*% x == B (or its transpose variant).
Returns a vector when B is a vector or single-column
matrix.
R <- chol(crossprod(matrix(rnorm(16), 4, 4)) + diag(4)) b <- rnorm(4) x <- solve_triangular(R, b)R <- chol(crossprod(matrix(rnorm(16), 4, 4)) + diag(4)) b <- rnorm(4) x <- solve_triangular(R, b)
Compute the solution to or the inverse of a when
b is missing, for a sparse adgCMatrix coefficient matrix.
## S4 method for signature 'adgCMatrix,missing' solve(a, b, ...) ## S4 method for signature 'adgCMatrix,ANY' solve(a, b, ...)## S4 method for signature 'adgCMatrix,missing' solve(a, b, ...) ## S4 method for signature 'adgCMatrix,ANY' solve(a, b, ...)
a |
An |
b |
A matrix or vector right-hand side, or missing for inversion. |
... |
Further arguments passed to the backend. |
An adgeMatrix or adgCMatrix containing the
solution.
Compute the solution to or the matrix inverse of a
when b is missing, dispatching through the amatrix backend.
## S4 method for signature 'adgeMatrix,missing' solve(a, b, ...) ## S4 method for signature 'adgeMatrix,ANY' solve(a, b, ...)## S4 method for signature 'adgeMatrix,missing' solve(a, b, ...) ## S4 method for signature 'adgeMatrix,ANY' solve(a, b, ...)
a |
An |
b |
A matrix or vector right-hand side, or missing for matrix inversion. |
... |
Further arguments passed to the backend. |
An adgeMatrix (or numeric vector when b is a
plain vector) containing the solution.
A <- adgeMatrix(crossprod(matrix(rnorm(9), 3, 3)) + 3 * diag(3)) solve(A)A <- adgeMatrix(crossprod(matrix(rnorm(9), 3, 3)) + 3 * diag(3)) solve(A)
Computes a rank-k truncated singular value decomposition of
X, dispatching to the most suitable algorithm and backend
based on matrix size, requested rank, and available hardware.
svd_factor( X, k = min(dim(X)), method = c("auto", "exact", "rsvd", "subspace"), n_oversamples = .amatrix_svd_factor_default_oversamples(k), n_iter = 2L )svd_factor( X, k = min(dim(X)), method = c("auto", "exact", "rsvd", "subspace"), n_oversamples = .amatrix_svd_factor_default_oversamples(k), n_iter = 2L )
X |
An |
k |
Positive integer; the number of singular values and
vectors to compute. Defaults to |
method |
One of |
n_oversamples |
Non-negative integer; extra random vectors
used to stabilize randomized algorithms. Ignored for
|
n_iter |
Non-negative integer; number of power iterations for
the subspace method. Ignored for |
An amSVD object containing slots
u, d, v, and metadata.
m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 3L) facm <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 3L) fac
Computes t(U) %*% Y, where U is the matrix of left
singular vectors stored in factor. Routes through a GPU
backend when the factor was computed in "fast" precision and
a device copy of t(U) is available.
svd_project(factor, Y)svd_project(factor, Y)
factor |
An |
Y |
Numeric matrix or vector with |
Numeric matrix of dimensions k x ncol(Y) containing
the projected coordinates.
m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 2L) coords <- svd_project(fac, m)m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 2L) coords <- svd_project(fac, m)
Computes V %*% (Z / d), mapping coordinates in the
rank-k SVD subspace back to the original column space.
Routes through a GPU backend when the factor was computed in
"fast" precision and a device copy of V is available.
svd_reconstruct(factor, Z)svd_reconstruct(factor, Z)
factor |
An |
Z |
Numeric matrix or vector with |
Numeric matrix of dimensions ncol(X) x ncol(Z),
where X is the original source matrix.
m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 2L) coords <- svd_project(fac, m) approx <- svd_reconstruct(fac, coords)m <- matrix(rnorm(30), nrow = 6) A <- adgeMatrix(m) fac <- svd_factor(A, k = 2L) coords <- svd_project(fac, m) approx <- svd_reconstruct(fac, coords)
Compute the singular value decomposition of an adgeMatrix,
dispatching through the amatrix backend. A fallback method for plain
matrix objects is also provided to preserve base R behaviour
after the generic is promoted to S4.
## S4 method for signature 'adgeMatrix' svd(x, nu = min(dim(x)), nv = min(dim(x)), LINPACK = FALSE, ...)## S4 method for signature 'adgeMatrix' svd(x, nu = min(dim(x)), nv = min(dim(x)), LINPACK = FALSE, ...)
x |
An |
nu |
Number of left singular vectors to compute. |
nv |
Number of right singular vectors to compute. |
LINPACK |
Ignored; retained for signature compatibility. |
... |
Further arguments passed to the backend. |
A list with components d (singular values), u
(left singular vectors, nrow(x) by nu), and v
(right singular vectors, ncol(x) by nv).
A <- adgeMatrix(matrix(rnorm(12), 4, 3)) s <- svd(A) length(s$d)A <- adgeMatrix(matrix(rnorm(12), 4, 3)) s <- svd(A) length(s$d)
Compute the singular value decomposition of a sparse
adgCMatrix, dispatching through the amatrix backend.
## S4 method for signature 'adgCMatrix' svd(x, nu = min(dim(x)), nv = min(dim(x)), LINPACK = FALSE, ...)## S4 method for signature 'adgCMatrix' svd(x, nu = min(dim(x)), nv = min(dim(x)), LINPACK = FALSE, ...)
x |
An |
nu |
Number of left singular vectors to compute. |
nv |
Number of right singular vectors to compute. |
LINPACK |
Ignored; retained for signature compatibility. |
... |
Further arguments passed to the backend. |
A list with components d, u, and v.
Returns (x + t(x)) / 2, enforcing exact symmetry. Handles both
dense aMatrix and sparse adgCMatrix inputs.
sym(x)sym(x)
x |
A square matrix or |
A symmetric matrix or aMatrix of the same class and
dimensions as x.
m <- matrix(c(1, 2, 3, 4), 2, 2) sym(m)m <- matrix(c(1, 2, 3, 4), 2, 2) sym(m)
Computes , an n x n weighted
outer cross-product. A GPU-resident fast path is used when available.
tcrossprod_weighted(X, w)tcrossprod_weighted(X, w)
X |
Numeric matrix or |
w |
Positive numeric vector of length |
An adgeMatrix of shape [n, n].
crossprod_weighted, xty_weighted
X <- matrix(rnorm(20), nrow = 5) w <- runif(5) tcrossprod_weighted(X, w)X <- matrix(rnorm(20), nrow = 5) w <- runif(5) tcrossprod_weighted(X, w)
Returns the trace (sum of diagonal elements) of a square matrix or
aMatrix.
trace(x)trace(x)
x |
A square matrix, sparse |
A single numeric scalar equal to the sum of diagonal elements.
trace(diag(1:4))trace(diag(1:4))
Estimates or using
Hutchinson's method with k Rademacher probe vectors. Supply
solve_fn to estimate the trace of an inverse without forming it
explicitly.
trace_estim(A = NULL, k = 30L, seed = NULL, solve_fn = NULL, n = NULL)trace_estim(A = NULL, k = 30L, seed = NULL, solve_fn = NULL, n = NULL)
A |
Square matrix or |
k |
Integer number of Rademacher probe vectors. Default |
seed |
Optional integer random seed for reproducibility. |
solve_fn |
Optional function |
n |
Integer dimension of the matrix; required when |
A single numeric scalar estimate of the trace.
A <- crossprod(matrix(rnorm(25), 5, 5)) + 5 * diag(5) trace_estim(A, k = 50L, seed = 1L)A <- crossprod(matrix(rnorm(25), 5, 5)) + 5 * diag(5) trace_estim(A, k = 50L, seed = 1L)
Temporarily overrides the session-default dispatch policy and/or
precision mode for the duration of code, then restores the
previous values on exit, even when code errors.
with_amatrix(policy = NULL, precision = NULL, code)with_amatrix(policy = NULL, precision = NULL, code)
policy |
Optional temporary policy. Must be one of
|
precision |
Optional temporary precision. Must be either
|
code |
Expression to evaluate under the temporary defaults. |
The result of evaluating code.
adgeMatrix,
amatrix_set_default_policy,
amatrix_set_default_precision
with_amatrix(policy = "auto", precision = "fast", { adgeMatrix(matrix(1:4, nrow = 2)) })with_amatrix(policy = "auto", precision = "fast", { adgeMatrix(matrix(1:4, nrow = 2)) })
Solves the weighted least-squares problem
using either the
normal equations or a QR decomposition of the weight-scaled design.
wls_fit( X, Y, weights, intercept = FALSE, include_fitted = TRUE, include_residuals = TRUE, cache = TRUE, method = c("normal", "qr") )wls_fit( X, Y, weights, intercept = FALSE, include_fitted = TRUE, include_residuals = TRUE, cache = TRUE, method = c("normal", "qr") )
X |
Numeric matrix or |
Y |
Numeric matrix, vector, or |
weights |
Positive numeric vector of length |
intercept |
Logical; when |
include_fitted |
Logical; include fitted values in the result. |
include_residuals |
Logical; include residuals in the result. |
cache |
Logical; cache intermediate factorizations for reuse
across calls sharing the same |
method |
Solver method: |
An object of class "wls_fit", a named list
containing:
adgeMatrix of shape [p, q].
adgeMatrix of shape [n, q],
or NULL when include_fitted = FALSE.
adgeMatrix of shape [n, q], or
NULL when include_residuals = FALSE.
Integer model rank.
Residual degrees of freedom.
X <- matrix(rnorm(50), nrow = 10) y <- rnorm(10) w <- runif(10, 0.5, 2) fit <- wls_fit(X, y, weights = w) coef(fit)X <- matrix(rnorm(50), nrow = 10) y <- rnorm(10) w <- runif(10, 0.5, 2) fit <- wls_fit(X, y, weights = w) coef(fit)
Computes using the matrix determinant lemma
in time, reusing an existing Cholesky factor of
.
woodbury_logdet(A_factor, U, V = NULL, C_inv = NULL)woodbury_logdet(A_factor, U, V = NULL, C_inv = NULL)
A_factor |
An |
U |
Numeric matrix of shape |
V |
Numeric matrix of shape |
C_inv |
Numeric matrix of shape |
A length-1 numeric: .
A <- crossprod(matrix(rnorm(25), 5)) + diag(5) U <- matrix(rnorm(10), 5, 2) ld <- woodbury_logdet(A, U) is.finite(ld)A <- crossprod(matrix(rnorm(25), 5)) + diag(5) U <- matrix(rnorm(10), 5, 2) ld <- woodbury_logdet(A, U) is.finite(ld)
Computes in time using the
Woodbury matrix identity, avoiding an refactorisation of
the updated matrix.
woodbury_solve(A_factor, U, b, V = NULL, C_inv = NULL)woodbury_solve(A_factor, U, b, V = NULL, C_inv = NULL)
A_factor |
An |
U |
Numeric matrix of shape |
b |
Numeric matrix of shape |
V |
Numeric matrix of shape |
C_inv |
Numeric matrix of shape |
Numeric matrix of shape [n, rhs]: the solution
.
A <- crossprod(matrix(rnorm(25), 5)) + diag(5) U <- matrix(rnorm(10), 5, 2) b <- rnorm(5) x <- woodbury_solve(A, U, b) length(x)A <- crossprod(matrix(rnorm(25), 5)) + diag(5) U <- matrix(rnorm(10), 5, 2) b <- rnorm(5) x <- woodbury_solve(A, U, b) length(x)
Computes , a p x k weighted
cross-product between X and response matrix y. A
GPU-resident fast path is used when available.
xty_weighted(X, w, y)xty_weighted(X, w, y)
X |
Numeric matrix or |
w |
Positive numeric vector of length |
y |
Numeric vector or matrix of shape |
An adgeMatrix of shape [p, k].
crossprod_weighted,
tcrossprod_weighted
X <- matrix(rnorm(20), nrow = 5) w <- runif(5) y <- rnorm(5) xty_weighted(X, w, y)X <- matrix(rnorm(20), nrow = 5) w <- runif(5) y <- rnorm(5) xty_weighted(X, w, y)