Compression and allocation#

See FlashTSQR and budget allocation for complete numerical and ownership contracts.

Inference-only LoRA tensor compression; importing does not load PyTorch.

class QualityOption(rank: int, cost: int, loss: float)[source]#

One measured candidate; lower loss is better, cost units are caller-defined.

allocate_quality_budget(curves: Mapping[str, Sequence[QualityOption]], budget: int) → dict[str, int][source]#

Choose one rank per item minimizing summed loss within an integer budget.

Costs may represent bytes or another additive integer resource. Losses must be comparable and additive across items; no monotonicity, interpolation or isotonic fitting is assumed. Ties prefer lower cost then lexicographic ranks in sorted item-name order. Returns ranks; inputs remain unchanged.

Exact sparse multiple-choice knapsack with dominated-state pruning. Runtime and memory depend on the number of reachable costs, so large frontiers can be expensive. No cost rounding or silent approximation is performed.

allocate_spectral_budget(spectra: Mapping[str, Sequence[float]], budget: int, *, min_rank: int = 0) → dict[str, int][source]#

Maximize retained squared singular values under a direction budget.

Inputs are descending nonnegative finite spectra. Ties use module name, then direction index. Returns prefix ranks totaling exactly budget without changing inputs. Zero ranks are allowed; PEFT export requires positive ranks. This objective does not model quality, parameter bytes, or serving latency.

class CompressionInfo(qr: 'ExecutionInfo', eigh_backend: 'str', original_rank: 'int', retained_rank: 'int', padded: 'bool' = False)[source]#
class LoRAResult(a: torch.Tensor, b: torch.Tensor, singular_values: torch.Tensor, info: CompressionInfo)[source]#

FP32 factors, descending singular values, and per-call execution metadata.

a and b preserve the input batching convention. singular_values contains the complete original-rank spectrum, even when factors are truncated. This tensor API represents B @ A; external adapter scaling is unchanged and must still be applied by the caller. Results are detached from autograd.

refactor_lora(a: torch.Tensor, b: torch.Tensor, *, eigh_backend: Literal['auto', 'torch', 'jacobi', 'cpu'] = 'auto') → LoRAResult[source]#

Refactor B @ A into singular-value order, using our GPU TSQR.

Inputs are unmodified 2D factors or same-shape 3D batches. Outputs remain on the input GPU in float32. QR uses the smaller ambient side; h and h @ h.T are formed in FP64 before eigendecomposition. Singular values are split evenly between factors. Numerical null directions below rank * eps64 times the largest Gram eigenvalue are set to zero. No generic QR is substituted.

EVD auto uses torch on CUDA, Jacobi on ROCm for small cores, and CPU FP64 EVD for larger ROCm cores, as in probe. The selected EVD is always reported. Set eigh_backend explicitly to disallow that auto selection. This operation may synchronize with the host and does not support autograd or graph capture.

truncate_lora(a: torch.Tensor, b: torch.Tensor, keep: int, *, pad_to_original_rank: bool = False, eigh_backend: Literal['auto', 'torch', 'jacobi', 'cpu'] = 'auto') → LoRAResult[source]#

Return rank-keep factors, compact by default, with the full spectrum.

keep=0 produces empty rank dimensions. Explicit padding preserves nominal shapes for legacy consumers but does not reduce stored tensor bytes. Inputs follow refactor_lora’s shape, dtype, scaling and device contracts.

QR factorization#

Batched Householder TSQR with owned, reusable factorization state.

class ExecutionInfo(path: str, device: str, apply_mode: str, source_sha256: tuple[tuple[str, str], ...], backend: str = 'FlashTSQR')[source]#

Implementation selected for this factorization, without global state.

class QRFactorization(r, shape, apply, tensors, ready, info)[source]#

Owned QR state for x[batch, rows, columns].

r is [batch, columns, columns]. apply_q(z) evaluates the implicit thin Q times z without materializing Q. Keep r and the private reflector state unmodified. Later factorizations do not invalidate this object. Applications on other streams wait for factorization completion. Native state is immutable and its allocator use is recorded on consumer streams. Callers remain responsible for ordering writes to their input tensors. Autograd and CUDA graph capture are unsupported.

apply_q(z: torch.Tensor) → torch.Tensor[source]#

Apply Q to GPU float32 z[batch, columns, k], for any positive k.

qr_factor(x: torch.Tensor, *, path: Literal['auto', 'full', 'wide'] = 'auto', apply_mode: Literal['serial', 'cooperative'] = 'serial') → QRFactorization[source]#

Factor GPU float32 x[batch, rows >= columns, columns].

Input is not modified. The default selects the shared-memory FlashTSQR kernel, or its global-workspace wide kernel when shared memory cannot fit. A compiler and a matching PyTorch CUDA/ROCm toolkit are required on first use. Compilation uses PyTorch’s extension cache and environment overrides; LoRAForge does not change compiler or architecture environment variables. cooperative is an explicit experimental apply mode for the full path.