diff --git a/.gitignore b/.gitignore index 95731a59..c0405484 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,10 @@ *.jl.cov *.jl.mem /Manifest.toml +/test/Manifest.toml /docs/Manifest.toml /docs/build/ +/docs/src/citing.md +/docs/src/dev/contributing.md +/docs/src/dev/testing.md +/docs/src/index.md diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 393e3914..00000000 --- a/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -# Documentation: http://docs.travis-ci.com/user/languages/julia -language: julia -notifications: - email: false -julia: - - 1.10 - - nightly -os: - - linux -arch: - - x64 -cache: - directories: - - ~/.julia/artifacts -jobs: - fast_finish: true - allow_failures: - - julia: nightly -after_success: - - | - julia -e ' - using Pkg - Pkg.add("Coverage") - using Coverage - Codecov.submit(process_folder())' diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 00000000..1243ac92 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,125 @@ +cff-version: 1.2.0 +message: "If you use NextLA.jl in your research, please cite it as below." +title: "NextLA.jl" +abstract: >- + Hardware-agnostic, datatype-flexible dense linear algebra in pure Julia: + recursive GEMM, TRSM, SYRK, Cholesky and LU, tiled QR kernels, GPU backends + through package extensions, and mixed-precision factorizations. +type: software +license: MIT +repository-code: "https://github.com/NextLinearAlgebra/NextLA.jl" +url: "https://nextlinearalgebra.github.io/NextLA.jl" +keywords: + - julia + - linear algebra + - GPU + - mixed precision + - BLAS + - LAPACK +authors: + - given-names: Rabab + family-names: Alomairy + - given-names: Evelyne + family-names: Ringoot + - given-names: Sophie + family-names: Xuan + - given-names: Vicki + family-names: Carrica + - given-names: Maxwell + family-names: Onyango + - given-names: Julian + family-names: Samaroo + - given-names: Felipe + family-names: Tome +preferred-citation: + type: conference-paper + title: "Synthesizing Numerical Linear Algebra using Julia" + authors: + - given-names: Sophie + family-names: Xuan + - given-names: Evelyne + family-names: Ringoot + - given-names: Rabab + family-names: Alomairy + - given-names: Felipe + family-names: Tome + - given-names: Julian + family-names: Samaroo + - given-names: Alan + family-names: Edelman + collection-title: "2024 IEEE High Performance Extreme Computing Conference (HPEC)" + publisher: + name: IEEE + year: 2024 + url: "https://ieee-hpec.org/wp-content/uploads/2025/01/161.pdf" +references: + - type: conference-paper + title: "Toward Portable GPU Performance: Julia Recursive Implementation of TRMM and TRSM" + authors: + - given-names: Vicki + family-names: Carrica + - given-names: Maxwell + family-names: Onyango + - given-names: Rabab + family-names: Alomairy + - given-names: Evelyne + family-names: Ringoot + - given-names: James + family-names: Schloss + - given-names: Alan + family-names: Edelman + collection-title: "Asynchronous Many-Task Systems and Applications (WAMTA)" + publisher: + name: Springer Nature + year: 2025 + doi: "10.1007/978-3-031-97196-9_13" + - type: conference-paper + title: "Hierarchical Recursive Precision for Accelerating Symmetric Linear Solves on MXUs" + authors: + - given-names: Vicki + family-names: Carrica + - given-names: Rabab + family-names: Alomairy + - given-names: Evelyne + family-names: Ringoot + - given-names: Alan + family-names: Edelman + collection-title: "Euro-Par 2026: Parallel Processing" + publisher: + name: Springer Nature + start: 451 + end: 465 + year: 2026 + doi: "10.1007/978-3-032-35248-4_31" + - type: conference-paper + title: "Performant Unified GPU Kernels for Portable Singular Value Computation Across Hardware and Precision" + authors: + - given-names: Evelyne + family-names: Ringoot + - given-names: Rabab + family-names: Alomairy + - given-names: Valentin + family-names: Churavy + - given-names: Alan + family-names: Edelman + collection-title: "Proceedings of the 54th International Conference on Parallel Processing (ICPP '25)" + publisher: + name: ACM + year: 2025 + doi: "10.1145/3754598.3754667" + - type: conference-paper + title: "Accelerating Bidiagonalization of Banded Matrices through Memory-Aware Bulge-Chasing on GPUs" + authors: + - given-names: Evelyne + family-names: Ringoot + - given-names: Rabab + family-names: Alomairy + - given-names: Alan + family-names: Edelman + collection-title: "ISC High Performance 2026 Research Paper Proceedings (41st International Conference)" + publisher: + name: IEEE + start: 1 + end: 14 + year: 2026 + doi: "10.23919/isc.2026.11520476" diff --git a/CITATION.md b/CITATION.md new file mode 100644 index 00000000..3a19b440 --- /dev/null +++ b/CITATION.md @@ -0,0 +1,103 @@ +# Citing NextLA + +If you use NextLA.jl in your research, please cite: + +> **[1]** S. Xuan, E. Ringoot, R. Alomairy, F. Tome, J. Samaroo, and A. Edelman, "Synthesizing Numerical +> Linear Algebra using Julia," in *2024 IEEE High Performance Extreme Computing Conference (HPEC)*, +> IEEE, 2024. +> +> Available: + +```bibtex +@inproceedings{nextla1, + title={{Synthesizing Numerical Linear Algebra using Julia}}, + author={Xuan, Sophie and Ringoot, Evelyne and Alomairy, Rabab and Tome, Felipe and Samaroo, Julian and Edelman, Alan}, + booktitle={2024 IEEE High Performance Extreme Computing Conference (HPEC)}, + year={2024}, + publisher={IEEE}, + url={https://ieee-hpec.org/wp-content/uploads/2025/01/161.pdf} +} +``` + +Poster, IEEE HPEC 2024: + +[![Synthesizing Numerical Linear Algebra using Julia, poster](docs/src/assets/ieee_hpec_poster.png)](docs/src/assets/ieee_hpec_poster.pdf) + +> **[2]** V. Carrica, M. Onyango, R. Alomairy, E. Ringoot, J. Schloss, and A. Edelman, "Toward Portable +> GPU Performance: Julia Recursive Implementation of TRMM and TRSM," in *Asynchronous Many-Task Systems +> and Applications (WAMTA)*, Springer Nature, 2025. +> +> doi: [10.1007/978-3-031-97196-9_13](https://doi.org/10.1007/978-3-031-97196-9_13) + +```bibtex +@inproceedings{nextla2, + title={{Toward Portable GPU Performance: Julia Recursive Implementation of TRMM and TRSM}}, + author={Carrica, Vicki and Onyango, Maxwell and Alomairy, Rabab and Ringoot, Evelyne and Schloss, James and Edelman, Alan}, + booktitle={Asynchronous Many-Task Systems and Applications (WAMTA)}, + year={2025}, + publisher={Springer Nature}, + doi={10.1007/978-3-031-97196-9_13} +} +``` + +## Related publications + +Work by the NextLA authors on algorithms that NextLA implements. + +> **[3]** V. Carrica, R. Alomairy, E. Ringoot, and A. Edelman, "Hierarchical Recursive Precision for +> Accelerating Symmetric Linear Solves on MXUs," in *Euro-Par 2026: Parallel Processing*, Lecture Notes in +> Computer Science, Springer Nature, 2026, pp. 451–465. +> +> doi: [10.1007/978-3-032-35248-4_31](https://doi.org/10.1007/978-3-032-35248-4_31) +> +> Also available as [arXiv:2601.08082](https://arxiv.org/abs/2601.08082) + +```bibtex +@inproceedings{carrica2026hierarchical, + title={{Hierarchical Recursive Precision for Accelerating Symmetric Linear Solves on MXUs}}, + author={Carrica, Vicki and Alomairy, Rabab and Ringoot, Evelyne and Edelman, Alan}, + booktitle={Euro-Par 2026: Parallel Processing}, + series={Lecture Notes in Computer Science}, + pages={451--465}, + year={2026}, + publisher={Springer Nature}, + doi={10.1007/978-3-032-35248-4_31} +} +``` + +> **[4]** E. Ringoot, R. Alomairy, V. Churavy, and A. Edelman, "Performant Unified GPU Kernels for +> Portable Singular Value Computation Across Hardware and Precision," in *Proceedings of the 54th +> International Conference on Parallel Processing (ICPP '25)*, ACM, 2025. +> +> doi: [10.1145/3754598.3754667](https://doi.org/10.1145/3754598.3754667) + +```bibtex +@inproceedings{ringoot2025performant, + title={{Performant Unified GPU Kernels for Portable Singular Value Computation Across Hardware and Precision}}, + author={Ringoot, Evelyne and Alomairy, Rabab and Churavy, Valentin and Edelman, Alan}, + booktitle={Proceedings of the 54th International Conference on Parallel Processing (ICPP '25)}, + year={2025}, + publisher={ACM}, + doi={10.1145/3754598.3754667} +} +``` + +> **[5]** E. Ringoot, R. Alomairy, and A. Edelman, "Accelerating Bidiagonalization of Banded Matrices +> through Memory-Aware Bulge-Chasing on GPUs," in *ISC High Performance 2026 Research Paper Proceedings +> (41st International Conference)*, IEEE, 2026, pp. 1–14. +> +> doi: [10.23919/isc.2026.11520476](https://doi.org/10.23919/isc.2026.11520476) +> +> Also available as [arXiv:2510.12705](https://arxiv.org/abs/2510.12705) + +```bibtex +@inproceedings{ringoot2026accelerating, + title={{Accelerating Bidiagonalization of Banded Matrices through Memory-Aware Bulge-Chasing on GPUs}}, + author={Ringoot, Evelyne and Alomairy, Rabab and Edelman, Alan}, + booktitle={ISC High Performance 2026 Research Paper Proceedings (41st International Conference)}, + pages={1--14}, + year={2026}, + publisher={IEEE}, + doi={10.23919/isc.2026.11520476} +} +``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..55343497 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,65 @@ +# Contributing + +Contributions are welcome through pull requests on +[GitHub](https://github.com/NextLinearAlgebra/NextLA.jl). + +## Repository layout + +``` +src/ +├── NextLA.jl module entry point, includes every feature +├── streams.jl GPU streams and events (used by TLR compression) +├── dense/ dense matrices in one precision +│ ├── core/ NextLAMatrix.jl (wrapper type routing LinearAlgebra calls to NextLA) +│ ├── blas/ +│ │ ├── gemm/ GEMM: extended, batched, grouped, recursive +│ │ ├── trsm/ TRSM/TRMM kernels, unified_rectrxm!, batched TRSM +│ │ ├── syrk/ SYRK: dispatch, batched, portable kernel, recursive +│ │ └── axpy.jl, gerc.jl (BLAS level 1 and 2) +│ └── lapack/ +│ ├── cholesky/ potrf!, recursive, blocked and batched Cholesky +│ ├── lu/ pivoted LU (lu_pivot.jl), recursive and tiled unpivoted LU +│ ├── qr/ Householder reflectors, tile QR kernels and their PLASMA +│ │ helpers parfb, pamm, pemv (one per file) +│ └── rotations/ Givens rotations +├── mxp/ submodule NextLA.MixedPrecision +│ ├── core/ mxp.jl (module definition), the mixed-precision containers, +│ │ adaptive precision selection and quantization +│ ├── blas/ gemm/, trsm/, syrk/ +│ └── lapack/ cholesky/, lu/ +└── tlr/ submodule NextLA.TileLowRank (tile low-rank matrices) + ├── core/ tlr.jl (module definition), TLRMatrix, CompressedFTLRMatrix, + │ compression/ (adaptive randomized approximation) + ├── blas/ gemm/ (TLR GEMM into dense or compressed results) + └── lapack/ (empty for now) +ext/ +├── NextLACUDAExt.jl + ext/cuda/ cuBLAS / cuSOLVER methods, streams, batched SVD +├── NextLAAMDGPUExt.jl + ext/amdgpu/ rocBLAS / rocSOLVER methods, streams, batched SVD +├── NextLAoneAPIExt.jl + ext/oneapi/ oneMKL methods +└── NextLAMetalExt.jl + ext/metal/ MPS methods +test/ mirrors src/ (dense/, mxp/, tlr/): the test for src/.jl is + test/.jl; shared helpers in test/setup/ +docs/ this documentation (Documenter.jl) +``` + +How to run all or some of the tests, on the CPU or a GPU: [`test/README.md`](test/README.md). + +Each of `dense/`, `mxp/` and `tlr/` has the same three folders: `core/` for the types, data +structures and module definition the rest builds on, `blas/` for BLAS-style routines and `lapack/` +for factorizations and LAPACK-style routines. Each routine-group folder has one entry file named +after the folder (`gemm/gemm.jl`, `trsm/trsm.jl`, `qr/qr.jl`, ...) that includes every other file +in it and nothing else, and `src/NextLA.jl` includes only those entry files. Exports stay in the +file that defines the symbol. + +### Modules + +| Module | Folder | Depends on | Loaded with | +|:------------------------|:------------|:----------------------|:--------------------------------| +| `NextLA` | `src/dense` | nothing in the others | `using NextLA` | +| `NextLA.MixedPrecision` | `src/mxp` | `NextLA` | `using NextLA.MixedPrecision` | +| `NextLA.TileLowRank` | `src/tlr` | `NextLA` | `using NextLA.TileLowRank` | + +`MixedPrecision` and `TileLowRank` are submodules: they live inside `NextLA`, can use anything from it +through `..NextLA`, and are not re-exported by it. The dependency runs one way only. Code in +`src/dense` never refers to a submodule, so `NextLA` builds and works with the `include` line of a +submodule removed. TLR code lives in `src/tlr` and follows the same rule. diff --git a/Project.toml b/Project.toml index 22390ef8..780cf1b7 100644 --- a/Project.toml +++ b/Project.toml @@ -26,10 +26,4 @@ BFloat16s = "0.5, 0.6" KernelAbstractions = "0.9.34" LinearAlgebra = "1" Random = "1" -julia = "1.9" - -[extras] -Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" - -[targets] -test = ["Test"] +julia = "1.10" diff --git a/README.md b/README.md index e7c795f0..8108b22e 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,144 @@ - # NextLA.jl -[![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://nextlinearalgebra.github.io/NextLA.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://nextlinearalgebra.github.io/NextLA.jl/dev/) [![Build Status](https://github.com/NextLinearAlgebra/NextLA.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/NextLinearAlgebra/NextLA.jl/actions/workflows/CI.yml?query=branch%3Amain) -[![Build Status](https://app.travis-ci.com/rabab53/NextLA.jl.svg?branch=main)](https://app.travis-ci.com/rabab53/NextLA.jl) [![Coverage](https://codecov.io/gh/NextLinearAlgebra/NextLA.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/NextLinearAlgebra/NextLA.jl) +**NextLA.jl** is a hardware-agnostic, datatype-flexible **dense linear algebra** library written in pure Julia. +It reimplements LAPACK/BLAS-style routines on top of [KernelAbstractions.jl](https://github.com/JuliaGPU/KernelAbstractions.jl), +so one code path runs on **CPUs and on NVIDIA, AMD, Intel and Apple GPUs**, for `Float64`, `Float32`, `Float16`, +`BFloat16` and complex element types, and adds **mixed-precision** recursive factorizations on top. + +Instead of writing one implementation per data type and per device, as Fortran and C libraries do, +NextLA relies on Julia's multiple dispatch, type inference and LLVM-based compilation to generate +specialized code for each combination. + +![Handout](docs/src/assets/handout.png) + +## Features -**NextLA.jl** is a high-performance, hardware-agnostic, and datatype-flexible **dense linear algebra** package implemented in **Julia**. It provides a unified API for linear algebra operations, enabling users to efficiently execute fundamental matrix computations across **CPUs and GPUs** without sacrificing performance. +- **Unified API.** Implements LAPACK/BLAS subroutines in Julia, avoiding type- and hardware-specific implementations. + Supports `Float64`, `Float32`, `Float16`, complex numbers and other numerical types. +- **Multi-architecture support.** Efficiently runs on CPUs and GPUs, leveraging Julia's LLVM-based compilation: the + same call runs on a `Matrix`, `CuArray`, `ROCArray`, `oneArray` or `MtlArray`. +- **High performance.** Benchmarks show that Julia-based implementations achieve performance on par with or exceeding + LAPACK/CUSOLVER. +- **Mixed precision.** Recursive factorizations on matrices that store each block in its own + precision, from `Float64` down to `Float8_E5M2`. +- **Tile low-rank.** Matrices stored as tiles compressed to low rank by adaptive randomized approximation, with GEMM + between compressed and dense matrices. +- **Future-proof and composable.** Designed for extensibility, allowing new data types and hardware architectures to be + integrated with minimal modifications. -![Handout](handout.png) +## Why Julia for dense linear algebra? -## 🚀 Features +Traditionally, linear algebra libraries have been optimized for Fortran and C, requiring separate implementations for +different hardware and data types. NextLA.jl leverages Julia's multiple dispatch, type inference, and metaprogramming +capabilities to dynamically generate optimized machine code, making it a future-proof alternative. -- **Unified API**: Implements LAPACK/BLAS subroutines in Julia, avoiding type- and hardware-specific implementations. -- **Multi-Architecture Support**: Efficiently runs on **CPUs and GPUs**, leveraging Julia's LLVM-based compilation. -- **High Performance**: Benchmarks show that Julia-based implementations achieve **performance on par with or exceeding LAPACK/CUSOLVER**. -- **Broad Datatype Support**: Supports **Float64, Float32, Float16, complex numbers**, and other numerical types seamlessly. -- **Future-Proof & Composable**: Designed for extensibility, allowing new data types and hardware architectures to be integrated with minimal modifications. +## Installation -## 📌 Why Julia for Dense Linear Algebra? +NextLA is registered in the Julia General registry and is tested on Julia 1.10 and nightly. -Traditionally, linear algebra libraries have been optimized for **Fortran and C**, requiring separate implementations for different hardware and data types. **NextLA.jl** leverages Julia’s **multiple dispatch, type inference, and metaprogramming capabilities** to dynamically generate optimized machine code, making it a future-proof alternative. +```julia +using Pkg +Pkg.add("NextLA") # latest release +Pkg.add(url = "https://github.com/NextLinearAlgebra/NextLA.jl") # development version +``` + +For GPU support, also add the backend package you want (`CUDA`, `AMDGPU`, `oneAPI` or `Metal`). -## 📈 Performance +## Quick start -Benchmarks indicate that **NextLA.jl** achieves performance **comparable to or better than** state-of-art for medium to large problem sizes. Key highlights: +```julia +using NextLA, LinearAlgebra -- **Close to native performance** across different data types. -- **No need for separate CPU/GPU implementations**—a single API works across both. -- **Efficient parallel execution**, taking advantage of Julia's **multi-threading and GPU acceleration**. +n = 1000 +A = rand(n, n) +S = A * A' + n * I # symmetric positive definite +B = rand(n, 5) # five right-hand sides + +# Solve S * X = B: a Cholesky factorization, then two triangular solves +F = copy(S) +potrf_recursive!(F) # S = L * L', L in the lower triangle of F +X = copy(B) +trsm!('L', 'L', 'N', 'N', 1.0, F, X) # solve L * Y = B +trsm!('L', 'L', 'T', 'N', 1.0, F, X) # solve L' * X = Y +S * X ≈ B # true +``` -## 📚 References +### On a GPU -```bibtex -@inproceedings{nextla1, - title={{Synthesizing Numerical Linear Algebra using Julia}}, - author={Xuan, Sophie and Ringoot, Evelyne and Alomairy, Rabab and Tome, Felipe and Samaroo, Julian and Edelman, Alan}, - booktitle={2024 IEEE High Performance Extreme Computing Conference (HPEC)}, - year={2024}, - organization={IEEE} -} +```julia +using NextLA, CUDA, LinearAlgebra -@inproceedings{nextla2, - title={{Toward Portable GPU Performance: Julia Recursive Implementation of TRMM and TRSM}}, - author={Vicki Carrica⋆, Maxwell Onyango⋆, Rabab Alomairy, Evelyne Ringoot, James Schloss, and Alan Edelman}, - booktitle={Asynchronous Many-Task Systems and Applications (WAMTA)}, - year={2025}, - organization={Springer Nature} -} +A = CUDA.rand(Float32, 1000, 1000) +S = A * A' + 1000f0 * I # built on the GPU +F = copy(S) +potrf_recursive!(F) # same call as on the CPU, runs on the GPU +tril(F) * tril(F)' ≈ S # true ``` -## 👥 Contributors - -- **Rabab Alomairy** (@Rabab53) -- **Sophie Xuan** (@Azura-yuwi) -- **Evelyne Ringoot** (@evelyne-ringoot) -- **Vicki Carrica** (@vickicarrica) -- **Maxwell Onyango** (@maxmlewa) -- **Julian Samaroo** (@jpsamaroo) + +For AMD, Intel or Apple GPUs, load `AMDGPU`, `oneAPI` or `Metal` and use `ROCArray`, `oneArray` +or `MtlArray` instead. + +### Mixed precision + +```julia +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +A = rand(1000, 1000) +S = A * A' + 1000I +M = SymmMixedPrec(S, 'L'; precisions = DataType[Float32, Float64]) # off-diagonal block in Float32 +potrf_recursive!(M) # Cholesky directly on the mixed-precision matrix +L = reconstruct_matrix(TriMixedPrec(M)) # back to a dense Float64 factor +norm(L * L' - S) / norm(S) # about 1e-8, set by the Float32 blocks +``` + +See the [documentation](https://nextlinearalgebra.github.io/NextLA.jl/dev/) for the full guide and API reference. + +## Documentation + +The documentation is built with [Documenter.jl](https://documenter.juliadocs.org/). To build it locally: + +```bash +julia --project=docs -e 'using Pkg; Pkg.develop(PackageSpec(path=pwd())); Pkg.instantiate()' +julia --project=docs docs/make.jl +``` + +Then open `docs/build/index.html`. + +## Running the tests + +```bash +julia --project -e 'using Pkg; Pkg.test()' +``` + +This runs every test on the CPU. How to test on a GPU, run only some tests, and the other options: +[test/README.md](test/README.md). + +## Citing + +If you use NextLA.jl in your research, please cite the papers listed in [CITATION.md](CITATION.md) +(BibTeX included). GitHub's "Cite this repository" button uses [CITATION.cff](CITATION.cff). + +## Contributors + +- Rabab Alomairy ([@Rabab53](https://github.com/Rabab53)) +- Sophie Xuan ([@Azura-yuwi](https://github.com/Azura-yuwi)) +- Evelyne Ringoot ([@evelyne-ringoot](https://github.com/evelyne-ringoot)) +- Vicki Carrica ([@vickicarrica](https://github.com/vickicarrica)) +- Maxwell Onyango ([@maxmlewa](https://github.com/maxmlewa)) +- Julian Samaroo ([@jpsamaroo](https://github.com/jpsamaroo)) +- Felipe Tome ([@fda-tome](https://github.com/fda-tome)) +- Abdulmalik Alquwayfili ([@aalquwayfili](https://github.com/aalquwayfili)) +- Akhil Akkapelli ([@AkhilAkkapelli](https://github.com/AkhilAkkapelli)) +- Alessandro Carraro ([@alecarraro](https://github.com/alecarraro)) +- Xavier Henry ([@silentPenguin07](https://github.com/silentPenguin07)) +- Joseph Zhang ([@jz268](https://github.com/jz268)) +- Eric Lin ([@cire694](https://github.com/cire694)) +- Ruhundaka Ejilemele ([@r-ejilemele](https://github.com/r-ejilemele)) + +## License + +MIT, see [LICENSE](LICENSE). diff --git a/docs/Project.toml b/docs/Project.toml index 1ec50b00..de5d9abd 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -1,3 +1,9 @@ [deps] -NextLA = "d37ed344-79c4-486d-9307-6d11355a15a3" Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" +NextLA = "d37ed344-79c4-486d-9307-6d11355a15a3" + +[sources] +NextLA = {path = "/home/akhil/NEXTLA/NextLA.jl"} + +[compat] +Documenter = "1" diff --git a/docs/make.jl b/docs/make.jl index cea3ea95..51ea8e7d 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -1,24 +1,160 @@ using NextLA +using NextLA.MixedPrecision using Documenter DocMeta.setdocmeta!(NextLA, :DocTestSetup, :(using NextLA); recursive=true) +# Edit links and source links need the git remote. When the docs are built from a +# checkout without .git (e.g. an unpacked archive), turn them off rather than fail. +const IN_GIT = isdir(joinpath(@__DIR__, "..", ".git")) +const REMOTE_KW = IN_GIT ? (; repo=Remotes.GitHub("NextLinearAlgebra", "NextLA.jl")) : (; remotes=nothing) + +# Some pages live at the repository root so they also read on GitHub. Copy them into +# the site at build time (the copies are git-ignored), adapting what only works on GitHub: +# - links between root files point to the matching site page, links into docs/src +# become relative site links, and files that are not part of the site +# (CITATION.cff, LICENSE) point to GitHub; +# - Julia's Markdown parser has no task lists, so checkboxes become ✅ and ⬜; +# - GitHub's "> [!NOTE]" box becomes a Documenter note admonition; +# - "Edit on GitHub" opens the root file, not the generated copy. +# README.md becomes the Home page (index.md): see home_page below. +const ROOT_PAGES = [ + "README.md" => "index.md", + "CITATION.md" => "citing.md", + "CONTRIBUTING.md" => "dev/contributing.md", + "test/README.md" => "dev/testing.md", +] +const GITHUB_BLOB = "https://github.com/NextLinearAlgebra/NextLA.jl/blob/main/" +github_note(block) = "!!! note\n" * + join((" " * replace(l, r"^> ?" => "") for l in split(chomp(block), "\n")[2:end]), "\n") * "\n" +# Headings get an anchor prefixed with the page name (home-installation, ...), so a +# root page's "Installation" or "Mixed precision" never clashes with a manual heading. +# Lines inside code fences are left alone; a fence closes only on a backtick run at least +# as long as the one that opened it, so ```` blocks may contain ``` lines. +function prefixed_headings(text, prefix) + fence = "" + lines = map(split(text, "\n")) do l + f = match(r"^(`{3,})(.*)$", l) + if f !== nothing + if isempty(fence) + fence = f.captures[1] + elseif length(f.captures[1]) >= length(fence) && isempty(strip(f.captures[2])) + fence = "" + end + return l + end + m = match(r"^(#{1,6}) (.+)$", l) + (!isempty(fence) || m === nothing) && return l + slug = strip(replace(lowercase(m.captures[2]), r"[^a-z0-9]+" => "-"), '-') + return "$(m.captures[1]) [$(m.captures[2])](@id $prefix-$slug)" + end + return join(lines, "\n") +end +# The README speaks to someone on GitHub; on the Home page leave out what only makes +# sense there (the badges, the docs link, how to build the docs and run the tests). +const README_ONLY_SECTIONS = ["Documentation", "Running the tests"] +function home_page(text) + text = replace(text, r"^\[!\[.*\n"m => "") + text = replace(text, r"\n{3,}" => "\n\n") + text = replace(text, r"^See the \[documentation\]\(https://nextlinearalgebra\.github\.io/[^)]*\).*\n"m => + "Continue with [Getting started](@ref), or go to the [API reference](@ref \"Matrix multiply (GEMM)\").\n") + for section in README_ONLY_SECTIONS + text = replace(text, Regex("^## \\Q$section\\E\\n(?:(?!## ).*\\n)*", "m") => "") + end + return rstrip(text) * "\n" +end +for (from, to) in ROOT_PAGES + text = read(joinpath(@__DIR__, "..", from), String) + to == "index.md" && (text = home_page(text)) + text = prefixed_headings(text, to == "index.md" ? "home" : splitext(basename(to))[1]) + text = replace(text, r"^> \[!NOTE\]\n(?:>.*(?:\n|$))+"m => github_note) + up = "../"^count(==('/'), to) # from the page's folder back to docs/src + text = replace(text, + r"^- \[x\] "m => "- ✅ ", + r"^- \[ \] "m => "- ⬜ ", + "](docs/src/" => "](" * up, + "](README.md)" => "](" * up * "index.md)", + "](CITATION.md)" => "](" * up * "citing.md)", + "](CONTRIBUTING.md)" => "](" * up * "dev/contributing.md)", + "](test/README.md)" => "](" * up * "dev/testing.md)", + "](" * GITHUB_BLOB * "test/README.md)" => "](" * up * "dev/testing.md)", + "](CITATION.cff)" => "](" * GITHUB_BLOB * "CITATION.cff)", + "](LICENSE)" => "](" * GITHUB_BLOB * "LICENSE)", + ) + dest = joinpath(@__DIR__, "src", to) + edit = relpath(joinpath(@__DIR__, "..", from), dirname(dest)) + meta = (to == "index.md" ? "CurrentModule = NextLA\n" : "") * "EditURL = \"$edit\"\n" + write(dest, "```@meta\n" * meta * "```\n\n" * text) +end + +# Local switches (CI sets neither): NEXTLA_DOCS_BUILDDIR builds into another folder, so a +# served docs/build stays complete until the new build is copied over it; NEXTLA_DOCS_DOCTEST=false +# skips the doctests for a quick preview. makedocs(; - modules=[NextLA], - authors="Rabab Alomairy", + build=get(ENV, "NEXTLA_DOCS_BUILDDIR", "build"), + doctest=get(ENV, "NEXTLA_DOCS_DOCTEST", "true") != "false", + modules=[NextLA, NextLA.MixedPrecision], + authors="Rabab Alomairy, Evelyne Ringoot, Sophie Xuan, Vicki Carrica, Maxwell Onyango, Julian Samaroo, Felipe Tome and contributors", sitename="NextLA.jl", + REMOTE_KW..., format=Documenter.HTML(; + prettyurls=get(ENV, "CI", "false") == "true", canonical="https://nextlinearalgebra.github.io/NextLA.jl", + repolink="https://github.com/NextLinearAlgebra/NextLA.jl", edit_link="main", - assets=String[], + assets=["assets/bibtex.css"], + size_threshold=300 * 1024, + size_threshold_warn=200 * 1024, ), + # Every exported, documented name must appear somewhere in the manual. + checkdocs=:exports, pages=[ "Home" => "index.md", - "Mixed precision" => "mixed_precision.md", + "Getting started" => "getting_started.md", + "Manual" => [ + "Backends and GPUs" => "manual/backends.md", + "Mixed precision" => "manual/mixed_precision.md", + "Tile low-rank" => "manual/tile_low_rank.md", + "Benchmarks" => "manual/benchmarks.md", + ], + # Mirrors src/: dense/{core,blas,lapack}, mxp/{core,blas,lapack}, tlr/{core,blas}. + "API reference" => [ + "Dense" => [ + "Core" => "api/dense/core.md", + "BLAS" => [ + "GEMM" => "api/dense/blas/gemm.md", + "TRSM and TRMM" => "api/dense/blas/trsm.md", + "SYRK" => "api/dense/blas/syrk.md", + "AXPY and GERC" => "api/dense/blas/axpy_gerc.md", + ], + "LAPACK" => [ + "Cholesky" => "api/dense/lapack/cholesky.md", + "LU" => "api/dense/lapack/lu.md", + "QR" => "api/dense/lapack/qr.md", + "Rotations" => "api/dense/lapack/rotations.md", + ], + ], + "Mixed precision" => [ + "Core" => "api/mxp/core.md", + "BLAS" => "api/mxp/blas.md", + "LAPACK" => "api/mxp/lapack.md", + ], + "Tile low-rank" => [ + "Core" => "api/tlr/core.md", + "BLAS" => "api/tlr/blas.md", + ], + ], + "Developer documentation" => [ + "Contributing" => "dev/contributing.md", + "Running the tests" => "dev/testing.md", + "NextLA TODO" => "dev/todo.md", + ], + "Citing NextLA" => "citing.md", ], ) deploydocs(; repo="github.com/NextLinearAlgebra/NextLA.jl", devbranch="main", + push_preview=true, ) diff --git a/docs/src/api/dense/blas/axpy_gerc.md b/docs/src/api/dense/blas/axpy_gerc.md new file mode 100644 index 00000000..378182d9 --- /dev/null +++ b/docs/src/api/dense/blas/axpy_gerc.md @@ -0,0 +1,81 @@ +```@meta +CurrentModule = NextLA +``` + +# AXPY and GERC + +Level 1 and 2 BLAS routines in `src/dense/blas`. + +```@autodocs +Modules = [NextLA] +Pages = ["axpy.jl", "gerc.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Each example stands on its own and ends with a check that prints `true`. `axpy!` and `gerc!` +are not exported, so they are called as `NextLA.axpy!` and `NextLA.gerc!`. + +### `axpy!` on long vectors + +`NextLA.axpy!(alpha, x, y)` overwrites `y` with `alpha * x + y`; `alpha` must have the element +type of `x` and `y` (`2.0`, not `2`, for `Float64` vectors). + +```jldoctest +using NextLA + +x = rand(4096) +y = rand(4096) +y0 = copy(y) + +NextLA.axpy!(2.0, x, y) # y = 2.0 * x + y +y ≈ 2.0 * x + y0 + +# output + +true +``` + +### Complex rank-1 update with `gerc!` + +`gerc!` adds `alpha * x * y'` to a rectangular matrix, with `y` conjugated. + +```jldoctest +using NextLA + +m, n = 2048, 1024 +x = rand(ComplexF64, m) +y = rand(ComplexF64, n) +A = rand(ComplexF64, m, n) +A0 = copy(A) + +alpha = 0.5 - 1.0im +NextLA.gerc!(alpha, x, y, A) # A = A + alpha * x * y' +A ≈ A0 + alpha * x * y' + +# output + +true +``` + +### On the GPU + +`axpy!` and `gerc!` are written with broadcasts, so they run on GPU arrays unchanged (this block +is not run when the documentation is built). + +```julia +using CUDA, NextLA + +x = CUDA.rand(Float64, 2^20) +y = CUDA.rand(Float64, 2^20) +y0 = copy(y) +NextLA.axpy!(2.0, x, y) + +u = CUDA.rand(ComplexF32, 4096) +v = CUDA.rand(ComplexF32, 4096) +A = CUDA.zeros(ComplexF32, 4096, 4096) +NextLA.gerc!(1.0f0 + 0.0f0im, u, v, A) + +Array(y) ≈ 2.0 * Array(x) + Array(y0) && Array(A) ≈ Array(u) * Array(v)' # true +``` diff --git a/docs/src/api/dense/blas/gemm.md b/docs/src/api/dense/blas/gemm.md new file mode 100644 index 00000000..751ba5ff --- /dev/null +++ b/docs/src/api/dense/blas/gemm.md @@ -0,0 +1,172 @@ +```@meta +CurrentModule = NextLA +``` + +# Matrix multiply (GEMM) + +`C := α op(A) op(B) + β C` in several forms: + +- [`gemm!`](@ref) — the dense entry point, in output-first (`gemm!(C, A, B; alpha, beta)`) or BLAS + (`gemm!(transA, transB, alpha, A, B, beta, C)`) argument order. +- [`gemmEx!`](@ref) — storage and accumulation types chosen separately. +- [`gemm_batched!`](@ref) and [`gemmEx_batched!`](@ref) — many independent products in one call, + from a vector of matrices or a 3-D strided array. +- Grouped GEMM — batches of products with different shapes. +- [`recgemm!`](@ref) — recursive GEMM; its mixed-precision method is documented under + [Mixed-precision BLAS](@ref). +- [`GEMM_ADD!`](@ref) / [`GEMM_SUB!`](@ref) — the tiled KernelAbstractions kernel. + +## Dense and extended GEMM + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("gemm", "gemmEx.jl"), joinpath("gemm", "recgemm.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Compute types and alignment + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("gemm", "gemm_types.jl"), joinpath("gemm", "gemm_precision.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Batched GEMM + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("gemm", "gemm_batched.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Grouped GEMM + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("gemm", "gemm_grouped.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Tiled kernel + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("gemm", "matmul.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Both argument orders of [`gemm!`](@ref) make the same update; the BLAS order takes the transposes +as flags, the output-first order as `transpose`/`adjoint` wrappers. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(2048, 1024) +B = rand(2048, 1024) +C1 = rand(1024, 1024) +C0 = copy(C1) +C2 = copy(C1) + +gemm!('T', 'N', 2.0, A, B, 1.0, C1) # BLAS order: C1 = 2 Aᵀ B + C1 +gemm!(C2, transpose(A), B; alpha = 2.0, beta = 1.0) # output first, same update +C1 ≈ C2 ≈ 2.0 * transpose(A) * B + C0 + +# output + +true +``` + +[`gemmEx!`](@ref) multiplies `Float16` matrices with a `Float32` accumulation and rounds once on +store; [`recgemm!`](@ref) picks that accumulation by itself. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(Float16, 2048, 2048) +B = rand(Float16, 2048, 2048) +C1 = zeros(Float16, 2048, 2048) +C2 = zeros(Float16, 2048, 2048) + +gemmEx!('N', 'N', 1.0, A, B, 0.0, C1; compute_type = Float32) # accumulate in Float32 +recgemm!(1.0, A, B, 0.0, C2) # chooses Float32 by itself +C1 ≈ C2 && isapprox(C1, Float64.(A) * Float64.(B); rtol = 1e-3) + +# output + +true +``` + +[`gemm_batched!`](@ref) takes a 3-D strided batch, where an operand with batch count 1 is shared +by every member, or a vector of matrices. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(1024, 1024, 8) +B = rand(1024, 1024, 1) # batch count 1: one B shared by every member +C = zeros(1024, 1024, 8) +gemm_batched!('N', 'N', 1.0, A, B, 0.0, C) + +As = [rand(1024, 1024) for _ in 1:4] +Bs = [rand(1024, 1024) for _ in 1:4] +Cs = [zeros(1024, 1024) for _ in 1:4] +gemm_batched!('N', 'T', 1.0, As, Bs, 0.0, Cs) + +all(C[:, :, i] ≈ A[:, :, i] * B[:, :, 1] for i in 1:8) && + all(Cs[i] ≈ As[i] * transpose(Bs[i]) for i in 1:4) + +# output + +true +``` + +Grouped GEMM runs products of different shapes in one call, described by +[`GroupedGemmTask`](@ref)s (a loop on the CPU, one grouped call on CUDA). + +```jldoctest +using NextLA, LinearAlgebra + +shapes = [(1024, 2048, 512), (2048, 1024, 1024), (4096, 512, 1024)] # (m, n, k) per member +tasks = [NextLA.GroupedGemmTask('N', 'N', 1.0, rand(m, k), rand(k, n), 0.0, zeros(m, n)) + for (m, n, k) in shapes] + +NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float64}()) +all(t.C ≈ t.A * t.B for t in tasks) + +# output + +true +``` + +On the GPU the same calls reach cuBLAS: GEMMEx for mixed precision, one strided-batched call for a +3-D batch, and the TF32 tensor cores through [`TF32`](@ref) (CUDA only). This block is not run when +the documentation is built. + +```julia +using NextLA, CUDA + +# Float16 storage, Float32 accumulation: one cuBLAS GEMMEx call +A = CUDA.rand(Float16, 4096, 4096) +B = CUDA.rand(Float16, 4096, 4096) +C = CUDA.zeros(Float16, 4096, 4096) +gemmEx!('N', 'N', 1f0, A, B, 0f0, C; compute_type = Float32) + +# a 3-D strided batch: one cuBLAS strided-batched call +Ab = CUDA.rand(Float32, 1024, 1024, 16) +Bb = CUDA.rand(Float32, 1024, 1024, 16) +Cb = CUDA.zeros(Float32, 1024, 1024, 16) +gemm_batched!('N', 'N', 1f0, Ab, Bb, 0f0, Cb) + +# Float32 operands on the TF32 tensor cores (CUDA only) +X = CUDA.rand(Float32, 4096, 4096) +Y = CUDA.rand(Float32, 4096, 4096) +Z = CUDA.zeros(Float32, 4096, 4096) +NextLA.precision_gemm!('N', 'N', 1f0, X, Y, 0f0, Z, TF32()) + +isapprox(C, Float32.(A) * Float32.(B); rtol = 1e-3) && + Cb[:, :, 16] ≈ Ab[:, :, 16] * Bb[:, :, 16] && + isapprox(Z, X * Y; rtol = 1e-2) +``` diff --git a/docs/src/api/dense/blas/syrk.md b/docs/src/api/dense/blas/syrk.md new file mode 100644 index 00000000..b3525aba --- /dev/null +++ b/docs/src/api/dense/blas/syrk.md @@ -0,0 +1,100 @@ +```@meta +CurrentModule = NextLA +``` + +# Symmetric rank-k update (SYRK) + +`C := α op(A) op(A)ᵀ + β C` on one triangle of `C`. + +- [`syrk!`](@ref) — BLAS on the CPU, vendor SYRK on GPUs. +- [`syrk_batched!`](@ref) — many independent updates. +- [`SYRK_KERNEL!`](@ref) — a portable tiled KernelAbstractions SYRK for backends or element types + no vendor library covers (e.g. `Float16`). +- [`recsyrk!`](@ref) — recursive SYRK; its mixed-precision method is under + [Mixed-precision BLAS](@ref). + +```@autodocs +Modules = [NextLA] +Pages = [ + joinpath("syrk", "syrk_dispatch.jl"), + joinpath("syrk", "syrk_batched.jl"), + joinpath("syrk", "syrk_kernel.jl"), + joinpath("syrk", "recsyrk.jl"), +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +With `trans = 'T'` and `beta = 1`, [`syrk!`](@ref) adds `AᵀA` into the chosen triangle of an +existing `C` and leaves the other triangle exactly as it was. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(4096, 2048) +C = rand(2048, 2048) +C0 = copy(C) + +syrk!('U', 'T', 1.0, A, 1.0, C) # upper triangle: C += Aᵀ A +UpperTriangular(C) ≈ UpperTriangular(transpose(A) * A + C0) && tril(C, -1) == tril(C0, -1) + +# output + +true +``` + +[`recsyrk!`](@ref) gives the same triangle as [`syrk!`](@ref), and `Symmetric` turns that triangle +into the full product without copying. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(2048, 1024) +C1 = zeros(2048, 2048) +C2 = zeros(2048, 2048) + +syrk!('L', 'N', 1.0, A, 0.0, C1) +recsyrk!(1.0, A, 0.0, C2) # same update, blocked recursively +LowerTriangular(C1) ≈ LowerTriangular(C2) && Symmetric(C1, :L) ≈ A * A' + +# output + +true +``` + +[`recsyrk!`](@ref) also takes `Float16` storage with a `Float32` result, accumulating in `Float32` +where BLAS has no half-precision SYRK. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(Float16, 2048, 1024) +C = zeros(Float32, 2048, 2048) + +recsyrk!(1.0, A, 0.0, C) # lower triangle +isapprox(LowerTriangular(C), LowerTriangular(Float64.(A) * Float64.(A)'); rtol = 1e-4) + +# output + +true +``` + +On the GPU, [`syrk!`](@ref) calls cuBLAS SYRK, and [`recsyrk!`](@ref) covers `Float16`, which +cuBLAS SYRK does not. This block is not run when the documentation is built. + +```julia +using NextLA, CUDA, LinearAlgebra + +A = CUDA.rand(Float32, 4096, 2048) +C = CUDA.zeros(Float32, 4096, 4096) +syrk!('L', 'N', 1f0, A, 0f0, C) # cuBLAS SYRK + +# cuBLAS has no Float16 SYRK; recsyrk! accumulates in Float32 through GEMMEx +A16 = CUDA.rand(Float16, 4096, 2048) +C32 = CUDA.zeros(Float32, 4096, 4096) +recsyrk!(1f0, A16, 0f0, C32) + +isapprox(tril(C), tril(A * A'); rtol = 1e-4) && + isapprox(tril(C32), tril(Float32.(A16) * Float32.(A16)'); rtol = 1e-4) +``` diff --git a/docs/src/api/dense/blas/trsm.md b/docs/src/api/dense/blas/trsm.md new file mode 100644 index 00000000..1ed308a9 --- /dev/null +++ b/docs/src/api/dense/blas/trsm.md @@ -0,0 +1,133 @@ +```@meta +CurrentModule = NextLA +``` + +# Triangular solve and multiply + +- [`trsm!`](@ref) — triangular solve in BLAS argument order, `op(A) X = α B` or `X op(A) = α B`. +- [`trmm!`](@ref) — triangular multiply in BLAS argument order. +- [`unified_rectrxm!`](@ref) — the recursive engine behind both, selected with `func = 'S'` + (solve) or `'M'` (multiply). Its mixed-precision method is under [Mixed-precision BLAS](@ref). +- [`trsm_batched!`](@ref) — many independent solves. +- `LeftLowerTRSM!`, `RightUpperTRMM!`, ... — the KernelAbstractions base-case kernels. + +## Recursive TRSM / TRMM + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("trsm", "rectrxm.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## BLAS-style entry points and kernels + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("trsm", "trsm_kernels.jl"), joinpath("trsm", "trmm.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Batched TRSM + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("trsm", "trsm_batched.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +### Right-side solve with the conjugate transpose + +`side = 'R'` with `transa = 'C'` solves `X * U' = α B` for a complex upper triangle `U`. + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +A = rand(ComplexF64, n, n) + n * I +B = rand(ComplexF64, 512, n) + +X = trsm!('R', 'U', 'C', 'N', 0.5, A, copy(B)) # X * U' = 0.5 * B +X * UpperTriangular(A)' ≈ 0.5 * B + +# output + +true +``` + +### Unit diagonal + +With `diag = 'U'` the stored diagonal is never read, so here it holds `NaN`; small off-diagonal +entries keep the unit triangle well conditioned. + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +A = rand(n, n) / n +A[diagind(A)] .= NaN +B = rand(n, 256) + +X = trsm!('L', 'L', 'T', 'U', 1.0, A, copy(B)) # transpose(L) * X = B, L unit lower +transpose(UnitLowerTriangular(A)) * X ≈ B + +# output + +true +``` + +### Multiply into a separate output + +The eight-argument [`trmm!`](@ref) writes `alpha * op(A) * B` into `C` and leaves `B` unchanged. + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +A = rand(n, n) +B = rand(n, 256) +C = similar(B) + +trmm!('L', 'U', 'N', 'N', 1.0, A, B, C) # C = U * B +C ≈ UpperTriangular(A) * B + +# output + +true +``` + +### Batched solve over a vector of matrices + +[`trsm_batched!`](@ref) also takes vectors of matrices, and an optional `alpha` last. + +```jldoctest +using NextLA, LinearAlgebra + +n = 1024 +A = [rand(n, n) + n * I for _ in 1:4] +B = [rand(n, 128) for _ in 1:4] + +X = trsm_batched!('L', 'U', 'N', 'N', A, deepcopy(B), 2.0) +all(UpperTriangular(A[k]) * X[k] ≈ 2 * B[k] for k in 1:4) + +# output + +true +``` + +### On the GPU + +The same calls on `CuArray`s reach cuBLAS `trsm!` and `trmm!` (not run when the documentation is built). + +```julia +using NextLA, LinearAlgebra, CUDA + +n = 4096 +A = CUDA.rand(Float32, n, n) + n * I +B = CUDA.rand(Float32, n, 512) + +X = trsm!('L', 'L', 'N', 'N', 1.0f0, A, copy(B)) # solve L * X = B +C = trmm!('L', 'L', 'N', 'N', 1.0f0, A, copy(X)) # multiply back: C = L * X +C ≈ B # true +``` diff --git a/docs/src/api/dense/core.md b/docs/src/api/dense/core.md new file mode 100644 index 00000000..efd94d1a --- /dev/null +++ b/docs/src/api/dense/core.md @@ -0,0 +1,64 @@ +```@meta +CurrentModule = NextLA +``` + +# Dense core + +Types and helpers in `src/dense/core` that the rest of NextLA builds on. + +## `NextLAMatrix` + +`NextLAMatrix{T}(data::Matrix{T})` wraps a dense matrix so that `LinearAlgebra.lu!` on it runs +NextLA's own pivoted LU ([`getrf2!`](@ref)) and `LinearAlgebra.BLAS.axpy!` runs NextLA's `axpy!`. +The other `LinearAlgebra.BLAS` calls on it (`gemv!`, `gemm!`, `trmm!`, `trsm!`, `syrk!`, `herk!`, +`syr2k!`, `her2k!`) pass the wrapped matrix to the system BLAS. + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(1024, 1024) +F = lu!(NextLAMatrix{Float64}(copy(A))) # NextLA's getrf, with partial pivoting +F.L * F.U ≈ A[F.p, :] + +# output + +true +``` + +```@autodocs +Modules = [NextLA] +Pages = ["NextLAMatrix.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Machine parameters + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("src", "NextLA.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +The example stands on its own and ends with a check that prints `true`. + +### Solving a system through `NextLAMatrix` + +`lu!` on a `NextLAMatrix` returns an ordinary `LinearAlgebra.LU`, so `\` solves with it. + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +A = rand(n, n) +B = rand(n, 256) + +F = lu!(NextLAMatrix{Float64}(copy(A))) # NextLA's getrf, with partial pivoting +X = F \ B +A * X ≈ B + +# output + +true +``` diff --git a/docs/src/api/dense/lapack/cholesky.md b/docs/src/api/dense/lapack/cholesky.md new file mode 100644 index 00000000..10c8e547 --- /dev/null +++ b/docs/src/api/dense/lapack/cholesky.md @@ -0,0 +1,129 @@ +```@meta +CurrentModule = NextLA +``` + +# Cholesky + +Factorizations `A = L Lᵀ` or `A = Uᵀ U` of symmetric positive definite matrices. + +| Routine | Algorithm | +|:-------------------------------|:-----------------------------------------------------------| +| [`potrf!`](@ref) | single call to LAPACK / the vendor solver | +| [`potrf_recursive!`](@ref) | recursive 2×2 blocking over `potrf!`, TRSM and SYRK | +| [`potrf_batched!`](@ref) | many independent matrices | +| [`cholesky_blocked!`](@ref) | blocked KernelAbstractions factorization | +| [`cholesky_lower!`](@ref) | single-kernel KernelAbstractions factorization | + +The mixed-precision method of `potrf_recursive!` for `SymmMixedPrec` is under +[Mixed-precision LAPACK](@ref). + +## Factorizations + +```@autodocs +Modules = [NextLA] +Pages = [ + joinpath("cholesky", "potrf.jl"), + joinpath("cholesky", "recpotrf.jl"), + joinpath("cholesky", "potrf_batched.jl"), + joinpath("cholesky", "potrf_blocked.jl"), + joinpath("cholesky", "potrf_kernel.jl"), + joinpath("cholesky", "potrf_register.jl"), +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +### Solve `S * X = B` + +Factor `S = L * Lᵀ` with [`potrf!`](@ref), then solve with `L` and `Lᵀ` using two calls to +[`trsm!`](@ref). + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +M = rand(n, n) +S = M * M' + n * I +B = rand(n, 256) + +F, info = potrf!('L', copy(S)) # S = L * L' +X = copy(B) +trsm!('L', 'L', 'N', 'N', 1.0, F, X) # L * Y = B +trsm!('L', 'L', 'T', 'N', 1.0, F, X) # L' * X = Y +S * X ≈ B + +# output + +true +``` + +### Upper factor + +With `uplo = 'U'`, [`potrf_recursive!`](@ref) writes `U` with `S = Uᵀ * U` and leaves the +strict lower triangle as it was. + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +M = rand(n, n) +S = M * M' + n * I + +F = potrf_recursive!(copy(S), 512; uplo = 'U') # block_size 512 +U = UpperTriangular(F) +U' * U ≈ S && tril(F, -1) == tril(S, -1) + +# output + +true +``` + +### Matrices that are not positive definite + +[`potrf!`](@ref) reports the order of the first leading minor that is not positive definite +through `info`; [`potrf_recursive!`](@ref) throws `PosDefException` with the same order. + +```jldoctest +using NextLA, LinearAlgebra + +n = 1024 +M = rand(n, n) +S = M * M' + n * I +S[700, 700] = -1.0 # leading minor of order 700 is indefinite + +_, info = potrf!('L', copy(S)) +err = try + potrf_recursive!(copy(S), 256) +catch e + e +end +info == 700 && err == PosDefException(700) + +# output + +true +``` + +### On the GPU + +On a `CuArray`, [`potrf!`](@ref) calls cuSOLVER, [`potrf_recursive!`](@ref) stays on the +device, and [`cholesky_blocked!`](@ref) runs its own kernels (not run when the documentation is +built). + +```julia +using NextLA, LinearAlgebra, CUDA + +n = 4096 +M = CUDA.rand(Float64, n, n) +S = M * M' + n * I +B = CUDA.rand(Float64, n, 256) + +F, info = potrf!('L', copy(S)) +F2 = potrf_recursive!(copy(S), 1024) +F3 = cholesky_blocked!(copy(S)) + +X = trsm!('L', 'L', 'N', 'N', 1.0, F, copy(B)) +trsm!('L', 'L', 'T', 'N', 1.0, F, X) +info == 0 && tril(F2) ≈ tril(F) && tril(F3) ≈ tril(F) && S * X ≈ B # true +``` diff --git a/docs/src/api/dense/lapack/lu.md b/docs/src/api/dense/lapack/lu.md new file mode 100644 index 00000000..fd5c4b83 --- /dev/null +++ b/docs/src/api/dense/lapack/lu.md @@ -0,0 +1,158 @@ +```@meta +CurrentModule = NextLA +``` + +# LU + +| Routine | Pivoting | Notes | +|:---------------------------------------|:----------|:-------------------------------------------------| +| `LinearAlgebra.lu!(::NextLAMatrix)` | partial or complete | Julia implementation of LAPACK `getrf` | +| [`getrf2!`](@ref) | partial | recursive LAPACK `getrf2` | +| [`lu_recursive!`](@ref) | none | recursive, square matrices | +| [`lu_recursive_nopiv!`](@ref) | none | recursive, any shape | +| [`lu_base!`](@ref) | none | single-workgroup kernel for one block | +| [`tile_lu_factor!`](@ref) | none | tiled driver over `lu_base!` | + +!!! warning + The unpivoted routines require a matrix that needs no pivoting, e.g. a diagonally dominant + one. A zero pivot throws `ZeroPivotException`; small pivots are not checked. + +The mixed-precision method of `lu_recursive!` for `FullMixedPrec` is under +[Mixed-precision LAPACK](@ref). + +## Pivoted LU (LAPACK style) + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("lu", "lu_pivot.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Recursive and tiled LU + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("lu", "reclu.jl"), joinpath("lu", "lu_base.jl"), joinpath("lu", "lu_tiled.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Each example stands on its own and ends with a check that prints `true`. + +Pivoted LU of a `NextLAMatrix`, then a solve with several right-hand sides through the returned +`LinearAlgebra.LU` object: + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(2048, 2048) +B = rand(2048, 16) + +F = lu!(NextLAMatrix{Float64}(copy(A))) # partial pivoting, computed by getrf2! +X = F \ B +A * X ≈ B + +# output + +true +``` + +[`getrf2!`](@ref) called directly returns LAPACK's pivot vector; `laswp` applies those row +interchanges to the right-hand side before the two triangular solves: + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +A = rand(n, n) +b = rand(n, 1) + +F = copy(A) +ipiv = zeros(Int, n) +_, _, info = getrf2!(F, ipiv, 0) + +x = copy(b) +laswp(x, 1, n, ipiv, 1) # x := P * b +x = UpperTriangular(F) \ (UnitLowerTriangular(F) \ x) +info == 0 && A * x ≈ b + +# output + +true +``` + +Complete pivoting with [`getc2!`](@ref), which permutes both rows and columns, +`A[p, q] = L * U`: + +```jldoctest +using NextLA, LinearAlgebra + +A = rand(1024, 1024) +F = getc2!(NextLAMatrix{Float64}(copy(A)), CompletePivoting()) + +p = LinearAlgebra.LU(F.factors, F.ipiv, 0).p # row permutation from ipiv +q = LinearAlgebra.LU(F.factors, F.jpiv, 0).p # column permutation from jpiv +UnitLowerTriangular(F.factors) * UpperTriangular(F.factors) ≈ A[p, q] + +# output + +true +``` + +Unpivoted recursive LU of a diagonally dominant matrix, with leaves of at most 512 rows, used to +solve a system: + +```jldoctest +using NextLA, LinearAlgebra + +n = 4096 +A = rand(n, n) + n * I # diagonally dominant: no pivoting needed +F = lu_recursive!(copy(A), 512) + +b = rand(n) +x = UpperTriangular(F) \ (UnitLowerTriangular(F) \ b) +A * x ≈ b + +# output + +true +``` + +[`lu_recursive_nopiv!`](@ref) factors a tall panel, here 4096 by 1024; `L` is unit lower +trapezoidal and `U` square: + +```jldoctest +using NextLA, LinearAlgebra + +m, n = 4096, 1024 +A = rand(m, n) +A[1:n, :] += m * I # needs no pivoting + +F = lu_recursive_nopiv!(copy(A), 256) +L = tril(F, -1) + Matrix(I, m, n) +U = triu(F[1:n, :]) +L * U ≈ A + +# output + +true +``` + +On a GPU the same calls take device arrays. [`tile_lu_factor!`](@ref) runs on a GPU only, with +tiles of at most 32. This block is not run when the documentation is built: + +```julia +using NextLA, CUDA, LinearAlgebra + +n = 4096 +A = rand(n, n) + n * I +dF = lu_recursive!(CuArray(A), 1024) # the leaves go to cuSOLVER, unpivoted +F = Array(dF) +UnitLowerTriangular(F) * UpperTriangular(F) ≈ A + +B = rand(2048, 2048) +dG, p, info = tile_lu_factor!(CuArray(B), 32) # pivoting within each 32×32 tile +G = Array(dG) +info == 0 && UnitLowerTriangular(G) * UpperTriangular(G) ≈ B[p, :] +``` diff --git a/docs/src/api/dense/lapack/qr.md b/docs/src/api/dense/lapack/qr.md new file mode 100644 index 00000000..dfce3951 --- /dev/null +++ b/docs/src/api/dense/lapack/qr.md @@ -0,0 +1,180 @@ +```@meta +CurrentModule = NextLA +``` + +# QR and Householder kernels + +Julia versions of the LAPACK and PLASMA kernels used by tiled QR factorizations. Most routines +come in two forms: a low-level one with explicit sizes and workspace that mirrors the LAPACK +signature, and a convenience one that infers them. These routines are not exported; call them as +`NextLA.geqrt!`, etc. + +| Kernel | Purpose | +|:---------------------------|:-------------------------------------------------------------------| +| `larfg!` | generate an elementary Householder reflector | +| `larf!` | apply one reflector | +| `larft!` | form the triangular factor `T` of a block reflector | +| `larfb!` | apply a block reflector | +| `geqr2!` | unblocked QR | +| `geqrt!` | blocked QR with compact-WY `T` factors | +| `unmqr!` | apply `Q` or `Qᵀ` from `geqrt!` | +| `tsqrt!` / `tsmqr!` | QR of a triangle on top of a square tile, and applying its `Q` | +| `ttqrt!` / `ttmqr!` | QR of a triangle on top of a triangle, and applying its `Q` | +| `parfb!`, `pamm!`, `pemv!` | pentagonal block-reflector application and its building blocks | + +Plane (Givens) rotations, `lartg`, are on the [Rotations](@ref) page. + +## Householder reflectors + +```@autodocs +Modules = [NextLA] +Pages = ["larfg.jl", "larf.jl", "larft.jl", "larfb.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Tile QR + +```@autodocs +Modules = [NextLA] +Pages = ["geqr2.jl", "geqrt.jl", "unmqr.jl", "tsqrt.jl", "tsmqr.jl", "ttqrt.jl", "ttmqr.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Pentagonal kernels + +```@autodocs +Modules = [NextLA] +Pages = ["parfb.jl", "pamm.jl", "pemv.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Each example stands on its own and ends with a check that prints `true`. + +Least squares with a blocked QR: [`geqrt!`](@ref) factors `A`, [`unmqr!`](@ref) applies `Qᴴ` to +the right-hand side, and a triangular solve with `R` finishes: + +```jldoctest +using NextLA, LinearAlgebra + +m, n, ib = 2048, 1024, 64 +A = rand(m, n) +b = rand(m) + +F = copy(A) +T = zeros(ib, n) +NextLA.geqrt!(F, T) # R in triu(F), reflectors below it + +c = reshape(copy(b), m, 1) +NextLA.unmqr!('L', 'C', F, T, c) # c := Qᴴ * b +x = UpperTriangular(F[1:n, :]) \ c[1:n] +x ≈ A \ b + +# output + +true +``` + +One blocked QR step built from the Householder kernels: [`geqr2!`](@ref) factors a 128-column +panel, [`larft!`](@ref) forms its block reflector and [`larfb!`](@ref) applies it to the trailing +columns: + +```jldoctest +using NextLA, LinearAlgebra + +n, nb = 1024, 128 +A0 = rand(n, n) +A = copy(A0) +panel, rest = view(A, :, 1:nb), view(A, :, nb+1:n) + +tau = zeros(nb) +NextLA.geqr2!(panel, tau) # unblocked QR of the panel +T = zeros(nb, nb) +NextLA.larft!('F', 'C', panel, tau, T) # H = I - V * T * Vᴴ +NextLA.larfb!('L', 'C', 'F', 'C', panel, T, rest) # rest := Hᴴ * rest + +triu(A[1:nb, :]) ≈ qr(A0).R[1:nb, :] # the first 128 rows of R + +# output + +true +``` + +Tile QR of a 1024 by 256 panel stored as four 256 by 256 tiles (a flat tree): [`geqrt!`](@ref) +factors the top tile and [`tsqrt!`](@ref) folds each tile below into its `R`; then +[`unmqr!`](@ref) and [`tsmqr!`](@ref) apply `Qᴴ` to other columns in the same order. `R` and the +top rows of `Qᴴ C` match `LinearAlgebra.qr` up to the signs of the rows: + +```jldoctest +using NextLA, LinearAlgebra + +nb, ib = 256, 32 # tile size, inner block size +P = rand(4nb, nb) # the panel +C = rand(4nb, 1024) # columns to update with Qᴴ +A, B = copy(P), copy(C) +tile(X, i) = view(X, (i-1)*nb+1:i*nb, :) +Ts = [zeros(ib, nb) for _ in 1:4] + +NextLA.geqrt!(tile(A, 1), Ts[1]) +for i in 2:4 + NextLA.tsqrt!(tile(A, 1), tile(A, i), Ts[i]) +end + +NextLA.unmqr!('L', 'C', tile(A, 1), Ts[1], tile(B, 1)) +for i in 2:4 + NextLA.tsmqr!('L', 'C', tile(B, 1), tile(B, i), tile(A, i), Ts[i]) +end + +F = qr(P) +abs.(triu(tile(A, 1))) ≈ abs.(F.R) && abs.(tile(B, 1)) ≈ abs.((F.Q' * C)[1:nb, :]) + +# output + +true +``` + +The binary-tree variant on two tiles: each tile is factored with [`geqrt!`](@ref), then +[`ttqrt!`](@ref) merges the two triangles and [`ttmqr!`](@ref) applies the merge: + +```jldoctest +using NextLA, LinearAlgebra + +nb, ib = 256, 32 +P = rand(2nb, nb) +C = rand(2nb, 1024) +A, B = copy(P), copy(C) +top, bot = 1:nb, nb+1:2nb +T1, T2, T12 = zeros(ib, nb), zeros(ib, nb), zeros(ib, nb) + +NextLA.geqrt!(view(A, top, :), T1) +NextLA.geqrt!(view(A, bot, :), T2) +R2 = triu(A[bot, :]) # ttqrt! needs zeros below the second triangle +NextLA.ttqrt!(view(A, top, :), R2, T12) + +NextLA.unmqr!('L', 'C', view(A, top, :), T1, view(B, top, :)) +NextLA.unmqr!('L', 'C', view(A, bot, :), T2, view(B, bot, :)) +NextLA.ttmqr!('L', 'C', view(B, top, :), view(B, bot, :), R2, T12) + +F = qr(P) +abs.(triu(A[top, :])) ≈ abs.(F.R) && abs.(B[top, :]) ≈ abs.((F.Q' * C)[1:nb, :]) + +# output + +true +``` + +The kernels are KernelAbstractions code and take device arrays directly. This block is not run +when the documentation is built: + +```julia +using NextLA, CUDA, LinearAlgebra + +A = rand(1024, 1024) +C = rand(1024, 1024) +dF, dT, dC = CuArray(A), CUDA.zeros(Float64, 64, 1024), CuArray(C) + +NextLA.geqrt!(dF, dT) +NextLA.unmqr!('L', 'C', dF, dT, dC) # dC := Qᴴ * C on the GPU +Array(dC) ≈ qr(A).Q' * C +``` diff --git a/docs/src/api/dense/lapack/rotations.md b/docs/src/api/dense/lapack/rotations.md new file mode 100644 index 00000000..c26b71b0 --- /dev/null +++ b/docs/src/api/dense/lapack/rotations.md @@ -0,0 +1,13 @@ +```@meta +CurrentModule = NextLA +``` + +# Rotations + +Plane (Givens) rotations in `src/dense/lapack/rotations`. + +```@autodocs +Modules = [NextLA] +Pages = [joinpath("rotations", "lartg.jl")] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` diff --git a/docs/src/api/mxp/blas.md b/docs/src/api/mxp/blas.md new file mode 100644 index 00000000..7eccb706 --- /dev/null +++ b/docs/src/api/mxp/blas.md @@ -0,0 +1,52 @@ +```@meta +CurrentModule = NextLA +``` + +# Mixed-precision BLAS + +The recursive GEMM, triangular solve/multiply and SYRK methods of `NextLA.MixedPrecision`, +in `src/mxp/blas`. Load them with `using NextLA.MixedPrecision`. + +```@autodocs +Modules = [MixedPrecision] +Pages = [ + "recgemm_mixedprec.jl", + "rectrxm_mixed.jl", + "recsyrk_mixedprec.jl", +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Each example stands on its own and ends with a check that prints `true`: the relative error of +the mixed-precision result against the same computation in `Float64`, with a tolerance that +matches the coarsest precision used. + +### GEMM and SYRK updates into mixed-precision containers + +`recgemm!` updates a `FullMixedPrec` and `recsyrk!` the stored triangle of a `SymmMixedPrec`, from +ordinary dense factors. + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +n, k = 2048, 512 +A = rand(n, k) +B = rand(k, n) +C = rand(n, n) + +F = FullMixedPrec(C; precisions = DataType[Float32, Float64]) +recgemm!(-1.0, A, B, 1.0, F) # F = C - A * B + +S = SymmMixedPrec(C + C', 'L'; precisions = DataType[Float32, Float64]) +recsyrk!(1.0, A, 0.5, S) # S = A * A' + (C + C') / 2 + +relerr(X, Y) = norm(X - Y) / norm(Y) +relerr(reconstruct_matrix(F), C - A * B) < 1e-5 && + relerr(reconstruct_matrix(S), A * A' + (C + C') / 2) < 1e-5 + +# output + +true +``` diff --git a/docs/src/api/mxp/core.md b/docs/src/api/mxp/core.md new file mode 100644 index 00000000..26bf12fc --- /dev/null +++ b/docs/src/api/mxp/core.md @@ -0,0 +1,80 @@ +```@meta +CurrentModule = NextLA +``` + +# Mixed-precision core + +The `NextLA.MixedPrecision` module, its containers, precision selection and quantization, in +`src/mxp/core`. Load it with `using NextLA.MixedPrecision`; see the [Mixed precision](@ref) guide +for concepts and examples. + +```@docs +MixedPrecision +``` + +## Containers + +```@autodocs +Modules = [MixedPrecision] +Pages = ["fullmixedprec.jl", "symmmixedprec.jl", "trimixedprec.jl", "tiledtrimixedprec.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Precision selection and quantization + +```@autodocs +Modules = [MixedPrecision] +Pages = ["adaptive.jl", "quantize.jl"] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Each example stands on its own and ends with a check that prints `true`: the relative error of +the mixed-precision result against the same computation in `Float64`, with a tolerance that +matches the coarsest precision used. + +### Building the containers from one `precisions` list + +`precisions[1]` is used for the top-level off-diagonal blocks, `precisions[2]` for the next +level, and `precisions[end]` for the diagonal leaves, which is also the element type. + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +A = rand(2048, 2048) +precisions = DataType[Float16, Float32, Float64] # level 0, level 1, leaves + +F = FullMixedPrec(A; precisions) # all of A +S = SymmMixedPrec(A + A', 'L'; precisions) # lower triangle of a symmetric matrix +T = TriMixedPrec(A, 'U'; precisions) # upper triangle of A + +relerr(X, Y) = norm(X - Y) / norm(Y) +eltype(F.A21) == Float16 && eltype(F.A11.A21) == Float32 && eltype(F) == Float64 && + relerr(reconstruct_matrix(F), A) < 1e-3 && + relerr(reconstruct_matrix(S), A + A') < 1e-3 && + relerr(reconstruct_matrix(T), triu(A)) < 1e-3 + +# output + +true +``` + +### Storing large values in `Float16` with `quantize` + +`quantize` divides a block by a `Float32` scale when its values exceed the range of the storage +type, and `dequantize` multiplies it back. + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +A = 1e6 .* randn(2048, 2048) # far past floatmax(Float16) = 65504 +Q, s = quantize(A, Float16) # A ≈ s * Q, with Q in Float16 +B = dequantize(Q, s, Float64) + +eltype(Q) == Float16 && s > 1 && norm(B - A) / norm(A) < 1e-3 + +# output + +true +``` diff --git a/docs/src/api/mxp/lapack.md b/docs/src/api/mxp/lapack.md new file mode 100644 index 00000000..2713702b --- /dev/null +++ b/docs/src/api/mxp/lapack.md @@ -0,0 +1,95 @@ +```@meta +CurrentModule = NextLA +``` + +# Mixed-precision LAPACK + +The recursive Cholesky and LU methods of `NextLA.MixedPrecision`, in `src/mxp/lapack`. Load them +with `using NextLA.MixedPrecision`. + +```@autodocs +Modules = [MixedPrecision] +Pages = [ + "recpotrf_mixedprec.jl", + "reclu_mixedprec.jl", +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Usage examples + +Each example stands on its own and ends with a check that prints `true`: the relative error of +the mixed-precision result against the same computation in `Float64`, with a tolerance that +matches the coarsest precision used. + +### Cholesky with precisions from `adaptive_precisions`, then a solve + +`potrf_recursive!` factors a `SymmMixedPrec` in place, and `TriMixedPrec(M)` hands the factor to +`unified_rectrxm!` for the two triangular solves. + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +n = 2048 +A = rand(n, n) +S = A * A' + n * I # symmetric positive definite + +p = adaptive_precisions(S, DataType[Float16, Float32, Float64], 256, 1e-6) +M = SymmMixedPrec(S, 'L'; precisions = p) +potrf_recursive!(M) # S = L * L', L stored in M + +L = TriMixedPrec(M) # the factor, without copying +B = rand(n, 256) +X = copy(B) +unified_rectrxm!('L', 'L', 'N', 1.0, 'S', L, X) # L * Y = B +unified_rectrxm!('L', 'L', 'T', 1.0, 'S', L, X) # L' * X = Y + +relerr(X, Y) = norm(X - Y) / norm(Y) +relerr(reconstruct_matrix(L), cholesky(S).L) < 1e-5 && relerr(X, S \ B) < 1e-5 + +# output + +true +``` + +### LU without pivoting, then a solve + +`lu_recursive!` stores `L` (unit diagonal) and `U` in the same `FullMixedPrec`, and +`unified_rectrxm!` reads either triangle of it. + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +n = 2048 +A = rand(n, n) + n * I # diagonally dominant: no pivoting needed +M = FullMixedPrec(A; precisions = DataType[Float32, Float64]) +lu_recursive!(M) # A = L * U, both stored in M + +B = rand(n, 256) +X = copy(B) +unified_rectrxm!('L', 'L', 'N', 'U', 1.0, 'S', M, X) # L * Y = B, unit diagonal +unified_rectrxm!('L', 'U', 'N', 'N', 1.0, 'S', M, X) # U * X = Y + +norm(X - A \ B) / norm(A \ B) < 1e-5 + +# output + +true +``` + +### On the GPU + +`FullMixedPrec` built from a `CuArray` stores its blocks as `CuArray`s, and `lu_recursive!` and +`reconstruct_matrix` work on it unchanged (this block is not run when the documentation is built). + +```julia +using CUDA, NextLA, NextLA.MixedPrecision, LinearAlgebra + +n = 4096 +A = CUDA.rand(Float64, n, n) + n * I # diagonally dominant, on the GPU +M = FullMixedPrec(A; precisions = DataType[Float16, Float32, Float64]) +lu_recursive!(M) + +F = Array(reconstruct_matrix(M)) # reconstruct_matrix returns a CuMatrix +isapprox(UnitLowerTriangular(F) * UpperTriangular(F), Array(A); rtol = 1e-3) # true +``` diff --git a/docs/src/api/tlr/blas.md b/docs/src/api/tlr/blas.md new file mode 100644 index 00000000..44e9c0a2 --- /dev/null +++ b/docs/src/api/tlr/blas.md @@ -0,0 +1,28 @@ +```@meta +CurrentModule = NextLA +``` + +# Tile low-rank BLAS + +Matrix multiplication with TLR operands, in `src/tlr/blas`: `NextLA.gemm!` into a dense result, +`NextLA.gemm` into a compressed one, and the workspace sizing around them. + +```@autodocs +Modules = [NextLA.TileLowRank] +Pages = [ + joinpath("blas", "gemm", "arena.jl"), + joinpath("blas", "gemm", "compressed_accumulation", "driver.jl"), + joinpath("blas", "gemm", "compressed_accumulation", "rolling_schedule.jl"), + joinpath("blas", "gemm", "compressed_accumulation", "run_coupling.jl"), + joinpath("blas", "gemm", "compressed_accumulation", "workspace.jl"), + joinpath("blas", "gemm", "compute_policy.jl"), + joinpath("blas", "gemm", "dense_accumulation", "dense_diagonal.jl"), + joinpath("blas", "gemm", "dense_accumulation", "driver.jl"), + joinpath("blas", "gemm", "dense_accumulation", "runs.jl"), + joinpath("blas", "gemm", "dense_accumulation", "schedule.jl"), + joinpath("blas", "gemm", "dense_accumulation", "three_stage.jl"), + joinpath("blas", "gemm", "dense_accumulation", "two_stage.jl"), + joinpath("blas", "gemm", "dense_accumulation", "workspace.jl"), +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` diff --git a/docs/src/api/tlr/core.md b/docs/src/api/tlr/core.md new file mode 100644 index 00000000..36048897 --- /dev/null +++ b/docs/src/api/tlr/core.md @@ -0,0 +1,40 @@ +```@meta +CurrentModule = NextLA +``` + +# Tile low-rank core + +`NextLA.TileLowRank`, in `src/tlr/core`: tile low-rank (TLR) matrices, whose off-diagonal tiles are +stored as low-rank factors, and their compression from dense matrices. Load it with +`using NextLA.TileLowRank`; it is not re-exported by `NextLA`. + +```@docs +NextLA.TileLowRank +``` + +## Containers + +```@autodocs +Modules = [NextLA.TileLowRank] +Pages = [ + joinpath("core", "compressed_ftlr_matrix.jl"), + joinpath("core", "interface.jl"), + joinpath("core", "tlr_matrix.jl"), +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` + +## Compression + +```@autodocs +Modules = [NextLA.TileLowRank] +Pages = [ + joinpath("core", "compression", "ara.jl"), + joinpath("core", "compression", "blas_utils.jl"), + joinpath("core", "compression", "compress.jl"), + joinpath("core", "compression", "norms.jl"), + joinpath("core", "compression", "uncompress.jl"), + joinpath("core", "compression", "workspace.jl"), +] +Filter = x -> !(x isa Function && startswith(String(nameof(x)), "_")) +``` diff --git a/docs/src/assets/bibtex.css b/docs/src/assets/bibtex.css new file mode 100644 index 00000000..393b5a15 --- /dev/null +++ b/docs/src/assets/bibtex.css @@ -0,0 +1,5 @@ +/* BibTeX boxes on the Citing page wrap long lines instead of scrolling sideways. */ +pre code.language-bibtex { + white-space: pre-wrap; + overflow-wrap: anywhere; +} diff --git a/handout.png b/docs/src/assets/handout.png similarity index 100% rename from handout.png rename to docs/src/assets/handout.png diff --git a/ieee_hpec_poster.pdf b/docs/src/assets/ieee_hpec_poster.pdf similarity index 100% rename from ieee_hpec_poster.pdf rename to docs/src/assets/ieee_hpec_poster.pdf diff --git a/docs/src/assets/ieee_hpec_poster.png b/docs/src/assets/ieee_hpec_poster.png new file mode 100644 index 00000000..61536998 Binary files /dev/null and b/docs/src/assets/ieee_hpec_poster.png differ diff --git a/docs/src/dev/todo.md b/docs/src/dev/todo.md new file mode 100644 index 00000000..0d4ee5ab --- /dev/null +++ b/docs/src/dev/todo.md @@ -0,0 +1,146 @@ +# NextLA TODO + +What NextLA.jl already does and what is still to build, grouped like BLAS and LAPACK. + +✅ done · 🟡 partly done · 🔄 in progress on a branch · ⬜ to do + +## Summary + +| Area | Done | ✅ | 🟡 | 🔄 | ⬜ | +|:--|:-:|:-:|:-:|:-:|:-:| +| BLAS level 3 (matrix–matrix) | 4 of 7 | 4 | | | 3 | +| BLAS level 2 (matrix–vector) | 2 of 6 | 2 | | | 4 | +| BLAS level 1 (vector) | 1 of 3 | 1 | 1 | | 1 | +| Cholesky (symmetric / Hermitian positive definite) | 1 of 6 | 1 | | | 5 | +| LU (general matrices) | 3 of 8 | 3 | 2 | | 3 | +| QR and LQ | 4 of 10 | 4 | 1 | 1 | 4 | +| Least squares and triangular | 1 of 4 | 1 | | | 3 | +| Eigenvalues | 0 of 4 | | | 1 | 3 | +| Singular values | 0 of 3 | | | 3 | | +| Auxiliary | 2 of 3 | 2 | | | 1 | +| Mixed precision (NextLA.MixedPrecision) | 4 of 6 | 4 | | 1 | 1 | +| Tile low-rank (NextLA.TileLowRank) | 2 of 3 | 2 | | | 1 | +| **All** | **24 of 63** | 24 | 4 | 6 | 29 | + +## BLAS level 3 (matrix–matrix) + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | gemm | `gemm!`, `recgemm!`, `gemmEx!`, `gemm_batched!`, `matmul!` (tiled kernel), `precision_gemm_grouped!` (unexported) | +| ✅ | trsm | `trsm!`, `unified_rectrxm!`, `trsm_batched!` | +| ✅ | trmm | `trmm!`, `unified_rectrxm!` | +| ✅ | syrk | `syrk!`, `recsyrk!`, `SYRK_KERNEL!`, `syrk_batched!` | +| ⬜ | herk | — | +| ⬜ | symm / hemm | — | +| ⬜ | syr2k / her2k | — | + +## BLAS level 2 (matrix–vector) + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | ger / geru | `geru!` | +| ✅ | gerc | `gerc!` (unexported) | +| ⬜ | gemv | — | +| ⬜ | trmv / trsv | — | +| ⬜ | symv / hemv, syr / her, syr2 / her2 | — | +| ⬜ | banded and packed (gbmv, sbmv, tbsv, spmv, …) | — | + +## BLAS level 1 (vector) + +| | Routine | In NextLA | +|:-:|:--|:--| +| 🟡 | axpy | `axpy!` (unexported) | +| ✅ | rotg | `lartg` (unexported) | +| ⬜ | dot, nrm2, asum, iamax, scal, copy, swap, rot | — | + +## Cholesky (symmetric / Hermitian positive definite) + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | potrf | `potrf!`, `potrf_recursive!`, `potrf_batched!`, `cholesky_lower!`, `cholesky_blocked!` | +| ⬜ | potrs (solve with the factor) | — | +| ⬜ | potri (inverse) | — | +| ⬜ | pocon (condition number) | — | +| ⬜ | pstrf (pivoted Cholesky) | — | +| ⬜ | pbtrf / pptrf (banded, packed) | — | + +## LU (general matrices) + +| | Routine | In NextLA | +|:-:|:--|:--| +| 🟡 | getrf, partial pivoting | `getrf2!`, `lu!(::NextLAMatrix)`, `lu_base!` (n ≤ 32), `tile_lu_factor!` (GPU, pivots within a tile) | +| ✅ | getrf, no pivoting | `lu_recursive!`, `lu_recursive_nopiv!` | +| ✅ | getc2 (complete pivoting) | `getc2!` | +| ✅ | laswp (row swaps) | `laswp` | +| 🟡 | tile LU kernels (getrf_incpiv, gessm, ssssm) | `dgetrf_tiled!`, `dgessm_kernel_L_inv!`, `dssssm_kernel!` (unexported) | +| ⬜ | getrs (solve), gesv (driver) | — | +| ⬜ | getri (inverse), gecon (condition) | — | +| ⬜ | gbtrf (banded) | — | + +## QR and LQ + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | geqrt (QR of a tile, compact WY) | `geqrt!`, `geqr2!` (unexported) | +| ✅ | larfg / larf / larft / larfb | `larfg!`, `larf!`, `larft!`, `larfb!` (unexported) | +| ✅ | unmqr / ormqr (apply Q) | `unmqr!` (unexported) | +| ✅ | tsqrt / tsmqr, ttqrt / ttmqr (tile QR) | `tsqrt!`, `tsmqr!`, `ttqrt!`, `ttmqr!`, `parfb!`, `pamm!`, `pemv!` (unexported) | +| ⬜ | tiled QR driver over a whole matrix | — | +| 🟡 | geqrf (blocked QR with τ) | `geqrt!` per tile | +| ⬜ | orgqr / ungqr (form Q explicitly) | — | +| ⬜ | gelqt, tslqt, ttlqt (LQ) | — | +| ⬜ | geqp3 (QR with column pivoting) | — | +| 🔄 | CAQR / TSQR, 2.5D QR, CholeskyQR3 | — | + +## Least squares and triangular + +| | Routine | In NextLA | +|:-:|:--|:--| +| ⬜ | gels (least squares) | — | +| ⬜ | trtri (triangular inverse) | — | +| ✅ | trtrs (triangular solve) | `trsm!` | +| ⬜ | trcon, lauum | — | + +## Eigenvalues + +| | Routine | In NextLA | +|:-:|:--|:--| +| ⬜ | sytrd / hetrd (tridiagonal reduction) | — | +| ⬜ | steqr / stedc, syev / heev / syevd | — | +| 🔄 | gehrd, hseqr, geev (nonsymmetric) | — | +| ⬜ | sytrf / hetrf (symmetric indefinite) | — | + +## Singular values + +| | Routine | In NextLA | +|:-:|:--|:--| +| 🔄 | gebrd / gbbrd (bidiagonal reduction) | — | +| 🔄 | bdsqr / bdsdc (bidiagonal SVD) | — | +| 🔄 | gesvd / gesdd (driver) | — | + +## Auxiliary + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | lamch (machine parameters) | `lamch` (unexported) | +| ✅ | lartg (Givens) | `lartg` (unexported) | +| ⬜ | lange / lansy (norms), lacpy / laset | — | + +## Mixed precision (NextLA.MixedPrecision) + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | containers | `FullMixedPrec`, `SymmMixedPrec`, `TriMixedPrec`, `TiledTriMixedPrec` | +| ✅ | precision choice and quantization | `adaptive_precisions`, `quantize`, `dequantize`, `reconstruct_matrix` | +| ✅ | GEMM, TRSM/TRMM, SYRK | `recgemm!`, `unified_rectrxm!`, `recsyrk!` (mixed methods) | +| ✅ | Cholesky, LU | `potrf_recursive!`, `lu_recursive!` (mixed methods) | +| 🔄 | mixed-precision solve / iterative refinement | — | +| ⬜ | mixed-precision QR | — | + +## Tile low-rank (NextLA.TileLowRank) + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | TLR matrices and compression | `TLRMatrix`, `CompressedFTLRMatrix`, `uncompress!` | +| ✅ | TLR matrix multiply | `NextLA.gemm!` and `NextLA.gemm` with TLR operands | +| ⬜ | TLR factorizations (Cholesky, LU) | — | diff --git a/docs/src/getting_started.md b/docs/src/getting_started.md new file mode 100644 index 00000000..fb2773ec --- /dev/null +++ b/docs/src/getting_started.md @@ -0,0 +1,160 @@ +```@meta +CurrentModule = NextLA +``` + +# Getting started + +Install NextLA, then follow four short workflows, one for each part of the library: dense matrices, +mixed precision, tile low-rank and the GPU. Each one chains several routines and ends with a check +that prints `true`; the CPU ones are run as doctests every time the documentation is built. + +## Installation + +```julia +using Pkg +Pkg.add("NextLA") # latest registered release +Pkg.add(url = "https://github.com/NextLinearAlgebra/NextLA.jl") # development version (main) +``` + +NextLA needs Julia 1.10 or later and is tested on 1.10 and nightly. For GPU support, also add the +backend package you want: `CUDA`, `AMDGPU`, `oneAPI` or `Metal`. To check an installation, run the +test suite as described in [Running the tests](dev/testing.md). + +In-place routines follow the BLAS/LAPACK argument conventions, including the character flags +`side`, `uplo`, `trans` and `diag`. + +## Usage + +### Dense matrices: solve a symmetric positive definite system + +[`syrk!`](@ref) builds `S = A Aᵀ + n I`, [`potrf_recursive!`](@ref) factors it as `S = L Lᵀ`, two +calls to [`trsm!`](@ref) solve `S X = B`, and [`gemm!`](@ref) computes the residual. + +```jldoctest +using NextLA, LinearAlgebra + +n = 2048 +A = rand(n, n) +B = rand(n, 256) + +S = Matrix{Float64}(n * I, n, n) +syrk!('L', 'N', 1.0, A, 1.0, S) # lower triangle of S = A Aᵀ + n I +potrf_recursive!(S) # Cholesky: L in the lower triangle of S + +X = copy(B) +trsm!('L', 'L', 'N', 'N', 1.0, S, X) # L Y = B +trsm!('L', 'L', 'T', 'N', 1.0, S, X) # Lᵀ X = Y + +R = copy(B) +gemm!(R, A * A' + n * I, X; alpha = -1.0, beta = 1.0) # R = B - (A Aᵀ + n I) X +norm(R) / norm(B) < 1e-10 + +# output + +true +``` + +For a general matrix, `lu!(NextLAMatrix{Float64}(A))` gives a pivoted LU that solves with `\`; for +least squares, the QR kernels `NextLA.geqrt!` and `NextLA.unmqr!` factor `A` and apply `Qᵀ`. The +[LU](api/dense/lapack/lu.md) and [QR](api/dense/lapack/qr.md) API pages show both. + +### Mixed precision: the same solve with fewer bits + +[`adaptive_precisions`](@ref NextLA.MixedPrecision.adaptive_precisions) picks a precision for each level of the block tree, +[`SymmMixedPrec`](@ref NextLA.MixedPrecision.SymmMixedPrec) stores `S` that way, [`potrf_recursive!`](@ref) factors it in place, and +[`unified_rectrxm!`](@ref) solves with the mixed-precision factor. + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +n = 2048 +A = rand(n, n) +S = A * A' + n * I # symmetric positive definite +B = rand(n, 256) + +p = adaptive_precisions(S, DataType[Float16, Float32, Float64], 256, 1e-6) +M = SymmMixedPrec(S, 'L'; precisions = p) # off-diagonal blocks in lower precisions +potrf_recursive!(M) # S = L Lᵀ, L stored in M +L = TriMixedPrec(M) # the factor, without copying + +X = copy(B) +unified_rectrxm!('L', 'L', 'N', 1.0, 'S', L, X) # L Y = B +unified_rectrxm!('L', 'L', 'T', 1.0, 'S', L, X) # Lᵀ X = Y +norm(X - S \ B) / norm(S \ B) < 1e-5 # close to the Float64 solve + +# output + +true +``` + +### Tile low-rank: compress, then multiply + +[`TLRMatrix`](@ref NextLA.TileLowRank.TLRMatrix) stores the off-diagonal tiles as low-rank +factors, [`ranks`](@ref NextLA.TileLowRank.ranks) shows how much was kept, and `NextLA.gemm!` +multiplies with the compressed matrix. + +```jldoctest +using NextLA, NextLA.TileLowRank, LinearAlgebra, Random +Random.seed!(1) # compression is randomized + +n = 2048 +A = [1 / (1 + abs(i - j)) for i in 1:n, j in 1:n] + I # low-rank off-diagonal tiles + +T = TLRMatrix(A, 256; maxrank = 64, tol = 1e-8, rel = true) # 8 × 8 tiles of 256 +stored = sum(ranks(T)) * 2 * 256 + 8 * 256^2 # numbers kept: factors plus dense diagonal + +C = zeros(n, n) +NextLA.gemm!(C, T, A; workspace = gemm_maximum_workspace_bytes(T, T)) # C = A * A +stored < n^2 / 2 && norm(C - A * A) / norm(A * A) < 1e-7 + +# output + +true +``` + +### On a GPU + +Build the matrices on the GPU and call the same routines; dense routines reach the vendor library +(here cuBLAS and cuSOLVER), and mixed-precision and tile low-rank containers keep their data on the +device. This +example is not run when the documentation is built, since the build machine has no GPU. + +```julia +using NextLA, NextLA.MixedPrecision, NextLA.TileLowRank, CUDA, LinearAlgebra + +n = 4096 +A = CUDA.rand(Float64, n, n) +S = A * A' + n * I # on the GPU +B = CUDA.rand(Float64, n, 256) + +F = potrf_recursive!(copy(S)) # Cholesky on the GPU +X = trsm!('L', 'L', 'N', 'N', 1.0, F, copy(B)) # L Y = B +trsm!('L', 'L', 'T', 'N', 1.0, F, X) # Lᵀ X = Y + +D = CUDA.rand(Float64, n, n) + n * I # diagonally dominant +M = FullMixedPrec(D; precisions = DataType[Float16, Float32, Float64]) +lu_recursive!(M) # mixed-precision LU, blocks on the GPU +G = Array(reconstruct_matrix(M)) + +K = CuArray([1 / (1 + abs(i - j)) for i in 1:n, j in 1:n]) # low-rank off-diagonal tiles +T = TLRMatrix(K, 256; maxrank = 64, tol = 1e-8, rel = true) # compressed on the GPU +C = CUDA.zeros(Float64, n, n) +NextLA.gemm!(C, T, T; workspace = gemm_maximum_workspace_bytes(T, T)) # C = K * K + +S * X ≈ B && isapprox(UnitLowerTriangular(G) * UpperTriangular(G), Array(D); rtol = 1e-3) && + norm(C - K * K) / norm(K * K) < 1e-6 # true +``` + +## Getting help + +Questions, bug reports and feature requests go to the +[GitHub issues](https://github.com/NextLinearAlgebra/NextLA.jl/issues). + +## Where to go next + +- [Backends and GPUs](@ref): which routine runs on which backend, and with which element types. +- [Mixed precision](@ref): the full guide to `NextLA.MixedPrecision`. +- [Tile low-rank](@ref): the full guide to `NextLA.TileLowRank`. +- [Benchmarks](@ref): speed against the vendor libraries. +- [API reference](api/dense/core.md): every routine, organised like the source; each page ends with + more worked examples. diff --git a/docs/src/index.md b/docs/src/index.md deleted file mode 100644 index e2e1036f..00000000 --- a/docs/src/index.md +++ /dev/null @@ -1,14 +0,0 @@ -```@meta -CurrentModule = NextLA -``` - -# NextLA - -Documentation for [NextLA](https://github.com/NextLinearAlgebra/NextLA.jl). - -```@index -``` - -```@autodocs -Modules = [NextLA] -``` diff --git a/docs/src/manual/backends.md b/docs/src/manual/backends.md new file mode 100644 index 00000000..26316e52 --- /dev/null +++ b/docs/src/manual/backends.md @@ -0,0 +1,138 @@ +```@meta +CurrentModule = NextLA +``` + +# Backends and GPUs + +NextLA writes its kernels once with +[KernelAbstractions.jl](https://github.com/JuliaGPU/KernelAbstractions.jl) and picks the backend from +the array it is given (`KernelAbstractions.get_backend(A)`). Vendor-specific code lives in +[package extensions](https://pkgdocs.julialang.org/v1/creating-packages/#Conditional-loading-of-code-in-packages-(Extensions)) +under `ext/`, which Julia loads automatically when the matching GPU package is loaded: + +| Extension | Loaded by | Vendor libraries used | +|:------------------|:---------------|:-------------------------------| +| `NextLACUDAExt` | `using CUDA` | cuBLAS, cuSOLVER | +| `NextLAAMDGPUExt` | `using AMDGPU` | rocBLAS, rocSOLVER | +| `NextLAoneAPIExt` | `using oneAPI` | oneMKL | +| `NextLAMetalExt` | `using Metal` | Metal Performance Shaders | + +Without any GPU package, every routine runs on the CPU, calling `LinearAlgebra.BLAS`/`LAPACK` +where they cover the element type and portable Julia kernels otherwise. + +## Usage + +```julia +using NextLA, CUDA # or AMDGPU, oneAPI, Metal + +using LinearAlgebra +A = rand(Float32, 100, 100) +S = CuArray(A * A' + 100I) # move the matrix to the GPU once + +potrf_recursive!(S) # runs on the GPU +``` + +The call is the same as on the CPU. Keep all operands on the same device: NextLA does not move data +between host and device for you. + +## What runs where + +The table lists the main entry points. "Portable" means the generic KernelAbstractions or recursive +Julia implementation; "vendor" means the call is forwarded to the vendor library for the supported +element types (other types fall back to the portable path where one exists). + +| Routine | CPU | CUDA | AMDGPU | oneAPI | Metal | +|:-----------------------------------------|:------------|:---------|:---------|:---------|:---------| +| [`gemm!`](@ref), [`recgemm!`](@ref) | BLAS | `mul!` | `mul!` | `mul!` | `mul!` | +| [`gemmEx!`](@ref) (mixed types) | portable | vendor | vendor | — | — | +| [`gemm_batched!`](@ref) | loop | vendor | vendor | vendor | vendor | +| [`trsm!`](@ref), [`unified_rectrxm!`](@ref) | portable | vendor + portable | vendor + portable | portable | portable | +| [`trsm_batched!`](@ref) | loop | vendor | vendor | vendor | vendor | +| [`syrk!`](@ref) | BLAS | vendor | vendor | vendor | vendor | +| [`recsyrk!`](@ref), [`SYRK_KERNEL!`](@ref) | portable | portable | portable | portable | portable | +| [`potrf!`](@ref) | LAPACK | vendor | vendor | — | vendor | +| [`potrf_batched!`](@ref) | loop | vendor | vendor | vendor | vendor | +| [`potrf_recursive!`](@ref) | recursive | recursive | recursive | needs `potrf!` | recursive | +| [`lu_recursive!`](@ref) (leaf) | `lu!(NoPivot())` | cuSOLVER `getrf` | rocSOLVER `getrf_npvt` | — | — | +| [`cholesky_blocked!`](@ref) | — | portable | portable | portable | portable | +| [`syrk_batched!`](@ref) | loop | loop | vendor | vendor (strided), loop (pointer) | via [`gemm_batched!`](@ref) | +| [`lu_base!`](@ref) | portable | portable | portable | portable | portable | +| [`tile_lu_factor!`](@ref) | — | portable | portable | portable | portable | +| QR tile kernels (`geqrt!`, `tsqrt!`, `ttqrt!`, `unmqr!`, `tsmqr!`, `ttmqr!`, …) | portable | portable | portable | portable | portable | + +Notes: + +- [`gemmEx!`](@ref) with differing storage and compute types is a CUDA and AMDGPU feature; the CPU + accepts any combination and accumulates in `compute_type`. oneAPI and Metal throw. +- [`trsm!`](@ref) reaches cuBLAS/rocBLAS `trsm!` for `Float32`, `Float64`, `ComplexF32` and + `ComplexF64` dense matrices; `Float16`, views and the other backends take the portable recursion. +- [`potrf!`](@ref) has no generic device fallback, so on a backend without a wrapper (oneAPI) it + throws instead of silently copying to the host. [`potrf_recursive!`](@ref) calls it at its leaves. +- `Float16` has no vendor SYRK, so recursive Cholesky in half precision uses [`recsyrk!`](@ref). +- [`cholesky_blocked!`](@ref) is GPU-only: on the CPU it throws and points to [`potrf!`](@ref). + [`tile_lu_factor!`](@ref) refuses the CPU because its kernels give wrong results there. +- cuBLAS has no batched SYRK, so [`syrk_batched!`](@ref) loops single calls on CUDA; Metal has no SYRK + at all, and its single-matrix [`syrk!`](@ref) can overwrite the other triangle. +- The AMDGPU fast path of [`unified_rectrxm!`](@ref) compiles and is selected for `ROCMatrix` + arguments, but has not been run on AMD hardware. +- The QR tile kernels are not exported (call them as `NextLA.geqrt!` and so on). Their CUDA runs + pass the test suite on Julia 1.10. + +## Element types + +| Type | Notes | +|:-------------------------|:------------------------------------------------------------------------| +| `Float64`, `Float32` | Supported by every routine below. | +| `ComplexF64`, `ComplexF32` | Supported by every routine below; `cholesky_lower!` gives wrong results. | +| `Float16` | Portable kernels; GEMM accumulates in `Float32`. Not in the CPU batched routines or `getrf2!`. | +| `BFloat16` | From [BFloat16s.jl](https://github.com/JuliaMath/BFloat16s.jl). As `Float16`, and no Cholesky (`potrf!`, `potrf_recursive!`). | +| `Float8_E5M2` | Storage type for mixed-precision off-diagonal blocks. | + +Measured on the CPU: each routine runs on 32×32 inputs and its result is compared with a +`Float64`/`ComplexF64` reference. ✓ correct result, ✗ wrong result, — no method for that type, +*GPU only* / *refused* throws by design. On GPUs the vendor libraries decide which types the vendor +paths take; other types use the portable code. + +| Routine | `Float64` | `Float32` | `Float16` | `BFloat16` | `ComplexF64` | `ComplexF32` | +|:--|:-:|:-:|:-:|:-:|:-:|:-:| +| `gemm!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `gemmEx!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `recgemm!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `gemm_batched!` | ✓ | ✓ | — | — | ✓ | ✓ | +| `trsm!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `trmm!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `unified_rectrxm!` (solve) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `unified_rectrxm!` (multiply) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `trsm_batched!` | ✓ | ✓ | — | — | ✓ | ✓ | +| `syrk!` | ✓ | ✓ | — | — | ✓ | ✓ | +| `recsyrk!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `SYRK_KERNEL!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `syrk_batched!` | ✓ | ✓ | — | — | ✓ | ✓ | +| `potrf!` | ✓ | ✓ | ✓ | — | ✓ | ✓ | +| `potrf_recursive!` | ✓ | ✓ | ✓ | — | ✓ | ✓ | +| `cholesky_blocked!` | GPU only | GPU only | GPU only | GPU only | GPU only | GPU only | +| `cholesky_lower!` | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | +| `potrf_batched!` | ✓ | ✓ | — | — | ✓ | ✓ | +| `getrf2!` (pivoted LU) | ✓ | ✓ | — | — | ✓ | ✓ | +| `lu_recursive!` (no pivoting) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `lu_recursive_nopiv!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `lu_base!` (pivoted, n ≤ 32) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `geqrt!` + `unmqr!` (QR of a tile) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `tsqrt!` + `tsmqr!` (triangle on square) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `ttqrt!` + `ttmqr!` (triangle on triangle) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `geru!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `gerc!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `axpy!` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| `lartg` (Givens) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +## GEMM compute modes + +For reduced-precision inputs, [`gemmEx!`](@ref) and its batched variants take a `compute_type` +that sets the accumulation precision. [`default_compute_type`](@ref) picks one from the storage +types of `A`, `B` and `C`, and [`GEMM_COMPUTE_TYPES`](@ref) documents the supported behaviour per +backend. The precision-policy entry points such as [`precision_gemm_batched!`](@ref) take a compute +*mode* instead, where [`TF32`](@ref) requests TensorFloat-32 computation for `Float32` operands. + +Some vendor GEMMs need aligned leading dimensions; [`is_gemm_aligned`](@ref), +[`gemm_alignment_quantum`](@ref) and [`aligned_leading_dimension`](@ref) help allocate arrays that +qualify. diff --git a/docs/src/manual/benchmarks.md b/docs/src/manual/benchmarks.md new file mode 100644 index 00000000..489edfce --- /dev/null +++ b/docs/src/manual/benchmarks.md @@ -0,0 +1,114 @@ +# Benchmarks + +Speed of the recursive routines, dense and mixed precision, against the vendor libraries on one +GPU. Measured on an NVIDIA GB10 (NVIDIA DGX Spark) with Julia 1.10.14, 1.13.4, last run 2026-11-24. + +- Numbers are **GFLOP/s** (higher is better): the routine's standard flop count divided by the + fastest of up to five timed calls, after an untimed warm-up. +- Mixed-precision columns use the containers of `NextLA.MixedPrecision`. `F16/F32` means the + off-diagonal blocks are stored in `Float16` and the diagonal leaves in `Float32`. The leaves are + 4096×4096, so at n = 4096 there is no split and the matrix is one leaf in the leaf type. +- The GB10 runs `Float64` at about 400 GFLOP/s on every library, so lower precisions are where + the speed is. +- — means not measured. + +## Speed (GFLOP/s) + +### GEMM + +`C = A * B`, square, `2n³` flops. + +| n | FP64 cuBLAS | FP64 NextLA | FP32 cuBLAS | FP32 NextLA | F32/F64 | F16/F64 | F16/F32 | F16 dense, F32 accum. | +|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 4096 | 398 | 402 | 19 297 | 18 974 | 400 | 400 | 17 934 | 62 974 | +| 8192 | 405 | 405 | 18 384 | 19 210 | 885 | 868 | 1 928 | 84 496 | +| 16384 | — | — | 15 764 | 15 134 | 1 693 | 2 123 | 1 547 | 66 222 | +| 32768 | — | — | 14 776 | 15 480 | — | — | — | 95 696 | + +### SYRK + +`C = A * Aᵀ`, lower triangle, `n³` flops. + +| n | FP64 cuBLAS | FP64 NextLA | FP32 cuBLAS | FP32 NextLA | F32/F64 | F16/F64 | F16/F32 | F16 dense, F32 accum. | +|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 4096 | 392 | 385 | 13 618 | 1 388 | 384 | 384 | 1 370 | 34 246 | +| 8192 | 392 | 414 | 8 637 | 1 362 | 744 | 738 | 1 357 | 56 901 | +| 16384 | 402 | 586 | 14 217 | 1 815 | 2 685 | 2 604 | 1 546 | 95 374 | +| 32768 | — | — | 14 030 | — | 4 631 | 3 259 | — | 91 820 | + +### TRSM + +`L \ B`, `n` right-hand sides, `n³` flops. + +| n | FP64 cuBLAS | FP64 NextLA | FP32 cuBLAS | FP32 NextLA | F32/F64 | F16/F64 | F16/F32 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 4096 | 345 | 345 | 8 395 | 8 228 | 222 | 222 | 665 | +| 8192 | 374 | 374 | 12 121 | 12 274 | 432 | 440 | 1 285 | +| 16384 | 389 | 390 | 13 569 | 14 436 | 839 | 864 | 2 543 | +| 32768 | — | — | 14 231 | 14 530 | — | — | 4 836 | + +### TRMM + +`L * B`, `n` columns, `n³` flops. + +| n | FP64 cuBLAS | FP64 NextLA | FP32 cuBLAS | FP32 NextLA | F32/F64 | F16/F64 | F16/F32 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 4096 | 374 | 390 | 8 833 | 11 276 | 231 | 229 | 394 | +| 8192 | 395 | 400 | 6 699 | 14 844 | 451 | 455 | 770 | +| 16384 | 402 | 403 | 6 768 | 14 734 | 866 | 894 | 1 523 | +| 32768 | — | — | 6 668 | 15 158 | — | — | — | + +### Cholesky + +`S = L Lᵀ`, `n³/3` flops. + +| n | FP64 cuSOLVER | FP64 NextLA | FP32 cuSOLVER | FP32 NextLA | F32/F64 | F16/F64 | F16/F32 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 4096 | 375 | 375 | 6 902 | 6 521 | 374 | 375 | 6 524 | +| 8192 | 397 | 374 | 10 031 | 9 591 | 292 | 237 | 1 705 | +| 16384 | 403 | 386 | 10 674 | 10 396 | 403 | 428 | 2 387 | +| 32768 | — | — | 11 410 | 13 433 | — | — | 3 909 | + +### LU + +`2n³/3` flops; NextLA does not pivot, cuSOLVER `getrf!` does. + +| n | FP64 cuSOLVER | FP64 NextLA | FP32 cuSOLVER | FP32 NextLA | F32/F64 | F16/F64 | F16/F32 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 4096 | 330 | 393 | 3 022 | 2 954 | 381 | 381 | 2 862 | +| 8192 | 373 | 420 | 6 327 | 2 269 | 301 | 302 | 1 278 | +| 16384 | 390 | 432 | 9 997 | 2 072 | 435 | 463 | 1 825 | +| 32768 | — | — | 12 164 | 1 990 | — | — | 3 162 | + +## Accuracy + +Error of the mixed-precision result against the same computation in `Float64`, at n = 8192 +(one split: off-diagonal blocks in the first type, leaves in the second). For the +factorizations it is the solve residual `‖Ax − b‖ / (‖A‖ ‖x‖)`. + +| Routine | Measures | F32/F64 | F16/F64 | F16/F32 | +|:---|:---|---:|---:|---:| +| GEMM | relative error of `C` | 8.4e-07 | 1.6e-04 | 1.6e-04 | +| SYRK | not measured on the GPU | — | — | — | +| TRSM | relative error of `X` | 1.6e-09 | 4.1e-08 | 4.1e-08 | +| TRMM | relative error of `B` | 1.1e-07 | 3.1e-06 | 3.1e-06 | +| Cholesky | solve residual | 5.4e-10 | 2.2e-08 | 3.2e-08 | +| LU | solve residual | 5.4e-10 | 2.9e-08 | 3.0e-08 | + +## Choosing precisions automatically + +[`adaptive_precisions`](@ref NextLA.MixedPrecision.adaptive_precisions) picks the storage type of each +level from a tolerance `ε`. It was run on 8 test matrices of size n = 16384 (kernel matrices, block-graded +matrices and randsvd matrices with condition numbers 10² to 10¹⁰), with 4096×4096 leaves. +Speed-up is the vendor `Float64` time divided by NextLA's (median over the matrices); error is the +largest over the matrices (solve residual for the factorizations, relative error for GEMM). + +| ε | Usual choice | Cholesky: speed-up vs cuSOLVER, error | LU: speed-up vs cuSOLVER, error | GEMM: speed-up vs cuBLAS, error | +|---:|:---|:---|:---|:---| +| 1e-04 | F16/F16/F64 | 1.1×, 1e-07 (3 of 8 not SPD) | 1.2×, 4e-07 | 5.3×, 3e-05 | +| 1e-08 | F32/F32/F64 | 1.0×, 9e-10 (1 of 8 not SPD) | 1.1×, 9e-10 | 7.7×, 5e-07 | +| 1e-12 | F64/F64/F64 | 0.8×, 8e-17 | 0.9×, 8e-17 | 1.5×, 7e-14 | + +Cholesky can fail with `PosDefException` when `Float16` (or, for the worst-conditioned matrix, +`Float32`) off-diagonal blocks are chosen: `adaptive_precisions` bounds the storage error in norm, +but rounding can still make the matrix lose positive definiteness. LU and GEMM do not have this problem. diff --git a/docs/src/manual/mixed_precision.md b/docs/src/manual/mixed_precision.md new file mode 100644 index 00000000..952cf315 --- /dev/null +++ b/docs/src/manual/mixed_precision.md @@ -0,0 +1,216 @@ +```@meta +CurrentModule = NextLA.MixedPrecision +``` + +# Mixed precision + +The `NextLA.MixedPrecision` submodule stores a matrix as a **tree of blocks, each level in its own +floating-point type**, and runs recursive GEMM, triangular solve/multiply, SYRK, Cholesky and LU +directly on that tree. Off-diagonal blocks, which usually carry less of the matrix's norm, can be +stored in `Float16`, `BFloat16` or even 8-bit floats, while the diagonal leaves stay in `Float32` +or `Float64`. + +The submodule is not re-exported by NextLA. Load it explicitly: + +```julia +using NextLA +using NextLA.MixedPrecision +``` + +## The recursive splitting + +All containers split an `n × n` matrix the same way: at `n ÷ 2` when `n` is a power of two, and +otherwise at the largest power of two below `n`. The diagonal blocks `A11` and `A22` are split +again; the off-diagonal blocks are stored as dense arrays. + +``` + level 0 after level 1 +┌─────────┬─────────┐ ┌────┬────┬─────────┐ +│ │ │ │ L │ o1 │ │ +│ A11 │ A12 │ ├────┼────┤ o0 │ +│ │ │ │ o1 │ L │ │ +├─────────┼─────────┤ → ├────┴────┼────┬────┤ +│ │ │ │ │ L │ o1 │ +│ A21 │ A22 │ │ o0 ├────┼────┤ +│ │ │ │ │ o1 │ L │ +└─────────┴─────────┘ └─────────┴────┴────┘ + +o0: precisions[1] o1: precisions[2] +L: leaves, precisions[end] +``` + +The `precisions` vector gives one type per level, from the top down: + +- `precisions[1]` is used for the off-diagonal blocks at level 0, +- `precisions[2]` for the off-diagonal blocks at level 1, and so on, +- `precisions[end]` is used for the leaves (the diagonal blocks where recursion stops) and is the + container's element type `T_Base`. + +Recursion stops when one precision is left or a block is `1 × 1`. So +`precisions = DataType[Float16, Float32, Float64]` stores the two largest off-diagonal blocks in +`Float16`, the next four in `Float32`, and four `Float64` leaves of size about `n/4`. + +### Rules for `precisions` + +- Allowed types: `Float8_E5M2`, `BFloat16`, `Float16`, `Float32`, `Float64`. +- The leaf type `precisions[end]` must be `Float32` or `Float64`. +- The input matrix must be square, non-empty and finite. + +## Containers + +| Container | Stores | Typical use | +|:-------------------------|:----------------------------------------|:-------------------------------------| +| [`FullMixedPrec`](@ref) | a dense square matrix (`A11`, `A12`, `A21`, `A22`) | GEMM output, LU | +| [`SymmMixedPrec`](@ref) | one triangle of a symmetric matrix | SYRK output, Cholesky | +| [`TriMixedPrec`](@ref) | one triangle of a triangular matrix | triangular solve and multiply | +| [`TiledTriMixedPrec`](@ref) | a triangular matrix as a flat grid of tiles | tile-based algorithms | + +All of them are `AbstractMatrix` subtypes, so `size`, `M[i, j]` and `eltype` work, and +[`reconstruct_matrix`](@ref) copies the container back into a dense matrix of type `T_Base`. +`transpose(M)` and `M'` return a lazy transposed wrapper. + +Each example on this page stands on its own and ends with a check that prints `true`. They are run +as doctests every time the documentation is built. + +```jldoctest +using NextLA, NextLA.MixedPrecision + +A = rand(1024, 1024) +F = FullMixedPrec(A; precisions = DataType[Float16, Float64]) # off-diagonal Float16, leaves Float64 + +B = reconstruct_matrix(F) # back to a dense Float64 matrix +isapprox(B, A; rtol = 1e-3) # equal up to Float16 rounding + +# output + +true +``` + +## Scaling + +Narrow types have little range: `floatmax(Float16)` is 65504. To store large values, every block +carries a `Float32` **scale factor** `s`. A block whose largest magnitude exceeds `floatmax` of its +storage type is stored as `A_block / s`, and reads return `stored * s`. Unscaled blocks have +`s = 1`. + +- Scale factors are always `Float32`. +- A block that would need a scale beyond `floatmax(Float32)` throws an `ArgumentError`, rather than + being stored as `Inf`. +- Updates (GEMM, SYRK, solves) that push a block past the range of its type raise its scale. +- Leaves of [`lu_recursive!`](@ref) and [`potrf_recursive!`](@ref) must be unscaled, since a single + scale cannot represent both factors; a scaled leaf throws an `ArgumentError`. + +The same block quantization is available on its own: + +```jldoctest +using NextLA.MixedPrecision + +A = 1e6 .* rand(1024, 1024) # too large for Float16 (max 65504) + +Q, s = quantize(A, Float16) # Q = A / s in Float16, s is a Float32 scale +isapprox(dequantize(Q, s, Float64), A; rtol = 1e-3) + +# output + +true +``` + +## Choosing precisions automatically + +[`adaptive_precisions`](@ref) picks the coarsest type per level that keeps the error below a target +`epsilon`, from the norms of the off-diagonal blocks at each level relative to the whole matrix: + +```jldoctest +using NextLA.MixedPrecision, LinearAlgebra + +A = rand(1024, 1024) +S = A * A' + 1024I + +U = DataType[Float16, Float32, Float64] # candidate types +p = adaptive_precisions(S, U, 16, 1e-8; uplo = 'L') +M = SymmMixedPrec(S, 'L'; precisions = p) # p is ready to use as `precisions` +p[end] # the leaves keep the input's precision + +# output + +Float64 +``` + +- `U` lists the candidate types in any order. +- `n_min` (here `16`) stops splitting before any block would be smaller than this. +- `epsilon` is the target accuracy; a larger `epsilon` allows coarser types. +- `uplo` is `'L'` or `'U'` for a symmetric or triangular matrix (only that triangle is read), and + `'F'` for a full one. + +The leaf type is the coarsest type in `U` that is at least as fine as `eltype(A)` and has the range +of `Float32`, so the result is always a valid `precisions` argument when `U` contains `Float32` or +`Float64`. + +## Routines + +The routines below extend the dense NextLA functions of the same name with methods for the +containers. They walk the block tree, call the dense routines on the leaves and GEMM on the +off-diagonal blocks, and run independent halves on separate threads for large matrices. + +| Routine | Container argument | Computes | +|:-------------------------------------------------------------|:----------------------|:----------------------------------------------| +| [`recgemm!(α, A, B, β, C)`](@ref recgemm!) | `C::FullMixedPrec` | `C = αAB + βC` | +| [`recsyrk!(α, A, β, C)`](@ref recsyrk!) | `C::SymmMixedPrec` | `C = αAAᵀ + βC` on `C.uplo` | +| [`potrf_recursive!(A)`](@ref potrf_recursive!) | `A::SymmMixedPrec` | Cholesky, in place | +| [`lu_recursive!(A)`](@ref lu_recursive!) | `A::FullMixedPrec` | unpivoted LU, in place | +| [`unified_rectrxm!(side, uplo, trans, α, func, A, B)`](@ref unified_rectrxm!) | `A::FullMixedPrec`, `SymmMixedPrec`, `TriMixedPrec` | triangular solve (`'S'`) or multiply (`'M'`) | + +### Example: Cholesky, then a triangular solve + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +A = rand(1024, 1024) +S = A * A' + 1024I + +M = SymmMixedPrec(S, 'L'; precisions = DataType[Float32, Float64]) +potrf_recursive!(M) # M now holds the factor L + +L = TriMixedPrec(M) # view the factor as triangular, no copy +b = rand(1024, 1) +x = unified_rectrxm!('L', 'L', 'N', 1.0, 'S', L, copy(b)) # solve L x = b +isapprox(reconstruct_matrix(L) * x, b; rtol = 1e-6) + +# output + +true +``` + +### Example: LU + +```jldoctest +using NextLA, NextLA.MixedPrecision, LinearAlgebra + +D = rand(1024, 1024) + 1024I # diagonally dominant, so no pivoting is needed + +F = FullMixedPrec(D; precisions = DataType[Float32, Float64]) +lu_recursive!(F) +LU = reconstruct_matrix(F) # L below the diagonal, U on and above +isapprox(UnitLowerTriangular(LU) * UpperTriangular(LU), D; rtol = 1e-5) + +# output + +true +``` + +## Pitfalls + +- **No pivoting.** [`lu_recursive!`](@ref) on a `FullMixedPrec` does not pivot; use matrices that + need none (e.g. diagonally dominant). +- **`uplo` must match.** For `SymmMixedPrec` and `TriMixedPrec`, `unified_rectrxm!` requires + `uplo == A.uplo` and throws an `ArgumentError` otherwise, since only that triangle is stored. +- **Transposes.** To solve with `Aᵀ`, pass `trans = 'T'` rather than `transpose(A)`. +- **Recovering a Cholesky factor.** After `potrf_recursive!(M)`, use + `reconstruct_matrix(TriMixedPrec(M))` for the dense factor; `reconstruct_matrix(M)` would mirror + it into both triangles. +- **`TiledTriMixedPrec`** is a storage format with `precisions` of at most two types (off-diagonal + tiles, diagonal tiles) and a `threshold` for the tile size; the recursive routines above do not + take it. + +The docstrings are on the [Mixed-precision core](@ref), [Mixed-precision BLAS](@ref) and +[Mixed-precision LAPACK](@ref) pages. diff --git a/docs/src/manual/tile_low_rank.md b/docs/src/manual/tile_low_rank.md new file mode 100644 index 00000000..f5a30f02 --- /dev/null +++ b/docs/src/manual/tile_low_rank.md @@ -0,0 +1,122 @@ +```@meta +CurrentModule = NextLA +``` + +# Tile low-rank + +Many large matrices, such as covariance matrices and discretized integral operators, have +off-diagonal blocks of low numerical rank. A **tile low-rank (TLR)** matrix splits the matrix into +tiles and stores each such tile as two thin factors `U * V'`, which saves memory and makes +products cheaper. `NextLA.TileLowRank` provides TLR matrices, their compression from dense +matrices, and matrix multiplication with them. Load it with `using NextLA.TileLowRank`; it is not +re-exported by `NextLA`. + +Each example on this page stands on its own and ends with a check that prints `true`. They are run +as doctests every time the documentation is built. + +## Two containers + +| Container | Diagonal tiles | Off-diagonal tiles | Use it when | +|:--|:--|:--|:--| +| [`TLRMatrix`](@ref NextLA.TileLowRank.TLRMatrix) | dense | `U * V'` | the diagonal tiles are full rank (the usual case) | +| [`CompressedFTLRMatrix`](@ref NextLA.TileLowRank.CompressedFTLRMatrix) | `U * V'` | `U * V'` | every tile, diagonal included, is low rank | + +Both store the factors of all tiles packed into one array, and both are built by compressing a +dense matrix. + +## Compressing a matrix + +```jldoctest +using NextLA, NextLA.TileLowRank, LinearAlgebra, Random +Random.seed!(1) # compression is randomized + +n = 2048 +A = [1 / (1 + abs(i - j)) for i in 1:n, j in 1:n] + I + +C = TLRMatrix(A, 256; maxrank = 64, tol = 1e-8, rel = true) +B = uncompress!(similar(A), C) # back to a dense matrix +norm(B - A) / norm(A) < 1e-7 + +# output + +true +``` + +- **`tile_size`** (here `256`) is the side of a square tile, or a tuple `(bm, bn)`. A size that does + not divide `n` leaves a smaller last row and column of tiles. +- **`maxrank`** caps the rank of every tile. +- **`tol`** is the error allowed per tile in the Frobenius norm: absolute, or relative to the tile's + norm with `rel = true`. Each tile gets the smallest rank that meets it, up to `maxrank`. With the + default `tol = 0` nothing may be dropped, so tiles are kept at rank `maxrank`. +- Compression uses a randomized range finder and draws from Julia's global random number + generator; seed it for reproducible ranks. + +## Looking inside + +```jldoctest +using NextLA, NextLA.TileLowRank, LinearAlgebra, Random +Random.seed!(1) + +n = 2048 +A = [1 / (1 + abs(i - j)) for i in 1:n, j in 1:n] + I +C = TLRMatrix(A, 256; maxrank = 64, tol = 1e-8, rel = true) + +grid_size(C) # (8, 8) tiles +r = ranks(C) # rank of each tile, row by row; 0 for the dense diagonal +U, V = get_factors(C, 1, 2) # the factors of tile (1, 2): U * V' approximates it +stored = sum(r) * 2 * 256 + 8 * 256^2 # numbers stored: factors plus dense diagonal +size(U, 2) == r[2] && stored < n^2 / 2 # about a fifth of the dense matrix + +# output + +true +``` + +[`ranks`](@ref NextLA.TileLowRank.ranks) gives the rank of each tile as a vector, row by row, and +[`maxrank`](@ref NextLA.TileLowRank.maxrank) the largest of them (not the `maxrank` cap given to +the constructor). [`get_factors`](@ref NextLA.TileLowRank.get_factors) returns the factors of one +tile and [`dense_diag`](@ref NextLA.TileLowRank.dense_diag) the dense diagonal tiles. + +## Multiplying + +`NextLA.gemm!(C, A, B; workspace)` computes `C = A * B` into a dense `C` when `A`, `B` or both are +TLR matrices; the other operand may be dense. It takes `alpha`, `beta`, `transA` and `transB` like +the dense [`gemm!`](@ref). `workspace` is a byte count; +[`gemm_maximum_workspace_bytes`](@ref NextLA.TileLowRank.gemm_maximum_workspace_bytes) is enough +for the fastest schedule and +[`gemm_minimum_workspace_bytes`](@ref NextLA.TileLowRank.gemm_minimum_workspace_bytes) the least +that works. + +```jldoctest +using NextLA, NextLA.TileLowRank, LinearAlgebra, Random +Random.seed!(1) + +n = 2048 +A = [1 / (1 + abs(i - j)) for i in 1:n, j in 1:n] + I +T = TLRMatrix(A, 256; maxrank = 64, tol = 1e-8, rel = true) + +C = zeros(n, n) +NextLA.gemm!(C, T, T; workspace = gemm_maximum_workspace_bytes(T, T)) # TLR × TLR +D = zeros(n, n) +NextLA.gemm!(D, T, A; workspace = gemm_maximum_workspace_bytes(T, T)) # TLR × dense +norm(C - A * A) / norm(A * A) < 1e-7 && norm(D - A * A) / norm(A * A) < 1e-7 + +# output + +true +``` + +`NextLA.gemm(A, B; maxrank, tol, rel)` multiplies two `CompressedFTLRMatrix` operands and returns +the product compressed, as another `CompressedFTLRMatrix`, without forming it densely. + +## Limitations + +- TLR GEMM takes `Float64`, `Float32`, `Float16` and `BFloat16` operands; the low-precision types + accumulate in `Float32`. The examples here use `Float64`. +- Compression can keep tiles at a higher rank than needed; check the result with `ranks`. Keep + `maxrank` below the tile size: equal to it, the factors come out wrong. +- GPU arrays work too: compressing a `CuArray` keeps the factors on the device, and `NextLA.gemm!` + multiplies there (checked with CUDA). +- There are no TLR factorizations (Cholesky, LU) yet. + +The docstrings are on the [Tile low-rank core](@ref) and [Tile low-rank BLAS](@ref) pages. diff --git a/docs/src/mixed_precision.md b/docs/src/mixed_precision.md deleted file mode 100644 index 95ab9d65..00000000 --- a/docs/src/mixed_precision.md +++ /dev/null @@ -1,9 +0,0 @@ -```@meta -CurrentModule = NextLA -``` - -# Mixed precision - -```@autodocs -Modules = [NextLA.MixedPrecision] -``` diff --git a/ext/NextLAAMDGPUExt.jl b/ext/NextLAAMDGPUExt.jl index 674388e4..b1f797cd 100644 --- a/ext/NextLAAMDGPUExt.jl +++ b/ext/NextLAAMDGPUExt.jl @@ -6,7 +6,9 @@ using LinearAlgebra include("amdgpu/common.jl") include("amdgpu/gemm.jl") +include("amdgpu/streams.jl") include("amdgpu/potrf.jl") +include("amdgpu/svd.jl") include("amdgpu/syrk.jl") include("amdgpu/trsm.jl") include("amdgpu/rectrxm.jl") diff --git a/ext/NextLACUDAExt.jl b/ext/NextLACUDAExt.jl index 16efb204..f2a9e654 100644 --- a/ext/NextLACUDAExt.jl +++ b/ext/NextLACUDAExt.jl @@ -5,7 +5,9 @@ using CUDA include("cuda/common.jl") include("cuda/gemm.jl") +include("cuda/streams.jl") include("cuda/potrf.jl") +include("cuda/svd.jl") include("cuda/syrk.jl") include("cuda/trsm.jl") include("cuda/rectrxm.jl") diff --git a/ext/amdgpu/common.jl b/ext/amdgpu/common.jl index 4e199c3d..7f225f4e 100644 --- a/ext/amdgpu/common.jl +++ b/ext/amdgpu/common.jl @@ -33,7 +33,7 @@ end @inline NextLA._build_batch_ptrs(batch::AbstractVector{<:AMDGPU.StridedROCMatrix}) = _device_batch_strided(batch) -# SYRK entry points, added with src/syrk/. rocBLAS is the only backend +# SYRK entry points, added with src/dense/blas/syrk/. rocBLAS is the only backend # with a native batched SYRK in both layouts. @inline _rocblas_syrk_fname(::Type{Float32}, ::Val{:single}) = rocBLAS.rocblas_ssyrk_64 @inline _rocblas_syrk_fname(::Type{Float64}, ::Val{:single}) = rocBLAS.rocblas_dsyrk_64 diff --git a/ext/amdgpu/rectrxm.jl b/ext/amdgpu/rectrxm.jl index 92894e59..dcaa9f17 100644 --- a/ext/amdgpu/rectrxm.jl +++ b/ext/amdgpu/rectrxm.jl @@ -2,7 +2,7 @@ # ext/cuda/rectrxm.jl. # # Same design as the CUDA file: an added method, strictly more specific than -# the AbstractMatrix method in src/trsm/rectrxm.jl, so the recursive +# the AbstractMatrix method in src/dense/blas/trsm/rectrxm.jl, so the recursive # KernelAbstractions path stays for everything this does not cover. The # argument mapping is the CUDA one -- rocBLAS takes transa itself, so the # original uplo is passed unflipped, and alpha goes to rocBLAS directly with no @@ -28,7 +28,7 @@ function NextLA.unified_rectrxm!(side::Char, uplo::Char, - transpose::Char, + trans::Char, diag::Char, alpha::Number, func::Char, @@ -38,10 +38,10 @@ function NextLA.unified_rectrxm!(side::Char, throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) end if func == 'S' - rocBLAS.trsm!(side, uplo, transpose, diag, T(alpha), A, B) + rocBLAS.trsm!(side, uplo, trans, diag, T(alpha), A, B) elseif func == 'M' C = similar(B) - rocBLAS.trmm!(side, uplo, transpose, diag, T(alpha), A, B, C) + rocBLAS.trmm!(side, uplo, trans, diag, T(alpha), A, B, C) copyto!(B, C) else throw(ArgumentError("func must be 'S' or 'M', got '$func'")) diff --git a/ext/amdgpu/streams.jl b/ext/amdgpu/streams.jl new file mode 100644 index 00000000..d835d8dc --- /dev/null +++ b/ext/amdgpu/streams.jl @@ -0,0 +1,11 @@ +NextLA.create_streams(::AMDGPU.ROCBackend, n::Int) = [AMDGPU.HIPStream() for _ in 1:n] + +function NextLA.with_stream(f, ::AMDGPU.ROCBackend, s::AMDGPU.HIPStream) + AMDGPU.stream!(f, s) +end + +NextLA.sync_stream(::AMDGPU.ROCBackend, s::AMDGPU.HIPStream) = AMDGPU.synchronize(s) + +function NextLA.sync_streams_with_default(::AMDGPU.ROCBackend, streams) + AMDGPU.synchronize() +end diff --git a/ext/amdgpu/svd.jl b/ext/amdgpu/svd.jl new file mode 100644 index 00000000..c03000a0 --- /dev/null +++ b/ext/amdgpu/svd.jl @@ -0,0 +1,47 @@ +# Batched thin SVD on AMD. +# +# rocSOLVER's closest counterpart to cuSOLVER's `gesvdaStridedBatched` is the +# batched one-sided Jacobi SVD `rocsolver_?gesvdj_strided_batched`. Like +# `gesvda` it factors the tall-skinny panel directly, so it forms no Gram and +# does not square the condition number — which is the property +# `ara_truncate!` relies on. +# +# !!! warning "Unverified" +# This path has never been executed: the AMDGPU extension does not +# precompile on the development machine (`AMDGPUBackend` undefined in +# AMDGPU, a pre-existing version mismatch), so the wrapper below is written +# against the rocSOLVER signature but has no test coverage. Until it runs, +# the generic looped-LAPACK method in `compression/ara.jl` remains correct for +# ROCArrays — it simply copies to the host. Treat a first run of this +# method as bring-up, not as a regression. + +for (jname, elty, rty) in ((:rocsolver_sgesvdj_strided_batched, :Float32, :Float32), + (:rocsolver_dgesvdj_strided_batched, :Float64, :Float64)) + @eval function NextLA.TileLowRank.batched_thin_svd!(A::ROCArray{$elty,3}) + m, n, count = size(A) + m >= n || + throw(ArgumentError("batched_thin_svd! requires size(A,1) >= size(A,2)")) + count == 0 && return (similar(A), similar(A, $rty, n, 0), + similar(A, n, n, count)) + + U = similar(A, $elty, m, n, count) + V = similar(A, $elty, n, n, count) + S = similar(A, $rty, n, count) + residual = similar(A, $rty, count) + n_sweeps = similar(A, Int32, count) + info = similar(A, Int32, count) + + # `abstol <= 0` asks rocSOLVER for machine precision; the truncation + # tolerance is applied afterwards to the singular values, not here. + AMDGPU.rocSOLVER.$jname( + AMDGPU.rocBLAS.handle(), + AMDGPU.rocSOLVER.rocblas_svect_singular, # left: thin U + AMDGPU.rocSOLVER.rocblas_svect_singular, # right: thin V + m, n, A, m, m * n, + $rty(0), residual, Int32(100), n_sweeps, + S, n, U, m, m * n, V, n, n * n, + info, count, + ) + return (U, S, V) + end +end diff --git a/ext/cuda/gemm.jl b/ext/cuda/gemm.jl index 8b94e205..1ef7667e 100644 --- a/ext/cuda/gemm.jl +++ b/ext/cuda/gemm.jl @@ -1,5 +1,17 @@ @inline NextLA.supports_grouped_gemm(::Type{<:CUDA.CUDABackend}) = true +@inline function NextLA.TileLowRank.validate_compressed_ftlr_tile_alignment( + ::CUDA.CUDABackend, ::Type{T}, bm::Int, bn::Int) where {T} + return NextLA.TileLowRank.validate_compressed_ftlr_tile_alignment_cuda(T, bm, bn) +end + +@inline NextLA.TileLowRank.required_tlr_gemm_rank_multiple( + ::CUDA.CUDABackend, ::Type{Float16}, mode) = 8 +@inline NextLA.TileLowRank.required_tlr_gemm_rank_multiple( + ::CUDA.CUDABackend, ::Type{NextLA.BFloat16}, mode) = 8 +@inline NextLA.TileLowRank.required_tlr_gemm_rank_multiple( + ::CUDA.CUDABackend, ::Type{Float32}, ::NextLA.TF32) = 4 + @inline _grouped_cuptr(A::CUDA.StridedCuArray{T}) where {T} = pointer(A) @inline _grouped_cuptr(A::Base.ReshapedArray) = _grouped_cuptr(parent(A)) @inline _grouped_cuptr(A::SubArray{T}) where {T} = Base.unsafe_convert(CUDA.CuPtr{T}, A) diff --git a/ext/cuda/rectrxm.jl b/ext/cuda/rectrxm.jl index 1cc303a5..4138b4a4 100644 --- a/ext/cuda/rectrxm.jl +++ b/ext/cuda/rectrxm.jl @@ -1,6 +1,6 @@ # CUBLAS fast path for unified_rectrxm!. # -# src/trsm/rectrxm.jl solves and multiplies by recursing over NextLA's own +# src/dense/blas/trsm/rectrxm.jl solves and multiplies by recursing over NextLA's own # KernelAbstractions TRSM/TRMM kernels. That is what makes the routine portable, # and it stays the path for CPU, oneAPI and Metal. On CUDA the vendor library is # much faster — measured on an RTX 2000 Ada, Float32, lower/left solve: @@ -10,12 +10,12 @@ # CUBLAS/rocBLAS. That branch does it by replacing the generic method, which # also removes the routine from every backend without a vendor BLAS. Here it is # an added method instead: typed on StridedCuMatrix it is strictly more specific -# than the AbstractMatrix method in src/trsm/rectrxm.jl, so nothing is overwritten +# than the AbstractMatrix method in src/dense/blas/trsm/rectrxm.jl, so nothing is overwritten # and the recursive path is untouched. # # The argument mapping is not one-to-one with the generic version: # -# - src/trsm/rectrxm.jl handles trans='T'/'C' by wrapping A in Transpose/Adjoint +# - src/dense/blas/trsm/rectrxm.jl handles trans='T'/'C' by wrapping A in Transpose/Adjoint # and flipping uplo. CUBLAS takes transa itself, so the ORIGINAL uplo is # passed through unflipped. # - For a solve it scales B by alpha before recursing, and for a multiply it @@ -24,12 +24,12 @@ # # Typed on the four element types cuBLAS trsm/trmm take -- Float32, Float64, # ComplexF32 and ComplexF64 -- which are also the types the generic path in -# src/trsm/rectrxm.jl accepts, so what is supported does not depend on the +# src/dense/blas/trsm/rectrxm.jl accepts, so what is supported does not depend on the # backend. Float16 keeps the portable path, which widens it to Float32. function NextLA.unified_rectrxm!(side::Char, uplo::Char, - transpose::Char, + trans::Char, diag::Char, alpha::Number, func::Char, @@ -39,11 +39,11 @@ function NextLA.unified_rectrxm!(side::Char, throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) end if func == 'S' - CUBLAS.trsm!(side, uplo, transpose, diag, T(alpha), A, B) + CUBLAS.trsm!(side, uplo, trans, diag, T(alpha), A, B) elseif func == 'M' # CUBLAS trmm! writes into a separate output; passing B as both operand # and destination gives the in-place form the generic method provides. - CUBLAS.trmm!(side, uplo, transpose, diag, T(alpha), A, B, B) + CUBLAS.trmm!(side, uplo, trans, diag, T(alpha), A, B, B) else throw(ArgumentError("func must be 'S' or 'M', got '$func'")) end diff --git a/ext/cuda/streams.jl b/ext/cuda/streams.jl new file mode 100644 index 00000000..3ee9226e --- /dev/null +++ b/ext/cuda/streams.jl @@ -0,0 +1,23 @@ +NextLA.create_streams(::CUDA.CUDABackend, n::Int) = [CUDA.CuStream() for _ in 1:n] + +function NextLA.with_stream(f, ::CUDA.CUDABackend, s::CUDA.CuStream) + CUDA.stream!(f, s) +end + +NextLA.sync_stream(::CUDA.CUDABackend, s::CUDA.CuStream) = CUDA.synchronize(s) + +function NextLA.sync_streams_with_default(::CUDA.CUDABackend, + streams::AbstractVector{<:CUDA.CuStream}) + ev = CUDA.CuEvent() + CUDA.record(ev) + for s in streams + CUDA.wait(ev, s) + end +end + +NextLA.create_event(::CUDA.CUDABackend) = CUDA.CuEvent() +NextLA.record_event!(::CUDA.CUDABackend, event::CUDA.CuEvent, stream::CUDA.CuStream) = + CUDA.record(event, stream) +NextLA.wait_event!(::CUDA.CUDABackend, event::CUDA.CuEvent, stream::CUDA.CuStream) = + CUDA.wait(event, stream) +NextLA.sync_event(::CUDA.CUDABackend, event::CUDA.CuEvent) = CUDA.wait(event) diff --git a/ext/cuda/svd.jl b/ext/cuda/svd.jl new file mode 100644 index 00000000..b87e5e65 --- /dev/null +++ b/ext/cuda/svd.jl @@ -0,0 +1,29 @@ +# Batched thin SVD on CUDA, used by TLR's ARA truncation. +# +# Source: origin/alecarraro-dev, by Alessandro , carved +# out of that branch's monolithic ext/NextLACUDAExt.jl into this repo's +# per-backend ext layout. Verbatim, comment included. + +# s=48, and it recovers the true rank at s=16/32 where the Gram route +# over-retains by 30–40%. It is slower below s≈32, which is accepted in exchange +# for a single code path. +# +# The routine is documented as *approximate*, and its left factor is indeed not +# orthonormal when returned untruncated. `ara_truncate!` consumes the right +# factor, measured clean at ~1e-14, and truncates before use. +function NextLA.TileLowRank.batched_thin_svd!( + A::CUDA.StridedCuArray{T,3}, +) where {T<:Union{Float32,Float64,ComplexF32,ComplexF64}} + size(A, 1) >= size(A, 2) || + throw(ArgumentError("batched_thin_svd! requires size(A,1) >= size(A,2)")) + size(A, 2) == 0 && return ( + similar(A, size(A, 1), 0, size(A, 3)), + similar(A, real(T), 0, size(A, 3)), + similar(A, 0, 0, size(A, 3)), + ) + size(A, 3) == 0 && return (similar(A), similar(A, real(T), size(A, 2), 0), + similar(A, size(A, 2), size(A, 2), 0)) + U, S, V = CUDA.CUSOLVER.gesvda!('V', A; rank=size(A, 2)) + return (U, S, V) +end + diff --git a/ext/cuda/syrk.jl b/ext/cuda/syrk.jl index 8471c628..326a5087 100644 --- a/ext/cuda/syrk.jl +++ b/ext/cuda/syrk.jl @@ -3,7 +3,7 @@ # Source: origin/pr/19, by Alessandro , carved out of # that branch's monolithic ext/NextLACUDAExt.jl into this repo's per-backend # ext layout. Only the @warn wording differs, for the reason in -# src/syrk/syrk.jl. +# src/dense/blas/syrk/syrk.jl. # # CUBLAS has no batched SYRK entry point, so both batch layouts loop single # syrk! calls rather than dispatching natively. That is a library gap, not an diff --git a/ext/metal/common.jl b/ext/metal/common.jl index 003e231b..2b5d6e58 100644 --- a/ext/metal/common.jl +++ b/ext/metal/common.jl @@ -26,7 +26,7 @@ end end # Single-matrix counterpart of _supports_mps_batched_matmul above, added with -# src/syrk/: MPS gates matmul on the (input, output) element-type pair either +# src/dense/blas/syrk/: MPS gates matmul on the (input, output) element-type pair either # way, batched or not. @inline function _supports_mps_matmul(::Type{Tin}, ::Type{Tin}, ::Type{Tout}) where {Tin, Tout} return (Tin, Tout) in MPS.MPS_VALID_MATMUL_TYPES diff --git a/ext/metal/gemm.jl b/ext/metal/gemm.jl index f6a729b0..19a59462 100644 --- a/ext/metal/gemm.jl +++ b/ext/metal/gemm.jl @@ -101,7 +101,7 @@ end # list of separately allocated matrices. Without this method such a call -- and # Metal's own gemmEx_batched! for the same shape, which routes here through # _try_same_type_batched! -- falls through to the generic CPU loop in -# src/gemm/gemm_batched.jl and hands BLAS.gemm! a Metal device matrix. Refuse +# src/dense/blas/gemm/gemm_batched.jl and hands BLAS.gemm! a Metal device matrix. Refuse # it here instead, with an error that names the backend. function NextLA.gemm_batched!(transA::Char, transB::Char, diff --git a/ext/oneapi/common.jl b/ext/oneapi/common.jl index fbd40179..c5e3eb75 100644 --- a/ext/oneapi/common.jl +++ b/ext/oneapi/common.jl @@ -6,7 +6,7 @@ const support = oneAPI.Support @inline NextLA.SUBGROUP_SIZE(::Type{<:oneAPI.oneAPIBackend}) = Val(32) -# TRSM entry points, added with src/trsm/batched.jl. oneMKL has both a +# TRSM entry points, added with src/dense/blas/trsm/trsm_batched.jl. oneMKL has both a # pointer-batched and a strided-batched TRSM. @inline _onemkl_trsm_fname(::Type{Float32}, ::Val{:pointer}) = support.onemklStrsm_batch @inline _onemkl_trsm_fname(::Type{Float64}, ::Val{:pointer}) = support.onemklDtrsm_batch @@ -16,7 +16,7 @@ const support = oneAPI.Support @inline _onemkl_trsm_fname(::Type{Float64}, ::Val{:strided}) = support.onemklDtrsm_batch_strided @inline _onemkl_trsm_fname(::Type{ComplexF32}, ::Val{:strided}) = support.onemklCtrsm_batch_strided @inline _onemkl_trsm_fname(::Type{ComplexF64}, ::Val{:strided}) = support.onemklZtrsm_batch_strided -# Cholesky entry points, added with src/cholesky/potrf_batched.jl. +# Cholesky entry points, added with src/dense/lapack/cholesky/potrf_batched.jl. @inline _onemkl_potrf_strided_fname(::Type{Float32}) = support.onemklSpotrf_batch_strided @inline _onemkl_potrf_strided_fname(::Type{Float64}) = support.onemklDpotrf_batch_strided @inline _onemkl_potrf_strided_fname(::Type{ComplexF32}) = support.onemklCpotrf_batch_strided @@ -26,7 +26,7 @@ const support = oneAPI.Support @inline _onemkl_potrf_strided_scratchpad_fname(::Type{ComplexF32}) = support.onemklCpotrf_batch_strided_scratchpad_size @inline _onemkl_potrf_strided_scratchpad_fname(::Type{ComplexF64}) = support.onemklZpotrf_batch_strided_scratchpad_size -# SYRK entry points, added with src/syrk/. oneMKL has a native strided +# SYRK entry points, added with src/dense/blas/syrk/. oneMKL has a native strided # batched SYRK but no pointer-batched one. @inline _onemkl_syrk_fname(::Type{Float32}) = support.onemklSsyrk_batch_strided @inline _onemkl_syrk_fname(::Type{Float64}) = support.onemklDsyrk_batch_strided diff --git a/ext/oneapi/syrk.jl b/ext/oneapi/syrk.jl index 2409f21a..73aa4a5e 100644 --- a/ext/oneapi/syrk.jl +++ b/ext/oneapi/syrk.jl @@ -3,7 +3,7 @@ # Source: origin/pr/19, by Alessandro , carved out of # that branch's monolithic ext/NextLAoneAPIExt.jl into this repo's per-backend # ext layout. Only the @warn wording differs, for the reason in -# src/syrk/syrk.jl. The _onemkl_syrk_fname table went to common.jl beside the +# src/dense/blas/syrk/syrk.jl. The _onemkl_syrk_fname table went to common.jl beside the # other oneMKL name tables. # # oneMKL has a native strided batched SYRK but no pointer-batched one, so the @@ -72,7 +72,7 @@ function NextLA.syrk_batched!(uplo::Char, return C end -# recsyrk!'s Float16 updates (src/syrk/recsyrk.jl). oneAPI has no gemmEx!, so the +# recsyrk!'s Float16 updates (src/dense/blas/syrk/recsyrk.jl). oneAPI has no gemmEx!, so the # multiply goes through gemm! -- mul! on the device -- as vicki-development's # recsyrk_dev.jl did with oneMKL.gemm!. Never executed: no Intel GPU here. NextLA._syrk_half_gemm!(alpha, A, B, beta, C::oneAPI.oneStridedMatrix) = diff --git a/src/NextLA.jl b/src/NextLA.jl index 3409e452..f94684da 100644 --- a/src/NextLA.jl +++ b/src/NextLA.jl @@ -9,7 +9,7 @@ import LinearAlgebra: BLAS, LAPACK import LinearAlgebra.BLAS: @blasfunc using Random: Random using KernelAbstractions -# @unroll: chol_kernel_register! unrolls over its register strip. TLRmodule +# @unroll: chol_kernel_register! unrolls over its register strip. TileLowRank # imports it separately, being its own module. using KernelAbstractions.Extras: @unroll @@ -33,6 +33,15 @@ Determines single / double precision machine parameters - eps = relative machine precision - sfmin = safe min, such that 1/sfmin does not overflow - base = base of the machine + +# Examples +```jldoctest +julia> NextLA.lamch(Float64, 'E') == eps(Float64) / 2 +true + +julia> NextLA.lamch(Float32, 'S') == floatmin(Float32) +true +``` """ function lamch(::Type{T}, cmach) where {T <: Number} ep = eps(T) @@ -66,38 +75,18 @@ end @inline _rec_split(n::Integer) = ispow2(n) ? n ÷ 2 : prevpow(2, n) -include("NextLAMatrix.jl") -include("lu.jl") -include("lu/factor.jl") -include("trsm/trmm.jl") -include("trsm/trsm.jl") -include("trsm/rectrxm.jl") -include("gemm/matmul.jl") -include("gemm/gemm.jl") -include("syrk/syrk.jl") -include("cholesky/potrf_batched.jl") -include("cholesky/cholesky.jl") -include("trsm/batched.jl") -include("lauu2.jl") -include("lauum.jl") - -include("geqrt.jl") -include("geqr2.jl") -include("larf.jl") -include("larfg.jl") -include("larft.jl") -include("larfb.jl") -include("unmqr.jl") -include("gerc.jl") -include("rotations/lartg.jl") -include("tsqrt.jl") -include("tsmqr.jl") -include("parfb.jl") -include("pamm.jl") -include("axpy.jl") -include("pemv.jl") -include("ttmqr.jl") -include("ttqrt.jl") -include("mxp/mxp.jl") +include("streams.jl") +include("dense/core/NextLAMatrix.jl") +include("dense/blas/gemm/gemm.jl") +include("dense/blas/trsm/trsm.jl") +include("dense/blas/syrk/syrk.jl") +include("dense/blas/axpy.jl") +include("dense/blas/gerc.jl") +include("dense/lapack/lu/lu.jl") +include("dense/lapack/cholesky/cholesky.jl") +include("dense/lapack/qr/qr.jl") +include("dense/lapack/rotations/rotations.jl") +include("mxp/core/mxp.jl") +include("tlr/core/tlr.jl") end diff --git a/src/axpy.jl b/src/dense/blas/axpy.jl similarity index 100% rename from src/axpy.jl rename to src/dense/blas/axpy.jl diff --git a/src/gemm/gemm.jl b/src/dense/blas/gemm/gemm.jl similarity index 74% rename from src/gemm/gemm.jl rename to src/dense/blas/gemm/gemm.jl index d9b8d987..bb0b2dd8 100644 --- a/src/gemm/gemm.jl +++ b/src/dense/blas/gemm/gemm.jl @@ -1,10 +1,11 @@ -# GEMM: the extended, batched, grouped and mixed-precision forms. +# GEMM: the tiled KernelAbstractions kernel and the extended, batched, grouped +# and mixed-precision forms. # # Source: alecarraro-dev @ 0f1ac84 (PR #20), by Alessandro . # The five gemm_* files are verbatim; this entry file is not. # -# This sits alongside src/gemm/matmul.jl, which keeps the tiled KernelAbstractions -# GEMM and GEMM_ADD!/GEMM_SUB!. Nothing here replaces it. +# matmul.jl keeps the tiled KernelAbstractions GEMM and GEMM_ADD!/GEMM_SUB!. +# Nothing in the gemm_* files replaces it. # # Layout contract: this is the only file here that includes. Exports stay in # the file that defines the symbol, so moving a unit to another feature is a @@ -14,6 +15,7 @@ # when the corresponding GPU package is. gemm_batched.jl carries CPU fallbacks, # so this feature works with no GPU package present. +include("matmul.jl") include("gemm_types.jl") include("gemmEx.jl") include("gemm_batched.jl") diff --git a/src/gemm/gemmEx.jl b/src/dense/blas/gemm/gemmEx.jl similarity index 90% rename from src/gemm/gemmEx.jl rename to src/dense/blas/gemm/gemmEx.jl index bea0056a..36590db1 100644 --- a/src/gemm/gemmEx.jl +++ b/src/dense/blas/gemm/gemmEx.jl @@ -17,6 +17,18 @@ Compute `C := alpha * A * B + beta * C` in place. `gemm!` is the common NextLA dispatch point for dense and structured matrix products. Dense matrix products forward to `LinearAlgebra.mul!`, while structured matrix types provide specialized methods. + +# Examples +```jldoctest +julia> A = rand(1024, 1024); B = rand(1024, 1024); C = rand(1024, 1024); + +julia> C0 = copy(C); + +julia> gemm!(C, A, B; alpha=2.0, beta=0.5); # C = 2AB + C/2 + +julia> C ≈ 2.0 * A * B + 0.5 * C0 +true +``` """ function gemm! end @@ -38,6 +50,16 @@ vicki-development called GEMM this way through `src/wrappers.jl`, a CUDA/AMD shim this repo does not take. Here it forwards to the output-first method, so it runs on every backend and reaches cuBLAS/rocBLAS through `mul!` on GPU arrays. + +# Examples +```jldoctest +julia> A = rand(1024, 1024); B = rand(1024, 1024); C = zeros(1024, 1024); + +julia> gemm!('T', 'N', 1.0, A, B, 0.0, C); # C = Aᵀ B + +julia> C ≈ transpose(A) * B +true +``` """ function gemm!(transA::Char, transB::Char, alpha::Number, A::AbstractMatrix, B::AbstractMatrix, beta::Number, C::AbstractMatrix) @@ -107,6 +129,18 @@ unqualified (it is exported) and as `NextLA.gemmEx!`. combination, backend-specific errors may be raised. - Algorithm selection and backend-specific math modes are out of scope for this API. + +# Examples +```jldoctest +julia> A = rand(Float16, 1024, 1024); B = rand(Float16, 1024, 1024); + +julia> C = zeros(Float32, 1024, 1024); # Float16 operands, Float32 result + +julia> gemmEx!('N', 'N', 1.0, A, B, 0.0, C; compute_type=Float32); + +julia> C ≈ Float32.(A) * Float32.(B) +true +``` """ function gemmEx!(transA::Char, transB::Char, diff --git a/src/gemm/gemm_batched.jl b/src/dense/blas/gemm/gemm_batched.jl similarity index 96% rename from src/gemm/gemm_batched.jl rename to src/dense/blas/gemm/gemm_batched.jl index 88f00973..db99ed35 100644 --- a/src/gemm/gemm_batched.jl +++ b/src/dense/blas/gemm/gemm_batched.jl @@ -101,6 +101,16 @@ where `op(A)` and `op(B)` are determined by `transA` and `transB`. - On the CPU, `gemm_batched!` falls back to a loop of standard GEMMs. - GPU backends may dispatch to native pointer-batched or strided-batched GEMM kernels when available. + +# Examples +```jldoctest +julia> A = rand(1024, 1024, 4); B = rand(1024, 1024, 4); C = zeros(1024, 1024, 4); + +julia> gemm_batched!('N', 'N', 1.0, A, B, 0.0, C); + +julia> all(C[:, :, i] ≈ A[:, :, i] * B[:, :, i] for i in 1:4) +true +``` """ function gemm_batched!(transA::Char, transB::Char, @@ -221,6 +231,18 @@ exported surface. combination, backend-specific errors may be raised. - Algorithm selection and backend-specific math modes are out of scope for this API. + +# Examples +```jldoctest +julia> A = [rand(1024, 1024) for _ in 1:4]; B = [rand(1024, 1024) for _ in 1:4]; + +julia> C = [zeros(1024, 1024) for _ in 1:4]; + +julia> NextLA.gemmEx_batched!('N', 'T', 1.0, A, B, 0.0, C); # same type: allowed on the CPU + +julia> all(C[i] ≈ A[i] * transpose(B[i]) for i in 1:4) +true +``` """ function gemmEx_batched!(transA::Char, transB::Char, diff --git a/src/gemm/gemm_grouped.jl b/src/dense/blas/gemm/gemm_grouped.jl similarity index 93% rename from src/gemm/gemm_grouped.jl rename to src/dense/blas/gemm/gemm_grouped.jl index a868cc25..c4e39926 100644 --- a/src/gemm/gemm_grouped.jl +++ b/src/dense/blas/gemm/gemm_grouped.jl @@ -21,7 +21,16 @@ end GroupedGemmTask{typeof(A),typeof(B),typeof(C),promote_type(typeof(alpha), typeof(beta))}( transA, transB, alpha, A, B, beta, C) -"""Whether a backend has the heterogeneous grouped-GEMM interface used by compressed FTLR.""" +"""Whether a backend has the heterogeneous grouped-GEMM interface used by compressed FTLR. + +# Examples +```jldoctest +julia> A = rand(1024, 1024); + +julia> NextLA.supports_grouped_gemm(NextLA.get_backend(A)) # the CPU runs grouped GEMM as a loop +true +``` +""" @inline supports_grouped_gemm(::Type) = false @inline supports_grouped_gemm(::Type{<:KernelAbstractions.CPU}) = true @inline supports_grouped_gemm(backend) = supports_grouped_gemm(typeof(backend)) @@ -34,6 +43,17 @@ end Execute heterogeneous GEMMs. CUDA uses its native grouped primitive; CPU implements the same semantics with an ordinary GEMM loop. + +# Examples +```jldoctest +julia> tasks = [NextLA.GroupedGemmTask('N', 'N', 1.0, rand(1024, 512), rand(512, 2048), 0.0, zeros(1024, 2048)), + NextLA.GroupedGemmTask('N', 'T', 1.0, rand(2048, 1024), rand(512, 1024), 0.0, zeros(2048, 512))]; + +julia> NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float64}()); + +julia> tasks[1].C ≈ tasks[1].A * tasks[1].B && tasks[2].C ≈ tasks[2].A * transpose(tasks[2].B) +true +``` """ function precision_gemm_grouped!(tasks::AbstractVector{<:GroupedGemmTask}, mode::AbstractGEMMComputeMode) diff --git a/src/gemm/gemm_precision.jl b/src/dense/blas/gemm/gemm_precision.jl similarity index 89% rename from src/gemm/gemm_precision.jl rename to src/dense/blas/gemm/gemm_precision.jl index 3180dfef..d396dff6 100644 --- a/src/gemm/gemm_precision.jl +++ b/src/dense/blas/gemm/gemm_precision.jl @@ -5,7 +5,19 @@ abstract type AbstractGEMMComputeMode end """Request ordinary GEMM accumulation in `T`.""" struct GEMMCompute{T} <: AbstractGEMMComputeMode end -"""Request TensorFloat-32 computation for FP32 GEMM operands and output.""" +"""Request TensorFloat-32 computation for FP32 GEMM operands and output. + +# Examples +CUDA only; every other backend throws `ArgumentError`. +```julia +using NextLA, CUDA + +A = CUDA.rand(Float32, 4096, 4096); B = CUDA.rand(Float32, 4096, 4096) +C = CUDA.zeros(Float32, 4096, 4096) +NextLA.precision_gemm!('N', 'N', 1f0, A, B, 0f0, C, TF32()) # TF32 tensor cores +isapprox(C, A * B; rtol = 1e-2) +``` +""" struct TF32 <: AbstractGEMMComputeMode end @inline gemm_compute_mode(mode::AbstractGEMMComputeMode) = mode @@ -101,6 +113,16 @@ end Dispatch a batched GEMM from its actual operand and destination storage types plus an explicit accumulation mode. The destination determines whether this is an intermediate (`Tin`) or final (`Tout`) contraction stage. + +# Examples +```jldoctest +julia> A = rand(1024, 1024, 4); B = rand(1024, 1024, 4); C = zeros(1024, 1024, 4); + +julia> NextLA.precision_gemm_batched!('N', 'N', 1.0, A, B, 0.0, C, NextLA.GEMMCompute{Float64}()); + +julia> all(C[:, :, i] ≈ A[:, :, i] * B[:, :, i] for i in 1:4) +true +``` """ function precision_gemm_batched!(transA, transB, alpha, A, B, beta, C, mode::AbstractGEMMComputeMode) @@ -146,7 +168,18 @@ function precision_gemm_batched_ptrs!(transA, transB, alpha, return Cd end -"""Precision-policy dispatch for one GEMM, including mixed output storage.""" +"""Precision-policy dispatch for one GEMM, including mixed output storage. + +# Examples +```jldoctest +julia> A = rand(Float32, 1024, 1024); B = rand(Float32, 1024, 1024); C = zeros(Float32, 1024, 1024); + +julia> NextLA.precision_gemm!('N', 'N', 1f0, A, B, 0f0, C, NextLA.GEMMCompute{Float32}()); + +julia> C ≈ A * B +true +``` +""" function precision_gemm!(transA, transB, alpha, A, B, beta, C, mode::AbstractGEMMComputeMode) backend = get_backend(C) diff --git a/src/gemm/gemm_types.jl b/src/dense/blas/gemm/gemm_types.jl similarity index 93% rename from src/gemm/gemm_types.jl rename to src/dense/blas/gemm/gemm_types.jl index af946971..6fd94a31 100644 --- a/src/gemm/gemm_types.jl +++ b/src/dense/blas/gemm/gemm_types.jl @@ -136,6 +136,17 @@ accepted for the signature but take no part, so an untyped literal such as `0.5` on `Float32` data cannot raise the compute type to `Float64`. Backends may still reject unsupported storage and compute type combinations. + +# Examples +```jldoctest +julia> A = rand(Float16, 1024, 1024); C = zeros(Float32, 1024, 1024); + +julia> default_compute_type(1.0, A, A, 0.0, A) # the Float64 scalars take no part +Float16 + +julia> default_compute_type(1.0, A, A, 0.0, C) === Float32 +true +``` """ @inline function default_compute_type(alpha, A, B, beta, C) T = promote_type(_batch_eltype(A), _batch_eltype(B), _batch_eltype(C)) @@ -161,6 +172,15 @@ and leading dimensions against this quantum to keep the fast kernels selected. | `Float64` | 2 | See also [`aligned_leading_dimension`](@ref), [`is_gemm_aligned`](@ref). + +# Examples +```jldoctest +julia> gemm_alignment_quantum(Float16) +8 + +julia> gemm_alignment_quantum(Float64) * sizeof(Float64) == 16 +true +``` """ @inline gemm_alignment_quantum(::Type{T}) where {T} = 16 ÷ gcd(16, sizeof(T)) @@ -173,6 +193,8 @@ dense `T` matrix 16-byte aligned. Allocate the padded array and take a logical view over the first `m` rows: ```julia +using NextLA, CUDA +n = 1024 ld = aligned_leading_dimension(Float16, 4097) # 4104 store = CuArray{Float16}(undef, ld, n) C = view(store, 1:4097, :) # stride(C, 2) == 4104 @@ -197,6 +219,15 @@ Applied to a nominal tile size this reports whether tile boundaries land on aligned addresses (tile row `i` of a dense output starts at element offset `(i-1) * bm`, which is independent of the leading dimension). Applied to a leading dimension it reports whether columns do. + +# Examples +```jldoctest +julia> is_gemm_aligned(Float16, 4097) +false + +julia> is_gemm_aligned(Float16, aligned_leading_dimension(Float16, 4097)) +true +``` """ @inline is_gemm_aligned(::Type{T}, n::Integer) where {T} = iszero(n % gemm_alignment_quantum(T)) diff --git a/src/gemm/matmul.jl b/src/dense/blas/gemm/matmul.jl similarity index 91% rename from src/gemm/matmul.jl rename to src/dense/blas/gemm/matmul.jl index df0fedcd..ad52fb59 100644 --- a/src/gemm/matmul.jl +++ b/src/dense/blas/gemm/matmul.jl @@ -124,6 +124,18 @@ end `C .+= scale * A * B`. `A` or `B` may be a `Transpose` or an `Adjoint`. A `Float16` `C` accumulates in `Float32`; a result beyond `floatmax(Float16)` is stored as `Inf`. Shapes that do not fit throw `DimensionMismatch`. + +# Examples +```jldoctest +julia> A = rand(1024, 1024); B = rand(1024, 1024); C = rand(1024, 1024); + +julia> C0 = copy(C); + +julia> GEMM_ADD!(A, B, C, 2.0); # C += 2AB + +julia> C ≈ C0 + 2.0 * A * B +true +``` """ function GEMM_ADD!(A, B, C, scale::Number = 1) _check_matmul_dims(A, B, C) @@ -135,8 +147,20 @@ end GEMM_SUB!(A, B, C, scale=1) -> A `A .-= scale * B * C`. Note the output is the *first* argument here, unlike -`GEMM_ADD!` — both orders match the callers in `src/trsm/rectrxm.jl`. Operands, +`GEMM_ADD!` — both orders match the callers in `src/dense/blas/trsm/rectrxm.jl`. Operands, `Float16` accumulation and shape checks are as for `GEMM_ADD!`. + +# Examples +```jldoctest +julia> A = rand(1024, 1024); B = rand(1024, 1024); C = rand(1024, 1024); + +julia> A0 = copy(A); + +julia> GEMM_SUB!(A, B, C); # A -= BC; the output is the first argument + +julia> A ≈ A0 - B * C +true +``` """ function GEMM_SUB!(A, B, C, scale::Number = 1) _check_matmul_dims(B, C, A) diff --git a/src/gemm/recgemm.jl b/src/dense/blas/gemm/recgemm.jl similarity index 100% rename from src/gemm/recgemm.jl rename to src/dense/blas/gemm/recgemm.jl diff --git a/src/gerc.jl b/src/dense/blas/gerc.jl similarity index 87% rename from src/gerc.jl rename to src/dense/blas/gerc.jl index c0aa1a3d..4e8aea95 100644 --- a/src/gerc.jl +++ b/src/dense/blas/gerc.jl @@ -32,14 +32,16 @@ The algorithm efficiently computes the outer product by: - Skips zero elements in y to minimize operations - In-place operation minimizes memory allocation -# Example -```julia -m, n = 4, 3 -A = zeros(ComplexF64, m, n) -x = complex.([1.0, 2.0, 3.0, 4.0], [0.1, 0.2, 0.3, 0.4]) -y = complex.([1.0, 0.0, 2.0], [0.5, 0.0, 1.0]) -alpha = 2.0 + 1.0im -gerc!(alpha, x, y, A) # A updated with rank-1 modification +# Examples +```jldoctest +julia> x = rand(ComplexF64, 1024); y = rand(ComplexF64, 1024); + +julia> A = rand(ComplexF64, 1024, 1024); A0 = copy(A); + +julia> NextLA.gerc!(2.0 + 1.0im, x, y, A); # alpha must have the element type of A + +julia> A ≈ A0 + (2.0 + 1.0im) * x * y' +true ``` """ function gerc!(alpha::T, x::AbstractVector{T}, y::AbstractVector{T}, A::AbstractMatrix{T}) where {T} diff --git a/src/syrk/recsyrk.jl b/src/dense/blas/syrk/recsyrk.jl similarity index 96% rename from src/syrk/recsyrk.jl rename to src/dense/blas/syrk/recsyrk.jl index 50a5a572..c87b027b 100644 --- a/src/syrk/recsyrk.jl +++ b/src/dense/blas/syrk/recsyrk.jl @@ -26,7 +26,7 @@ export recsyrk! # # The branch's GEMM calls, gemm!('N', 'T', alpha, A, B, beta, C), are kept as # written: this package's gemm! has that BLAS-order form too -# (src/gemm/gemmEx.jl), forwarding to the output-first method with the second +# (src/dense/blas/gemm/gemmEx.jl), forwarding to the output-first method with the second # operand transposed -- the whole point of the off-diagonal update. 'T', not # 'C': SYRK does not conjugate. @@ -160,6 +160,18 @@ Performs an in-place, nested recursive block symmetric rank-k update (`C = alpha*A*Aᵀ + beta*C`), writing the `uplo` triangle, `'L'` or `'U'`. Falls back to standard hardware routines using the dispatch helper at the specified base case threshold. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 512); C = zeros(1024, 1024); + +julia> recsyrk!(1.0, A, 0.0, C; uplo='U'); + +julia> UpperTriangular(C) ≈ UpperTriangular(A * A') +true +``` """ function recsyrk!( alpha::Number, A::AbstractMatrix, beta::Number, C::AbstractMatrix, threshold::Int=256; diff --git a/src/syrk/syrk.jl b/src/dense/blas/syrk/syrk.jl similarity index 100% rename from src/syrk/syrk.jl rename to src/dense/blas/syrk/syrk.jl diff --git a/src/syrk/syrk_batched.jl b/src/dense/blas/syrk/syrk_batched.jl similarity index 84% rename from src/syrk/syrk_batched.jl rename to src/dense/blas/syrk/syrk_batched.jl index 808098bf..e7c50626 100644 --- a/src/syrk/syrk_batched.jl +++ b/src/dense/blas/syrk/syrk_batched.jl @@ -21,6 +21,22 @@ exported surface. falls back to a loop of single-matrix [`syrk!`](@ref) calls. Metal is the one exception: its strided path routes to [`gemm_batched!`](@ref) instead. - When any fallback is used, `syrk_batched!` emits `@warn` naming the layout. + +# Examples +```jldoctest; filter = r"└ @ NextLA .*" +julia> using LinearAlgebra + +julia> A = rand(1024, 512, 4); C = zeros(1024, 1024, 4); + +julia> NextLA.syrk_batched!('L', 'N', 1.0, A, 0.0, C); # on the CPU this loops syrk! and says so +┌ Warning: syrk_batched! has no native batched SYRK here; looping syrk! +│ backend = "Array{Float64, 3}" +│ layout = :strided +└ @ NextLA src/dense/blas/syrk/syrk_batched.jl + +julia> all(LowerTriangular(C[:, :, i]) ≈ LowerTriangular(A[:, :, i] * A[:, :, i]') for i in 1:4) +true +``` """ function syrk_batched!(uplo::Char, trans::Char, diff --git a/src/syrk/syrk_dispatch.jl b/src/dense/blas/syrk/syrk_dispatch.jl similarity index 84% rename from src/syrk/syrk_dispatch.jl rename to src/dense/blas/syrk/syrk_dispatch.jl index 250c6be0..68c59cfe 100644 --- a/src/syrk/syrk_dispatch.jl +++ b/src/dense/blas/syrk/syrk_dispatch.jl @@ -30,6 +30,18 @@ where `op(A)` is determined by `trans`. ## Notes - On the CPU, `syrk!` is a thin wrapper around `LinearAlgebra.BLAS.syrk!`. - GPU backends may dispatch to native SYRK kernels when available. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 512); C = zeros(1024, 1024); + +julia> syrk!('L', 'N', 1.0, A, 0.0, C); # lower triangle of A * Aᵀ + +julia> LowerTriangular(C) ≈ LowerTriangular(A * A') +true +``` """ function syrk!(uplo::Char, trans::Char, diff --git a/src/syrk/syrk_kernel.jl b/src/dense/blas/syrk/syrk_kernel.jl similarity index 95% rename from src/syrk/syrk_kernel.jl rename to src/dense/blas/syrk/syrk_kernel.jl index 50713068..2c5abd96 100644 --- a/src/syrk/syrk_kernel.jl +++ b/src/dense/blas/syrk/syrk_kernel.jl @@ -13,12 +13,12 @@ export SYRK_KERNEL! # @synchronize splits the body into separate ndrange loops on the CPU # backend and only @localmem/@private survive the split, so both were out # of scope in the second half. They are kernel arguments now, which is why -# matmul! in src/gemm/matmul.jl takes N, R and M rather than computing them. +# matmul! in src/dense/blas/gemm/matmul.jl takes N, R and M rather than computing them. # # 2. I and J were likewise assigned before the first @synchronize and read # after it. `I` then resolves to LinearAlgebra.I and the kernel dies in # isless(::UniformScaling{Bool}, ::Int64). They are recomputed in every -# synchronize-delimited block, exactly as src/gemm/matmul.jl:31-32,56-57 does. +# synchronize-delimited block, exactly as src/dense/blas/gemm/matmul.jl:31-32,56-57 does. # This is the fifth routine in this repo to carry that bug. # # 3. Both @synchronize calls sat inside an `if gj <= gi` block that skipped @@ -32,7 +32,7 @@ export SYRK_KERNEL! # only. Both triangles work now, and the other one is left untouched, which # is the property that distinguishes SYRK from a GEMM. # -# The branch's `const TILE_DIM = 32` is dropped: it duplicates src/gemm/matmul.jl:3 +# The branch's `const TILE_DIM = 32` is dropped: it duplicates src/dense/blas/gemm/matmul.jl:3 # and would be a redefinition in this module. The one in scope here is that # same constant. diff --git a/src/trsm/rectrxm.jl b/src/dense/blas/trsm/rectrxm.jl similarity index 93% rename from src/trsm/rectrxm.jl rename to src/dense/blas/trsm/rectrxm.jl index a8fca0bb..918509e0 100644 --- a/src/trsm/rectrxm.jl +++ b/src/dense/blas/trsm/rectrxm.jl @@ -1,5 +1,5 @@ """ - unified_rectrxm!(side, uplo, transpose, alpha, func, A, B) + unified_rectrxm!(side, uplo, trans, alpha, func, A, B) Unified recursive function for triangular matrix solve (TRSM) and multiply (TRMM) operations. @@ -13,7 +13,7 @@ using recursive algorithms that are cache-friendly and numerically stable. - `uplo::Char`: Specifies the triangular part of the matrix to reference - 'U': Use the upper triangle - 'L': Use the lower triangle -- `transpose::Char`: Specifies the transposition operation +- `trans::Char`: Specifies the transposition operation - 'N': No transpose - 'T': Transpose - 'C': Conjugate transpose @@ -39,21 +39,37 @@ Uses recursive divide-and-conquer approach that: - Uses different thresholds for TRSM (256) vs TRMM (16) operations - Automatically handles transpose operations by adjusting matrix views - Recursive partitioning adapts to matrix size for optimal performance + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> A = rand(n, n) + n * I; + +julia> B = rand(n, 256); + +julia> C = unified_rectrxm!('L', 'U', 'N', 1.0, 'M', A, copy(B)); + +julia> unified_rectrxm!('L', 'U', 'N', 1.0, 'S', A, C) ≈ B +true +``` """ function unified_rectrxm!( side::Char, uplo::Char, - transpose::Char, + trans::Char, alpha::Number, func::Char, A::AbstractMatrix, B::AbstractMatrix ) - return unified_rectrxm!(side, uplo, transpose, 'N', alpha, func, A, B) + return unified_rectrxm!(side, uplo, trans, 'N', alpha, func, A, B) end """ - unified_rectrxm!(side, uplo, transpose, diag, alpha, func, A, B) + unified_rectrxm!(side, uplo, trans, diag, alpha, func, A, B) As above, with `diag` selecting whether `A` has a unit diagonal. @@ -66,7 +82,7 @@ unaffected. function unified_rectrxm!( side::Char, uplo::Char, - transpose::Char, + trans::Char, diag::Char, alpha::Number, func::Char, @@ -81,8 +97,8 @@ function unified_rectrxm!( n = size(A, 1) # Handle transpose operations by adjusting matrix view and uplo flag - if transpose == 'T' || transpose == 'C' - A = (transpose == 'T') ? Transpose(A) : Adjoint(A) + if trans == 'T' || trans == 'C' + A = (trans == 'T') ? transpose(A) : adjoint(A) uplo = (uplo == 'L') ? 'U' : 'L' end @@ -195,7 +211,7 @@ function _trxm_base!(func::Char, side::Char, uplo::Char, A::AbstractMatrix{Float end function unified_rec(func::Char, side::Char, uplo::Char, A::AbstractMatrix{T}, n, B::AbstractMatrix{T}, threshold::Int=256; unitdiag::Bool=false) where T <: Union{AbstractFloat, Complex{<:AbstractFloat}} - # src/trsm/trmm.jl's kernels index one TILE_DIM = 16 tile, so a multiply's base + # src/dense/blas/trsm/trmm.jl's kernels index one TILE_DIM = 16 tile, so a multiply's base # case is valid only up to 16 rows: a larger one reads the wrong elements and # returns a silently wrong result (0.52 relative error at n = 64). Clamping here # covers every caller, not only unified_rectrxm!, which already passes 16. diff --git a/src/trsm/trmm.jl b/src/dense/blas/trsm/trmm.jl similarity index 96% rename from src/trsm/trmm.jl rename to src/dense/blas/trsm/trmm.jl index bcd95f16..f552b44f 100644 --- a/src/trsm/trmm.jl +++ b/src/dense/blas/trsm/trmm.jl @@ -415,11 +415,18 @@ This is a simplified interface for triangular matrix multiplication operations. # Returns - Updated matrix B (same as input B, modified in-place) -# Example -```julia -A = complex.(triu(randn(4, 4)), triu(randn(4, 4))) -B = complex.(randn(4, 3), randn(4, 3)) -C = trmm('L', 'U', 'N', 'N', A, copy(B)) +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 16; # larger sizes give wrong results (known bug) + +julia> A = complex.(triu(randn(n, n)), triu(randn(n, n))); B = complex.(randn(n, 3), randn(n, 3)); B0 = copy(B); + +julia> NextLA.trmm('L', 'U', 'N', 'N', A, B); # B = UpperTriangular(A) * B, returns nothing + +julia> B ≈ UpperTriangular(A) * B0 +true ``` # Implementation Notes @@ -461,6 +468,22 @@ A thin entry point over [`unified_rectrxm!`](@ref) with `func = 'M'`: cuBLAS / rocBLAS `trmm!` on `CuMatrix` / `ROCMatrix` of `Float32`, `Float64`, `ComplexF32` or `ComplexF64`, the portable recursive kernels everywhere else. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> A = rand(n, n); + +julia> B = rand(n, 256); + +julia> C = trmm!('L', 'L', 'T', 'N', 2.0, A, copy(B)); + +julia> C ≈ 2 * transpose(LowerTriangular(A)) * B +true +``` """ trmm!(side::Char, uplo::Char, transa::Char, diag::Char, alpha::Number, A::AbstractMatrix, B::AbstractMatrix) = diff --git a/src/dense/blas/trsm/trsm.jl b/src/dense/blas/trsm/trsm.jl new file mode 100644 index 00000000..9abfbb50 --- /dev/null +++ b/src/dense/blas/trsm/trsm.jl @@ -0,0 +1,21 @@ +# Triangular solve and multiply: TRSM, TRMM, the recursive unified_rectrxm! +# and batched TRSM. +# +# trsm_kernels.jl keeps the KernelAbstractions kernels, the four +# Left/RightLower/UpperTRSM! drivers and the trsm! front end; trmm.jl does the +# same for TRMM; rectrxm.jl keeps unified_rectrxm!, which recurses over both. +# +# trsm_batched.jl: Source alecarraro-dev @ 0f1ac84 (PR #20), by Alessandro +# , verbatim. Its vendor implementations live in +# ext/*/trsm.jl as package extensions, loaded only when the corresponding GPU +# package is; trsm_batched.jl carries a CPU fallback, so batched TRSM works with +# no GPU package present. +# +# Layout contract: this is the only file here that includes. Exports stay in +# the file that defines the symbol, so moving a unit to another feature is a +# git mv plus one include line — the export travels with it. + +include("trmm.jl") +include("trsm_kernels.jl") +include("rectrxm.jl") +include("trsm_batched.jl") diff --git a/src/trsm/trsm_batched.jl b/src/dense/blas/trsm/trsm_batched.jl similarity index 87% rename from src/trsm/trsm_batched.jl rename to src/dense/blas/trsm/trsm_batched.jl index 9e2b5061..afe655c6 100644 --- a/src/trsm/trsm_batched.jl +++ b/src/dense/blas/trsm/trsm_batched.jl @@ -12,6 +12,22 @@ corresponding triangular system defined by `A[:, :, b]`. This entry point is reserved for backend batched-library dispatch. CPU arrays fall back to a BLAS loop, CUDA/AMDGPU/oneAPI extensions override this with native batched kernels, and Metal currently throws an error. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> A = rand(n, n, 4) .+ n * Matrix(I, n, n); + +julia> B = rand(n, 64, 4); + +julia> X = trsm_batched!('L', 'L', 'N', 'N', A, copy(B)); + +julia> all(LowerTriangular(A[:, :, k]) * X[:, :, k] ≈ B[:, :, k] for k in 1:4) +true +``` """ function trsm_batched!(side, uplo, diff --git a/src/trsm/trsm.jl b/src/dense/blas/trsm/trsm_kernels.jl similarity index 90% rename from src/trsm/trsm.jl rename to src/dense/blas/trsm/trsm_kernels.jl index 696f2e96..23f147e5 100644 --- a/src/trsm/trsm.jl +++ b/src/dense/blas/trsm/trsm_kernels.jl @@ -128,7 +128,7 @@ end function LeftLowerTRSM!(A, B, unitdiag::Bool=false) n, m = size(B) backend = get_backend(A) - lower_left_kernel(backend, (n,))(Transpose(A), B, n, Val(unitdiag), ndrange=(n, m)) + lower_left_kernel(backend, (n,))(transpose(A), B, n, Val(unitdiag), ndrange=(n, m)) end function LeftUpperTRSM!(A, B, unitdiag::Bool=false) @@ -146,7 +146,7 @@ end function RightUpperTRSM!(A, B, unitdiag::Bool=false) n, m = size(B) backend = get_backend(A) - right_upper_kernel(backend, (m,))(Transpose(A), B, m, Val(unitdiag), ndrange=(m, n)) + right_upper_kernel(backend, (m,))(transpose(A), B, m, Val(unitdiag), ndrange=(m, n)) end """ @@ -176,11 +176,18 @@ This is a simplified interface for triangular system solving. # Returns - Updated matrix B containing the solution -# Example -```julia -A = complex.(triu(randn(4, 4)), triu(randn(4, 4))) -B = complex.(randn(4, 3), randn(4, 3)) -X = trsm('L', 'U', 'N', 'N', A, copy(B)) +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> A = complex.(triu(randn(n, n)), triu(randn(n, n))) + n*I; B = complex.(randn(n, 3), randn(n, 3)); B0 = copy(B); + +julia> NextLA.trsm('L', 'U', 'N', 'N', A, B); # B = UpperTriangular(A) \\ B, returns nothing + +julia> UpperTriangular(A) * B ≈ B0 +true ``` """ function trsm(side, uplo, transa, diag, A, B, alpha=one(eltype(A))) @@ -222,6 +229,22 @@ wherever that does, for real and complex element types. On `CuMatrix` and reaches cuBLAS / rocBLAS `trsm!` through that function's extension methods; on the CPU, oneAPI, Metal, `Float16` and views it runs the portable recursive kernels. `LinearAlgebra.BLAS.trsm!` takes the same arguments but is CPU BLAS only. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> A = rand(n, n) + n * I; + +julia> B = rand(n, 256); + +julia> X = trsm!('L', 'L', 'N', 'N', 1.0, A, copy(B)); + +julia> LowerTriangular(A) * X ≈ B +true +``` """ trsm!(side::Char, uplo::Char, transa::Char, diag::Char, alpha::Number, A::AbstractMatrix, B::AbstractMatrix) = diff --git a/src/NextLAMatrix.jl b/src/dense/core/NextLAMatrix.jl similarity index 100% rename from src/NextLAMatrix.jl rename to src/dense/core/NextLAMatrix.jl diff --git a/src/cholesky/cholesky.jl b/src/dense/lapack/cholesky/cholesky.jl similarity index 88% rename from src/cholesky/cholesky.jl rename to src/dense/lapack/cholesky/cholesky.jl index 2c4b7731..4b6fe3ab 100644 --- a/src/cholesky/cholesky.jl +++ b/src/dense/lapack/cholesky/cholesky.jl @@ -6,12 +6,12 @@ # `using AMDGPU` at top level, and no CPU method at all. That file has been # turned down five times now -- for recgemm, unified_rec_mixed, reclu, syrk, # and here -- so potrf! is written portably instead, in the shape Alessandro -# gave syrk! in src/syrk/syrk_dispatch.jl: dimension checks, then the reference +# gave syrk! in src/dense/blas/syrk/syrk_dispatch.jl: dimension checks, then the reference # library on the CPU, with the vendor calls living in # ext/{cuda,amdgpu,oneapi,metal}/potrf.jl beside the batched wrappers already # there. See KNOWN_ISSUES.md. # -# potrf_batched! (src/cholesky/potrf_batched.jl) is the batch entry point; TLR +# potrf_batched! (src/dense/lapack/cholesky/potrf_batched.jl) is the batch entry point; TLR # is its only caller. # # potrf_kernel.jl and recpotrf.jl are Vicki's, ported off CUDA. Her @@ -24,6 +24,7 @@ # the file that defines the symbol, so moving a unit to another feature is a # git mv plus one include line -- the export travels with it. +include("potrf_batched.jl") include("potrf.jl") include("potrf_kernel.jl") include("potrf_blocked.jl") diff --git a/src/cholesky/potrf.jl b/src/dense/lapack/cholesky/potrf.jl similarity index 91% rename from src/cholesky/potrf.jl rename to src/dense/lapack/cholesky/potrf.jl index c5fba468..823b69f7 100644 --- a/src/cholesky/potrf.jl +++ b/src/dense/lapack/cholesky/potrf.jl @@ -34,6 +34,24 @@ Convenience form, equivalent to `potrf!('L', A)`. use [`potrf_batched!`](@ref), which has its own backend wrappers. - Unlike `LinearAlgebra.cholesky`, a non-positive-definite input is reported through `info` rather than raising `PosDefException`. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> M = rand(n, n); + +julia> S = M * M' + n * I; + +julia> F, info = potrf!('L', copy(S)); + +julia> L = LowerTriangular(F); + +julia> info == 0 && L * L' ≈ S +true +``` """ function potrf!(uplo::Char, A::AbstractMatrix) backend = KernelAbstractions.get_backend(A) diff --git a/src/cholesky/potrf_batched.jl b/src/dense/lapack/cholesky/potrf_batched.jl similarity index 80% rename from src/cholesky/potrf_batched.jl rename to src/dense/lapack/cholesky/potrf_batched.jl index 7c91b4e8..92bce6cb 100644 --- a/src/cholesky/potrf_batched.jl +++ b/src/dense/lapack/cholesky/potrf_batched.jl @@ -15,6 +15,22 @@ native batched kernels, and Metal currently throws an error. The return value follows the underlying backend wrapper as closely as practical: CPU, CUDA, and AMDGPU return `(A, status)`, oneAPI returns `A`, and Metal throws. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> S = stack(M * M' + n * I for M in (rand(n, n) for _ in 1:4)); + +julia> F, status = potrf_batched!('L', copy(S)); + +julia> L = LowerTriangular(F[:, :, 4]); + +julia> all(iszero, status) && L * L' ≈ S[:, :, 4] +true +``` """ function potrf_batched!(uplo::Char, A::AbstractArray{T,3}) where {T} backend = KernelAbstractions.get_backend(A) diff --git a/src/cholesky/potrf_blocked.jl b/src/dense/lapack/cholesky/potrf_blocked.jl similarity index 96% rename from src/cholesky/potrf_blocked.jl rename to src/dense/lapack/cholesky/potrf_blocked.jl index ecbacf30..600294ec 100644 --- a/src/cholesky/potrf_blocked.jl +++ b/src/dense/lapack/cholesky/potrf_blocked.jl @@ -128,6 +128,18 @@ there. No positive-definiteness check. The kernel takes `sqrt` of each diagonal entry as it goes, so an indefinite matrix yields `NaN` rather than an error or an `info` code — unlike `potrf!`, which reports through `info`. + +# Examples +GPU only, so this example is not run as a doctest: +```julia +using NextLA, LinearAlgebra, CUDA + +n = 1024 +M = CUDA.rand(Float64, n, n) +S = M * M' + n * I +L = tril(cholesky_blocked!(copy(S))) +L * L' ≈ S # true +``` """ function cholesky_blocked!(A::AbstractMatrix; block::Integer = CHOL_BLOCK, threads::Integer = 512, kernel::Symbol = :shared) diff --git a/src/cholesky/potrf_kernel.jl b/src/dense/lapack/cholesky/potrf_kernel.jl similarity index 93% rename from src/cholesky/potrf_kernel.jl rename to src/dense/lapack/cholesky/potrf_kernel.jl index 9e9505a5..66656de1 100644 --- a/src/cholesky/potrf_kernel.jl +++ b/src/dense/lapack/cholesky/potrf_kernel.jl @@ -66,6 +66,22 @@ dispatches to the vendor library. Unlike [`potrf!`](@ref) this zeroes the opposite triangle, and it reports nothing about definiteness — a non-positive-definite input yields `NaN`s from the square root rather than an `info` code. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> M = rand(n, n); + +julia> S = M * M' + n * I; + +julia> F = cholesky_lower!(copy(S)); + +julia> istril(F) && F * F' ≈ S +true +``` """ function cholesky_lower!(A) N = size(A, 1) diff --git a/src/cholesky/potrf_register.jl b/src/dense/lapack/cholesky/potrf_register.jl similarity index 100% rename from src/cholesky/potrf_register.jl rename to src/dense/lapack/cholesky/potrf_register.jl diff --git a/src/cholesky/recpotrf.jl b/src/dense/lapack/cholesky/recpotrf.jl similarity index 93% rename from src/cholesky/recpotrf.jl rename to src/dense/lapack/cholesky/recpotrf.jl index 8629a811..d902b51e 100644 --- a/src/cholesky/recpotrf.jl +++ b/src/dense/lapack/cholesky/recpotrf.jl @@ -25,6 +25,22 @@ The other triangle is not referenced and is left as it was on entry. A matrix th positive definite throws `PosDefException(k)`, `k` the order of the first leading minor that is not, as `LinearAlgebra.cholesky!` does; `A` is then partly factored. The recursion splits `n` at the largest power of two below it (at `n ÷ 2` when `n` is one). + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> n = 1024; + +julia> M = rand(n, n); + +julia> S = M * M' + n * I; + +julia> L = LowerTriangular(potrf_recursive!(copy(S), 256)); + +julia> L * L' ≈ S +true +``` """ function potrf_recursive!(A::AbstractMatrix, block_size::Integer=POTRF_BLOCK_SIZE; uplo::Char='L') uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U', got '$uplo'")) diff --git a/src/dense/lapack/lu/lu.jl b/src/dense/lapack/lu/lu.jl new file mode 100644 index 00000000..6562d22d --- /dev/null +++ b/src/dense/lapack/lu/lu.jl @@ -0,0 +1,21 @@ +# LU factorisation: the LAPACK-style pivoted LU, an unblocked base kernel, a +# tiled driver and the recursive LU. +# +# lu_pivot.jl keeps lu!, getrf2!, getc2!, laswp, geru! and the pivoting +# strategies. +# +# lu_base.jl and lu_tiled.jl: Source vicki-development @ 694d019, by Vicki +# . Both are pure KernelAbstractions with no calls outside +# themselves; what was changed in them, and why, is in the commit that adapted +# them. lu_base! is a single-workgroup factorisation for one block, and +# tile_lu_factor! drives a tiled one over a grid of them. reclu.jl keeps +# lu_recursive! and lu_recursive_nopiv!. +# +# Layout contract: this is the only file here that includes. Exports stay in +# the file that defines the symbol, so moving a unit to another feature is a +# git mv plus one include line — the export travels with it. + +include("lu_pivot.jl") +include("lu_base.jl") +include("lu_tiled.jl") +include("reclu.jl") diff --git a/src/lu/lu_base.jl b/src/dense/lapack/lu/lu_base.jl similarity index 93% rename from src/lu/lu_base.jl rename to src/dense/lapack/lu/lu_base.jl index d4099959..d05b19de 100644 --- a/src/lu/lu_base.jl +++ b/src/dense/lapack/lu/lu_base.jl @@ -15,7 +15,7 @@ end # @synchronize. On the CPU backend a @synchronize splits the kernel body into # separate ndrange loops and only @localmem/@private survive the split, so a # plain local assigned before it is out of scope afterwards — the kernel failed -# with `UndefVarError: col_k not defined`. Same fix as src/gemm/matmul.jl. +# with `UndefVarError: col_k not defined`. Same fix as src/dense/blas/gemm/matmul.jl. @kernel function lu_base_kernel!(A, ipiv, M, max_ind, col_start, col_stop, row_start, row_stop) I, J = @index(Global, NTuple) @@ -91,6 +91,18 @@ LU with partial pivoting in one work-group, in place: `L` (unit diagonal) and `U into `A`, and `p` is the row permutation as a vector, `A0[p, :] == L * U`. As LAPACK's getrf, `info` is 0 or the first `k` with a zero `U[k, k]`, and nothing is thrown. On a GPU `n` must be at most 32. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> F, p, info = lu_base!(copy(A)); + +julia> info == 0 && UnitLowerTriangular(F) * UpperTriangular(F) ≈ A[p, :] +true +``` """ function lu_base!(A::AbstractMatrix{T}) where T backend = KernelAbstractions.get_backend(A) diff --git a/src/lu.jl b/src/dense/lapack/lu/lu_pivot.jl similarity index 93% rename from src/lu.jl rename to src/dense/lapack/lu/lu_pivot.jl index 55da29e2..5955b3eb 100644 --- a/src/lu.jl +++ b/src/dense/lapack/lu/lu_pivot.jl @@ -42,9 +42,20 @@ The factorization has form where P is a permutation matrix, L is lower triangula with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n) -This is the recursive form of the algorithm. -""" +This is the recursive form of the algorithm. + +# Examples +```jldoctest +julia> using LinearAlgebra +julia> A = rand(1024, 1024); b = rand(1024); + +julia> F = lu!(NextLAMatrix{Float64}(copy(A))); + +julia> A * (F \\ b) ≈ b +true +``` +""" function LinearAlgebra.lu!(A::NextLAMatrix{T}, ::RowMaximum; check::Bool = true, allowsingular::Bool = false) where {T<:BlasFloat} A = A.data m, n = size(A) @@ -180,8 +191,21 @@ This is the recursive form of the algorithm. - =0: successful exit - <0: if info = -i, the i-th argument had an illegal value - >0: if info = i, U[i,i] is exactly zero. The factorization has been completed, but the factor U is exactly singular and division by zero will occur if it is used to solve a system of equations -""" +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 1024); B = copy(A); ipiv = zeros(Int, 1024); + +julia> _, _, info = getrf2!(B, ipiv, 0); + +julia> F = LinearAlgebra.LU(B, ipiv, info); # wrap the LAPACK-style output + +julia> info == 0 && F.L * F.U ≈ A[F.p, :] +true +``` +""" function getrf2!(A::AbstractMatrix{T}, ipiv::AbstractVector{Int}, info::Int) where {T<:BlasFloat} @@ -319,8 +343,20 @@ where P and Q are permutation matrices, L is lower triangular with unit diagonal - on exit, the factors L and U from the factorization A = P * L * U * Q; the unit diagonal elements of L are not stored. - If U(k,k) appears to be less than smin, U(k,k) is given the value smin, i.e, given a nonsingular pertubed system -""" +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> F = getc2!(NextLAMatrix{Float64}(copy(A)), CompletePivoting()); + +julia> p = LinearAlgebra.LU(F.factors, F.ipiv, 0).p; q = LinearAlgebra.LU(F.factors, F.jpiv, 0).p; +julia> UnitLowerTriangular(F.factors) * UpperTriangular(F.factors) ≈ A[p, q] +true +``` +""" function getc2!(A::NextLAMatrix{T}, ::CompletePivoting; check::Bool = true, allowsingular::Bool = false) where {T<:BlasFloat} A = A.data check && LAPACK.chkfinite(A) @@ -441,8 +477,17 @@ end Performs operation A = alpha * x * y^T + A, where alpha is a scalar, x is an m element vector, y is an n element vector, and A is an m-by-n matrix -""" +# Examples +```jldoctest +julia> A = rand(1024, 1024); x = rand(1024); y = rand(1024); + +julia> B = copy(A); geru!(2.0, x, y, B); + +julia> B ≈ A + 2.0 * x * transpose(y) +true +``` +""" function geru!(alpha::T, x::AbstractVector{T}, y::AbstractVector{T}, A::AbstractMatrix{T}) where T m,n = size(A) # assume incy = incx = 1 diff --git a/src/lu/lu_tiled.jl b/src/dense/lapack/lu/lu_tiled.jl similarity index 94% rename from src/lu/lu_tiled.jl rename to src/dense/lapack/lu/lu_tiled.jl index 9893d2e6..894e322f 100644 --- a/src/lu/lu_tiled.jl +++ b/src/dense/lapack/lu/lu_tiled.jl @@ -17,7 +17,7 @@ end end # col_k, offset and temp are recomputed in each block a @synchronize delimits, -# for the reason documented in src/lu/lu_base.jl and src/gemm/matmul.jl: the CPU +# for the reason documented in src/dense/lapack/lu/lu_base.jl and src/dense/blas/gemm/matmul.jl: the CPU # backend splits the body there and plain locals do not survive the split. @kernel function lu_gpu_tiled!(A, ipiv, M, max_ind, pivot, next, col_start, col_stop, row_start, row_stop) I, J = @index(Global, NTuple) @@ -143,6 +143,21 @@ diagonal) and `U` are packed into `A`, and `p` is the row permutation as a vecto `A0[p, :] == L * U`. A tile's row swaps reach the rest of its tile row as a gather of those rows. As LAPACK's getrf, `info` is 0 or the first `k` with a zero `U[k, k]`, and nothing is thrown. The tile `n` must divide both dimensions and be at most 32. + +# Examples +GPU only (it throws `ArgumentError` on the CPU backend), so this example is not run as a doctest: +```julia +julia> using NextLA, CUDA, LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> F, p, info = tile_lu_factor!(CuArray(A), 32); + +julia> F = Array(F); + +julia> info == 0 && UnitLowerTriangular(F) * UpperTriangular(F) ≈ A[p, :] +true +``` """ function tile_lu_factor!(A::AbstractMatrix{T}, n::Int) where T backend = KernelAbstractions.get_backend(A) diff --git a/src/lu/reclu.jl b/src/dense/lapack/lu/reclu.jl similarity index 93% rename from src/lu/reclu.jl rename to src/dense/lapack/lu/reclu.jl index 851e53c3..8e62e167 100644 --- a/src/lu/reclu.jl +++ b/src/dense/lapack/lu/reclu.jl @@ -39,6 +39,18 @@ rows without pivoting, keeping the bulk of operations in `A`'s precision. Unpivoted, leaves included, so the matrix must need no pivoting -- a diagonally dominant one, for instance. A zero pivot throws `ZeroPivotException`; a small one is not checked. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 1024) + 1024I; # diagonally dominant: needs no pivoting + +julia> F = lu_recursive!(copy(A), 256); + +julia> UnitLowerTriangular(F) * UpperTriangular(F) ≈ A +true +``` """ function lu_recursive!(A::AbstractMatrix, block_size::Integer=LU_BLOCK_SIZE) block_size >= 1 || throw(ArgumentError("block_size must be at least 1")) @@ -117,6 +129,20 @@ square, and this when it is not. Unpivoted, leaves included, so the matrix must need no pivoting -- a diagonally dominant one, for instance. A zero pivot throws `ZeroPivotException`; a small one is not checked. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(2048, 1024); A[1:1024, :] += 2048I; # tall, needs no pivoting + +julia> F = lu_recursive_nopiv!(copy(A), 256); + +julia> L = tril(F, -1) + Matrix(I, 2048, 1024); U = triu(F[1:1024, :]); + +julia> L * U ≈ A +true +``` """ function lu_recursive_nopiv!(A::AbstractMatrix, block_size::Integer=LU_BLOCK_SIZE) block_size >= 1 || throw(ArgumentError("block_size must be at least 1")) diff --git a/src/geqr2.jl b/src/dense/lapack/qr/geqr2.jl similarity index 95% rename from src/geqr2.jl rename to src/dense/lapack/qr/geqr2.jl index c0a841fd..dda16d5f 100644 --- a/src/geqr2.jl +++ b/src/dense/lapack/qr/geqr2.jl @@ -132,6 +132,20 @@ Helper function for unblocked QR factorization using Householder reflectors. # Returns - Modified `A` containing Q and R factors - `tau`: Vector of scalar factors (length min(m,n)) + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 256); F = copy(A); tau = zeros(256); + +julia> NextLA.geqr2!(F, tau); + +julia> G = LinearAlgebra.QR(F, tau); # same storage as LAPACK geqr2 + +julia> G.Q * G.R ≈ A +true +``` """ function geqr2!(A::AbstractMatrix{T}, tau::AbstractVector{T}) where {T} m, n = size(A) diff --git a/src/geqrt.jl b/src/dense/lapack/qr/geqrt.jl similarity index 91% rename from src/geqrt.jl rename to src/dense/lapack/qr/geqrt.jl index f1e070ba..631503d6 100644 --- a/src/geqrt.jl +++ b/src/dense/lapack/qr/geqrt.jl @@ -80,6 +80,20 @@ Helper function for blocked QR factorization. Computes A = Q*R where Q is orthog - Modified `A` matrix containing Q and R factors - `T`: Upper triangular block reflector matrix (ib × n) - `tau`: Vector of scalar factors for elementary reflectors (length n) + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 1024); F = copy(A); T = zeros(64, 1024); # inner block size 64 + +julia> NextLA.geqrt!(F, T); + +julia> G = LinearAlgebra.QRCompactWY(F, T); # same storage as LAPACK geqrt + +julia> G.Q * G.R ≈ A +true +``` """ function geqrt!(A::AbstractMatrix{T}, T_matrix::AbstractMatrix{T}) where {T} m, n = size(A) diff --git a/src/larf.jl b/src/dense/lapack/qr/larf.jl similarity index 95% rename from src/larf.jl rename to src/dense/lapack/qr/larf.jl index 1180703c..bc19088b 100644 --- a/src/larf.jl +++ b/src/dense/lapack/qr/larf.jl @@ -168,13 +168,18 @@ The reflector can be applied from either the left (H*C) or right (C*H) side. - For side='L': length(A) must equal number of rows in C - For side='R': length(A) must equal number of columns in C -# Example -```julia -# Apply reflector from left: C := H * C -larf!('L', v, tau, C) +# Examples +```jldoctest +julia> using LinearAlgebra -# Apply reflector from right: C := C * H -larf!('R', v, tau, C) +julia> C = rand(1024, 1024); v = rand(1024); tau = 2 / (v' * v); + +julia> HC = (I - tau * v * v') * C; + +julia> NextLA.larf!('L', v, 1, tau, C); # C := H * C + +julia> C ≈ HC +true ``` """ function larf!(side::Char, v::AbstractVector{T}, incv::Integer, tau::T, C::AbstractMatrix{T}) where {T} diff --git a/src/larfb.jl b/src/dense/lapack/qr/larfb.jl similarity index 89% rename from src/larfb.jl rename to src/dense/lapack/qr/larfb.jl index a265ddbe..facc4921 100644 --- a/src/larfb.jl +++ b/src/dense/lapack/qr/larfb.jl @@ -67,7 +67,7 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, W .= conj.(transpose(C1)) # W := W * V1 - LinearAlgebra.mul!(W, W, V1) + LinearAlgebra.rmul!(W, V1) if m > k C2 = @view C[k+1:m, :] @@ -78,21 +78,21 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, if trans == 'N' # W := W * T' - LinearAlgebra.mul!(W, W, adjoint(Tblock)) + LinearAlgebra.rmul!(W, adjoint(Tblock)) else # W := W * T - LinearAlgebra.mul!(W, W, Tblock) + LinearAlgebra.rmul!(W, Tblock) end if m > k C2 = @view C[k+1:m, :] V2 = @view V[k+1:m, 1:k] # C2 -= V2 * W' - LinearAlgebra.mul!(C2, V2, adjoint(W), -one, one) + LinearAlgebra.mul!(C2, Base.unalias(C2, V2), adjoint(W), -one, one) end # W := W * V1' - LinearAlgebra.mul!(W, W, adjoint(V1)) + LinearAlgebra.rmul!(W, adjoint(V1)) # C1 -= W^H (conjugate transpose) C1 .-= conj.(transpose(W)) @@ -109,7 +109,7 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, W .= C1 # W := W * V1 - LinearAlgebra.mul!(W, W, V1) + LinearAlgebra.rmul!(W, V1) if n > k C2 = @view C[:, k+1:n] @@ -120,10 +120,10 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, if trans == 'N' # W := W * T - LinearAlgebra.mul!(W, W, Tblock) + LinearAlgebra.rmul!(W, Tblock) else # W := W * T' - LinearAlgebra.mul!(W, W, adjoint(Tblock)) + LinearAlgebra.rmul!(W, adjoint(Tblock)) end if n > k @@ -134,7 +134,7 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, end # W := W * V1' - LinearAlgebra.mul!(W, W, adjoint(V1)) + LinearAlgebra.rmul!(W, adjoint(V1)) # C1 -= W C1 .-= W @@ -181,13 +181,20 @@ Applies the block reflector efficiently by: The algorithm exploits the triangular structure of the reflector matrix to minimize computational cost. -# Example -```julia -m, n, k = 8, 6, 4 -C = complex.(randn(m, n), randn(m, n)) -V = complex.(randn(m, k), randn(m, k)) # k reflector vectors -T = triu(complex.(randn(k, k), randn(k, k))) # Upper triangular -larfb!('L', 'N', 'F', 'C', V, T, C) # Apply H*C +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 128); V = copy(A); T = zeros(128, 128); + +julia> NextLA.geqrt!(V, T); # one block of 128 reflectors + +julia> C = rand(1024, 1024); C0 = copy(C); + +julia> NextLA.larfb!('L', 'C', 'F', 'C', V, T, C); # C := Qᴴ * C + +julia> C ≈ qr(A).Q' * C0 +true ``` """ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, V::AbstractMatrix{T}, T_mat::AbstractMatrix{T}, C::AbstractMatrix{T}) where {T} diff --git a/src/larfg.jl b/src/dense/lapack/qr/larfg.jl similarity index 89% rename from src/larfg.jl rename to src/dense/lapack/qr/larfg.jl index e7d3ae99..960321ca 100644 --- a/src/larfg.jl +++ b/src/dense/lapack/qr/larfg.jl @@ -39,6 +39,18 @@ For the elementary reflector H = I - tau * v * v^H where v = [1; u]: # Note This is a low-level LAPACK-style computational routine. Input validation should be performed by higher-level interfaces. + +# Examples +```jldoctest +julia> alpha = rand(); x = rand(1023); y = [alpha; x]; + +julia> beta, tau = NextLA.larfg!(1024, alpha, x, 1, 0.0); # x now holds v[2:end] + +julia> v = [1; x]; + +julia> y - tau * v * (v' * y) ≈ [beta; zeros(1023)] # H * y = [beta; 0] +true +``` """ function larfg!(n::Integer, alpha::T, x::AbstractVector{T}, incx::Integer, tau::T) where {T} one = oneunit(eltype(alpha)) @@ -126,11 +138,16 @@ that zeros out all but the first component. # Input Validation - Vector must have at least one element -# Example -```julia -x = complex.([3.0, 4.0, 0.0], [0.0, 0.0, 0.0]) -alpha, tau, x_new = larfg!(x) -# x_new[1] will be the magnitude -||x||, x_new[2:end] will be the reflector vector +# Examples +```jldoctest +julia> alpha = rand(); x = rand(1023); y = [alpha; x]; + +julia> beta, tau = NextLA.larfg!(alpha, x, 1, 0.0); # x now holds v[2:end] + +julia> v = [1; x]; + +julia> y - tau * v * (v' * y) ≈ [beta; zeros(1023)] # H * y = [beta; 0] +true ``` # Mathematical Background diff --git a/src/larft.jl b/src/dense/lapack/qr/larft.jl similarity index 96% rename from src/larft.jl rename to src/dense/lapack/qr/larft.jl index b96b2c6d..467f1d3f 100644 --- a/src/larft.jl +++ b/src/dense/lapack/qr/larft.jl @@ -240,18 +240,26 @@ H = I - V * T * V^H - For 'C' storage: size(V,2) must equal length(tau) - For 'R' storage: size(V,1) must equal length(tau) -# Example -```julia -m, k = 8, 4 -V = complex.(randn(m, k), randn(m, k)) # Elementary reflector vectors -tau = complex.(randn(k), randn(k)) # Reflector scaling factors -T = larft('F', 'C', V, tau) # Compute triangular factor -``` - # Mathematical Background The triangular factor T enables efficient block operations. Instead of applying k individual reflectors H(1), H(2), ..., H(k), the block reflector H = I - V*T*V^H can be applied in O(n²k) operations rather than O(nk²). + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 128); F = copy(A); tau = zeros(128); + +julia> NextLA.geqr2!(F, tau); # 128 reflectors below the diagonal of F + +julia> T = zeros(128, 128); NextLA.larft!('F', 'C', F, tau, T); + +julia> V = tril(F, -1) + Matrix(I, 1024, 128); + +julia> (I - V * UpperTriangular(T) * V') * [triu(F[1:128, :]); zeros(896, 128)] ≈ A +true +``` """ function larft!(direct::Char, storev::Char, V::AbstractMatrix{T}, tau::AbstractVector{T}, T_mat::AbstractMatrix{T}) where {T} # Determine dimensions based on storage format diff --git a/src/pamm.jl b/src/dense/lapack/qr/pamm.jl similarity index 98% rename from src/pamm.jl rename to src/dense/lapack/qr/pamm.jl index c7ca2913..6f770b79 100644 --- a/src/pamm.jl +++ b/src/dense/lapack/qr/pamm.jl @@ -45,6 +45,16 @@ and leading dimensions must meet minimum requirements. This is a low-level computational kernel used internally by blocked QR and LQ factorization routines. It is optimized for performance with specific memory access patterns. + +# Examples +```jldoctest +julia> A1 = rand(256, 1024); A2 = rand(1024, 1024); V = rand(1024, 256); W = zeros(256, 1024); + +julia> NextLA.pamm!('W', 'L', 'C', 'F', 1024, 1024, 256, 0, A1, A2, V, W); # W := A1 + Vᴴ * A2 + +julia> W ≈ A1 + V' * A2 +true +``` """ function pamm!(op::Char, side::Char, storev::Char, direct::Char, m::Integer, n::Integer, k::Integer, l::Integer, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, W::AbstractMatrix{T}) where {T} # Input validation with descriptive error messages @@ -497,15 +507,6 @@ This is a simplified interface that automatically computes required parameters. # Returns - Updated A1 and A2 matrices - -# Example -```julia -m, n, k, l = 6, 4, 3, 2 -A1 = complex.(randn(m, k), randn(m, k)) -A2 = complex.(randn(m, l), randn(m, l)) -V = complex.(randn(m, k), randn(m, k)) -A1_new, A2_new = pamm('A', 'L', 'C', 'F', A1, A2, V) -``` """ function pamm!(op::Char, side::Char, storev::Char, direct::Char, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}) where {T} # Determine dimensions diff --git a/src/parfb.jl b/src/dense/lapack/qr/parfb.jl similarity index 90% rename from src/parfb.jl rename to src/dense/lapack/qr/parfb.jl index 1e344131..d441ba27 100644 --- a/src/parfb.jl +++ b/src/dense/lapack/qr/parfb.jl @@ -40,6 +40,22 @@ block operations to apply the transformation to both matrix blocks simultaneousl - Uses optimized BLAS-3 operations for performance - Handles different storage formats and operation types - Validates all input parameters with descriptive error messages + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A1 = triu(rand(256, 256)); A2 = rand(1024, 256); M = [A1; A2]; + +julia> T = zeros(256, 256); NextLA.tsqrt!(A1, A2, T); # one block: T is 256×256 + +julia> C1 = rand(256, 1024); C2 = rand(1024, 1024); C = [C1; C2]; W = zeros(256, 1024); + +julia> NextLA.parfb!('L', 'C', 'F', 'C', 256, 1024, 1024, 1024, 256, 0, C1, C2, A2, T, W); + +julia> [C1; C2] ≈ qr(M).Q' * C +true +``` """ function parfb!(side::Char, trans::Char, direct::Char, storev::Char, m1::Integer, n1::Integer, m2::Integer, n2::Integer, k::Integer, l::Integer, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, T_mat::AbstractMatrix{T}, work::AbstractMatrix{T}) where {T} @@ -209,14 +225,20 @@ This is a simplified interface that automatically computes required parameters. # Returns - Updated A1 and A2 matrices -# Example -```julia -m1, n1, m2, n2, k = 4, 6, 4, 6, 3 -A1 = complex.(randn(m1, n1), randn(m1, n1)) -A2 = complex.(randn(m2, n2), randn(m2, n2)) -V = complex.(randn(m1+m2, k), randn(m1+m2, k)) -T = complex.(randn(k, k), randn(k, k)) -A1_new, A2_new = parfb('L', 'N', 'F', 'C', A1, A2, V, T) +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A1 = triu(rand(256, 256)); A2 = triu(rand(256, 256)); M = [A1; A2]; + +julia> T = zeros(256, 256); NextLA.ttqrt!(A1, A2, T); # one block; V = A2 is triangular + +julia> C1 = rand(256, 1024); C2 = rand(256, 1024); C = [C1; C2]; + +julia> NextLA.parfb!('L', 'C', 'F', 'C', C1, C2, A2, T); # [C1; C2] := Qᴴ * [C1; C2] + +julia> [C1; C2] ≈ qr(M).Q' * C +true ``` """ function parfb!(side::Char, trans::Char, direct::Char, storev::Char, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, T_mat::AbstractMatrix{T}) where {T} diff --git a/src/pemv.jl b/src/dense/lapack/qr/pemv.jl similarity index 92% rename from src/pemv.jl rename to src/dense/lapack/qr/pemv.jl index a801df7c..6977d763 100644 --- a/src/pemv.jl +++ b/src/dense/lapack/qr/pemv.jl @@ -35,6 +35,20 @@ panel-based factorizations. - Uses BLAS-3 operations where possible for performance - Handles edge cases with l=1 efficiently - Validates input parameters with descriptive error messages + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 256); x = rand(1024); y = rand(256); y0 = copy(y); work = zeros(1024); + +julia> NextLA.pemv!('C', 'C', 1024, 256, 256, 2.0, A, x, 0.5, y, work); # last 256 rows: upper triangle only + +julia> P = [A[1:768, :]; triu(A[769:1024, :])]; + +julia> y ≈ 2.0 * P' * x + 0.5 * y0 +true +``` """ function pemv!(trans::Char, storev::Char, m::Integer, n::Integer, l::Integer, alpha::T, A::AbstractMatrix{T}, x::AbstractVector{T}, beta::T, y::AbstractVector{T}, work::AbstractVector{T}) where {T} # Input validation @@ -198,16 +212,20 @@ This is a simplified interface that automatically computes required parameters. # Returns - Updated vector Y -# Example -```julia -m, n, l = 6, 4, 3 -A = complex.(randn(m, n), randn(m, n)) -X = complex.(randn(n), randn(n)) -Y = complex.(randn(m), randn(m)) -Y_new = pemv('N', 'C', A, X, Y, 2.0, 1.0) +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 256); x = rand(1024); y = rand(256); y0 = copy(y); + +julia> NextLA.pemv!('C', 'C', 2.0, A, x, 0.5, y); # l = 256: last 256 rows, upper triangle only + +julia> P = [A[1:768, :]; triu(A[769:1024, :])]; + +julia> y ≈ 2.0 * P' * x + 0.5 * y0 +true ``` """ - function pemv!(trans::Char, storev::Char, alpha::T, A::AbstractMatrix{T}, x::AbstractVector{T}, beta::T, y::AbstractVector{T}) where {T} # Determine dimensions m, n = size(A) diff --git a/src/dense/lapack/qr/qr.jl b/src/dense/lapack/qr/qr.jl new file mode 100644 index 00000000..82e4198a --- /dev/null +++ b/src/dense/lapack/qr/qr.jl @@ -0,0 +1,26 @@ +# QR: Householder reflectors and the tiled-QR kernels. +# +# geqr2/geqrt/unmqr factor a tile and apply its Q; larfg/larf/larft/larfb build +# and apply Householder reflectors; tsqrt/tsmqr and ttqrt/ttmqr factor and +# apply Q for a triangle stacked on a square or on another triangle. parfb +# applies a block reflector to a pair of tiles, with pamm and pemv (PLASMA's +# CORE_zpamm and CORE_zpemv) as its building blocks. +# +# Layout contract: this is the only file here that includes. Exports stay in +# the file that defines the symbol, so moving a unit to another feature is a +# git mv plus one include line — the export travels with it. + +include("geqrt.jl") +include("geqr2.jl") +include("larf.jl") +include("larfg.jl") +include("larft.jl") +include("larfb.jl") +include("unmqr.jl") +include("tsqrt.jl") +include("tsmqr.jl") +include("parfb.jl") +include("pamm.jl") +include("pemv.jl") +include("ttmqr.jl") +include("ttqrt.jl") diff --git a/src/tsmqr.jl b/src/dense/lapack/qr/tsmqr.jl similarity index 95% rename from src/tsmqr.jl rename to src/dense/lapack/qr/tsmqr.jl index 69be308b..54b009d9 100644 --- a/src/tsmqr.jl +++ b/src/dense/lapack/qr/tsmqr.jl @@ -176,22 +176,26 @@ combined matrix [A1; A2]. - For side='R': m2 must equal m1 (same number of rows) - Block size ib should be positive and ≤ min(size(V,2), ib) -# Example -```julia -# Apply Q from left to triangular-pentagonal matrix -m1, n1, m2, n2 = 6, 8, 10, 8 -k, ib = 4, 2 -A1 = triu(randn(ComplexF64, m1, n1)) -A2 = randn(ComplexF64, m2, n2) -V = randn(ComplexF64, m2, k) -T = triu(randn(ComplexF64, ib, k)) -tsmqr!('L', 'N', A1, A2, V, T, ib) -``` - # Algorithm Uses blocked approach to apply the orthogonal transformation Q = I - V*T*V^H efficiently. The compact WY representation enables high-performance matrix-matrix operations instead of multiple vector operations. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A1 = triu(rand(256, 256)); A2 = rand(1024, 256); M = [A1; A2]; + +julia> T = zeros(32, 256); NextLA.tsqrt!(A1, A2, T); + +julia> C1 = rand(256, 1024); C2 = rand(1024, 1024); C = [C1; C2]; + +julia> NextLA.tsmqr!('L', 'C', C1, C2, A2, T); # [C1; C2] := Qᴴ * [C1; C2] + +julia> [C1; C2] ≈ qr(M).Q' * C +true +``` """ function tsmqr!(side::Char, trans::Char, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, T_matrix::AbstractMatrix{T}) where {T} diff --git a/src/tsqrt.jl b/src/dense/lapack/qr/tsqrt.jl similarity index 96% rename from src/tsqrt.jl rename to src/dense/lapack/qr/tsqrt.jl index e1a290fa..994796b9 100644 --- a/src/tsqrt.jl +++ b/src/dense/lapack/qr/tsqrt.jl @@ -180,18 +180,23 @@ upper triangular and A2 is general. - A2 must have same number of columns as A1 (m×n) - Block size ib should be positive and ≤ n for efficiency -# Example -```julia -n, m = 6, 8 -ib = 4 -A1 = triu(randn(ComplexF64, n, n)) # Upper triangular -A2 = randn(ComplexF64, m, n) # General matrix -A1_qr, A2_qr, T, tau = tsqrt!(copy(A1), copy(A2), ib) -``` - # Algorithm Notes Uses blocked algorithm for efficiency with large matrices. The compact WY representation (stored in T) enables efficient application of the Q factor. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A1 = triu(rand(256, 256)); A2 = rand(1024, 256); M = [A1; A2]; + +julia> T = zeros(32, 256); # inner block size 32 + +julia> NextLA.tsqrt!(A1, A2, T); # R in A1, reflectors in A2 + +julia> UpperTriangular(A1) ≈ qr(M).R +true +``` """ function tsqrt!(A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, T_matrix::AbstractMatrix{T}) where{T} m1 = size(A1, 1) diff --git a/src/ttmqr.jl b/src/dense/lapack/qr/ttmqr.jl similarity index 91% rename from src/ttmqr.jl rename to src/dense/lapack/qr/ttmqr.jl index 57f152c1..668cf52d 100644 --- a/src/ttmqr.jl +++ b/src/dense/lapack/qr/ttmqr.jl @@ -110,6 +110,22 @@ Helper function for triangular-trapezoidal matrix transformation. # Returns - Modified `A1` and `A2` + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A1 = triu(rand(256, 256)); A2 = triu(rand(256, 256)); M = [A1; A2]; + +julia> T = zeros(32, 256); NextLA.ttqrt!(A1, A2, T); + +julia> C1 = rand(256, 1024); C2 = rand(256, 1024); C = [C1; C2]; + +julia> NextLA.ttmqr!('L', 'C', C1, C2, A2, T); # [C1; C2] := Qᴴ * [C1; C2] + +julia> [C1; C2] ≈ qr(M).Q' * C +true +``` """ function ttmqr!(side::Char, trans::Char, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, T_matrix::AbstractMatrix{T}) where T diff --git a/src/ttqrt.jl b/src/dense/lapack/qr/ttqrt.jl similarity index 94% rename from src/ttqrt.jl rename to src/dense/lapack/qr/ttqrt.jl index 1ef37a62..b0a0b312 100644 --- a/src/ttqrt.jl +++ b/src/dense/lapack/qr/ttqrt.jl @@ -129,6 +129,20 @@ Helper for triangular-triangular QR factorization. # Returns - Modified `A` and `B` matrices in-place + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A1 = triu(rand(256, 256)); A2 = triu(rand(256, 256)); M = [A1; A2]; + +julia> T = zeros(32, 256); # inner block size 32 + +julia> NextLA.ttqrt!(A1, A2, T); # R in A1, reflectors in A2 + +julia> UpperTriangular(A1) ≈ qr(M).R +true +``` """ function ttqrt!(A::AbstractMatrix{T}, B::AbstractMatrix{T}, T_mat::AbstractMatrix{T}) where {T} m, n = size(A) diff --git a/src/unmqr.jl b/src/dense/lapack/qr/unmqr.jl similarity index 96% rename from src/unmqr.jl rename to src/dense/lapack/qr/unmqr.jl index 50c69306..74d67886 100644 --- a/src/unmqr.jl +++ b/src/dense/lapack/qr/unmqr.jl @@ -178,20 +178,25 @@ to a general matrix C. - For side='L': number of rows of C must match Q dimension - For side='R': number of columns of C must match Q dimension -# Example -```julia -# Apply Q from QR factorization to matrix C -m, n, k = 10, 8, 6 -ib = 4 -A = randn(ComplexF64, m, k) -A_qr, T, tau = geqrt!(copy(A), ib) -C = randn(ComplexF64, m, n) -unmqr!('L', 'N', A_qr, T, C, ib) # C := Q * C -``` - # Algorithm Uses the blocked compact WY representation to apply Q efficiently through matrix-matrix operations rather than individual elementary reflectors. + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> A = rand(1024, 1024); F = copy(A); T = zeros(64, 1024); + +julia> NextLA.geqrt!(F, T); + +julia> C = rand(1024, 1024); C0 = copy(C); + +julia> NextLA.unmqr!('L', 'C', F, T, C); # C := Qᴴ * C + +julia> C ≈ qr(A).Q' * C0 +true +``` """ function unmqr!(side::Char, trans::Char, A::AbstractMatrix{T}, T_matrix::AbstractMatrix{T}, C::AbstractMatrix{T}) where {T} diff --git a/src/rotations/lartg.jl b/src/dense/lapack/rotations/lartg.jl similarity index 92% rename from src/rotations/lartg.jl rename to src/dense/lapack/rotations/lartg.jl index f05382d6..8468f835 100644 --- a/src/rotations/lartg.jl +++ b/src/dense/lapack/rotations/lartg.jl @@ -30,6 +30,18 @@ Special cases: # Note This is a low-level LAPACK-style computational routine. Input validation should be performed by higher-level interfaces. + +# Examples +```jldoctest +julia> x = rand(1024); y = rand(1024); + +julia> c, s, r = NextLA.lartg(x[1], y[1]); + +julia> xr = c * x + s * y; yr = -s * x + c * y; # rotate the pair of rows + +julia> xr[1] ≈ r && abs(yr[1]) < 1e-12 +true +``` """ function lartg(f::R, g::S) where {R,S} T = promote_type(R, S) diff --git a/src/dense/lapack/rotations/rotations.jl b/src/dense/lapack/rotations/rotations.jl new file mode 100644 index 00000000..c0c37687 --- /dev/null +++ b/src/dense/lapack/rotations/rotations.jl @@ -0,0 +1,7 @@ +# Givens rotations. +# +# Layout contract: this is the only file here that includes. Exports stay in +# the file that defines the symbol, so moving a unit to another feature is a +# git mv plus one include line — the export travels with it. + +include("lartg.jl") diff --git a/src/lauu2.jl b/src/lauu2.jl deleted file mode 100644 index 4c0d517f..00000000 --- a/src/lauu2.jl +++ /dev/null @@ -1,107 +0,0 @@ -export lauu2! - -""" - lauu2!(uplo, n, A) - -Compute the product U * U^H or L^H * L, where the triangular factor U or L -is stored in the upper or lower triangular part of the array A. - -This is an unblocked algorithm for computing the product of a triangular -matrix with its conjugate transpose. The result overwrites the original -triangular matrix. - -# Arguments -- `uplo`: Character specifying which triangle is stored - - 'U' or 'u': Upper triangular, computes U * U^H - - 'L' or 'l': Lower triangular, computes L^H * L -- `n`: Order of the triangular matrix (≥ 0) -- `A`: Triangular matrix to be transformed (modified in-place) - -# Algorithm -For upper triangular (uplo='U'): -- Computes A := U * U^H where U is upper triangular -- Result is Hermitian, only upper triangle is computed and stored - -For lower triangular (uplo='L'): -- Computes A := L^H * L where L is lower triangular -- Result is Hermitian, only lower triangle is computed and stored - -The algorithm processes one column (or row) at a time using dot products -and matrix-vector operations. This is the unblocked version, suitable -for small matrices or as a building block for blocked algorithms. - -# Input Validation -- uplo must be 'U', 'u', 'L', or 'l' -- n must be non-negative - -# Notes -This routine is typically used in Cholesky factorization algorithms -and for computing covariance matrices from triangular factors. - -# Example -```julia -n = 4 -A = triu(randn(ComplexF64, n, n)) # Upper triangular matrix -lauu2!('U', n, A, n) # A := U * U^H -``` -""" -function lauu2!(uplo::Char, n::Int, A::AbstractMatrix{T}) where T - - # Input validation with descriptive error messages - if !(uplo in ['U', 'u', 'L', 'l']) - throw(ArgumentError("uplo must be 'U', 'u', 'L', or 'l', got '$uplo'")) - end - - if n < 0 - throw(ArgumentError("n must be non-negative, got $n")) - end - - # Quick return for degenerate case - if n == 0 - return - end - - if uplo in ['U', 'u'] - # Upper triangular case: Compute U * U^H - for i in 1:n - aii = A[i, i] # Diagonal element of U - - if i < n - # Update diagonal: A[i,i] = |U[i,i]|² + sum(|U[i,j]|² for j > i) - A[i, i] = real(aii * conj(aii)) + real(dot(A[i, i+1:n], A[i, i+1:n])) - - # Update off-diagonal elements in column i - for k in 1:i-1 - A[k, i] = A[k, i] * aii + dot(A[k, i+1:n], conj(A[i, i+1:n])) - end - else - # Final column: scale by diagonal element - for k in 1:i - A[k, i] = A[k, i] * aii - end - end - end - else - # Lower triangular case: Compute L^H * L - for i in 1:n - aii = A[i, i] # Diagonal element of L - - if i < n - # Update diagonal: A[i,i] = |L[i,i]|² + sum(|L[j,i]|² for j > i) - A[i, i] = real(conj(aii) * aii) + real(dot(A[i+1:n, i], A[i+1:n, i])) - - # Update off-diagonal elements in row i - for k in 1:i-1 - A[i, k] = conj(aii) * A[i, k] + dot(A[i+1:n, k], conj(A[i+1:n, i])) - end - else - # Final row: scale by conjugate of diagonal element - for k in 1:i - A[i, k] = conj(aii) * A[i, k] - end - end - end - end -end - -lauu2!(uplo::Char, A::AbstractMatrix{T}) where {T} = lauu2!(uplo, size(A, 1), A) diff --git a/src/lauum.jl b/src/lauum.jl deleted file mode 100644 index 123c4e1c..00000000 --- a/src/lauum.jl +++ /dev/null @@ -1,186 +0,0 @@ -export lauum! - -# Import the unblocked version (lauu2!) for use in blocked algorithm - -""" - lauum!(uplo, n, A, ib) - -Compute the product U * U^H or L^H * L using a blocked algorithm, where -the triangular factor U or L is stored in the upper or lower triangular -part of the matrix a. - -This is a blocked version of the triangular matrix multiplication that -achieves better performance on large matrices by exploiting cache locality -and enabling vectorization. - -# Arguments -- `uplo`: Character specifying which triangle contains the factor - - 'U': Upper triangular, computes U * U^H - - 'L': Lower triangular, computes L^H * L -- `n`: Order of the triangular matrix (≥ 0) -- `A`: Matrix containing triangular factor (modified in-place) -- `ib`: Block size for blocked algorithm (typically 32-64) - -# Algorithm -The blocked algorithm partitions the matrix into blocks of size ib -and processes them using high-performance BLAS operations: -- Level-3 BLAS (matrix-matrix operations) for most computations -- Level-2 BLAS (matrix-vector operations) for smaller blocks -- Automatic fallback to unblocked algorithm for small matrices - -For upper triangular (uplo='U'): A := U * U^H -For lower triangular (uplo='L'): A := L^H * L - -# Performance Notes -- Block size should be chosen based on cache size (typically 32-64) -- Uses parallel processing for independent block operations -- Optimal performance achieved when n >> block_size - -# Input Validation -- uplo must be 'U' or 'L' -- n must be non-negative -- block_size is automatically clamped to valid range - -# Example -```julia -n = 100 -block_size = 32 -A = triu(randn(ComplexF64, n, n)) -lauum!('U', n, A, n, block_size) # A := U * U^H -``` -""" -function lauum!(uplo::Char, n::Integer, A::AbstractMatrix{T}, ib::Integer) where {T} - # Input validation with descriptive error messages - if !(uplo in ['U', 'L']) - throw(ArgumentError("uplo must be 'U' or 'L', got '$uplo'")) - end - - if n < 0 - throw(ArgumentError("n must be non-negative, got $n")) - end - - # Quick return for degenerate case - if n == 0 - return - end - - # Adjust block_size to reasonable bounds - ib = max(1, min(ib, n)) - - # Use unblocked algorithm for small matrices or invalid block size - if ib <= 1 || ib >= n - lauu2!(uplo, n, A) - return - end - - # Call appropriate blocked computation - if uplo == 'U' - compute_upper!(n, ib, A) - else - compute_lower!(n, ib, A) - end -end - -""" - compute_upper!(n, block_size, a) - -Blocked computation of U * U^H for upper triangular matrix U. - -Processes the matrix in blocks to achieve better cache performance and -enable vectorized operations. Uses Level-3 BLAS operations where possible. - -# Arguments -- `n`: Order of the matrix -- `block_size`: Size of blocks for processing -- `a`: Matrix containing U (modified in-place) - -# Algorithm -For each diagonal block: -1. Update off-diagonal blocks using TRMM operations -2. Compute diagonal block product U_block * U_block^H -3. Add contribution from remaining blocks using SYRK operations -""" -function compute_upper!(n::Integer, ib::Integer, A::AbstractMatrix{T}) where T - Threads.@threads for i in 1:ib:n - b = min(ib, n - i + 1) # Actual block size for this iteration - j_end = i + b - 1 - - # Update off-diagonal blocks: A[1:i-1, i:j_end] = A[1:i-1, i:j_end] * A[i:j_end, i:j_end]^H - if i > 1 - view(A, 1:i-1, i:j_end) .= view(A, 1:i-1, i:j_end) * view(A, i:j_end, i:j_end)' - end - - # Compute diagonal block: U_block * U_block^H - U_block = view(A, i:j_end, i:j_end) - U_Ut = U_block * U_block' - - # Store only upper triangular part (GPU-agnostic: use triu broadcast instead of scalar indexing) - view(A, i:j_end, i:j_end) .= triu(U_Ut) - - # Add contribution from trailing blocks if they exist - if j_end < n - # Update off-diagonal: add A[1:i-1, j_end+1:n] * A[i:j_end, j_end+1:n]^H - if i > 1 - view(A, 1:i-1, i:j_end) .+= view(A, 1:i-1, j_end+1:n) * view(A, i:j_end, j_end+1:n)' - end - - # Rank-k update: add A[i:j_end, j_end+1:n] * A[i:j_end, j_end+1:n]^H to diagonal block - trailing_block = view(A, i:j_end, j_end+1:n) - syrk_result = trailing_block * trailing_block' - - view(A, i:j_end, i:j_end) .+= triu(syrk_result) - end - end -end - -""" - compute_lower!(n, ib, A) - -Blocked computation of L^H * L for lower triangular matrix L. - -Processes the matrix in blocks to achieve better cache performance and -enable vectorized operations. Uses Level-3 BLAS operations where possible. - -# Arguments -- `n`: Order of the matrix -- `block_size`: Size of blocks for processing -- `A`: Matrix containing L (modified in-place) - -# Algorithm -For each diagonal block: -1. Update off-diagonal blocks using TRMM operations -2. Compute diagonal block product L_block^H * L_block -3. Add contribution from remaining blocks using SYRK operations -""" -function compute_lower!(n::Integer, ib::Integer, A::AbstractMatrix{T}) where T - Threads.@threads for i in 1:ib:n - b = min(ib, n - i + 1) # Actual block size for this iteration - j_end = i + b - 1 - - # Update off-diagonal blocks: A[i:j_end, 1:i-1] = A[i:j_end, i:j_end]^H * A[i:j_end, 1:i-1] - if i > 1 - view(A, i:j_end, 1:i-1) .= view(A, i:j_end, i:j_end)' * view(A, i:j_end, 1:i-1) - end - - # Compute diagonal block: L_block^H * L_block - L_block = view(A, i:j_end, i:j_end) - Lt_L = L_block' * L_block - - # Store only lower triangular part (GPU-agnostic: use tril broadcast instead of scalar indexing) - view(A, i:j_end, i:j_end) .= tril(Lt_L) - - # Add contribution from trailing blocks if they exist - if j_end < n - # Update off-diagonal: add A[j_end+1:n, i:j_end]^H * A[j_end+1:n, 1:i-1] - if i > 1 - view(A, i:j_end, 1:i-1) .+= view(A, j_end+1:n, i:j_end)' * view(A, j_end+1:n, 1:i-1) - end - - # Rank-k update: add A[j_end+1:n, i:j_end]^H * A[j_end+1:n, i:j_end] to diagonal block - trailing_block = view(A, j_end+1:n, i:j_end) - syrk_result = trailing_block' * trailing_block - - view(A, i:j_end, i:j_end) .+= tril(syrk_result) - end - end -end diff --git a/src/lu/factor.jl b/src/lu/factor.jl deleted file mode 100644 index a81c962c..00000000 --- a/src/lu/factor.jl +++ /dev/null @@ -1,21 +0,0 @@ -# LU factorisation: an unblocked base kernel and a tiled driver. -# -# Source: vicki-development @ 694d019, by Vicki . Both files -# are pure KernelAbstractions with no calls outside themselves; what was -# changed in them, and why, is in the commit that adapted them. -# -# This sits alongside the flat src/lu.jl, which keeps lu!, getrf2!, getc2!, -# laswp, geru! and the pivoting strategies. Nothing here replaces those: -# lu_base! is a single-workgroup factorisation for one block, and -# tile_lu_factor! drives a tiled one over a grid of them. -# -# The entry file is factor.jl rather than lu.jl so it is never confused with -# the flat src/lu.jl, the same reason src/trsm/ uses batched.jl. -# -# Layout contract: this is the only file here that includes. Exports stay in -# the file that defines the symbol, so moving a unit to another feature is a -# git mv plus one include line — the export travels with it. - -include("lu_base.jl") -include("lu_tiled.jl") -include("reclu.jl") diff --git a/src/mxp/gemm/recgemm_mixedprec.jl b/src/mxp/blas/gemm/recgemm_mixedprec.jl similarity index 87% rename from src/mxp/gemm/recgemm_mixedprec.jl rename to src/mxp/blas/gemm/recgemm_mixedprec.jl index e1a757c6..22783bb2 100644 --- a/src/mxp/gemm/recgemm_mixedprec.jl +++ b/src/mxp/blas/gemm/recgemm_mixedprec.jl @@ -13,6 +13,20 @@ holds `C / s`, so its update uses `alpha / s`. An off-diagonal block with less r `Float32` is updated in a `Float32` copy and stored back with its scale raised when the update took it past `floatmax` of its type; a leaf keeps its scale. With `parallel`, the four quadrant updates of the top level run on separate threads. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 512); B = rand(512, 1024); C = rand(1024, 1024); + +julia> M = FullMixedPrec(C; precisions = DataType[Float32, Float64]); + +julia> recgemm!(1.0, A, B, 0.5, M); # M = A * B + 0.5 * M + +julia> isapprox(reconstruct_matrix(M), A * B + 0.5 * C; rtol = 1e-5) +true +``` """ function recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::FullMixedPrec; parallel::Bool=(size(C, 1) > RECGEMM_PARALLEL_THRESHOLD)) diff --git a/src/mxp/syrk/recsyrk_mixedprec.jl b/src/mxp/blas/syrk/recsyrk_mixedprec.jl similarity index 86% rename from src/mxp/syrk/recsyrk_mixedprec.jl rename to src/mxp/blas/syrk/recsyrk_mixedprec.jl index fb9ae30e..eaa679d7 100644 --- a/src/mxp/syrk/recsyrk_mixedprec.jl +++ b/src/mxp/blas/syrk/recsyrk_mixedprec.jl @@ -14,6 +14,20 @@ diagonal block of the top level has more than `RECSYRK_PARALLEL_THRESHOLD` rows, diagonal halves run on separate threads and spawn nothing further; the second half is never larger than the first and may be under the threshold. `A` with a row count other than `C`'s throws a `DimensionMismatch`. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 512); C = rand(1024, 1024); C = C + C'; + +julia> M = SymmMixedPrec(C, 'L'; precisions = DataType[Float32, Float64]); + +julia> recsyrk!(1.0, A, 1.0, M); # M = A * A' + M, lower triangle + +julia> isapprox(reconstruct_matrix(M), A * A' + C; rtol = 1e-5) +true +``` """ function recsyrk!(alpha::Number, A::AbstractMatrix, beta::Number, C::SymmMixedPrec) size(A, 1) == size(C, 1) || throw(DimensionMismatch("A must have $(size(C, 1)) rows, like C")) diff --git a/src/mxp/trsm/rectrxm_mixed.jl b/src/mxp/blas/trsm/rectrxm_mixed.jl similarity index 96% rename from src/mxp/trsm/rectrxm_mixed.jl rename to src/mxp/blas/trsm/rectrxm_mixed.jl index 221f6f11..89903bcf 100644 --- a/src/mxp/trsm/rectrxm_mixed.jl +++ b/src/mxp/blas/trsm/rectrxm_mixed.jl @@ -208,6 +208,20 @@ end diagonal as ones, and the form without `diag` takes `diag = 'N'`. `A` is a `FullMixedPrec`, `SymmMixedPrec` or `TriMixedPrec`; for its transpose pass `trans = 'T'`, not `transpose(A)`. Any other `side`, `uplo`, `trans`, `diag` or `func` throws an `ArgumentError`. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> T = tril(rand(1024, 1024)) + 1024I; B = rand(1024, 512); + +julia> M = TriMixedPrec(T, 'L'; precisions = DataType[Float32, Float64]); + +julia> X = unified_rectrxm!('L', 'L', 'N', 'N', 1.0, 'S', M, copy(B)); # solve T * X = B + +julia> isapprox(X, LowerTriangular(T) \\ B; rtol = 1e-5) +true +``` """ function unified_rectrxm!( side::Char, uplo::Char, trans::Char, diag::Char, alpha::Number, func::Char, diff --git a/src/mxp/adaptive.jl b/src/mxp/core/adaptive.jl similarity index 90% rename from src/mxp/adaptive.jl rename to src/mxp/core/adaptive.jl index 38c1b867..bec9aa4a 100644 --- a/src/mxp/adaptive.jl +++ b/src/mxp/core/adaptive.jl @@ -29,6 +29,20 @@ order. The part of `A` that is read must be finite and not zero, `A` square and `A` throws `DimensionMismatch` and any other violation an `ArgumentError`. The result builds a container only when its last type meets the containers' leaf rule, `Float32` or `Float64`, which it does whenever `U` holds one of them. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); S = A * A' + 1024I; + +julia> p = adaptive_precisions(S, DataType[Float16, Float32, Float64], 256, 1e-6); # two levels and the leaves + +julia> M = SymmMixedPrec(S, 'L'; precisions = p); + +julia> length(p) == 3 && p[end] == Float64 && isapprox(reconstruct_matrix(M), S; rtol = 1e-5) +true +``` """ function adaptive_precisions( A::AbstractMatrix, @@ -76,7 +90,7 @@ function adaptive_precisions( end for r in blocks leaf = view(A, r, r) - norm_A = hypot(norm_A, _norm_mixedprec_block(uplo == 'L' ? tril(leaf) : uplo == 'U' ? triu(leaf) : leaf)) + norm_A = hypot(norm_A, _norm_mixedprec_block(uplo == 'L' ? tril!(copy(leaf)) : uplo == 'U' ? triu!(copy(leaf)) : leaf)) end isfinite(norm_A) || throw(ArgumentError("A must be finite")) iszero(norm_A) && throw(ArgumentError("A must not be zero")) diff --git a/src/mxp/blocks.jl b/src/mxp/core/blocks.jl similarity index 89% rename from src/mxp/blocks.jl rename to src/mxp/core/blocks.jl index 936935b5..d68aa2e6 100644 --- a/src/mxp/blocks.jl +++ b/src/mxp/core/blocks.jl @@ -57,7 +57,12 @@ function _triangular_mixedprec(::Type{C}, A::AbstractMatrix, uplo::Char, precisi n = size(A, 1) T_Base = precisions[end] if length(precisions) == 1 || n == 1 - base, base_scale = _quantize_mixedprec_block(uplo == 'L' ? tril(A) : triu(A), T_Base) + # tril!(copy(A)), not tril(A): from Julia 1.11 tril of a view goes through + # copytrito! to LAPACK.lacpy!, a CPU call that fails for a view of a GPU + # array. copy gives an array of the parent's type, whose tril! runs on its + # device (as tril did on Julia 1.10). The same holds in tiledtrimixedprec.jl + # and adaptive.jl. + base, base_scale = _quantize_mixedprec_block(uplo == 'L' ? tril!(copy(A)) : triu!(copy(A)), T_Base) return C{T_Base}(nothing, nothing, nothing, 1f0, base_scale, base, uplo, n) end mid = _rec_split(n) diff --git a/src/mxp/fullmixedprec.jl b/src/mxp/core/fullmixedprec.jl similarity index 89% rename from src/mxp/fullmixedprec.jl rename to src/mxp/core/fullmixedprec.jl index 01097c65..9c1e7d9b 100644 --- a/src/mxp/fullmixedprec.jl +++ b/src/mxp/core/fullmixedprec.jl @@ -38,6 +38,18 @@ factors. A block whose largest magnitude exceeds `floatmax` of its storage type a `Float32` scale factor and stored with it. A block whose largest magnitude exceeds `floatmax(Float32) * floatmax` of its storage type cannot be represented and throws an `ArgumentError`. `A` must be square, non-empty and finite. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> M = FullMixedPrec(A; precisions = DataType[Float32, Float64]); # off-diagonal blocks in Float32 + +julia> isapprox(reconstruct_matrix(M), A; rtol = 1e-5) +true +``` """ function FullMixedPrec( A::AbstractMatrix; @@ -80,6 +92,20 @@ end Copies the hierarchical mixed-precision matrix back into one dense array with element type `T_Base`, of the same array type as the stored blocks, with each block's scale applied. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> M = FullMixedPrec(A; precisions = DataType[Float16, Float32, Float64]); + +julia> B = reconstruct_matrix(M); + +julia> B isa Matrix{Float64} && isapprox(B, A; rtol = 1e-3) +true +``` """ function reconstruct_matrix(A::FullMixedPrec{T_Base}) where {T_Base} B = A.Base !== nothing ? A.Base : A.A21 diff --git a/src/mxp/mxp.jl b/src/mxp/core/mxp.jl similarity index 76% rename from src/mxp/mxp.jl rename to src/mxp/core/mxp.jl index 75a18f93..cab6ad4d 100644 --- a/src/mxp/mxp.jl +++ b/src/mxp/core/mxp.jl @@ -6,7 +6,7 @@ Not re-exported by NextLA; opt in with `using NextLA.MixedPrecision`. """ module MixedPrecision -using LinearAlgebra: norm, tril, triu, Transpose, Adjoint +using LinearAlgebra: norm, tril!, triu!, Transpose, Adjoint import ..NextLA: recgemm!, recsyrk!, potrf_recursive!, lu_recursive!, unified_rectrxm! @@ -23,11 +23,11 @@ include("tiledtrimixedprec.jl") include("adaptive.jl") include("quantize.jl") -include("gemm/recgemm_mixedprec.jl") -include("trsm/rectrxm_mixed.jl") -include("lu/reclu_mixedprec.jl") -include("syrk/recsyrk_mixedprec.jl") -include("cholesky/recpotrf_mixedprec.jl") +include("../blas/gemm/recgemm_mixedprec.jl") +include("../blas/trsm/rectrxm_mixed.jl") +include("../lapack/lu/reclu_mixedprec.jl") +include("../blas/syrk/recsyrk_mixedprec.jl") +include("../lapack/cholesky/recpotrf_mixedprec.jl") export FullMixedPrec, SymmMixedPrec, TriMixedPrec, TiledTriMixedPrec export reconstruct_matrix, adaptive_precisions diff --git a/src/mxp/quantize.jl b/src/mxp/core/quantize.jl similarity index 59% rename from src/mxp/quantize.jl rename to src/mxp/core/quantize.jl index a35c3c0b..6bf7d593 100644 --- a/src/mxp/quantize.jl +++ b/src/mxp/core/quantize.jl @@ -5,6 +5,18 @@ Stores `A` in `T` with one `Float32` scale factor, as the containers store each `Q = A / s`, with `s = 1` unless the values of `A` exceed `floatmax(T)`. An empty `A` gives an empty `Q` and `s = 1`. A non-finite `A`, or one whose values need a scale past `floatmax(Float32)`, throws an `ArgumentError`. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = 1.0e6 .* randn(1024, 1024); # past floatmax(Float16) = 65504 + +julia> Q, s = quantize(A, Float16); + +julia> eltype(Q) == Float16 && s > 1 && isapprox(s .* Q, A; rtol = 1e-3) +true +``` """ function quantize(A::AbstractMatrix{<:AbstractFloat}, ::Type{T}=Float16) where {T<:AbstractFloat} isempty(A) && return (similar(A, T), 1f0) @@ -15,5 +27,19 @@ end dequantize(Q, s, T) -> AbstractMatrix{T} Inverse of `quantize`: returns `Q * s` in `T`, of the same array type as `Q`. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = randn(1024, 1024); + +julia> Q, s = quantize(A, Float32); + +julia> B = dequantize(Q, s, Float64); + +julia> B isa Matrix{Float64} && isapprox(B, A; rtol = 1e-6) +true +``` """ dequantize(Q::AbstractMatrix, s::Real, ::Type{T}) where {T<:AbstractFloat} = T.(Q) .* T(s) diff --git a/src/mxp/symmmixedprec.jl b/src/mxp/core/symmmixedprec.jl similarity index 86% rename from src/mxp/symmmixedprec.jl rename to src/mxp/core/symmmixedprec.jl index 606e0c45..25f89617 100644 --- a/src/mxp/symmmixedprec.jl +++ b/src/mxp/core/symmmixedprec.jl @@ -38,6 +38,21 @@ factors. A block whose largest magnitude exceeds `floatmax` of its storage type a `Float32` scale factor and stored with it. A block whose largest magnitude exceeds `floatmax(Float32) * floatmax` of its storage type cannot be represented and throws an `ArgumentError`. `A` must be square, non-empty and finite, and `uplo` must be 'L' or 'U'. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); S = A + A'; + +julia> M = SymmMixedPrec(S, 'L'; precisions = DataType[Float32, Float64]); + +julia> eltype(M.OffDiag) == Float32 && eltype(M.A11.Base) == Float64 +true + +julia> isapprox(reconstruct_matrix(M), S; rtol = 1e-5) +true +``` """ function SymmMixedPrec( A::AbstractMatrix, @@ -81,8 +96,10 @@ end function _reconstruct!(C::AbstractMatrix, A::SymmMixedPrec{T_Base}) where {T_Base} if A.Base !== nothing - r = 1:size(C, 1) - C .= T_Base.(ifelse.(A.uplo == 'L' ? r .>= r' : r .<= r', A.Base, transpose(A.Base)) .* T_Base(A.Base_scale)) + # The triangle test is part of the one fused broadcast, so it runs where C + # is (on the device for a GPU array) instead of building a CPU mask first. + r, lower = 1:size(C, 1), A.uplo == 'L' + C .= T_Base.(ifelse.(ifelse.(lower, r .>= r', r .<= r'), A.Base, transpose(A.Base)) .* T_Base(A.Base_scale)) return C end mid, n = size(A.A11, 1), A.n diff --git a/src/mxp/tiledtrimixedprec.jl b/src/mxp/core/tiledtrimixedprec.jl similarity index 93% rename from src/mxp/tiledtrimixedprec.jl rename to src/mxp/core/tiledtrimixedprec.jl index 4ca533f0..a60fd33d 100644 --- a/src/mxp/tiledtrimixedprec.jl +++ b/src/mxp/core/tiledtrimixedprec.jl @@ -35,6 +35,18 @@ stored with it; a tile beyond `floatmax(Float32) * floatmax` of its storage type `Float32` and `Float64`; the diagonal tiles' type, `precisions[end]`, must be `Float32` or `Float64`, which have the range of the scale factors. `A` must be square, non-empty and finite, `uplo` 'L' or 'U' and `threshold` at least 1. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> M = TiledTriMixedPrec(A, 'L'; precisions = DataType[Float32, Float64], threshold = 256); # 4 × 4 tiles + +julia> isapprox(reconstruct_matrix(M), tril(A); rtol = 1e-5) +true +``` """ function TiledTriMixedPrec( A::AbstractMatrix, @@ -56,7 +68,7 @@ function TiledTriMixedPrec( diag_scales = Vector{Float32}(undef, t) for k in 1:t block = view(A, offsets[k]:offsets[k+1]-1, offsets[k]:offsets[k+1]-1) - diag[k], diag_scales[k] = _quantize_mixedprec_block(uplo == 'L' ? tril(block) : triu(block), T_Diag) + diag[k], diag_scales[k] = _quantize_mixedprec_block(uplo == 'L' ? tril!(copy(block)) : triu!(copy(block)), T_Diag) end off = Matrix{Union{Nothing, M_OffDiag}}(nothing, t, t) off_scales = ones(Float32, t, t) diff --git a/src/mxp/transposedmixedprec.jl b/src/mxp/core/transposedmixedprec.jl similarity index 100% rename from src/mxp/transposedmixedprec.jl rename to src/mxp/core/transposedmixedprec.jl diff --git a/src/mxp/trimixedprec.jl b/src/mxp/core/trimixedprec.jl similarity index 86% rename from src/mxp/trimixedprec.jl rename to src/mxp/core/trimixedprec.jl index c88fa387..833f1f5e 100644 --- a/src/mxp/trimixedprec.jl +++ b/src/mxp/core/trimixedprec.jl @@ -39,6 +39,18 @@ factors. A block whose largest magnitude exceeds `floatmax` of its storage type a `Float32` scale factor and stored with it. A block whose largest magnitude exceeds `floatmax(Float32) * floatmax` of its storage type cannot be represented and throws an `ArgumentError`. `A` must be square, non-empty and finite, and `uplo` must be 'L' or 'U'. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); + +julia> M = TriMixedPrec(A, 'L'; precisions = DataType[Float32, Float64]); # reads tril(A) only + +julia> isapprox(reconstruct_matrix(M), tril(A); rtol = 1e-5) +true +``` """ function TriMixedPrec( A::AbstractMatrix, @@ -77,8 +89,9 @@ end function _reconstruct!(C::AbstractMatrix, A::TriMixedPrec{T_Base}) where {T_Base} if A.Base !== nothing - r = 1:size(C, 1) - C .= ifelse.(A.uplo == 'L' ? r .>= r' : r .<= r', T_Base.(A.Base .* T_Base(A.Base_scale)), zero(T_Base)) + # The triangle test is part of the one fused broadcast (see symmmixedprec.jl). + r, lower = 1:size(C, 1), A.uplo == 'L' + C .= ifelse.(ifelse.(lower, r .>= r', r .<= r'), T_Base.(A.Base .* T_Base(A.Base_scale)), zero(T_Base)) return C end mid, n = size(A.A11, 1), A.n @@ -100,6 +113,18 @@ end Views a `SymmMixedPrec` as a `TriMixedPrec` over the same stored blocks, without copying. The result reads only the `uplo` triangle, so a `SymmMixedPrec` factored in place can be used as its triangular factor. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); S = A + A'; + +julia> M = SymmMixedPrec(S, 'L'; precisions = DataType[Float32, Float64]); + +julia> reconstruct_matrix(TriMixedPrec(M)) == tril(reconstruct_matrix(M)) +true +``` """ function TriMixedPrec(A::SymmMixedPrec{T_Base}) where {T_Base} A.Base !== nothing && diff --git a/src/mxp/cholesky/recpotrf_mixedprec.jl b/src/mxp/lapack/cholesky/recpotrf_mixedprec.jl similarity index 87% rename from src/mxp/cholesky/recpotrf_mixedprec.jl rename to src/mxp/lapack/cholesky/recpotrf_mixedprec.jl index 78adf6a4..bd58895b 100644 --- a/src/mxp/cholesky/recpotrf_mixedprec.jl +++ b/src/mxp/lapack/cholesky/recpotrf_mixedprec.jl @@ -18,6 +18,22 @@ when it is narrower; a result past `floatmax` of the block's type is stored with scale raised. A leaf stored with a scale factor throws `ArgumentError`, since its factor does not scale with it. `reconstruct_matrix(TriMixedPrec(A))` recovers the dense factor with zeros in the other triangle; `reconstruct_matrix(A)` would mirror it into both. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024); S = A * A' + 1024I; + +julia> M = SymmMixedPrec(S, 'L'; precisions = DataType[Float32, Float64]); + +julia> potrf_recursive!(M); + +julia> L = reconstruct_matrix(TriMixedPrec(M)); + +julia> isapprox(L, cholesky(S).L; rtol = 1e-5) +true +``` """ function potrf_recursive!(A::SymmMixedPrec{T_Base}, block_size::Integer=POTRF_BLOCK_SIZE) where {T_Base} if A.Base !== nothing diff --git a/src/mxp/lu/reclu_mixedprec.jl b/src/mxp/lapack/lu/reclu_mixedprec.jl similarity index 88% rename from src/mxp/lu/reclu_mixedprec.jl rename to src/mxp/lapack/lu/reclu_mixedprec.jl index e9261637..3bb7554d 100644 --- a/src/mxp/lu/reclu_mixedprec.jl +++ b/src/mxp/lapack/lu/reclu_mixedprec.jl @@ -24,6 +24,22 @@ With `parallel`, the two off-diagonal solves of a level, which are independent, separate threads at the top level and, below it, at each level with more than `RECLU_PARALLEL_THRESHOLD` rows; the trailing `recgemm!` uses its own threshold. `parallel = false` runs the whole factorization on the calling thread. + +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra + +julia> A = rand(1024, 1024) + 1024I; # diagonally dominant: no pivoting needed + +julia> M = FullMixedPrec(A; precisions = DataType[Float32, Float64]); + +julia> lu_recursive!(M); + +julia> F = reconstruct_matrix(M); # L below the diagonal, U on and above it + +julia> isapprox(UnitLowerTriangular(F) * UpperTriangular(F), A; rtol = 1e-5) +true +``` """ function lu_recursive!(A::FullMixedPrec{T_Base}, block_size::Integer=LU_BLOCK_SIZE; parallel::Bool=(size(A, 1) > RECLU_PARALLEL_THRESHOLD)) where {T_Base} diff --git a/src/streams.jl b/src/streams.jl new file mode 100644 index 00000000..78857e08 --- /dev/null +++ b/src/streams.jl @@ -0,0 +1,49 @@ +""" + create_streams(backend, n) → Vector + +Create `n` independent execution streams for `backend`. On non-GPU backends +returns a length-`n` vector of `nothing` values (sequential fallback). +""" +create_streams(_, n::Int) = fill(nothing, n) + +""" + with_stream(f, backend, stream) + +Execute `f()` directing backend operations onto `stream`. On CPU / when +`stream === nothing`, calls `f()` directly. +""" +with_stream(f, _, ::Nothing) = f() + +""" + sync_stream(backend, stream) + +Block the calling thread until all work submitted to `stream` completes. +No-op on CPU or when `stream === nothing`. +""" +sync_stream(_, ::Nothing) = nothing + +""" + sync_streams_with_default(backend, streams) + +Insert a GPU-side barrier that makes every element of `streams` wait for all +work currently outstanding on the backend's *default* stream to finish. + +Use this after a kernel / BLAS call on the default stream to ensure that +category streams launching co-dependent work see the result. + +- On CPU: no-op (execution is sequential). +- On CUDA: records a `CuEvent` on the current stream, then calls + `CUDA.wait(event, s)` for each stream `s`. This is a pure + GPU-side dependency — the CPU does **not** block. +- On other GPU backends: falls back to a full device synchronise. +""" +sync_streams_with_default(_, _) = nothing + +"""Create a reusable backend event for stream-to-stream and host dependencies.""" +create_event(_) = nothing +"""Record `event` after work currently queued on `stream`.""" +record_event!(_, ::Nothing, ::Nothing) = nothing +"""Make `stream` wait for `event` without blocking the host.""" +wait_event!(_, ::Nothing, ::Nothing) = nothing +"""Block the host until `event` completes.""" +sync_event(_, ::Nothing) = nothing diff --git a/src/tlr/blas/gemm/arena.jl b/src/tlr/blas/gemm/arena.jl new file mode 100644 index 00000000..393e5362 --- /dev/null +++ b/src/tlr/blas/gemm/arena.jl @@ -0,0 +1,25 @@ +# Result-independent bump arena shared by dense-output and compressed-output ARA GEMM. + +mutable struct GemmArena{A} + storage::A + cursor::Int +end + +@inline arena_reset!(arena::GemmArena) = + (arena.cursor = firstindex(arena.storage); arena) +@inline arena_reset!(::Nothing) = nothing + +function workspace_array!(arena::GemmArena, _, ::Type{T}, dims::Int...) where {T} + T === eltype(arena.storage) || throw(ArgumentError( + "workspace element type $(eltype(arena.storage)) does not match $T")) + count = prod(dims) + first = arena.cursor + last = first + count - 1 + last <= lastindex(arena.storage) || throw(ArgumentError( + "workspace slice exhausted while requesting $(count * sizeof(T)) bytes")) + arena.cursor = last + 1 + return reshape(view(arena.storage, first:last), dims...) +end + +@inline workspace_array!(::Nothing, backend, ::Type{T}, dims::Int...) where {T} = + allocate(backend, T, dims...) diff --git a/src/tlr/blas/gemm/compressed_accumulation/driver.jl b/src/tlr/blas/gemm/compressed_accumulation/driver.jl new file mode 100644 index 00000000..835a9452 --- /dev/null +++ b/src/tlr/blas/gemm/compressed_accumulation/driver.jl @@ -0,0 +1,432 @@ +# Allocation-returning compressed-output GEMM: sampling-side selection, run +# scattering, and reusable-workspace traversal. + +@inline _active_rank_cap(A::CompressedFTLRMatrix) = + isempty(A.ranks) ? 0 : min(maxrank(A), maximum(Int, A.ranks)) + +""" + require_complementary_packing(X, name) + +Require logical outer `TileRowMajor` and inner `TileColMajor` packing. +Transposition preserves this complementary logical layout, enabling the same +zero-copy path for all transpose combinations. +""" +@inline function require_complementary_packing(X, name::String) + compressed_ftlr_outer_order(X) isa TileRowMajor && + compressed_ftlr_inner_order(X) isa TileColMajor || throw(ArgumentError( + "canonical TLR gemm! requires complementary packing (outer row-major, " * + "inner col-major) for $name")) + return nothing +end + +""" + choose_tlr_sampling_side(LA, LB, rmaxC, block, rA, rB) -> Symbol + +Choose the lower-workspace ARA sampling side. Complementary packing makes both +zero-copy sampling stacks available for every transpose combination, so the +decision compares the retained core workspace of fixed-column and fixed-row +runs. +""" +function choose_tlr_sampling_side(LA::AbstractTLRMatrix, + LB::AbstractTLRMatrix, + rmaxC::Int, block::Int, + rA::Int, rB::Int) + require_complementary_packing(LA, "A") + require_complementary_packing(LB, "B") + + qm, qk = grid_size(LA) + _, qn = grid_size(LB) + right = qk * (block * (rB + qm * rA) + + rmaxC * qm * (rA + rB) + qm * rA * rB) + left = qk * (block * (rA + qn * rB) + + rmaxC * qn * (rA + rB) + qn * rA * rB) + return right < left ? :right : :left +end + +@kernel function _store_tlr_run_factor_kernel!(dest, src, slots) + i, k, p = @index(Global, NTuple) + @inbounds dest[i, k, Int(slots[p])] = src[i, k, p] +end + +@kernel function _store_tlr_run_diagnostic_kernel!(ranks, err_sq, + ranks_run, err_run, slots) + p = @index(Global, Linear) + slot = Int(@inbounds slots[p]) + @inbounds begin + ranks[slot] = ranks_run[p] + err_sq[slot] = err_run[p] + end +end + +""" + store_tlr_run!(C, U, V, ranks_run, err_run, outer_slots, inner_slots, + ranks_dev, err_dev, slots_dev, slots_host) + +Scatter one run's factors and diagnostics into `C`. Outer and inner factors +need separate slot maps; diagnostics use outer-factor order. `slots_dev` and +`slots_host` are caller-owned traversal scratch. +""" +function store_tlr_run!(C::CompressedFTLRMatrix, U, V, ranks_run, err_run, + outer_slots::AbstractVector{Int}, + inner_slots::AbstractVector{Int}, + ranks_dev, err_dev, slots_dev, slots_host) + backend = get_backend(C) + count = length(outer_slots) + + # outer factors and diagnostics + @inbounds for p in 1:count + slots_host[p] = Int32(outer_slots[p]) + end + copyto!(slots_dev, slots_host) + sd_outer = view(slots_dev, 1:count) + _store_tlr_run_factor_kernel!(backend)( + compressed_ftlr_uniform_view(C.outer), U, sd_outer; ndrange=size(U), + ) + _store_tlr_run_diagnostic_kernel!(backend)( + ranks_dev, err_dev, ranks_run, err_run, sd_outer; ndrange=count, + ) + + # inner factors + @inbounds for p in 1:count + slots_host[p] = Int32(inner_slots[p]) + end + copyto!(slots_dev, slots_host) + sd_inner = view(slots_dev, 1:count) + _store_tlr_run_factor_kernel!(backend)( + compressed_ftlr_uniform_view(C.inner), V, sd_inner; ndrange=size(V), + ) + return nothing +end + +function _validate_canonical_tlr_gemm(C::CompressedFTLRMatrix, + LA::AbstractTLRMatrix, + LB::AbstractTLRMatrix) + require_complementary_packing(C, "C") + require_complementary_packing(LA, "A") + require_complementary_packing(LB, "B") + size(LA, 2) == size(LB, 1) || + throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C must be size(op(A),1) × size(op(B),2)")) + nominal_tile_size(LA, 2) == nominal_tile_size(LB, 1) || + throw(DimensionMismatch("logical contraction tile sizes must agree")) + nominal_tile_size(C) == + (nominal_tile_size(LA, 1), nominal_tile_size(LB, 2)) || + throw(DimensionMismatch("C's tile shape must match the logical output tile")) + any(!iszero, tail_tile_size(X, d) for X in (C, LA, LB) for d in 1:2) && + throw(ArgumentError( + "canonical TLR gemm! currently requires regular-grid tiling")) + return nothing +end + +function tlr_gemm_workspace_spec(C::CompressedFTLRMatrix{BackendT,T}, + A::CompressedFTLRMatrix{BackendT,T}, + B::CompressedFTLRMatrix{BackendT,T}; + transA::Char='N', transB::Char='N', + block::Int=32) where {BackendT,T} + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + _validate_canonical_tlr_gemm(C, LA, LB) + + # sampling cost + qm, qk = grid_size(LA) + _, qn = grid_size(LB) + rA, rB = _active_rank_cap(A), _active_rank_cap(B) + cap = maximum_storage_rank(C) + blk = min(block, max(cap, 1)) + side = choose_tlr_sampling_side(LA, LB, cap, blk, rA, rB) + + # reachable run family + # Complementary packing makes `:row_right` redundant with `:column`. + family = side === :right ? :column : :row_left + nmember = family === :column ? qm : qn + bm = nominal_tile_size(C, 1) + bn = nominal_tile_size(C, 2) + + return ( + backend=typeof(get_backend(C)), T=T, rankT=eltype(C.ranks), + family=family, qm=qm, qk=qk, qn=qn, nmember=nmember, + rA=rA, rB=rB, block=blk, maxrank=cap, bm=bm, bn=bn, + Thi=tlr_orthogonalization_type(T), + ) +end + +function _prepare_tlr_gemm_workspace(C, A, B, workspace; + transA::Char, transB::Char, block::Int) + spec = tlr_gemm_workspace_spec(C, A, B; transA, transB, block) + + if workspace === nothing + return CompressedGemmWorkspace(C, spec), spec + elseif workspace isa Int + workspace >= 0 || + throw(ArgumentError("workspace bytes must be nonnegative")) + required = tlr_gemm_workspace_bytes(spec, 1) + workspace >= required || throw(ArgumentError( + "workspace has $workspace bytes; at least $required bytes are required")) + ws = CompressedGemmWorkspace(C, spec; bytes=workspace) + return ws, spec + elseif workspace isa CompressedGemmWorkspace + workspace.operation == spec || throw(ArgumentError( + "CompressedGemmWorkspace geometry, backend, or element type does not match this operation")) + return workspace, spec + end + + throw(ArgumentError( + "workspace must be nothing, an integer byte count, or CompressedGemmWorkspace")) +end + +"""Internal fixed-width ARA driver used by allocation-returning [`gemm`](@ref).""" +function _gemm_tlr!(C::CompressedFTLRMatrix{BackendT,T}, + A::CompressedFTLRMatrix{BackendT,T}, + B::CompressedFTLRMatrix{BackendT,T}; + alpha=true, beta=false, + transA::Char='N', transB::Char='N', + tol::Real=0.0, rel::Bool=false, + eps_rel=nothing, r_required::Int=10, block::Int=32, + compute=nothing, workspace=nothing) where {BackendT,T} + # argument checks + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + _validate_canonical_tlr_gemm(C, LA, LB) + tol >= 0 || throw(ArgumentError("tol must be nonnegative")) + r_required >= 1 || throw(ArgumentError("r_required must be positive")) + block >= 1 || throw(ArgumentError("block must be positive")) + + # compute policy and sampling tolerance + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + validate_tlr_gemm_precision(get_backend(C), T, T, mode) + ScalarT = gemm_compute_type(mode) + α, β = ScalarT(alpha), ScalarT(beta) + floor_rel = ara_stopping_floor(tlr_orthogonalization_type(T)) + sample_tol = eps_rel === nothing ? max(Float64(tol), floor_rel) : + Float64(eps_rel) + sample_tol >= floor_rel || throw(ArgumentError( + "eps_rel=$sample_tol is below the supported floor $floor_rel")) + + # workspace and zero-copy factor panels + ws_owner, workspace_spec = _prepare_tlr_gemm_workspace( + C, A, B, workspace; transA, transB, block) + qmA, qnA = regular_grid_size(LA) + qmB, qnB = regular_grid_size(LB) + ops = ( + av=(data=compressed_ftlr_uniform_view(compressed_ftlr_inner_storage(LA)), + order=compressed_ftlr_inner_order(LA), qm=qmA, qn=qnA), + bu=(data=compressed_ftlr_uniform_view(compressed_ftlr_outer_storage(LB)), + order=compressed_ftlr_outer_order(LB), qm=qmB, qn=qnB), + bv=(data=compressed_ftlr_uniform_view(compressed_ftlr_inner_storage(LB)), + order=compressed_ftlr_inner_order(LB), qm=qmB, qn=qnB), + au=(data=compressed_ftlr_uniform_view(compressed_ftlr_outer_storage(LA)), + order=compressed_ftlr_outer_order(LA), qm=qmA, qn=qnA), + ) + + # traversal shape shared by both families + qm, qk = grid_size(LA) + _, qn = grid_size(LB) + rA, rB = _active_rank_cap(A), _active_rank_cap(B) + cap_C = maximum_storage_rank(C) + blk = min(block, max(cap_C, 1)) + backend = get_backend(C) + ranks_dev = ws_owner.ranks_global + err_dev = ws_owner.errors_global + bm_tile = nominal_tile_size(C, 1) + bn_tile = nominal_tile_size(C, 2) + + if workspace_spec.family === :column + # fixed-column rolling lanes + # Each column reuses its arena and admits pending members as slots retire. + arena = ws_owner.arena + cap = ws_owner.capacity + for j in 1:qn + arena_reset!(arena) + initial = 1:min(cap, qm) + run = RunCoupling( + Val(:column), ops, initial, j; alpha=α, beta=β, C, + block=blk, maxrank=cap_C, rA, rB, compute=mode, arena) + ara_ws = ARAWorkspace( + T, backend, bm_tile, cap_C, cap; block=blk, arena, + state_storage=ws_owner.ara_state) + rolling_lane_loop!( + C, run, ara_ws, 1:qm, j, ops, arena, ws_owner; + beta=β, eps_rel=sample_tol, r_required, tol, rel, + compute=mode, + ) + end + else + # fixed-row rolling lanes + arena = ws_owner.arena + cap = ws_owner.capacity + for i in 1:qm + arena_reset!(arena) + initial = 1:min(cap, qn) + run = RunCoupling( + Val(:row), ops, i, initial; alpha=α, beta=β, C, + block=blk, maxrank=cap_C, rA, rB, compute=mode, + arena, + ) + ara_ws = ARAWorkspace( + T, backend, bn_tile, cap_C, cap; block=blk, arena, + state_storage=ws_owner.ara_state) + rolling_lane_loop!( + C, run, ara_ws, 1:qn, i, ops, arena, ws_owner; + beta=β, eps_rel=sample_tol, r_required, tol, rel, + compute=mode, + ) + end + end + + # host diagnostics + ranks_host = Array(ranks_dev) + err_host = Array(err_dev) + copyto!(C.ranks, ranks_host) + @inbounds for k in eachindex(C.resid) + C.resid[k] = sqrt(max(err_host[k], 0.0)) + end + return C +end + +function _uniform_ara_operand(A::CompressedFTLRMatrix{BackendT,T}) where {BackendT,T} + qm, qn = grid_size(A) + cap = maxrank(A) + + uniform = CompressedFTLRMatrix( + get_backend(A), T, size(A)..., nominal_tile_size(A), fill(cap, qm, qn); + outer_order=TileRowMajor, inner_order=TileColMajor) + + # logical factors in uniform capacities + @inbounds for j in 1:qn, i in 1:qm + r = compressed_ftlr_rank(A, i, j) + r == 0 && continue + U, V = get_factors(A, i, j) + Ud = compressed_ftlr_storage_outer(uniform, i, j) + Vd = compressed_ftlr_storage_inner(uniform, i, j) + copyto!(view(Ud, :, 1:r), U) + copyto!(view(Vd, :, 1:r), V) + end + return uniform +end + +function _pack_ara_output(staging::CompressedFTLRMatrix; + rank_multiple::Int=0) + # discovered ranks and packed destination + qm, qn = grid_size(staging) + rank_grid = [ranks(staging)[ + tile_linear_index(staging.outer.order, qm, qn, i, j)] + for i in 1:qm, j in 1:qn] + C = CompressedFTLRMatrix( + get_backend(staging), eltype(staging), size(staging)..., + nominal_tile_size(staging), rank_grid; + outer_order=TileRowMajor, inner_order=TileColMajor, + rank_multiple) + + # factors and residuals + @inbounds for j in 1:qn, i in 1:qm + slot = tile_linear_index(C.outer.order, qm, qn, i, j) + C.resid[slot] = residuals(staging)[ + tile_linear_index(staging.outer.order, qm, qn, i, j)] + r = rank_grid[i, j] + r == 0 && continue + # `staging` retains one fixed physical width even after its diagnostic + # rank vector is overwritten with the discovered ranks. + Us = compressed_ftlr_factor_view(staging.outer, i, j, i, r) + Vs = compressed_ftlr_factor_view(staging.inner, i, j, j, r) + copyto!(compressed_ftlr_outer(C, i, j), Us) + copyto!(compressed_ftlr_inner(C, i, j), Vs) + end + return C +end + +""" + gemm(A::CompressedFTLRMatrix, B::CompressedFTLRMatrix; + maxrank, rank_multiple=0, r_required=10, ...) + +Return a compressed approximation to `alpha * op(A) * op(B)`. ARA discovers +ranks in private fixed-width staging, which is compacted before return. +Operands must use regular-grid tiling. Tensor-core modes require stored widths, +`maxrank`, and `rank_multiple` to satisfy the backend rank quantum. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> P = NextLA.gemm(A, A; maxrank=64, tol=1e-6, rel=true); + +julia> Pd = uncompress!(zeros(n, n), P); + +julia> maximum(ranks(P)) <= 64 && norm(Pd - K * K) / norm(K * K) < 1e-4 +true +``` +""" +function gemm(A::CompressedFTLRMatrix{BackendT,T}, + B::CompressedFTLRMatrix{BackendT,T}; + maxrank::Int, + rank_multiple::Int=0, + alpha=true, + transA::Char='N', transB::Char='N', + tol::Real=0.0, rel::Bool=false, + eps_rel=nothing, r_required::Int=10, block::Int=32, + compute=nothing, workspace=nothing) where {BackendT,T} + # argument and geometry checks + maxrank >= 0 || throw(ArgumentError("maxrank must be nonnegative")) + r_required >= 1 || throw(ArgumentError("r_required must be positive")) + rank_multiple >= 0 || throw(ArgumentError("rank_multiple must be nonnegative")) + workspace isa CompressedGemmWorkspace && throw(ArgumentError( + "allocation-returning gemm accepts workspace=nothing or a byte count; " * + "a CompressedGemmWorkspace is bound to private output staging")) + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || + throw(DimensionMismatch("inner dimensions must match")) + nominal_tile_size(LA, 2) == nominal_tile_size(LB, 1) || + throw(DimensionMismatch("logical contraction tile sizes must agree")) + any(!iszero, tail_tile_size(X, d) for X in (LA, LB) for d in 1:2) && + throw(ArgumentError( + "compressed-output gemm currently requires regular-grid tiling")) + typeof(get_backend(A)) === typeof(get_backend(B)) || throw(ArgumentError( + "compressed operands must use the same backend")) + + # compute and rank alignment + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + validate_tlr_gemm_storage(LA, mode; name="left operand") + validate_tlr_gemm_storage(LB, mode; name="right operand") + required_multiple = required_tlr_gemm_rank_multiple(get_backend(A), T, mode) + if required_multiple > 1 + iszero(maxrank % required_multiple) || throw(ArgumentError( + "maxrank=$maxrank is incompatible with this GEMM precision; " * + "use a multiple of $required_multiple")) + rank_multiple > 0 && iszero(rank_multiple % required_multiple) || + throw(ArgumentError( + "compressed-output GEMM with this precision requires " * + "rank_multiple=$required_multiple (or a multiple of it)")) + end + + # output geometry + out_tile = (nominal_tile_size(LA, 1), nominal_tile_size(LB, 2)) + maxrank <= min(out_tile...) || throw(ArgumentError( + "maxrank=$maxrank exceeds output tile extent $(min(out_tile...))")) + qm, qn = grid_size(LA)[1], grid_size(LB)[2] + if maxrank == 0 + return CompressedFTLRMatrix( + get_backend(A), T, size(LA, 1), size(LB, 2), out_tile, + Base.zeros(Int, qm, qn); rank_multiple, + outer_order=TileRowMajor, inner_order=TileColMajor) + end + + # uniform staging and compression + UA = _uniform_ara_operand(A) + UB = _uniform_ara_operand(B) + staging = CompressedFTLRMatrix( + get_backend(A), T, size(LA, 1), size(LB, 2), out_tile, + fill(maxrank, qm, qn); + outer_order=TileRowMajor, inner_order=TileColMajor) + _gemm_tlr!( + staging, UA, UB; alpha, beta=false, transA, transB, tol, rel, eps_rel, + r_required, block, compute=mode, workspace) + return _pack_ara_output(staging; rank_multiple) +end diff --git a/src/tlr/blas/gemm/compressed_accumulation/rolling_schedule.jl b/src/tlr/blas/gemm/compressed_accumulation/rolling_schedule.jl new file mode 100644 index 00000000..4d58c072 --- /dev/null +++ b/src/tlr/blas/gemm/compressed_accumulation/rolling_schedule.jl @@ -0,0 +1,277 @@ +function _retirement_outputs(ws_owner, count::Int) + U = view(ws_owner.U, :, :, 1:count) + V = view(ws_owner.V, :, :, 1:count) + rr = view(ws_owner.ranks_slot, 1:count) + ee = view(ws_owner.errors_slot, 1:count) + fill!(U, zero(eltype(U))) + fill!(V, zero(eltype(V))) + return U, V, rr, ee +end + +""" + _capped_capture_sq!(capture, run, Q, s, progress, cap, block, Gbuf, Ebuf; + beta, compute, proj, sketch, beta_tmp, slot0) + -> capture or nothing + +Squared range-capture error `‖X - QQᴴX‖_F²` of the members whose basis stopped +at the ARA cap (`progress[p] >= cap`), and zero for the others, for +`ara_truncate!(...; capture)`, which adds it to the reported residual and +leaves the rank choice as it was. Returns `nothing`, computing nothing, when no +member reached the cap. + +ARA's stopping test (`r_required` consecutive negligible samples) bounds what `Q` +misses only for members that converged. A member stopped by the cap can miss +much more, and without this its residual would be the truncation error alone, +which is zero when the cap holds the whole basis. The miss is estimated a +posteriori from fresh Gaussian vectors (Halko, Martinsson and Tropp, SIAM Rev. +53(2), 2011, §4.3): for `G` with `w` columns of independent N(0, 1) entries, +`E‖Xᴴ(I - QQᴴ)G‖_F² = w‖(I - QQᴴ)X‖_F²`, with relative standard deviation at most +`√(2/w)` (the Gaussian trace estimator, Avron and Toledo, J. ACM 58(2), 2011). +Here `w = min(block, s)`. + +`Gbuf` (the rows of `Q`) and `Ebuf` (the rows of `Xᴴ`) are the caller's +truncation outputs before they are written: `Gbuf` holds `G`, and `Ebuf` first +`QᴴG`, then `Xᴴ(I - QQᴴ)G`. +""" +function _capped_capture_sq!(capture, run, Q, s::Int, progress, cap::Int, + block::Int, Gbuf, Ebuf; beta, compute, proj, + sketch, beta_tmp, slot0::Int) + capped = [progress[p] >= cap for p in eachindex(progress)] + any(capped) || return nothing + T = eltype(Q) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + w = min(block, s) + G = view(Gbuf, :, 1:w, :) + QG = view(Ebuf, 1:s, 1:w, :) + E = view(Ebuf, :, 1:w, :) + + # Gaussian block projected off the basis + Random.randn!(G) + precision_gemm_batched!(adjoint_blas_char(T), 'N', one(T), Q, G, + zero(T), QG, mode) + precision_gemm_batched!('N', 'N', -one(T), Q, QG, one(T), G, mode) + + # operator samples and the estimate + apply_corange!(E, run, G, w; beta, compute, proj, sketch, beta_tmp, slot0) + batch_frobenius_norms_sq!(capture, E) + est = Array(capture) + @inbounds for p in eachindex(est) + est[p] = capped[p] ? est[p] / w : 0.0 + end + copyto!(capture, est) + return capture +end + +""" + _finalize_wave!(Cout, run, ara_ws, slots, member_ids, progress, fixed, + arena, ws_owner; beta, tol, rel, compute) + +Compute the complementary basis for a retired wave, truncate it, and scatter +the factors into `Cout`. Fixed-column and fixed-row runs swap scratch shapes and +`ara_truncate!` factor order because direct and co-range sampling exchange the +outer/inner roles; see [`apply_corange!`](@ref). +""" +function _finalize_wave!(Cout, run::RunCoupling{:column}, ara_ws, + slots::UnitRange{Int}, member_ids, + progress, j::Int, arena, ws_owner; + beta, tol, rel, compute) + count = length(slots) + count == 0 && return + + # retired buffers and basis width + U, V, rr, ee = _retirement_outputs(ws_owner, count) + s = maximum(view(progress, slots)) + logical = view(member_ids, slots) + + # complementary basis and truncation + if s > 0 + arena_reset_phase!(arena) + a = run_t_arena(arena) + T = eltype(run.S) + backend = get_backend(run.S) + rA, rB, qk = size(run.S, 1), size(run.S, 2), run.qk + Q = view(ara_ws.Q, :, 1:s, slots) + proj = workspace_array!(a, backend, T, rA, s, qk, count) + sketch = workspace_array!(a, backend, T, rB, qk, s, count) + rC = run.betaV === nothing ? 0 : size(first(run.betaV), 2) + bt = workspace_array!(a, backend, T, rC, s, count) + Z = workspace_array!(a, backend, T, size(V, 1), s, count) + + apply_corange!( + Z, run, Q, s; beta, compute, proj, sketch, beta_tmp=bt, + slot0=first(slots)) + + Uh = workspace_array!(a, backend, T, size(U, 1), s, count) + Vh = workspace_array!(a, backend, T, size(V, 1), s, count) + capture = _capped_capture_sq!( + ee, run, Q, s, view(progress, slots), size(ara_ws.Q, 2), + ara_ws.block, Uh, Vh; beta, compute, proj, sketch, beta_tmp=bt, + slot0=first(slots)) + ara_truncate!( + Uh, Vh, rr, ee, Q, Z; tol, relative=rel, + maxrank=min(s, size(U, 2)), capture, compute) + + copyto!(view(U, :, 1:s, :), Uh) + copyto!(view(V, :, 1:s, :), Vh) + else + fill!(rr, zero(eltype(rr))) + fill!(ee, 0.0) + end + + # canonical factor and diagnostic slots + qm = grid_size(Cout)[1] + qn = grid_size(Cout)[2] + outslots = view(ws_owner.output_slots, 1:count) + inslots = view(ws_owner.output_slots_inner, 1:count) + @inbounds for p in 1:count + outslots[p] = j + (logical[p] - 1) * qn # tile_linear_index(TileRowMajor, ...) + inslots[p] = logical[p] + (j - 1) * qm # tile_linear_index(TileColMajor, ...) + end + store_tlr_run!( + Cout, U, V, rr, ee, outslots, inslots, ws_owner.ranks_global, + ws_owner.errors_global, ws_owner.indices, ws_owner.indices_host) +end + +function _finalize_wave!(Cout, run::RunCoupling{:row}, ara_ws, + slots::UnitRange{Int}, member_ids, progress, + i::Int, arena, ws_owner; + beta, tol, rel, compute) + count = length(slots) + count == 0 && return + + # retired buffers and basis width + U, V, rr, ee = _retirement_outputs(ws_owner, count) + s = maximum(view(progress, slots)) + logical = view(member_ids, slots) + + # complementary basis and truncation + if s > 0 + arena_reset_phase!(arena) + a = run_t_arena(arena) + T = eltype(run.S) + backend = get_backend(run.S) + rA, rB, qk = size(run.S, 1), size(run.S, 2), run.qk + Q = view(ara_ws.Q, :, 1:s, slots) + proj = workspace_array!(a, backend, T, rB, s, qk, count) + sketch = workspace_array!(a, backend, T, rA, qk, s, count) + rC = run.betaU === nothing ? 0 : size(first(run.betaU), 2) + bt = workspace_array!(a, backend, T, rC, s, count) + L = workspace_array!(a, backend, T, size(U, 1), s, count) + + apply_corange!( + L, run, Q, s; beta, compute, proj, sketch, beta_tmp=bt, + slot0=first(slots)) + + Uh = workspace_array!(a, backend, T, size(U, 1), s, count) + Vh = workspace_array!(a, backend, T, size(V, 1), s, count) + capture = _capped_capture_sq!( + ee, run, Q, s, view(progress, slots), size(ara_ws.Q, 2), + ara_ws.block, Vh, Uh; beta, compute, proj, sketch, beta_tmp=bt, + slot0=first(slots)) + ara_truncate!( + Vh, Uh, rr, ee, Q, L; tol, relative=rel, + maxrank=min(s, size(U, 2)), capture, compute) + + copyto!(view(U, :, 1:s, :), Uh) + copyto!(view(V, :, 1:s, :), Vh) + else + fill!(rr, zero(eltype(rr))) + fill!(ee, 0.0) + end + + # canonical factor and diagnostic slots + qm = grid_size(Cout)[1] + qn = grid_size(Cout)[2] + outslots = view(ws_owner.output_slots, 1:count) + inslots = view(ws_owner.output_slots_inner, 1:count) + @inbounds for p in 1:count + outslots[p] = logical[p] + (i - 1) * qn # tile_linear_index(TileRowMajor, ...) + inslots[p] = i + (logical[p] - 1) * qm # tile_linear_index(TileColMajor, ...) + end + store_tlr_run!( + Cout, U, V, rr, ee, outslots, inslots, ws_owner.ranks_global, + ws_owner.errors_global, ws_owner.indices, ws_owner.indices_host) +end + +function rolling_lane_loop!(Cout, run, ara_ws, allmembers::AbstractVector{Int}, + fixed::Int, ops, arena, ws_owner; + beta, eps_rel, r_required, tol, rel, compute) + # initial active-slot prefix + cap = ws_owner.capacity + member_ids = ws_owner.member_ids + progress = ws_owner.progress + initial = min(cap, length(allmembers)) + copyto!(member_ids, 1, allmembers, 1, initial) + fill!(progress, 0) + pending = initial + 1 + nactive = initial + ara_reset!(ara_ws.state, ara_ws.block, size(ara_ws.Q, 2)) + copyto!(ara_ws.state.samples_host, ara_ws.state.samples) + fill!(ara_ws.Q, zero(eltype(ara_ws.Q))) + + # hot samplers, reused every pass below + sampler = (Y, width, _) -> apply_run!(Y, run, width, nactive; beta, compute) + swapper = (p, q) -> swap_run_members!(run, p, q) + + while nactive > 0 || pending <= length(allmembers) + # cold-start admission + if nactive == 0 + nnew = min(cap, length(allmembers) - pending + 1) + slots = 1:nnew + ids = view(member_ids, slots) + copyto!(ids, view(allmembers, pending:(pending + nnew - 1))) + + arena_reset_phase!(arena) + admit_wave!( + run, ops, ids, slots, fixed, arena; + C=iszero(beta) ? nothing : Cout, compute) + + ara_reset_slots!(ara_ws, 1, nnew) + fill!(view(progress, slots), 0) + pending += nnew + nactive = nnew + ara_ws = rebind_ara_phase(ara_ws, arena) + rebind_sampling_scratch!(run, arena) + end + + # packed ARA pass and retirements + info = ara_packed_pass!( + ara_ws, sampler, nactive, member_ids, progress; + eps_rel, r_required, compute, swap_member! = swapper) + nactive = info.nactive + retired = info.retired + isempty(retired) && continue + + # retired-wave truncation and scatter + _finalize_wave!( + Cout, run, ara_ws, retired, member_ids, progress, fixed, + arena, ws_owner; beta, tol, rel, compute) + + # freed-slot backfill + nnew = min(cap - nactive, max(length(allmembers) - pending + 1, 0)) + if nnew > 0 + slots = (nactive + 1):(nactive + nnew) + ids = view(member_ids, slots) + copyto!(ids, view(allmembers, pending:(pending + nnew - 1))) + + arena_reset_phase!(arena) + admit_wave!( + run, ops, ids, slots, fixed, arena; + C=iszero(beta) ? nothing : Cout, compute) + + ara_reset_slots!(ara_ws, first(slots), nnew) + fill!(view(progress, slots), 0) + pending += nnew + nactive += nnew + end + + # active sampling views + if nactive > 0 + ara_ws = rebind_ara_phase(ara_ws, arena) + rebind_sampling_scratch!(run, arena) + end + end + + return Cout +end diff --git a/src/tlr/blas/gemm/compressed_accumulation/run_coupling.jl b/src/tlr/blas/gemm/compressed_accumulation/run_coupling.jl new file mode 100644 index 00000000..b125a274 --- /dev/null +++ b/src/tlr/blas/gemm/compressed_accumulation/run_coupling.jl @@ -0,0 +1,775 @@ +# Run-coupling state for the canonical TLR-output GEMM's rolling traversal ---- + +""" + RunCoupling{Fixed} + +Retained state for a fixed-column or fixed-row run, physically ordered by ARA +slot and swap-compacted by [`swap_run_members!`](@ref). Both directions use +`S = V_A'W_B` and the same three-stage sampler: + + proj = shared' * Om # H (:column) or G (:row) + sketch = (Fixed === :column ? S : S') * proj # T (:column) or W (:row) + Y = member[p] * sketch[p] # same reduction either way + +Complementary packing makes the fixed factor stack zero-copy and the swept +stack member-specific. Fixed columns right-sample; fixed rows left-sample, so +[`apply_run!`](@ref) changes only the middle transpose. + +Member stacks have nonuniform offsets and require pointer-batched GEMM. +Member and beta descriptors are swap-tracked; scratch descriptors are reused +without swapping; pointer APIs require a descriptor for every operand. The +caller-owned `Y` descriptor is created by `apply_run!`. +[`apply_corange!`](@ref) runs once after convergence and uses view batches. +""" +mutable struct RunCoupling{Fixed,ST,SHT,MT,BUT,BVT,PT,SKT,OT,BT,T} + S::ST + shared::SHT + member::MT + betaU::BUT + betaV::BVT + member_ptrs::Union{Nothing,BatchPtrDescriptor} + sketch_ptrs::Union{Nothing,BatchPtrDescriptor} + betaU_ptrs::Union{Nothing,BatchPtrDescriptor} + betaV_ptrs::Union{Nothing,BatchPtrDescriptor} + sharedOm_ptrs::Union{Nothing,BatchPtrDescriptor} + beta_tmp_ptrs::Union{Nothing,BatchPtrDescriptor} + proj::PT + sketch::SKT + Omega::OT + beta_tmp::BT + alpha::T + qk::Int +end + +""" + RunCoupling(Val(:column), ops, rows, j; alpha, beta=false, C=nothing, block, maxrank) + +Fixed-column constructor: the run covers output tiles `(rows, j)`. +""" +function RunCoupling(::Val{:column}, ops, rows, j::Int; + alpha, beta=false, C=nothing, + block::Int, maxrank::Int, + rA::Int=size(ops.au.data, 2), + rB::Int=size(ops.bv.data, 2), + compute=nothing, arena=nothing) + ids = collect(Int, rows) + nmember = length(ids) + + # persistent factor stacks and constructor scratch + # Temporary coupling factors use the arena to avoid traversal allocations. + parena = run_persistent_t_arena(arena) + tarena = run_t_arena(arena) + member = [ + _factor_row_stack(ops.au, i, rA; arena=parena, force_pack=true) + for i in ids + ] + rowV = [_factor_row_stack(ops.av, i, rA; arena=tarena) for i in ids] + colW = _factor_column_stack(ops.bu, j, rB; arena=tarena) + shared = _factor_column_stack(ops.bv, j, rB; arena=parena) + T = eltype(shared) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + qk = size(shared, 3) + bm = size(first(member), 1) + bn = size(shared, 1) + backend = get_backend(shared) + + # coupling matrix S = V_A' W_B, batched over member and contraction tile + S = workspace_array!(parena, backend, T, rA, rB, qk, nmember) + if nmember > 0 && qk > 0 && rA > 0 && rB > 0 + left_factor_views = [view(rowV[p], :, :, kidx) for p in 1:nmember for kidx in 1:qk] + right_factor_views = [view(colW, :, :, kidx) for p in 1:nmember for kidx in 1:qk] + coupling_views = [view(S, :, :, kidx, p) for p in 1:nmember for kidx in 1:qk] + precision_gemm_batched!(adjoint_blas_char(T), 'N', one(T), + left_factor_views, right_factor_views, zero(T), coupling_views, mode) + end + + # existing-output beta factors + betaU, betaV = if iszero(beta) + (nothing, nothing) + else + C === nothing && throw(ArgumentError("C must be supplied when beta != 0")) + ([compressed_ftlr_storage_outer(C, i, j) for i in ids], + [compressed_ftlr_storage_inner(C, i, j) for i in ids]) + end + + # sampling and truncation scratch + # Only phase scratch is rewound; persistent coupling data remains intact. + arena_reset_phase!(arena) + proj = workspace_array!(tarena, backend, T, rB, block, qk) + sketch = workspace_array!(tarena, backend, T, rA, qk, block, nmember) + Omega = workspace_array!(tarena, backend, T, bn, block, 1) + beta_tmp = workspace_array!(tarena, backend, T, + betaV === nothing ? 0 : size(first(betaV), 2), + max(block, maxrank), nmember) + + # pointer-batched descriptors + ptrs_ok = nmember > 0 && supports_pointer_batched(backend) + member_ptrs = ptrs_ok ? + BatchPtrDescriptor([reshape(member[p], bm, rA * qk) for p in 1:nmember]) : + nothing + sketch_ptrs = ptrs_ok ? + BatchPtrDescriptor([view(reshape(sketch, rA * qk, block, nmember), :, :, p) + for p in 1:nmember]) : + nothing + has_beta_ptrs = ptrs_ok && betaU !== nothing + betaU_ptrs = has_beta_ptrs ? BatchPtrDescriptor(betaU) : nothing + betaV_ptrs = has_beta_ptrs ? BatchPtrDescriptor(betaV) : nothing + sharedOm_ptrs = has_beta_ptrs ? + BatchPtrDescriptor([view(Omega, :, :, 1) for _ in 1:nmember]) : nothing + beta_tmp_ptrs = has_beta_ptrs ? + BatchPtrDescriptor([view(beta_tmp, :, :, p) for p in 1:nmember]) : nothing + + return RunCoupling{:column,typeof(S),typeof(shared),typeof(member), + typeof(betaU),typeof(betaV),typeof(proj),typeof(sketch), + typeof(Omega),typeof(beta_tmp),T}( + S, shared, member, betaU, betaV, + member_ptrs, sketch_ptrs, betaU_ptrs, betaV_ptrs, sharedOm_ptrs, beta_tmp_ptrs, + proj, sketch, Omega, beta_tmp, T(alpha), qk) +end + +""" + RunCoupling(Val(:row), ops, i, cols; alpha, beta=false, C=nothing, block, maxrank) + +Fixed-row constructor: the run covers output tiles `(i, cols)`. +""" +function RunCoupling(::Val{:row}, ops, i::Int, cols; + alpha, beta=false, C=nothing, + block::Int, maxrank::Int, + rA::Int=size(ops.au.data, 2), + rB::Int=size(ops.bv.data, 2), + compute=nothing, arena=nothing) + ids = collect(Int, cols) + nmember = length(ids) + qk = ops.au.qn + T = eltype(ops.au.data) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + backend = get_backend(ops.au.data) + bm = size(ops.au.data, 1) + bn = size(ops.bv.data, 1) + parena = run_persistent_t_arena(arena) + tarena = run_t_arena(arena) + + # member/shared factor panels + Ainner = [_trimmed_tile(ops.av, i, kidx, rA) for kidx in 1:qk] + shared = _factor_row_stack(ops.au, i, rA; arena=parena) + Bouter = [[_trimmed_tile(ops.bu, kidx, j, rB) for kidx in 1:qk] for j in ids] + member = [ + _factor_column_stack(ops.bv, j, rB; arena=parena, force_pack=true) + for j in ids + ] + + # coupling matrix S = V_A' W_B, batched over member and contraction tile + S = workspace_array!(parena, backend, T, rA, rB, qk, nmember) + if nmember > 0 && qk > 0 && rA > 0 && rB > 0 + left_factor_views = [Ainner[kidx] for p in 1:nmember for kidx in 1:qk] + right_factor_views = [Bouter[p][kidx] for p in 1:nmember for kidx in 1:qk] + coupling_views = [view(S, :, :, kidx, p) for p in 1:nmember for kidx in 1:qk] + precision_gemm_batched!(adjoint_blas_char(T), 'N', one(T), + left_factor_views, right_factor_views, zero(T), coupling_views, mode) + end + + # existing-output beta factors + betaU, betaV = if iszero(beta) + (nothing, nothing) + else + C === nothing && throw(ArgumentError("C must be supplied when beta != 0")) + ([compressed_ftlr_storage_outer(C, i, j) for j in ids], + [compressed_ftlr_storage_inner(C, i, j) for j in ids]) + end + rC = betaU === nothing ? 0 : size(first(betaU), 2) + + # phase-only sampling and truncation scratch + arena_reset_phase!(arena) + proj = workspace_array!(tarena, backend, T, rA, block, qk) + sketch = workspace_array!(tarena, backend, T, rB, qk, block, nmember) + Omega = workspace_array!(tarena, backend, T, bm, block, 1) + beta_tmp = workspace_array!(tarena, backend, T, rC, max(block, maxrank), nmember) + + # pointer-batched descriptors + ptrs_ok = nmember > 0 && qk > 0 && supports_pointer_batched(backend) + member_ptrs = ptrs_ok ? + BatchPtrDescriptor([reshape(member[p], bn, rB * qk) for p in 1:nmember]) : + nothing + sketch_ptrs = ptrs_ok ? + BatchPtrDescriptor([view(reshape(sketch, rB * qk, block, nmember), :, :, p) + for p in 1:nmember]) : + nothing + has_beta_ptrs = ptrs_ok && betaU !== nothing + betaU_ptrs = has_beta_ptrs ? BatchPtrDescriptor(betaU) : nothing + betaV_ptrs = has_beta_ptrs ? BatchPtrDescriptor(betaV) : nothing + sharedOm_ptrs = has_beta_ptrs ? + BatchPtrDescriptor([view(Omega, :, :, 1) for _ in 1:nmember]) : nothing + beta_tmp_ptrs = has_beta_ptrs ? + BatchPtrDescriptor([view(beta_tmp, :, :, p) for p in 1:nmember]) : nothing + + return RunCoupling{:row,typeof(S),typeof(shared),typeof(member), + typeof(betaU),typeof(betaV),typeof(proj),typeof(sketch), + typeof(Omega),typeof(beta_tmp),T}( + S, shared, member, betaU, betaV, + member_ptrs, sketch_ptrs, betaU_ptrs, betaV_ptrs, sharedOm_ptrs, beta_tmp_ptrs, + proj, sketch, Omega, beta_tmp, T(alpha), qk) +end + +"""Swap active slots `p` and `q`; `shared` has no member axis.""" +function swap_run_members!(run::RunCoupling, p::Int, q::Int) + p == q && return run + + # coupling and member factors + backend = get_backend(run.S) + S3 = reshape(run.S, :, 1, size(run.S, 4)) + ara_swap_basis_kernel!(backend)(S3, p, q; ndrange=(size(S3, 1), 1)) + run.member[p], run.member[q] = run.member[q], run.member[p] + run.member_ptrs !== nothing && swap_batch_ptrs!(run.member_ptrs, p, q) + + # beta factors + if run.betaU !== nothing + run.betaU[p], run.betaU[q] = run.betaU[q], run.betaU[p] + run.betaV[p], run.betaV[q] = run.betaV[q], run.betaV[p] + run.betaU_ptrs !== nothing && swap_batch_ptrs!(run.betaU_ptrs, p, q) + run.betaV_ptrs !== nothing && swap_batch_ptrs!(run.betaV_ptrs, p, q) + end + return run +end + +""" + apply_run!(Y, run, sketch_width, nactive; beta, compute) + +Hot per-pass sampler: fixed columns right-sample and fixed rows left-sample. +One projection batch is independent of `nactive`; the other stages use the +active prefix. Supported backends reuse persistent pointer descriptors, while +the caller-owned `Y` descriptor is built per call; CPU uses view batches. +""" +function apply_run!(Y::AbstractArray{T,3}, run::RunCoupling{:column}, + sketch_width::Int, nactive::Int; + beta=false, compute=nothing) where {T} + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + adj = adjoint_blas_char(T) + qk = run.qk + bm = size(Y, 1) + rA, rB = size(run.S, 1), size(run.S, 2) + use_ptrs = run.member_ptrs !== nothing + + # random sketch and output descriptor + Om = view(run.Omega, :, 1:sketch_width, :) + Random.randn!(Om) + proj = view(run.proj, :, 1:sketch_width, :) + + Yptrs = use_ptrs ? + BatchPtrDescriptor([view(Y, :, 1:sketch_width, p) for p in 1:nactive]) : + nothing + + # operator samples + if qk > 0 && rA > 0 && rB > 0 + # shared projection + precision_gemm_batched!(adj, 'N', one(T), run.shared, Om, + zero(T), proj, mode) + + # coupling contraction + coupling_views = [view(run.S, :, :, kidx, p) for p in 1:nactive for kidx in 1:qk] + proj_views = [view(proj, :, :, kidx) for p in 1:nactive for kidx in 1:qk] + sketch_views = [view(run.sketch, :, kidx, 1:sketch_width, p) + for p in 1:nactive for kidx in 1:qk] + precision_gemm_batched!('N', 'N', run.alpha, coupling_views, proj_views, + zero(T), sketch_views, mode) + + # member reduction + if use_ptrs + Uref = reshape(run.member[1], bm, rA * qk) + Sref = view(reshape(run.sketch, rA * qk, size(run.sketch, 3), + size(run.sketch, 4)), :, 1:sketch_width, 1) + precision_gemm_batched_ptrs!('N', 'N', one(T), + run.member_ptrs, Uref, run.sketch_ptrs, Sref, + zero(T), Yptrs, view(Y, :, 1:sketch_width, 1), nactive, mode) + else + member_views = [reshape(run.member[p], bm, rA * qk) for p in 1:nactive] + sketch_stacks = [reshape(view(run.sketch, :, :, 1:sketch_width, p), rA * qk, sketch_width) + for p in 1:nactive] + output_views = [view(Y, :, 1:sketch_width, p) for p in 1:nactive] + precision_gemm_batched!('N', 'N', one(T), member_views, sketch_stacks, + zero(T), output_views, mode) + end + else + fill!(view(Y, :, 1:sketch_width, :), zero(T)) + end + + # beta contribution + if run.betaU !== nothing + if use_ptrs + tmpref = view(run.beta_tmp, :, 1:sketch_width, 1) + precision_gemm_batched_ptrs!(adj, 'N', one(T), + run.betaV_ptrs, first(run.betaV), run.sharedOm_ptrs, view(Om, :, :, 1), + zero(T), run.beta_tmp_ptrs, tmpref, nactive, mode) + precision_gemm_batched_ptrs!('N', 'N', T(beta), + run.betaU_ptrs, first(run.betaU), run.beta_tmp_ptrs, tmpref, + one(T), Yptrs, view(Y, :, 1:sketch_width, 1), nactive, mode) + else + tmp = [view(run.beta_tmp, :, 1:sketch_width, p) for p in 1:nactive] + omega_views = [view(Om, :, :, 1) for _ in 1:nactive] + output_views = [view(Y, :, 1:sketch_width, p) for p in 1:nactive] + precision_gemm_batched!(adj, 'N', one(T), view(run.betaV, 1:nactive), + omega_views, zero(T), tmp, mode) + precision_gemm_batched!('N', 'N', T(beta), view(run.betaU, 1:nactive), + tmp, one(T), output_views, mode) + end + end + return Y +end + +function apply_run!(Y::AbstractArray{T,3}, run::RunCoupling{:row}, + sketch_width::Int, nactive::Int; + beta=false, compute=nothing) where {T} + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + adj = adjoint_blas_char(T) + qk = run.qk + rA, rB = size(run.S, 1), size(run.S, 2) + bn = size(Y, 1) + + # random sketch and output descriptor + Om = view(run.Omega, :, 1:sketch_width, :) + Random.randn!(Om) + use_ptrs = run.member_ptrs !== nothing + Yptrs = use_ptrs ? + BatchPtrDescriptor([view(Y, :, 1:sketch_width, p) for p in 1:nactive]) : + nothing + + # operator samples + if qk > 0 && rA > 0 && rB > 0 + # shared strided projection + # `Om` broadcasts over the contraction-tile batch. + proj = view(run.proj, :, 1:sketch_width, :) + precision_gemm_batched!(adj, 'N', one(T), run.shared, Om, + zero(T), proj, mode) + + # coupling contraction + coupling_views = [view(run.S, :, :, kidx, p) for p in 1:nactive for kidx in 1:qk] + proj_views = [view(proj, :, :, kidx) for p in 1:nactive for kidx in 1:qk] + sketch_views = [view(run.sketch, :, kidx, 1:sketch_width, p) + for p in 1:nactive for kidx in 1:qk] + precision_gemm_batched!(adj, 'N', run.alpha, coupling_views, proj_views, + zero(T), sketch_views, mode) + + # member reduction + if use_ptrs + Bref = reshape(first(run.member), bn, rB * qk) + sketch2 = reshape(run.sketch, rB * qk, size(run.sketch, 3), size(run.sketch, 4)) + Sref = view(sketch2, :, 1:sketch_width, 1) + precision_gemm_batched_ptrs!('N', 'N', one(T), + run.member_ptrs, Bref, run.sketch_ptrs, Sref, + zero(T), Yptrs, view(Y, :, 1:sketch_width, 1), nactive, mode) + else + member_views = [reshape(run.member[p], bn, rB * qk) for p in 1:nactive] + sketch_stacks = [reshape(view(run.sketch, :, :, 1:sketch_width, p), + rB * qk, sketch_width) for p in 1:nactive] + output_views = [view(Y, :, 1:sketch_width, p) for p in 1:nactive] + precision_gemm_batched!('N', 'N', one(T), member_views, sketch_stacks, + zero(T), output_views, mode) + end + else + fill!(view(Y, :, 1:sketch_width, 1:nactive), zero(T)) + end + + # beta contribution + if run.betaU !== nothing + if use_ptrs + tmpref = view(run.beta_tmp, :, 1:sketch_width, 1) + precision_gemm_batched_ptrs!(adj, 'N', one(T), + run.betaU_ptrs, first(run.betaU), run.sharedOm_ptrs, view(Om, :, :, 1), + zero(T), run.beta_tmp_ptrs, tmpref, nactive, mode) + precision_gemm_batched_ptrs!('N', 'N', T(beta), + run.betaV_ptrs, first(run.betaV), run.beta_tmp_ptrs, tmpref, + one(T), Yptrs, view(Y, :, 1:sketch_width, 1), nactive, mode) + else + tmp = [view(run.beta_tmp, :, 1:sketch_width, p) for p in 1:nactive] + omega_views = [view(Om, :, :, 1) for p in 1:nactive] + output_views = [view(Y, :, 1:sketch_width, p) for p in 1:nactive] + precision_gemm_batched!(adj, 'N', one(T), view(run.betaU, 1:nactive), + omega_views, zero(T), tmp, mode) + precision_gemm_batched!('N', 'N', T(beta), view(run.betaV, 1:nactive), + tmp, one(T), output_views, mode) + end + end + return Y +end + +""" + apply_corange!(Z, run, Q, sketch_width; beta, compute, proj, sketch, beta_tmp, slot0=1) + +Form `Z_slot = X_tile(slot)'Q_slot` after convergence. `S` and `Q` share the +final slot order. External `proj` and `sketch` use the opposite fixed-axis +shape because this apply builds the complementary basis; see [`apply_run!`](@ref). +""" +function apply_corange!(Z::AbstractArray{T,3}, run::RunCoupling{:column}, + Q::AbstractArray{T,3}, sketch_width::Int; + beta=false, compute=nothing, + proj, sketch, beta_tmp, slot0::Int=1) where {T} + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + adj = adjoint_blas_char(T) + nmember = size(Q, 3) + qk = run.qk + rA, rB = size(run.S, 1), size(run.S, 2) + bn = size(Z, 1) + + # complementary operator samples + if qk > 0 && rA > 0 && rB > 0 + member_views = [view(run.member[slot0 + p - 1], :, :, kidx) for p in 1:nmember for kidx in 1:qk] + input_views = [view(Q, :, 1:sketch_width, p) for p in 1:nmember for kidx in 1:qk] + proj_views = [view(proj, :, 1:sketch_width, kidx, p) for p in 1:nmember for kidx in 1:qk] + precision_gemm_batched!(adj, 'N', one(T), member_views, input_views, + zero(T), proj_views, mode) + + coupling_views = [view(run.S, :, :, kidx, slot0 + p - 1) for p in 1:nmember for kidx in 1:qk] + sketch_views = [view(sketch, :, kidx, 1:sketch_width, p) + for p in 1:nmember for kidx in 1:qk] + precision_gemm_batched!(adj, 'N', run.alpha, coupling_views, proj_views, + zero(T), sketch_views, mode) + + shared_stack = reshape(run.shared, bn, rB * qk) + tasks = [GroupedGemmTask( + 'N', 'N', one(T), shared_stack, + reshape(view(sketch, :, :, 1:sketch_width, p), + rB * qk, sketch_width), + zero(T), view(Z, :, 1:sketch_width, p)) for p in 1:nmember] + precision_gemm_grouped!(tasks, mode) + else + fill!(Z, zero(T)) + end + + # beta contribution + if run.betaU !== nothing + tmp = [view(beta_tmp, :, 1:sketch_width, p) for p in 1:nmember] + input_views = [view(Q, :, 1:sketch_width, p) for p in 1:nmember] + out_views = [view(Z, :, 1:sketch_width, p) for p in 1:nmember] + betaU = view(run.betaU, slot0:(slot0 + nmember - 1)) + betaV = view(run.betaV, slot0:(slot0 + nmember - 1)) + precision_gemm_batched!(adj, 'N', one(T), betaU, input_views, + zero(T), tmp, mode) + precision_gemm_batched!('N', 'N', T(beta), betaV, tmp, + one(T), out_views, mode) + end + return Z +end + +function apply_corange!(Z::AbstractArray{T,3}, run::RunCoupling{:row}, + Q::AbstractArray{T,3}, sketch_width::Int; + beta=false, compute=nothing, + proj, sketch, beta_tmp, slot0::Int=1) where {T} + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + adj = adjoint_blas_char(T) + nmember = size(Q, 3) + qk = run.qk + rA, rB = size(run.S, 1), size(run.S, 2) + bm = size(Z, 1) + + # complementary operator samples + if qk > 0 && rA > 0 && rB > 0 + member_views = [view(run.member[slot0 + p - 1], :, :, kidx) for p in 1:nmember for kidx in 1:qk] + input_views = [view(Q, :, 1:sketch_width, p) for p in 1:nmember for kidx in 1:qk] + proj_views = [view(proj, :, 1:sketch_width, kidx, p) + for p in 1:nmember for kidx in 1:qk] + precision_gemm_batched!(adj, 'N', one(T), member_views, input_views, + zero(T), proj_views, mode) + + coupling_views = [view(run.S, :, :, kidx, slot0 + p - 1) for p in 1:nmember for kidx in 1:qk] + sketch_views = [view(sketch, :, kidx, 1:sketch_width, p) + for p in 1:nmember for kidx in 1:qk] + precision_gemm_batched!('N', 'N', run.alpha, coupling_views, proj_views, + zero(T), sketch_views, mode) + + # grouped reshaped arena subviews + shared_stack = reshape(run.shared, bm, rA * qk) + tasks = [GroupedGemmTask( + 'N', 'N', one(T), shared_stack, + reshape(view(sketch, :, :, 1:sketch_width, p), + rA * qk, sketch_width), + zero(T), view(Z, :, 1:sketch_width, p)) for p in 1:nmember] + precision_gemm_grouped!(tasks, mode) + else + fill!(Z, zero(T)) + end + + # beta contribution + if run.betaU !== nothing + tmp = [view(beta_tmp, :, 1:sketch_width, p) for p in 1:nmember] + input_views = [view(Q, :, 1:sketch_width, p) for p in 1:nmember] + out_views = [view(Z, :, 1:sketch_width, p) for p in 1:nmember] + betaU = view(run.betaU, slot0:(slot0 + nmember - 1)) + betaV = view(run.betaV, slot0:(slot0 + nmember - 1)) + precision_gemm_batched!(adj, 'N', one(T), betaV, input_views, + zero(T), tmp, mode) + precision_gemm_batched!('N', 'N', T(beta), betaU, tmp, + one(T), out_views, mode) + end + return Z +end + +# Factor-stack packing helpers ------------------------------------------------ + +@kernel function _pack_factor_row_kernel!(dest, src, row::Int, qm::Int, qn::Int, + row_major::Bool) + i, k, kidx = @index(Global, NTuple) + tile = row_major ? kidx + (row - 1) * qn : row + (kidx - 1) * qm + @inbounds dest[i, k, kidx] = src[i, k, tile] +end + +@kernel function _pack_factor_column_kernel!(dest, src, col::Int, qm::Int, qn::Int, + row_major::Bool) + i, k, kidx = @index(Global, NTuple) + tile = row_major ? col + (kidx - 1) * qn : kidx + (col - 1) * qm + @inbounds dest[i, k, kidx] = src[i, k, tile] +end + +function _factor_row_stack(p, row::Int, rank::Int; + arena=nothing, force_pack::Bool=false) + if !force_pack && p.order isa TileRowMajor && rank == size(p.data, 2) + return view(p.data, :, :, + (row - 1) * p.qn + 1:row * p.qn) + end + + # packed fallback + backend = get_backend(p.data) + dest = workspace_array!(arena, backend, eltype(p.data), size(p.data, 1), rank, p.qn) + rank == 0 && return dest + _pack_factor_row_kernel!(backend)( + dest, p.data, row, p.qm, p.qn, p.order isa TileRowMajor; + ndrange=size(dest), + ) + return dest +end + +function _factor_column_stack(p, col::Int, rank::Int; + arena=nothing, force_pack::Bool=false) + if !force_pack && p.order isa TileColMajor && rank == size(p.data, 2) + return view(p.data, :, :, + (col - 1) * p.qm + 1:col * p.qm) + end + + # packed fallback + backend = get_backend(p.data) + dest = workspace_array!(arena, backend, eltype(p.data), size(p.data, 1), rank, p.qm) + rank == 0 && return dest + _pack_factor_column_kernel!(backend)( + dest, p.data, col, p.qm, p.qn, p.order isa TileRowMajor; + ndrange=size(dest), + ) + return dest +end + +@inline function _trimmed_tile(p, i::Int, j::Int, rank::Int) + slot = tile_linear_index(p.order, p.qm, p.qn, i, j) + return view(p.data, :, 1:rank, slot) +end + +function _pack_factor_row_into!(dest, p, row::Int) + isempty(dest) && return dest + _pack_factor_row_kernel!(get_backend(dest))( + dest, p.data, row, p.qm, p.qn, p.order isa TileRowMajor; + ndrange=size(dest), + ) + return dest +end + +function _pack_factor_column_into!(dest, p, col::Int) + isempty(dest) && return dest + _pack_factor_column_kernel!(get_backend(dest))( + dest, p.data, col, p.qm, p.qn, p.order isa TileRowMajor; + ndrange=size(dest), + ) + return dest +end + +# Rolling-admission support ------------------------------------------------- + +function _update_beta_slot!(run::RunCoupling{:column}, C, fixed::Int, member::Int, slot::Int) + run.betaU === nothing && return + u = compressed_ftlr_storage_outer(C, member, fixed) + v = compressed_ftlr_storage_inner(C, member, fixed) + run.betaU[slot] = u + run.betaV[slot] = v + run.betaU_ptrs !== nothing && + set_batch_ptrs!(run.betaU_ptrs, slot, [u]) + run.betaV_ptrs !== nothing && + set_batch_ptrs!(run.betaV_ptrs, slot, [v]) +end + +function _update_beta_slot!(run::RunCoupling{:row}, C, fixed::Int, member::Int, slot::Int) + run.betaU === nothing && return + u = compressed_ftlr_storage_outer(C, fixed, member) + v = compressed_ftlr_storage_inner(C, fixed, member) + run.betaU[slot] = u + run.betaV[slot] = v + run.betaU_ptrs !== nothing && + set_batch_ptrs!(run.betaU_ptrs, slot, [u]) + run.betaV_ptrs !== nothing && + set_batch_ptrs!(run.betaV_ptrs, slot, [v]) +end + +function admit_wave!(run::RunCoupling{:column}, ops, rows::AbstractVector{Int}, + slots::UnitRange{Int}, j::Int, arena; + C=nothing, compute=nothing) + isempty(slots) && return run + length(rows) == length(slots) || throw(DimensionMismatch("rows/slots mismatch")) + + # coupling inputs + T = eltype(run.S) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + tarena = run_t_arena(arena) + rA, rB, qk = size(run.S, 1), size(run.S, 2), run.qk + rowV = [ + _factor_row_stack(ops.av, row, rA; arena=tarena, force_pack=true) + for row in rows + ] + colW = _factor_column_stack( + ops.bu, j, rB; arena=tarena, force_pack=true) + + # member and beta factors + for (slot, row) in zip(slots, rows) + _pack_factor_row_into!(run.member[slot], ops.au, row) + C === nothing || _update_beta_slot!(run, C, j, row, slot) + end + + # admitted coupling matrices + if qk > 0 && rA > 0 && rB > 0 + left = [view(rowV[p], :, :, k) for p in eachindex(rows) for k in 1:qk] + right = [view(colW, :, :, k) for _ in rows for k in 1:qk] + dest = [view(run.S, :, :, k, slot) for slot in slots for k in 1:qk] + precision_gemm_batched!( + adjoint_blas_char(T), 'N', one(T), left, right, zero(T), dest, mode) + end + return run +end + +function admit_wave!(run::RunCoupling{:row}, ops, cols::AbstractVector{Int}, + slots::UnitRange{Int}, i::Int, arena; + C=nothing, compute=nothing) + isempty(slots) && return run + length(cols) == length(slots) || throw(DimensionMismatch("cols/slots mismatch")) + + # coupling inputs + T = eltype(run.S) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + rA, rB, qk = size(run.S, 1), size(run.S, 2), run.qk + Ainner = [_trimmed_tile(ops.av, i, k, rA) for k in 1:qk] + + # member and beta factors + for (slot, col) in zip(slots, cols) + _pack_factor_column_into!(run.member[slot], ops.bv, col) + C === nothing || _update_beta_slot!(run, C, i, col, slot) + end + + # admitted coupling matrices + if qk > 0 && rA > 0 && rB > 0 + left = [Ainner[k] for _ in cols for k in 1:qk] + right = [ + _trimmed_tile(ops.bu, k, col, rB) for col in cols for k in 1:qk + ] + dest = [view(run.S, :, :, k, slot) for slot in slots for k in 1:qk] + precision_gemm_batched!( + adjoint_blas_char(T), 'N', one(T), left, right, zero(T), dest, mode) + end + return run +end + +"""Rebind sampling arrays and descriptors after phase-arena reset.""" +function rebind_sampling_scratch!(run::RunCoupling, arena) + a = run_t_arena(arena) + backend = get_backend(run.S) + + # phase arrays + run.proj = workspace_array!(a, backend, eltype(run.S), size(run.proj)...) + run.sketch = workspace_array!(a, backend, eltype(run.S), size(run.sketch)...) + run.Omega = workspace_array!(a, backend, eltype(run.S), size(run.Omega)...) + run.beta_tmp = workspace_array!( + a, backend, eltype(run.S), size(run.beta_tmp)...) + + # refreshed descriptors + cap = size(run.S, 4) + run.sketch_ptrs !== nothing && set_batch_ptrs!( + run.sketch_ptrs, 1, + [view(reshape(run.sketch, :, size(run.sketch, 3), size(run.sketch, 4)), + :, :, p) for p in 1:size(run.sketch, 4)]) + run.sharedOm_ptrs !== nothing && set_batch_ptrs!( + run.sharedOm_ptrs, 1, + [view(run.Omega, :, :, 1) for _ in 1:cap]) + run.beta_tmp_ptrs !== nothing && set_batch_ptrs!( + run.beta_tmp_ptrs, 1, + [view(run.beta_tmp, :, :, p) for p in 1:cap]) + return run +end + +# Arena sizing ------------------------------------------------------------ + +""" + ara_run_workspace_bytes(family, rA, rB, qk, nmember, block, maxrank, bm, bn, + ::Type{T}, ::Type{Thi}) + -> (persistent_t_bytes, phase_t_bytes, phase_thi_bytes) + +Return persistent and peak phase bytes for one `ARARunArena`. Sampling and +finalization share a rewound phase arena; `Q`, `S`, and packed factor stacks +persist. `maxrank` bounds both achieved and beta-term ranks, so the result is +an upper bound enforced by `workspace_array!`. +""" +function ara_run_workspace_bytes(family::Symbol, rA::Int, rB::Int, qk::Int, + nmember::Int, block::Int, maxrank::Int, + bm::Int, bn::Int, ::Type{T}, ::Type{Thi}) where {T,Thi} + blk = min(block, max(maxrank, 1)) + + # family-independent ARA scratch, parameterized by basis height + ara_sample_t(m) = m * blk * nmember + # Yblk + max(maxrank, 1) * blk * nmember + # Dproj + 2 * blk * blk * nmember # R1, R2 + ara_thi(m) = m * blk * nmember + blk * blk * nmember # Y_hi, G_hi + + persistent, phase, thi_elems = if family === :column + persist_t = nmember * bm * rA * qk + # member (rowU) + bn * rB * qk + # shared (colZ) + rA * rB * qk * nmember + # S + bm * maxrank * nmember # Q + constructor_t = nmember * bm * rA * qk + # rowV packing + bn * rB * qk # colW packing + sample_t = rB * block * qk + # proj (Hbuf) + rA * qk * block * nmember + # sketch (Tbuf) + bn * block + # Omega + maxrank * max(block, maxrank) * nmember + # beta_tmp + ara_sample_t(bm) + final_t = rA * maxrank * qk * nmember + # proj (G) + rB * qk * maxrank * nmember + # sketch (Wbuf) + maxrank * maxrank * nmember + # beta_tmp + bn * maxrank * nmember + # Z + bm * maxrank * nmember + # Uh + bn * maxrank * nmember # Vh + (persist_t, max(constructor_t, sample_t, final_t), ara_thi(bm)) + elseif family === :row_left + persist_t = bm * rA * qk + # shared (Astack) + bn * rB * qk * nmember + # member (Bstack) + rA * rB * qk * nmember + # S + bn * maxrank * nmember # right basis Q + sample_t = rA * block * qk + # proj (Gbuf) + rB * qk * block * nmember + # sketch (Wbuf) + bm * block + # Omega + maxrank * max(block, maxrank) * nmember + # beta_tmp + ara_sample_t(bn) + final_t = rB * maxrank * qk * nmember + # proj (H) + rA * qk * maxrank * nmember + # sketch (Tbuf) + maxrank * maxrank * nmember + # beta_tmp + bm * maxrank * nmember + # L + bm * maxrank * nmember + # Uh + bn * maxrank * nmember # Vh + (persist_t, max(sample_t, final_t), ara_thi(bn)) + else + throw(ArgumentError("unknown run family $family")) + end + + return ( + persistent_t_bytes=persistent * sizeof(T), + phase_t_bytes=phase * sizeof(T), + phase_thi_bytes=thi_elems * sizeof(Thi), + ) +end diff --git a/src/tlr/blas/gemm/compressed_accumulation/workspace.jl b/src/tlr/blas/gemm/compressed_accumulation/workspace.jl new file mode 100644 index 00000000..ee95b30a --- /dev/null +++ b/src/tlr/blas/gemm/compressed_accumulation/workspace.jl @@ -0,0 +1,184 @@ +""" + ARARunArena(backend, ::Type{T}, ::Type{Thi}, + persistent_t_bytes, phase_t_bytes, phase_thi_bytes) + +Reusable scratch for a `RunCoupling` and its `ARAWorkspace`, reset by +`arena_reset!` between runs. `persistent_t` holds `Q`, `S`, and packed +factor stacks; `phase_t` is rewound between sampling and finalization; +`phase_thi` holds promoted Cholesky-QR scratch. `run_t_arena` and +`run_thi_arena` also accept `nothing` for allocation-backed callers. +""" +struct ARARunArena{PA<:GemmArena,TA<:GemmArena,HA<:GemmArena} + persistent_t::PA + phase_t::TA + phase_thi::HA +end + +function ARARunArena(backend, ::Type{T}, ::Type{Thi}, + persistent_t_bytes::Int, phase_t_bytes::Int, + phase_thi_bytes::Int) where {T,Thi} + persistent_t_bytes >= 0 && phase_t_bytes >= 0 && phase_thi_bytes >= 0 || + throw(ArgumentError("arena byte counts must be nonnegative")) + + persistent = allocate(backend, T, cld(persistent_t_bytes, sizeof(T))) + phase = allocate(backend, T, cld(phase_t_bytes, sizeof(T))) + phase_hi = allocate(backend, Thi, cld(phase_thi_bytes, sizeof(Thi))) + + return ARARunArena( + GemmArena(persistent, 1), + GemmArena(phase, 1), + GemmArena(phase_hi, 1), + ) +end + +@inline arena_reset!(arena::ARARunArena) = + (arena_reset!(arena.persistent_t); arena_reset!(arena.phase_t); + arena_reset!(arena.phase_thi); arena) +@inline arena_reset_phase!(arena::ARARunArena) = + (arena_reset!(arena.phase_t); arena_reset!(arena.phase_thi); arena) +@inline arena_reset_phase!(::Nothing) = nothing + +@inline run_t_arena(::Nothing) = nothing +@inline run_t_arena(arena::ARARunArena) = arena.phase_t +@inline run_persistent_t_arena(::Nothing) = nothing +@inline run_persistent_t_arena(arena::ARARunArena) = arena.persistent_t +@inline run_thi_arena(::Nothing) = nothing +@inline run_thi_arena(arena::ARARunArena) = arena.phase_thi + +Base.sizeof(arena::ARARunArena) = + sizeof(arena.persistent_t.storage) + + sizeof(arena.phase_t.storage) + + sizeof(arena.phase_thi.storage) + +""" + CompressedGemmWorkspace + +Reusable single-stream storage for canonical TLR-output GEMM: one +phase-reusing `ARARunArena` plus traversal, diagnostic, and scatter buffers. +""" +struct CompressedGemmWorkspace{A,U,V,RS,ES,I,RD,ED,AS,M,P,O,IH,K} + arena::A + U::U + V::V + ranks_slot::RS + errors_slot::ES + indices::I + ranks_global::RD + errors_global::ED + ara_state::AS + member_ids::M + progress::P + output_slots::O + output_slots_inner::O + indices_host::IH + operation::K + capacity::Int +end + +function Base.sizeof(ws::CompressedGemmWorkspace) + return sizeof(ws.arena) + sizeof(ws.U) + sizeof(ws.V) + + sizeof(ws.ranks_slot) + sizeof(ws.errors_slot) + + sizeof(ws.indices) + sizeof(ws.ranks_global) + + sizeof(ws.errors_global) + sizeof(ws.ara_state.dR) + + sum(sizeof, ( + ws.ara_state.status, ws.ara_state.kcut, + ws.ara_state.samples, ws.ara_state.ranks, + ws.ara_state.svec, ws.ara_state.jcount, + ws.ara_state.rmax, + )) +end + +function CompressedGemmWorkspace(C::CompressedFTLRMatrix{BackendT,T}, spec; + bytes=nothing) where {BackendT,T} + # requested byte budget and slot capacity + requested = bytes === nothing ? + tlr_gemm_workspace_bytes(spec, spec.nmember) : bytes + requested >= tlr_gemm_workspace_bytes(spec, 1) || throw(ArgumentError( + "workspace has $requested bytes; at least " * + "$(tlr_gemm_workspace_bytes(spec, 1)) bytes are required")) + capacity = _tlr_workspace_capacity(spec, requested) + backend = get_backend(C) + + # run arena for the selected capacity + ab = ara_run_workspace_bytes( + spec.family, spec.rA, spec.rB, spec.qk, capacity, + spec.block, spec.maxrank, spec.bm, spec.bn, + T, spec.Thi) + arena = ARARunArena( + backend, T, spec.Thi, ab.persistent_t_bytes, + ab.phase_t_bytes, ab.phase_thi_bytes) + + # convergence-state scratch, one entry per slot + n = capacity + opkey = spec + ara_state = ( + dR=allocate(backend, Float64, opkey.block, n), + status=allocate(backend, Int32, n), + status_host=Vector{Int32}(undef, n), + kcut=allocate(backend, Int32, n), + kcut_host=Vector{Int32}(undef, n), + samples=allocate(backend, Int32, n), + ranks=allocate(backend, Int32, n), + svec=allocate(backend, Int32, n), + jcount=allocate(backend, Int32, n), + rmax=allocate(backend, Float64, n), + samples_host=Vector{Int32}(undef, n), + ) + + # traversal output (U, V), diagnostic, and scatter buffers + return CompressedGemmWorkspace( + arena, + allocate(backend, T, opkey.bm, opkey.maxrank, n), + allocate(backend, T, opkey.bn, opkey.maxrank, n), + allocate(backend, opkey.rankT, n), + allocate(backend, Float64, n), + allocate(backend, Int32, n), + allocate(backend, opkey.rankT, opkey.qm * opkey.qn), + allocate(backend, Float64, opkey.qm * opkey.qn), + ara_state, + Vector{Int}(undef, n), + Base.zeros(Int, n), + Vector{Int}(undef, n), + Vector{Int}(undef, n), + Vector{Int32}(undef, n), + spec, + capacity, + ) +end + +function tlr_gemm_workspace_bytes(spec, capacity::Int) + 1 <= capacity <= spec.nmember || + throw(ArgumentError("slot capacity must be in 1:$(spec.nmember)")) + + # arena and traversal storage + k = spec + ab = ara_run_workspace_bytes( + k.family, k.rA, k.rB, k.qk, capacity, k.block, + k.maxrank, k.bm, k.bn, k.T, k.Thi) + arena = ab.persistent_t_bytes + ab.phase_t_bytes + ab.phase_thi_bytes + traversal_t = (k.bm + k.bn) * k.maxrank * capacity * sizeof(k.T) + + # diagnostics and convergence state + diagnostics = capacity * sizeof(k.rankT) + + capacity * sizeof(Float64) + + capacity * sizeof(Int32) + + k.qm * k.qn * (sizeof(k.rankT) + sizeof(Float64)) + ara_state = k.block * capacity * sizeof(Float64) + + 6 * capacity * sizeof(Int32) + + capacity * sizeof(Float64) + + return arena + traversal_t + diagnostics + ara_state +end + +function _tlr_workspace_capacity(spec, bytes::Int) + lo, hi = 1, spec.nmember + while lo < hi + mid = (lo + hi + 1) >>> 1 + if tlr_gemm_workspace_bytes(spec, mid) <= bytes + lo = mid + else + hi = mid - 1 + end + end + return lo +end diff --git a/src/tlr/blas/gemm/compute_policy.jl b/src/tlr/blas/gemm/compute_policy.jl new file mode 100644 index 00000000..d4f0f8f9 --- /dev/null +++ b/src/tlr/blas/gemm/compute_policy.jl @@ -0,0 +1,73 @@ +# TLR compute defaults; generic compute-mode machinery lives in NextLA. +# Float16, BFloat16, Float32, and Float64 are supported, with low-precision +# operands accumulated in Float32. + +@inline default_gemm_compute_mode(::Type{Float16}) = GEMMCompute{Float32}() +@inline default_gemm_compute_mode(::Type{BFloat16}) = GEMMCompute{Float32}() +@inline default_gemm_compute_mode(::Type{Float32}) = GEMMCompute{Float32}() +@inline default_gemm_compute_mode(::Type{Float64}) = GEMMCompute{Float64}() + +function default_gemm_compute_mode(::Type{T}) where {T} + throw(ArgumentError("TLR GEMM does not support operand type $T; supported operand types are Float16, BFloat16, Float32, and Float64")) +end + +function validate_tlr_gemm_precision(backend, ::Type{Tin}, ::Type{Tout}, mode) where {Tin,Tout} + Tin in (Float16, BFloat16, Float32, Float64) || + throw(ArgumentError("TLR GEMM operand type must be Float16, BFloat16, Float32, or Float64; got $Tin")) + validate_gemm_signature(backend, Tin, Tin, Tin, mode) # Stage 1/2 workspace + validate_gemm_signature(backend, Tin, Tin, Tout, mode) # Stage 3 destination + return nothing +end + +# Backends opt in when a compute mode requires rank-aligned tensor-core panels. +@inline required_tlr_gemm_rank_multiple(backend, ::Type, mode) = 1 + +# Backends also opt in when grouped tensor-core kernels require aligned tile +# start addresses. Construction stays backend-agnostic; GEMM owns this error. +@inline validate_compressed_ftlr_tile_alignment( + backend, ::Type, bm::Int, bn::Int) = nothing + +function validate_compressed_ftlr_tile_alignment_cuda( + ::Type{T}, bm::Int, bn::Int) where {T} + q = gemm_alignment_quantum(T) + (is_gemm_aligned(T, bm) && is_gemm_aligned(T, bn)) || throw(ArgumentError( + "CompressedFTLR nominal tile size ($bm, $bn) is not 16-byte aligned for $T: " * + "both extents must be multiples of $q; use " * + "($(cld(bm, q) * q), $(cld(bn, q) * q)) instead")) + return nothing +end + +function validate_tlr_gemm_storage(A, mode; name::AbstractString="operand") + X = A isa TransposeTLRMatrix ? parent(A) : A + X = X isa TLRMatrix ? offdiagonal(X) : X + backend = get_backend(X) + T = eltype(X) + bm, bn = nominal_tile_size(X) + + # tile alignment + validate_compressed_ftlr_tile_alignment(backend, T, bm, bn) + q = required_tlr_gemm_rank_multiple(backend, T, mode) + q <= 1 && return nothing + + # stored-rank alignment + qm, qn = grid_size(X) + @inbounds for j in 1:qn, i in 1:qm + width = compressed_ftlr_storage_rank(X, i, j) + (iszero(width) || iszero(width % q)) || throw(ArgumentError( + "$name stores tile ($i, $j) at rank width $width, but this GEMM " * + "precision requires widths divisible by $q; construct it with " * + "rank_multiple=$q (or a multiple of it)")) + end + return nothing +end + +"""Scale a dense destination once before product terms are accumulated.""" +@inline function scale_output!(C, beta) + T = eltype(C) + if iszero(beta) + fill!(C, zero(T)) + elseif !isone(beta) + C .*= T(beta) + end + return C +end diff --git a/src/tlr/blas/gemm/dense_accumulation/dense_diagonal.jl b/src/tlr/blas/gemm/dense_accumulation/dense_diagonal.jl new file mode 100644 index 00000000..304d2204 --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/dense_diagonal.jl @@ -0,0 +1,241 @@ +@inline diag_tile_ref(A::TLRMatrix, k::Int) = (diag_tile_view(A, k), 'N') +@inline diag_tile_ref(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}, k::Int) = + (diag_tile_view(parent(A), k), 'T') + +"""Nonzero-execution-rank `(i,k,r)` tiles between `OA`'s off-diagonal factors +and `DB`'s diagonal, paired with each tile's intermediate (`S = V'D`) element +count. Shared by the workspace-bound queries and `tlr_offdiag_times_diag!`'s +packing loop, so the two can never enumerate different tile sets.""" +function _tlr_right_cross_items(OA, DB) + qm, qk = grid_size(OA) + items = Tuple{Int,Int,Int}[] + @inbounds for k in 1:min(qk, ndiag_tiles(DB)), i in 1:qm + r = compressed_ftlr_storage_rank(OA, i, k) + r == 0 || push!(items, (i, k, r)) + end + + sizes = [r * length(tile_axis_range(DB, k, 2)) for (_, k, r) in items] + return items, sizes +end + +"""Mirror of [`_tlr_right_cross_items`](@ref): nonzero-execution-rank `(k,j,r)` +tiles between `DA`'s diagonal and `OB`'s off-diagonal factors, paired with +each tile's intermediate (`W = DU`) element count.""" +function _tlr_left_cross_items(OB, DA) + qk, qn = grid_size(OB) + items = Tuple{Int,Int,Int}[] + @inbounds for k in 1:min(qk, ndiag_tiles(DA)), j in 1:qn + r = compressed_ftlr_storage_rank(OB, k, j) + r == 0 || push!(items, (k, j, r)) + end + + sizes = [length(tile_axis_range(DA, k, 1)) * r for (k, _, r) in items] + return items, sizes +end + +"""Workspace element counts for the two off-diagonal/dense-diagonal cross terms.""" +function _tlr_diagonal_intermediate_sizes(A::TLRMatrix, B::TLRMatrix, + transA::Char, transB::Char) + DA = transA == 'T' ? transpose(A) : A + DB = transB == 'T' ? transpose(B) : B + OA = offdiagonal(DA) + OB = offdiagonal(DB) + _, qk = grid_size(OA) + qkB, _ = grid_size(OB) + + qk == qkB || throw(DimensionMismatch("TLR contraction grids do not match")) + + _, right = _tlr_right_cross_items(OA, DB) + _, left = _tlr_left_cross_items(OB, DA) + return right, left +end + +function gemm_minimum_workspace_bytes(A::TLRMatrix, B::TLRMatrix; + transA::Char='N', transB::Char='N') + compressed = gemm_minimum_workspace_bytes( + offdiagonal(A), offdiagonal(B); transA, transB) + right, left = _tlr_diagonal_intermediate_sizes(A, B, transA, transB) + one_cross = max(isempty(right) ? 0 : maximum(right), + isempty(left) ? 0 : maximum(left)) * sizeof(eltype(A)) + return max(compressed, one_cross) +end + +@inline function _tlr_aligned_intermediate_elements(sizes, ::Type{T}) where {T} + alignment = gemm_alignment_quantum(T) + total = 0 + @inbounds for count in sizes + total = cld(total, alignment) * alignment + count + end + return total +end + +function gemm_maximum_workspace_bytes(A::TLRMatrix, B::TLRMatrix; + transA::Char='N', transB::Char='N') + compressed = gemm_maximum_workspace_bytes( + offdiagonal(A), offdiagonal(B); transA, transB) + right, left = _tlr_diagonal_intermediate_sizes(A, B, transA, transB) + T = eltype(A) + all_cross = max(_tlr_aligned_intermediate_elements(right, T), + _tlr_aligned_intermediate_elements(left, T)) * sizeof(T) + return max(compressed, all_cross) +end + +""" + _tlr_pack_cross_items!(mode, arena, capacity, T, items, sizes, push_item!) + +Pack dense-diagonal cross terms into 16-byte-aligned arena passes. `sizes` +contains each intermediate's elements; `push_item!` carves that intermediate +and appends its two `GroupedGemmTask`s. +""" +function _tlr_pack_cross_items!(mode, arena, capacity::Int, ::Type{T}, items, sizes, + push_item!) where {T} + if !isempty(sizes) + needed = maximum(sizes) * sizeof(T) + capacity >= needed || throw(ArgumentError( + "workspace has $capacity bytes; a dense-diagonal update requires at least $needed bytes")) + end + + first_item = 1 + while first_item <= length(items) + arena_reset!(arena) + stage1 = GroupedGemmTask[] + stage2 = GroupedGemmTask[] + + # aligned items for this pass + used = 0 + item = first_item + while item <= length(items) + count = sizes[item] + aligned_used = cld(used, gemm_alignment_quantum(T)) * gemm_alignment_quantum(T) + aligned_used + count <= length(arena.storage) || break + arena.cursor = firstindex(arena.storage) + aligned_used + push_item!(stage1, stage2, item) + used = aligned_used + count + item += 1 + end + + precision_gemm_grouped!(stage1, mode) + precision_gemm_grouped!(stage2, mode) + first_item = item + end + return nothing +end + +# O_A D_B: S_ik = V_A_ik' D_B_kk (stage 1), C[rows,cols] += α U_A_ik S_ik (stage 2). +function tlr_offdiag_times_diag!(C, OA, DB, alpha, mode, arena, capacity::Int) + T = eltype(OA) + items, sizes = _tlr_right_cross_items(OA, DB) + backend = get_backend(OA) + + # cross-term batches + _tlr_pack_cross_items!(mode, arena, capacity, T, items, sizes, + (stage1, stage2, idx) -> begin + i, k, r = items[idx] + cols = tile_axis_range(DB, k, 2) + S = workspace_array!(arena, backend, T, r, length(cols)) + V = compressed_ftlr_storage_inner(OA, i, k) + D, opD = diag_tile_ref(DB, k) + push!(stage1, GroupedGemmTask( + 'T', opD, one(T), V, D, zero(T), S)) + U = compressed_ftlr_storage_outer(OA, i, k) + rows = tile_axis_range(OA, i, 1) + push!(stage2, GroupedGemmTask( + 'N', 'N', alpha, U, S, one(alpha), view(C, rows, cols))) + end) + return C +end + +# D_A O_B: W_kj = D_A_kk U_B_kj (stage 1), C[rows,cols] += α W_kj V_B_kj' (stage 2). +function tlr_diag_times_offdiag!(C, DA, OB, alpha, mode, arena, capacity::Int) + T = eltype(OB) + items, sizes = _tlr_left_cross_items(OB, DA) + backend = get_backend(OB) + + # cross-term batches + _tlr_pack_cross_items!(mode, arena, capacity, T, items, sizes, + (stage1, stage2, idx) -> begin + k, j, r = items[idx] + rows = tile_axis_range(DA, k, 1) + W = workspace_array!(arena, backend, T, length(rows), r) + U = compressed_ftlr_storage_outer(OB, k, j) + D, opD = diag_tile_ref(DA, k) + push!(stage1, GroupedGemmTask( + opD, 'N', one(T), D, U, zero(T), W)) + V = compressed_ftlr_storage_inner(OB, k, j) + cols = tile_axis_range(OB, j, 2) + push!(stage2, GroupedGemmTask( + 'N', 'T', alpha, W, V, one(alpha), view(C, rows, cols))) + end) + return C +end + +function tlr_diag_times_diag!(C, DA, DB, alpha, mode) + n = min(ndiag_tiles(DA), ndiag_tiles(DB)) + tasks = GroupedGemmTask[] + sizehint!(tasks, n) + + # diagonal product tasks + @inbounds for k in 1:n + Atile, opA = diag_tile_ref(DA, k) + Btile, opB = diag_tile_ref(DB, k) + rows = tile_axis_range(DA, k, 1) + cols = tile_axis_range(DB, k, 2) + push!(tasks, GroupedGemmTask( + opA, opB, alpha, Atile, Btile, one(alpha), + view(C, rows, cols))) + end + + isempty(tasks) || precision_gemm_grouped!(tasks, mode) + return C +end + +"""Add the block-diagonal part of `op(A::TLRMatrix) * op(B::Matrix)` to `C`. + +The off-diagonal part is handled by the compressed two-stage lowering. Each +dense diagonal tile contributes to one disjoint output row block, so these +updates need no numerical workspace and can be submitted as one grouped GEMM. +""" +function tlr_diag_times_dense!(C, DA, B, alpha, mode) + tasks = GroupedGemmTask[] + sizehint!(tasks, ndiag_tiles(DA)) + output_cols = 1:size(C, 2) + + # diagonal-row updates + @inbounds for k in 1:ndiag_tiles(DA) + D, opD = diag_tile_ref(DA, k) + rows = tile_axis_range(DA, k, 1) + inner = tile_axis_range(DA, k, 2) + Bdense, opB = dense_block(B, inner, output_cols) + push!(tasks, GroupedGemmTask( + opD, opB, alpha, D, Bdense, one(alpha), + view(C, rows, output_cols))) + end + + isempty(tasks) || precision_gemm_grouped!(tasks, mode) + return C +end + +"""Add the block-diagonal part of `op(A::Matrix) * op(B::TLRMatrix)` to `C`. + +This is the mirror of [`tlr_diag_times_dense!`](@ref): each diagonal tile +updates one disjoint output column block after the compressed FoldLeft pass. +""" +function dense_times_tlr_diag!(C, A, DB, alpha, mode) + tasks = GroupedGemmTask[] + sizehint!(tasks, ndiag_tiles(DB)) + output_rows = 1:size(C, 1) + + # diagonal-column updates + @inbounds for k in 1:ndiag_tiles(DB) + D, opD = diag_tile_ref(DB, k) + inner = tile_axis_range(DB, k, 1) + cols = tile_axis_range(DB, k, 2) + Adense, opA = dense_block(A, output_rows, inner) + push!(tasks, GroupedGemmTask( + opA, opD, alpha, Adense, D, one(alpha), + view(C, output_rows, cols))) + end + + isempty(tasks) || precision_gemm_grouped!(tasks, mode) + return C +end diff --git a/src/tlr/blas/gemm/dense_accumulation/driver.jl b/src/tlr/blas/gemm/dense_accumulation/driver.jl new file mode 100644 index 00000000..b1825219 --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/driver.jl @@ -0,0 +1,395 @@ +# gemm! entry points for the dense-output TLR GEMM: materializes a dense +# C from compressed full-grid factors and optional dense diagonal storage. + +""" + gemm!(C, A, B; workspace, + alpha=true, beta=false, + transA='N', transB='N', compute=nothing) -> C + +Compute `C := alpha·(op(A)·op(B)) + beta·C` for dense-diagonal TLR matrices. +The compressed off-diagonal product uses the common three-stage grouped +lowering; off-diagonal/diagonal cross terms and the diagonal product are added +as grouped updates. `compute` defaults low-precision operands to `Float32` and +otherwise uses the operand type; `alpha` and `beta` use that compute type. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = TLRMatrix(K, (256, 256); maxrank=64, tol=1e-6, rel=true); + +julia> C = zeros(n, n); + +julia> NextLA.gemm!(C, A, A; workspace=gemm_maximum_workspace_bytes(A, A)); + +julia> norm(C - K * K) / norm(K * K) < 1e-5 +true +``` +""" +function gemm!(C::AbstractMatrix, A::TLRMatrix{BackendT,T}, B::TLRMatrix{BackendT,T}; + workspace, alpha=true, beta=false, + transA::Char=('N'), transB::Char=('N'), compute=nothing) where {BackendT,T} + # logical operands and geometry + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch( + "inner dimensions must match: size(op(A),2) == size(op(B),1)")) + size(C) == (size(LA, 1), size(LB, 2)) || throw(DimensionMismatch( + "C must be size(op(A),1) × size(op(B),2)")) + nominal_tile_size(LA, 2) == nominal_tile_size(LB, 1) || + throw(DimensionMismatch( + "op(A)'s column tile size must equal op(B)'s row tile size (contraction tiling)")) + + # compute policy + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + backend = get_backend(A) + validate_tlr_gemm_precision(backend, T, eltype(C), mode) + validate_tlr_gemm_storage(LA, mode; name="compressed left operand") + + # scalars and workspace + ScalarT = gemm_compute_type(mode) + α = ScalarT(alpha) + β = ScalarT(beta) + ws = workspace isa DenseGemmWorkspace ? workspace : DenseGemmWorkspace(A, workspace) + required = gemm_minimum_workspace_bytes(A, B; transA, transB) + sizeof(ws) >= required || throw(ArgumentError( + "workspace has $(sizeof(ws)) bytes; at least $required bytes are required")) + + # compressed and diagonal terms + gemm!(C, offdiagonal(A), offdiagonal(B); + workspace=ws, alpha=α, beta=β, transA, transB, compute=mode) + _, arena, capacity = prepare_dense_accumulation_workspace(A, ws) + tlr_offdiag_times_diag!(C, offdiagonal(LA), LB, α, mode, arena, capacity) + tlr_diag_times_offdiag!(C, LA, offdiagonal(LB), α, mode, arena, capacity) + return tlr_diag_times_diag!(C, LA, LB, α, mode) +end + +function validate_compressed_ftlr_gemm(C::AbstractMatrix, A, B, compute) + T = eltype(A) + + # backend capabilities + (typeof(get_backend(A)) === typeof(get_backend(B)) && + typeof(get_backend(A)) === typeof(get_backend(C))) || + throw(ArgumentError("CompressedFTLR operands and output must use the same backend")) + supports_grouped_gemm(get_backend(A)) || throw(ArgumentError( + "CompressedFTLR dense GEMM requires a grouped-GEMM backend; " * + "currently CPU and CUDA are supported")) + T === BFloat16 && !supports_bfloat16_grouped_gemm(get_backend(A)) && + throw(ArgumentError("CompressedFTLR BF16 grouped GEMMEx requires an NVIDIA SM80 or newer device")) + + # output and packing geometry + size(C) == (size(A, 1), size(B, 2)) || + throw(DimensionMismatch("C must be size(A,1) × size(B,2)")) + nominal_tile_size(A, 2) == nominal_tile_size(B, 1) || + throw(DimensionMismatch("CompressedFTLR contraction tile dimensions must match")) + compressed_ftlr_outer_order(B) isa TileRowMajor || + throw(ArgumentError("CompressedFTLR Stage-1 fusion requires the logical B outer factors to be tile-row-major")) + (compressed_ftlr_right_valid(A, B) || compressed_ftlr_left_valid(A, B)) || + throw(ArgumentError("CompressedFTLR needs a FoldRight A-U row stack or a FoldLeft B-Z column stack")) + _, qk = grid_size(A) + qk == grid_size(B)[1] || throw(DimensionMismatch( + "CompressedFTLR contraction grids do not match")) + @inbounds for k in 1:qk + length(tile_axis_range(A, k, 2)) == length(tile_axis_range(B, k, 1)) || + throw(DimensionMismatch( + "CompressedFTLR contraction tile $k has incompatible tail extents")) + end + + # precision and storage + validate_tlr_gemm_precision(get_backend(A), T, eltype(C), compute) + validate_tlr_gemm_storage(A, compute; name="left operand") + validate_tlr_gemm_storage(B, compute; name="right operand") + # grouped output-storage limitation + # CUDA grouped GEMM rejects low-precision input with Float32 output. + eltype(C) === T || throw(ArgumentError( + "CompressedFTLR grouped GEMMEx currently requires output storage to match operand storage; " * + "got $T × $T → $(eltype(C))", + )) + return nothing +end + +""" + gemm!(C, A::CompressedFTLRMatrix, B::CompressedFTLRMatrix; workspace, alpha=true, beta=false) + +Exact-rank dense accumulation for logical `N/T` operands and trailing boundary +tiles. Packed layouts select FoldRight or FoldLeft grouped lowering. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> C = zeros(n, n); + +julia> NextLA.gemm!(C, A, A; workspace=gemm_maximum_workspace_bytes(A, A), transB='T'); + +julia> norm(C - K * transpose(K)) / norm(K * transpose(K)) < 1e-5 +true +``` +""" +function gemm!(C::AbstractMatrix, A::CompressedFTLRMatrix{BackendT,T}, B::CompressedFTLRMatrix{BackendT,T}; + workspace, alpha=true, beta=false, + transA::Char='N', transB::Char='N', compute=nothing, analysis=nothing) where {BackendT,T} + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C must be size(op(A),1) × size(op(B),2)")) + + # compute scalars + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + ScalarT = gemm_compute_type(mode) + α = ScalarT(alpha) + β = ScalarT(beta) + + # symbolic analysis and execution + if analysis === nothing + # one-shot prepared descriptors + validate_compressed_ftlr_gemm(C, LA, LB, mode) + # mutable ranks may invalidate the construction-time maximum + (all(iszero, ranks(A)) || all(iszero, ranks(B))) && + return scale_output!(C, β) + ws = workspace isa DenseGemmWorkspace ? workspace : + DenseGemmWorkspace(A, workspace) + one_shot = analyze_compressed_gemm( + C, A, B; workspace=ws, transA, transB, compute=mode) + try + return execute_compressed_gemm_analysis!( + one_shot, C, A, B, ws, α, β, transA, transB, mode) + finally + close(one_shot) + end + elseif analysis isa CompressedGemmAnalysis + return execute_compressed_gemm_analysis!( + analysis, C, A, B, workspace, α, β, transA, transB, mode) + end + + throw(ArgumentError("analysis must be nothing or CompressedGemmAnalysis")) +end + +@inline function validate_dense_backend(C, compressed, dense) + backend = get_backend(compressed) + typeof(get_backend(dense)) === typeof(backend) && + typeof(get_backend(C)) === typeof(backend) || + throw(ArgumentError( + "compressed operand, dense operand, and output must use the same backend")) + return backend +end + +""" + gemm!(C, A::TLRMatrix, B::AbstractMatrix; ...) + +Compute `C := alpha*op(A)*op(B) + beta*C` for a dense-diagonal TLR left +operand. The compressed off-diagonal part uses the fixed FoldRight two-stage +lowering; the dense diagonal is then added as independent block GEMMs. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = TLRMatrix(K, (256, 256); maxrank=64, tol=1e-6, rel=true); + +julia> B = rand(n, n); C = zeros(n, n); + +julia> NextLA.gemm!(C, A, B; workspace=2^20); + +julia> norm(C - K * B) / norm(K * B) < 1e-5 +true +``` +""" +function gemm!(C::AbstractMatrix, A::TLRMatrix{BackendT,T}, + B::AbstractMatrix{T}; + workspace, alpha=true, beta=false, + transA::Char='N', transB::Char='N', compute=nothing) where {BackendT,T} + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + ScalarT = gemm_compute_type(mode) + alpha_value = ScalarT(alpha) + gemm!(C, offdiagonal(A), B; + workspace, alpha=alpha_value, beta=ScalarT(beta), transA, transB, + compute=mode) + return tlr_diag_times_dense!( + C, transA == 'T' ? transpose(A) : A, transB == 'T' ? transpose(B) : B, + alpha_value, mode) +end + +""" + gemm!(C, A::AbstractMatrix, B::TLRMatrix; ...) + +Compute `C := alpha*op(A)*op(B) + beta*C` for a dense-diagonal TLR right +operand. The compressed off-diagonal part uses the fixed FoldLeft two-stage +lowering; the dense diagonal is then added as independent block GEMMs. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> B = TLRMatrix(K, (256, 256); maxrank=64, tol=1e-6, rel=true); + +julia> A = rand(n, n); C = rand(n, n); C0 = copy(C); + +julia> NextLA.gemm!(C, A, B; workspace=2^20, alpha=2.0, beta=-1.0); + +julia> norm(C - (2 * A * K - C0)) / norm(2 * A * K - C0) < 1e-5 +true +``` +""" +function gemm!(C::AbstractMatrix, A::AbstractMatrix{T}, + B::TLRMatrix{BackendT,T}; + workspace, alpha=true, beta=false, + transA::Char='N', transB::Char='N', compute=nothing) where {BackendT,T} + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + ScalarT = gemm_compute_type(mode) + alpha_value = ScalarT(alpha) + gemm!(C, A, offdiagonal(B); + workspace, alpha=alpha_value, beta=ScalarT(beta), transA, transB, + compute=mode) + return dense_times_tlr_diag!( + C, transA == 'T' ? transpose(A) : A, transB == 'T' ? transpose(B) : B, + alpha_value, mode) +end + +function _execute_one_shot_two_stage!( + C, A, B, workspace, alpha, beta, transA, transB, mode) + analysis = analyze_compressed_gemm( + C, A, B; workspace, transA, transB, compute=mode) + try + return execute_compressed_mixed_analysis!( + analysis, C, A, B, workspace, alpha, beta, + transA, transB, mode) + finally + close(analysis) + end +end + +""" + gemm!(C, A::CompressedFTLRMatrix, B::AbstractMatrix; ...) + +Compute `C := alpha·op(A)·op(B) + beta·C`. The first stage fuses +`Vᵢₖ′Bₖ` contractions across an output-column run; the second stage applies +the corresponding row-packed `Uᵢₖ` stack and accumulates into dense `C`. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> B = rand(n, n); C = zeros(n, n); + +julia> NextLA.gemm!(C, A, B; workspace=2^20, transB='T'); + +julia> norm(C - K * transpose(B)) / norm(K * transpose(B)) < 1e-5 +true +``` +""" +function gemm!(C::AbstractMatrix, A::CompressedFTLRMatrix{BackendT,T}, + B::AbstractMatrix{T}; + workspace, alpha=true, beta=false, analysis=nothing, + transA::Char='N', transB::Char='N', compute=nothing) where {BackendT,T} + # logical operands and validation + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C must be size(op(A),1) × size(op(B),2)")) + backend = validate_dense_backend(C, A, B) + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + validate_tlr_gemm_precision(backend, T, eltype(C), mode) + validate_tlr_gemm_storage(LA, mode; name="compressed left operand") + ScalarT = gemm_compute_type(mode) + + # reusable analysis + if analysis !== nothing + analysis isa CompressedMixedGemmAnalysis || throw(ArgumentError( + "analysis must be nothing or CompressedMixedGemmAnalysis")) + return execute_compressed_mixed_analysis!( + analysis, C, A, B, workspace, ScalarT(alpha), ScalarT(beta), + transA, transB, mode) + end + + # workspace-dependent execution path + ws, arena, budget = prepare_dense_accumulation_workspace(A, workspace) + plan = two_stage_rank_plan(LA, :right) + if budget < plan.total_rank * sizeof(T) + return compressed_dense_gemm_sequential!( + C, LA, LB, ScalarT(alpha), ScalarT(beta), budget, mode, arena) + end + return _execute_one_shot_two_stage!( + C, A, B, ws, ScalarT(alpha), ScalarT(beta), transA, transB, mode) +end + +""" + gemm!(C, A::AbstractMatrix, B::CompressedFTLRMatrix; ...) + +Compute `C := alpha·op(A)·op(B) + beta·C`. The mirrored two-stage lowering +fuses dense-panel-times-`Uₖⱼ` contractions over an output-row run before applying +the column-packed `Vₖⱼ` stack to dense `C`. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> B = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> A = rand(n, n); C = zeros(n, n); + +julia> NextLA.gemm!(C, A, B; workspace=2^20); + +julia> norm(C - A * K) / norm(A * K) < 1e-5 +true +``` +""" +function gemm!(C::AbstractMatrix, A::AbstractMatrix{T}, + B::CompressedFTLRMatrix{BackendT,T}; + workspace, alpha=true, beta=false, analysis=nothing, + transA::Char='N', transB::Char='N', compute=nothing) where {BackendT,T} + # logical operands and validation + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C must be size(op(A),1) × size(op(B),2)")) + backend = validate_dense_backend(C, B, A) + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + validate_tlr_gemm_precision(backend, T, eltype(C), mode) + validate_tlr_gemm_storage(LB, mode; name="compressed right operand") + ScalarT = gemm_compute_type(mode) + + # reusable analysis + if analysis !== nothing + analysis isa CompressedMixedGemmAnalysis || throw(ArgumentError( + "analysis must be nothing or CompressedMixedGemmAnalysis")) + return execute_compressed_mixed_analysis!( + analysis, C, A, B, workspace, ScalarT(alpha), ScalarT(beta), + transA, transB, mode) + end + + # workspace-dependent execution path + ws, arena, budget = prepare_dense_accumulation_workspace(B, workspace) + plan = two_stage_rank_plan(LB, :left) + if budget < plan.total_rank * sizeof(T) + return dense_compressed_gemm_sequential!( + C, LA, LB, ScalarT(alpha), ScalarT(beta), budget, mode, arena) + end + return _execute_one_shot_two_stage!( + C, A, B, ws, ScalarT(alpha), ScalarT(beta), transA, transB, mode) +end diff --git a/src/tlr/blas/gemm/dense_accumulation/runs.jl b/src/tlr/blas/gemm/dense_accumulation/runs.jl new file mode 100644 index 00000000..2f2801f5 --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/runs.jl @@ -0,0 +1,156 @@ +"""A scheduled dense-output region and the fold used to lower it. + +For compressed × compressed, `rows` and `cols` index output tile ranges. For a +two-stage specialization, the dense axis is a physical matrix range and the +compressed axis is a tile range. The fold has the same meaning in every case: +`:right` ends with the compressed left operand's outer stack, while `:left` +ends with the compressed right operand's inner stack. +""" +struct DenseAccumulationRun + rows::UnitRange{Int} + cols::UnitRange{Int} + fold::Symbol +end + +"""Unprepared grouped tasks for one dense-output run. + +Two-stage products leave `stage3 === nothing` and set `terminal_stage == 2`; +compressed × compressed sets `terminal_stage == 3`. The terminal stage is the +only stage whose prepared scalars are replaced by the numerical call's +`alpha` and `beta`. +""" +struct DenseAccumulationRunTasks{S1,S2,S3,Z} + stage1::S1 + stage2::S2 + stage3::S3 + terminal_stage::Int + zero_target::Z + needs_zero::Bool + scale_targets::Vector{Tuple{UnitRange{Int},UnitRange{Int}}} +end + +"""One dense-output run with persistent grouped-GEMM descriptors.""" +struct PreparedDenseAccumulationRun + stage1::Union{Nothing,AbstractPreparedGroupedGemm} + stage2::Union{Nothing,AbstractPreparedGroupedGemm} + stage3::Union{Nothing,AbstractPreparedGroupedGemm} + terminal_stage::Int + zero_target::Any + needs_zero::Bool + scale_targets::Vector{Tuple{UnitRange{Int},UnitRange{Int}}} +end + +@inline function _destroy_prepared_dense_accumulation_run!(run::PreparedDenseAccumulationRun) + run.stage1 === nothing || destroy_prepared_grouped_gemm!(run.stage1) + run.stage2 === nothing || destroy_prepared_grouped_gemm!(run.stage2) + run.stage3 === nothing || destroy_prepared_grouped_gemm!(run.stage3) + return nothing +end + +function _prepare_dense_accumulation_run(tasks::DenseAccumulationRunTasks, mode) + stage1 = stage2 = stage3 = nothing + try + stage1 = tasks.stage1 === nothing ? nothing : + prepare_precision_gemm_grouped(tasks.stage1, mode) + stage2 = tasks.stage2 === nothing ? nothing : + prepare_precision_gemm_grouped(tasks.stage2, mode) + stage3 = tasks.stage3 === nothing ? nothing : + prepare_precision_gemm_grouped(tasks.stage3, mode) + catch + stage1 === nothing || destroy_prepared_grouped_gemm!(stage1) + stage2 === nothing || destroy_prepared_grouped_gemm!(stage2) + stage3 === nothing || destroy_prepared_grouped_gemm!(stage3) + rethrow() + end + + return PreparedDenseAccumulationRun( + stage1, stage2, stage3, tasks.terminal_stage, tasks.zero_target, + tasks.needs_zero, tasks.scale_targets) +end + +function prepare_dense_accumulation_runs(build_tasks, schedule, mode) + prepared = PreparedDenseAccumulationRun[] + sizehint!(prepared, length(schedule)) + try + for run in schedule + push!(prepared, _prepare_dense_accumulation_run(build_tasks(run), mode)) + end + catch + foreach(_destroy_prepared_dense_accumulation_run!, prepared) + rethrow() + end + + return prepared +end + +@inline dense_accumulation_runs_have_fallback(runs) = + any(run -> any(stage -> stage isa PreparedGroupedGemmBundle, + (run.stage1, run.stage2, run.stage3)), runs) + +function close_dense_accumulation_analysis!(analysis) + analysis.closed && return analysis + analysis.closed = true + foreach(_destroy_prepared_dense_accumulation_run!, analysis.runs) + return analysis +end + +function validate_dense_accumulation_analysis_binding( + analysis, C, A, B, workspace, transA, transB, mode) + analysis.closed && throw(ArgumentError("dense-accumulation analysis has been closed")) + C === analysis.C && A === analysis.A && B === analysis.B || + throw(ArgumentError("analysis is bound to different matrix objects")) + workspace === analysis.workspace && sizeof(workspace) == analysis.workspace_bytes || + throw(ArgumentError("analysis numerical workspace does not match")) + transA == analysis.transA && transB == analysis.transB || + throw(ArgumentError("analysis transpose modes do not match")) + typeof(mode) === typeof(analysis.compute) || + throw(ArgumentError("analysis compute policy does not match")) + return nothing +end + +@inline function _submit_prepared_dense_accumulation_stage( + stage, backend, manage_pointer_mode, overrides...) + stage === nothing && return nothing + if manage_pointer_mode && !(stage isa PreparedGroupedGemmBundle) + return with_grouped_host_pointer_mode(backend) do + precision_gemm_grouped_prepared!(stage, overrides...) + end + end + return precision_gemm_grouped_prepared!(stage, overrides...) +end + +function _execute_prepared_dense_accumulation_runs_inner!( + runs, C, backend, ::Type{T}, alpha, beta, manage_pointer_mode) where {T} + for run in runs + # beta pre-scale for the terminal stage's untouched output region + run.needs_zero && fill!(run.zero_target, zero(T)) + @inbounds for (rows, cols) in run.scale_targets + scale_output!(view(C, rows, cols), beta) + end + + # stage submission with terminal scalar overrides + @inbounds for (index, stage) in enumerate((run.stage1, run.stage2, run.stage3)) + if index == run.terminal_stage + _submit_prepared_dense_accumulation_stage( + stage, backend, manage_pointer_mode, alpha, beta) + else + _submit_prepared_dense_accumulation_stage( + stage, backend, manage_pointer_mode) + end + end + end + + return C +end + +function execute_prepared_dense_accumulation_runs!( + runs, C, backend, ::Type{T}, alpha, beta, has_fallback::Bool) where {T} + if has_fallback + return _execute_prepared_dense_accumulation_runs_inner!( + runs, C, backend, T, alpha, beta, true) + end + return with_grouped_host_pointer_mode(backend) do + _execute_prepared_dense_accumulation_runs_inner!( + runs, C, backend, T, alpha, beta, false) + end +end diff --git a/src/tlr/blas/gemm/dense_accumulation/schedule.jl b/src/tlr/blas/gemm/dense_accumulation/schedule.jl new file mode 100644 index 00000000..0f6279f6 --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/schedule.jl @@ -0,0 +1,435 @@ +"""Whether FoldRight has the required row-packed outer factors.""" + +@inline compressed_ftlr_right_valid(A, B) = + compressed_ftlr_outer_order(A) isa TileRowMajor && compressed_ftlr_outer_order(B) isa TileRowMajor +@inline compressed_ftlr_left_valid(A, B) = + compressed_ftlr_outer_order(B) isa TileRowMajor && compressed_ftlr_inner_order(B) isa TileColMajor + +@inline function compressed_ftlr_prefix(values::Vector{Int}) + prefix = Base.zeros(Int, length(values) + 1) + @inbounds for i in eachindex(values) + prefix[i + 1] = prefix[i] + values[i] + end + return prefix +end + +@inline _compressed_ftlr_range_total(prefix::Vector{Int}, rows::UnitRange{Int}) = + prefix[last(rows) + 1] - prefix[first(rows)] + +# column-range views: work is scheduled over tile rows `irange` × tile columns +# `jrange`; a narrower `jrange` than the full `1:qn` is what lets the workspace +# budget be met below one output row, so every `j`-aggregating quantity below +# is queried on the range rather than read whole. + +"""`σ_k` restricted to `jrange`: `Σ_{j ∈ jrange} rB_kj`.""" +@inline compressed_ftlr_row_rank(meta, k::Int, jrange) = + meta.b_row_k_prefix[k, last(jrange) + 1] - meta.b_row_k_prefix[k, first(jrange)] + +"""Column offset of tile `j` inside a `jrange`-local S block.""" +@inline compressed_ftlr_row_rank_offset(meta, k::Int, j::Int, jrange) = + meta.b_row_k_prefix[k, j] - meta.b_row_k_prefix[k, first(jrange)] + +"""Total output width spanned by `jrange`, in matrix columns.""" +@inline compressed_ftlr_width(meta, jrange) = + meta.output_col_prefix[last(jrange) + 1] - meta.output_col_prefix[first(jrange)] + +"""Matrix column span of `jrange` in the dense output.""" +@inline function compressed_ftlr_output_cols(B, jrange) + lo = first(tile_axis_range(B, first(jrange), 2)) + hi = last(tile_axis_range(B, last(jrange), 2)) + return lo:hi +end + +""" + _compressed_ftlr_rank_metadata(A, B) + +Build host rank prefixes for constant-time range queries. `a_k_prefix` tracks A +over `k`; `b_row_ranks` and `b_col_ranks` are B's row/column rank sums; +`pair_ranks[i] = Σ_k rA_ik·b_row_ranks[k]`. Output extents are rank-independent. +""" +function _compressed_ftlr_rank_metadata(A, B) + qm, qk = grid_size(A) + qkB, qn = grid_size(B) + qk == qkB || throw(DimensionMismatch("CompressedFTLR contraction grids do not match")) + + a_k_prefix = Base.zeros(Int, qm, qk + 1) + b_row_ranks = Base.zeros(Int, qk) + b_col_ranks = Base.zeros(Int, qn) + b_col_k_prefix = Base.zeros(Int, qn, qk + 1) + b_row_k_prefix = Base.zeros(Int, qk, qn + 1) + + # nonzero B-tile prefixes + # Stage 2 skips zero-rank tiles, so execution needs O(1) hole detection per range. + b_row_nonzero_prefix = Base.zeros(Int, qk, qn + 1) + @inbounds for k in 1:qk, j in 1:qn + r = compressed_ftlr_storage_rank(B, k, j) + b_row_ranks[k] += r + b_col_ranks[j] += r + b_row_nonzero_prefix[k, j + 1] = b_row_nonzero_prefix[k, j] + (r != 0) + end + + # B rank prefixes + @inbounds for j in 1:qn, k in 1:qk + b_col_k_prefix[j, k + 1] = b_col_k_prefix[j, k] + compressed_ftlr_storage_rank(B, k, j) + end + @inbounds for k in 1:qk, j in 1:qn + b_row_k_prefix[k, j + 1] = b_row_k_prefix[k, j] + compressed_ftlr_storage_rank(B, k, j) + end + + # A prefixes and shared-stage sizes + pair_ranks = Base.zeros(Int, qm) + @inbounds for i in 1:qm, k in 1:qk + r = compressed_ftlr_storage_rank(A, i, k) + a_k_prefix[i, k + 1] = a_k_prefix[i, k] + r + pair_ranks[i] += r * b_row_ranks[k] + end + + # output geometry + b_col_prefix = compressed_ftlr_prefix(b_col_ranks) + output_row_heights = [length(tile_axis_range(A, i, 1)) for i in 1:qm] + output_col_widths = [length(tile_axis_range(B, j, 2)) for j in 1:qn] + output_col_prefix = compressed_ftlr_prefix(output_col_widths) + + return (; a_k_prefix, qk, b_col_ranks, b_col_k_prefix, b_row_k_prefix, + b_col_prefix, b_row_nonzero_prefix, pair_ranks, + output_row_heights, output_col_widths, output_col_prefix) +end + +""" + _compressed_ftlr_fold_cost(meta, A, B) + +Per-row byte and FLOP costs for both fold bracketings: + + F_R(i) = 2·n_·Σ_k rA_ik·rB_k· + 2·m_i·n_·ρ_i (Stage 2 + Stage 3, FoldRight) + F_L(i) = 2·m_i·Σ_k rA_ik·rB_k· + 2·m_i·n_·γ_· (Stage 2 + Stage 3, FoldLeft) + +Stage 2 is shared; only Stage 3 differs. Costs must not short-circuit when +`pair_ranks[i] == 0`: A may retain rank where B's contraction row is zero, and a +zero-rank row inside a FoldLeft run still occupies its contiguous output slice. +Unconditional terms therefore match the allocated arenas. +""" +function _compressed_ftlr_fold_cost(meta, A, B, + jrange::UnitRange{Int}=1:length(meta.output_col_widths)) + qm = length(meta.pair_ranks) + qk = meta.qk + Tbytes = sizeof(eltype(A)) + width = compressed_ftlr_width(meta, jrange) + total_rank = meta.b_col_prefix[last(jrange) + 1] - + meta.b_col_prefix[first(jrange)] + + # column-restricted shared-stage sizes + # `pair_ranks` is full-grid, so narrower column ranges are recomputed. + pair = if jrange == 1:length(meta.output_col_widths) + meta.pair_ranks + else + p = Base.zeros(Int, qm) + @inbounds for i in 1:qm, k in 1:qk + p[i] += compressed_ftlr_storage_rank(A, i, k) * + compressed_ftlr_row_rank(meta, k, jrange) + end + p + end + + # per-row workspace + right = compressed_ftlr_right_valid(A, B) ? + [(pair[i] + width * meta.a_k_prefix[i, end]) * Tbytes for i in 1:qm] : nothing + left = compressed_ftlr_left_valid(A, B) ? + [(pair[i] + meta.output_row_heights[i] * total_rank) * Tbytes for i in 1:qm] : nothing + (right === nothing && left === nothing) && throw(ArgumentError( + "CompressedFTLR needs row-packed B outer factors and either row-packed A outer factors or column-packed B inner factors")) + row_bytes = [min(right === nothing ? typemax(Int) : right[i], + left === nothing ? typemax(Int) : left[i]) for i in 1:qm] + + # hoisted flop weights over the selected columns + # `ω_k` reduces the FoldRight sum to O(qk·qn + qm·qk); FoldLeft's weighted + # column rank is likewise independent of output row. + omega = Base.zeros(Int, qk) + @inbounds for k in 1:qk, j in jrange + omega[k] += meta.output_col_widths[j] * compressed_ftlr_storage_rank(B, k, j) + end + weighted_col_rank = 0 + @inbounds for j in jrange + weighted_col_rank += meta.output_col_widths[j] * meta.b_col_ranks[j] + end + + # per-row flop costs + right_flops = right === nothing ? nothing : + [sum((compressed_ftlr_storage_rank(A, i, k) * omega[k] for k in 1:qk); init=0) + + meta.output_row_heights[i] * width * meta.a_k_prefix[i, end] + for i in 1:qm] + left_flops = left === nothing ? nothing : + [meta.output_row_heights[i] * (pair[i] + weighted_col_rank) for i in 1:qm] + + # prefix profiles + maximum_bytes = min(right === nothing ? typemax(Int) : sum(right), + left === nothing ? typemax(Int) : sum(left)) + return ( + columns=jrange, nrows=qm, + right_byte_prefix=right === nothing ? nothing : compressed_ftlr_prefix(right), + left_byte_prefix=left === nothing ? nothing : compressed_ftlr_prefix(left), + right_flop_prefix=right_flops === nothing ? nothing : compressed_ftlr_prefix(right_flops), + left_flop_prefix=left_flops === nothing ? nothing : compressed_ftlr_prefix(left_flops), + minimum=isempty(row_bytes) ? 0 : maximum(row_bytes), maximum=maximum_bytes, + ) +end + +"""One rectangular output-tile run executed with one `fold`.""" +function compressed_ftlr_rank_plan(A, B) + meta = _compressed_ftlr_rank_metadata(A, B) + profile = _compressed_ftlr_fold_cost(meta, A, B) + return (; meta..., profile) +end + +""" + gemm_minimum_workspace_bytes(A, B; transA='N', transB='N') -> Int + +Single-column workspace floor. The maximum workspace gives the fastest schedule. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> lo = gemm_minimum_workspace_bytes(A, A); + +julia> C = zeros(n, n); + +julia> NextLA.gemm!(C, A, A; workspace=lo); + +julia> lo <= gemm_maximum_workspace_bytes(A, A) && norm(C - K * K) / norm(K * K) < 1e-5 +true +``` +""" +function gemm_minimum_workspace_bytes(A::CompressedFTLRMatrix, B::CompressedFTLRMatrix; + transA::Char='N', transB::Char='N') + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + return _compressed_ftlr_column_floor(compressed_ftlr_rank_plan(LA, LB), LA, LB) +end + +""" + gemm_maximum_workspace_bytes(A, B; transA='N', transB='N') -> Int + +Largest workspace, in bytes, that the dense-output `gemm!(C, A, B; workspace)` +uses for `C := op(A)·op(B)`; a larger workspace is accepted but not used beyond +this. + +`A` and `B` are both `CompressedFTLRMatrix` or both `TLRMatrix`; `transA` and +`transB` select `op` as in `gemm!`. For `CompressedFTLRMatrix` operands the +result is the byte count that schedules the whole product as one run with the +cheaper fold. For `TLRMatrix` operands it is the larger of that value for the +off-diagonal parts and the bytes that hold every off-diagonal/dense-diagonal +cross-term intermediate at once. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = TLRMatrix(K, (256, 256); maxrank=64, tol=1e-6, rel=true); + +julia> hi = gemm_maximum_workspace_bytes(A, A); + +julia> C = zeros(n, n); + +julia> NextLA.gemm!(C, A, A; workspace=hi); + +julia> hi >= gemm_minimum_workspace_bytes(A, A) && norm(C - K * K) / norm(K * K) < 1e-5 +true +``` +""" +function gemm_maximum_workspace_bytes(A::CompressedFTLRMatrix, B::CompressedFTLRMatrix; + transA::Char='N', transB::Char='N') + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + return compressed_ftlr_rank_plan(LA, LB).profile.maximum +end + +""" + gemm_workspace_bytes(A, B; runs=1, transA='N', transB='N') -> Int + +Smallest workspace yielding at most `runs` rectangular work units. `runs = 1` +equals `gemm_maximum_workspace_bytes`; the result is clamped at +`gemm_minimum_workspace_bytes`. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> bytes = gemm_workspace_bytes(A, A; runs=2); + +julia> C = zeros(n, n); + +julia> NextLA.gemm!(C, A, A; workspace=bytes); + +julia> bytes <= gemm_maximum_workspace_bytes(A, A) && norm(C - K * K) / norm(K * K) < 1e-5 +true +``` +""" +function gemm_workspace_bytes(A::CompressedFTLRMatrix, B::CompressedFTLRMatrix; + runs::Int=1, transA::Char='N', transB::Char='N') + runs >= 1 || throw(ArgumentError("runs must be positive; got $runs")) + + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + plan = compressed_ftlr_rank_plan(LA, LB) + lo = _compressed_ftlr_column_floor(plan, LA, LB) + hi = plan.profile.maximum + scheduled(bytes) = length(compressed_ftlr_column_schedule(plan, LA, LB, plan.profile, bytes)) + + # monotone budget bisection + scheduled(lo) <= runs && return lo + while lo < hi + mid = lo + (hi - lo) ÷ 2 + if scheduled(mid) <= runs + hi = mid + else + lo = mid + 1 + end + end + return hi +end + +"""Contiguous output-row runs greedily packed under an exact ragged budget.""" +function _compressed_ftlr_row_runs(profile, budget::Int) + budget >= profile.minimum || throw(ArgumentError( + "workspace has $budget bytes; at least $(profile.minimum) bytes are required")) + + # greedy contiguous rows + runs = DenseAccumulationRun[] + i = 1 + while i <= profile.nrows + j = i - 1 + while j < profile.nrows && _compressed_ftlr_select_fold(profile, i:(j + 1), budget) !== nothing + j += 1 + end + # A zero-work row is allowed even for a zero byte budget. + j >= i || (j = i) + fold = _compressed_ftlr_select_fold(profile, i:j, budget) + fold === nothing && throw(ArgumentError("workspace cannot schedule CompressedFTLR row $i")) + push!(runs, DenseAccumulationRun(i:j, profile.columns, fold)) + i = j + 1 + end + + return runs +end + +function _compressed_ftlr_select_fold(profile, rows::UnitRange{Int}, budget::Int) + # workspace feasibility + right_bytes = profile.right_byte_prefix === nothing ? typemax(Int) : + _compressed_ftlr_range_total(profile.right_byte_prefix, rows) + left_bytes = profile.left_byte_prefix === nothing ? typemax(Int) : + _compressed_ftlr_range_total(profile.left_byte_prefix, rows) + right_ok = right_bytes <= budget + left_ok = left_bytes <= budget + !right_ok && !left_ok && return nothing + right_ok && !left_ok && return :right + left_ok && !right_ok && return :left + + # flop tiebreak + right_flops = _compressed_ftlr_range_total(profile.right_flop_prefix, rows) + left_flops = _compressed_ftlr_range_total(profile.left_flop_prefix, rows) + return right_flops <= left_flops ? :right : :left +end + +# Column-block partitioning lowers the workspace floor when a full output row +# does not fit. The rectangles tile `C` without repeated accumulation; only A's +# outer factors are reread. Full-width scheduling remains the fast path. + +""" +Widest column block from `j0` whose row floor fits `budget`. Monotonicity permits +bisection; returns `nothing` if one column cannot fit. +""" +function _compressed_ftlr_widest_column_block(meta, A, B, j0::Int, qn::Int, budget::Int) + _compressed_ftlr_fold_cost(meta, A, B, j0:j0).minimum <= budget || return nothing + lo, hi = j0, qn # lo always feasible, hi+1 always infeasible + while lo < hi + mid = (lo + hi + 1) >> 1 + if _compressed_ftlr_fold_cost(meta, A, B, j0:mid).minimum <= budget + lo = mid + else + hi = mid - 1 + end + end + return j0:lo +end + +""" +Schedule the output under `budget`, using sequential column blocks only when a +full-width run does not fit. Peak workspace is the maximum over runs. +""" +function compressed_ftlr_column_schedule(meta, A, B, profile, + budget::Int) + # full-width fast path + profile.minimum <= budget && return _compressed_ftlr_row_runs(profile, budget) + + # sequential column blocks + qn = length(meta.output_col_widths) + runs = DenseAccumulationRun[] + j = 1 + while j <= qn + block = _compressed_ftlr_widest_column_block(meta, A, B, j, qn, budget) + block === nothing && throw(ArgumentError( + "workspace has $budget bytes; not enough for a single output tile column")) + append!(runs, _compressed_ftlr_row_runs( + _compressed_ftlr_fold_cost(meta, A, B, block), budget)) + j = last(block) + 1 + end + + return runs +end + +"""Smallest workspace in which any schedule exists: the per-row floor of the +narrowest (single-column) blocks, which is what column subdivision buys over the +full-width floor `profile.minimum`.""" +function _compressed_ftlr_column_floor(meta, A, B) + qn = length(meta.output_col_widths) + floor_bytes = 0 + @inbounds for j in 1:qn + floor_bytes = max(floor_bytes, _compressed_ftlr_fold_cost(meta, A, B, j:j).minimum) + end + return floor_bytes +end + +function prepare_compressed_ftlr_workspace(A, B, plan, workspace) + profile = plan.profile + T = eltype(A) + + # workspace ownership and compatibility + ws = if workspace isa Int + DenseGemmWorkspace(A, workspace) + elseif workspace isa DenseGemmWorkspace + eltype(workspace) === T || throw(ArgumentError( + "workspace element type $(eltype(workspace)) does not match operand type $T")) + typeof(get_backend(workspace.storage)) === typeof(get_backend(A)) || + throw(ArgumentError("workspace and operands must use the same backend")) + workspace + else + throw(ArgumentError("workspace must be an integer byte count or DenseGemmWorkspace")) + end + + # column-subdivision floor + # `profile.minimum` is full-width, so compute the true floor only below it. + bytes = sizeof(ws) + if bytes < profile.minimum + required = _compressed_ftlr_column_floor(plan, A, B) + bytes >= required || throw(ArgumentError( + "workspace has $bytes bytes; at least $required bytes are required")) + end + + # bounded arena + budget = min(bytes, profile.maximum) + arena = GemmArena(view(ws.storage, :), 1) + return ws, arena, budget, profile +end diff --git a/src/tlr/blas/gemm/dense_accumulation/three_stage.jl b/src/tlr/blas/gemm/dense_accumulation/three_stage.jl new file mode 100644 index 00000000..7557680f --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/three_stage.jl @@ -0,0 +1,507 @@ +@inline function compressed_ftlr_row_outer_stack(A, i::Int, rho::Int) + qm, qk = grid_size(A) + 1 <= i <= qm || throw(BoundsError(A, (i, :))) + + f = compressed_ftlr_outer_storage(A) + fi, fj = compressed_ftlr_logical_coords(A, i, 1) + li, lj = compressed_ftlr_logical_coords(A, i, qk) + first_slot = tile_linear_index(f.order, f.qm, f.qn, fi, fj) + last_slot = tile_linear_index(f.order, f.qm, f.qn, li, lj) + first = f.offsets[first_slot] + last = f.offsets[last_slot + 1] - 1 + rows = length(tile_axis_range(A, i, 1)) + + rho == 0 && return reshape(view(f.data, 1:0), rows, 0) + packed = reshape(view(f.data, first:last), length(first:last) ÷ rho, rho) + return view(packed, 1:rows, :) +end + +""" +Zero-copy horizontal stack of B's row-packed outer factors for fixed `k` and +columns `j0:j1`, preserving fused Stage 1 for column-restricted runs. +""" +@inline function _compressed_ftlr_row_w_stack(B, k::Int, j0::Int, j1::Int, rho::Int) + _, qn = grid_size(B) + (1 <= j0 <= j1 <= qn) || throw(BoundsError(B, (k, j0:j1))) + + f = compressed_ftlr_outer_storage(B) + fi, fj = compressed_ftlr_logical_coords(B, k, j0) + li, lj = compressed_ftlr_logical_coords(B, k, j1) + first_slot = tile_linear_index(f.order, f.qm, f.qn, fi, fj) + last_slot = tile_linear_index(f.order, f.qm, f.qn, li, lj) + first = f.offsets[first_slot] + last = f.offsets[last_slot + 1] - 1 + rows = length(tile_axis_range(B, k, 1)) + + rho == 0 && return reshape(view(f.data, 1:0), rows, 0) + packed = reshape(view(f.data, first:last), length(first:last) ÷ rho, rho) + return view(packed, 1:rows, :) +end + +""" +Zero-copy vertical stack of A's column-packed inner factors for fixed `k` and +rows `i0:i1`. It fuses Stage 1 to one task per `k`; zero-rank rows occupy no +bytes and vanish from the span. +""" +@inline function _compressed_ftlr_run_v_stack(A, i0::Int, i1::Int, k::Int, rho::Int) + _, qk = grid_size(A) + 1 <= k <= qk || throw(BoundsError(A, (:, k))) + + f = compressed_ftlr_inner_storage(A) + fi0, fk0 = compressed_ftlr_logical_coords(A, i0, k) + fi1, fk1 = compressed_ftlr_logical_coords(A, i1, k) + first_slot = tile_linear_index(f.order, f.qm, f.qn, fi0, fk0) + last_slot = tile_linear_index(f.order, f.qm, f.qn, fi1, fk1) + first = f.offsets[first_slot] + last = f.offsets[last_slot + 1] - 1 + rows = length(tile_axis_range(A, k, 2)) + + rho == 0 && return reshape(view(f.data, 1:0), rows, 0) + packed = reshape(view(f.data, first:last), length(first:last) ÷ rho, rho) + return view(packed, 1:rows, :) +end + +@inline function compressed_ftlr_col_z_stack(B, j::Int, gamma::Int) + qk, qn = grid_size(B) + 1 <= j <= qn || throw(BoundsError(B, (:, j))) + + f = compressed_ftlr_inner_storage(B) + fi, fj = compressed_ftlr_logical_coords(B, 1, j) + li, lj = compressed_ftlr_logical_coords(B, qk, j) + first_slot = tile_linear_index(f.order, f.qm, f.qn, fi, fj) + last_slot = tile_linear_index(f.order, f.qm, f.qn, li, lj) + first = f.offsets[first_slot] + last = f.offsets[last_slot + 1] - 1 + rows = length(tile_axis_range(B, j, 2)) + + gamma == 0 && return reshape(view(f.data, 1:0), rows, 0) + packed = reshape(view(f.data, first:last), length(first:last) ÷ gamma, gamma) + return view(packed, 1:rows, :) +end + +@inline function _ragged_view(data, offset::Int, rows::Int, cols::Int) + cols == 0 && return reshape(view(data, 1:0), rows, 0) + return reshape(view(data, offset:(offset + rows * cols - 1)), rows, cols) +end + +# Stage 2 skips zero-rank pairs, but each fold sizes its `T` arena from only one +# operand. Opposite-side rank holes therefore leave reserved entries unwritten: +# FoldRight when some `rA_ik > 0` meets an `rB_kj == 0`, and FoldLeft for the +# converse. `rho_k` and B prefix tables detect these holes in O(qk), allowing +# the `T` clear to be skipped for all-positive ranks. +""" +Stage-1 layout with one fused `(rho_k × σ_k)` block per active `k`. +`row_off[ii,k]` locates a row contribution and `koff[k]` locates the block. +""" +function _compressed_ftlr_stage1_layout(A, irange, jrange, plan) + _, qk = grid_size(A) + nr = length(irange) + rho_k = Base.zeros(Int, qk) + row_off = Base.zeros(Int, nr, qk) + koff = Base.zeros(Int, qk + 1) + koff[1] = 1 + + # contraction-row blocks + @inbounds for k in 1:qk + acc = 0 + for (ii, i) in enumerate(irange) + row_off[ii, k] = acc + acc += compressed_ftlr_storage_rank(A, i, k) + end + rho_k[k] = acc + koff[k + 1] = koff[k] + acc * compressed_ftlr_row_rank(plan, k, jrange) + end + + return rho_k, row_off, koff, koff[end] - 1 +end + +"""One grouped Stage-1 task per active `k`, with zero-copy row and column stacks.""" +function _compressed_ftlr_stage1_tasks(A, B, irange, jrange, plan, + rho_k, koff, sdata) + T = eltype(A) + i0, i1 = first(irange), last(irange) + j0, j1 = first(jrange), last(jrange) + _, qk = grid_size(A) + s1 = GroupedGemmTask[] + + # active contraction rows + @inbounds for k in 1:qk + rBsum = compressed_ftlr_row_rank(plan, k, jrange) + (rho_k[k] == 0 || rBsum == 0) && continue + task = GroupedGemmTask('T', 'N', one(T), + _compressed_ftlr_run_v_stack(A, i0, i1, k, rho_k[k]), + _compressed_ftlr_row_w_stack(B, k, j0, j1, rBsum), zero(T), + _ragged_view(sdata, koff[k], rho_k[k], rBsum)) + push!(s1, task) + end + + return isempty(s1) ? nothing : s1 +end + +"""`k`'s fused dense Stage-1 block, shaped `(rho_k × σ_k)`. Individual `S_ikj` +are strided views into it: rows `row_off[ii,k] .+ (1:rA)`, columns +`b_row_k_prefix[k,j] .+ (1:rB)`.""" +@inline _compressed_ftlr_sblock(sdata, koff, rho_k, plan, k, jrange) = + reshape(view(sdata, koff[k]:(koff[k + 1] - 1)), + rho_k[k], compressed_ftlr_row_rank(plan, k, jrange)) + +""" +Execute one FoldRight CompressedFTLR row run: `T^R_ikj = S_ikj Z_kj'`, then +`C_i += [U_i1 ... U_iqk]·[T^R_i1j;...;T^R_iqkj]`, concatenating over `k` on the +left. `T` is packed `(i,j,k)`-order so each row is already the Stage-3 +`rho_i × (qn*bn)` stack, letting Stage 3 issue one wide GEMM per row. +""" +function build_compressed_ftlr_foldright_run(C, A, B, plan, + irange, jrange, alpha, beta, arena) + T = eltype(A) + _, qk = grid_size(A) + qkB, _ = grid_size(B) + qk == qkB || throw(DimensionMismatch("CompressedFTLR contraction grids do not match")) + + nr = length(irange) + scale_targets = Tuple{UnitRange{Int},UnitRange{Int}}[] + sizehint!(scale_targets, nr) + width = compressed_ftlr_width(plan, jrange) + output_cols = compressed_ftlr_output_cols(B, jrange) + + # stage-1 layout and terminal row offsets + rho_k, row_off, koff, s_total = _compressed_ftlr_stage1_layout(A, irange, jrange, plan) + + # column-major terminal rows with strided `(k,j)` pieces + tbase = Base.zeros(Int, nr + 1) + tbase[1] = 1 + @inbounds for (ii, i) in enumerate(irange) + tbase[ii + 1] = tbase[ii] + plan.a_k_prefix[i, end] * width + end + t_total = tbase[end] - 1 + + # inactive run + if s_total == 0 + @inbounds for i in irange + push!(scale_targets, (tile_axis_range(A, i, 1), output_cols)) + end + return DenseAccumulationRunTasks( + nothing, nothing, nothing, 0, nothing, false, scale_targets) + end + + arena_reset!(arena) + backend = get_backend(A) + sdata = workspace_array!(arena, backend, T, s_total) + tdata = workspace_array!(arena, backend, T, t_total) + + s1 = _compressed_ftlr_stage1_tasks(A, B, irange, jrange, plan, rho_k, koff, sdata) + + # stage-2 tasks with loop-local `tstack` and `Sblock` views + s2 = GroupedGemmTask[] + @inbounds for (ii, i) in enumerate(irange) + rho = plan.a_k_prefix[i, end] + rho == 0 && continue + tstack = _ragged_view(tdata, tbase[ii], rho, width) + for k in 1:qk + rA = compressed_ftlr_storage_rank(A, i, k) + rA == 0 && continue + rho_before_k = plan.a_k_prefix[i, k] + Sblock = _compressed_ftlr_sblock(sdata, koff, rho_k, plan, k, jrange) + Srows = (row_off[ii, k] + 1):(row_off[ii, k] + rA) + for j in jrange + rB = compressed_ftlr_storage_rank(B, k, j) + rB == 0 && continue + scol = compressed_ftlr_row_rank_offset(plan, k, j, jrange) + tcol = plan.output_col_prefix[j] - + plan.output_col_prefix[first(jrange)] + Sview = view(Sblock, Srows, (scol + 1):(scol + rB)) + task = GroupedGemmTask('N', 'T', one(T), + Sview, + compressed_ftlr_storage_inner(B, k, j), zero(T), + view(tstack, (rho_before_k + 1):(rho_before_k + rA), + (tcol + 1):(tcol + plan.output_col_widths[j]))) + push!(s2, task) + end + end + end + + # stage-3 row tasks + s3 = GroupedGemmTask[] + @inbounds for (ii, i) in enumerate(irange) + rho = plan.a_k_prefix[i, end] + rows = tile_axis_range(A, i, 1) + if rho == 0 + push!(scale_targets, (rows, output_cols)) + continue + end + task = GroupedGemmTask('N', 'N', alpha, compressed_ftlr_row_outer_stack(A, i, rho), + _ragged_view(tdata, tbase[ii], rho, width), beta, + view(C, rows, output_cols)) + push!(s3, task) + end + return DenseAccumulationRunTasks( + s1, isempty(s2) ? nothing : s2, isempty(s3) ? nothing : s3, 3, tdata, + any(k -> rho_k[k] > 0 && + plan.b_row_nonzero_prefix[k, last(jrange) + 1] - + plan.b_row_nonzero_prefix[k, first(jrange)] < length(jrange), + eachindex(rho_k)), + scale_targets) +end + +""" +FoldLeft companion: `T^L_ikj = U_ik S_ikj`, then +`C_ij += [T^L_i1j ... T^L_iqkj]·[Z_1j';...;Z_qkj']`, concatenating over `k` on +the right. For every output column `j`, the `T` arena stacks all rows in the +run vertically into one `run_height × gamma_j` matrix, letting Stage 3 share +`Z_j` across the run and issue one GEMM per `j` rather than one per `(i,j)`. +""" +function build_compressed_ftlr_foldleft_run(C, A, B, plan, + irange, jrange, alpha, beta, arena) + T = eltype(A) + _, qk = grid_size(A) + qkB, _ = grid_size(B) + qk == qkB || throw(DimensionMismatch("CompressedFTLR contraction grids do not match")) + + nr = length(irange) + j0 = first(jrange) + scale_targets = Tuple{UnitRange{Int},UnitRange{Int}}[] + sizehint!(scale_targets, length(jrange)) + + # stage-1 layout and run geometry + rho_k, row_off, koff, s_total = _compressed_ftlr_stage1_layout(A, irange, jrange, plan) + i0, i1 = first(irange), last(irange) + run_row_prefix = Base.zeros(Int, nr + 1) + @inbounds for (ii, i) in enumerate(irange) + run_row_prefix[ii + 1] = run_row_prefix[ii] + plan.output_row_heights[i] + end + run_height = run_row_prefix[end] + + # terminal column offsets rebased to `jrange` + tbase_cols = Base.zeros(Int, length(jrange) + 1) + tbase_cols[1] = 1 + @inbounds for (jj, j) in enumerate(jrange) + tbase_cols[jj + 1] = tbase_cols[jj] + run_height * plan.b_col_ranks[j] + end + t_total = tbase_cols[end] - 1 + output_rows = (first(tile_axis_range(A, i0, 1)): + last(tile_axis_range(A, i1, 1))) + + # inactive run + if s_total == 0 + @inbounds for i in irange + push!(scale_targets, (tile_axis_range(A, i, 1), + compressed_ftlr_output_cols(B, jrange))) + end + return DenseAccumulationRunTasks( + nothing, nothing, nothing, 0, nothing, false, scale_targets) + end + arena_reset!(arena) + backend = get_backend(A) + sdata = workspace_array!(arena, backend, T, s_total) + tdata = workspace_array!(arena, backend, T, t_total) + + s1 = _compressed_ftlr_stage1_tasks(A, B, irange, jrange, plan, rho_k, koff, sdata) + + # stage-2 tasks with loop-local `Sblock` and `Tj` views + s2 = GroupedGemmTask[] + @inbounds for (ii, i) in enumerate(irange) + Trows = (run_row_prefix[ii] + 1):run_row_prefix[ii + 1] + for k in 1:qk + rA = compressed_ftlr_storage_rank(A, i, k) + rA == 0 && continue + Sblock = _compressed_ftlr_sblock(sdata, koff, rho_k, plan, k, jrange) + Srows = (row_off[ii, k] + 1):(row_off[ii, k] + rA) + Uik = compressed_ftlr_storage_outer(A, i, k) + for j in jrange + rB = compressed_ftlr_storage_rank(B, k, j) + rB == 0 && continue + scol = compressed_ftlr_row_rank_offset(plan, k, j, jrange) + Sview = view(Sblock, Srows, (scol + 1):(scol + rB)) + Tj = _ragged_view(tdata, tbase_cols[j - j0 + 1], run_height, + plan.b_col_ranks[j]) + task = GroupedGemmTask('N', 'N', one(T), Uik, Sview, zero(T), + view(Tj, Trows, + (plan.b_col_k_prefix[j, k] + 1): + (plan.b_col_k_prefix[j, k] + rB))) + push!(s2, task) + end + end + end + + # stage-3 column tasks + s3 = GroupedGemmTask[] + @inbounds for j in jrange + gamma = plan.b_col_ranks[j] + output_cols = tile_axis_range(B, j, 2) + if gamma == 0 + push!(scale_targets, (output_rows, output_cols)) + continue + end + task = GroupedGemmTask('N', 'T', alpha, + _ragged_view(tdata, tbase_cols[j - j0 + 1], run_height, gamma), + compressed_ftlr_col_z_stack(B, j, gamma), beta, + view(C, output_rows, output_cols)) + push!(s3, task) + end + return DenseAccumulationRunTasks( + s1, isempty(s2) ? nothing : s2, isempty(s3) ? nothing : s3, 3, tdata, + any(1:plan.qk) do k + compressed_ftlr_row_rank(plan, k, jrange) > 0 && + any(i -> compressed_ftlr_storage_rank(A, i, k) == 0, irange) + end, + scale_targets) +end + +# symbolic analysis: reusable prepared-run bundle for repeated numerical calls + +""" + CompressedGemmAnalysis + +Explicit symbolic metadata for `CompressedFTLRMatrix × CompressedFTLRMatrix → dense`. +The object owns device pointer tables and is bound to the output, operands, +workspace, logical operations, compute policy, and rank metadata used to create it. +Factor values and numerical scalars may be changed between numerical calls. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> ws = DenseGemmWorkspace(A, A; bytes=gemm_maximum_workspace_bytes(A, A)); + +julia> C = zeros(n, n); + +julia> analysis = analyze_compressed_gemm(C, A, A; workspace=ws); + +julia> NextLA.gemm!(C, A, A; workspace=ws, analysis); + +julia> NextLA.gemm!(C, A, A; workspace=ws, analysis, alpha=2.0, beta=1.0); + +julia> close(analysis); + +julia> norm(C - 3 * K * K) / norm(3 * K * K) < 1e-5 +true +``` +""" +mutable struct CompressedGemmAnalysis{CT,AT,BT,WT,ModeT,RAT,RBT} + C::CT + A::AT + B::BT + workspace::WT + transA::Char + transB::Char + compute::ModeT + runs::Vector{PreparedDenseAccumulationRun} + # copied same-type rank snapshots for allocation-free mutation guards + A_ranks::RAT + B_ranks::RBT + workspace_bytes::Int + has_fallback::Bool + closed::Bool +end + +Base.close(analysis::CompressedGemmAnalysis) = close_dense_accumulation_analysis!(analysis) + +""" + analyze_compressed_gemm(C, A, B; workspace, transA='N', transB='N', compute=nothing) + +Build reusable symbolic metadata and prepared descriptors. `workspace` must be +a `DenseGemmWorkspace`. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> ws = DenseGemmWorkspace(A, A; bytes=gemm_workspace_bytes(A, A; runs=2)); + +julia> C = zeros(n, n); + +julia> analysis = analyze_compressed_gemm(C, A, A; workspace=ws, transA='T'); + +julia> NextLA.gemm!(C, A, A; workspace=ws, transA='T', analysis); + +julia> close(analysis); + +julia> norm(C - transpose(K) * K) / norm(transpose(K) * K) < 1e-5 +true +``` +""" +function analyze_compressed_gemm( + C::AbstractMatrix, + A::CompressedFTLRMatrix{BackendT,T}, + B::CompressedFTLRMatrix{BackendT,T}; + workspace, + transA::Char='N', + transB::Char='N', + compute=nothing, +) where {BackendT,T} + # binding and geometry + workspace isa DenseGemmWorkspace || throw(ArgumentError( + "symbolic compressed GEMM analysis requires a reusable DenseGemmWorkspace")) + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C must be size(op(A),1) × size(op(B),2)")) + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + validate_compressed_ftlr_gemm(C, LA, LB, mode) + + # plan and placeholder scalars + plan = compressed_ftlr_rank_plan(LA, LB) + ws, arena, budget, profile = + prepare_compressed_ftlr_workspace(LA, LB, plan, workspace) + ws === workspace || error("internal error: symbolic analysis replaced its workspace") + scalar_type = gemm_compute_type(mode) + placeholder_alpha = one(scalar_type) + placeholder_beta = zero(scalar_type) + + # scheduled prepared runs + schedule = compressed_ftlr_column_schedule(plan, LA, LB, profile, budget) + prepared_runs = prepare_dense_accumulation_runs(schedule, mode) do run + run.fold === :right ? + build_compressed_ftlr_foldright_run( + C, LA, LB, plan, run.rows, run.cols, + placeholder_alpha, placeholder_beta, arena) : + build_compressed_ftlr_foldleft_run( + C, LA, LB, plan, run.rows, run.cols, + placeholder_alpha, placeholder_beta, arena) + end + + # bound analysis and cleanup + analysis = CompressedGemmAnalysis( + C, A, B, workspace, transA, transB, mode, prepared_runs, + copy(ranks(A)), copy(ranks(B)), + sizeof(workspace), + dense_accumulation_runs_have_fallback(prepared_runs), + false) + finalizer(analysis) do object + try + close_dense_accumulation_analysis!(object) + catch + # Device teardown may precede Julia object finalization. + end + end + return analysis +end + +function execute_compressed_gemm_analysis!( + analysis::CompressedGemmAnalysis, C, A, B, workspace, + alpha, beta, transA, transB, mode) + validate_dense_accumulation_analysis_binding( + analysis, C, A, B, workspace, transA, transB, mode) + + # rank snapshot guards + ranks(A) == analysis.A_ranks || + throw(ArgumentError("left operand exact ranks changed after symbolic analysis")) + ranks(B) == analysis.B_ranks || + throw(ArgumentError("right operand exact ranks changed after symbolic analysis")) + + backend = get_backend(A) + return execute_prepared_dense_accumulation_runs!( + analysis.runs, C, backend, eltype(A), alpha, beta, + analysis.has_fallback) +end diff --git a/src/tlr/blas/gemm/dense_accumulation/two_stage.jl b/src/tlr/blas/gemm/dense_accumulation/two_stage.jl new file mode 100644 index 00000000..2c543f1b --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/two_stage.jl @@ -0,0 +1,396 @@ +# Two-stage compressed/dense lowering: FoldRight for compressed × dense and +# FoldLeft for dense × compressed, sharing the dense-accumulation run lifecycle. + +"""Dense block view and its transpose flag.""" +@inline dense_block(A::AbstractMatrix, rows, cols) = (view(A, rows, cols), 'N') +@inline dense_block(A::Transpose, rows, cols) = (view(parent(A), cols, rows), 'T') + +""" + CompressedMixedGemmAnalysis + +Reusable symbolic metadata for `CompressedFTLRMatrix × dense → dense` and +`dense × CompressedFTLRMatrix → dense`, returned by +`analyze_compressed_gemm(C, A, B; workspace, ...)` when exactly one of `A`, `B` +is a `CompressedFTLRMatrix`. + +It is bound to the objects `C`, `A`, `B` and `workspace`, to `transA`/`transB`, +the compute policy, and a copy of the compressed operand's ranks; `gemm!(C, A, B; +workspace, analysis, ...)` throws an `ArgumentError` if any of these differ. +Dense values, factor values, `alpha` and `beta` may change between calls. The +workspace must hold at least one fused run: the sum of the compressed +operand's stored ranks times `sizeof(T)` bytes. `close(analysis)` releases the +prepared descriptors; a finalizer also does this. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [div(i - 1, 256) == div(j - 1, 256) ? 0.0 : 1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = CompressedFTLRMatrix(K, 256; maxrank=64, tol=1e-6, rel=true); + +julia> B = rand(n, n); C = zeros(n, n); + +julia> ws = DenseGemmWorkspace(A, 2^20); + +julia> analysis = analyze_compressed_gemm(C, A, B; workspace=ws); + +julia> NextLA.gemm!(C, A, B; workspace=ws, analysis); + +julia> B .*= 2; + +julia> NextLA.gemm!(C, A, B; workspace=ws, analysis); + +julia> close(analysis); + +julia> norm(C - K * B) / norm(K * B) < 1e-5 +true +``` +""" +mutable struct CompressedMixedGemmAnalysis{CT,AT,BT,WT,ModeT,RT} + C::CT + A::AT + B::BT + workspace::WT + transA::Char + transB::Char + compute::ModeT + fold::Symbol + # copied compressed-operand ranks + ranks::RT + workspace_bytes::Int + runs::Vector{PreparedDenseAccumulationRun} + has_fallback::Bool + closed::Bool +end + +@inline function _validate_two_stage_grouped_precision(A) + eltype(A) === BFloat16 && + !supports_bfloat16_grouped_gemm(get_backend(A)) && + throw(ArgumentError( + "CompressedFTLR BF16 grouped GEMMEx requires an NVIDIA SM80 or newer device")) + return nothing +end + +# A fused run needs the sum of every active rank stack. Workspaces below that +# floor retain the API contract through a compressed-only tilewise fallback. +function compressed_dense_gemm_sequential!( + C, A::AbstractTLRMatrix{T}, + B::AbstractMatrix, alpha, beta, budget::Int, + compute, arena=nothing) where {T} + scale_output!(C, beta) + r = maxrank(A) + (isempty(C) || r == 0) && return C + + # widest workspace-backed column batch + mt, kt = grid_size(A) + n = size(B, 2) + batch_width = clamp(div(budget, max(r * sizeof(T), 1)), 1, n) + arena_reset!(arena) + work = workspace_array!(arena, get_backend(A), T, r, batch_width) + + # tilewise updates + @inbounds for i in 1:mt, cols in Iterators.partition(1:n, batch_width) + rows = tile_axis_range(A, i, 1) + Cview = view(C, rows, cols) + for k in 1:kt + inner = tile_axis_range(A, k, 2) + U, V = get_factors(A, i, k) + rk = size(V, 2) + rk == 0 && continue + Tview = view(work, 1:rk, 1:length(cols)) + Bd, opB = dense_block(B, inner, cols) + precision_gemm!('T', opB, one(T), V, Bd, zero(T), Tview, compute) + precision_gemm!('N', 'N', alpha, U, Tview, one(alpha), Cview, compute) + end + end + + return C +end + +function dense_compressed_gemm_sequential!( + C, A::AbstractMatrix, + B::AbstractTLRMatrix{T}, + alpha, beta, budget::Int, compute, arena=nothing) where {T} + scale_output!(C, beta) + r = maxrank(B) + (isempty(C) || r == 0) && return C + + # tallest workspace-backed row batch + kt, nt = grid_size(B) + m = size(A, 1) + height = clamp(div(budget, max(r * sizeof(T), 1)), 1, m) + arena_reset!(arena) + work = workspace_array!(arena, get_backend(B), T, height, r) + + # tilewise updates + @inbounds for j in 1:nt, rows in Iterators.partition(1:m, height) + cols = tile_axis_range(B, j, 2) + Cview = view(C, rows, cols) + for k in 1:kt + inner = tile_axis_range(B, k, 1) + Ad, opA = dense_block(A, rows, inner) + U, V = get_factors(B, k, j) + rk = size(U, 2) + rk == 0 && continue + Tview = view(work, 1:length(rows), 1:rk) + precision_gemm!(opA, 'N', one(T), Ad, U, zero(T), Tview, compute) + precision_gemm!('N', 'T', alpha, Tview, V, one(alpha), Cview, compute) + end + end + + return C +end + +function two_stage_rank_plan(A, fold::Symbol) + fold in (:left, :right) || throw(ArgumentError( + "two-stage compressed fold must be :left or :right")) + + # output-rank prefixes + qm, qn = grid_size(A) + outputs, contraction = fold === :left ? (qn, qm) : (qm, qn) + prefix = Base.zeros(Int, outputs, contraction + 1) + @inbounds for output in 1:outputs, k in 1:contraction + rank = fold === :left ? + compressed_ftlr_storage_rank(A, k, output) : + compressed_ftlr_storage_rank(A, output, k) + prefix[output, k + 1] = prefix[output, k] + rank + end + + totals = [prefix[output, end] for output in 1:outputs] + bases = compressed_ftlr_prefix(totals) + return (; prefix, totals, bases, total_rank=bases[end], fold) +end + +"""Largest aligned dense-row run admitted by a FoldLeft workspace.""" +@inline function dense_compressed_row_run_height( + budget_elements::Int, total_rank::Int, rows::Int, ::Type{T}) where {T} + total_rank > 0 || throw(ArgumentError("total rank must be positive")) + rows > 0 || throw(ArgumentError("row count must be positive")) + height = clamp(fld(budget_elements, total_rank), 1, rows) + height == rows && return height + alignment_rows = gemm_alignment_quantum(T) + height < alignment_rows && return height + return fld(height, alignment_rows) * alignment_rows +end + +function two_stage_schedule(C, plan, budget::Int, ::Type{T}) where {T} + plan.total_rank == 0 && return DenseAccumulationRun[ + DenseAccumulationRun(1:size(C, 1), 1:size(C, 2), plan.fold)] + + budget_elements = fld(budget, sizeof(T)) + budget_elements >= plan.total_rank || throw(ArgumentError( + "two-stage compressed analysis requires at least " * + "$(plan.total_rank * sizeof(T)) workspace bytes for one fused run")) + + # fold-specific dense-axis partitions + if plan.fold === :left + height = dense_compressed_row_run_height( + budget_elements, plan.total_rank, size(C, 1), T) + return [DenseAccumulationRun(rows, 1:length(plan.totals), :left) + for rows in Iterators.partition(1:size(C, 1), height)] + end + width = clamp(fld(budget_elements, plan.total_rank), 1, size(C, 2)) + return [DenseAccumulationRun(1:length(plan.totals), cols, :right) + for cols in Iterators.partition(1:size(C, 2), width)] +end + +function _build_dense_compressed_run(C, A, B, plan, run, work) + rows = run.rows + h = length(rows) + qk, _ = grid_size(B) + stage1 = GroupedGemmTask[] + stage2 = GroupedGemmTask[] + scales = Tuple{UnitRange{Int},UnitRange{Int}}[] + T = eltype(B) + + # grouped stages by output column + @inbounds for j in run.cols + gamma = plan.totals[j] + cols = tile_axis_range(B, j, 2) + Cview = view(C, rows, cols) + if gamma == 0 + push!(scales, (rows, cols)) + continue + end + Tj = view(work, 1:h, (plan.bases[j] + 1):plan.bases[j + 1]) + for k in 1:qk + rk = compressed_ftlr_storage_rank(B, k, j) + rk == 0 && continue + inner = tile_axis_range(B, k, 1) + Ad, opA = dense_block(A, rows, inner) + Tk = view(Tj, :, (plan.prefix[j, k] + 1):plan.prefix[j, k + 1]) + push!(stage1, GroupedGemmTask( + opA, 'N', one(T), Ad, + compressed_ftlr_storage_outer(B, k, j), zero(T), Tk)) + end + push!(stage2, GroupedGemmTask( + 'N', 'T', one(T), Tj, + compressed_ftlr_col_z_stack(B, j, gamma), zero(T), Cview)) + end + + return DenseAccumulationRunTasks( + isempty(stage1) ? nothing : stage1, isempty(stage2) ? nothing : stage2, + nothing, 2, work, false, scales) +end + +function _build_compressed_dense_run(C, A, B, plan, run, work) + cols = run.cols + w = length(cols) + _, qk = grid_size(A) + stage1 = GroupedGemmTask[] + stage2 = GroupedGemmTask[] + scales = Tuple{UnitRange{Int},UnitRange{Int}}[] + T = eltype(A) + + # grouped stages by output row + @inbounds for i in run.rows + rho = plan.totals[i] + rows = tile_axis_range(A, i, 1) + Cview = view(C, rows, cols) + if rho == 0 + push!(scales, (rows, cols)) + continue + end + Ti = view(work, (plan.bases[i] + 1):plan.bases[i + 1], 1:w) + for k in 1:qk + rk = compressed_ftlr_storage_rank(A, i, k) + rk == 0 && continue + inner = tile_axis_range(A, k, 2) + Bd, opB = dense_block(B, inner, cols) + Tk = view(Ti, (plan.prefix[i, k] + 1):plan.prefix[i, k + 1], :) + push!(stage1, GroupedGemmTask( + 'T', opB, one(T), + compressed_ftlr_storage_inner(A, i, k), Bd, zero(T), Tk)) + end + push!(stage2, GroupedGemmTask( + 'N', 'N', one(T), + compressed_ftlr_row_outer_stack(A, i, rho), Ti, zero(T), Cview)) + end + + return DenseAccumulationRunTasks( + isempty(stage1) ? nothing : stage1, isempty(stage2) ? nothing : stage2, + nothing, 2, work, false, scales) +end + +function _prepare_two_stage_runs(C, A, B, compressed, plan, budget, mode, arena) + # run schedule and zero-rank case + schedule = two_stage_schedule(C, plan, budget, eltype(compressed)) + plan.total_rank == 0 && return prepare_dense_accumulation_runs(schedule, mode) do _ + DenseAccumulationRunTasks( + nothing, nothing, nothing, 0, nothing, false, + [(1:size(C, 1), 1:size(C, 2))]) + end + + # shared numerical workspace + arena_reset!(arena) + backend = get_backend(compressed) + if plan.fold === :left + height = maximum(length(run.rows) for run in schedule) + work = workspace_array!(arena, backend, eltype(compressed), + height, plan.total_rank) + return prepare_dense_accumulation_runs(schedule, mode) do run + _build_dense_compressed_run(C, A, B, plan, run, work) + end + end + width = maximum(length(run.cols) for run in schedule) + work = workspace_array!(arena, backend, eltype(compressed), + plan.total_rank, width) + return prepare_dense_accumulation_runs(schedule, mode) do run + _build_compressed_dense_run(C, A, B, plan, run, work) + end +end + +Base.close(analysis::CompressedMixedGemmAnalysis) = + close_dense_accumulation_analysis!(analysis) + +function _new_compressed_mixed_analysis( + C, A, B, workspace, transA, transB, mode, fold, compressed, runs) + # bound analysis + analysis = CompressedMixedGemmAnalysis( + C, A, B, workspace, transA, transB, mode, fold, + copy(ranks(compressed)), + sizeof(workspace), runs, dense_accumulation_runs_have_fallback(runs), false) + + # cleanup finalizer + finalizer(analysis) do object + try + close_dense_accumulation_analysis!(object) + catch + # Device teardown may precede Julia object finalization. + end + end + + return analysis +end + +function analyze_compressed_gemm( + C::AbstractMatrix, A::AbstractMatrix{T}, + B::CompressedFTLRMatrix{BackendT,T}; + workspace, transA::Char='N', transB::Char='N', compute=nothing, +) where {BackendT,T} + # binding and geometry + workspace isa DenseGemmWorkspace || throw(ArgumentError( + "symbolic two-stage GEMM analysis requires a reusable DenseGemmWorkspace")) + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C has the wrong dimensions")) + backend = validate_dense_backend(C, B, A) + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + validate_tlr_gemm_precision(backend, T, eltype(C), mode) + _validate_two_stage_grouped_precision(LB) + + # fold-left plan and prepared runs + _, arena, budget = prepare_dense_accumulation_workspace(B, workspace) + plan = two_stage_rank_plan(LB, :left) + runs = _prepare_two_stage_runs(C, LA, LB, LB, plan, budget, mode, arena) + return _new_compressed_mixed_analysis( + C, A, B, workspace, transA, transB, + mode, :left, B, runs) +end + +function analyze_compressed_gemm( + C::AbstractMatrix, A::CompressedFTLRMatrix{BackendT,T}, + B::AbstractMatrix{T}; + workspace, transA::Char='N', transB::Char='N', compute=nothing, +) where {BackendT,T} + # binding and geometry + workspace isa DenseGemmWorkspace || throw(ArgumentError( + "symbolic two-stage GEMM analysis requires a reusable DenseGemmWorkspace")) + LA = transA == 'T' ? transpose(A) : A + LB = transB == 'T' ? transpose(B) : B + size(LA, 2) == size(LB, 1) || throw(DimensionMismatch("inner dimensions must match")) + size(C) == (size(LA, 1), size(LB, 2)) || + throw(DimensionMismatch("C has the wrong dimensions")) + backend = validate_dense_backend(C, A, B) + mode = compute === nothing ? default_gemm_compute_mode(T) : gemm_compute_mode(compute) + validate_tlr_gemm_precision(backend, T, eltype(C), mode) + _validate_two_stage_grouped_precision(LA) + + # fold-right plan and prepared runs + _, arena, budget = prepare_dense_accumulation_workspace(A, workspace) + plan = two_stage_rank_plan(LA, :right) + runs = _prepare_two_stage_runs(C, LA, LB, LA, plan, budget, mode, arena) + return _new_compressed_mixed_analysis( + C, A, B, workspace, transA, transB, + mode, :right, A, runs) +end + +function execute_compressed_mixed_analysis!( + analysis::CompressedMixedGemmAnalysis, C, A, B, workspace, + alpha, beta, transA, transB, mode) + validate_dense_accumulation_analysis_binding( + analysis, C, A, B, workspace, transA, transB, mode) + + # compressed-rank guard + compressed = analysis.fold === :right ? A : B + ranks(compressed) == analysis.ranks || + throw(ArgumentError("compressed operand ranks changed after analysis")) + + return execute_prepared_dense_accumulation_runs!( + analysis.runs, C, get_backend(compressed), eltype(compressed), alpha, beta, + analysis.has_fallback) +end diff --git a/src/tlr/blas/gemm/dense_accumulation/workspace.jl b/src/tlr/blas/gemm/dense_accumulation/workspace.jl new file mode 100644 index 00000000..54aa14a9 --- /dev/null +++ b/src/tlr/blas/gemm/dense_accumulation/workspace.jl @@ -0,0 +1,76 @@ +""" + DenseGemmWorkspace(A, bytes) + DenseGemmWorkspace(A, B; bytes, transA='N', transB='N') + +Reusable numerical storage for GEMMs whose destination is dense. + +Both constructors allocate `fld(bytes, sizeof(T))` elements of `A`'s element +type `T` on `A`'s backend. The two-operand form first checks that `bytes` is at +least `gemm_minimum_workspace_bytes(A, B; transA, transB)` and throws an +`ArgumentError` otherwise. Pass the result as `workspace` to `gemm!` or +`analyze_compressed_gemm`; `sizeof(ws)` is its usable size in bytes. + +# Examples + +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; K = [1/(1 + abs(i - j)) for i in 1:n, j in 1:n]; + +julia> A = TLRMatrix(K, (256, 256); maxrank=64, tol=1e-6, rel=true); + +julia> ws = DenseGemmWorkspace(A, A; bytes=gemm_maximum_workspace_bytes(A, A)); + +julia> C = zeros(n, n); + +julia> NextLA.gemm!(C, A, A; workspace=ws); + +julia> NextLA.gemm!(C, A, A; workspace=ws, beta=1.0); + +julia> norm(C - 2 * K * K) / norm(2 * K * K) < 1e-5 +true +``` +""" +struct DenseGemmWorkspace{T,A<:AbstractVector{T}} + storage::A +end + +Base.eltype(::DenseGemmWorkspace{T}) where {T} = T +Base.sizeof(ws::DenseGemmWorkspace) = sizeof(ws.storage) + +function DenseGemmWorkspace(A::AbstractTLRMatrix{T}, bytes::Int) where {T} + bytes >= 0 || throw(ArgumentError("workspace bytes must be nonnegative")) + storage = allocate(get_backend(A), T, fld(bytes, sizeof(T))) + return DenseGemmWorkspace(storage) +end + +function DenseGemmWorkspace(A::AbstractTLRMatrix{T}, + B::AbstractTLRMatrix{T}; + bytes::Int, + transA::Char='N', transB::Char='N') where {T} + required = gemm_minimum_workspace_bytes(A, B; transA, transB) + bytes >= required || throw(ArgumentError( + "workspace has $bytes bytes; at least $required bytes are required")) + workspace = DenseGemmWorkspace(A, bytes) + sizeof(workspace) >= required || throw(ArgumentError( + "workspace byte count must contain at least $required bytes of complete $T elements")) + return workspace +end + +function prepare_dense_accumulation_workspace( + A::AbstractTLRMatrix{T}, workspace) where {T} + ws = if workspace isa Int + DenseGemmWorkspace(A, workspace) + elseif workspace isa DenseGemmWorkspace + eltype(workspace) === T || throw(ArgumentError( + "workspace element type $(eltype(workspace)) does not match operand type $T")) + typeof(get_backend(workspace.storage)) === typeof(get_backend(A)) || + throw(ArgumentError("workspace and operands must use the same backend")) + workspace + else + throw(ArgumentError( + "workspace must be an integer byte count or DenseGemmWorkspace")) + end + + return ws, GemmArena(view(ws.storage, :), 1), sizeof(ws) +end diff --git a/src/tlr/core/compressed_ftlr_matrix.jl b/src/tlr/core/compressed_ftlr_matrix.jl new file mode 100644 index 00000000..de78a5c9 --- /dev/null +++ b/src/tlr/core/compressed_ftlr_matrix.jl @@ -0,0 +1,310 @@ +""" + CompressedFTLRPackedFactors + +One packed factor allocation for a rectangular tile grid. `offsets` gives each +tile's scalar span in this factor's tile order. +""" +struct CompressedFTLRPackedFactors{AT<:AbstractVector,O<:TileOrderStyle} + data::AT + offsets::Vector{Int} # scalar offsets, 1-based, length ntile + 1 + order::O + logical_dimensions::Vector{Int} + qm::Int + qn::Int +end + +""" + CompressedFTLRMatrix + +Logical-rank block-compressed storage with independently ordered factors. + +Every tile of the full grid, diagonal included, is stored as factors `U * V'` of +its own logical rank. All `U` factors share one packed vector and all `V` factors +another. Build one by compressing a dense matrix, +`CompressedFTLRMatrix(A, tile_size; maxrank, ...)`, or allocate one from known +ranks, `CompressedFTLRMatrix(backend, T, m, n, tile_size, ranks)`. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> using Random; Random.seed!(1); # compression is randomized + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V'; + +julia> F = CompressedFTLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> B = similar(A); uncompress!(B, F); + +julia> all(==(8), ranks(F)) && norm(B - A) / norm(A) < 1e-8 # diagonal tiles too +true +``` +""" +struct CompressedFTLRMatrix{BackendT<:Backend,T,AT<:AbstractVector{T}, + OuterT<:TileOrderStyle,InnerT<:TileOrderStyle} <: AbstractTLRMatrix{T} + backend::BackendT + m::Int + n::Int + nominal_tile_size::NTuple{2,Int} + tail_tile_size::NTuple{2,Int} + outer::CompressedFTLRPackedFactors{AT,OuterT} + inner::CompressedFTLRPackedFactors{AT,InnerT} + ranks::Vector{Int} + rank_multiple::Int + resid::Vector{Float64} + maxrank::Int +end + +@inline function compressed_ftlr_rank(A::CompressedFTLRMatrix, i::Int, j::Int) + slot = tile_linear_index(A.outer.order, A.outer.qm, A.outer.qn, i, j) + return A.ranks[slot] +end +@inline compressed_ftlr_rank( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + compressed_ftlr_rank(parent(A), j, i) +@inline function compressed_ftlr_storage_rank(A::CompressedFTLRMatrix, i::Int, j::Int) + r = compressed_ftlr_rank(A, i, j) + return iszero(r) || iszero(A.rank_multiple) ? r : cld(r, A.rank_multiple) * A.rank_multiple +end +@inline compressed_ftlr_storage_rank( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + compressed_ftlr_storage_rank(parent(A), j, i) +@inline compressed_ftlr_logical_coords(::CompressedFTLRMatrix, i::Int, j::Int) = (i, j) +@inline compressed_ftlr_logical_coords( + ::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = (j, i) + +@inline function compressed_ftlr_factor_view(f::CompressedFTLRPackedFactors, + i::Int, j::Int, axis_index::Int, + visible_r=nothing) + logical_rows = f.logical_dimensions[axis_index] + slot = tile_linear_index(f.order, f.qm, f.qn, i, j) + first = f.offsets[slot] + next = f.offsets[slot + 1] + ld = aligned_leading_dimension(eltype(f.data), logical_rows) + stored_r = (next - first) ÷ ld + width = visible_r === nothing ? stored_r : visible_r + + stored_r == 0 && return reshape(view(f.data, 1:0), logical_rows, 0) + packed = reshape(view(f.data, first:(next - 1)), ld, stored_r) + return view(packed, 1:logical_rows, 1:width) +end + +@inline compressed_ftlr_outer(A::CompressedFTLRMatrix, i::Int, j::Int) = + compressed_ftlr_factor_view(A.outer, i, j, i, compressed_ftlr_rank(A, i, j)) +@inline compressed_ftlr_inner(A::CompressedFTLRMatrix, i::Int, j::Int) = + compressed_ftlr_factor_view(A.inner, i, j, j, compressed_ftlr_rank(A, i, j)) +@inline compressed_ftlr_outer( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + compressed_ftlr_inner(parent(A), j, i) +@inline compressed_ftlr_inner( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + compressed_ftlr_outer(parent(A), j, i) +@inline compressed_ftlr_storage_outer(A::CompressedFTLRMatrix, i::Int, j::Int) = + compressed_ftlr_factor_view(A.outer, i, j, i) +@inline compressed_ftlr_storage_inner(A::CompressedFTLRMatrix, i::Int, j::Int) = + compressed_ftlr_factor_view(A.inner, i, j, j) +@inline compressed_ftlr_storage_outer( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + compressed_ftlr_storage_inner(parent(A), j, i) +@inline compressed_ftlr_storage_inner( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + compressed_ftlr_storage_outer(parent(A), j, i) +@inline compressed_ftlr_outer_order(A::CompressedFTLRMatrix) = A.outer.order +@inline compressed_ftlr_inner_order(A::CompressedFTLRMatrix) = A.inner.order +@inline compressed_ftlr_outer_order( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}) = + transpose(parent(A).inner.order) +@inline compressed_ftlr_inner_order( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}) = + transpose(parent(A).outer.order) +@inline tile_order(A::CompressedFTLRMatrix) = A.outer.order +""" + rank_multiple(A) -> Int + +Return the multiple to which stored factor widths are rounded up. With `0` (the +default) each tile's factors are stored with exactly its logical rank; with a +positive value a nonzero rank `r` is stored with width `cld(r, k) * k` for +`k = rank_multiple(A)`, while [`ranks`](@ref) and [`get_factors`](@ref) still report +and return the logical rank. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 6), randn(n, 6); + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true, + rank_multiple=8); + +julia> rank_multiple(C) == 8 && maxrank(C) == 6 +true +``` +""" +@inline rank_multiple(A::CompressedFTLRMatrix) = A.rank_multiple +@inline rank_multiple(A::TransposeTLRMatrix) = rank_multiple(parent(A)) +""" + maximum_storage_rank(A) -> Int + +Return the largest stored factor width in `A`: [`maxrank`](@ref)`(A)` rounded up to +a multiple of [`rank_multiple`](@ref)`(A)`, or `maxrank(A)` itself when either is +zero. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 6), randn(n, 6); + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true, + rank_multiple=8); + +julia> maximum_storage_rank(C) == 8 && size(get_factors(C, 1, 2)[1], 2) == 6 +true +``` +""" +@inline function maximum_storage_rank(A::CompressedFTLRMatrix) + r, multiple = maxrank(A), rank_multiple(A) + return iszero(r) || iszero(multiple) ? r : cld(r, multiple) * multiple +end +@inline maximum_storage_rank(A::TransposeTLRMatrix) = maximum_storage_rank(parent(A)) + +@inline compressed_ftlr_outer_storage(A::CompressedFTLRMatrix) = A.outer +@inline compressed_ftlr_inner_storage(A::CompressedFTLRMatrix) = A.inner +@inline compressed_ftlr_outer_storage( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}) = parent(A).inner +@inline compressed_ftlr_inner_storage( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}) = parent(A).outer + +""" + compressed_ftlr_uniform_view(f::CompressedFTLRPackedFactors) + +View uniformly packed factors as `[extent, width, qm*qn]` in `f.order`. This is +valid only for private regular-grid staging and throws on nonuniform extents, +capacities, or backing storage. +""" +function compressed_ftlr_uniform_view(f::CompressedFTLRPackedFactors) + ntiles = f.qm * f.qn + extent = f.logical_dimensions[1] + + # regular-grid extent + all(==(extent), f.logical_dimensions) || + throw(ArgumentError("packed factors are not on a regular grid (nonuniform tile extent)")) + + # uniform tile capacity + ld = aligned_leading_dimension(eltype(f.data), extent) + stride = f.offsets[2] - f.offsets[1] + stride % ld == 0 || throw(ArgumentError( + "packed factor stride is not a multiple of its leading dimension")) + capacity = stride ÷ ld + all(k -> f.offsets[k + 1] - f.offsets[k] == stride, 1:ntiles) || throw(ArgumentError( + "packed factors do not have a uniform per-tile width")) + + # backing size + length(f.data) == stride * ntiles || throw(ArgumentError( + "packed factor storage size is inconsistent with a uniform-capacity layout")) + return view(reshape(f.data, ld, capacity, ntiles), 1:extent, :, :) +end + +@inline function _compressed_ftlr_offsets(order::TileOrderStyle, qm::Int, qn::Int, + leading_dimension_at, rank_at) + offsets = Vector{Int}(undef, qm * qn + 1) + offsets[1] = 1 + @inbounds for slot in 1:(qm * qn) + i, j = inverse_tile_index(order, qm, qn, slot) + offsets[slot + 1] = offsets[slot] + leading_dimension_at(i, j) * rank_at(i, j) + end + return offsets +end + +""" + CompressedFTLRMatrix(backend, T, m, n, tile_size, ranks; + outer_order=TileRowMajor, inner_order=TileColMajor, + rank_multiple=0) + +Allocate a finalized CompressedFTLR matrix from known logical tile ranks. +Physical factor widths equal the logical ranks when `rank_multiple == 0` and +are otherwise rounded up to that positive multiple. A regular nominal grid may +have one trailing row and/or column tile. + +`backend` is a KernelAbstractions backend such as `CPU()`, `tile_size` a tuple +`(bm, bn)` or one integer for square tiles, and `ranks` a `cld(m, bm) × cld(n, bn)` +integer matrix whose entries do not exceed their tile's dimensions. All factors +start as zeros, ready to be filled in place. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> backend = NextLA.KernelAbstractions.CPU(); + +julia> F = CompressedFTLRMatrix(backend, Float64, 1024, 1024, 128, fill(5, 8, 8); + rank_multiple=8); + +julia> X, Y = get_factors(F, 3, 4); + +julia> size(X) == (128, 5) && iszero(X) && maxrank(F) == 5 && maximum_storage_rank(F) == 8 +true +``` +""" +function CompressedFTLRMatrix(backend::Backend, ::Type{T}, m::Int, n::Int, + tile_size::NTuple{2,Int}, ranks_in::AbstractMatrix{Int}; + outer_order=TileRowMajor, inner_order=TileColMajor, + rank_multiple::Int=0) where {T} + # argument checks + bm, bn = tile_size + m > 0 && n > 0 && bm > 0 && bn > 0 || + throw(ArgumentError("m, n, and tile dimensions must be positive")) + qm, qn = cld(m, bm), cld(n, bn) + size(ranks_in) == (qm, qn) || + throw(DimensionMismatch("ranks must be a $qm × $qn matrix")) + all(>=(0), ranks_in) || throw(ArgumentError("CompressedFTLR ranks must be nonnegative")) + rank_multiple >= 0 || throw(ArgumentError("rank_multiple must be nonnegative")) + rowdims = [min(bm, m - (i - 1) * bm) for i in 1:qm] + coldims = [min(bn, n - (j - 1) * bn) for j in 1:qn] + @inbounds for j in 1:qn, i in 1:qm + ranks_in[i, j] <= min(rowdims[i], coldims[j]) || + throw(ArgumentError("CompressedFTLR rank at ($i, $j) exceeds its logical tile extent")) + end + + # packed offsets and backing storage + outer_style = outer_order isa Type ? outer_order() : outer_order + inner_style = inner_order isa Type ? inner_order() : inner_order + storage_rank_at = function (i, j) + r = ranks_in[i, j] + return iszero(r) || iszero(rank_multiple) ? r : cld(r, rank_multiple) * rank_multiple + end + + # leading dimensions for 16-byte-aligned factor bases, including ragged tiles + uoffsets = _compressed_ftlr_offsets( + outer_style, qm, qn, + (i, j) -> aligned_leading_dimension(T, rowdims[i]), storage_rank_at) + voffsets = _compressed_ftlr_offsets( + inner_style, qm, qn, + (i, j) -> aligned_leading_dimension(T, coldims[j]), storage_rank_at) + udata = zeros(backend, T, uoffsets[end] - 1) + vdata = zeros(backend, T, voffsets[end] - 1) + outer = CompressedFTLRPackedFactors(udata, uoffsets, outer_style, rowdims, qm, qn) + inner = CompressedFTLRPackedFactors(vdata, voffsets, inner_style, coldims, qm, qn) + + # diagnostic rank vector, in the outer factor's own tile order + rankvec = Vector{Int}(undef, qm * qn) + @inbounds for j in 1:qn, i in 1:qm + rankvec[tile_linear_index(outer_style, qm, qn, i, j)] = ranks_in[i, j] + end + + return CompressedFTLRMatrix{typeof(backend),T,typeof(udata),typeof(outer_style), + typeof(inner_style)}( + backend, m, n, tile_size, (m % bm, n % bn), outer, inner, + rankvec, rank_multiple, Base.zeros(Float64, qm * qn), maximum(rankvec)) +end + +function CompressedFTLRMatrix(backend::Backend, ::Type{T}, m::Int, n::Int, b::Int, + ranks_in::AbstractMatrix{Int}; kwargs...) where {T} + return CompressedFTLRMatrix(backend, T, m, n, (b, b), ranks_in; kwargs...) +end + +@inline get_factors(A::CompressedFTLRMatrix, i::Int, j::Int) = + (compressed_ftlr_outer(A, i, j), compressed_ftlr_inner(A, i, j)) +@inline get_factors( + A::TransposeTLRMatrix{<:Any,<:CompressedFTLRMatrix}, i::Int, j::Int) = + (compressed_ftlr_outer(A, i, j), compressed_ftlr_inner(A, i, j)) diff --git a/src/tlr/core/compression/ara.jl b/src/tlr/core/compression/ara.jl new file mode 100644 index 00000000..0a9b4537 --- /dev/null +++ b/src/tlr/core/compression/ara.jl @@ -0,0 +1,1057 @@ +# Blocked ARA support for Boukaram, Turkiyyah & Keyes, SIAM J. Sci. Comput. +# 41(4):C339-C366, 2019, Algorithm 2.3. Each pass samples a block, applies +# BCGS2 and two mixed-precision Cholesky-QR passes, and stops after +# `r_required` negligible projected columns. `ara_block_norms!` uses the +# diagonal of the composite triangular factor because projected column norms +# remain O(1) when the residual block is rank-deficient; its diagonal entries +# measure residuals against both the basis and earlier block columns. + +"""Minimal reusable workspace for ARA's Cholesky-QR passes.""" +struct ARACholeskyWorkspace{QT,YT,GT,RT,QViews,RViews} + Q::QT + Y_hi::YT + G_hi::GT + R1::RT + R2::RT + Q_tiles::QViews + R1_tiles::RViews + R2_tiles::RViews +end + +function ARACholeskyWorkspace(Q::AbstractArray{T,3}, + Y_hi::AbstractArray{Thi,3}, + G_hi::AbstractArray{Thi,3}, + R1::AbstractArray{T,3}, + R2::AbstractArray{T,3}) where {T,Thi} + _, width, count = size(Q) + size(Y_hi) == size(Q) || + throw(DimensionMismatch("Y_hi must have the same dimensions as Q")) + size(G_hi) == (width, width, count) || + throw(DimensionMismatch("G_hi must have size ($width, $width, $count)")) + size(R1) == size(G_hi) == size(R2) || + throw(DimensionMismatch("R1 and R2 must match G_hi")) + + return ARACholeskyWorkspace( + Q, Y_hi, G_hi, R1, R2, + batch_views(Q), batch_views(R1), batch_views(R2), + ) +end + +@kernel function _ara_copy_upper_triangle_kernel!(dest::AbstractArray{T,3}, + src::AbstractArray{Thi,3}) where {T,Thi} + row, col, batch = @index(Global, NTuple) + @inbounds begin + v = row <= col ? T(src[row, col, batch]) : zero(T) + dest[row, col, batch] = row == col && iszero(v) ? T(NaN) : v + end +end + +""" + ara_cholesky_pass!(ws, R, R_tiles; status=nothing, count=size(ws.Q, 3)) + +Apply one mixed-precision Cholesky-QR pass to the first `count` +members of `ws.Q`. The Gram matrix and Cholesky factorization use the promoted +type; the triangular solve and stored factor use the basis storage type. + +ARA deliberately treats a failed Cholesky factorization as a rank signal. +When provided, `status` receives the per-member factorization status. +A zero pivot is stored as `NaN`, so the solve marks the columns from it on as +non-finite on every backend instead of throwing, and `ara_mask_breakdown!` +discards them. +""" +function ara_cholesky_pass!(ws::ARACholeskyWorkspace, Rdest, Rdest_tiles; + status=nothing, + count::Int=size(ws.Q, 3)) + total = size(ws.Q, 3) + 0 <= count <= total || + throw(ArgumentError("count must lie in 0:$total")) + status === nothing || length(status) >= count || + throw(DimensionMismatch("status must have at least $count entries")) + count == 0 && return ws + + Q = count == total ? ws.Q : view(ws.Q, :, :, 1:count) + Y_hi = count == total ? ws.Y_hi : view(ws.Y_hi, :, :, 1:count) + G_hi = count == total ? ws.G_hi : view(ws.G_hi, :, :, 1:count) + R = count == total ? Rdest : view(Rdest, :, :, 1:count) + Q_tiles = count == total ? ws.Q_tiles : view(ws.Q_tiles, 1:count) + R_tiles = count == total ? Rdest_tiles : view(Rdest_tiles, 1:count) + + Y_hi .= Q + Thi = eltype(Y_hi) + gemm_batched!(adjoint_blas_char(Thi), 'N', + one(Thi), Y_hi, Y_hi, zero(Thi), G_hi) + result = potrf_batched!('U', G_hi) + if status !== nothing && result isa Tuple + copyto!(view(status, 1:count), result[2]) + end + _ara_copy_upper_triangle_kernel!(get_backend(Q))( + R, G_hi; ndrange=size(R), + ) + trsm_batched!('R', 'U', 'N', 'N', R_tiles, Q_tiles, one(eltype(Q))) + return ws +end + +# Diagonal of the composite factor R₂R₁. One thread per (column, member): +# no barriers, so this is safe on the KernelAbstractions CPU backend. +@kernel function _ara_block_norms_kernel!(dR, + R1::AbstractArray{T,3}, + R2::AbstractArray{T,3}) where {T} + j, b = @index(Global, NTuple) + @inbounds begin + dR[j, b] = sqrt(abs2_f64(R1[j, j, b])) * + sqrt(abs2_f64(R2[j, j, b])) + end +end + +""" + ara_block_norms!(dR, ws::ARACholeskyWorkspace) -> dR + +Projected column norms after two Cholesky-QR passes: +`dR[j,b] = |R₁[j,j]R₂[j,j]|`. This is the residual of column `j` against both +the existing basis and the earlier columns of the same block. +""" +function ara_block_norms!(dR, ws::ARACholeskyWorkspace; + count::Int=size(ws.R1, 3)) + s, _, total = size(ws.R1) + 0 <= count <= total || + throw(ArgumentError("count must lie in 0:$total")) + size(dR) == (s, count) || + throw(DimensionMismatch("dR must have size ($s, $count)")) + count == 0 && return dR + + R1 = count == total ? ws.R1 : view(ws.R1, :, :, 1:count) + R2 = count == total ? ws.R2 : view(ws.R2, :, :, 1:count) + _ara_block_norms_kernel!(get_backend(R1))( + dR, R1, R2; ndrange=(s, count), + ) + return dR +end + +""" + ARAConvergenceState(backend, count) + +Per-batch-member bookkeeping for the ARA loop over `count` members. + +`samples[b]` is how many columns member `b` should draw on the next pass and is +the single source of truth for whether it is still active: `0` means converged +(or capped). `ranks[b]` is the index of the last column that carried +significant energy, `svec[b]` the number of consecutive negligible columns seen +so far, `jcount[b]` the columns accumulated, and `rmax[b]` the running maximum +projected norm against which the relative test is made. + +Members advance independently, so `jcount` is tracked per member rather than as +a shared loop counter. +""" +struct ARAConvergenceState{IV,FV} + samples::IV + ranks::IV + svec::IV + jcount::IV + rmax::FV + samples_host::Vector{Int32} +end + +function ARAConvergenceState(backend, count::Int) + count >= 0 || throw(ArgumentError("count must be nonnegative")) + ints() = allocate(backend, Int32, count) + return ARAConvergenceState( + ints(), ints(), ints(), ints(), allocate(backend, Float64, count), + Vector{Int32}(undef, count), + ) +end + +function ARAConvergenceState(samples, ranks, svec, jcount, rmax, samples_host) + count = length(samples) + all(length(x) == count for x in (ranks, svec, jcount, rmax)) || + throw(DimensionMismatch("ARA convergence arrays must have equal length")) + length(samples_host) == count || + throw(DimensionMismatch("ARA samples host mirror must have length $count")) + + return ARAConvergenceState( + samples, ranks, svec, jcount, rmax, samples_host) +end + +""" + ara_reset!(state, block, maxrank) -> state + +Arm every member for a first pass of width `min(block, maxrank)`. +""" +function ara_reset!(state::ARAConvergenceState, block::Int, maxrank::Int) + fill!(state.samples, Int32(max(min(block, maxrank), 0))) + fill!(state.ranks, Int32(0)) + fill!(state.svec, Int32(0)) + fill!(state.jcount, Int32(0)) + fill!(state.rmax, 0.0) + return state +end + +# One thread per batch member; the scan over the block is serial within a +# member, which keeps `rmax` a true running maximum (the relative test compares +# each column against the largest norm seen *so far*, as in the reference). +@kernel function _ara_convergence_kernel!(samples, ranks, svec, jcount, rmax, + dR, + eps_rel::Float64, + r_required::Int, + block::Int, + maxrank::Int, +) + b = @index(Global, Linear) + @inbounds begin + drawn = Int(samples[b]) + if drawn > 0 + # member state and block scan + m = rmax[b] + sv = Int(svec[b]) + rk = Int(ranks[b]) + j0 = Int(jcount[b]) + for j in 1:min(drawn, block) + d = dR[j, b] + m = ifelse(d > m, d, m) + if d <= eps_rel * m + sv += 1 + else + sv = 0 + rk = j0 + j + end + end + + # updated state and next width + j0 += min(drawn, block) + rmax[b] = m + svec[b] = Int32(sv) + ranks[b] = Int32(rk) + jcount[b] = Int32(j0) + done = (sv >= r_required) | (j0 >= maxrank) + samples[b] = done ? Int32(0) : Int32(min(block, maxrank - j0)) + end + end +end + +""" + ara_update_convergence!(state, dR, eps_rel, r_required, block, maxrank) + -> active_count + +Fold one block of projected norms into `state` and return how many members are +still sampling. + +A member stops when `r_required` consecutive columns satisfy +`dR[j] ≤ eps_rel · rmax`, or when it reaches `maxrank`. Members already at +`samples == 0` are skipped; packing active members contiguously is separate. + +The returned count comes from a device-to-host copy of `samples`, one small +transfer per pass. That is the loop's only synchronization point. +""" +function ara_update_convergence!(state::ARAConvergenceState, + dR, + eps_rel::Real, + r_required::Int, + block::Int, + maxrank::Int, + count::Int=length(state.samples), +) + count == 0 && return 0 + 0 <= count <= length(state.samples) || + throw(ArgumentError("count must lie in 0:$(length(state.samples))")) + size(dR, 2) >= count || + throw(DimensionMismatch("dR must have at least $count columns")) + block <= size(dR, 1) || + throw(ArgumentError("block exceeds the rows of dR")) + eps_rel >= 0 || throw(ArgumentError("eps_rel must be nonnegative")) + r_required >= 1 || throw(ArgumentError("r_required must be positive")) + + _ara_convergence_kernel!(get_backend(dR))( + state.samples, state.ranks, state.svec, state.jcount, state.rmax, dR, + Float64(eps_rel), r_required, block, maxrank; ndrange=count, + ) + copyto!(state.samples_host, state.samples) + return Base.count(>(Int32(0)), view(state.samples_host, 1:count)) +end + +"""Number of members still drawing samples, from the host mirror.""" +@inline count_active(state::ARAConvergenceState) = + count(>(Int32(0)), state.samples_host) + +# --------------------------------------------------------------------------- +# The blocked ARA loop (Algorithm 2.3). +# --------------------------------------------------------------------------- + +""" + ara_stopping_floor(Tgram) -> Float64 + +Smallest supported relative tolerance, `√u_hi`. Two-pass Cholesky-QR requires +`κ ≤ u_hi^{-1/2}` (Yamamoto et al., ETNA 44:306-326, 2015); below this tolerance, +`potrf_batched!` breakdown is expected and acts as a convergence signal. +""" +@inline ara_stopping_floor(::Type{Tgram}) where {Tgram} = + sqrt(Float64(eps(real(Tgram))) / 2) + +"""Scratch for [`ara_build_basis!`](@ref) over a batch of `count` panels.""" +struct ARAWorkspace{QT,YT,DT,CT,FM,IV,SV} + Q::QT # m × maxrank × count: the basis, grown in place + Yblk::YT # m × block × count: current sample block + Dproj::DT # maxrank × block × count: BCGS2 coefficients + chol::CT # two-pass Cholesky-QR workspace over `Yblk` + dR::FM + status::IV # per-member potrf info from the first Cholesky-QR pass + status_host::Vector{Int32} + kcut::IV # per-member first numerically invalid column + kcut_host::Vector{Int32} + state::SV + block::Int +end + +""" + ARAWorkspace(::Type{T}, backend, m, maxrank, count; block=32) + +Allocate ARA scratch. `block` is the sample width and affects efficiency and +oversampling, not correctness. +""" +function ARAWorkspace(::Type{T}, backend, m::Int, maxrank::Int, count::Int; + block::Int=32, arena=nothing, + state_storage=nothing) where {T} + maxrank >= 0 && count >= 0 && m >= 0 || + throw(ArgumentError("m, maxrank and count must be nonnegative")) + Q = workspace_array!( + run_persistent_t_arena(arena), backend, T, m, maxrank, count) + return ARAWorkspace(Q; block, arena, state_storage) +end + +""" + ARAWorkspace(Q; block=32, arena=nothing) + +Wrap a caller-owned basis panel `Q` (`m × maxrank × count`). Other storage is +allocated on `Q`'s backend or drawn from `arena` when supplied. +""" +function ARAWorkspace(Q::AbstractArray{T,3}; block::Int=32, arena=nothing, + state_storage=nothing) where {T} + block >= 1 || throw(ArgumentError("block must be positive")) + + # basis growth and Cholesky-QR scratch + m, maxrank, count = size(Q) + backend = get_backend(Q) + blk = min(block, max(maxrank, 1)) + Thi = tlr_orthogonalization_type(T) + tarena = run_t_arena(arena) + thi_arena = run_thi_arena(arena) + Yblk = workspace_array!(tarena, backend, T, m, blk, count) + Dproj = workspace_array!(tarena, backend, T, max(maxrank, 1), blk, count) + R1 = workspace_array!(tarena, backend, T, blk, blk, count) + R2 = workspace_array!(tarena, backend, T, blk, blk, count) + chol = ARACholeskyWorkspace( + Yblk, + workspace_array!(thi_arena, backend, Thi, m, blk, count), + workspace_array!(thi_arena, backend, Thi, blk, blk, count), + R1, R2, + ) + + # convergence-state scratch, fresh or caller-supplied + if state_storage === nothing + dR = allocate(backend, Float64, blk, count) + status = allocate(backend, Int32, count) + status_host = Vector{Int32}(undef, count) + kcut = allocate(backend, Int32, count) + kcut_host = Vector{Int32}(undef, count) + state = ARAConvergenceState(backend, count) + else + size(state_storage.dR) == (blk, count) || + throw(DimensionMismatch("ARA dR storage must have size ($blk, $count)")) + dR = state_storage.dR + status = state_storage.status + status_host = state_storage.status_host + kcut = state_storage.kcut + kcut_host = state_storage.kcut_host + state = ARAConvergenceState( + state_storage.samples, state_storage.ranks, state_storage.svec, + state_storage.jcount, state_storage.rmax, + state_storage.samples_host) + end + + return ARAWorkspace( + Q, Yblk, Dproj, chol, dR, status, status_host, kcut, kcut_host, + state, blk, + ) +end + +""" + rebind_ara_phase(ws, arena) + +Recreate only the phase-backed sampling/orthogonalization views after a rolling +scheduler has reused the phase arena for admission or retirement. Persistent +`Q` and every convergence/status buffer retain their identities and contents. +""" +function rebind_ara_phase(ws::ARAWorkspace, arena) + arena_reset_phase!(arena) + T = eltype(ws.Q) + backend = get_backend(ws.Q) + m, maxrank, count = size(ws.Q) + blk = ws.block + Thi = tlr_orthogonalization_type(T) + a = run_t_arena(arena) + ahi = run_thi_arena(arena) + + Yblk = workspace_array!(a, backend, T, m, blk, count) + Dproj = workspace_array!(a, backend, T, max(maxrank, 1), blk, count) + R1 = workspace_array!(a, backend, T, blk, blk, count) + R2 = workspace_array!(a, backend, T, blk, blk, count) + chol = ARACholeskyWorkspace( + Yblk, + workspace_array!(ahi, backend, Thi, m, blk, count), + workspace_array!(ahi, backend, Thi, blk, blk, count), + R1, R2, + ) + + return ARAWorkspace( + ws.Q, Yblk, Dproj, chol, ws.dR, ws.status, ws.status_host, + ws.kcut, ws.kcut_host, ws.state, ws.block, + ) +end + +""" + ara_build_basis!(ws, sample_right!; eps_rel, r_required=10, compute) + -> (; Q, ranks, passes) + +Grow an orthonormal basis for the column space of a batch of implicit operators +to relative tolerance `eps_rel` (Boukaram, Turkiyyah & Keyes, Algorithm 2.3). + +`sample_right!(Y, width)` must overwrite the first `width` +columns of the `m × block × count` array `Y` with `Xᵦ Ω` for a freshly drawn +Gaussian `Ω`, independently per batch member. Freshness is required because the +stopping rule is the Halko–Martinsson–Tropp a posteriori bound, whose failure +probability decays like `10^{-r_required}` only for independent samples. + +Each pass projects the block against the existing basis with two-pass block +classical Gram-Schmidt, normalizes it with two mixed-precision Cholesky-QR +passes, and folds `diag(R)` into the convergence state. A member stops when +`r_required` consecutive columns are negligible, when `potrf_batched!` reports +a numerically singular block, or at `maxrank`. + +`eps_rel` below [`ara_stopping_floor`](@ref) is rejected rather than silently +run to `maxrank`. +""" +function ara_build_basis!(ws::ARAWorkspace, sample_right!; + eps_rel::Real, + r_required::Int=10, + compute=nothing, +) + T = eltype(ws.Q) + Thi = tlr_orthogonalization_type(T) + maxrank, count = size(ws.Q, 2), size(ws.Q, 3) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + blk = ws.block + + eps_rel > 0 || throw(ArgumentError("eps_rel must be positive")) + floor_rel = ara_stopping_floor(Thi) + eps_rel >= floor_rel || throw(ArgumentError( + "eps_rel = $eps_rel is below the Cholesky-QR orthogonality limit " * + "√u = $floor_rel for Gram type $Thi; the stopping test cannot be met " * + "and the loop would run to maxrank. Use a coarser tolerance or a " * + "higher-precision Gram.")) + (count == 0 || maxrank == 0) && + return (; Q=view(ws.Q, :, 1:0, :), ranks=ws.state.ranks, passes=0) + + adj = adjoint_blas_char(T) + ara_reset!(ws.state, blk, maxrank) + fill!(ws.Q, zero(T)) + passes = 0 + grown = 0 # columns of `Q` written so far (batch-uniform) + + while grown < maxrank + # fresh sample block, zero-padded past `width` on a partial final pass + width = min(blk, maxrank - grown) + sample_right!(ws.Yblk, width) + width < blk && fill!(view(ws.Yblk, :, (width + 1):blk, :), zero(T)) + + # interleaved BCGS2 and Cholesky-QR2 + # Algorithm 2.3 applies `(P·CQR)²`. Interleaving is required because the + # first normalization can amplify an `O(u‖Y‖)` overlap with `Q` to an + # O(1) fraction; the second projection must run afterward to remove it. + Qc = grown > 0 ? view(ws.Q, :, 1:grown, :) : nothing + D = grown > 0 ? view(ws.Dproj, 1:grown, :, :) : nothing + fill!(ws.status, Int32(0)) + @unroll for pass in 1:2 + if Qc !== nothing + precision_gemm_batched!(adj, 'N', one(T), Qc, ws.Yblk, + zero(T), D, mode) + precision_gemm_batched!('N', 'N', -one(T), Qc, D, + one(T), ws.Yblk, mode) + end + if pass == 1 + ara_cholesky_pass!(ws.chol, ws.chol.R1, ws.chol.R1_tiles; + status=ws.status) + else + ara_cholesky_pass!(ws.chol, ws.chol.R2, ws.chol.R2_tiles) + end + end + copyto!(ws.status_host, ws.status) + + # valid block prefix and basis append + ara_block_norms!(ws.dR, ws.chol) + ara_mask_breakdown!(ws.Yblk, ws.dR, ws.kcut, ws.chol.R1, ws.status, + width, floor_rel; scale=ws.state.rmax) + copyto!(ws.kcut_host, ws.kcut) + view(ws.Q, :, (grown + 1):(grown + width), :) .= + view(ws.Yblk, :, 1:width, :) + grown += width + passes += 1 + + # per-member stopping test and breakdown retirement + ara_update_convergence!(ws.state, ws.dR, eps_rel, r_required, + width, maxrank) + active = _ara_retire_broken!(ws.state, ws.kcut_host, width) + active == 0 && break + end + + return (; Q=view(ws.Q, :, 1:grown, :), ranks=ws.state.ranks, passes) +end + +# A block is usable through column `k-1` when `potrf` reports `info = k`. +# Status alone is insufficient: a positive but tiny pivot can pass `potrf` and +# still make the triangular solve unstable or produce `NaN` on a zero panel. +# The pivots are measured against the member's own scale as well as the block's: +# a block that is all rounding noise has no large pivot of its own to be cut +# against, and normalizing it would turn its rounding-level overlap with the +# basis into an O(1) one. +@kernel function _ara_cut_kernel!(kcut, R1::AbstractArray{T,3}, status, + width::Int, floor_rel::Float64, + scale, has_scale::Bool) where {T} + b = @index(Global, Linear) + @inbounds begin + # largest finite pivot, of this block or seen before for this member + mx = has_scale ? Float64(scale[b]) : 0.0 + for j in 1:width + d = sqrt(abs2_f64(R1[j, j, b])) + (isfinite(d) && d > mx) && (mx = d) + end + + # factorization and small-pivot cutoffs + k = width + 1 + info = Int(status[b]) + (info > 0 && info < k) && (k = info) + thresh = floor_rel * mx + for j in 1:width + d = sqrt(abs2_f64(R1[j, j, b])) + if !isfinite(d) || d < thresh + (j < k) && (k = j) + break + end + end + + kcut[b] = Int32(k) + end +end + +@kernel function _ara_mask_breakdown_kernel!(Y::AbstractArray{T,3}, dR, kcut, + width::Int) where {T} + j, b = @index(Global, NTuple) + @inbounds if j >= Int(kcut[b]) && j <= width + for i in axes(Y, 1) + Y[i, j, b] = zero(T) + end + dR[j, b] = 0.0 + end +end + +""" + ara_mask_breakdown!(Y, dR, kcut, R1, status, width, floor_rel; scale=nothing) -> kcut + +Discard the columns of a block that the orthonormalization could not deliver, +keeping its valid prefix. `R1` is the first-pass triangular factor and +`floor_rel` the CholeskyQR2 validity threshold `√u_hi`; the composite factor +cannot identify where the first pass became invalid. + +A column is cut when its pivot is below `floor_rel` times the largest pivot of +the block, or of `scale[b]`, the largest projected norm earlier passes saw for +member `b` (`ARAConvergenceState.rmax`). Without `scale`, a block of pure +rounding noise, which a member that has already stopped still draws while others +sample, has no large pivot to be measured against and is kept. +""" +function ara_mask_breakdown!(Y, dR, kcut, R1, status, width::Int, floor_rel::Float64; + scale=nothing) + width == 0 && return kcut + backend = get_backend(Y) + count = size(Y, 3) + _ara_cut_kernel!(backend)(kcut, R1, status, width, floor_rel, + scale === nothing ? dR : scale, scale !== nothing; + ndrange=count) + _ara_mask_breakdown_kernel!(backend)(Y, dR, kcut, width; ndrange=(width, count)) + return kcut +end + +# Breakdown means the block of `width` fresh Gaussian samples produced only +# `k-1 < width` independent directions. For `Y_Δ = (I-QQᵀ)XΩ_Δ` with Gaussian +# `Ω_Δ`, the samples are in general position, so `rank(Y_Δ) = rank((I-QQᵀ)X)` +# almost surely: the residual range has dimension `k-1` and this pass has just +# captured all of it. The member is therefore converged, and forcing it is not a +# heuristic but the conclusion of that argument. Runs *after* the convergence +# update so the rank from this pass is recorded first. +function _ara_retire_broken!(state::ARAConvergenceState, kcut_host, width::Int) + any(k -> k <= width, kcut_host) || return count_active(state) + samples = state.samples_host + copyto!(samples, state.samples) + @inbounds for b in eachindex(kcut_host) + (kcut_host[b] <= width) && (samples[b] = Int32(0)) + end + copyto!(state.samples, samples) + return count_active(state) +end + +# Swap two batch members in the persistent basis and convergence state. Packed +# ARA keeps live members in `1:nactive`; a retiring member is exchanged with the +# last live slot, leaving a dense active prefix and a retired suffix. The +# accumulated basis is moved once, at retirement, rather than inactive members +# occupying every later batched factorization. +@kernel function ara_swap_basis_kernel!(Q, p::Int, q::Int) + i, j = @index(Global, NTuple) + @inbounds begin + x = Q[i, j, p] + Q[i, j, p] = Q[i, j, q] + Q[i, j, q] = x + end +end + +@kernel function _ara_swap_state_kernel!(samples, ranks, svec, jcount, rmax, + p::Int, q::Int) + _ = @index(Global, Linear) + @inbounds begin + x = samples[p]; samples[p] = samples[q]; samples[q] = x + x = ranks[p]; ranks[p] = ranks[q]; ranks[q] = x + x = svec[p]; svec[p] = svec[q]; svec[q] = x + x = jcount[p]; jcount[p] = jcount[q]; jcount[q] = x + y = rmax[p]; rmax[p] = rmax[q]; rmax[q] = y + end +end + +function _ara_swap_members!(ws::ARAWorkspace, p::Int, q::Int) + p == q && return ws + + backend = get_backend(ws.Q) + ara_swap_basis_kernel!(backend)(ws.Q, p, q; + ndrange=(size(ws.Q, 1), size(ws.Q, 2))) + _ara_swap_state_kernel!(backend)( + ws.state.samples, ws.state.ranks, ws.state.svec, ws.state.jcount, + ws.state.rmax, p, q; ndrange=(1,), + ) + + ws.state.samples_host[p], ws.state.samples_host[q] = + ws.state.samples_host[q], ws.state.samples_host[p] + return ws +end + +@kernel function _ara_append_local_kernel!(Q, Y, samples, jcount) + i, j, b = @index(Global, NTuple) + @inbounds begin + drawn = Int(samples[b]) + if j <= drawn + Q[i, Int(jcount[b]) + j, b] = Y[i, j, b] + end + end +end + +@kernel function _ara_reset_slot_kernel!(Q, samples, ranks, svec, jcount, rmax, + firstslot::Int, count::Int, + first_width::Int) + i, j, slotlocal = @index(Global, NTuple) + if slotlocal <= count + slot = firstslot + slotlocal - 1 + @inbounds Q[i, j, slot] = zero(eltype(Q)) + if i == 1 && j == 1 + @inbounds begin + samples[slot] = Int32(first_width) + ranks[slot] = Int32(0) + svec[slot] = Int32(0) + jcount[slot] = Int32(0) + rmax[slot] = 0.0 + end + end + end +end + +""" + ara_reset_slots!(ws, firstslot, count, maxrank) + +Reset a contiguous slot range for rolling admission without disturbing basis +or convergence state retained by older active slots. +""" +function ara_reset_slots!(ws::ARAWorkspace, firstslot::Int, count::Int, + maxrank::Int=size(ws.Q, 2)) + count == 0 && return ws + 1 <= firstslot <= size(ws.Q, 3) && + firstslot + count - 1 <= size(ws.Q, 3) || + throw(BoundsError(ws.Q, (:, :, firstslot:(firstslot + count - 1)))) + + first_width = min(ws.block, maxrank) + _ara_reset_slot_kernel!(get_backend(ws.Q))( + ws.Q, ws.state.samples, ws.state.ranks, ws.state.svec, + ws.state.jcount, ws.state.rmax, firstslot, count, first_width; + ndrange=(size(ws.Q, 1), size(ws.Q, 2), count), + ) + + @inbounds fill!( + view(ws.state.samples_host, firstslot:(firstslot + count - 1)), + Int32(first_width), + ) + return ws +end + +function _ara_orthogonalize_group!(ws::ARAWorkspace, slots::UnitRange{Int}, + width::Int, projection_width::Int, + mode, floor_rel) + isempty(slots) && return + T = eltype(ws.Q) + adj = adjoint_blas_char(T) + Y = view(ws.Yblk, :, 1:width, slots) + Qc = projection_width > 0 ? + view(ws.Q, :, 1:projection_width, slots) : nothing + D = projection_width > 0 ? + view(ws.Dproj, 1:projection_width, 1:width, slots) : nothing + status = view(ws.status, slots) + fill!(status, Int32(0)) + + chol = ARACholeskyWorkspace( + Y, + view(ws.chol.Y_hi, :, 1:width, slots), + view(ws.chol.G_hi, 1:width, 1:width, slots), + view(ws.chol.R1, 1:width, 1:width, slots), + view(ws.chol.R2, 1:width, 1:width, slots), + ) + + for pass in 1:2 + if Qc !== nothing + precision_gemm_batched!(adj, 'N', one(T), Qc, Y, + zero(T), D, mode) + precision_gemm_batched!('N', 'N', -one(T), Qc, D, + one(T), Y, mode) + end + if pass == 1 + ara_cholesky_pass!( + chol, chol.R1, chol.R1_tiles; status, count=length(slots)) + else + ara_cholesky_pass!( + chol, chol.R2, chol.R2_tiles; count=length(slots)) + end + end + + dR = view(ws.dR, 1:width, slots) + ara_block_norms!(dR, chol) + kcut = view(ws.kcut, slots) + ara_mask_breakdown!(Y, dR, kcut, chol.R1, status, width, floor_rel; + scale=view(ws.state.rmax, slots)) + return +end + +""" + ara_packed_pass!(ws, sample_right!, nactive, progress_host; ...) + +Execute one complete rolling-ARA pass on the active prefix. Basis progress is +slot-local: projection uses the largest active prefix (younger slots contain +zeros beyond their own progress), and each normalized block is appended at +that slot's `jcount`. The returned retired suffix has already been +swap-compacted through `swap_member!`. +""" +function ara_packed_pass!(ws::ARAWorkspace, sample_right!, nactive::Int, + member_ids::Vector{Int}, progress_host::Vector{Int}; + eps_rel::Real, r_required::Int=10, + compute=nothing, + swap_member!::Function=(p, q) -> nothing) + nactive == 0 && return (; nactive=0, retired=1:0, width=0, + projection_width=0, discarded=0) + nactive <= size(ws.Q, 3) || + throw(DimensionMismatch("active count exceeds workspace capacity")) + + T = eltype(ws.Q) + Thi = tlr_orthogonalization_type(T) + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + floor_rel = ara_stopping_floor(Thi) + + eps_rel >= floor_rel || throw(ArgumentError( + "eps_rel = $eps_rel is below the Cholesky-QR limit $floor_rel")) + drawn = collect(Int, view(ws.state.samples_host, 1:nactive)) + width = maximum(drawn) + width > 0 || return (; nactive=0, retired=1:nactive, width=0, + projection_width=maximum(view(progress_host, 1:nactive)), + discarded=0) + projection_width = maximum(view(progress_host, 1:nactive)) + + # full-width prefix and partial-width suffix + # Both groups share the sampling launch but use separate Cholesky-QR batches + # so padded terminal columns never enter a factorization. + nfull = count(==(width), drawn) + if nfull < nactive + p, q = 1, nactive + while p <= nfull + if drawn[p] == width + p += 1 + continue + end + while q > nfull && drawn[q] != width + q -= 1 + end + q <= nfull && break + _ara_swap_members!(ws, p, q) + swap_member!(p, q) + member_ids[p], member_ids[q] = member_ids[q], member_ids[p] + progress_host[p], progress_host[q] = + progress_host[q], progress_host[p] + drawn[p], drawn[q] = drawn[q], drawn[p] + p += 1 + q -= 1 + end + end + + # sampled panels + Y = view(ws.Yblk, :, :, 1:nactive) + sample_right!(Y, width, view(member_ids, 1:nactive)) + width < ws.block && fill!(view(Y, :, (width + 1):ws.block, :), zero(T)) + + # width-specific orthogonalization + nfull > 0 && _ara_orthogonalize_group!( + ws, 1:nfull, width, projection_width, mode, floor_rel) + if nfull < nactive + terminal_width = drawn[nfull + 1] + _ara_orthogonalize_group!( + ws, (nfull + 1):nactive, terminal_width, projection_width, + mode, floor_rel) + end + + copyto!(ws.status_host, ws.status) + copyto!(ws.kcut_host, ws.kcut) + + # basis progress and convergence + _ara_append_local_kernel!(get_backend(ws.Q))( + ws.Q, Y, ws.state.samples, ws.state.jcount; + ndrange=(size(ws.Q, 1), width, nactive), + ) + @inbounds for p in 1:nactive + progress_host[p] += drawn[p] + end + discarded = sum(width - d for d in drawn) + ara_update_convergence!( + ws.state, ws.dR, eps_rel, r_required, width, size(ws.Q, 2), nactive) + + # breakdown retirement within each valid prefix + # A terminal member's deliberately discarded tail is irrelevant. + samples = ws.state.samples_host + copyto!(samples, ws.state.samples) + @inbounds for p in 1:nactive + if ws.kcut_host[p] <= drawn[p] + samples[p] = Int32(0) + end + end + copyto!(ws.state.samples, samples) + + # retired suffix + oldactive = nactive + p = 1 + while p <= nactive + if samples[p] > 0 + p += 1 + continue + end + while nactive > p && samples[nactive] == 0 + nactive -= 1 + end + if p < nactive + _ara_swap_members!(ws, p, nactive) + swap_member!(p, nactive) + member_ids[p], member_ids[nactive] = + member_ids[nactive], member_ids[p] + progress_host[p], progress_host[nactive] = + progress_host[nactive], progress_host[p] + end + nactive -= 1 + end + return (; nactive, retired=(nactive + 1):oldactive, width, + projection_width, discarded) +end + +# A2 truncation uses `Z = PΣWᵀ` to obtain the represented matrix's SVD, +# `QZᵀ = (QW)ΣPᵀ`, and its exact Eckart-Young error. It returns +# `U = QW[:,1:r]` and column-scaled `V = P[:,1:r]diag(σ[1:r])`. +# Zero columns of `Q` induce zero columns of `Z` and zero rows in retained +# right singular vectors, so `U` remains orthonormal after breakdown masking. +# Per-member `W` tails are zeroed to support different ranks in one batched GEMM. + +""" + batched_thin_svd!(A) -> (U, S, V) + +Thin SVD `A[:,:,b] = U[:,:,b] * Diagonal(S[:,b]) * V[:,:,b]'` of every member of +a batch of tall-skinny matrices, with `size(A,1) ≥ size(A,2)`. `A` may be +overwritten. + +This backend hook defaults to host LAPACK. CUDA overrides it with +`CUDA.CUSOLVER.gesvda!`, avoiding the condition-number squaring of a Gram-based +SVD; AMD uses batched one-sided Jacobi SVD. +""" +function batched_thin_svd!(A::AbstractArray{T,3}) where {T} + m, n, count = size(A) + m >= n || throw(ArgumentError("batched_thin_svd! requires size(A,1) >= size(A,2)")) + RT = real(T) + + n == 0 && return ( + similar(A, T, m, 0, count), + similar(A, RT, 0, count), + similar(A, T, 0, 0, count), + ) + + # host factorizations + Ah = A isa Array ? A : Array(A) + U = Array{T,3}(undef, m, n, count) + S = Array{RT,2}(undef, n, count) + V = Array{T,3}(undef, n, n, count) + @inbounds for b in 1:count + F = svd!(view(Ah, :, :, b); full=false) + copyto!(view(U, :, :, b), F.U) + copyto!(view(S, :, b), F.S) + copyto!(view(V, :, :, b), F.V) + end + + A isa Array && return (U, S, V) + + # backend restoration + dev = similar(A, T, 0) # backend-typed constructor + return (_to_backend(dev, U), _to_backend(dev, S), _to_backend(dev, V)) +end + +@inline function _to_backend(proto, H::Array) + D = similar(proto, eltype(H), size(H)) + copyto!(D, H) + return D +end + +# The smallest rank whose discarded energy fits the budget is capped at +# `maxrank`; a tail scan reports achieved error. With original energy supplied, +# Pythagoras adds range-capture error `‖X‖² - Σσ_k²`, making total error +# `‖X‖² - Σ_{k≤r}σ_k²` (the randQB_EI indicator). Cancellation can make capture +# smaller than subtraction roundoff, so values below that floor are clamped to +# zero to avoid inflated ranks. +@kernel function _ara_truncation_rank_kernel!(ranks, err_sq, S, energy, tol_sq, + relative::Bool, has_energy::Bool, + maxrank::Int, width::Int, rows::Int, + capture_sq, has_capture::Bool) + b = @index(Global, Linear) + @inbounds begin + # represented energy + total = 0.0 + for k in 1:width + total += Float64(S[k, b])^2 + end + + # range-capture budget + reference = has_energy ? Float64(energy[b]) : total + capture = 0.0 + if has_energy + capture = reference - total + floor_sq = Float64(rows) * Float64(eps(Float64)) * reference + capture = (capture < floor_sq) ? 0.0 : capture + end + reported = has_capture ? Float64(capture_sq[b]) : 0.0 + budget = (relative ? Float64(tol_sq) * reference : Float64(tol_sq)) - capture + + # smallest admissible rank + dropped = 0.0 + r = width + while r > 0 + e = Float64(S[r, b])^2 + dropped + e > budget && break + dropped += e + r -= 1 + end + + if r > maxrank # capacity is authoritative + for k in (maxrank + 1):r + dropped += Float64(S[k, b])^2 + end + r = maxrank + end + + ranks[b] = eltype(ranks)(r) + err_sq[b] = capture + reported + dropped + end +end + +# Zero `W[:, r_b+1 : width]` and scale `V[:, k] = P[:, k]·σ_k` (zero past `r_b`), +# so the subsequent GEMM can run at one uniform width for the whole batch. +@kernel function _ara_apply_truncation_kernel!(W::AbstractArray{T,3}, + V::AbstractArray{T,3}, + P::AbstractArray{T,3}, + S, ranks, width::Int) where {T} + k, b = @index(Global, NTuple) + @inbounds begin + keep = k <= Int(ranks[b]) + for i in axes(W, 1) + W[i, k, b] = keep ? W[i, k, b] : zero(T) + end + + # σₖpₖ is zero when σₖ is, whatever pₖ holds: cuSOLVER's gesvda returns + # NaN left vectors for zero singular values, and NaN * 0 is NaN + scale = keep ? T(S[k, b]) : zero(T) + for i in axes(V, 1) + V[i, k, b] = iszero(scale) ? zero(T) : P[i, k, b] * scale + end + end +end + +""" + ara_truncate!(U, V, ranks, err_sq, Q, Z; tol, relative=true, maxrank) + -> (; U, V, ranks, err_sq) + +Optimally truncate `X ≈ Q Zᵀ` to per-member rank, writing `U` (`b_m × maxrank × +count`, orthonormal columns) and `V` (`b_n × maxrank × count`). + +`tol` is the Frobenius error budget, relative to each member's reference energy +when `relative=true`. `err_sq[b]` is the achieved squared error; +`ranks[b] == maxrank` indicates that the spectrum exceeded capacity. + +`energy[b] = ‖X‖_F²` of the original operator may be supplied when known +independently. The range-capture error `‖X‖² - ‖Z‖²` is then included, so +`err_sq` covers both range capture and truncation. +With neither, the reference is `‖Z‖²` and capture is assumed zero, which is +correct when `Q` was built to tolerance by [`ara_build_basis!`](@ref). +`capture[b]`, an estimate of the squared range-capture error `‖X - QQᴴX‖_F²` +when `‖X‖²` is not known, is added to `err_sq[b]` only: the ranks are chosen as +without it, so a zero entry leaves that member unchanged. `capture` may be the +same array as `err_sq`. + +`Z` is overwritten. +""" +function ara_truncate!(U, V, ranks, err_sq, Q, Z; + tol::Real, relative::Bool=true, maxrank::Int, + energy=nothing, capture=nothing, compute=nothing) + T = eltype(Q) + bm, sQ, count = size(Q) + bn = size(Z, 1) + size(Z) == (bn, sQ, count) || + throw(DimensionMismatch("Z must be ($bn, $sQ, $count)")) + size(U) == (bm, maxrank, count) || + throw(DimensionMismatch("U must be ($bm, $maxrank, $count)")) + size(V) == (bn, maxrank, count) || + throw(DimensionMismatch("V must be ($bn, $maxrank, $count)")) + maxrank <= sQ || + throw(ArgumentError("maxrank must not exceed the basis width $sQ")) + tol >= 0 || throw(ArgumentError("tol must be nonnegative")) + energy === nothing || capture === nothing || + throw(ArgumentError("give energy or capture, not both")) + count == 0 && return (; U, V, ranks, err_sq) + + mode = compute === nothing ? default_gemm_compute_mode(T) : + gemm_compute_mode(compute) + backend = get_backend(Q) + + P, S, W = batched_thin_svd!(Z) + _ara_truncation_rank_kernel!(backend)( + ranks, err_sq, S, energy === nothing ? err_sq : energy, + Float64(tol)^2, relative, energy !== nothing, maxrank, sQ, bn, + capture === nothing ? err_sq : capture, capture !== nothing; + ndrange=count, + ) + _ara_apply_truncation_kernel!(backend)( + W, V, P, S, ranks, maxrank; ndrange=(maxrank, count), + ) + + # left factors at uniform batch width + precision_gemm_batched!('N', 'N', one(T), Q, view(W, :, 1:maxrank, :), + zero(T), U, mode) + return (; U, V, ranks, err_sq) +end diff --git a/src/tlr/core/compression/blas_utils.jl b/src/tlr/core/compression/blas_utils.jl new file mode 100644 index 00000000..d0ed963b --- /dev/null +++ b/src/tlr/core/compression/blas_utils.jl @@ -0,0 +1,19 @@ +@inline tlr_orthogonalization_type(::Type{Float16}) = Float32 +@inline tlr_orthogonalization_type(::Type{Float32}) = Float64 +@inline tlr_orthogonalization_type(::Type{Float64}) = Float64 +@inline tlr_orthogonalization_type(::Type{ComplexF32}) = ComplexF64 +@inline tlr_orthogonalization_type(::Type{ComplexF64}) = ComplexF64 +@inline tlr_orthogonalization_type(::Type{T}) where {T} = T + +@inline adjoint_blas_char(::Type{<:Complex}) = 'C' +@inline adjoint_blas_char(::Type) = 'T' + +""" + batch_views(A, r=size(A, 2)) -> Vector{<:AbstractMatrix} + +Per-batch-entry views into a `[m, maxrank, n]` factor array, trimmed to the +first `r` columns. These concrete vectors are built with the workspace and +reused by pointer-batched BLAS paths. +""" +@inline batch_views(A::AbstractArray{T,3}, r::Int=size(A, 2)) where {T} = + [view(A, :, 1:r, k) for k in axes(A, 3)] diff --git a/src/tlr/core/compression/compress.jl b/src/tlr/core/compression/compress.jl new file mode 100644 index 00000000..cc672b1e --- /dev/null +++ b/src/tlr/core/compression/compress.jl @@ -0,0 +1,360 @@ +# Dense-diagonal copy ---------------------------------------------------------- + +@kernel function _copy_diag_from_dense_kernel!(D::AbstractArray{T,3}, + A::AbstractMatrix{T}, + tile_m::Int, + tile_n::Int) where {T} + row, col, batch = @index(Global, NTuple) + p0 = (batch - 1) * tile_m + 1 + q0 = (batch - 1) * tile_n + 1 + @inbounds D[row, col, batch] = A[p0+row-1, q0+col-1] +end + +function _copy_diagonal_from_dense!(A_tlr::TLRMatrix{<:Any,T}, + A::AbstractMatrix{T}) where {T} + # full diagonal tiles + n_full_diag = size(A_tlr.D, 3) + bm, bn = nominal_tile_size(A_tlr) + if n_full_diag > 0 + _copy_diag_from_dense_kernel!(get_backend(A_tlr))( + A_tlr.D, A, bm, bn; ndrange=(bm, bn, n_full_diag)) + end + + # corner diagonal tile + if size(A_tlr.D_corner, 3) != 0 + tile_k = ndiag_tiles(A_tlr) + tm, tn = tile_size(A_tlr, tile_k, tile_k) + copyto!(view(A_tlr.D_corner, 1:tm, 1:tn, 1), + dense_tile_view(A, A_tlr, tile_k, tile_k)) + end + + # compressed metadata + qm, qn = grid_size(A_tlr) + @inbounds for k in 1:ndiag_tiles(A_tlr) + slot = tile_linear_index(tile_order(A_tlr), qm, qn, k, k) + ranks(A_tlr)[slot] = 0 + residuals(A_tlr)[slot] = 0.0 + end + return A_tlr +end + +# Tile-batch compression core -------------------------------------------------- + +struct DenseTiles{T,AT<:AbstractMatrix{T},TV<:AbstractVector,CV} + A::AT + tiles::TV + p0s::CV + q0s::CV + tm::Int + tn::Int +end + +function _tile_norms_sq!(out, src::DenseTiles) + n = length(src.tiles) + n == 0 && return out + backend = get_backend(src.A) + W, _, NT = norm_launch(backend, src.tn) + tile_norm_sq_kernel!(backend, NT)( + out, src.A, src.p0s, src.q0s, src.tm, src.tn, Val{W}(), Val{NT}(); + ndrange=(NT * n,), workgroupsize=NT) + return out +end + +"""A homogeneous `[tile_rows, tile_cols, tile_count]` dense tile batch.""" +struct PackedTiles{T,PT<:AbstractArray{T,3},TV<:AbstractVector} + data::PT + tiles::TV +end +PackedTiles(data::AbstractArray{<:Any,3}) = + PackedTiles(data, [view(data, :, :, k) for k in axes(data, 3)]) + +_tile_norms_sq!(out, src::PackedTiles) = batch_frobenius_norms_sq!(out, src.data) + +""" + compress_tiles!(src, workspace; eps_sq, rel, r_required=10) + +Run blocked ARA on one homogeneous tile batch. Results are left in the +workspace; no matrix container is constructed. +""" +function compress_tiles!(src::Union{DenseTiles{T},PackedTiles{T}}, cat; + eps_sq::Float64, rel::Bool, + r_required::Int=10) where {T} + r_required >= 1 || throw(ArgumentError("r_required must be positive")) + isempty(src.tiles) && return cat + + if cat.R_keep == 0 + _tile_norms_sq!(cat.errors_sq, src) + fill!(cat.ranks, zero(eltype(cat.ranks))) + return cat + end + + # sampling setup + _tile_norms_sq!(cat.errors_sq, src) + eps_rel = max(sqrt(eps_sq), ara_stopping_floor(tlr_orthogonalization_type(T))) + sampler = function (Y, width) + Random.randn!(cat.omega) + gemm_batched!('N', 'N', one(T), src.tiles, + cat.omega_tiles, zero(T), cat.Y_tiles) + return Y + end + + # basis growth, then co-range and optimal truncation + ara_build_basis!(cat.ara, sampler; eps_rel, r_required) + gemm_batched!(adjoint_blas_char(T), 'N', one(T), + src.tiles, cat.Q_tiles, zero(T), cat.V_tiles) + ara_truncate!(view(cat.U, :, 1:cat.R_keep, :), + view(cat.V, :, 1:cat.R_keep, :), + cat.ranks, cat.errors_sq, cat.ara.Q, cat.Z; + tol=sqrt(eps_sq), relative=rel, maxrank=cat.R_keep, + energy=cat.errors_sq) + return cat +end + +function _compress_category!(A::AbstractMatrix, cat, + tile_size::NTuple{2,Int}, + eps_sq::Float64, rel::Bool, + r_required::Int) + isempty(cat.tile_ids) && return cat + bm, bn = tile_size + tm, tn = cat.tile_shape + tiles = [view(A, + (i-1)*bm+1:(i-1)*bm+tm, + (j-1)*bn+1:(j-1)*bn+tn) for (i, j) in cat.tile_ids] + return compress_tiles!(DenseTiles(A, tiles, cat.p0s, cat.q0s, tm, tn), cat; + eps_sq, rel, r_required) +end + +function _compress_all_categories!(A::AbstractMatrix{T}, + ws::FTLRCompressionWorkspace, + eps_sq::Float64, rel::Bool, + r_required::Int) where {T} + cats = ws.cats + backend = get_backend(A) + tile_size = ws.key.tile_size + + if backend isa KernelAbstractions.CPU + for cat in cats + _compress_category!(A, cat, tile_size, eps_sq, rel, r_required) + end + else + for (cat, stream) in zip(cats, ws.streams) + with_stream(backend, stream) do + _compress_category!(A, cat, tile_size, eps_sq, rel, r_required) + end + end + for stream in ws.streams + sync_stream(backend, stream) + end + end + + return ws +end + +# Final packed-factor construction -------------------------------------------- + +@kernel function _scatter_lowrank_factor_kernel!(destination, source, + offsets, ranks, ld::Int) + factor = @index(Group, Linear) + lane = @index(Local, Linear) + logical_rows = size(source, 1) + active = logical_rows * (@inbounds ranks[factor]) + k = lane + while k <= active + row = (k - 1) % logical_rows + 1 + col = (k - 1) ÷ logical_rows + 1 + @inbounds destination[offsets[factor] + (col-1)*ld + row-1] = + source[row, col, factor] + k += @groupsize()[1] + end +end + +function _scatter_factor_batch!(C::CompressedFTLRMatrix, cat, side::Symbol) + isempty(cat.tile_ids) && return C + + # packed destination + backend = get_backend(C) + factors = side === :outer ? C.outer : C.inner + source = side === :outer ? cat.U : cat.V + tile_axis = side === :outer ? first(cat.tile_ids[1]) : last(cat.tile_ids[1]) + ld = aligned_leading_dimension(eltype(factors.data), + factors.logical_dimensions[tile_axis]) + + # factor offsets + offsets_host = Vector{Int}(undef, length(cat.tile_ids)) + @inbounds for (k, (i, j)) in enumerate(cat.tile_ids) + slot = tile_linear_index(factors.order, factors.qm, factors.qn, i, j) + offsets_host[k] = factors.offsets[slot] + end + offsets = copyto!(allocate(backend, Int, length(offsets_host)), offsets_host) + + # scatter launch + wg = backend isa KernelAbstractions.CPU ? 1 : 128 + _scatter_lowrank_factor_kernel!(backend, wg)( + factors.data, source, offsets, cat.ranks, ld; + ndrange=(wg * length(cat.tile_ids),), workgroupsize=wg) + return C +end + +function _finalize_compressed_ftlr(ws::FTLRCompressionWorkspace; + rank_multiple::Int=0, + outer_order=TileRowMajor, + inner_order=TileColMajor) + key = ws.key + backend = key.device + qm, qn = cld(key.m, key.tile_size[1]), cld(key.n, key.tile_size[2]) + + # gather per-category ranks and residuals into one host grid + rank_grid = Base.zeros(Int, qm, qn) + residual_grid = Base.zeros(Float64, qm, qn) + for cat in ws.cats + rk = cat.ranks isa Vector ? cat.ranks : Array(cat.ranks) + err = cat.errors_sq isa Vector ? cat.errors_sq : Array(cat.errors_sq) + @inbounds for (k, (i, j)) in enumerate(cat.tile_ids) + rank_grid[i, j] = rk[k] + residual_grid[i, j] = sqrt(max(Float64(real(err[k])), 0.0)) + end + end + + # exact-rank storage, sized from the discovered grid + C = CompressedFTLRMatrix( + backend, key.T, key.m, key.n, key.tile_size, rank_grid; + outer_order, inner_order, rank_multiple) + @inbounds for j in axes(rank_grid, 2), i in axes(rank_grid, 1) + slot = tile_linear_index(C.outer.order, C.outer.qm, C.outer.qn, i, j) + C.resid[slot] = residual_grid[i, j] + end + + # scatter each category's factors into the packed storage + for cat in ws.cats + _scatter_factor_batch!(C, cat, :outer) + _scatter_factor_batch!(C, cat, :inner) + end + KernelAbstractions.synchronize(backend) + return C +end + +# Public dense constructors ---------------------------------------------------- + +""" + CompressedFTLRMatrix(A, tile_size; maxrank, tol=0, rel=false, r_required=10, + rank_multiple=0, workspace=nothing) + +Compress dense `A` in one adaptive pass and return finalized packed factors. +`rank_multiple == 0` stores exact widths; a positive value rounds each nonzero +tile rank up to that multiple without changing its logical rank. + +Every tile, diagonal included, is compressed with the blocked adaptive randomized +range finder, which draws from the global random number generator. + +- `tile_size`: a tuple `(bm, bn)` or one integer for square tiles. +- `maxrank`: required cap on each tile's rank. +- `tol`: Frobenius-norm error allowed per tile, absolute, or relative to the + tile's norm when `rel=true`. With the default `tol=0` nothing may be dropped, + so tiles are typically kept at rank `maxrank`; pass a positive `tol`. +- `r_required`: consecutive negligible samples needed before a tile's basis stops + growing. +- `workspace`: an [`FTLRCompressionWorkspace`](@ref) built for the same matrix + size, element type, tile size and `maxrank` with `diagonal=:compressed`, reused + instead of allocating a new one. +- `outer_order`, `inner_order` (also accepted): tile orders of the packed factors, + [`TileRowMajor`](@ref) and [`TileColMajor`](@ref) by default. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 16), randn(n, 16); A = U * V'; + +julia> F = CompressedFTLRMatrix(A, 256; maxrank=64, tol=1e-8, rel=true); + +julia> B = similar(A); uncompress!(B, F); + +julia> all(==(16), ranks(F)) && norm(B - A) / norm(A) < 1e-8 +true +``` +""" +function CompressedFTLRMatrix(A::AbstractMatrix{T}, + tile_size::NTuple{2,Int}; + maxrank::Int, + tol::Real=0.0, + rel::Bool=false, + r_required::Int=10, + rank_multiple::Int=0, + workspace::Union{Nothing,FTLRCompressionWorkspace}=nothing, + outer_order=TileRowMajor, + inner_order=TileColMajor) where {T} + tol >= 0 || throw(ArgumentError("tol must be nonnegative")) + r_required >= 1 || throw(ArgumentError("r_required must be positive")) + rank_multiple >= 0 || throw(ArgumentError("rank_multiple must be nonnegative")) + + # workspace validation + ws = workspace === nothing ? FTLRCompressionWorkspace( + A, tile_size; maxrank, diagonal=:compressed) : workspace + validate_compression_workspace( + ws, A, tile_size, maxrank, :compressed) + + # compression and packing + _compress_all_categories!(A, ws, Float64(tol)^2, rel, r_required) + return _finalize_compressed_ftlr( + ws; rank_multiple, outer_order, inner_order) +end + +CompressedFTLRMatrix(A::AbstractMatrix, b::Int; kwargs...) = + CompressedFTLRMatrix(A, (b, b); kwargs...) + +""" + TLRMatrix(A, tile_size; maxrank, tol=0, rel=false, r_required=10, + rank_multiple=0, workspace=nothing) + +Compress only the off-diagonal tiles of dense `A`, keep the diagonal dense, +and return a finalized `TLRMatrix`. + +The keyword arguments are those of the dense `CompressedFTLRMatrix` constructor: +`maxrank` caps each tile's rank, and `tol` is the Frobenius-norm error allowed per +tile, absolute or, with `rel=true`, relative to the tile's norm. With the default +`tol=0` tiles are typically kept at rank `maxrank`. A reused `workspace` must have +been built with `diagonal=:dense`. Compression draws from the global random +number generator. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> using Random; Random.seed!(1); # compression is randomized + +julia> n = 1024; U, V = randn(n, 16), randn(n, 16); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 256; maxrank=64, tol=1e-8, rel=true); + +julia> B = similar(A); uncompress!(B, C); + +julia> maxrank(C) == 16 && norm(B - A) / norm(A) < 1e-8 +true +``` +""" +function TLRMatrix(A::AbstractMatrix{T}, tile_size::NTuple{2,Int}; + maxrank::Int, + tol::Real=0.0, + rel::Bool=false, + r_required::Int=10, + rank_multiple::Int=0, + workspace::Union{Nothing,FTLRCompressionWorkspace}=nothing) where {T} + tol >= 0 || throw(ArgumentError("tol must be nonnegative")) + r_required >= 1 || throw(ArgumentError("r_required must be positive")) + rank_multiple >= 0 || throw(ArgumentError("rank_multiple must be nonnegative")) + + # workspace validation + ws = workspace === nothing ? FTLRCompressionWorkspace( + A, tile_size; maxrank, diagonal=:dense) : workspace + validate_compression_workspace(ws, A, tile_size, maxrank, :dense) + + # off-diagonal compression and diagonal copy + _compress_all_categories!(A, ws, Float64(tol)^2, rel, r_required) + offdiag = _finalize_compressed_ftlr(ws; rank_multiple) + C = TLRMatrix(offdiag) + _copy_diagonal_from_dense!(C, A) + KernelAbstractions.synchronize(get_backend(C)) + return C +end + +TLRMatrix(A::AbstractMatrix, b::Int; kwargs...) = TLRMatrix(A, (b, b); kwargs...) diff --git a/src/tlr/core/compression/norms.jl b/src/tlr/core/compression/norms.jl new file mode 100644 index 00000000..d3ebe572 --- /dev/null +++ b/src/tlr/core/compression/norms.jl @@ -0,0 +1,149 @@ +# Squared magnitude accumulated in Float64. Energy and error decisions are +# intentionally more accurate than factor storage and GEMM compute precision. +@inline abs2_f64(x::Real) = abs2(Float64(x)) +@inline abs2_f64(x::Complex) = + abs2(Float64(real(x))) + abs2(Float64(imag(x))) + +@inline function norm_launch(backend, ncols::Int) + W = unwrap(SUBGROUP_SIZE(typeof(backend))) + nsub = ncols >= 8 ? 8 : ncols >= 4 ? 4 : ncols >= 2 ? 2 : 1 + return W, nsub, W * nsub +end + +# Per-tile squared Frobenius norm for tiles addressed within a dense matrix. +@kernel function tile_norm_sq_kernel!(out::AbstractVector{Tout}, + A::AbstractMatrix{T}, + p0s, + q0s, + tm::Int, + tn::Int, + ::Val{W}, + ::Val{NT}, +) where {Tout,T,W,NT} + ob = @index(Group, Linear) + tid = @index(Local, Linear) + partial = @localmem Float64 (NT,) + p0 = Int(@inbounds p0s[ob]) - 1 + q0 = Int(@inbounds q0s[ob]) - 1 + lane = (tid - 1) % W + 1 + sg = (tid - 1) ÷ W + 1 + nsub = NT ÷ W + + # tile accumulation + acc = 0.0 + col = sg + while col <= tn + row = lane + while row <= tm + @inbounds acc += abs2_f64(A[p0+row, q0+col]) + row += W + end + col += nsub + end + @inbounds partial[tid] = acc + + # workgroup reduction with literal CPU-backend barriers + @synchronize + if NT > 512 && tid <= 512; @inbounds partial[tid] += partial[tid+512]; end + @synchronize + if NT > 256 && tid <= 256; @inbounds partial[tid] += partial[tid+256]; end + @synchronize + if NT > 128 && tid <= 128; @inbounds partial[tid] += partial[tid+128]; end + @synchronize + if NT > 64 && tid <= 64; @inbounds partial[tid] += partial[tid+ 64]; end + @synchronize + if NT > 32 && tid <= 32; @inbounds partial[tid] += partial[tid+ 32]; end + @synchronize + if NT > 16 && tid <= 16; @inbounds partial[tid] += partial[tid+ 16]; end + @synchronize + if NT > 8 && tid <= 8; @inbounds partial[tid] += partial[tid+ 8]; end + @synchronize + if NT > 4 && tid <= 4; @inbounds partial[tid] += partial[tid+ 4]; end + @synchronize + if NT > 2 && tid <= 2; @inbounds partial[tid] += partial[tid+ 2]; end + @synchronize + if NT > 1 && tid == 1; @inbounds partial[1] += partial[2]; end + @synchronize + + if tid == 1 + @inbounds out[ob] = Tout(partial[1]) + end +end + +# Per-slab squared Frobenius norm of a packed `[m, n, batch]` array. +@kernel function tile_norm_sq_kernel!(out::AbstractVector{Tout}, + X::AbstractArray{T,3}, + ::Val{W}, + ::Val{NT}, +) where {Tout,T,W,NT} + ob = @index(Group, Linear) + tid = @index(Local, Linear) + partial = @localmem Float64 (NT,) + tm = size(X, 1) + tn = size(X, 2) + lane = (tid - 1) % W + 1 + sg = (tid - 1) ÷ W + 1 + nsub = NT ÷ W + + # slab accumulation + acc = 0.0 + col = sg + while col <= tn + row = lane + while row <= tm + @inbounds acc += abs2_f64(X[row, col, ob]) + row += W + end + col += nsub + end + @inbounds partial[tid] = acc + + # workgroup reduction with literal CPU-backend barriers + @synchronize + if NT > 512 && tid <= 512; @inbounds partial[tid] += partial[tid+512]; end + @synchronize + if NT > 256 && tid <= 256; @inbounds partial[tid] += partial[tid+256]; end + @synchronize + if NT > 128 && tid <= 128; @inbounds partial[tid] += partial[tid+128]; end + @synchronize + if NT > 64 && tid <= 64; @inbounds partial[tid] += partial[tid+ 64]; end + @synchronize + if NT > 32 && tid <= 32; @inbounds partial[tid] += partial[tid+ 32]; end + @synchronize + if NT > 16 && tid <= 16; @inbounds partial[tid] += partial[tid+ 16]; end + @synchronize + if NT > 8 && tid <= 8; @inbounds partial[tid] += partial[tid+ 8]; end + @synchronize + if NT > 4 && tid <= 4; @inbounds partial[tid] += partial[tid+ 4]; end + @synchronize + if NT > 2 && tid <= 2; @inbounds partial[tid] += partial[tid+ 2]; end + @synchronize + if NT > 1 && tid == 1; @inbounds partial[1] += partial[2]; end + @synchronize + + if tid == 1 + @inbounds out[ob] = Tout(partial[1]) + end +end + +""" + batch_frobenius_norms_sq!(out, X) -> out + +Compute one squared Frobenius norm for each slab of `X`, accumulating in +`Float64` in one kernel launch. +""" +function batch_frobenius_norms_sq!(out::AbstractVector, + X::AbstractArray{<:Any,3}) + count = size(X, 3) + length(out) == count || + throw(DimensionMismatch("out must have one entry per batch slab")) + count == 0 && return out + + backend = get_backend(X) + W, _, NT = norm_launch(backend, size(X, 2)) + tile_norm_sq_kernel!(backend, NT)( + out, X, Val{W}(), Val{NT}(); + ndrange=(NT * count,), workgroupsize=NT, + ) + return out +end diff --git a/src/tlr/core/compression/uncompress.jl b/src/tlr/core/compression/uncompress.jl new file mode 100644 index 00000000..7c4a6e53 --- /dev/null +++ b/src/tlr/core/compression/uncompress.jl @@ -0,0 +1,116 @@ +export uncompress! + +@kernel function _copy_diag_kernel!(A::AbstractMatrix{T}, + D::AbstractArray{T,3}, tile_m::Int, tile_n::Int) where {T} + row, col, batch = @index(Global, NTuple) + p0 = (batch - 1) * tile_m + 1 + q0 = (batch - 1) * tile_n + 1 + @inbounds A[p0+row-1, q0+col-1] = D[row, col, batch] +end + +function _copy_diagonal_to_dense!(A::AbstractMatrix{T}, A_tlr::TLRMatrix{<:Any,T}) where {T} + # full diagonal tiles + n_full_diag = size(A_tlr.D, 3) + bm, bn = nominal_tile_size(A_tlr) + _copy_diag_kernel!(get_backend(A_tlr))( + A, A_tlr.D, bm, bn; + ndrange=(bm, bn, n_full_diag), + ) + + # corner diagonal tile + if size(A_tlr.D_corner, 3) != 0 + tile_k = ndiag_tiles(A_tlr) + tm, tn = tile_size(A_tlr, tile_k, tile_k) + copyto!(dense_tile_view(A, A_tlr, tile_k, tile_k), view(A_tlr.D_corner, 1:tm, 1:tn, 1)) + end + return A +end + +""" + uncompress!(A, A_tlr) + +Write `A_tlr` into `A`. Rank-zero diagonal slots are reconstructed from dense +diagonal storage after the compressed off-diagonal tiles. + +`A` must have the same size and element type as `A_tlr`; every entry is +overwritten, and `A` is returned. A size mismatch throws a `DimensionMismatch`. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> B = zeros(n, n); uncompress!(B, C); + +julia> norm(B - A) / norm(A) < 1e-8 +true +``` +""" +function uncompress!(A::AbstractMatrix{T}, A_tlr::TLRMatrix{<:Any,T}) where {T} + size(A) == size(A_tlr) || + throw(DimensionMismatch("A dimensions must match A_tlr")) + + uncompress!(A, offdiagonal(A_tlr)) + _copy_diagonal_to_dense!(A, A_tlr) + return A +end + +""" + uncompress!(A, A_tlr::CompressedFTLRMatrix) + +Write an exact-rank CompressedFTLR matrix into dense storage. + +`A` is first zeroed, then each tile with nonzero rank is written as `U * V'`; +`A` is returned. It must have the same size and element type as `A_tlr`. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V'; + +julia> F = CompressedFTLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> B = ones(n, n); uncompress!(B, F); # every entry of B is overwritten + +julia> norm(B - A) / norm(A) < 1e-8 +true +``` +""" +function uncompress!(A::AbstractMatrix{T}, A_tlr::CompressedFTLRMatrix{<:Any,T}) where {T} + size(A) == size(A_tlr) || throw(DimensionMismatch("A dimensions must match A_tlr")) + + fill!(A, zero(T)) + qm, qn = grid_size(A_tlr) + mode = default_gemm_compute_mode(T) + + # grouped exact-rank reconstruction + # Exact ranks are heterogeneous, so supported backends use one grouped call. + if supports_grouped_gemm(get_backend(A_tlr)) + T === BFloat16 && !supports_bfloat16_grouped_gemm(get_backend(A_tlr)) && + throw(ArgumentError("CompressedFTLR BF16 grouped GEMMEx requires an NVIDIA SM80 or newer device")) + tasks = GroupedGemmTask[] + sizehint!(tasks, qm * qn) + @inbounds for j in 1:qn, i in 1:qm + compressed_ftlr_rank(A_tlr, i, j) == 0 && continue + U, V = get_factors(A_tlr, i, j) + push!(tasks, GroupedGemmTask( + 'N', adjoint_blas_char(T), one(T), U, V, zero(T), + dense_tile_view(A, A_tlr, i, j))) + end + isempty(tasks) || precision_gemm_grouped!(tasks, mode) + return A + end + + # generic tile reconstruction + @inbounds for j in 1:qn, i in 1:qm + compressed_ftlr_rank(A_tlr, i, j) == 0 && continue + U, V = get_factors(A_tlr, i, j) + precision_gemm!('N', adjoint_blas_char(T), one(T), U, V, zero(T), + dense_tile_view(A, A_tlr, i, j), mode) + end + return A +end diff --git a/src/tlr/core/compression/workspace.jl b/src/tlr/core/compression/workspace.jl new file mode 100644 index 00000000..19139abf --- /dev/null +++ b/src/tlr/core/compression/workspace.jl @@ -0,0 +1,157 @@ +""" + FTLRCompressionWorkspace(A, tile_size; maxrank, diagonal=:compressed, + block=max(min(32, maxrank), 1)) + +Reusable dense-to-FTLR compression storage. + +There is one category per distinct logical tile shape. `diagonal=:compressed` +includes every tile; `diagonal=:dense` excludes diagonal tiles so the same +workspace builds the compressed off-diagonal part of a `TLRMatrix`. + +Pass it as `workspace` to `CompressedFTLRMatrix(A, ...)` (with +`diagonal=:compressed`) or `TLRMatrix(A, ...)` (with `diagonal=:dense`) to compress +several matrices of the same size, element type and backend with the same +`tile_size` and `maxrank` without reallocating the scratch; any mismatch throws an +`ArgumentError`. Each call still returns newly allocated factors, so earlier results +stay valid. `block` is the number of random samples drawn per step. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> using Random; Random.seed!(1); # compression is randomized + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A1 = U * V' + n * I; A2 = 2 * A1; + +julia> ws = FTLRCompressionWorkspace(A1, 128; maxrank=32, diagonal=:dense); + +julia> C1 = TLRMatrix(A1, 128; maxrank=32, tol=1e-8, rel=true, workspace=ws); + +julia> C2 = TLRMatrix(A2, 128; maxrank=32, tol=1e-8, rel=true, workspace=ws); + +julia> B = similar(A2); uncompress!(B, C2); + +julia> maxrank(C1) == maxrank(C2) == 8 && norm(B - A2) / norm(A2) < 1e-8 +true +``` +""" +struct FTLRCompressionWorkspace{CatsT,StreamV,KeyT} + cats::CatsT + streams::StreamV + key::KeyT +end + +function make_category_workspace(tile_shape::NTuple{2,Int}, tile_ids, + U::AbstractArray{T,3}, V; + block::Int=max(min(32, size(U, 2), tile_shape...), 1), + p0s=nothing, q0s=nothing) where {T} + tm, tn = tile_shape + kout = size(U, 2) + ntiles = size(U, 3) + + # shape checks + size(U) == (tm, kout, ntiles) || throw(DimensionMismatch("invalid U batch shape")) + size(V) == (tn, kout, ntiles) || throw(DimensionMismatch("invalid V batch shape")) + length(tile_ids) == ntiles || throw(DimensionMismatch("tile_ids must match batch size")) + + # sketch width and ARA basis scratch + backend = get_backend(U) + S = min(kout, tm, tn) + blk = S == 0 ? 0 : max(min(block, S), 1) + Z = view(V, :, 1:S, :) + Q = zeros(backend, T, tm, S, ntiles) + ara = S == 0 ? nothing : ARAWorkspace(Q; block=blk) + omega = zeros(backend, T, tn, blk, ntiles) + Y = S == 0 ? zeros(backend, T, tm, 0, ntiles) : ara.Yblk + + # tile-origin device buffers, empty when the caller has none + empty_i32 = allocate(backend, Int32, 0) + pdev = p0s === nothing ? empty_i32 : p0s + qdev = q0s === nothing ? empty_i32 : q0s + + return ( + tile_shape, tile_ids, U, V, + ranks=zeros(backend, Int, ntiles), + errors_sq=zeros(backend, Float64, ntiles), + R_keep=min(kout, S), Z, V_tiles=batch_views(Z, S), + p0s=pdev, q0s=qdev, ara, Q_tiles=batch_views(Q, S), omega, + omega_tiles=batch_views(omega, blk), Y_tiles=batch_views(Y, blk), + ) +end + +function _compression_batch_specs(m::Int, n::Int, + tile_size::NTuple{2,Int}, diagonal::Symbol) + diagonal in (:compressed, :dense) || throw(ArgumentError( + "diagonal must be :compressed or :dense")) + + bm, bn = tile_size + qm, qn = cld(m, bm), cld(n, bn) + shapes = NTuple{2,Int}[] + ids_by_shape = Dict{NTuple{2,Int},Vector{NTuple{2,Int}}}() + + # shape-grouped tile ids + @inbounds for j in 1:qn, i in 1:qm + diagonal === :dense && i == j && continue + tm = min(bm, m - (i - 1) * bm) + tn = min(bn, n - (j - 1) * bn) + shape = (tm, tn) + if !haskey(ids_by_shape, shape) + ids_by_shape[shape] = NTuple{2,Int}[] + push!(shapes, shape) + end + push!(ids_by_shape[shape], (i, j)) + end + + return [(shape=shape, tile_ids=ids_by_shape[shape]) for shape in shapes] +end + +function FTLRCompressionWorkspace(A::AbstractMatrix{T}, + tile_size::NTuple{2,Int}; + maxrank::Int, + diagonal::Symbol=:compressed, + block::Int=max(min(32, maxrank), 1)) where {T} + m, n = size(A) + bm, bn = tile_size + m > 0 && n > 0 && bm > 0 && bn > 0 && maxrank >= 0 || throw(ArgumentError( + "matrix and tile dimensions must be positive and maxrank nonnegative")) + + # one category workspace per distinct tile shape + backend = get_backend(A) + specs = _compression_batch_specs(m, n, tile_size, diagonal) + cats = map(specs) do spec + ids = spec.tile_ids + count = length(ids) + tm, tn = spec.shape + p0_host = Int32[(i - 1) * bm + 1 for (i, _) in ids] + q0_host = Int32[(j - 1) * bn + 1 for (_, j) in ids] + p0s = copyto!(allocate(backend, Int32, count), p0_host) + q0s = copyto!(allocate(backend, Int32, count), q0_host) + U = zeros(backend, T, tm, maxrank, count) + V = zeros(backend, T, tn, maxrank, count) + make_category_workspace( + spec.shape, ids, U, V; block, p0s, q0s) + end + + # workspace identity + key = (; device=backend, T, m, n, tile_size, maxrank, diagonal) + return FTLRCompressionWorkspace(cats, create_streams(backend, length(cats)), key) +end + +FTLRCompressionWorkspace(A::AbstractMatrix, b::Int; kwargs...) = + FTLRCompressionWorkspace(A, (b, b); kwargs...) + +function validate_compression_workspace(ws::FTLRCompressionWorkspace, + A::AbstractMatrix, + tile_size::NTuple{2,Int}, + maxrank::Int, + diagonal::Symbol) + key = ws.key + expected = (typeof(get_backend(A)), eltype(A), size(A, 1), size(A, 2), + tile_size, maxrank, diagonal) + actual = (typeof(key.device), key.T, key.m, key.n, key.tile_size, key.maxrank, + key.diagonal) + actual == expected || throw(ArgumentError( + "FTLRCompressionWorkspace does not match source, geometry, maxrank, " * + "or diagonal policy")) + return ws +end diff --git a/src/tlr/core/interface.jl b/src/tlr/core/interface.jl new file mode 100644 index 00000000..1aef187e --- /dev/null +++ b/src/tlr/core/interface.jl @@ -0,0 +1,355 @@ +""" + TileOrderStyle + +Policy type selecting how a logical tile grid is linearized. +""" +abstract type TileOrderStyle end + +""" + TileColMajor() + +Column-major traversal of the logical tile grid. + +Pass it (or the type itself) as `outer_order` or `inner_order` to a +`CompressedFTLRMatrix` constructor to choose the tile order in which the packed `U` +or `V` factors are stored. The defaults are `outer_order=TileRowMajor` and +`inner_order=TileColMajor`; `TLRMatrix` accepts only these defaults. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V'; + +julia> F = CompressedFTLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true, + outer_order=TileColMajor); + +julia> B = similar(A); uncompress!(B, F); + +julia> norm(B - A) / norm(A) < 1e-8 +true +``` +""" +struct TileColMajor <: TileOrderStyle end +""" + TileRowMajor() + +Row-major traversal of the logical tile grid. + +This is the default `outer_order`, and the only one `TLRMatrix` accepts. The +per-tile vectors `ranks(A)` and `residuals(A)` follow the outer order, so +with `TileRowMajor` tile `(i, j)` is entry `(i - 1) * nt + j`, where `nt` is the +number of tile columns. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> using Random; Random.seed!(1); # compression is randomized + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> A[1:128, 129:256] .= 0; # tile (1, 2) becomes rank 0, tile (2, 1) stays rank 8 + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> r = ranks(C); # tile (i, j) is entry (i - 1) * 8 + j + +julia> r[2] == 0 && r[9] == 8 +true +``` +""" +struct TileRowMajor <: TileOrderStyle end + +Base.transpose(::TileColMajor) = TileRowMajor() +Base.transpose(::TileRowMajor) = TileColMajor() + +""" + tile_linear_index(order, mt, nt, i, j) + +Return the linear traversal index associated with logical tile `(i, j)`. +""" +@inline function tile_linear_index(order, mt::Int, nt::Int, i::Int, j::Int) + 1 <= i <= mt || throw(BoundsError((mt, nt), (i, :))) + 1 <= j <= nt || throw(BoundsError((mt, nt), (:, j))) + (order === TileColMajor || order isa TileColMajor) && + return i + (j - 1) * mt + (order === TileRowMajor || order isa TileRowMajor) && + return j + (i - 1) * nt + throw(ArgumentError("unsupported tile order $(typeof(order))")) +end + +""" + inverse_tile_index(order, mt, nt, linear) + +Return the logical tile coordinate corresponding to `linear`. +""" +@inline function inverse_tile_index(order, mt::Int, nt::Int, linear::Int) + 1 <= linear <= mt * nt || throw(BoundsError((mt, nt), linear)) + k = linear - 1 + (order === TileColMajor || order isa TileColMajor) && + return (k % mt + 1, k ÷ mt + 1) + (order === TileRowMajor || order isa TileRowMajor) && + return (k ÷ nt + 1, k % nt + 1) + throw(ArgumentError("unsupported tile order $(typeof(order))")) +end + +""" + AbstractTLRMatrix{T} + +Shared interface for tile low-rank matrix containers. Concrete subtypes decide +how diagonal tiles are represented and how low-rank tile indices are mapped to +storage. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true); + +julia> F = CompressedFTLRMatrix(U * V', 128; maxrank=32, tol=1e-8, rel=true); + +julia> C isa AbstractTLRMatrix{Float64} && F isa AbstractTLRMatrix{Float64} +true +``` +""" +abstract type AbstractTLRMatrix{T} end + +"""Zero-copy container view representing the transpose of a TLR matrix.""" +struct TransposeTLRMatrix{T,A<:AbstractTLRMatrix{T}} <: AbstractTLRMatrix{T} + parent::A +end + +Base.parent(A::TransposeTLRMatrix) = getfield(A, :parent) +Base.transpose(A::AbstractTLRMatrix) = TransposeTLRMatrix(A) +Base.transpose(A::TransposeTLRMatrix) = parent(A) + +Base.eltype(::Type{<:AbstractTLRMatrix{T}}) where {T} = T +Base.eltype(::AbstractTLRMatrix{T}) where {T} = T +Base.size(A::AbstractTLRMatrix) = (A.m, A.n) +Base.size(A::AbstractTLRMatrix, d::Int) = size(A)[d] +Base.size(A::TransposeTLRMatrix) = reverse(size(parent(A))) + +""" + nominal_tile_size(A) -> (bm, bn) + nominal_tile_size(A, axis) -> Int + +Return the full tile size `(bm, bn)` that `A` was built with, or one entry of it +(`axis = 1` for rows, `2` for columns). Tiles in the last tile row or column can be +smaller; see [`tail_tile_size`](@ref) and [`tile_size`](@ref). + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V' + n * I, (128, 256); maxrank=32, tol=1e-8, rel=true); + +julia> nominal_tile_size(C) == (128, 256) && nominal_tile_size(C, 2) == 256 +true +``` +""" +@inline nominal_tile_size(A::AbstractTLRMatrix) = A.nominal_tile_size +@inline nominal_tile_size(A::TransposeTLRMatrix) = reverse(nominal_tile_size(parent(A))) +@inline nominal_tile_size(A::AbstractTLRMatrix, axis::Int) = + nominal_tile_size(A)[axis] + +""" + tail_tile_size(A) -> (tail_m, tail_n) + tail_tile_size(A, axis) -> Int + +Return the size of the partial last tile row and column, `(m % bm, n % bn)` for an +`m × n` matrix with nominal tile size `(bm, bn)`, or one entry of it. A zero entry +means the tiles divide that dimension evenly and the last tile is full size. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1000; U, V = randn(n, 8), randn(n, 8); # 1000 = 7 * 128 + 104 + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true); + +julia> tail_tile_size(C) == (104, 104) && tail_tile_size(C, 1) == 104 +true +``` +""" +@inline tail_tile_size(A::AbstractTLRMatrix) = A.tail_tile_size +@inline tail_tile_size(A::TransposeTLRMatrix) = reverse(tail_tile_size(parent(A))) +@inline tail_tile_size(A::AbstractTLRMatrix, axis::Int) = + tail_tile_size(A)[axis] + +""" + grid_size(A) -> (n_tile_rows, n_tile_cols) + +Full tile grid including partial boundary tiles: `(n_tile_rows, n_tile_cols)`. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V' + n * I, (128, 256); maxrank=32, tol=1e-8, rel=true); + +julia> grid_size(C) == (8, 4) +true +``` +""" +@inline grid_size(A::AbstractTLRMatrix) = + (cld(size(A, 1), nominal_tile_size(A, 1)), + cld(size(A, 2), nominal_tile_size(A, 2))) + +""" + regular_grid_size(A) -> (q_m, q_n) + +Sub-grid of full-size tiles, `(⌊m/bm⌋, ⌊n/bn⌋)`. It excludes any partial +boundary row or column and equals `grid_size` when the matrix tiles evenly. +""" +@inline regular_grid_size(A::AbstractTLRMatrix) = + (fld(size(A, 1), nominal_tile_size(A, 1)), + fld(size(A, 2), nominal_tile_size(A, 2))) + +""" + tile_size(A, i, j) -> (rows, cols) + +Return the size of tile `(i, j)` of `A`: the nominal tile size, except that tiles +in the last tile row or column take the partial size from `tail_tile_size(A)` when +it is nonzero. The tile indices are not bounds-checked. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1000; U, V = randn(n, 8), randn(n, 8); # 1000 = 7 * 128 + 104 + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true); + +julia> tile_size(C, 1, 8) == (128, 104) && tile_size(C, 8, 8) == (104, 104) +true +``` +""" +@inline function tile_size(A, tile_i::Int, tile_j::Int) + mt, nt = grid_size(A) + bm, bn = nominal_tile_size(A) + tail_m, tail_n = tail_tile_size(A) + row_size = tile_i == mt && !iszero(tail_m) ? tail_m : bm + col_size = tile_j == nt && !iszero(tail_n) ? tail_n : bn + return row_size, col_size +end + +""" + maxrank(A) -> Int + +Return the largest logical rank of any tile stored in `A`. For a matrix built by +compression this is the rank actually reached, which can be smaller than the +`maxrank` cap passed to the constructor. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> using Random; Random.seed!(1); # compression is randomized + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true); + +julia> maxrank(C) == 8 # the cap was 32; the largest tile rank found is 8 +true +``` +""" +@inline maxrank(A::AbstractTLRMatrix) = A.maxrank +@inline maxrank(A::TransposeTLRMatrix) = maxrank(parent(A)) +""" + ranks(A) -> Vector{Int} + +Return the logical rank of every tile of the full tile grid, one entry per tile, +ordered by the outer factor's tile order (row-major for a `TLRMatrix`, see +[`TileRowMajor`](@ref)). Diagonal tiles of a `TLRMatrix` are stored densely and +have rank 0. The vector is the matrix's own storage, not a copy. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> using Random; Random.seed!(1); # compression is randomized + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true); + +julia> r = ranks(C); length(r) == 64 && count(iszero, r) == 8 && count(==(8), r) == 56 +true +``` +""" +@inline ranks(A::AbstractTLRMatrix) = A.ranks +@inline ranks(A::TransposeTLRMatrix) = ranks(parent(A)) +""" + residuals(A) -> Vector{Float64} + +Return the estimated compression error of every tile, in the Frobenius norm and +in absolute terms, in the same tile order as [`ranks`](@ref). Entries are zero for +tiles that were not compressed: diagonal tiles of a `TLRMatrix` and every tile of +a matrix allocated from known ranks. The vector is the matrix's own storage. +For the result of `NextLA.gemm`, a tile that stopped at `maxrank` also includes an +estimate of what the rank cap left out. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> length(residuals(C)) == 64 && maximum(residuals(C)) < 1e-8 * norm(A) +true +``` +""" +@inline residuals(A::AbstractTLRMatrix) = A.resid +@inline residuals(A::TransposeTLRMatrix) = residuals(parent(A)) +@inline KernelAbstractions.get_backend(A::AbstractTLRMatrix) = A.backend +@inline KernelAbstractions.get_backend(A::TransposeTLRMatrix) = get_backend(parent(A)) +@inline tile_order(A::AbstractTLRMatrix) = A.order +@inline tile_order(A::TransposeTLRMatrix) = transpose(tile_order(parent(A))) + +""" + tile_origin_coords(A, i, j) -> (row, col) + +Return the matrix row and column of the first (top-left) entry of tile `(i, j)`, +`((i - 1) * bm + 1, (j - 1) * bn + 1)` for nominal tile size `(bm, bn)`. The tile +indices are not bounds-checked. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V' + n * I, 128; maxrank=32, tol=1e-8, rel=true); + +julia> tile_origin_coords(C, 2, 3) == (129, 257) +true +``` +""" +@inline function tile_origin_coords(A, tile_i::Int, tile_j::Int) + return ((tile_i - 1) * nominal_tile_size(A, 1) + 1, + (tile_j - 1) * nominal_tile_size(A, 2) + 1) +end + +@inline function dense_tile_view(dense::AbstractMatrix, A, tile_i::Int, tile_j::Int) + p0, q0 = tile_origin_coords(A, tile_i, tile_j) + tm, tn = tile_size(A, tile_i, tile_j) + return view(dense, p0:(p0+tm-1), q0:(q0+tn-1)) +end + +"""Logical row/column range of one TLR tile along `axis`.""" +@inline function tile_axis_range(A::AbstractTLRMatrix, tile::Int, axis::Int) + first = (tile - 1) * nominal_tile_size(A, axis) + 1 + extent = tile_size(A, axis == 1 ? tile : 1, axis == 2 ? tile : 1)[axis] + return first:(first + extent - 1) +end diff --git a/src/tlr/core/tlr.jl b/src/tlr/core/tlr.jl new file mode 100644 index 00000000..71036c5d --- /dev/null +++ b/src/tlr/core/tlr.jl @@ -0,0 +1,76 @@ +""" + TileLowRank + +Tile low-rank (TLR) matrices. A `TLRMatrix` splits a matrix into tiles, keeps the +diagonal tiles dense and stores each off-diagonal tile as low-rank factors `U*V'`; +a `CompressedFTLRMatrix` stores every tile that way. Both are built by compressing a +dense matrix, expanded back with `uncompress!`, and multiplied with TLR methods of +`gemm!`. Opt in with `using NextLA.TileLowRank`; this module is not re-exported by `NextLA`. +""" +module TileLowRank + +using LinearAlgebra +using Random +using KernelAbstractions +using KernelAbstractions: zeros, allocate +using KernelAbstractions.Extras: @unroll + +import ..NextLA: gemm, gemm! +using ..NextLA: gemm_batched!, trsm_batched!, potrf_batched! +using ..NextLA: precision_gemm!, precision_gemm_batched!, precision_gemm_grouped!, GroupedGemmTask +using ..NextLA: gemm_compute_mode, gemm_compute_type, supports_grouped_gemm, supports_bfloat16_grouped_gemm +using ..NextLA: GEMMCompute, validate_gemm_signature +using ..NextLA: gemm_alignment_quantum, aligned_leading_dimension, is_gemm_aligned +using ..NextLA: AbstractPreparedGroupedGemm, prepare_precision_gemm_grouped +using ..NextLA: precision_gemm_grouped_prepared!, destroy_prepared_grouped_gemm! +using ..NextLA: with_grouped_host_pointer_mode, with_grouped_device_pointer_mode +using ..NextLA: PreparedGroupedGemmBundle +using ..NextLA: create_streams, with_stream, sync_stream, sync_streams_with_default +using ..NextLA: create_event, record_event!, wait_event!, sync_event +using ..NextLA: SUBGROUP_SIZE, unwrap, BFloat16 +using ..NextLA: BatchPtrDescriptor, swap_batch_ptrs!, set_batch_ptrs! +using ..NextLA: precision_gemm_batched_ptrs! +using ..NextLA: supports_pointer_batched + +export TileColMajor, TileRowMajor +export AbstractTLRMatrix, TLRMatrix, CompressedFTLRMatrix +export offdiagonal +export uncompress! +export get_factors +export FTLRCompressionWorkspace +export maxrank, ranks, rank_multiple, maximum_storage_rank +export residuals, dense_diag, dense_diag_corner, grid_size +export nominal_tile_size, tail_tile_size +export ndiag_tiles, tile_origin_coords, tile_size +export gemm_minimum_workspace_bytes, gemm_maximum_workspace_bytes, gemm_workspace_bytes +export DenseGemmWorkspace +export CompressedGemmAnalysis, CompressedMixedGemmAnalysis, analyze_compressed_gemm + +include("interface.jl") +include("compressed_ftlr_matrix.jl") +include("tlr_matrix.jl") + +include("compression/blas_utils.jl") +include("compression/norms.jl") +include("compression/ara.jl") +include("compression/workspace.jl") +include("compression/compress.jl") +include("compression/uncompress.jl") + +include("../blas/gemm/compute_policy.jl") +include("../blas/gemm/arena.jl") + +include("../blas/gemm/dense_accumulation/workspace.jl") +include("../blas/gemm/dense_accumulation/runs.jl") +include("../blas/gemm/dense_accumulation/schedule.jl") +include("../blas/gemm/dense_accumulation/three_stage.jl") +include("../blas/gemm/dense_accumulation/two_stage.jl") +include("../blas/gemm/dense_accumulation/dense_diagonal.jl") +include("../blas/gemm/dense_accumulation/driver.jl") + +include("../blas/gemm/compressed_accumulation/workspace.jl") +include("../blas/gemm/compressed_accumulation/run_coupling.jl") +include("../blas/gemm/compressed_accumulation/rolling_schedule.jl") +include("../blas/gemm/compressed_accumulation/driver.jl") + +end diff --git a/src/tlr/core/tlr_matrix.jl b/src/tlr/core/tlr_matrix.jl new file mode 100644 index 00000000..d9922159 --- /dev/null +++ b/src/tlr/core/tlr_matrix.jl @@ -0,0 +1,278 @@ +""" + TLRMatrix + +Dense-diagonal tile-low-rank matrix. `offdiag` is a finalized full-grid +[`CompressedFTLRMatrix`](@ref); its diagonal ranks are zero. Dense diagonal +tiles are stored separately in `D`, with an optional ragged final tile in +`D_corner`. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> B = similar(A); uncompress!(B, C); + +julia> offdiagonal(C) isa CompressedFTLRMatrix && norm(B - A) / norm(A) < 1e-8 +true +``` +""" +struct TLRMatrix{BackendT<:Backend,T,Arr3T<:AbstractArray{T,3}, + OffdiagT<:CompressedFTLRMatrix{BackendT,T}} <: AbstractTLRMatrix{T} + offdiag::OffdiagT + D::Arr3T + D_corner::Arr3T +end + +""" + offdiagonal(A::TLRMatrix) -> CompressedFTLRMatrix + +Return the `CompressedFTLRMatrix` that holds the off-diagonal tiles of `A`. It +covers the full tile grid, with rank 0 on the diagonal tiles, and is `A`'s own +storage, not a copy. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> B = similar(A); uncompress!(B, offdiagonal(C)); + +julia> iszero(B[1:128, 1:128]) && norm(B[1:128, 129:n] - A[1:128, 129:n]) < 1e-8 * norm(A) +true +``` +""" +@inline offdiagonal(A::TLRMatrix) = A.offdiag +@inline offdiagonal(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}) = + transpose(offdiagonal(parent(A))) +Base.size(A::TLRMatrix) = size(A.offdiag) +@inline nominal_tile_size(A::TLRMatrix) = nominal_tile_size(A.offdiag) +@inline tail_tile_size(A::TLRMatrix) = tail_tile_size(A.offdiag) +@inline KernelAbstractions.get_backend(A::TLRMatrix) = get_backend(A.offdiag) +@inline tile_order(A::TLRMatrix) = tile_order(A.offdiag) +@inline ranks(A::TLRMatrix) = ranks(A.offdiag) +@inline residuals(A::TLRMatrix) = residuals(A.offdiag) +@inline maxrank(A::TLRMatrix) = maxrank(A.offdiag) +@inline rank_multiple(A::TLRMatrix) = rank_multiple(A.offdiag) +@inline maximum_storage_rank(A::TLRMatrix) = maximum_storage_rank(A.offdiag) + +""" + ndiag_tiles(A::TLRMatrix) -> Int + +Return the number of diagonal tiles of `A`, `minimum(grid_size(A))`. These are +the tiles stored densely, including a ragged last one. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> m, n = 1024, 512; U, V = randn(m, 8), randn(n, 8); + +julia> C = TLRMatrix(U * V', 128; maxrank=32, tol=1e-8, rel=true); + +julia> grid_size(C) == (8, 4) && ndiag_tiles(C) == 4 +true +``` +""" +@inline ndiag_tiles(A::TLRMatrix) = min(grid_size(A)...) +@inline ndiag_tiles(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}) = + ndiag_tiles(parent(A)) +""" + dense_diag(A::TLRMatrix) -> AbstractArray{T,3} + +Return the dense diagonal tiles of `A` as a `bm × bn × k` array, where `(bm, bn)` +is the nominal tile size; slice `[:, :, t]` is diagonal tile `(t, t)`. Only +full-size diagonal tiles are included; a smaller last diagonal tile is in +[`dense_diag_corner`](@ref). The array is `A`'s own storage, not a copy. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> D = dense_diag(C); size(D) == (128, 128, 8) && D[:, :, 2] == A[129:256, 129:256] +true +``` +""" +@inline dense_diag(A::TLRMatrix) = A.D +""" + dense_diag_corner(A::TLRMatrix) -> AbstractArray{T,3} + +Return the last diagonal tile of `A` when it is smaller than the nominal tile +size, as a `tm × tn × 1` array. When every diagonal tile is full size the array +has third dimension 0. The array is `A`'s own storage, not a copy. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1000; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> size(dense_diag(C), 3) == 7 && dense_diag_corner(C)[:, :, 1] == A[897:1000, 897:1000] +true +``` +""" +@inline dense_diag_corner(A::TLRMatrix) = A.D_corner +@inline dense_diag(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}) = + PermutedDimsArray(dense_diag(parent(A)), (2, 1, 3)) +@inline dense_diag_corner(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}) = + PermutedDimsArray(dense_diag_corner(parent(A)), (2, 1, 3)) + +@inline function diag_tile_view(A::TLRMatrix, tile_k::Int) + 1 <= tile_k <= ndiag_tiles(A) || throw(BoundsError(1:ndiag_tiles(A), tile_k)) + if tile_k <= size(A.D, 3) + return view(A.D, :, :, tile_k) + end + size(A.D_corner, 3) != 0 || throw(BoundsError(1:size(A.D, 3), tile_k)) + return view(A.D_corner, :, :, 1) +end + +@inline diag_tile_view(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}, tile_k::Int) = + transpose(diag_tile_view(parent(A), tile_k)) + +""" + get_factors(A::TLRMatrix, i, j) -> (U, V) + get_factors(A::CompressedFTLRMatrix, i, j) -> (U, V) + +Return an exact-rank factor pair for an off-diagonal tile. + +Tile `(i, j)` is approximated by `U * V'`; `U` has the tile's row count and `V` its +column count, and both have exactly `r` columns, the tile's logical rank (padding +from `rank_multiple` is not included). They are views into `A`'s packed storage. +For a `TLRMatrix`, asking for a diagonal tile throws an `ArgumentError`; use +`dense_diag` instead. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> X, Y = get_factors(C, 1, 2); T12 = A[1:128, 129:256]; + +julia> size(X) == size(Y) == (128, 8) && norm(X * Y' - T12) < 1e-8 * norm(T12) +true +``` +""" +@inline function get_factors(A::TLRMatrix, i::Int, j::Int) + i == j && throw(ArgumentError("tile ($i, $j) is diagonal and stored densely")) + return get_factors(A.offdiag, i, j) +end +@inline get_factors(A::TransposeTLRMatrix{<:Any,<:TLRMatrix}, i::Int, j::Int) = + get_factors(offdiagonal(A), i, j) + +""" + TLRMatrix(offdiag::CompressedFTLRMatrix) + +Wrap finalized full-grid compressed off-diagonal storage and allocate a +separate dense diagonal. Diagonal ranks in `offdiag` must be zero. + +`offdiag` is used as is, not copied, and must have the default factor orders +(`outer_order=TileRowMajor`, `inner_order=TileColMajor`); otherwise an +`ArgumentError` is thrown. The new dense diagonal tiles are zero. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> n = 1024; U, V = randn(n, 8), randn(n, 8); A = U * V' + n * I; + +julia> C = TLRMatrix(A, 128; maxrank=32, tol=1e-8, rel=true); + +julia> C0 = TLRMatrix(offdiagonal(C)); # shares the off-diagonal factors, zero diagonal + +julia> dense_diag(C0) .= dense_diag(C); B = similar(A); uncompress!(B, C0); + +julia> norm(B - A) / norm(A) < 1e-8 +true +``` +""" +function TLRMatrix(offdiag::CompressedFTLRMatrix{BackendT,T}) where {BackendT,T} + # layout and zero-diagonal-rank checks + compressed_ftlr_outer_order(offdiag) isa TileRowMajor || throw(ArgumentError( + "TLRMatrix requires row-major outer-factor packing")) + compressed_ftlr_inner_order(offdiag) isa TileColMajor || throw(ArgumentError( + "TLRMatrix requires column-major inner-factor packing")) + @inbounds for k in 1:min(grid_size(offdiag)...) + compressed_ftlr_rank(offdiag, k, k) == 0 || throw(ArgumentError( + "TLRMatrix off-diagonal storage requires rank zero at ($k, $k)")) + end + + # dense-diagonal sizing, with an optional ragged corner tile + bm, bn = nominal_tile_size(offdiag) + mt, nt = grid_size(offdiag) + n_diag = min(mt, nt) + tail_m, tail_n = tail_tile_size(offdiag) + corner_tm = n_diag == mt && !iszero(tail_m) ? tail_m : bm + corner_tn = n_diag == nt && !iszero(tail_n) ? tail_n : bn + has_corner = n_diag > 0 && (corner_tm != bm || corner_tn != bn) + backend = get_backend(offdiag) + D = zeros(backend, T, bm, bn, n_diag - has_corner) + D_corner = zeros( + backend, T, max(corner_tm, 1), max(corner_tn, 1), has_corner ? 1 : 0) + + return TLRMatrix{BackendT,T,typeof(D),typeof(offdiag)}(offdiag, D, D_corner) +end + +""" + TLRMatrix(backend, T, m, n, tile_size, ranks; rank_multiple=0) + +Allocate a finalized dense-diagonal TLR matrix from known off-diagonal ranks. +The supplied full-grid rank matrix must contain zeros on its diagonal. + +`backend` is a KernelAbstractions backend such as `CPU()`, `T` the element type, +`m × n` the matrix size and `tile_size` a tuple `(bm, bn)` or one integer for square +tiles. `ranks` is a `cld(m, bm) × cld(n, bn)` integer matrix. All factors and +diagonal tiles start as zeros, ready to be filled in place. + +# Examples +```jldoctest +julia> using NextLA.TileLowRank, LinearAlgebra + +julia> backend = NextLA.KernelAbstractions.CPU(); + +julia> r = [i == j ? 0 : 4 for i in 1:8, j in 1:8]; + +julia> Z = TLRMatrix(backend, Float64, 1024, 1024, (128, 128), r); + +julia> X, Y = get_factors(Z, 1, 2); + +julia> size(X) == (128, 4) && iszero(X) && iszero(dense_diag(Z)) && maxrank(Z) == 4 +true +``` +""" +function TLRMatrix( + backend::Backend, ::Type{T}, m::Int, n::Int, + tile_size::NTuple{2,Int}, ranks_in::AbstractMatrix{Int}; + outer_order=TileRowMajor, inner_order=TileColMajor, + rank_multiple::Int=0, +) where {T} + (outer_order === TileRowMajor || outer_order isa TileRowMajor) || throw(ArgumentError( + "TLRMatrix requires outer_order=TileRowMajor")) + (inner_order === TileColMajor || inner_order isa TileColMajor) || throw(ArgumentError( + "TLRMatrix requires inner_order=TileColMajor")) + offdiag = CompressedFTLRMatrix( + backend, T, m, n, tile_size, ranks_in; + outer_order, inner_order, rank_multiple) + return TLRMatrix(offdiag) +end + +function TLRMatrix( + backend::Backend, ::Type{T}, m::Int, n::Int, b::Int, + ranks_in::AbstractMatrix{Int}; kwargs..., +) where {T} + return TLRMatrix(backend, T, m, n, (b, b), ranks_in; kwargs...) +end diff --git a/src/tlr/lapack/.gitkeep b/src/tlr/lapack/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/src/trapezoidal.jl b/src/trapezoidal.jl deleted file mode 100644 index d1e84cd9..00000000 --- a/src/trapezoidal.jl +++ /dev/null @@ -1,46 +0,0 @@ -export LowerTrapezoidal, UnitLowerTrapezoidal, UpperTrapezoidal, UnitUpperTrapezoidal, trau!, trau, tral!, tral -import LinearAlgebra: triu!, tril!, triu, tril -abstract type AbstractTrapezoidal{T} <: AbstractMatrix{T} end - -# First loop through all methods that don't need special care for upper/lower and unit diagonal -for t in (:LowerTrapezoidal, :UnitLowerTrapezoidal, :UpperTrapezoidal, :UnitUpperTrapezoidal) - @eval begin - struct $t{T,S<:AbstractMatrix{T}} <: AbstractTrapezoidal{T} - data::S - - function $t{T,S}(data) where {T,S<:AbstractMatrix{T}} - Base.require_one_based_indexing(data) - new{T,S}(data) - end - end - $t(A::$t) = A - $t{T}(A::$t{T}) where {T} = A - $t(A::AbstractMatrix) = $t{eltype(A), typeof(A)}(A) - $t{T}(A::AbstractMatrix) where {T} = $t(convert(AbstractMatrix{T}, A)) - $t{T}(A::$t) where {T} = $t(convert(AbstractMatrix{T}, A.data)) - - AbstractMatrix{T}(A::$t) where {T} = $t{T}(A) - AbstractMatrix{T}(A::$t{T}) where {T} = copy(A) - - Base.size(A::$t) = size(A.data) - Base.axes(A::$t) = axes(A.data) - - Base.similar(A::$t, ::Type{T}) where {T} = $t(similar(parent(A), T)) - Base.similar(A::$t, ::Type{T}, dims::Dims{N}) where {T,N} = similar(parent(A), T, dims) - Base.parent(A::$t) = A.data - - Base.copy(A::$t) = $t(copy(A.data)) - - Base.real(A::$t{<:Real}) = A - Base.real(A::$t{<:Complex}) = (B = real(A.data); $t(B)) - end -end - -Base.getindex(A::UnitLowerTrapezoidal{T}, i::Integer, j::Integer) where {T} = - i > j ? ifelse(A.data[i,j] == nothing, zero(eltype(A.data)), A.data[i,j]) : ifelse(i == j, oneunit(T), zero(T)) -Base.getindex(A::LowerTrapezoidal, i::Integer, j::Integer) = -i >= j ? ifelse(A.data[i,j] == nothing, zero(eltype(A.data)), A.data[i,j]) : zero(eltype(A.data)) -Base.getindex(A::UnitUpperTrapezoidal{T}, i::Integer, j::Integer) where {T} = - i < j ? ifelse(A.data[i,j] == nothing, zero(eltype(A.data)), A.data[i,j]) : ifelse(i == j, oneunit(T), zero(T)) -Base.getindex(A::UpperTrapezoidal, i::Integer, j::Integer) = -i <= j ? ifelse(A.data[i,j] == nothing, zero(eltype(A.data)), A.data[i,j]) : zero(eltype(A.data)) \ No newline at end of file diff --git a/src/trsm/batched.jl b/src/trsm/batched.jl deleted file mode 100644 index 604e8672..00000000 --- a/src/trsm/batched.jl +++ /dev/null @@ -1,21 +0,0 @@ -# Batched triangular solve. -# -# Source: alecarraro-dev @ 0f1ac84 (PR #20), by Alessandro . -# trsm_batched.jl is verbatim; this entry file is not. -# -# This folder is named for the operation rather than for batching, the same way -# gemm_batched sits inside src/gemm/. The entry file is batched.jl rather than -# trsm.jl so it is never confused with the flat src/trsm/trsm.jl, which keeps the -# KernelAbstractions kernels, the four Left/RightLower/UpperTRSM! drivers and -# the trsm front end. Nothing here replaces those; src/trsm/rectrxm.jl likewise -# keeps unified_rectrxm!. -# -# Layout contract: this is the only file here that includes. Exports stay in -# the file that defines the symbol, so moving a unit to another feature is a -# git mv plus one include line — the export travels with it. -# -# The vendor implementations live in ext/*/trsm.jl as package extensions, -# loaded only when the corresponding GPU package is. trsm_batched.jl carries a -# CPU fallback, so this works with no GPU package present. - -include("trsm_batched.jl") diff --git a/test/Project.toml b/test/Project.toml index cb39ada8..65c4afd7 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,10 +1,12 @@ [deps] -AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" -CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" +ParallelTestRunner = "d3525ed8-44d0-4b2c-a655-542cee43accc" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" libblastrampoline_jll = "8e850b90-86db-534c-a0d3-1478176c7d93" -oneAPI = "8f75cd03-7ff8-4ecb-9b8f-daf728133b1b" + +[compat] +KernelAbstractions = "0.9.34" +ParallelTestRunner = "2.10" diff --git a/test/README.md b/test/README.md new file mode 100644 index 00000000..49dbbb1d --- /dev/null +++ b/test/README.md @@ -0,0 +1,167 @@ +# NextLA tests + +`test/runtests.jl` runs the tests with +[ParallelTestRunner.jl](https://github.com/JuliaTesting/ParallelTestRunner.jl): +each test runs in its own Julia process, several at once, and a test that +fails does not stop the others. A summary with the time and memory of each +test is printed at the end. + +## Running + +Run the tests from the NextLA folder with Julia 1.10 or newer. Everything +after `--` goes to the test runner. A shortcut keeps the commands short +(bash or zsh; ParallelTestRunner's docs suggest a similar one): + +```bash +alias nlatest='julia --project -e "using Pkg; Pkg.test(test_args=ARGS)" --' +``` + +The first run takes longer: Pkg sets up and precompiles the test environment. + +### Choosing tests + +Every test is named by its path without `.jl`, e.g. `dense/lapack/qr/geqrt`. +A name selects every test that starts with it; `!` leaves tests out. + +```bash +nlatest # everything: dense, mxp, tlr +nlatest --list # the test names; × marks those that failed last time +nlatest mxp # one part: dense, mxp or tlr +nlatest dense/lapack/qr # one folder +nlatest mxp/blas/trsm/rectrxm_mixed # one file +nlatest dense/lapack/qr/geqrt mxp/core # several +nlatest '!tlr' # everything except tlr +``` + +`--list` remembers the last run for each Julia version and each `--backends` +choice, so after a failure you can rerun just the tests it marks. + +### GPU backends + +Each test runs on the CPU and on each GPU backend that is installed in the +test environment and working (CUDA, AMDGPU, oneAPI, Metal), except where a +routine exists only for some backends: then its test runs only there, e.g. +`dense/blas/trsm/unified_rectrxm` on GPUs only. No GPU package is +a test dependency, so a plain run installs none and runs on the CPU. To test +on a GPU, add its package to the test environment once (this edits +`test/Project.toml`; do not commit that change): + +```bash +julia --project=test -e 'using Pkg; Pkg.add("CUDA")' # or AMDGPU, oneAPI, Metal +``` + +To run on the GPU, define `nlatest` with `--backends`; it then applies to every +test (the list is comma-separated: `CPU`, `CUDA`, `AMDGPU`, `oneAPI`, `Metal`): + +```bash +alias nlatest='julia --project -e "using Pkg; Pkg.test(test_args=ARGS)" -- --backends=CUDA' +nlatest # every test, CUDA only +nlatest mxp # the mixed-precision tests, CUDA only +``` + +Use `--backends=CPU,CUDA` for both, or `--backends=CPU` for the CPU alone (no +GPU package is loaded). `--backends` can be given only once, so to change it, +define `nlatest` again; without `--backends`, as at the top, every usable +backend runs. + +### Speed and output + +```bash +nlatest --jobs=4 # 4 tests at once +nlatest --jobs=1 # one test at a time +JULIA_NUM_THREADS=4 nlatest --jobs=4 mxp # 4 tests at once, 4 threads each +nlatest --quickfail # stop at the first failure +nlatest --verbose # more output (start and set-up times) +``` + +### Another Julia version + +With [juliaup](https://github.com/JuliaLang/juliaup), define `nlatest` with the +version (`+1.10`, `+release`, `+nightly`, ...) and, if needed, `--backends`: + +```bash +alias nlatest='julia +1.10 --project -e "using Pkg; Pkg.test(test_args=ARGS)" -- --backends=CUDA' +nlatest mxp # the mixed-precision tests on Julia 1.10, CUDA only +``` + +### From the Julia REPL + +Start Julia with `julia --project` in the NextLA folder (with juliaup, +`julia +1.10 --project` for another version). `Pkg.test` takes the same +arguments as `nlatest`, written between backticks; this is also the way on +Windows: + +```julia +using Pkg +Pkg.test("NextLA") # everything +Pkg.test("NextLA"; test_args=`--list`) # the test names +Pkg.test("NextLA"; test_args=`mxp`) # one part +Pkg.test("NextLA"; test_args=`dense/lapack/qr/geqrt mxp/core`) # several +Pkg.test("NextLA"; test_args=`'!tlr'`) # everything except tlr +Pkg.test("NextLA"; test_args=`--backends=CUDA mxp`) # mxp on CUDA only +Pkg.test("NextLA"; test_args=`--jobs=4 mxp`) # 4 tests at once +``` + +### Results + +Each test file runs in its own Julia process, so a failing file does not stop +the others. The summary lists every file with its time and memory, and the +command ends with an error if any test fails. + +## Test files + +### Dense (`test/dense`) + +One test per file, at the same path as the source it tests in `src/dense`, +e.g. `dense/lapack/qr/geqrt` or `dense/blas/gemm/recgemm`; `--list` shows them +all. Three test a source of another name: `dense/blas/trsm/unified_rectrxm` +(`rectrxm.jl`), `dense/lapack/cholesky/cholesky_blocked` (`potrf_blocked.jl`) +and `dense/lapack/lu/lu_factor` (`lu_base.jl`, `lu_tiled.jl`). Their shared +helpers (LAPACK reference wrappers, backends, the LU test matrices) are loaded +by `test/setup/dense.jl`. + +### Mixed precision (`test/mxp`) + +One test per source file, at the same path as the source in `src/mxp`: + +| Test name | Tests | +|---|---| +| `mxp/core/fullmixedprec` | `FullMixedPrec` | +| `mxp/core/symmmixedprec` | `SymmMixedPrec` | +| `mxp/core/trimixedprec` | `TriMixedPrec` | +| `mxp/core/tiledtrimixedprec` | `TiledTriMixedPrec` | +| `mxp/core/transposedmixedprec` | the lazy `transpose`/`adjoint` of a container | +| `mxp/core/blocks` | the argument checks all constructors share, and the block helpers | +| `mxp/core/adaptive` | `adaptive_precisions` | +| `mxp/core/quantize` | `quantize`, `dequantize` | +| `mxp/blas/gemm/recgemm_mixedprec` | `recgemm!` | +| `mxp/blas/trsm/rectrxm_mixed` | `unified_rectrxm!` with mixed-precision containers | +| `mxp/blas/syrk/recsyrk_mixedprec` | `recsyrk!` | +| `mxp/lapack/lu/reclu_mixedprec` | `lu_recursive!` | +| `mxp/lapack/cholesky/recpotrf_mixedprec` | `potrf_recursive!` | + +`mxp/core` runs all the container tests, `mxp/blas` the BLAS routines, and so on. + +The helpers shared by these tests (error bounds, test matrices, reference +results) are in `test/setup/mxp.jl`; the comment at its top explains the +error bounds. + +### Tile low-rank (`test/tlr`) + +One test per source file or folder, at the same path as the source in `src/tlr`: + +| Test name | Tests | +|---|---| +| `tlr/core/tlr_matrix` | `TLRMatrix` and the `TileLowRank` exports | +| `tlr/core/compressed_ftlr_matrix` | `CompressedFTLRMatrix`: layout, packing, `rank_multiple` | +| `tlr/core/compression/norms` | the batched tile norms and the orthogonalization type | +| `tlr/core/compression/ara` | adaptive randomized approximation: convergence, basis, truncation | +| `tlr/core/compression/compress` | dense to `TLRMatrix` / `CompressedFTLRMatrix`, the compression workspace | +| `tlr/blas/gemm/dense_accumulation` | `gemm!` into a dense `C` with TLR operands | +| `tlr/blas/gemm/compressed_accumulation` | `gemm` of two `CompressedFTLRMatrix` into a compressed result | + +The tests opt in with `using NextLA.TileLowRank`, as users do. Their helpers +(tile fixtures, reconstruction, the GEMM drivers) are in `test/setup/tlr.jl`. +The GPU tests run on the backends the TLR code is written for: CUDA for the +batched SVD, grouped GEMM and TF32 paths, and AMDGPU where the source has its +own path. diff --git a/test/backend_test_helpers.jl b/test/backend_test_helpers.jl index 60edaaac..1643a5f7 100644 --- a/test/backend_test_helpers.jl +++ b/test/backend_test_helpers.jl @@ -28,7 +28,7 @@ _method_file(f, args...) = replace(String(first(Base.functionloc(which(f, Tuple{typeof.(args)...})))), "\\" => "/") function _expected_gemm_batched_file(name::String) - name == "CPU" && return "src/gemm/gemm_batched.jl" + name == "CPU" && return "src/dense/blas/gemm/gemm_batched.jl" name == "CUDA" && return "ext/cuda/gemm.jl" name == "AMDGPU" && return "ext/amdgpu/gemm.jl" name == "oneAPI" && return "ext/oneapi/gemm.jl" @@ -37,7 +37,7 @@ function _expected_gemm_batched_file(name::String) end function _expected_potrf_batched_file(name::String) - name == "CPU" && return "src/cholesky/potrf_batched.jl" + name == "CPU" && return "src/dense/lapack/cholesky/potrf_batched.jl" name == "CUDA" && return "ext/cuda/potrf.jl" name == "AMDGPU" && return "ext/amdgpu/potrf.jl" name == "oneAPI" && return "ext/oneapi/potrf.jl" @@ -46,18 +46,18 @@ function _expected_potrf_batched_file(name::String) end function _expected_potrf_file(name::String) - name == "CPU" && return "src/cholesky/potrf.jl" + name == "CPU" && return "src/dense/lapack/cholesky/potrf.jl" name == "CUDA" && return "ext/cuda/potrf.jl" name == "AMDGPU" && return "ext/amdgpu/potrf.jl" name == "Metal" && return "ext/metal/potrf.jl" # oneAPI has no single-matrix potrf! wrapper; the generic method's backend # guard is what it hits. See KNOWN_ISSUES.md. - name == "oneAPI" && return "src/cholesky/potrf.jl" + name == "oneAPI" && return "src/dense/lapack/cholesky/potrf.jl" error("Unknown backend `$name`") end function _expected_syrk_file(name::String) - name == "CPU" && return "src/syrk/syrk_dispatch.jl" + name == "CPU" && return "src/dense/blas/syrk/syrk_dispatch.jl" name == "CUDA" && return "ext/cuda/syrk.jl" name == "AMDGPU" && return "ext/amdgpu/syrk.jl" name == "oneAPI" && return "ext/oneapi/syrk.jl" @@ -66,7 +66,7 @@ function _expected_syrk_file(name::String) end function _expected_trsm_batched_file(name::String) - name == "CPU" && return "src/trsm/trsm_batched.jl" + name == "CPU" && return "src/dense/blas/trsm/trsm_batched.jl" name == "CUDA" && return "ext/cuda/trsm.jl" name == "AMDGPU" && return "ext/amdgpu/trsm.jl" name == "oneAPI" && return "ext/oneapi/trsm.jl" diff --git a/test/axpy.jl b/test/dense/blas/axpy.jl similarity index 100% rename from test/axpy.jl rename to test/dense/blas/axpy.jl diff --git a/test/gemm/gemmEx.jl b/test/dense/blas/gemm/gemmEx.jl similarity index 100% rename from test/gemm/gemmEx.jl rename to test/dense/blas/gemm/gemmEx.jl diff --git a/test/gemm/gemm_batched.jl b/test/dense/blas/gemm/gemm_batched.jl similarity index 99% rename from test/gemm/gemm_batched.jl rename to test/dense/blas/gemm/gemm_batched.jl index ac9e033d..f51e65ae 100644 --- a/test/gemm/gemm_batched.jl +++ b/test/dense/blas/gemm/gemm_batched.jl @@ -478,7 +478,7 @@ end Cd = [AT(zeros(Float32, n, n)) for _ in 1:nb] # the vector-of-matrices form must be served by the backend's own - # method, not by the generic loop in src/gemm/gemm_batched.jl + # method, not by the generic loop in src/dense/blas/gemm/gemm_batched.jl # occursin, not ==: _method_file returns an absolute path and the # expected value is the repo-relative suffix, which is the idiom the # rest of this file already uses. diff --git a/test/gemm/gemm_grouped.jl b/test/dense/blas/gemm/gemm_grouped.jl similarity index 100% rename from test/gemm/gemm_grouped.jl rename to test/dense/blas/gemm/gemm_grouped.jl diff --git a/test/gemm/matmul.jl b/test/dense/blas/gemm/matmul.jl similarity index 98% rename from test/gemm/matmul.jl rename to test/dense/blas/gemm/matmul.jl index c5ef6e70..74abf560 100644 --- a/test/gemm/matmul.jl +++ b/test/dense/blas/gemm/matmul.jl @@ -46,7 +46,7 @@ for (backend_name, ArrayType, synchronize) in available_backends() end # The wrappers also expose the kernel's alpha and transpose flags, accumulate a -# Float16 product in Float32, and check shapes. src/trsm/rectrxm.jl's mixed-precision +# Float16 product in Float32, and check shapes. src/dense/blas/trsm/rectrxm.jl's mixed-precision # recursion needs all three. for (backend_name, ArrayType, synchronize) in available_backends() @testset "MATMUL scaled/transposed [$backend_name]" begin diff --git a/test/gemm/recgemm.jl b/test/dense/blas/gemm/recgemm.jl similarity index 100% rename from test/gemm/recgemm.jl rename to test/dense/blas/gemm/recgemm.jl diff --git a/test/gerc.jl b/test/dense/blas/gerc.jl similarity index 100% rename from test/gerc.jl rename to test/dense/blas/gerc.jl diff --git a/test/syrk/recsyrk.jl b/test/dense/blas/syrk/recsyrk.jl similarity index 100% rename from test/syrk/recsyrk.jl rename to test/dense/blas/syrk/recsyrk.jl diff --git a/test/syrk/syrk.jl b/test/dense/blas/syrk/syrk.jl similarity index 100% rename from test/syrk/syrk.jl rename to test/dense/blas/syrk/syrk.jl diff --git a/test/syrk/syrk_kernel.jl b/test/dense/blas/syrk/syrk_kernel.jl similarity index 100% rename from test/syrk/syrk_kernel.jl rename to test/dense/blas/syrk/syrk_kernel.jl diff --git a/test/trsm.jl b/test/dense/blas/trsm/trsm.jl similarity index 100% rename from test/trsm.jl rename to test/dense/blas/trsm/trsm.jl diff --git a/test/trsm/trsm_batched.jl b/test/dense/blas/trsm/trsm_batched.jl similarity index 100% rename from test/trsm/trsm_batched.jl rename to test/dense/blas/trsm/trsm_batched.jl diff --git a/test/trsm/unified_rectrxm.jl b/test/dense/blas/trsm/unified_rectrxm.jl similarity index 98% rename from test/trsm/unified_rectrxm.jl rename to test/dense/blas/trsm/unified_rectrxm.jl index 366ba8d3..2670c494 100644 --- a/test/trsm/unified_rectrxm.jl +++ b/test/dense/blas/trsm/unified_rectrxm.jl @@ -48,7 +48,7 @@ end # The GPU testset above is the only coverage unified_rectrxm! had, and on CUDA # it now dispatches into ext/cuda/rectrxm.jl. Without the block below, the -# recursive KernelAbstractions path in src/trsm/rectrxm.jl — which is what CPU, +# recursive KernelAbstractions path in src/dense/blas/trsm/rectrxm.jl — which is what CPU, # oneAPI and Metal use — would be exercised by nothing at all. @testset "unified_rectrxm! CPU (recursive KA path)" begin tol = 1e-12 @@ -97,9 +97,9 @@ end # The seven-argument form is generic and only delegates, so it always lands # in src/. The eight-argument form is the one the extension specialises. @test endswith(_slashes(_method_file(unified_rectrxm!, 'L', 'L', 'N', 1.0, 'S', A, B)), - "src/trsm/rectrxm.jl") + "src/dense/blas/trsm/rectrxm.jl") @test endswith(_slashes(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', 1.0, 'S', A, B)), - "src/trsm/rectrxm.jl") + "src/dense/blas/trsm/rectrxm.jl") # Backends with a vendor fast path; the rest stay on the portable kernels. fast = Dict("CUDA" => "ext/cuda/rectrxm.jl", "AMDGPU" => "ext/amdgpu/rectrxm.jl") diff --git a/test/NextLAMatrix.jl b/test/dense/core/NextLAMatrix.jl similarity index 100% rename from test/NextLAMatrix.jl rename to test/dense/core/NextLAMatrix.jl diff --git a/test/cholesky/cholesky.jl b/test/dense/lapack/cholesky/cholesky.jl similarity index 100% rename from test/cholesky/cholesky.jl rename to test/dense/lapack/cholesky/cholesky.jl diff --git a/test/cholesky/cholesky_blocked.jl b/test/dense/lapack/cholesky/cholesky_blocked.jl similarity index 100% rename from test/cholesky/cholesky_blocked.jl rename to test/dense/lapack/cholesky/cholesky_blocked.jl diff --git a/test/cholesky/potrf.jl b/test/dense/lapack/cholesky/potrf.jl similarity index 100% rename from test/cholesky/potrf.jl rename to test/dense/lapack/cholesky/potrf.jl diff --git a/test/cholesky/potrf_batched.jl b/test/dense/lapack/cholesky/potrf_batched.jl similarity index 100% rename from test/cholesky/potrf_batched.jl rename to test/dense/lapack/cholesky/potrf_batched.jl diff --git a/test/lu.jl b/test/dense/lapack/lu/lu.jl similarity index 100% rename from test/lu.jl rename to test/dense/lapack/lu/lu.jl diff --git a/test/lu/lu_factor.jl b/test/dense/lapack/lu/lu_factor.jl similarity index 100% rename from test/lu/lu_factor.jl rename to test/dense/lapack/lu/lu_factor.jl diff --git a/test/lu/reclu.jl b/test/dense/lapack/lu/reclu.jl similarity index 100% rename from test/lu/reclu.jl rename to test/dense/lapack/lu/reclu.jl diff --git a/test/geqr2.jl b/test/dense/lapack/qr/geqr2.jl similarity index 100% rename from test/geqr2.jl rename to test/dense/lapack/qr/geqr2.jl diff --git a/test/geqrt.jl b/test/dense/lapack/qr/geqrt.jl similarity index 100% rename from test/geqrt.jl rename to test/dense/lapack/qr/geqrt.jl diff --git a/test/larf.jl b/test/dense/lapack/qr/larf.jl similarity index 100% rename from test/larf.jl rename to test/dense/lapack/qr/larf.jl diff --git a/test/larfb.jl b/test/dense/lapack/qr/larfb.jl similarity index 100% rename from test/larfb.jl rename to test/dense/lapack/qr/larfb.jl diff --git a/test/larfg.jl b/test/dense/lapack/qr/larfg.jl similarity index 100% rename from test/larfg.jl rename to test/dense/lapack/qr/larfg.jl diff --git a/test/larft.jl b/test/dense/lapack/qr/larft.jl similarity index 100% rename from test/larft.jl rename to test/dense/lapack/qr/larft.jl diff --git a/test/pamm.jl b/test/dense/lapack/qr/pamm.jl similarity index 100% rename from test/pamm.jl rename to test/dense/lapack/qr/pamm.jl diff --git a/test/parfb.jl b/test/dense/lapack/qr/parfb.jl similarity index 100% rename from test/parfb.jl rename to test/dense/lapack/qr/parfb.jl diff --git a/test/pemv.jl b/test/dense/lapack/qr/pemv.jl similarity index 100% rename from test/pemv.jl rename to test/dense/lapack/qr/pemv.jl diff --git a/test/tsmqr.jl b/test/dense/lapack/qr/tsmqr.jl similarity index 100% rename from test/tsmqr.jl rename to test/dense/lapack/qr/tsmqr.jl diff --git a/test/tsqrt.jl b/test/dense/lapack/qr/tsqrt.jl similarity index 100% rename from test/tsqrt.jl rename to test/dense/lapack/qr/tsqrt.jl diff --git a/test/ttmqr.jl b/test/dense/lapack/qr/ttmqr.jl similarity index 100% rename from test/ttmqr.jl rename to test/dense/lapack/qr/ttmqr.jl diff --git a/test/ttqrt.jl b/test/dense/lapack/qr/ttqrt.jl similarity index 100% rename from test/ttqrt.jl rename to test/dense/lapack/qr/ttqrt.jl diff --git a/test/unmqr.jl b/test/dense/lapack/qr/unmqr.jl similarity index 100% rename from test/unmqr.jl rename to test/dense/lapack/qr/unmqr.jl diff --git a/test/rotations/lartg.jl b/test/dense/lapack/rotations/lartg.jl similarity index 100% rename from test/rotations/lartg.jl rename to test/dense/lapack/rotations/lartg.jl diff --git a/test/gpu_backends.jl b/test/gpu_backends.jl index 53d3b397..5b507cdf 100644 --- a/test/gpu_backends.jl +++ b/test/gpu_backends.jl @@ -24,6 +24,13 @@ function supports_float64(ArrayType) end end +# The backends asked for with the runner flag --backends (e.g. "CPU,CUDA"), as +# lowercase names; empty means every available backend. test/runtests.jl +# defines TEST_BACKENDS_WANTED in each test's module. +_wanted_backends() = + isdefined(@__MODULE__, :TEST_BACKENDS_WANTED) && !isempty(strip(TEST_BACKENDS_WANTED)) ? + lowercase.(strip.(split(TEST_BACKENDS_WANTED, ','))) : String[] + """ available_gpu_backends() @@ -42,7 +49,11 @@ function available_gpu_backends() ("Metal", :Metal, :MtlArray, :functional), ] debug = get(ENV, "NEXTLA_GPU_DEBUG", "0") == "1" + wanted = _wanted_backends() for (name, pkg_sym, array_sym, func_sym) in backend_defs + # A backend not asked for is not even loaded, so --backends=CPU never + # loads a GPU package. + isempty(wanted) || lowercase(name) in wanted || continue try # Load package - fails if not installed; require returns the module pkg = Base.require(Main, pkg_sym) @@ -82,12 +93,19 @@ on at least CPU when no GPU is available. """ function available_backends() backends = Tuple{String, Type, Function}[] - # CPU always available - push!(backends, ("CPU", Array, _ -> nothing)) + wanted = _wanted_backends() + # CPU always available (unless --backends leaves it out) + (isempty(wanted) || "cpu" in wanted) && push!(backends, ("CPU", Array, _ -> nothing)) # Add GPU backends for (name, AT, sync) in available_gpu_backends() push!(backends, (name, AT, sync)) end + # A backend asked for but not usable is an error, so a GPU run cannot pass + # on the CPU alone. + absent = setdiff(wanted, lowercase.(first.(backends))) + isempty(absent) || error("--backends=$TEST_BACKENDS_WANTED: not usable here: ", join(absent, ", "), + ". A GPU backend needs its package in the test environment (see test/README.md, ", + "\"GPU backends\") and a working device; NEXTLA_GPU_DEBUG=1 prints why it was skipped.") return backends end diff --git a/test/lauum.jl b/test/lauum.jl deleted file mode 100644 index 3400ce66..00000000 --- a/test/lauum.jl +++ /dev/null @@ -1,34 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LAUUM [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "uplo=$uplo, n=$n, ib=$ib" for uplo in ['U', 'L'], - n in [16, 32, 64, 128], - ib in [2, 4, 8] - A_init = if uplo == 'U' - Matrix(UpperTriangular(0.5 .+ rand(T, n, n))) - else - Matrix(LowerTriangular(-0.5 .+ rand(T, n, n))) - end - A_orig = copy(A_init) - A = ArrayType(copy(A_init)) - - NextLA.lauum!(uplo, n, A, ib) - synchronize(A) - - if uplo == 'U' - expected = Matrix(UpperTriangular(A_orig * A_orig')) - else - expected = Matrix(LowerTriangular(A_orig' * A_orig)) - end - @test norm(Array(A) - expected) / n < rtol - end - end - end -end - -@testset "LAUUM Error handling" begin - @test_throws ArgumentError NextLA.lauum!('X', 4, zeros(4, 4), 2) - @test_throws ArgumentError NextLA.lauum!('U', -1, zeros(0, 0), 2) -end diff --git a/test/mxp/blas/gemm/recgemm_mixedprec.jl b/test/mxp/blas/gemm/recgemm_mixedprec.jl new file mode 100644 index 00000000..0239ea20 --- /dev/null +++ b/test/mxp/blas/gemm/recgemm_mixedprec.jl @@ -0,0 +1,92 @@ +# recgemm! into a FullMixedPrec destination, src/mxp/blas/gemm/recgemm_mixedprec.jl. +# Accuracy is checked against Float64 BLAS with the bound of test/setup/mxp.jl for +# the narrowest precision involved (the container's or the operands'). + +const MXP_GEMM_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[NextLA.BFloat16, Float32], DataType[Float16, Float32, Float64], + DataType[NextLA.BFloat16, Float16, Float32, Float64]) + +@testset "RECGEMM mixed precision [$name]" for (name, AT, _) in MXP_BACKENDS + Random.seed!(2049) + + @testset "precisions=$P, n=$n, k=$k" for P in MXP_GEMM_PRECISIONS, n in (5, 13, 16), k in (1, 7, 16) + T = P[end] + A, B, C0 = mxp_rand(T, n, k), mxp_rand(T, k, n), mxp_rand(T, n, n) + alpha, beta = T(1.5), T(0.5) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + @test recgemm!(alpha, mxp_on(AT, A), mxp_on(AT, B), beta, C) === C + ref = 1.5 * Float64.(A) * Float64.(B) + 0.5 * Float64.(C0) + @test mxp_relerr(reconstruct_matrix(C), ref) <= mxp_tol(mxp_narrowest(P), k + 1) + end + + @testset "operands of another type than the container: A, B $TA into $P" for (TA, P) in + ((Float64, DataType[Float16, Float32]), (Float32, DataType[Float32, Float64])) + n, k = 16, 8 + A, B, C0 = mxp_rand(TA, n, k), mxp_rand(TA, k, n), mxp_rand(Float64, n, n) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + recgemm!(1.0, mxp_on(AT, A), mxp_on(AT, B), 1.0, C) + ref = Float64.(A) * Float64.(B) + C0 + @test mxp_relerr(reconstruct_matrix(C), ref) <= mxp_tol(mxp_narrowest(vcat(P, TA)), k + 1) + end + + @testset "beta = 0 overwrites C" begin + n = 8 + A, B = mxp_rand(Float64, n, n), mxp_rand(Float64, n, n) + C = FullMixedPrec(mxp_on(AT, mxp_rand(Float64, n, n)); precisions=DataType[Float32, Float64]) + recgemm!(1.0, mxp_on(AT, A), mxp_on(AT, B), 0.0, C) + @test mxp_relerr(reconstruct_matrix(C), A * B) <= mxp_tol(Float32, n) + end + + @testset "a scaled block takes alpha divided by its scale" begin + n = 8 + C0 = ones(n, n) + C0[5:8, 1:4] .= 1.0e5 + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, Float64]) + @test C.A21_scale != 1 + A, B = mxp_rand(Float64, n, n), mxp_rand(Float64, n, n) + recgemm!(-100.0, mxp_on(AT, A), mxp_on(AT, B), 1.0, C) + @test mxp_relerr(reconstruct_matrix(C), -100 * A * B + C0) <= mxp_tol(Float16, n + 1) + end + + # An update past floatmax of a Float16 off-diagonal block raises the block's + # scale, so the result stays finite where a fixed scale left Inf. + @testset "an update that overflows a Float16 block raises its scale" begin + C = FullMixedPrec(mxp_on(AT, zeros(4, 4)); precisions=DataType[Float16, Float32]) + A, B = fill(1000.0, 4, 4), fill(1000.0, 4, 4) + recgemm!(1.0, mxp_on(AT, A), mxp_on(AT, B), 0.0, C) + @test C.A12_scale > 1 && C.A21_scale > 1 + R = reconstruct_matrix(C) + @test all(isfinite, Array(R)) + @test mxp_relerr(R, A * B) <= mxp_tol(Float16, 4) + end + + # The four quadrant updates touch disjoint blocks, so the threaded run does the + # same arithmetic as the sequential one and gives the same bits. + @testset "parallel and sequential give the same result" begin + n = 16 + A, B, C0 = mxp_rand(Float32, n, n), mxp_rand(Float32, n, n), mxp_rand(Float32, n, n) + seq = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, Float32]) + par = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, Float32]) + recgemm!(1f0, mxp_on(AT, A), mxp_on(AT, B), 1f0, seq; parallel=false) + recgemm!(1f0, mxp_on(AT, A), mxp_on(AT, B), 1f0, par; parallel=true) + @test Array(reconstruct_matrix(seq)) == Array(reconstruct_matrix(par)) + end + + @testset "mismatched shapes throw DimensionMismatch" begin + C = FullMixedPrec(mxp_on(AT, rand(8, 8)); precisions=DataType[Float64]) + @test_throws DimensionMismatch recgemm!(1.0, mxp_on(AT, rand(7, 4)), mxp_on(AT, rand(4, 8)), 1.0, C) + @test_throws DimensionMismatch recgemm!(1.0, mxp_on(AT, rand(8, 4)), mxp_on(AT, rand(4, 7)), 1.0, C) + @test_throws DimensionMismatch recgemm!(1.0, mxp_on(AT, rand(8, 4)), mxp_on(AT, rand(5, 8)), 1.0, C) + end +end + +# Above RECGEMM_PARALLEL_THRESHOLD (512) the default is parallel. CPU only: the +# size is for the default, not for the device. +@testset "RECGEMM mixed precision, default parallel above the threshold [CPU]" begin + Random.seed!(2050) + n, k = 520, 16 + A, B, C0 = mxp_rand(Float32, n, k), mxp_rand(Float32, k, n), mxp_rand(Float32, n, n) + C = FullMixedPrec(copy(C0); precisions=DataType[Float16, Float32]) + recgemm!(1f0, A, B, 1f0, C) + @test mxp_relerr(reconstruct_matrix(C), Float64.(A) * Float64.(B) + C0) <= mxp_tol(Float16, k + 1) +end diff --git a/test/mxp/blas/syrk/recsyrk_mixedprec.jl b/test/mxp/blas/syrk/recsyrk_mixedprec.jl new file mode 100644 index 00000000..a1d6ce7e --- /dev/null +++ b/test/mxp/blas/syrk/recsyrk_mixedprec.jl @@ -0,0 +1,90 @@ +# recsyrk! over a SymmMixedPrec container, src/mxp/blas/syrk/recsyrk_mixedprec.jl. +# Checked on the stored triangle against Float64 BLAS, with the bound of +# test/setup/mxp.jl for the narrowest precision. + +const MXP_SYRK_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[NextLA.BFloat16, Float32], DataType[Float16, Float32, Float64], + DataType[NextLA.BFloat16, Float16, Float32, Float64]) + +_mxp_syrk_err(C, ref, uplo) = mxp_relerr(mxp_tri(uplo, Float64.(Array(reconstruct_matrix(C)))), mxp_tri(uplo, ref)) + +@testset "RECSYRK mixed precision [CPU]" begin + Random.seed!(2055) + + @testset "precisions=$P, uplo=$uplo, n=$n, k=$k" for P in MXP_SYRK_PRECISIONS, uplo in ('L', 'U'), + n in (13, 32, 45, 64), k in (1, 16) + T = P[end] + A, C0 = mxp_rand(T, n, k), mxp_spd(T, n) + C = SymmMixedPrec(copy(C0), uplo; precisions=P) + @test recsyrk!(T(1.5), A, T(0.5), C) === C + ref = 1.5 * Float64.(A) * transpose(Float64.(A)) + 0.5 * Float64.(C0) + @test _mxp_syrk_err(C, ref, uplo) <= mxp_tol(mxp_narrowest(P), k + 1) + R = reconstruct_matrix(C) + @test R == transpose(R) + end + + @testset "A of another type than the container: $TA into $P" for (TA, P) in + ((Float64, DataType[Float16, Float32]), (Float32, DataType[Float32, Float64])) + n, k = 32, 8 + A, C0 = mxp_rand(TA, n, k), mxp_spd(Float64, n) + C = SymmMixedPrec(copy(C0), 'L'; precisions=P) + recsyrk!(1.0, A, 1.0, C) + ref = Float64.(A) * transpose(Float64.(A)) + C0 + @test _mxp_syrk_err(C, ref, 'L') <= mxp_tol(mxp_narrowest(vcat(P, TA)), k + 1) + end + + @testset "a scaled block takes alpha divided by its scale, uplo=$uplo" for uplo in ('L', 'U') + n = 8 + C0 = ones(n, n) + C0[5:8, 1:4] .= 1.0e5 + C0[1:4, 5:8] .= 1.0e5 + C = SymmMixedPrec(copy(C0), uplo; precisions=DataType[Float16, Float64]) + @test C.OffDiag_scale != 1 + A = mxp_rand(Float64, n, 4) + recsyrk!(-100.0, A, 1.0, C) + @test _mxp_syrk_err(C, -100 * A * transpose(A) + C0, uplo) <= mxp_tol(Float16, 5) + end + + # An update past floatmax of the Float16 off-diagonal block raises its scale. + @testset "an update that overflows a Float16 block raises its scale, uplo=$uplo" for uplo in ('L', 'U') + C = SymmMixedPrec(zeros(4, 4), uplo; precisions=DataType[Float16, Float32]) + A = fill(1000.0, 4, 2) + recsyrk!(1.0, A, 0.0, C) + @test C.OffDiag_scale > 1 + @test _mxp_syrk_err(C, A * A', uplo) <= mxp_tol(Float16, 2) + end + + # The threaded path runs only above RECSYRK_PARALLEL_THRESHOLD (4096) rows in + # A11, too large for a test, so it is reached through the internal function. + # The two halves write disjoint blocks: same arithmetic, same bits. + @testset "parallel and sequential give the same result, uplo=$uplo" for uplo in ('L', 'U') + n = 32 + A, C0 = mxp_rand(Float64, n, 8), mxp_spd(Float64, n) + seq = SymmMixedPrec(copy(C0), uplo; precisions=DataType[Float16, Float32, Float64]) + par = SymmMixedPrec(copy(C0), uplo; precisions=DataType[Float16, Float32, Float64]) + MixedPrecision._recsyrk_mixed!(1.0, A, 1.0, seq; parallel=false) + MixedPrecision._recsyrk_mixed!(1.0, A, 1.0, par; parallel=true) + @test reconstruct_matrix(seq) == reconstruct_matrix(par) + end + + @testset "A with the wrong number of rows throws" begin + C = SymmMixedPrec(rand(8, 8), 'L'; precisions=DataType[Float64]) + @test_throws DimensionMismatch recsyrk!(1.0, rand(7, 3), 1.0, C) + end +end + +# On a GPU: the update runs on the device; the result is read through a host copy +# of the container and checked on the CPU. +@testset "RECSYRK mixed precision [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2056) + @testset "precisions=$P, uplo=$uplo" for P in (DataType[Float32, Float32], DataType[Float16, Float32, Float64]), + uplo in ('L', 'U') + n, k = 45, 16 + T = P[end] + A, C0 = mxp_rand(T, n, k), mxp_spd(T, n) + C = SymmMixedPrec(AT(C0), uplo; precisions=P) + recsyrk!(T(1.5), AT(A), T(0.5), C) + ref = 1.5 * Float64.(A) * transpose(Float64.(A)) + 0.5 * Float64.(C0) + @test _mxp_syrk_err(mxp_host(C), ref, uplo) <= mxp_tol(mxp_narrowest(P), k + 1) + end +end diff --git a/test/mxp/blas/trsm/rectrxm_mixed.jl b/test/mxp/blas/trsm/rectrxm_mixed.jl new file mode 100644 index 00000000..be1145bf --- /dev/null +++ b/test/mxp/blas/trsm/rectrxm_mixed.jl @@ -0,0 +1,208 @@ +# unified_rectrxm! with a mixed-precision container, src/mxp/blas/trsm/rectrxm_mixed.jl: +# triangular solve (func 'S') and multiply (func 'M') with A a TriMixedPrec, +# SymmMixedPrec or FullMixedPrec. A solve is checked by its backward error and a +# multiply by its forward error, both against the container's own stored values in +# Float64, so they measure the operation and not how the container rounded A; the +# bound is that of test/setup/mxp.jl for the narrowest precision involved. + +# A triangle with an O(1) diagonal and an off-diagonal part of norm O(1), so the +# solves with and without a unit diagonal are well conditioned. +function _mxp_trxm_matrix(T, n, uplo) + S = mxp_tri(uplo, mxp_rand(T, n, n) ./ T(n)) + S[LinearAlgebra.diagind(S)] .= one(T) .+ rand(T, n) + return S +end + +function _mxp_trxm_container(kind, T, n, uplo, P) + A = _mxp_trxm_matrix(T, n, uplo) + kind === TriMixedPrec && return TriMixedPrec(A, uplo; precisions=P) + kind === SymmMixedPrec && return SymmMixedPrec(A + transpose(A) - Diagonal(A), uplo; precisions=P) + return FullMixedPrec(A + transpose(mxp_tri(uplo, A)) - Diagonal(A); precisions=P) # both triangles +end + +# The triangle the routine reads, in Float64, from what the container stores. +_mxp_stored(Amp, uplo) = mxp_tri(uplo, Float64.(Array(reconstruct_matrix(Amp)))) + +function _mxp_trxm_err(side, uplo, trans, diag, func, alpha, Ad, X, B) + if func == 'S' + return mxp_trsm_backward_error(side, uplo, trans, diag, Ad, X, alpha .* Float64.(B)) + end + return mxp_relerr(X, alpha .* mxp_trmm_reference(side, uplo, trans == 'C' ? 'T' : trans, diag, Ad, B)) +end + +@testset "RECTRXM mixed [CPU]" begin + Random.seed!(2051) + + @testset "$(nameof(kind)) uplo=$uplo side=$side func=$func trans=$trans diag=$diag precisions=$P" for + kind in (TriMixedPrec, SymmMixedPrec, FullMixedPrec), uplo in ('L', 'U'), side in ('L', 'R'), + func in ('S', 'M'), trans in ('N', 'T', 'C'), diag in ('N', 'U'), + P in (DataType[Float32, Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64]) + n, m = 37, 5 + T = P[end] + Amp = _mxp_trxm_container(kind, T, n, uplo, P) + B = side == 'L' ? mxp_rand(T, n, m) : mxp_rand(T, m, n) + X = copy(B) + @test unified_rectrxm!(side, uplo, trans, diag, T(2), func, Amp, X) === X + @test _mxp_trxm_err(side, uplo, trans, diag, func, 2.0, _mxp_stored(Amp, uplo), X, B) <= + mxp_tol(mxp_narrowest(P), n) + end + + @testset "n=$n, precisions=$P" for n in (1, 2, 16, 64, 300), P in (DataType[NextLA.BFloat16, Float32], + DataType[NextLA.BFloat16, Float16, Float32, Float64]) + T = P[end] + for side in ('L', 'R'), func in ('S', 'M') + Amp = _mxp_trxm_container(TriMixedPrec, T, n, 'L', P) + B = side == 'L' ? mxp_rand(T, n, 3) : mxp_rand(T, 3, n) + X = copy(B) + unified_rectrxm!(side, 'L', 'N', 'N', one(T), func, Amp, X) + @test _mxp_trxm_err(side, 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= + mxp_tol(mxp_narrowest(P), n) + end + end + + # B of another type than the container: wider (the narrow block's product is + # added through a partial sum), narrower (the wider block multiplies B + # directly), and a transposed narrow block that is copied before mixing types. + @testset "B $TB with precisions=$P, trans=$trans" for (TB, P) in + ((Float64, DataType[Float16, Float32]), (Float64, DataType[Float32, Float32]), + (Float32, DataType[Float64, Float64]), (Float32, DataType[Float16, Float64])), + trans in ('N', 'T') + n = 37 + Amp = _mxp_trxm_container(TriMixedPrec, P[end], n, 'L', P) + for side in ('L', 'R'), func in ('S', 'M') + B = side == 'L' ? mxp_rand(TB, n, 4) : mxp_rand(TB, 4, n) + X = copy(B) + unified_rectrxm!(side, 'L', trans, 'N', one(TB), func, Amp, X) + @test eltype(X) === TB + @test _mxp_trxm_err(side, 'L', trans, 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= + mxp_tol(mxp_narrowest(vcat(P, TB)), n) + end + end + + @testset "scaled off-diagonal blocks, func=$func" for func in ('S', 'M') + n, m = 16, 4 + A = tril(rand(Float32, n, n)) * 1f5 + Diagonal(1f6 * ones(Float32, n)) + Amp = TriMixedPrec(A, 'L'; precisions=DataType[Float16, Float32]) + @test Amp.OffDiag_scale != 1 + B = mxp_rand(Float32, n, m) + X = copy(B) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, func, Amp, X) + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(Float16, n) + end + + @testset "a scaled leaf, func=$func" for func in ('S', 'M') + n, m = 16, 4 + A = tril(rand(n, n)) * 1.0e39 + 2.0e39I + Amp = TriMixedPrec(A, 'L'; precisions=DataType[Float32]) + @test Amp.Base_scale != 1 + B = mxp_rand(Float64, n, m) + X = copy(B) + unified_rectrxm!('L', 'L', 'N', 'N', 1.0, func, Amp, X) + Ad = tril(Float64.(Amp.Base) .* Amp.Base_scale) + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, Ad, X, B) <= mxp_tol(Float32, n) + end + + @testset "a multiply that overflows gives Inf, not floatmax" begin + Amp = TriMixedPrec(Matrix(1.0e39I, 4, 4), 'L'; precisions=DataType[Float32]) + @test Amp.Base_scale != 1 + B = fill(1f34, 4, 2) + unified_rectrxm!('L', 'L', 'N', 'N', 1, 'M', Amp, B) + @test all(isinf, B) + end + + # A non-finite source is converted as it is, not quantized (which would throw). + @testset "a non-finite B through a narrow off-diagonal block" begin + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 8, 'L', DataType[Float16, Float32]) + B = mxp_rand(Float32, 8, 2) + B[2, 1] = Inf32 + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'M', Amp, B) + @test !isfinite(B[2, 1]) && all(isfinite, B[:, 2]) + end + + # The off-diagonal product rounds B's part to the block's Float16 through a + # scaled copy; a plain conversion made values past floatmax(Float16) Inf. + @testset "an off-diagonal product keeps B values past floatmax(Float16)" begin + n = 16 + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32]) + B = 1.0f6 .* mxp_rand(Float32, n, 3) + X = copy(B) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', Amp, X) + @test all(isfinite, X) + @test _mxp_trxm_err('L', 'L', 'N', 'N', 'S', 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(Float16, n) + end + + # The dense driver's TRMM base case is only valid up to TILE_DIM = 16; a larger + # threshold used to give silently wrong answers, so unified_rec clamps it. + @testset "multiply respects the dense TRMM tile limit" begin + n, m = 64, 8 + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float32, Float32]) + B = mxp_rand(Float32, n, m) + X = copy(B) + MixedPrecision._rec_mixed!('M', 'L', 'L', 'N', Amp, X, 256) + @test _mxp_trxm_err('L', 'L', 'N', 'N', 'M', 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(Float32, n) + end + + @testset "the form without diag takes 'N', $(nameof(kind))" for kind in (TriMixedPrec, FullMixedPrec) + Amp = _mxp_trxm_container(kind, Float32, 16, 'L', DataType[Float32, Float32]) + B = mxp_rand(Float32, 16, 3) + B1, B2 = copy(B), copy(B) + unified_rectrxm!('L', 'L', 'N', 1f0, 'S', Amp, B1) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', Amp, B2) + @test B1 == B2 + end + + @testset "uplo must be A.uplo for a triangular or symmetric container" begin + Tri = _mxp_trxm_container(TriMixedPrec, Float32, 16, 'L', DataType[Float32, Float32]) + Sym = _mxp_trxm_container(SymmMixedPrec, Float32, 16, 'L', DataType[Float32, Float32]) + B = mxp_rand(Float32, 16, 3) + @test_throws ArgumentError unified_rectrxm!('L', 'U', 'N', 'N', 1, 'S', Tri, copy(B)) + @test_throws ArgumentError unified_rectrxm!('R', 'U', 'T', 'N', 1, 'M', Tri, copy(B')) + @test_throws ArgumentError unified_rectrxm!('L', 'U', 'N', 'N', 1, 'S', Sym, copy(B)) + end + + @testset "the flags are checked" begin + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 8, 'L', DataType[Float32]) + B = mxp_rand(Float32, 8, 2) + @test_throws ArgumentError unified_rectrxm!('X', 'L', 'N', 'N', 1f0, 'S', Amp, B) + @test_throws ArgumentError unified_rectrxm!('L', 'X', 'N', 'N', 1f0, 'S', Amp, B) + @test_throws ArgumentError unified_rectrxm!('L', 'L', 'X', 'N', 1f0, 'S', Amp, B) + @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'X', 1f0, 'S', Amp, B) + @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'X', Amp, B) + end +end + +# On a GPU: the solve runs on the device with each kind of container; the stored +# values are read through a host copy of the container and checked on the CPU. +@testset "RECTRXM mixed [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2052) + n = 37 + + @testset "FullMixedPrec uplo=$uplo side=$side func=$func trans=$trans diag=$diag precisions=$P" for + uplo in ('L', 'U'), side in ('L', 'R'), func in ('S', 'M'), trans in ('N', 'T'), diag in ('N', 'U'), + P in (DataType[Float32, Float32], DataType[Float16, Float32, Float64]) + T = P[end] + A = _mxp_trxm_matrix(T, n, uplo) + Amp = FullMixedPrec(AT(A + transpose(A) - Diagonal(A)); precisions=P) + B = side == 'L' ? mxp_rand(T, n, 4) : mxp_rand(T, 4, n) + X = AT(copy(B)) + unified_rectrxm!(side, uplo, trans, diag, T(2), func, Amp, X) + @test X isa AT + @test _mxp_trxm_err(side, uplo, trans, diag, func, 2.0, _mxp_stored(Amp, uplo), X, B) <= + mxp_tol(mxp_narrowest(P), n) + end + + @testset "$(nameof(kind)) uplo=$uplo side=$side func=$func trans=$trans" for + kind in (TriMixedPrec, SymmMixedPrec), uplo in ('L', 'U'), side in ('L', 'R'), func in ('S', 'M'), + trans in ('N', 'T') + P = DataType[Float16, Float32, Float64] + A = _mxp_trxm_matrix(Float64, n, uplo) + A = kind === SymmMixedPrec ? A + transpose(A) - Diagonal(A) : A + B = side == 'L' ? mxp_rand(Float64, n, 4) : mxp_rand(Float64, 4, n) + Amp = kind(AT(A), uplo; precisions=P) + X = AT(copy(B)) + unified_rectrxm!(side, uplo, trans, 'N', 2.0, func, Amp, X) + @test X isa AT + @test _mxp_trxm_err(side, uplo, trans, 'N', func, 2.0, _mxp_stored(mxp_host(Amp), uplo), X, B) <= + mxp_tol(Float16, n) + end +end diff --git a/test/mxp/cholesky/recpotrf_mixedprec.jl b/test/mxp/cholesky/recpotrf_mixedprec.jl deleted file mode 100644 index df782372..00000000 --- a/test/mxp/cholesky/recpotrf_mixedprec.jl +++ /dev/null @@ -1,77 +0,0 @@ -using NextLA.MixedPrecision -# potrf_recursive! over a SymmMixedPrec container. CPU only. - -function _mxp_spd(T, n) - R = rand(T, n, n) - return R * R' + T(n) * I -end - -@testset "POTRF_RECURSIVE mixed precision [CPU]" begin - Random.seed!(2057) - - @testset "n=$n uplo=$uplo" for n in (32, 40, 64), uplo in ('L', 'U') - T = Float32 - A0 = _mxp_spd(T, n) - - mp = SymmMixedPrec(copy(A0), uplo; precisions = DataType[Float32, Float32]) - @test potrf_recursive!(mp) === mp - - F = reconstruct_matrix(TriMixedPrec(mp)) - if uplo == 'L' - @test istril(F) - @test norm(F * F' - A0) / norm(A0) < 1e-3 - else - @test istriu(F) - @test norm(F' * F - A0) / norm(A0) < 1e-3 - end - end - - @testset "block_size reaches the leaves" begin - A0 = _mxp_spd(Float64, 32) - mp = SymmMixedPrec(copy(A0), 'L'; precisions = DataType[Float64]) - potrf_recursive!(mp, 8) - L = reconstruct_matrix(TriMixedPrec(mp)) - @test norm(L * L' - A0) / norm(A0) < 1e-12 - end - - @testset "Float16 off-diagonal blocks" begin - n = 32 - A0 = _mxp_spd(Float32, n) - mp = SymmMixedPrec(copy(A0), 'L'; precisions = DataType[Float16, Float32]) - potrf_recursive!(mp) - L = reconstruct_matrix(TriMixedPrec(mp)) - @test norm(L * L' - A0) / norm(A0) < 1e-2 - end - - # A leaf no larger than block_size is factored by potrf!, whose info turns - # into PosDefException. A larger leaf goes through the dense potrf_recursive!, - # which drops that info. - @testset "a matrix that is not positive definite throws, uplo=$uplo" for uplo in ('L', 'U') - A0 = -Matrix{Float64}(I, 8, 8) - mp = SymmMixedPrec(A0, uplo; precisions = DataType[Float32, Float64]) - @test_throws PosDefException potrf_recursive!(mp) - end - - @testset "a leaf larger than block_size, uplo=$uplo" for uplo in ('L', 'U') - A0 = _mxp_spd(Float64, 32) - mp = SymmMixedPrec(copy(A0), uplo; precisions = DataType[Float64]) - potrf_recursive!(mp, 8) - F = reconstruct_matrix(TriMixedPrec(mp)) - @test norm((uplo == 'L' ? F * F' : F' * F) - A0) / norm(A0) < 1e-12 - end - - @testset "a leaf stored with a scale factor throws" begin - mp = SymmMixedPrec(1.0e39 * ones(4, 4) + 1.0e40I, 'L'; precisions = DataType[Float32]) - @test mp.Base_scale != 1 - @test_throws ArgumentError potrf_recursive!(mp) - end - - # reconstruct_matrix round-trips an unfactored container, and is the - # symmetric counterpart to the FullMixedPrec method. - @testset "reconstruct_matrix round-trips" begin - n = 32 - A0 = _mxp_spd(Float32, n) - mp = SymmMixedPrec(copy(A0), 'L'; precisions = DataType[Float32, Float32]) - @test norm(reconstruct_matrix(mp) - A0) / norm(A0) < 1e-5 - end -end diff --git a/test/mxp/core/adaptive.jl b/test/mxp/core/adaptive.jl new file mode 100644 index 00000000..eb071694 --- /dev/null +++ b/test/mxp/core/adaptive.jl @@ -0,0 +1,108 @@ +# adaptive_precisions, src/mxp/core/adaptive.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "adaptive_precisions [CPU]" begin + Random.seed!(2047) + + n = 16 + A = tril(rand(Float64, n, n)) + n * I + + @testset "one precision per level, then the leaf precision" begin + u = adaptive_precisions(A) + @test u isa Vector{DataType} + @test all(T -> T in (Float32, Float64), u) + @test u[end] === Float64 + @test size(FullMixedPrec(A; precisions=u)) == (n, n) + end + + # The rule in the docstring, worked out for one level: n = 8 and n_min = 4 + # split once, into 4 + 4. E = ‖A21‖ / ‖tril(A)‖ (here 0.0141) and the level + # takes the coarsest type with u(T) <= epsilon / (sqrt(2) E). The three + # epsilons give a target of 5e-1, 5e-6 and 5e-11, so each type is chosen once. + @testset "the level type follows the documented rule, epsilon=$ϵ" for (ϵ, T) in + ((1e-2, Float16), (1e-7, Float32), (1e-12, Float64)) + B = Matrix(1.0I, 8, 8) + B[5:8, 1:4] .= 0.01 + E = norm(B[5:8, 1:4]) / norm(tril(B)) + U = DataType[Float16, Float32, Float64] + @test U[findfirst(S -> mxp_u(S) <= ϵ / (sqrt(2) * E), U)] === T + @test adaptive_precisions(B, U, 4, ϵ) == DataType[T, Float64] + end + + @testset "n_min controls the number of levels" begin + @test length(adaptive_precisions(A, DataType[Float32, Float64], 2)) > + length(adaptive_precisions(A, DataType[Float32, Float64], 8)) + end + + @testset "a matrix too small to split gets only the leaf precision" begin + @test adaptive_precisions(A[1:3, 1:3]) == DataType[Float64] + end + + @testset "the leaves are no finer than eltype(A)" begin + u = adaptive_precisions(Float32.(A), DataType[Float16, Float32, Float64]) + @test u[end] === Float32 + @test all(T -> T in (Float16, Float32), u) + @test adaptive_precisions(Float16.(A))[end] === Float32 + @test adaptive_precisions(Float32.(A), DataType[Float16])[end] === Float16 + end + + @testset "a non-float matrix gets the finest type of U for its leaves" begin + @test adaptive_precisions(round.(Int, 10A))[end] === Float64 + end + + @testset "a 16-bit matrix with large block norms is finite" begin + H = Float16.(fill(100, 2048, 2048) + 1000I) + @test adaptive_precisions(H; uplo='F')[end] === Float32 + end + + @testset "a BFloat16 matrix with very large or very small entries" begin + for v in (1f20, 1f-25) + B = NextLA.BFloat16.(fill(v, 64, 64) + 10v * I) + @test adaptive_precisions(B, DataType[NextLA.BFloat16, Float32]; uplo='F')[end] === Float32 + end + end + + @testset "U may be given in any order" begin + @test adaptive_precisions(A, DataType[Float64, Float32]) == adaptive_precisions(A) + end + + @testset "uplo='U' reads the upper triangle" begin + @test adaptive_precisions(copy(transpose(A)); uplo='U') == adaptive_precisions(A) + end + + @testset "uplo='F' measures both off-diagonal blocks" begin + F = [i == j ? 1.0 : i > j ? 1.0e-12 : 1.0 for i in 1:n, j in 1:n] + @test adaptive_precisions(F; uplo='L')[1] === Float32 + @test adaptive_precisions(F; uplo='F')[1] === Float64 + @test size(FullMixedPrec(F; precisions=adaptive_precisions(F; uplo='F'))) == (n, n) + end + + @testset "the other triangle is not read" begin + G = copy(A) + G[1, n] = NaN + @test adaptive_precisions(G) == adaptive_precisions(A) + end + + @testset "arguments are checked" begin + @test_throws DimensionMismatch adaptive_precisions(rand(Float64, 4, 8)) + @test_throws ArgumentError adaptive_precisions(zeros(0, 0)) + @test_throws ArgumentError adaptive_precisions(A, DataType[]) + @test_throws ArgumentError adaptive_precisions(A, DataType[Int]) + @test_throws ArgumentError adaptive_precisions(A, DataType[Float32, Float64], 0) + @test_throws ArgumentError adaptive_precisions(A, DataType[Float32, Float64], 4, 0.0) + @test_throws ArgumentError adaptive_precisions(A; uplo='X') + @test_throws ArgumentError adaptive_precisions(zeros(n, n)) + @test_throws ArgumentError adaptive_precisions(fill(NaN, n, n)) + end +end + +# On each GPU backend: the same precisions from a device matrix. +@testset "adaptive_precisions [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + + @testset "adaptive_precisions takes a device matrix" begin + S = mxp_spd(Float64, n) + @test adaptive_precisions(AT(S)) == adaptive_precisions(S) + end +end diff --git a/test/mxp/core/blocks.jl b/test/mxp/core/blocks.jl new file mode 100644 index 00000000..3aa62efb --- /dev/null +++ b/test/mxp/core/blocks.jl @@ -0,0 +1,126 @@ +# The block helpers of src/mxp/core/blocks.jl: the argument checks every +# container constructor shares, and storing an updated or solved off-diagonal +# block back with its scale. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "block helpers [CPU]" begin + Random.seed!(2047) + + @testset "leaves narrower than Float32 are refused" begin + for T in MXP_NARROW + @test_throws ArgumentError FullMixedPrec(rand(4, 4); precisions=DataType[T]) + @test_throws ArgumentError SymmMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float16, T]) + @test_throws ArgumentError TriMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float16, T]) + @test_throws ArgumentError TiledTriMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float16, T], threshold=2) + end + @test FullMixedPrec(rand(4, 4); precisions=DataType[Float16, Float32]) isa FullMixedPrec + end + + # The checks are shared (_check_mixedprec_args, and _quantize_mixedprec_block + # for the values), so each one is checked on every constructor. + @testset "arguments are checked, $(nameof(C))" for C in (FullMixedPrec, SymmMixedPrec, TriMixedPrec, TiledTriMixedPrec) + make(A, P) = C === FullMixedPrec ? C(A; precisions=P) : + C === TiledTriMixedPrec ? C(A, 'L'; precisions=P, threshold=2) : C(A, 'L'; precisions=P) + @test_throws ArgumentError make(zeros(0, 0), DataType[Float64]) + @test_throws DimensionMismatch make(rand(4, 8), DataType[Float64]) + @test_throws ArgumentError make(rand(4, 4), DataType[]) + @test_throws ArgumentError make(rand(4, 4), DataType[Int]) + @test_throws ArgumentError make(rand(4, 4), DataType[Float16, ComplexF64]) + @test_throws ArgumentError make([1.0 0.0; NaN 1.0], DataType[Float64]) + @test_throws ArgumentError make([1.0 0.0; Inf 1.0], DataType[Float64]) + @test_throws ArgumentError make(fill(1.0e300, 4, 4), DataType[Float16, Float32]) + end + + @testset "a solve that outgrows a Float16 block raises its scale" begin + blk = fill(Float16(100), 2, 2) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1000), blk, 1f0, Float32) + @test s > 1 && all(isfinite, blk) + @test Float32.(blk) .* s ≈ fill(1f5, 2, 2) rtol=2mxp_u(Float16) + end + + @testset "a block of the base type is solved in place, scale unchanged" begin + same = fill(1f0, 2, 2) + @test MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 2), same, 1f0, Float32) == 1f0 + @test same == fill(2f0, 2, 2) + end + + @testset "a solve past what the scale can carry throws" begin + blk = fill(1f0, 2, 2) + @test_throws ArgumentError MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1e80), blk, 1f0, Float64) + end + + @testset "an update of a Float32 block runs in place" begin + blk = fill(1f0, 2, 2) + @test MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .+= 1), blk, 1f0) == 1f0 + @test blk == fill(2f0, 2, 2) + end + + @testset "an update past floatmax of a Float16 block raises its scale" begin + blk = fill(Float16(1), 2, 2) + s = MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .= 1f6), blk, 1f0) + @test s > 1 && all(isfinite, blk) + @test Float32.(blk) .* s ≈ fill(1f6, 2, 2) rtol=2mxp_u(Float16) + end + + # floatmax(BFloat16) is just below floatmax(Float32), so a BFloat16 block is + # updated on a Float32 copy and solved on a copy of the leaf type, as Float16. + @testset "BFloat16 blocks raise their scale" begin + BF = NextLA.BFloat16 + blk = fill(BF(1), 2, 2) + s = MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .= floatmax(Float32)), blk, 1f0) + @test s > 1 && all(isfinite, blk) + @test Float64.(blk) .* s ≈ fill(Float64(floatmax(Float32)), 2, 2) rtol=2mxp_u(BF) + blk = fill(BF(1), 2, 2) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1e39), blk, 1f0, Float64) + @test s > 1 && all(isfinite, blk) + @test Float64.(blk) .* s ≈ fill(1e39, 2, 2) rtol=2mxp_u(BF) + end + + # A result with NaN or Inf is stored as it is and the scale stays (blocks.jl:30), + # so a breakdown in a routine shows in its result; the constructors, in + # contrast, refuse non-finite input. + @testset "a non-finite result is stored as it is, $T block, $x" for T in (Float16, Float32), x in (NaN32, Inf32, -Inf32) + blk = fill(T(1), 2, 2) + @test MixedPrecision._update_mixedprec_offdiag_block!(P -> (P[1, 1] = x), blk, 1f0) == 1f0 + @test isequal(blk[1, 1], T(x)) && blk[2, 2] == 1 + blk = fill(T(1), 2, 2) + @test MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W[1, 1] = x), blk, 2f0, Float64) == 2f0 + @test isequal(blk[1, 1], T(x)) && blk[2, 2] == 1 + end +end + +# On each GPU backend: the same helpers on device blocks (routines call them on +# the device inside recgemm!, recsyrk!, lu_recursive! and potrf_recursive!). +@testset "block helpers [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + @testset "a solve that outgrows a Float16 block raises its scale" begin + blk = AT(fill(Float16(100), 2, 2)) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1000), blk, 1f0, Float32) + @test blk isa AT && s > 1 + @test Float32.(Array(blk)) .* s ≈ fill(1f5, 2, 2) rtol=2mxp_u(Float16) + end + + @testset "a block of the base type is solved in place, scale unchanged" begin + same = AT(fill(1f0, 2, 2)) + @test MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 2), same, 1f0, Float32) == 1f0 + @test Array(same) == fill(2f0, 2, 2) + end + + @testset "a solve past what the scale can carry throws" begin + blk = AT(fill(1f0, 2, 2)) + @test_throws ArgumentError MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1e80), blk, 1f0, Float64) + end + + @testset "an update past floatmax of a $T block raises its scale" for T in MXP_NARROW + blk = AT(fill(T(1), 2, 2)) + big = T === Float16 ? 1f6 : floatmax(Float32) + s = MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .= big), blk, 1f0) + @test blk isa AT && s > 1 + @test Float64.(Array(blk)) .* s ≈ fill(Float64(big), 2, 2) rtol=2mxp_u(T) + end + + @testset "a non-finite result is stored as it is, $T block" for T in (Float16, Float32) + blk = AT(fill(T(1), 2, 2)) + @test MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .= NaN32), blk, 1f0) == 1f0 + @test all(isnan, Array(blk)) + end +end diff --git a/test/mxp/core/fullmixedprec.jl b/test/mxp/core/fullmixedprec.jl new file mode 100644 index 00000000..cc1cda40 --- /dev/null +++ b/test/mxp/core/fullmixedprec.jl @@ -0,0 +1,126 @@ +# FullMixedPrec, src/mxp/core/fullmixedprec.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "FullMixedPrec [CPU]" begin + Random.seed!(2047) + + @testset "$T, n=$n" for T in (Float32, Float64), n in (1, 4, 5, 8, 13, 16) + A = mxp_rand(T, n, n) + + @testset "one precision round-trips exactly" begin + M = FullMixedPrec(A; precisions=DataType[T]) + @test size(M) == (n, n) + @test reconstruct_matrix(M) == A + end + + @testset "precisions=$P" for P in (DataType[Float32, T], DataType[Float16, Float32, T], + DataType[NextLA.BFloat16, Float16, Float32, T]) + M = FullMixedPrec(A; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === T + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + @test M[1, 1] isa T + end + end + + # An input matrix of a 16-bit type (the leaves are Float32): every element is + # stored within one rounding of its block's type, and exactly where the block + # type is the input type. + @testset "$S input, n=$n, precisions=$P" for S in (Float16, NextLA.BFloat16), n in (5, 13), + P in (DataType[Float16, Float32], DataType[NextLA.BFloat16, Float32]) + A = S.(mxp_rand(Float32, n, n)) + M = FullMixedPrec(A; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === Float32 + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + P[1] === S && @test R == Float32.(A) + end + + # A view as input (the routines pass views of larger matrices): the same + # container as from a copy of the view. + @testset "a view as input, n=$n, precisions=$P" for n in (5, 13), + P in (DataType[Float32, Float64], DataType[Float16, Float32, Float64]) + B = mxp_rand(Float64, n + 3, n + 3) + V = view(B, 2:n+1, 3:n+2) + M = FullMixedPrec(V; precisions=P) + R = reconstruct_matrix(M) + @test R == reconstruct_matrix(FullMixedPrec(copy(V); precisions=P)) + @test mxp_storage_ok(R, copy(V), mxp_eltype_map(M)) + end + + @testset "each level stores its off-diagonal blocks in its precision" begin + M = FullMixedPrec(mxp_rand(Float64, 16, 16); + precisions=DataType[NextLA.BFloat16, Float16, Float32, Float64]) + @test eltype(M.A21) === eltype(M.A12) === NextLA.BFloat16 + @test eltype(M.A11.A21) === Float16 + @test eltype(M.A11.A11.A21) === Float32 + @test eltype(M.A11.A11.A11.Base) === Float64 + @test size(M.A11.A11.A11.Base) == (2, 2) + end + + @testset "every scale is Float32" begin + M = FullMixedPrec(rand(8, 8); precisions=DataType[Float32, Float64]) + @test M.A21_scale isa Float32 && M.A12_scale isa Float32 + @test M.A11.Base_scale isa Float32 + end + + @testset "a scaled off-diagonal block reads back unscaled" begin + A = fill(1.0, 4, 4) + A[3:4, 1:2] .= 1.0e5 + M = FullMixedPrec(A; precisions=DataType[Float16, Float64]) + @test M.A21_scale != 1 && M.A12_scale == 1 + @test reconstruct_matrix(M) ≈ A rtol=2mxp_u(Float16) + @test M[3, 1] ≈ 1.0e5 rtol=2mxp_u(Float16) + end + + # A leaf is stored in T_Base, so values past floatmax(T_Base) are kept as + # stored values times a scale; read back in T_Base they are Inf. + @testset "a leaf past floatmax of its type is stored with a scale" begin + A = fill(1.0e39, 4, 4) + 1.0e40I + M = FullMixedPrec(A; precisions=DataType[Float32]) + @test M.Base_scale != 1 + @test Float64.(M.Base) .* M.Base_scale ≈ A rtol=2mxp_u(Float32) + @test all(isinf, reconstruct_matrix(M)) + end + + @testset "typemin of an integer matrix is scaled, not stored as -Inf" begin + M = FullMixedPrec([1 0; typemin(Int) 1]; precisions=DataType[Float16, Float64]) + @test M.A21_scale > 1 && all(isfinite, M.A21) + R = reconstruct_matrix(M) + @test all(isfinite, R) + @test R[2, 1] ≈ Float64(typemin(Int)) rtol=2mxp_u(Float16) + end + + @testset "arguments are checked" begin + @test_throws DimensionMismatch FullMixedPrec(rand(4, 8); precisions=DataType[Float64]) + @test_throws ArgumentError FullMixedPrec(zeros(0, 0); precisions=DataType[Float64]) + @test_throws ArgumentError FullMixedPrec(rand(4, 4); precisions=DataType[]) + @test_throws ArgumentError FullMixedPrec(rand(4, 4); precisions=DataType[Int]) + @test_throws ArgumentError FullMixedPrec([1.0 NaN; 0.0 1.0]; precisions=DataType[Float64]) + @test_throws ArgumentError FullMixedPrec([1.0 Inf; 0.0 1.0]; precisions=DataType[Float64]) + @test_throws ArgumentError FullMixedPrec(fill(1.0e300, 4, 4); precisions=DataType[Float16, Float32]) + end + + @testset "out-of-bounds indexing throws" begin + M = FullMixedPrec(rand(8, 8); precisions=DataType[Float32, Float64]) + @test_throws BoundsError M[0, 1] + @test_throws BoundsError M[1, 9] + end +end + +# On each GPU backend: builds and reconstructs without scalar indexing. +@testset "FullMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + P = DataType[Float16, Float32, Float64] + + @testset "FullMixedPrec builds and reconstructs on the device" begin + A = mxp_rand(Float64, n, n) + M = FullMixedPrec(AT(A); precisions=P) + R = reconstruct_matrix(M) + @test R isa AT + @test eltype(M.A21) === Float16 && M.A21 isa AT + @test mxp_storage_ok(Array(R), A, mxp_eltype_map(M)) + end +end diff --git a/test/mxp/core/quantize.jl b/test/mxp/core/quantize.jl new file mode 100644 index 00000000..197b26ba --- /dev/null +++ b/test/mxp/core/quantize.jl @@ -0,0 +1,59 @@ +# quantize and dequantize, src/mxp/core/quantize.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "quantize and dequantize [CPU]" begin + Random.seed!(2047) + + @testset "to $T" for T in (Float16, NextLA.BFloat16, Float32) + A = mxp_rand(Float64, 32, 32) .* 1000 + q, s = quantize(A, T) + @test eltype(q) === T && s === 1f0 + back = dequantize(q, s, Float64) + @test mxp_storage_ok(back, A, fill(T, size(A))) + end + + @testset "the default type is Float16" begin + @test eltype(first(quantize(rand(Float32, 4, 4)))) === Float16 + end + + @testset "values past floatmax come back scaled, not saturated" begin + big = fill(1f5, 8, 8) + qb, sb = quantize(big) + @test sb > 1f0 + @test all(isfinite, Float32.(qb)) + @test dequantize(qb, sb, Float32) ≈ big rtol=2mxp_u(Float16) + end + + @testset "a zero matrix and an empty matrix" begin + z, sz = quantize(zeros(Float32, 4, 4)) + @test sz == 1f0 && all(iszero, z) + qe, se = quantize(zeros(Float64, 0, 3), Float16) + @test size(qe) == (0, 3) && eltype(qe) === Float16 + @test se === 1f0 + end + + @testset "a non-finite matrix throws" begin + @test_throws ArgumentError quantize([1.0 NaN]) + end + + @testset "dequantize converts before multiplying" begin + q3 = reshape(Float16[3], 1, 1) + @test dequantize(q3, 1.1f0, Float64)[1] == 3.0 * Float64(1.1f0) + @test (@inferred dequantize(q3, 1.1f0, Float64)) isa Matrix{Float64} + end +end + +# On each GPU backend: the result stays on the device. +@testset "quantize and dequantize [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + + @testset "quantize and dequantize stay on the device" begin + A = mxp_rand(Float64, n, n) + q, s = quantize(AT(A), Float16) + @test q isa AT && eltype(q) === Float16 + back = dequantize(q, s, Float64) + @test back isa AT + @test mxp_storage_ok(Array(back), A, fill(Float16, n, n)) + end +end diff --git a/test/mxp/core/symmmixedprec.jl b/test/mxp/core/symmmixedprec.jl new file mode 100644 index 00000000..1f9b2f05 --- /dev/null +++ b/test/mxp/core/symmmixedprec.jl @@ -0,0 +1,117 @@ +# SymmMixedPrec, src/mxp/core/symmmixedprec.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "SymmMixedPrec [CPU]" begin + Random.seed!(2047) + + @testset "$T, uplo=$uplo, n=$n, precisions=$P" for T in (Float32, Float64), uplo in ('L', 'U'), + n in (1, 7, 8, 13), P in (DataType[Float32, T], DataType[Float16, Float32, T], + DataType[NextLA.BFloat16, Float16, Float32, T]) + A = mxp_spd(T, n) + M = SymmMixedPrec(A, uplo; precisions=P) + @test size(M) == (n, n) + R = reconstruct_matrix(M) + @test eltype(R) === T + @test R == transpose(R) + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + @test transpose(M) === M + end + + @testset "one precision: a single leaf, $T, uplo=$uplo" for T in (Float32, Float64), uplo in ('L', 'U') + A = mxp_spd(T, 8) + M = SymmMixedPrec(A, uplo; precisions=DataType[T]) + @test M.Base !== nothing && M.OffDiag === nothing + @test reconstruct_matrix(M) == A + end + + # A leaf is stored in T_Base, so values past floatmax(T_Base) are kept as + # stored values times a scale; read back in T_Base they are Inf. + @testset "a leaf past floatmax of its type is stored with a scale, uplo=$uplo" for uplo in ('L', 'U') + A = fill(1.0e39, 4, 4) + 1.0e40I + M = SymmMixedPrec(A, uplo; precisions=DataType[Float32]) + @test M.Base_scale != 1 + @test Float64.(M.Base) .* M.Base_scale ≈ (uplo == 'L' ? tril(A) : triu(A)) rtol=2mxp_u(Float32) + @test all(isinf, reconstruct_matrix(M)) + end + + @testset "the other triangle is not read, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_spd(Float64, 8) + G = copy(A) + uplo == 'L' ? (G[1, 8] = NaN) : (G[8, 1] = NaN) + M = SymmMixedPrec(G, uplo; precisions=DataType[Float32, Float64]) + @test mxp_storage_ok(reconstruct_matrix(M), A, mxp_eltype_map(M)) + # and inside a leaf (A11 is a 4x4 leaf here), whose unread half is zeroed + # before it is stored + H = copy(A) + uplo == 'L' ? (H[1, 2] = NaN) : (H[2, 1] = NaN) + M = SymmMixedPrec(H, uplo; precisions=DataType[Float32, Float64]) + @test mxp_storage_ok(reconstruct_matrix(M), A, mxp_eltype_map(M)) + end + + @testset "a scaled off-diagonal block reads back unscaled, uplo=$uplo" for uplo in ('L', 'U') + A = ones(4, 4) + A[3:4, 1:2] .= 1.0e5 + A[1:2, 3:4] .= 1.0e5 + M = SymmMixedPrec(A, uplo; precisions=DataType[Float16, Float64]) + @test M.OffDiag_scale != 1 + @test reconstruct_matrix(M) ≈ A rtol=2mxp_u(Float16) + @test M[3, 1] ≈ 1.0e5 rtol=2mxp_u(Float16) + @test M[1, 3] ≈ 1.0e5 rtol=2mxp_u(Float16) + end + + # An input matrix of a 16-bit type (the leaves are Float32): every element is + # stored within one rounding of its block's type, and exactly where the block + # type is the input type. + @testset "$S input, uplo=$uplo, precisions=$P" for S in (Float16, NextLA.BFloat16), uplo in ('L', 'U'), + P in (DataType[Float16, Float32], DataType[NextLA.BFloat16, Float32]) + A = S.(mxp_spd(Float32, 13)) + M = SymmMixedPrec(A, uplo; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === Float32 + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + P[1] === S && @test R == Float32.(A) + end + + # A view as input (a principal submatrix of a symmetric matrix is symmetric): + # the same container as from a copy of the view. + @testset "a view as input, uplo=$uplo, precisions=$P" for uplo in ('L', 'U'), + P in (DataType[Float32, Float64], DataType[Float16, Float32, Float64]) + V = view(mxp_spd(Float64, 16), 2:14, 2:14) + M = SymmMixedPrec(V, uplo; precisions=P) + R = reconstruct_matrix(M) + @test R == reconstruct_matrix(SymmMixedPrec(copy(V), uplo; precisions=P)) + @test mxp_storage_ok(R, copy(V), mxp_eltype_map(M)) + end + + @testset "arguments are checked" begin + @test_throws ArgumentError SymmMixedPrec(rand(4, 4), 'X'; precisions=DataType[Float64]) + @test_throws DimensionMismatch SymmMixedPrec(rand(4, 8), 'L'; precisions=DataType[Float64]) + @test_throws BoundsError SymmMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float64])[5, 1] + end +end + +# On each GPU backend: built, stored and read back on the device. +@testset "SymmMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + P = DataType[Float16, Float32, Float64] + + @testset "builds and reconstructs on the device, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_spd(Float64, n) + M = SymmMixedPrec(AT(A), uplo; precisions=P) + @test M.OffDiag isa AT + R = reconstruct_matrix(M) + @test R isa AT + @test mxp_storage_ok(Array(R), A, mxp_eltype_map(M)) + end + + # One precision is no split: the whole matrix is a single leaf. + @testset "a single leaf reconstructs on the device, uplo=$uplo" for uplo in ('L', 'U') + M = SymmMixedPrec(AT(mxp_spd(Float64, n)), uplo; precisions=DataType[Float64]) + @test M.Base isa AT + R = reconstruct_matrix(M) + @test R isa AT + @test Array(R) == reconstruct_matrix(mxp_host(M)) + end +end diff --git a/test/mxp/core/tiledtrimixedprec.jl b/test/mxp/core/tiledtrimixedprec.jl new file mode 100644 index 00000000..3d05acd1 --- /dev/null +++ b/test/mxp/core/tiledtrimixedprec.jl @@ -0,0 +1,106 @@ +# TiledTriMixedPrec, src/mxp/core/tiledtrimixedprec.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "TiledTriMixedPrec [CPU]" begin + Random.seed!(2047) + + # The tile sizes are TriMixedPrec's split, n/2 for a power of 2 and else the + # largest power of 2 below n, stopped once a block has at most threshold rows. + @testset "uplo=$uplo, n=$n, threshold=$t, precisions=$P" for uplo in ('L', 'U'), + (n, t, sizes) in ((8, 4, [4, 4]), (8, 2, [2, 2, 2, 2]), (7, 3, [2, 2, 3]), + (13, 4, [4, 4, 4, 1]), (5, 1, [1, 1, 1, 1, 1]), (6, 6, [6])), + P in (DataType[Float32, Float64], DataType[Float16, Float64], DataType[NextLA.BFloat16, Float32], + DataType[Float64]) + A = mxp_tri(uplo, mxp_rand(Float64, n, n)) + M = TiledTriMixedPrec(A, uplo; precisions=P, threshold=t) + @test size(M) == (n, n) && size(M, 1) == n + @test size.(M.diag, 1) == sizes + R = reconstruct_matrix(M) + @test eltype(R) === P[end] + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + @test all(transpose(M)[i, j] == M[j, i] for i in 1:n, j in 1:n) + end + + @testset "a scaled tile reads back unscaled, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, ones(8, 8)) + uplo == 'L' ? (A[5:8, 1:4] .= 1.0e5) : (A[1:4, 5:8] .= 1.0e5) + M = TiledTriMixedPrec(A, uplo; precisions=DataType[Float16, Float64], threshold=4) + @test M.off_scales[uplo == 'L' ? CartesianIndex(2, 1) : CartesianIndex(1, 2)] != 1 + @test reconstruct_matrix(M) ≈ A rtol=2mxp_u(Float16) + end + + # Tiles are stored in their type, so values past its floatmax are kept as + # stored values times a scale; read back in T_Diag they are Inf in the stored + # triangle, and the other triangle stays zero. + @testset "a diagonal tile past floatmax of its type is stored with a scale, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, fill(1.0e39, 8, 8)) + 1.0e40I + M = TiledTriMixedPrec(A, uplo; precisions=DataType[Float32, Float32], threshold=4) + @test all(!=(1), M.diag_scales) + @test Float64.(M.diag[2]) .* M.diag_scales[2] ≈ mxp_tri(uplo, A[5:8, 5:8]) rtol=2mxp_u(Float32) + R = reconstruct_matrix(M) + @test all(isinf(R[i, j]) for i in 1:8, j in 1:8 if (uplo == 'L' ? i >= j : i <= j)) + @test all(iszero(R[i, j]) for i in 1:8, j in 1:8 if (uplo == 'L' ? i < j : i > j)) + end + + # A full input keeps only its uplo triangle; a NaN in the other triangle, in an + # off-diagonal tile and inside a diagonal tile, is never read. + @testset "only the uplo triangle of a full input is read, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_rand(Float64, 8, 8) + G = copy(A) + uplo == 'L' ? (G[1, 8] = NaN; G[1, 2] = NaN) : (G[8, 1] = NaN; G[2, 1] = NaN) + M = TiledTriMixedPrec(G, uplo; precisions=DataType[Float32, Float64], threshold=4) + @test mxp_storage_ok(reconstruct_matrix(M), mxp_tri(uplo, A), mxp_eltype_map(M)) + end + + # An input matrix of a 16-bit type (diagonal tiles are Float32): every element + # is stored within one rounding of its tile's type, and exactly where the + # off-diagonal type is the input type. + @testset "$S input, uplo=$uplo, precisions=$P" for S in (Float16, NextLA.BFloat16), uplo in ('L', 'U'), + P in (DataType[Float16, Float32], DataType[NextLA.BFloat16, Float32]) + A = S.(mxp_tri(uplo, mxp_rand(Float32, 13, 13))) + M = TiledTriMixedPrec(A, uplo; precisions=P, threshold=4) + R = reconstruct_matrix(M) + @test eltype(R) === Float32 + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + P[1] === S && @test R == Float32.(A) + end + + # A view as input: the same container as from a copy of the view. + @testset "a view as input, uplo=$uplo, precisions=$P" for uplo in ('L', 'U'), + P in (DataType[Float32, Float64], DataType[Float16, Float64]) + V = view(mxp_rand(Float64, 16, 16), 2:14, 3:15) + M = TiledTriMixedPrec(V, uplo; precisions=P, threshold=4) + R = reconstruct_matrix(M) + @test R == reconstruct_matrix(TiledTriMixedPrec(copy(V), uplo; precisions=P, threshold=4)) + @test mxp_storage_ok(R, mxp_tri(uplo, copy(V)), mxp_eltype_map(M)) + end + + @testset "arguments are checked" begin + A = tril(rand(8, 8)) + @test_throws ArgumentError TiledTriMixedPrec(A, 'X'; precisions=DataType[Float64], threshold=2) + @test_throws ArgumentError TiledTriMixedPrec(A, 'L'; precisions=DataType[Float64], threshold=0) + @test_throws ArgumentError TiledTriMixedPrec(A, 'L'; precisions=DataType[Float16, Float32, Float64], threshold=2) + @test_throws DimensionMismatch TiledTriMixedPrec(rand(4, 8), 'L'; precisions=DataType[Float64], threshold=2) + end + + @testset "out-of-bounds indexing throws" begin + M = TiledTriMixedPrec(tril(rand(8, 8)), 'L'; precisions=DataType[Float32, Float64], threshold=2) + @test_throws BoundsError M[0, 1] + @test_throws BoundsError M[9, 1] + end +end + +# On each GPU backend: built and read back on the device. +@testset "TiledTriMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + + @testset "builds and reconstructs on the device, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, mxp_rand(Float64, n, n)) + M = TiledTriMixedPrec(AT(A), uplo; precisions=DataType[Float16, Float64], threshold=4) + R = reconstruct_matrix(M) + @test R isa AT + @test mxp_storage_ok(Array(R), A, mxp_eltype_map(M)) + end +end diff --git a/test/mxp/core/transposedmixedprec.jl b/test/mxp/core/transposedmixedprec.jl new file mode 100644 index 00000000..197e2ab7 --- /dev/null +++ b/test/mxp/core/transposedmixedprec.jl @@ -0,0 +1,50 @@ +# The lazy transpose and adjoint, src/mxp/core/transposedmixedprec.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "TransposedMixedPrec [CPU]" begin + Random.seed!(2047) + + # Each element of the wrapper is the container's element at the swapped index, + # exactly. For TriMixedPrec the stored triangle moves to the other side and the + # rest reads zero. n = 13 with three types is three levels. + @testset "$(nameof(kind))$(uplo === nothing ? "" : " uplo=$uplo"), n=$n, precisions=$P, $f" for + (kind, uplo, n, P) in ((FullMixedPrec, nothing, 8, DataType[Float32, Float64]), + (FullMixedPrec, nothing, 13, DataType[Float16, Float32, Float64]), + (TriMixedPrec, 'L', 13, DataType[Float16, Float32, Float64]), + (TriMixedPrec, 'U', 13, DataType[Float16, Float32, Float64])), + f in (transpose, adjoint) + A = mxp_rand(Float64, n, n) + M = kind === FullMixedPrec ? FullMixedPrec(A; precisions=P) : TriMixedPrec(A, uplo; precisions=P) + Mᵀ = f(M) + @test parent(Mᵀ) === M + @test transpose(Mᵀ) === M + @test adjoint(Mᵀ) === M + @test size(Mᵀ) == reverse(size(M)) + @test eltype(Mᵀ) === eltype(M) + @test all(Mᵀ[i, j] == M[j, i] for i in 1:n, j in 1:n) + if kind === TriMixedPrec + @test all(iszero(Mᵀ[i, j]) for i in 1:n, j in 1:n if (uplo == 'L' ? i > j : i < j)) + end + @test_throws BoundsError Mᵀ[n + 1, 1] + end +end + +# On each GPU backend: wrapping a device container copies nothing and keeps its +# type. (Reading one element of a device container is scalar indexing, which is +# not supported, so no element is read here.) +@testset "TransposedMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + P = DataType[Float16, Float32, Float64] + + @testset "$(nameof(kind)), $f" for kind in (FullMixedPrec, TriMixedPrec), f in (transpose, adjoint) + A = AT(mxp_rand(Float64, n, n)) + M = kind === FullMixedPrec ? FullMixedPrec(A; precisions=P) : TriMixedPrec(A, 'U'; precisions=P) + Mᵀ = f(M) + @test parent(Mᵀ) === M + @test transpose(Mᵀ) === M + @test adjoint(Mᵀ) === M + @test size(Mᵀ) == (n, n) + @test eltype(Mᵀ) === eltype(M) + end +end diff --git a/test/mxp/core/trimixedprec.jl b/test/mxp/core/trimixedprec.jl new file mode 100644 index 00000000..ce3427ad --- /dev/null +++ b/test/mxp/core/trimixedprec.jl @@ -0,0 +1,148 @@ +# TriMixedPrec, src/mxp/core/trimixedprec.jl. +# Helpers and error bounds: test/setup/mxp.jl. + +@testset "TriMixedPrec [CPU]" begin + Random.seed!(2047) + + @testset "$T, uplo=$uplo, n=$n, precisions=$P" for T in (Float32, Float64), uplo in ('L', 'U'), + n in (1, 7, 8, 13), P in (DataType[Float32, T], DataType[Float16, Float32, T], + DataType[NextLA.BFloat16, Float16, Float32, T]) + A = mxp_tri(uplo, mxp_rand(T, n, n)) + M = TriMixedPrec(A, uplo; precisions=P) + @test size(M) == (n, n) + R = reconstruct_matrix(M) + @test eltype(R) === T + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + end + + @testset "one precision: a single leaf, $T, uplo=$uplo" for T in (Float32, Float64), uplo in ('L', 'U') + A = mxp_tri(uplo, mxp_rand(T, 8, 8)) + M = TriMixedPrec(A, uplo; precisions=DataType[T]) + @test M.Base !== nothing && M.OffDiag === nothing + @test reconstruct_matrix(M) == A + end + + # A leaf is stored in T_Base, so values past floatmax(T_Base) are kept as + # stored values times a scale; read back in T_Base they are Inf in the stored + # triangle, and the other triangle stays zero. + @testset "a leaf past floatmax of its type is stored with a scale, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, fill(1.0e39, 4, 4)) + 1.0e40I + M = TriMixedPrec(A, uplo; precisions=DataType[Float32]) + @test M.Base_scale != 1 + @test Float64.(M.Base) .* M.Base_scale ≈ A rtol=2mxp_u(Float32) + R = reconstruct_matrix(M) + @test all(isinf(R[i, j]) for i in 1:4, j in 1:4 if (uplo == 'L' ? i >= j : i <= j)) + @test all(iszero(R[i, j]) for i in 1:4, j in 1:4 if (uplo == 'L' ? i < j : i > j)) + end + + # A NaN in the unread triangle, in the other off-diagonal block and inside a + # leaf (A11 is a 4x4 leaf here), is never read. + @testset "the other triangle is not read, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, mxp_rand(Float64, 8, 8)) + G = copy(A) + uplo == 'L' ? (G[1, 8] = NaN; G[1, 2] = NaN) : (G[8, 1] = NaN; G[2, 1] = NaN) + M = TriMixedPrec(G, uplo; precisions=DataType[Float32, Float64]) + @test mxp_storage_ok(reconstruct_matrix(M), A, mxp_eltype_map(M)) + end + + @testset "every block is a copy of A, uplo=$uplo, precisions=$P" for uplo in ('L', 'U'), + P in (DataType[Float64], DataType[Float32, Float64]) + A = mxp_tri(uplo, mxp_rand(Float64, 8, 8)) + M = TriMixedPrec(A, uplo; precisions=P) + R = reconstruct_matrix(M) + A .= 0 + @test reconstruct_matrix(M) == R + end + + @testset "only the uplo triangle of a full input is kept, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_rand(Float64, 8, 8) + M = TriMixedPrec(A, uplo; precisions=DataType[Float32, Float64]) + @test mxp_storage_ok(reconstruct_matrix(M), mxp_tri(uplo, A), mxp_eltype_map(M)) + end + + @testset "converts from SymmMixedPrec without copying, uplo=$uplo" for uplo in ('L', 'U') + n = 13 + S = SymmMixedPrec(mxp_spd(Float64, n), uplo; precisions=DataType[Float16, Float32, Float64]) + M = TriMixedPrec(S) + @test size(M) == size(S) && M.uplo == uplo + @test M.OffDiag === S.OffDiag && M.A11.OffDiag === S.A11.OffDiag + @test all(M[i, j] == S[i, j] for i in 1:n, j in 1:n if (uplo == 'L' ? i >= j : i <= j)) + @test all(iszero(M[i, j]) for i in 1:n, j in 1:n if (uplo == 'L' ? i < j : i > j)) + end + + @testset "converting from SymmMixedPrec keeps the scales, uplo=$uplo" for uplo in ('L', 'U') + A = ones(4, 4) + A[3:4, 1:2] .= 1.0e5 + A[1:2, 3:4] .= 1.0e5 + S = SymmMixedPrec(A, uplo; precisions=DataType[Float16, Float64]) + M = TriMixedPrec(S) + @test M.OffDiag_scale == S.OffDiag_scale != 1 + @test reconstruct_matrix(M) ≈ mxp_tri(uplo, A) rtol=2mxp_u(Float16) + L = SymmMixedPrec(fill(1.0e39, 4, 4) + 1.0e40I, uplo; precisions=DataType[Float32]) + ML = TriMixedPrec(L) + @test ML.Base === L.Base && ML.Base_scale == L.Base_scale != 1 + end + + @testset "a scaled off-diagonal block reads back unscaled, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, ones(4, 4)) + uplo == 'L' ? (A[3:4, 1:2] .= 1.0e5) : (A[1:2, 3:4] .= 1.0e5) + M = TriMixedPrec(A, uplo; precisions=DataType[Float16, Float64]) + @test M.OffDiag_scale != 1 + @test reconstruct_matrix(M) ≈ A rtol=2mxp_u(Float16) + end + + # An input matrix of a 16-bit type (the leaves are Float32): every element is + # stored within one rounding of its block's type, and exactly where the block + # type is the input type. + @testset "$S input, uplo=$uplo, precisions=$P" for S in (Float16, NextLA.BFloat16), uplo in ('L', 'U'), + P in (DataType[Float16, Float32], DataType[NextLA.BFloat16, Float32]) + A = S.(mxp_tri(uplo, mxp_rand(Float32, 13, 13))) + M = TriMixedPrec(A, uplo; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === Float32 + @test mxp_storage_ok(R, A, mxp_eltype_map(M)) + P[1] === S && @test R == Float32.(A) + end + + # A view as input: the same container as from a copy of the view. + @testset "a view as input, uplo=$uplo, precisions=$P" for uplo in ('L', 'U'), + P in (DataType[Float32, Float64], DataType[Float16, Float32, Float64]) + V = view(mxp_rand(Float64, 16, 16), 2:14, 3:15) + M = TriMixedPrec(V, uplo; precisions=P) + R = reconstruct_matrix(M) + @test R == reconstruct_matrix(TriMixedPrec(copy(V), uplo; precisions=P)) + @test mxp_storage_ok(R, mxp_tri(uplo, copy(V)), mxp_eltype_map(M)) + end + + @testset "arguments are checked" begin + @test_throws ArgumentError TriMixedPrec(rand(4, 4), 'X'; precisions=DataType[Float64]) + @test_throws DimensionMismatch TriMixedPrec(rand(4, 8), 'L'; precisions=DataType[Float64]) + @test_throws BoundsError TriMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float64])[1, 0] + end +end + +# On each GPU backend: built, stored and read back on the device. +@testset "TriMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2048) + n = 13 + P = DataType[Float16, Float32, Float64] + + @testset "builds and reconstructs on the device, uplo=$uplo" for uplo in ('L', 'U') + A = mxp_tri(uplo, mxp_rand(Float64, n, n)) + M = TriMixedPrec(AT(A), uplo; precisions=P) + @test M.OffDiag isa AT + R = reconstruct_matrix(M) + @test R isa AT + @test mxp_storage_ok(Array(R), A, mxp_eltype_map(M)) + end + + # One precision is no split: the whole matrix is a single leaf. + @testset "a single leaf reconstructs on the device, uplo=$uplo" for uplo in ('L', 'U') + M = TriMixedPrec(AT(mxp_spd(Float64, n)), uplo; precisions=DataType[Float64]) + @test M.Base isa AT + R = reconstruct_matrix(M) + @test R isa AT + @test Array(R) == reconstruct_matrix(mxp_host(M)) + end +end diff --git a/test/mxp/gemm/recgemm_mixedprec.jl b/test/mxp/gemm/recgemm_mixedprec.jl deleted file mode 100644 index 9e3f6f6e..00000000 --- a/test/mxp/gemm/recgemm_mixedprec.jl +++ /dev/null @@ -1,113 +0,0 @@ -using NextLA.MixedPrecision -# recgemm! into a FullMixedPrec destination. CPU only: the container walks -# with scalar indexing on the host, the limitation recorded for src/mxp/. - -@testset "RECGEMM mixed precision [CPU]" begin - Random.seed!(2049) - - @testset "FullMixedPrec destination, n=$n" for n in [5, 8, 13, 16] - T = Float32 - A = rand(T, n, n) - B = rand(T, n, n) - C_dense = rand(T, n, n) - alpha, beta = T(1.5), T(0.5) - expected = alpha * A * B + beta * C_dense - - C_mp = FullMixedPrec(C_dense; precisions=DataType[Float32, Float32]) - @test recgemm!(alpha, A, B, beta, C_mp) === C_mp - @test reconstruct_matrix(C_mp) ≈ expected rtol=1e-4 - end - - @testset "a leaf C takes A n×k and B k×n, k=$k" for k in [1, 3, 8, 20] - n = 8 - A = rand(Float64, n, k) - B = rand(Float64, k, n) - C_dense = rand(Float64, n, n) - C_mp = FullMixedPrec(copy(C_dense); precisions=DataType[Float64]) - recgemm!(1.0, A, B, 1.0, C_mp) - @test reconstruct_matrix(C_mp) ≈ A * B + C_dense rtol=1e-12 - end - - @testset "a split C takes any k, k=$k" for k in [1, 3, 20] - n = 8 - A, B, C_dense = rand(n, k), rand(k, n), rand(n, n) - C_mp = FullMixedPrec(copy(C_dense); precisions=DataType[Float64, Float64, Float64]) - recgemm!(1.0, A, B, 1.0, C_mp) - @test reconstruct_matrix(C_mp) ≈ A * B + C_dense rtol=1e-12 - end - - @testset "an uneven split at every level, n=$n" for n in [5, 13, 100] - # n = 13 splits 8 + 5 and 5 splits 4 + 1, so no level has equal halves. - A, B, C_dense = rand(n, n), rand(n, n), rand(n, n) - C_mp = FullMixedPrec(copy(C_dense); precisions=DataType[Float64, Float64, Float64, Float64]) - recgemm!(1.0, A, B, 1.0, C_mp) - @test reconstruct_matrix(C_mp) ≈ A * B + C_dense rtol=1e-12 - end - - @testset "Float16 off-diagonal blocks" begin - n = 16 - A = rand(Float32, n, n) - B = rand(Float32, n, n) - C_dense = rand(Float32, n, n) - C_mp = FullMixedPrec(C_dense; precisions=DataType[Float16, Float32]) - expected = A * B + C_dense - recgemm!(1f0, A, B, 1f0, C_mp) - @test eltype(C_mp.A21) === Float16 - @test reconstruct_matrix(C_mp) ≈ expected rtol=1e-2 - end - - @testset "a scaled block takes alpha divided by its scale" begin - n = 8 - C_dense = ones(Float64, n, n) - C_dense[5:8, 1:4] .= 1.0e5 - C_mp = FullMixedPrec(copy(C_dense); precisions=DataType[Float16, Float64]) - @test C_mp.A21_scale != 1 - A = rand(Float64, n, n) - B = rand(Float64, n, n) - expected = -100 * A * B + C_dense - recgemm!(-100.0, A, B, 1.0, C_mp) - @test reconstruct_matrix(C_mp) ≈ expected rtol=1e-2 - end - - @testset "beta = 0 overwrites C" begin - n = 8 - A = rand(Float64, n, n) - B = rand(Float64, n, n) - C_mp = FullMixedPrec(rand(Float64, n, n); precisions=DataType[Float32, Float64]) - recgemm!(1.0, A, B, 0.0, C_mp) - @test reconstruct_matrix(C_mp) ≈ A * B rtol=1e-5 - end - - @testset "parallel and sequential agree" begin - n = 16 - T = Float32 - A = rand(T, n, n) - B = rand(T, n, n) - C_dense = rand(T, n, n) - - C_seq = FullMixedPrec(copy(C_dense); precisions=DataType[Float32, Float32]) - C_par = FullMixedPrec(copy(C_dense); precisions=DataType[Float32, Float32]) - recgemm!(one(T), A, B, one(T), C_seq; parallel=false) - recgemm!(one(T), A, B, one(T), C_par; parallel=true) - - @test reconstruct_matrix(C_seq) ≈ reconstruct_matrix(C_par) rtol=1e-5 - end - - @testset "mismatched shapes throw DimensionMismatch" begin - C_mp = FullMixedPrec(rand(8, 8); precisions=DataType[Float64]) - @test_throws DimensionMismatch recgemm!(1.0, rand(7, 4), rand(4, 8), 1.0, C_mp) - @test_throws DimensionMismatch recgemm!(1.0, rand(8, 4), rand(4, 7), 1.0, C_mp) - @test_throws DimensionMismatch recgemm!(1.0, rand(8, 4), rand(5, 8), 1.0, C_mp) - end -end - -# An update past floatmax of a Float16 off-diagonal block raises the block's -# scale, so the result stays finite where a fixed scale left Inf. -@testset "RECGEMM mixed precision re-scales an overflowing block [CPU]" begin - C_mp = FullMixedPrec(zeros(4, 4); precisions = DataType[Float16, Float32]) - A, B = fill(1000.0, 4, 4), fill(1000.0, 4, 4) - recgemm!(1.0, A, B, 0.0, C_mp) - @test C_mp.A12_scale > 1 && C_mp.A21_scale > 1 - @test all(isfinite, reconstruct_matrix(C_mp)) - @test reconstruct_matrix(C_mp) ≈ A * B rtol=1e-2 -end diff --git a/test/mxp/lapack/cholesky/recpotrf_mixedprec.jl b/test/mxp/lapack/cholesky/recpotrf_mixedprec.jl new file mode 100644 index 00000000..c771ed24 --- /dev/null +++ b/test/mxp/lapack/cholesky/recpotrf_mixedprec.jl @@ -0,0 +1,64 @@ +# potrf_recursive! over a SymmMixedPrec container, +# src/mxp/lapack/cholesky/recpotrf_mixedprec.jl. Checked by the backward error +# ‖A - LLᵀ‖/‖A‖ (Higham 2002, Thm 10.3) against the bound of test/setup/mxp.jl for +# the narrowest precision. + +const MXP_POTRF_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[NextLA.BFloat16, Float32], DataType[Float16, Float32, Float64], + DataType[NextLA.BFloat16, Float16, Float32, Float64]) + +_mxp_factor(A) = reconstruct_matrix(TriMixedPrec(A)) + +@testset "POTRF_RECURSIVE mixed precision [CPU]" begin + Random.seed!(2057) + + @testset "precisions=$P, uplo=$uplo, n=$n, block_size=$bs" for P in MXP_POTRF_PRECISIONS, uplo in ('L', 'U'), + n in (13, 32, 40, 64), bs in (8, 4096) + T = P[end] + A0 = mxp_spd(T, n) + A = SymmMixedPrec(copy(A0), uplo; precisions=P) + @test potrf_recursive!(A, bs) === A + F = _mxp_factor(A) + @test uplo == 'L' ? istril(F) : istriu(F) + @test mxp_chol_backward_error(F, Float64.(A0), uplo) <= mxp_tol(mxp_narrowest(P), n) + end + + # A leaf no larger than block_size is factored by potrf!, whose info turns into + # PosDefException. A larger leaf goes through the dense potrf_recursive!. + @testset "a matrix that is not positive definite throws, uplo=$uplo, block_size=$bs" for uplo in ('L', 'U'), + bs in (2, 4096) + A = SymmMixedPrec(-Matrix{Float64}(I, 8, 8), uplo; precisions=DataType[Float32, Float64]) + @test_throws PosDefException potrf_recursive!(A, bs) + end + + @testset "a leaf stored with a scale factor throws" begin + A = SymmMixedPrec(1.0e39 * ones(4, 4) + 1.0e40I, 'L'; precisions=DataType[Float32]) + @test A.Base_scale != 1 + @test_throws ArgumentError potrf_recursive!(A) + end + + # reconstruct_matrix of the factored container mirrors the factor into both + # triangles; TriMixedPrec(A) reads the factor alone. + @testset "the factor is read through TriMixedPrec, uplo=$uplo" for uplo in ('L', 'U') + A = SymmMixedPrec(mxp_spd(Float64, 16), uplo; precisions=DataType[Float32, Float64]) + potrf_recursive!(A) + F, R = _mxp_factor(A), reconstruct_matrix(A) + @test mxp_tri(uplo, R) == F + @test R == transpose(R) + end +end + +# On a GPU: the factorization runs on the device; the factor is read through a +# host copy of the container and checked on the CPU. +@testset "POTRF_RECURSIVE mixed precision [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + Random.seed!(2058) + @testset "precisions=$P, uplo=$uplo" for P in (DataType[Float32, Float32], DataType[Float16, Float32, Float64]), + uplo in ('L', 'U') + n = 64 + T = P[end] + A0 = mxp_spd(T, n) + A = SymmMixedPrec(AT(A0), uplo; precisions=P) + potrf_recursive!(A, 8) + @test mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(A0), uplo) <= mxp_tol(mxp_narrowest(P), n) + end +end diff --git a/test/mxp/lapack/lu/reclu_mixedprec.jl b/test/mxp/lapack/lu/reclu_mixedprec.jl new file mode 100644 index 00000000..4c7ef99c --- /dev/null +++ b/test/mxp/lapack/lu/reclu_mixedprec.jl @@ -0,0 +1,75 @@ +# lu_recursive! over a FullMixedPrec matrix, src/mxp/lapack/lu/reclu_mixedprec.jl. +# Checked by the backward error ‖A - LU‖/‖A‖ (Higham 2002, Thm 9.3) on diagonally +# dominant matrices, which need no pivoting and keep ‖|L||U|‖ ≈ ‖A‖ (§9.5), against +# the bound of test/setup/mxp.jl for the narrowest precision. The entry points of +# unified_rectrxm! it uses are tested in test/mxp/blas/trsm/rectrxm_mixed.jl. + +const MXP_LU_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[NextLA.BFloat16, Float32], DataType[Float16, Float32, Float64], + DataType[NextLA.BFloat16, Float16, Float32, Float64]) + +@testset "RECLU mixed precision [$name]" for (name, AT, _) in MXP_BACKENDS + Random.seed!(2053) + + @testset "precisions=$P, n=$n, block_size=$bs" for P in MXP_LU_PRECISIONS, n in (13, 32, 50, 100), bs in (8, 64) + T = P[end] + A0 = mxp_diagdom(T, n) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=P) + @test lu_recursive!(A, bs) === A + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(mxp_narrowest(P), n) + end + + @testset "the default block size" begin + A0 = mxp_diagdom(Float32, 64) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float32]) + lu_recursive!(A) + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, 64) + end + + # The two off-diagonal solves of a level write disjoint blocks, so the threaded + # run does the same arithmetic as the sequential one and gives the same bits. + @testset "parallel=false and parallel=true give the same factors" begin + A0 = mxp_diagdom(Float64, 64) + a = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float32, Float64]) + b = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float32, Float64]) + lu_recursive!(a, 8; parallel=true) + lu_recursive!(b, 8; parallel=false) + @test Array(reconstruct_matrix(a)) == Array(reconstruct_matrix(b)) + end + + @testset "two large Float32 scales do not overflow the trailing update" begin + n = 8 + A0 = rand(n, n) .* 2.0e24 + 1.0e27I + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float64]) + @test isinf(A.A21_scale * A.A12_scale) + lu_recursive!(A, 4) + R = reconstruct_matrix(A) + @test all(isfinite, Array(R)) + @test mxp_lu_backward_error(R, A0) <= mxp_tol(Float16, n) + end + + @testset "a leaf stored with a scale factor throws" begin + A = FullMixedPrec(mxp_on(AT, fill(1.0e39, 4, 4) + 1.0e40I); precisions=DataType[Float32]) + @test A.Base_scale != 1 + @test_throws ArgumentError lu_recursive!(A) + end +end + +@testset "RECLU mixed precision, other entry points [CPU]" begin + Random.seed!(2054) + + @testset "the dense method still takes a dense matrix" begin + A0 = mxp_diagdom(Float64, 16) + A = copy(A0) + lu_recursive!(A, 4) + @test mxp_lu_backward_error(A, A0) <= mxp_tol(Float64, 16) + end + + # Above RECLU_PARALLEL_THRESHOLD (512) the default is parallel. + @testset "default parallel above the threshold" begin + A0 = mxp_diagdom(Float32, 520) + A = FullMixedPrec(copy(A0); precisions=DataType[Float16, Float32]) + lu_recursive!(A) + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, 520) + end +end diff --git a/test/mxp/lu/reclu_mixedprec.jl b/test/mxp/lu/reclu_mixedprec.jl deleted file mode 100644 index 1e61e60c..00000000 --- a/test/mxp/lu/reclu_mixedprec.jl +++ /dev/null @@ -1,141 +0,0 @@ -using NextLA.MixedPrecision -# lu_recursive! over a FullMixedPrec matrix, and the unified_rectrxm! entry -# points it reaches the container through. CPU only. - -_mxp_lu_err(R, A0) = norm(UnitLowerTriangular(R) * UpperTriangular(R) - A0) / norm(A0) - -@testset "RECLU mixed precision [CPU]" begin - Random.seed!(2053) - - @testset "lu_recursive! n=$n" for n in [32, 50, 64] - T = Float32 - A0 = rand(T, n, n) + T(2n) * I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float32, Float32]) - - @test lu_recursive!(mp, 16) === mp - @test _mxp_lu_err(reconstruct_matrix(mp), A0) < 1e-3 - end - - @testset "an uneven split with a split trailing block, n=$n" for n in [12, 50, 100] - # n = 50 splits 32 + 18: the trailing update multiplies an 18×32 block by a 32×18 - # one into A22, which is split again. - A0 = rand(Float64, n, n) + 2n * I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float64, Float64, Float64]) - lu_recursive!(mp, 8) - @test _mxp_lu_err(reconstruct_matrix(mp), A0) < 1e-12 - end - - @testset "the dense method still takes a dense matrix" begin - A0 = rand(Float64, 16, 16) + 32I - A = copy(A0) - lu_recursive!(A, 4) - @test _mxp_lu_err(A, A0) < 1e-12 - end - - @testset "Float16 off-diagonal blocks" begin - n = 32 - A0 = rand(Float32, n, n) + Float32(2n) * I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float16, Float32]) - lu_recursive!(mp, 8) - @test _mxp_lu_err(reconstruct_matrix(mp), A0) < 1e-2 - end - - @testset "parallel=false gives the same factors as parallel=true" begin - A0 = rand(Float64, 64, 64) + 128I - a = FullMixedPrec(copy(A0); precisions = DataType[Float16, Float32, Float64]) - b = FullMixedPrec(copy(A0); precisions = DataType[Float16, Float32, Float64]) - lu_recursive!(a, 8; parallel=true) - lu_recursive!(b, 8; parallel=false) - @test reconstruct_matrix(a) ≈ reconstruct_matrix(b) rtol=1e-12 - @test _mxp_lu_err(reconstruct_matrix(b), A0) < 1e-2 - end - - @testset "two large Float32 scales do not overflow the trailing update" begin - n = 8 - A0 = rand(n, n) .* 2.0e24 + 1.0e27I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float16, Float64]) - @test isinf(mp.A21_scale * mp.A12_scale) - lu_recursive!(mp, 4) - @test all(isfinite, reconstruct_matrix(mp)) - @test _mxp_lu_err(reconstruct_matrix(mp), A0) < 1e-2 - end - - @testset "a leaf stored with a scale factor throws" begin - mp = FullMixedPrec(fill(1.0e39, 4, 4) + 1.0e40I; precisions = DataType[Float32]) - @test mp.Base_scale != 1 - @test_throws ArgumentError lu_recursive!(mp) - end - - # lu_recursive! reaches the container through unified_rectrxm!'s - # mixed-precision methods. Without them the call dies with - # "Implement KernelAbstractions.get_backend(::FullMixedPrec)", so assert - # that entry point exists rather than only exercising it indirectly. - @testset "mixed-precision entry point dispatches" begin - n = 32 - A0 = rand(Float32, n, n) + 32f0 * I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float32, Float32]) - B = rand(Float32, n, 4) - ref = copy(B) - LinearAlgebra.BLAS.trsm!('L', 'L', 'N', 'U', 1f0, A0, ref) - - Bm = copy(B) - @test unified_rectrxm!('L', 'L', 'N', 'U', 1f0, 'S', mp, Bm) === Bm - @test norm(Bm - ref) / norm(ref) < 1e-3 - end - - @testset "entry point: side=$side trans=$trans func=$func" for side in ('L', 'R'), trans in ('N', 'T'), func in ('S', 'M') - n = 32 - A0 = tril(rand(Float32, n, n)) + 32f0 * I - mp = TriMixedPrec(A0, 'L'; precisions = DataType[Float32, Float32]) - B = side == 'L' ? rand(Float32, n, 4) : rand(Float32, 4, n) - ref = Float64.(B) - if func == 'S' - LinearAlgebra.BLAS.trsm!(side, 'L', trans, 'N', 2.0, Float64.(A0), ref) - else - LinearAlgebra.BLAS.trmm!(side, 'L', trans, 'N', 2.0, Float64.(A0), ref) - end - Bm = copy(B) - unified_rectrxm!(side, 'L', trans, 'N', 2f0, func, mp, Bm) - @test norm(Bm - ref) / norm(ref) < 1e-4 - end - - @testset "entry point without diag takes 'N'" begin - n = 16 - A0 = tril(rand(Float32, n, n)) + 16f0 * I - mp = TriMixedPrec(A0, 'L'; precisions = DataType[Float32, Float32]) - B = rand(Float32, n, 3) - B1, B2 = copy(B), copy(B) - unified_rectrxm!('L', 'L', 'N', 1f0, 'S', mp, B1) - unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', mp, B2) - @test B1 == B2 - end - - @testset "entry point checks its flags" begin - mp = TriMixedPrec(tril(rand(Float32, 8, 8)) + 8f0 * I, 'L'; precisions = DataType[Float32]) - B = rand(Float32, 8, 2) - @test_throws ArgumentError unified_rectrxm!('X', 'L', 'N', 'N', 1f0, 'S', mp, B) - @test_throws ArgumentError unified_rectrxm!('L', 'X', 'N', 'N', 1f0, 'S', mp, B) - @test_throws ArgumentError unified_rectrxm!('L', 'L', 'X', 'N', 1f0, 'S', mp, B) - @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'X', 1f0, 'S', mp, B) - @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'X', mp, B) - end -end - -# A solve that takes a Float16 block past floatmax(Float16) stores it back with -# a raised scale instead of Inf. -@testset "a solve that outgrows a Float16 block raises its scale [CPU]" begin - blk = fill(Float16(100), 2, 2) - s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1000), blk, 1f0, Float32) - @test s > 1 && all(isfinite, blk) - @test Float32.(blk) .* s ≈ fill(1f5, 2, 2) rtol=2e-3 - same = fill(1f0, 2, 2) - @test MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 2), same, 1f0, Float32) == 1f0 - @test same == fill(2f0, 2, 2) -end - -# A solve that takes a Float32 block past what a Float32 scale can carry throws -# instead of storing Inf. -@testset "a solve past what the scale can carry throws [CPU]" begin - blk = fill(1f0, 2, 2) - @test_throws ArgumentError MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1e80), blk, 1f0, Float64) -end diff --git a/test/mxp/mxp.jl b/test/mxp/mxp.jl deleted file mode 100644 index 9c6b18be..00000000 --- a/test/mxp/mxp.jl +++ /dev/null @@ -1,353 +0,0 @@ -using NextLA.MixedPrecision - -const MXP_TYPES = (Float32, Float64) - -@testset "MXP [CPU]" begin - Random.seed!(2047) - - - @testset "FullMixedPrec" begin - @testset "$T" for T in MXP_TYPES - @testset "n=$n" for n in (4, 5, 8, 13, 16) - A = rand(T, n, n) - - @testset "single precision level round-trips exactly" begin - M = FullMixedPrec(A; precisions=DataType[T]) - @test size(M) == (n, n) - @test reconstruct_matrix(M) == A - end - - @testset "two levels round-trip within the coarser precision" begin - M = FullMixedPrec(A; precisions=DataType[Float32, T]) - @test size(M) == (n, n) - @test eltype(reconstruct_matrix(M)) === T - @test reconstruct_matrix(M) ≈ A rtol=test_rtol(Float32) - end - - @testset "indexing agrees with the dense original" begin - M = FullMixedPrec(A; precisions=DataType[Float32, T]) - @test all(isapprox(M[i, j], A[i, j]; rtol=test_rtol(Float32)) - for i in 1:n, j in 1:n) - @test M[1, 1] isa T - end - end - end - - @testset "three levels with Float16 off-diagonal blocks" begin - A = rand(Float64, 16, 16) - M = FullMixedPrec(A; precisions=DataType[Float16, Float32, Float64]) - @test eltype(M.A21) === Float16 - @test eltype(M.A11.A21) === Float32 - @test reconstruct_matrix(M) ≈ A rtol=1e-3 - end - - @testset "every scale is Float32" begin - M = FullMixedPrec(rand(8, 8); precisions=DataType[Float32, Float64]) - @test M.A21_scale isa Float32 - @test M.A11.Base_scale isa Float32 - end - - @testset "arguments are checked" begin - @test_throws DimensionMismatch FullMixedPrec(rand(Float64, 4, 8); - precisions=DataType[Float64]) - @test_throws ArgumentError FullMixedPrec(zeros(0, 0); precisions=DataType[Float64]) - @test_throws ArgumentError FullMixedPrec(rand(4, 4); precisions=DataType[]) - @test_throws ArgumentError FullMixedPrec(rand(4, 4); precisions=DataType[Int]) - @test_throws ArgumentError FullMixedPrec([1.0 NaN; 0.0 1.0]; precisions=DataType[Float64]) - @test_throws ArgumentError FullMixedPrec([1.0 Inf; 0.0 1.0]; precisions=DataType[Float64]) - end - - @testset "a block too large even for the largest scale throws" begin - @test_throws ArgumentError FullMixedPrec(fill(1.0e300, 4, 4); - precisions=DataType[Float16, Float32]) - end - - @testset "typemin of an integer matrix is scaled, not stored as -Inf" begin - M = FullMixedPrec([1 0; typemin(Int) 1]; precisions=DataType[Float16, Float64]) - @test M.A21_scale > 1 && all(isfinite, M.A21) - R = reconstruct_matrix(M) - @test all(isfinite, R) - @test R[2, 1] ≈ Float64(typemin(Int)) rtol=1e-3 - end - - @testset "out-of-bounds indexing throws" begin - M = FullMixedPrec(rand(8, 8); precisions=DataType[Float32, Float64]) - @test_throws BoundsError M[0, 1] - @test_throws BoundsError M[1, 9] - end - end - - @testset "transpose is lazy" begin - A = rand(Float64, 8, 8) - M = FullMixedPrec(A; precisions=DataType[Float32, Float64]) - Mᵀ = transpose(M) - @test parent(Mᵀ) === M - @test transpose(Mᵀ) === M - @test size(Mᵀ) == reverse(size(M)) - @test all(Mᵀ[i, j] == M[j, i] for i in 1:8, j in 1:8) - @test_throws BoundsError Mᵀ[9, 1] - end - - @testset "SymmMixedPrec" begin - @testset "$T, uplo=$uplo, n=$n" for T in MXP_TYPES, uplo in ('L', 'U'), n in (7, 8) - B = rand(T, n, n) - A = B + transpose(B) - - M = SymmMixedPrec(A, uplo; precisions=DataType[Float32, T]) - @test size(M) == (n, n) - - @testset "reads back symmetric, matching the stored triangle" begin - @test all(isapprox(M[i, j], A[i, j]; rtol=test_rtol(Float32)) - for i in 1:n, j in 1:n) - @test all(M[i, j] == M[j, i] for i in 1:n, j in 1:n) - end - - @testset "reconstruct_matrix fills both triangles" begin - R = reconstruct_matrix(M) - @test R ≈ A rtol=test_rtol(Float32) - @test R == transpose(R) - end - - @testset "transpose is the identity" begin - @test transpose(M) === M - end - end - - @testset "the other triangle is not read, uplo=$uplo" for uplo in ('L', 'U') - B = rand(8, 8) - A = B + transpose(B) - G = copy(A) - uplo == 'L' ? (G[1, 8] = NaN) : (G[8, 1] = NaN) - M = SymmMixedPrec(G, uplo; precisions=DataType[Float32, Float64]) - @test reconstruct_matrix(M) ≈ A rtol=test_rtol(Float32) - end - - @testset "a scaled off-diagonal block reads back unscaled, uplo=$uplo" for uplo in ('L', 'U') - A = ones(4, 4) - A[3:4, 1:2] .= 1.0e5 - A[1:2, 3:4] .= 1.0e5 - M = SymmMixedPrec(A, uplo; precisions=DataType[Float16, Float64]) - @test M.OffDiag_scale != 1 - @test all(isapprox.(reconstruct_matrix(M), A; rtol=1e-2)) - @test isapprox(M[3, 1], 1.0e5; rtol=1e-2) - @test isapprox(M[1, 3], 1.0e5; rtol=1e-2) - end - - @testset "arguments are checked" begin - @test_throws ArgumentError SymmMixedPrec(rand(4, 4), 'X'; precisions=DataType[Float64]) - @test_throws DimensionMismatch SymmMixedPrec(rand(4, 8), 'L'; precisions=DataType[Float64]) - @test_throws BoundsError SymmMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float64])[5, 1] - end - end - - @testset "TriMixedPrec" begin - @testset "$T, uplo=$uplo, n=$n" for T in MXP_TYPES, uplo in ('L', 'U'), n in (7, 8) - A = uplo == 'L' ? tril(rand(T, n, n)) : triu(rand(T, n, n)) - - M = TriMixedPrec(A, uplo; precisions=DataType[Float32, T]) - @test size(M) == (n, n) - - @testset "stored triangle matches, other triangle reads zero" begin - @test all(isapprox(M[i, j], A[i, j]; rtol=test_rtol(Float32)) - for i in 1:n, j in 1:n) - @test reconstruct_matrix(M) ≈ A rtol=test_rtol(Float32) - end - end - - @testset "only the uplo triangle of a full input is kept, uplo=$uplo" for uplo in ('L', 'U') - A = rand(8, 8) - M = TriMixedPrec(A, uplo; precisions=DataType[Float32, Float64]) - @test reconstruct_matrix(M) ≈ (uplo == 'L' ? tril(A) : triu(A)) rtol=test_rtol(Float32) - end - - @testset "converts from SymmMixedPrec preserving the triangle, uplo=$uplo" for uplo in ('L', 'U') - n = 8 - B = rand(Float64, n, n) - A = B + transpose(B) - S = SymmMixedPrec(A, uplo; precisions=DataType[Float32, Float64]) - M = TriMixedPrec(S) - - @test size(M) == size(S) - @test M.uplo == uplo - @test all(M[i, j] == S[i, j] for i in 1:n, j in 1:n if (uplo == 'L' ? i >= j : i <= j)) - @test all(iszero(M[i, j]) for i in 1:n, j in 1:n if (uplo == 'L' ? i < j : i > j)) - end - - @testset "a scaled off-diagonal block reads back unscaled" begin - A = tril(ones(4, 4)) - A[3:4, 1:2] .= 1.0e5 - M = TriMixedPrec(A, 'L'; precisions=DataType[Float16, Float64]) - @test M.OffDiag_scale != 1 - @test all(isapprox.(reconstruct_matrix(M), A; rtol=1e-2)) - end - - @testset "arguments are checked" begin - @test_throws ArgumentError TriMixedPrec(rand(4, 4), 'X'; precisions=DataType[Float64]) - @test_throws BoundsError TriMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float64])[1, 0] - end - end - - @testset "TiledTriMixedPrec" begin - @testset "uplo=$uplo" for uplo in ('L', 'U') - n = 8 - A = uplo == 'L' ? tril(rand(Float64, n, n)) : triu(rand(Float64, n, n)) - - M = TiledTriMixedPrec(A, uplo; precisions=DataType[Float32, Float64], - threshold=4) - - @test size(M) == (n, n) - @test size(M, 1) == n - @test all(isapprox(M[i, j], A[i, j]; rtol=test_rtol(Float32)) - for i in 1:n, j in 1:n) - @test M[1, 1] isa Float64 - @test reconstruct_matrix(M) ≈ A rtol=test_rtol(Float32) - @test all(transpose(M)[i, j] == M[j, i] for i in 1:n, j in 1:n) - end - - @testset "multi-level tiling keeps the whole off-diagonal block" begin - n = 8 - A = tril(rand(Float64, n, n)) - M = TiledTriMixedPrec(A, 'L'; precisions=DataType[Float32, Float64], - threshold=2) - - @test isapprox(M[7, 1], A[7, 1]; rtol=test_rtol(Float32)) - @test reconstruct_matrix(M) ≈ A rtol=test_rtol(Float32) - end - - @testset "uneven tiles, n=$n, threshold=$t" for (n, t) in ((7, 3), (13, 4), (5, 1)) - A = tril(rand(Float64, n, n)) - M = TiledTriMixedPrec(A, 'L'; precisions=DataType[Float32, Float64], threshold=t) - @test reconstruct_matrix(M) ≈ A rtol=test_rtol(Float32) - @test sum(size.(M.diag, 1)) == n - end - - @testset "a scaled tile reads back unscaled" begin - A = tril(ones(8, 8)) - A[5:8, 1:4] .= 1.0e5 - M = TiledTriMixedPrec(A, 'L'; precisions=DataType[Float16, Float64], threshold=4) - @test M.off_scales[2, 1] != 1 - @test all(isapprox.(reconstruct_matrix(M), A; rtol=1e-2)) - end - - @testset "arguments are checked" begin - A = tril(rand(8, 8)) - @test_throws ArgumentError TiledTriMixedPrec(A, 'X'; precisions=DataType[Float64], threshold=2) - @test_throws ArgumentError TiledTriMixedPrec(A, 'L'; precisions=DataType[Float64], threshold=0) - @test_throws ArgumentError TiledTriMixedPrec(A, 'L'; - precisions=DataType[Float16, Float32, Float64], - threshold=2) - end - - @testset "out-of-bounds indexing throws" begin - A = tril(rand(Float64, 8, 8)) - M = TiledTriMixedPrec(A, 'L'; precisions=DataType[Float32, Float64], - threshold=2) - @test_throws BoundsError M[0, 1] - @test_throws BoundsError M[9, 1] - end - end - - @testset "adaptive_precisions" begin - n = 16 - A = tril(rand(Float64, n, n)) + n * I - - @testset "returns one precision per level, then the leaf precision" begin - u = adaptive_precisions(A) - @test u isa Vector{DataType} - @test all(T -> T in (Float32, Float64), u) - @test u[end] === Float64 - @test size(FullMixedPrec(A; precisions=u)) == (n, n) - end - - @testset "n_min controls the number of levels" begin - @test length(adaptive_precisions(A, DataType[Float32, Float64], 2)) > - length(adaptive_precisions(A, DataType[Float32, Float64], 8)) - end - - @testset "a matrix too small to split gets only the leaf precision" begin - @test adaptive_precisions(A[1:3, 1:3]) == DataType[Float64] - end - - @testset "the leaves are no finer than eltype(A)" begin - u = adaptive_precisions(Float32.(A), DataType[Float16, Float32, Float64]) - @test u[end] === Float32 - @test all(T -> T in (Float16, Float32), u) - @test adaptive_precisions(Float16.(A))[end] === Float32 - @test adaptive_precisions(Float32.(A), DataType[Float16])[end] === Float16 - end - - @testset "a 16-bit matrix with large block norms is finite" begin - H = Float16.(fill(100, 2048, 2048) + 1000I) - @test adaptive_precisions(H; uplo='F')[end] === Float32 - end - - @testset "a BFloat16 matrix with very large or very small entries" begin - for v in (1f20, 1f-25) - B = NextLA.BFloat16.(fill(v, 64, 64) + 10v * I) - @test adaptive_precisions(B, DataType[NextLA.BFloat16, Float32]; uplo='F')[end] === Float32 - end - end - - @testset "U may be given in any order" begin - @test adaptive_precisions(A, DataType[Float64, Float32]) == adaptive_precisions(A) - end - - @testset "arguments are checked" begin - @test_throws DimensionMismatch adaptive_precisions(rand(Float64, 4, 8)) - @test_throws ArgumentError adaptive_precisions(zeros(0, 0)) - @test_throws ArgumentError adaptive_precisions(A, DataType[]) - @test_throws ArgumentError adaptive_precisions(A, DataType[Int]) - @test_throws ArgumentError adaptive_precisions(A, DataType[Float32, Float64], 0) - @test_throws ArgumentError adaptive_precisions(A, DataType[Float32, Float64], 4, 0.0) - @test_throws ArgumentError adaptive_precisions(A; uplo='X') - @test_throws ArgumentError adaptive_precisions(zeros(n, n)) - @test_throws ArgumentError adaptive_precisions(fill(NaN, n, n)) - end - - @testset "uplo='U' reads the upper triangle" begin - @test adaptive_precisions(copy(transpose(A)); uplo='U') == adaptive_precisions(A) - end - - @testset "uplo='F' measures both off-diagonal blocks" begin - F = [i == j ? 1.0 : i > j ? 1.0e-12 : 1.0 for i in 1:n, j in 1:n] - @test adaptive_precisions(F; uplo='L')[1] === Float32 - @test adaptive_precisions(F; uplo='F')[1] === Float64 - @test size(FullMixedPrec(F; precisions=adaptive_precisions(F; uplo='F'))) == (n, n) - end - - @testset "the other triangle is not read" begin - G = copy(A) - G[1, n] = NaN - @test adaptive_precisions(G) == adaptive_precisions(A) - end - end - - @testset "leaves narrower than Float32 are refused" begin - for T in (Float16, NextLA.BFloat16) - @test_throws ArgumentError FullMixedPrec(fill(1.0e5, 4, 4); precisions=DataType[T]) - @test_throws ArgumentError SymmMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float16, T]) - @test_throws ArgumentError TriMixedPrec(rand(4, 4), 'L'; precisions=DataType[Float16, T]) - end - @test FullMixedPrec(rand(4, 4); precisions=DataType[Float16, Float32]) isa FullMixedPrec - end - - @testset "a scaled off-diagonal block reads back unscaled" begin - A = fill(1.0, 4, 4) - A[3:4, 1:2] .= 1.0e5 - M = FullMixedPrec(A; precisions=DataType[Float16, Float64]) - @test M.A21_scale != 1 - @test all(isapprox.(reconstruct_matrix(M), A; rtol=1e-2)) - @test isapprox(M[3, 1], 1.0e5; rtol=1e-2) - end -end - -# BFloat16 is BFloat16s.jl's type, which works on every Julia version: Core.BFloat16 -# with its methods from 1.11, a software type on 1.10. Core.BFloat16 alone has no -# conversions, so storing a block in it used to fail unless BFloat16s was loaded. -@testset "MXP BFloat16 blocks [CPU]" begin - A = rand(8, 8) + 8I - M = FullMixedPrec(copy(A); precisions=DataType[NextLA.BFloat16, Float32]) - @test eltype(M.A21) === NextLA.BFloat16 - @test isapprox(reconstruct_matrix(M), A; rtol=1e-2) - @test adaptive_precisions(A, DataType[NextLA.BFloat16, Float32]) isa Vector{DataType} -end diff --git a/test/mxp/syrk/recsyrk_mixedprec.jl b/test/mxp/syrk/recsyrk_mixedprec.jl deleted file mode 100644 index 22db8ee7..00000000 --- a/test/mxp/syrk/recsyrk_mixedprec.jl +++ /dev/null @@ -1,68 +0,0 @@ -using NextLA.MixedPrecision -# recsyrk! over a SymmMixedPrec container. CPU only. - -_mxp_tri(uplo, X) = uplo == 'L' ? tril(X) : triu(X) - -@testset "RECSYRK mixed precision [CPU]" begin - Random.seed!(2055) - - @testset "SymmMixedPrec n=$n uplo=$uplo" for n in [32, 45, 64], uplo in ('L', 'U') - T = Float32 - A0 = rand(T, n, 16) - C0 = rand(T, n, n); C0 = C0 + transpose(C0) - mp = SymmMixedPrec(copy(C0), uplo; precisions = DataType[Float32, Float32]) - - @test recsyrk!(T(1.5), A0, T(0.5), mp) === mp - - expected = T(1.5) * (A0 * transpose(A0)) + T(0.5) * C0 - R = reconstruct_matrix(mp) - @test norm(_mxp_tri(uplo, R) - _mxp_tri(uplo, expected)) / norm(_mxp_tri(uplo, expected)) < 1e-3 - @test R ≈ expected rtol=1e-3 - end - - @testset "Float16 off-diagonal blocks, uplo=$uplo" for uplo in ('L', 'U') - n = 32 - A0 = rand(Float32, n, 8) - C0 = rand(Float32, n, n); C0 = C0 + transpose(C0) - mp = SymmMixedPrec(copy(C0), uplo; precisions = DataType[Float16, Float32]) - recsyrk!(1f0, A0, 1f0, mp) - @test reconstruct_matrix(mp) ≈ A0 * transpose(A0) + C0 rtol=1e-2 - end - - @testset "a scaled block takes alpha divided by its scale" begin - n = 8 - C0 = ones(Float64, n, n) - C0[5:8, 1:4] .= 1.0e5 - C0[1:4, 5:8] .= 1.0e5 - mp = SymmMixedPrec(copy(C0), 'L'; precisions = DataType[Float16, Float64]) - @test mp.OffDiag_scale != 1 - A0 = rand(Float64, n, 4) - recsyrk!(-100.0, A0, 1.0, mp) - @test reconstruct_matrix(mp) ≈ -100 * A0 * transpose(A0) + C0 rtol=1e-2 - end - - @testset "parallel and sequential agree" begin - n = 32 - A0 = rand(Float64, n, 8) - C0 = rand(Float64, n, n); C0 = C0 + transpose(C0) - seq = SymmMixedPrec(copy(C0), 'L'; precisions = DataType[Float32, Float64]) - par = SymmMixedPrec(copy(C0), 'L'; precisions = DataType[Float32, Float64]) - MixedPrecision._recsyrk_mixed!(1.0, A0, 1.0, seq; parallel=false) - MixedPrecision._recsyrk_mixed!(1.0, A0, 1.0, par; parallel=true) - @test reconstruct_matrix(seq) ≈ reconstruct_matrix(par) rtol=1e-12 - end - - @testset "A with the wrong number of rows throws" begin - mp = SymmMixedPrec(rand(8, 8), 'L'; precisions = DataType[Float64]) - @test_throws DimensionMismatch recsyrk!(1.0, rand(7, 3), 1.0, mp) - end -end - -# An update past floatmax of the Float16 off-diagonal block raises its scale. -@testset "RECSYRK mixed precision re-scales an overflowing block [CPU]" begin - C_mp = SymmMixedPrec(zeros(4, 4), 'L'; precisions = DataType[Float16, Float32]) - A = fill(1000.0, 4, 2) - recsyrk!(1.0, A, 0.0, C_mp) - @test C_mp.OffDiag_scale > 1 - @test reconstruct_matrix(C_mp) ≈ A * A' rtol=1e-2 -end diff --git a/test/mxp/trsm/rectrxm_mixed.jl b/test/mxp/trsm/rectrxm_mixed.jl deleted file mode 100644 index f878ea83..00000000 --- a/test/mxp/trsm/rectrxm_mixed.jl +++ /dev/null @@ -1,229 +0,0 @@ -using NextLA.MixedPrecision -# Triangular solve and multiply over the mixed-precision containers, checked -# against BLAS on the equivalent dense matrix. CPU only: the containers index -# scalar-wise on the host, the same limitation recorded for src/mxp/. - -# BLAS on the container's own values, in Float64, so a comparison measures the -# solve and not how the container rounded A. -function _mxp_reference(func, side, uplo, trans, diag, A, B) - ref = Float64.(B) - Ad = Float64.(A) - if func == 'S' - LinearAlgebra.BLAS.trsm!(side, uplo, trans, diag, 1.0, Ad, ref) - else - LinearAlgebra.BLAS.trmm!(side, uplo, trans, diag, 1.0, Ad, ref) - end - return ref -end - -_mxp_relerr(X, ref) = norm(Float64.(X) - ref) / norm(ref) - -@testset "RECTRXM mixed [CPU]" begin - Random.seed!(2051) - - rtol = 1e-4 # Float32 containers, accumulated over a recursion - - @testset "func=$func side=$side uplo=$uplo n=$n" for - func in ['S', 'M'], - side in ['L', 'R'], - uplo in ['L', 'U'], - n in [16, 37, 64] - - m = 8 - A = uplo == 'L' ? tril(rand(Float32, n, n)) : triu(rand(Float32, n, n)) - A += Diagonal(10f0 * ones(Float32, n)) - B = side == 'L' ? rand(Float32, n, m) : rand(Float32, m, n) - - Amp = TriMixedPrec(A, uplo; precisions = DataType[Float32, Float32]) - Bm = copy(B) - @test unified_rectrxm!(side, uplo, 'N', 'N', 1, func, Amp, Bm) === Bm - @test _mxp_relerr(Bm, _mxp_reference(func, side, uplo, 'N', 'N', A, B)) < rtol - end - - @testset "unit diagonal, func=$func" for func in ['S', 'M'] - n, m = 32, 4 - A = tril(rand(Float32, n, n)) / n - B = rand(Float32, n, m) - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float32, Float32]) - Bm = copy(B) - unified_rectrxm!('L', 'L', 'N', 'U', 1, func, Amp, Bm) - @test _mxp_relerr(Bm, _mxp_reference(func, 'L', 'L', 'N', 'U', A, B)) < rtol - end - - @testset "transposed container, func=$func side=$side" for func in ['S', 'M'], side in ['L', 'R'] - n, m = 32, 4 - A = tril(rand(Float32, n, n)) + Diagonal(10f0 * ones(Float32, n)) - B = side == 'L' ? rand(Float32, n, m) : rand(Float32, m, n) - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float32, Float32]) - Bm = copy(B) - unified_rectrxm!(side, 'L', 'T', 'N', 1, func, Amp, Bm) - @test _mxp_relerr(Bm, _mxp_reference(func, side, 'L', 'T', 'N', A, B)) < rtol - end - - @testset "FullMixedPrec, uplo=$uplo, transposed=$t" for uplo in ['L', 'U'], t in (false, true) - n, m = 32, 4 - A = rand(Float32, n, n) + Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, m) - Amp = FullMixedPrec(A; precisions = DataType[Float32, Float32]) - Bm = copy(B) - if t - unified_rectrxm!('L', uplo == 'L' ? 'U' : 'L', 'T', 'N', 1, 'S', Amp, Bm) - ref = _mxp_reference('S', 'L', uplo == 'L' ? 'U' : 'L', 'T', 'N', A, B) - else - unified_rectrxm!('L', uplo, 'N', 'N', 1, 'S', Amp, Bm) - ref = _mxp_reference('S', 'L', uplo, 'N', 'N', A, B) - end - @test _mxp_relerr(Bm, ref) < rtol - end - - @testset "Float16 blocks, func=$func" for func in ['S', 'M'] - n, m = 32, 4 - A = tril(rand(Float32, n, n)) + Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, m) - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float16, Float32]) - ref = _mxp_reference(func, 'L', 'L', 'N', 'N', reconstruct_matrix(Amp), B) - Bm = copy(B) - unified_rectrxm!('L', 'L', 'N', 'N', 1, func, Amp, Bm) - @test eltype(Bm) === Float32 - @test _mxp_relerr(Bm, ref) < 1e-2 - end - - @testset "scaled off-diagonal blocks, func=$func" for func in ['S', 'M'] - n, m = 16, 4 - A = tril(rand(Float32, n, n)) * 1f5 + Diagonal(1f6 * ones(Float32, n)) - B = rand(Float32, n, m) - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float16, Float32]) - @test Amp.OffDiag_scale != 1 - ref = _mxp_reference(func, 'L', 'L', 'N', 'N', reconstruct_matrix(Amp), B) - Bm = copy(B) - unified_rectrxm!('L', 'L', 'N', 'N', 1, func, Amp, Bm) - @test _mxp_relerr(Bm, ref) < 1e-2 - end - - @testset "a scaled leaf, func=$func" for func in ['S', 'M'] - n, m = 16, 4 - A = tril(rand(n, n)) * 1.0e39 + 2.0e39I - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float32]) - @test Amp.Base_scale != 1 - B = rand(n, m) - Bm = copy(B) - unified_rectrxm!('L', 'L', 'N', 'N', 1, func, Amp, Bm) - @test _mxp_relerr(Bm, _mxp_reference(func, 'L', 'L', 'N', 'N', A, B)) < 1e-2 - end - - @testset "a multiply that overflows gives Inf, not floatmax" begin - Amp = TriMixedPrec(Matrix(1.0e39I, 4, 4), 'L'; precisions = DataType[Float32]) - @test Amp.Base_scale != 1 - B = fill(1f34, 4, 2) - unified_rectrxm!('L', 'L', 'N', 'N', 1, 'M', Amp, B) - @test all(isinf, B) - end - - # The off-diagonal product rounds B's part to the block's - # Float16 through a scaled copy; a plain conversion made values past - # floatmax(Float16) Inf. - @testset "an off-diagonal product keeps B values past floatmax(Float16)" begin - n = 16 - A = tril(rand(Float32, n, n)) + n * I - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float16, Float32]) - B = 1.0f6 .* rand(Float32, n, 3) - ref = Float64.(A) \ Float64.(B) - Bm = copy(B) - unified_rectrxm!('L', 'L', 'N', 'N', 1, 'S', Amp, Bm) - @test all(isfinite, Bm) - @test _mxp_relerr(Bm, ref) < 1e-2 - end - - @testset "the form without diag takes 'N'" begin - n = 16 - A = tril(rand(Float32, n, n)) + Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, 3) - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float32, Float32]) - B1, B2 = copy(B), copy(B) - unified_rectrxm!('L', 'L', 'N', 1, 'S', Amp, B1) - unified_rectrxm!('L', 'L', 'N', 'N', 1, 'S', Amp, B2) - @test B1 == B2 - end - - @testset "uplo must be A.uplo for a triangular or symmetric container" begin - n = 16 - A = tril(rand(Float32, n, n)) + Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, 3) - Tri = TriMixedPrec(A, 'L'; precisions = DataType[Float32, Float32]) - Sym = SymmMixedPrec(A + tril(A, -1)', 'L'; precisions = DataType[Float32, Float32]) - @test_throws ArgumentError unified_rectrxm!('L', 'U', 'N', 'N', 1, 'S', Tri, copy(B)) - @test_throws ArgumentError unified_rectrxm!('R', 'U', 'T', 'N', 1, 'M', Tri, copy(B')) - @test_throws ArgumentError unified_rectrxm!('L', 'U', 'N', 'N', 1, 'S', Sym, copy(B)) - end - - # transpose(::SymmMixedPrec) is the matrix itself, but the recursion reads one - # stored triangle, whose transpose is the other one. - @testset "SymmMixedPrec with trans='T', n=$n uplo=$uplo" for n in [8, 13, 100], uplo in ['L', 'U'] - S = Matrix(Symmetric(rand(n, n))) + n * I - Sy = SymmMixedPrec(copy(S), uplo; precisions = DataType[Float64, Float64, Float64]) - Ad = uplo == 'L' ? tril(S) : triu(S) - for side in ('L', 'R'), func in ('S', 'M'), diag in ('N', 'U') - B = side == 'L' ? rand(n, 3) : rand(3, n) - X = copy(B) - unified_rectrxm!(side, uplo, 'T', diag, 1.0, func, Sy, X) - @test _mxp_relerr(X, _mxp_reference(func, side, uplo, 'T', diag, Ad, B)) < 1e-12 - end - end - - # The dense driver's TRMM base case is only valid up to TILE_DIM = 16; - # a larger threshold used to give silently wrong answers, so unified_rec - # clamps it. Guard the clamp from the mixed path's side. - @testset "multiply respects the dense TRMM tile limit" begin - n, m = 64, 8 - A = tril(rand(Float32, n, n)) + Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, m) - - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float32, Float32]) - # a deliberately oversized threshold must not reach src/trsm/trmm.jl's kernels - Bm = copy(B) - MixedPrecision._rec_mixed!('M', 'L', 'L', 'N', Amp, Bm, 256) - @test _mxp_relerr(Bm, _mxp_reference('M', 'L', 'L', 'N', 'N', A, B)) < rtol - end - - @testset "quantize/dequantize" begin - A = rand(Float32, 32, 32) .* 1000 - q, s = MixedPrecision.quantize(A) - @test eltype(q) === Float16 - @test s isa Float32 - back = MixedPrecision.dequantize(q, s, Float32) - @test norm(back - A) / norm(A) < 1e-2 # Float16 storage - - # a matrix past the Float16 range must come back scaled, not saturated - big = fill(1f5, 8, 8) - qb, sb = MixedPrecision.quantize(big) - @test sb > 1f0 - @test !any(isinf, Float32.(qb)) - @test norm(MixedPrecision.dequantize(qb, sb, Float32) - big) / norm(big) < 1e-2 - - z, sz = MixedPrecision.quantize(zeros(Float32, 4, 4)) - @test sz == 1f0 - @test all(iszero, z) - - @testset "any storage type" begin - q2, s2 = MixedPrecision.quantize(rand(Float64, 4, 4), Float32) - @test eltype(q2) === Float32 - @test s2 isa Float32 - end - - @testset "an empty matrix" begin - qe, se = MixedPrecision.quantize(zeros(Float64, 0, 3), Float16) - @test size(qe) == (0, 3) && eltype(qe) === Float16 - @test se === 1f0 - end - - @testset "a non-finite matrix throws" begin - @test_throws ArgumentError MixedPrecision.quantize([1.0 NaN]) - end - - @testset "dequantize converts before multiplying" begin - q3 = Float16[3] - @test MixedPrecision.dequantize(reshape(q3, 1, 1), 1.1f0, Float64)[1] == 3.0 * Float64(1.1f0) - @test (@inferred MixedPrecision.dequantize(reshape(q3, 1, 1), 1.1f0, Float64)) isa Matrix{Float64} - end - end -end diff --git a/test/runtests.jl b/test/runtests.jl index b6b43508..c26470cc 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,95 +1,121 @@ +# NextLA tests, run by ParallelTestRunner.jl: each test runs in its own Julia +# process, so a test that fails or crashes does not stop the others, and any +# set of tests can be run by name (names are matched with startswith; a name +# starting with ! is left out). +# +# Pkg.test("NextLA") # everything +# Pkg.test("NextLA"; test_args=`--list`) # the test names +# Pkg.test("NextLA"; test_args=`mxp`) # mixed precision only +# Pkg.test("NextLA"; test_args=`tlr`) # tile low-rank only +# Pkg.test("NextLA"; test_args=`mxp/blas/trsm`) # one routine +# Pkg.test("NextLA"; test_args=`dense/lapack/qr`) # one family of dense tests +# Pkg.test("NextLA"; test_args=`--jobs=1 mxp`) # one file at a time +# Pkg.test("NextLA"; test_args=`--backends=CPU mxp`) # mixed precision on the CPU only +# +# --backends=CPU (or CPU,CUDA, ...) limits every test to those backends; see +# test/gpu_backends.jl. Workers start with one thread unless JULIA_NUM_THREADS +# is set. test/README.md has the details. + using NextLA -using Test -using LinearAlgebra -using LinearAlgebra.LAPACK -using Random +using ParallelTestRunner + +const TESTDIR = @__DIR__ + +# --backends=: the backends every test runs on. +args = parse_args(ARGS; custom=["backends"]) +const BACKENDS = let flag = args.custom["backends"] + if flag === nothing # not given: every available backend + "" + elseif something(flag) === nothing # given without a value + error("--backends needs a value, e.g. --backends=CPU or --backends=CPU,CUDA") + else + String(something(flag)) + end +end +const WANTED = isempty(BACKENDS) ? String[] : lowercase.(strip.(split(BACKENDS, ','))) +# The names test/gpu_backends.jl knows (its backend_defs, plus CPU). Checked here, +# so a misspelt name stops the run once instead of failing every test. +const KNOWN_BACKENDS = ["cpu", "cuda", "amdgpu", "oneapi", "metal"] +let unknown = setdiff(WANTED, KNOWN_BACKENDS) + isempty(unknown) || error("--backends: unknown ", join(unknown, ", "), + "; known: CPU, CUDA, AMDGPU, oneAPI, Metal") +end -include("lapack_helpers.jl") -include("gpu_backends.jl") -include("backend_test_helpers.jl") -backends = available_backends() -@info "Test backends" backends=[b[1] for b in backends] +# Evaluated at the top level of each test's own module before the test (the +# test itself runs inside a @testset, a local scope, so constants go here). +const init_code = quote + using NextLA, Test, LinearAlgebra, Random + const TEST_BACKENDS_WANTED = $BACKENDS +end + +# One test per file under test/dense, test/mxp and test/tlr, named by its path +# without ".jl", e.g. "dense/lapack/qr/geqrt" or "mxp/blas/trsm/rectrxm_mixed". +# Each starts with the helpers of its part of the suite (test/setup/dense.jl, +# test/setup/mxp.jl or test/setup/tlr.jl); the helper files themselves are not +# tests. +const SETUP = Dict( + "dense" => [joinpath(TESTDIR, "setup", "dense.jl")], + "mxp" => [joinpath(TESTDIR, "gpu_backends.jl"), joinpath(TESTDIR, "setup", "mxp.jl")], + "tlr" => [joinpath(TESTDIR, "gpu_backends.jl"), joinpath(TESTDIR, "setup", "tlr.jl")], +) +# A folder under test/ with test files that is not a part above would never run; +# stop instead, so a new folder cannot be skipped without anyone noticing. +for d in readdir(TESTDIR) + p = joinpath(TESTDIR, d) + (isdir(p) && d != "setup" && !haskey(SETUP, d)) || continue + any(f -> endswith(f, ".jl"), (f for (_, _, fs) in walkdir(p) for f in fs)) && + error("test/$d has test files but is not a part in SETUP (test/runtests.jl), so they would not run") +end -# ── Helpers required by lu.jl ───────────────────────────────────────────────── -function parameter_creation(path::String, imat::Int, M::Int, N::Int) - kl = 0; ku = 0; anorm = 1.0; mode = :decay; cndnum = 10.0; dist = :uniform; type = 'N' - if path == "GE" - type = 'N' - if imat == 1; mode = :decay; cndnum = 2.0 - elseif imat == 2; mode = :decay; cndnum = 1e2 - elseif imat == 3; mode = :one_large; cndnum = 1e6 - elseif imat == 4; kl = 2; ku = 2; mode = :decay; cndnum = 1e2 - end +testsuite = Dict{String, Expr}() +for (part, setup) in SETUP, (name, body) in find_tests(joinpath(TESTDIR, part)) + testsuite["$part/$name"] = quote + $((:(include($f)) for f in setup)...) + $body end - return (; type, kl, ku, anorm, mode, cndnum, dist) end -function matrix_generation(type, M, N; dist=:uniform, mode=:decay, - cndnum=10.0, anorm=1.0, kl=0, ku=0, seed=1234) - rng = MersenneTwister(seed) - (M == 0 || N == 0) && return zeros(type, M, N) - k = min(M, N) - σ = zeros(real(type), k) - if mode == :one_large - σ .= 1.0; k > 0 && (σ[1] = cndnum) - elseif mode == :decay - if k == 1; σ[1] = anorm - else; for i in 1:k; σ[i] = anorm * (1/cndnum)^((i-1)/(k-1)); end; end - elseif mode == :random - σ .= rand(rng, real(type), k); maximum(σ) > 0 && (σ .*= anorm / maximum(σ)) - else; error("Unsupported mode"); end - U, _ = qr(randn(rng, type, M, M)) - V, _ = qr(randn(rng, type, N, N)) - Σ = Diagonal(σ) - A = U[:, 1:k] * Σ * V[:, 1:k]' - if kl > 0 || ku > 0 - for i in 1:M, j in 1:N - (j > i + ku || i > j + kl) && (A[i, j] = zero(type)) - end +# ParallelTestRunner picks one test process per 2 GiB of free host memory, up to +# one per CPU thread, but each process that uses CUDA also holds its own context +# and memory pool on the device. As CUDA.jl's own test/runtests.jl does, cap that +# number by the device's free memory (read through NVML when it can, so this +# process creates no CUDA context); an integrated GPU shares host memory, so its +# budget adds the host part. Only when CUDA is installed and asked for; --jobs=N +# overrides it, and any failure here leaves ParallelTestRunner's default. +const GPU_MEMORY_PER_TEST = 2 * 2^30 # context + pool of one test process (estimate) +const HOST_MEMORY_PER_TEST = 2 * 2^30 # ParallelTestRunner's default per process +function cuda_job_cap() + CUDA = getfield(Main, :CUDA) + CUDA.functional() || return typemax(Int) + dev = first(CUDA.devices()) + free = try # NVML first: it needs no CUDA context in this process + mig = CUDA.uuid(dev) != CUDA.parent_uuid(dev) + Int(CUDA.NVML.memory_info(CUDA.NVML.Device(CUDA.uuid(dev); mig)).free) + catch # no NVML, or it does not report memory (some integrated GPUs) + CUDA.device!(() -> Int(CUDA.free_memory()), dev) end - return A + integrated = CUDA.attribute(dev, CUDA.DEVICE_ATTRIBUTE_INTEGRATED) == 1 + budget, per_test = integrated ? (min(free, Int(Sys.free_memory())), GPU_MEMORY_PER_TEST + HOST_MEMORY_PER_TEST) : + (free, GPU_MEMORY_PER_TEST) + jobs = max(1, budget ÷ per_test) + @info "Test processes capped by GPU memory" device = CUDA.name(dev) integrated free = Base.format_bytes(free) jobs + return jobs end +const MAX_DEFAULT_JOBS = if (isempty(WANTED) || "cuda" in WANTED) && Base.find_package("CUDA") !== nothing + try + @eval Main using CUDA + Base.invokelatest(cuda_job_cap) + catch err + @warn "Could not read free GPU memory; using ParallelTestRunner's default number of jobs" err + typemax(Int) + end +else + typemax(Int) +end + +# Keep a separate record of test times and last failures for each --backends +# choice (ParallelTestRunner's history_key), so a CPU-only run does not mix with a +# GPU run in the ordering or in the marks that --list shows. +const HISTORY_KEY = isempty(WANTED) ? nothing : join(sort(WANTED), ",") -include("NextLAMatrix.jl") -include("lu.jl") -include("trsm/unified_rectrxm.jl") -include("trsm.jl") -include("lauum.jl") -include("axpy.jl") -include("gerc.jl") -include("larfg.jl") -include("larf.jl") -include("geqr2.jl") -include("larft.jl") -include("larfb.jl") -include("geqrt.jl") -include("unmqr.jl") -include("tsqrt.jl") -include("tsmqr.jl") -include("parfb.jl") -include("ttqrt.jl") -include("ttmqr.jl") -include("pamm.jl") -include("pemv.jl") -include("gemm/gemmEx.jl") -include("gemm/gemm_batched.jl") -include("gemm/gemm_grouped.jl") -include("gemm/recgemm.jl") -include("gemm/matmul.jl") -include("trsm/trsm_batched.jl") -include("lu/lu_factor.jl") -include("lu/reclu.jl") -include("syrk/syrk.jl") -include("syrk/syrk_kernel.jl") -include("syrk/recsyrk.jl") -include("rotations/lartg.jl") -include("cholesky/potrf_batched.jl") -include("cholesky/potrf.jl") -include("cholesky/cholesky.jl") -include("cholesky/cholesky_blocked.jl") -include("mxp/mxp.jl") -include("mxp/gemm/recgemm_mixedprec.jl") -include("mxp/trsm/rectrxm_mixed.jl") -include("mxp/lu/reclu_mixedprec.jl") -include("mxp/syrk/recsyrk_mixedprec.jl") -include("mxp/cholesky/recpotrf_mixedprec.jl") +runtests(NextLA, args; testsuite, init_code, max_default_jobs = MAX_DEFAULT_JOBS, history_key = HISTORY_KEY) diff --git a/test/setup/dense.jl b/test/setup/dense.jl new file mode 100644 index 00000000..857633e2 --- /dev/null +++ b/test/setup/dense.jl @@ -0,0 +1,51 @@ +# Helpers shared by the dense tests, test/dense/**. test/runtests.jl includes +# this file at the start of every dense test (each runs in its own module). + +using LinearAlgebra.LAPACK + +include(joinpath(@__DIR__, "..", "lapack_helpers.jl")) +include(joinpath(@__DIR__, "..", "gpu_backends.jl")) +include(joinpath(@__DIR__, "..", "backend_test_helpers.jl")) + +# The backends the dense tests run on (several files loop over this global). +backends = available_backends() + +# ── Helpers required by lu.jl ───────────────────────────────────────────────── +function parameter_creation(path::String, imat::Int, M::Int, N::Int) + kl = 0; ku = 0; anorm = 1.0; mode = :decay; cndnum = 10.0; dist = :uniform; type = 'N' + if path == "GE" + type = 'N' + if imat == 1; mode = :decay; cndnum = 2.0 + elseif imat == 2; mode = :decay; cndnum = 1e2 + elseif imat == 3; mode = :one_large; cndnum = 1e6 + elseif imat == 4; kl = 2; ku = 2; mode = :decay; cndnum = 1e2 + end + end + return (; type, kl, ku, anorm, mode, cndnum, dist) +end + +function matrix_generation(type, M, N; dist=:uniform, mode=:decay, + cndnum=10.0, anorm=1.0, kl=0, ku=0, seed=1234) + rng = MersenneTwister(seed) + (M == 0 || N == 0) && return zeros(type, M, N) + k = min(M, N) + σ = zeros(real(type), k) + if mode == :one_large + σ .= 1.0; k > 0 && (σ[1] = cndnum) + elseif mode == :decay + if k == 1; σ[1] = anorm + else; for i in 1:k; σ[i] = anorm * (1/cndnum)^((i-1)/(k-1)); end; end + elseif mode == :random + σ .= rand(rng, real(type), k); maximum(σ) > 0 && (σ .*= anorm / maximum(σ)) + else; error("Unsupported mode"); end + U, _ = qr(randn(rng, type, M, M)) + V, _ = qr(randn(rng, type, N, N)) + Σ = Diagonal(σ) + A = U[:, 1:k] * Σ * V[:, 1:k]' + if kl > 0 || ku > 0 + for i in 1:M, j in 1:N + (j > i + ku || i > j + kl) && (A[i, j] = zero(type)) + end + end + return A +end diff --git a/test/setup/mxp.jl b/test/setup/mxp.jl new file mode 100644 index 00000000..9783bc1c --- /dev/null +++ b/test/setup/mxp.jl @@ -0,0 +1,178 @@ +# Helpers shared by the mixed-precision tests, test/mxp/**. +# +# Error bounds. Every accuracy check uses the unit roundoff u = eps(T)/2 of the +# precision the result depends on (Higham, Accuracy and Stability of Numerical +# Algorithms, 2nd ed., 2002, §2.1), instead of a fixed number: +# - storing a value in T changes it by at most u(T) relative (§2.1, round to +# nearest, normal range); mxp_storage_ok checks that element by element; +# - an operation over n terms in precision T is checked against +# MXP_LAMBDA * sqrt(n) * u(T), the probabilistic bound of Higham and Mary, +# "A new approach to probabilistic rounding error analysis", SIAM J. Sci. +# Comput. 41(5), 2019, A2815-A2835, instead of the worst case n * u(T), which +# is far from what is observed and would hide errors of a wrong precision. +# - a solve or factorization is checked by its normwise backward error +# (§7.1, Rigal and Gaches; §9.3 for LU, §10.1 for Cholesky), which does not +# depend on the condition number. +# With Float32 data, a block rounded to Float16 by mistake gives an error near +# u(Float16) = 4.9e-4, far above the Float32 bound, so these checks see it. + +using NextLA.MixedPrecision + +# The backends the tests run on: every available one, or the ones given with the +# runner flag --backends (see test/gpu_backends.jl). +const MXP_BACKENDS = available_backends() +@info "Mixed-precision test backends" backends=first.(MXP_BACKENDS) + +# The containers support Float8_E5M2 through an optional package that is not a +# test dependency, so the storage types tested here are these. +const MXP_NARROW = (Float16, NextLA.BFloat16) + +const MXP_LAMBDA = 8 + +mxp_u(::Type{T}) where {T} = Float64(eps(T)) / 2 + +""" + mxp_tol(T, n) + +Normwise relative error allowed for a result computed over `n` terms whose +narrowest precision is `T`: `MXP_LAMBDA * sqrt(n) * u(T)`. +""" +mxp_tol(::Type{T}, n::Integer) where {T} = MXP_LAMBDA * sqrt(n) * mxp_u(T) + +"""The narrowest type in a `precisions` vector (largest unit roundoff).""" +mxp_narrowest(precisions) = argmax(mxp_u, precisions) + +mxp_relerr(X, ref) = norm(Float64.(Array(X)) - ref) / norm(ref) + +# --------------------------------------------------------------------------- +# Storage: the precision each element of a container is stored in. +# --------------------------------------------------------------------------- + +""" + mxp_eltype_map(M) -> Matrix{DataType} + +The storage type of every element of the container `M`, from its block tree. +""" +function mxp_eltype_map(M) + E = Matrix{DataType}(undef, size(M)) + _mxp_map!(E, M) + return E +end + +function _mxp_map!(E, M::FullMixedPrec) + M.Base !== nothing && return fill!(E, eltype(M.Base)) + mid, n = size(M.A11, 1), M.n + _mxp_map!(view(E, 1:mid, 1:mid), M.A11) + _mxp_map!(view(E, mid+1:n, mid+1:n), M.A22) + fill!(view(E, mid+1:n, 1:mid), eltype(M.A21)) + fill!(view(E, 1:mid, mid+1:n), eltype(M.A12)) + return E +end + +function _mxp_map!(E, M::Union{SymmMixedPrec, TriMixedPrec}) + M.Base !== nothing && return fill!(E, eltype(M.Base)) + mid, n = size(M.A11, 1), M.n + _mxp_map!(view(E, 1:mid, 1:mid), M.A11) + _mxp_map!(view(E, mid+1:n, mid+1:n), M.A22) + fill!(view(E, mid+1:n, 1:mid), eltype(M.OffDiag)) + fill!(view(E, 1:mid, mid+1:n), eltype(M.OffDiag)) + return E +end + +function _mxp_map!(E, M::TiledTriMixedPrec{TD, TO}) where {TD, TO} + fill!(E, TO) + o = M.offsets + for k in 1:length(M.diag) + fill!(view(E, o[k]:o[k+1]-1, o[k]:o[k+1]-1), TD) + end + return E +end + +""" + mxp_storage_ok(R, A, E) + +Whether every element of the reconstruction `R` is within one rounding of `A` in +its storage type `E[i, j]`. A conversion from Float64 to a type narrower than +Float32 may round twice, through Float32 (BFloat16s.jl converts that way), so +those elements are allowed u(T) + u(Float32). +""" +function mxp_storage_ok(R, A, E) + bound(T) = sizeof(T) < 4 ? mxp_u(T) + mxp_u(Float32) : mxp_u(T) + return all(abs(Float64(R[i]) - Float64(A[i])) <= bound(E[i]) * abs(Float64(A[i])) for i in eachindex(A)) +end + +# --------------------------------------------------------------------------- +# Matrices. Entries of rand() + 0.5 stay out of the Float16 subnormal range, so +# the storage bound above holds; diagonal dominance keeps LU without pivoting +# and the solves well conditioned (Higham 2002, §9.5). +# --------------------------------------------------------------------------- + +mxp_rand(T, m, n) = rand(T, m, n) .+ T(0.5) +# R * R' from BLAS need not be exactly symmetric; (S + S')/2 is, so the stored +# triangle and its mirror are the same matrix. +mxp_spd(T, n) = (R = mxp_rand(T, n, n); S = R * R' + T(n) * I; (S + S') / 2) +mxp_diagdom(T, n) = mxp_rand(T, n, n) + T(2n) * I +mxp_tri(uplo, X) = uplo == 'L' ? tril(X) : triu(X) +mxp_trimat(T, n, uplo) = mxp_tri(uplo, mxp_rand(T, n, n)) + T(n) * I + +# --------------------------------------------------------------------------- +# Backward errors (Higham 2002): of a triangular solve op(A) X = B or X op(A) = B, +# ‖B - op(A) X‖ / (‖A‖ ‖X‖ + ‖B‖) (Rigal and Gaches, Thm 7.1); of LU, ‖A - LU‖/‖A‖; +# of Cholesky, ‖A - LLᵀ‖/‖A‖. All in Float64, on the host. +# --------------------------------------------------------------------------- + +function mxp_trsm_backward_error(side, uplo, trans, diag, A, X, B) + Ad = Float64.(Array(A)) + Ad = uplo == 'L' ? tril(Ad) : triu(Ad) + diag == 'U' && (Ad[LinearAlgebra.diagind(Ad)] .= 1) + opA = trans == 'N' ? Ad : transpose(Ad) + Xd, Bd = Float64.(Array(X)), Float64.(B) + R = side == 'L' ? Bd - opA * Xd : Bd - Xd * opA + return norm(R) / (norm(opA) * norm(Xd) + norm(Bd)) +end + +mxp_lu_backward_error(F, A) = + (Fd = Float64.(Array(F)); norm(UnitLowerTriangular(Fd) * UpperTriangular(Fd) - A) / norm(A)) + +function mxp_chol_backward_error(F, A, uplo) + Fd = Float64.(Array(F)) + return norm((uplo == 'L' ? Fd * Fd' : Fd' * Fd) - A) / norm(A) +end + +# BLAS on Float64 copies: the exact answer of a triangular multiply, up to u(Float64). +function mxp_trmm_reference(side, uplo, trans, diag, A, B) + ref = Float64.(B) + LinearAlgebra.BLAS.trmm!(side, uplo, trans, diag, 1.0, Float64.(Array(A)), ref) + return ref +end + +""" + mxp_on(AT, A) + +`A` moved to the array type of a backend; `Array` leaves it as it is. +""" +mxp_on(AT, A) = AT === Array ? A : AT(A) + +# --------------------------------------------------------------------------- +# GPU. The Symm/Tri/Tiled constructors, adaptive_precisions and the +# reconstruct_matrix of Symm/Tri are tested on the device on every Julia version +# (fixes F5 and F3: tril!(copy(view)) instead of tril(view), and the triangle +# test inside the reconstruct broadcast). +# --------------------------------------------------------------------------- + +""" + mxp_host(M) + +A copy of the container `M` with every block moved to the host, to check a result +computed on a device against the same container read on the CPU. +""" +_mxp_host(x) = x === nothing ? nothing : x isa MixedPrecision.AbstractMixedPrec ? mxp_host(x) : Array(x) +mxp_host(M::FullMixedPrec{T}) where {T} = + FullMixedPrec{T}(_mxp_host(M.A11), _mxp_host(M.A22), _mxp_host(M.A21), _mxp_host(M.A12), + M.A21_scale, M.A12_scale, M.Base_scale, _mxp_host(M.Base), M.n) +mxp_host(M::SymmMixedPrec{T}) where {T} = + SymmMixedPrec{T}(_mxp_host(M.A11), _mxp_host(M.A22), _mxp_host(M.OffDiag), M.OffDiag_scale, + M.Base_scale, _mxp_host(M.Base), M.uplo, M.n) +mxp_host(M::TriMixedPrec{T}) where {T} = + TriMixedPrec{T}(_mxp_host(M.A11), _mxp_host(M.A22), _mxp_host(M.OffDiag), M.OffDiag_scale, + M.Base_scale, _mxp_host(M.Base), M.uplo, M.n) diff --git a/test/setup/tlr.jl b/test/setup/tlr.jl new file mode 100644 index 00000000..c524d123 --- /dev/null +++ b/test/setup/tlr.jl @@ -0,0 +1,269 @@ +# Helpers shared by the tile low-rank tests, test/tlr/**. test/runtests.jl +# includes this file at the start of every TLR test (each runs in its own module). +# +# References. A compressed matrix is compared with the dense matrix it was built +# from, through `reconstruct_tlr`, which expands every tile on the host; a TLR +# product is compared with the dense product of the reconstructed operands, so +# the check measures the GEMM, not the compression that made its inputs. +# +# Compression draws its random sketch from the global RNG, so every top-level +# testset starts with Random.seed! and its ranks are the same from run to run. + +using KernelAbstractions +using NextLA.TileLowRank + +# `const` so closures in allocation-sensitive tests resolve calls statically +# rather than boxing a global. +const _TLRM = NextLA.TileLowRank + +# The backends the tests run on: every available one, or the ones given with the +# runner flag --backends (see test/gpu_backends.jl). +const TLR_BACKENDS = available_backends() + +# ── Tile fixtures ───────────────────────────────────────────────────────────── + +function make_rect_lowrank_tile(::Type{T}, m::Int, n::Int, r::Int; seed::Integer) where {T} + 0 <= r <= min(m, n) || throw(ArgumentError("rank must satisfy 0 <= r <= min(m, n)")) + rng = MersenneTwister(seed) + if r == 0 + return zeros(T, m, n) + end + qleft = Matrix(qr(randn(rng, T, m, r)).Q) + qright = Matrix(qr(randn(rng, T, n, r)).Q) + sigma = r == 1 ? [T(1)] : collect(range(T(2), T(1), length=r)) + return qleft[:, 1:r] * Diagonal(sigma) * qright[:, 1:r]' +end + +make_lowrank_tile(::Type{T}, b::Int, r::Int; seed::Integer) where {T} = + make_rect_lowrank_tile(T, b, b, r; seed) + +function make_dense_tile(::Type{T}, b::Int; seed::Integer) where {T} + rng = MersenneTwister(seed) + tile = randn(rng, T, b, b) + tile .+= T(0.5) * Matrix{T}(I, b, b) + return tile +end + +function assemble_block_matrix(tile11, tile12, tile21, tile22) + top = hcat(tile11, tile12) + bottom = hcat(tile21, tile22) + return vcat(top, bottom) +end + +# 10×10 dense-diagonal fixture tiled 4|4|2: right/bottom/corner boundary tiles are +# all populated and every off-diagonal tile has known rank. +function boundary_dense_fixture(::Type{T}) where {T} + # diagonal tiles + d11 = make_dense_tile(T, 4; seed=11) + d22 = make_dense_tile(T, 4; seed=22) + d33 = make_dense_tile(T, 2; seed=33) + + # off-diagonal low-rank tiles + a12 = make_lowrank_tile(T, 4, 2; seed=101) + a21 = make_lowrank_tile(T, 4, 3; seed=102) + a13 = make_rect_lowrank_tile(T, 4, 2, 2; seed=103) + a23 = make_rect_lowrank_tile(T, 4, 2, 2; seed=104) + a31 = make_rect_lowrank_tile(T, 2, 4, 2; seed=105) + a32 = make_rect_lowrank_tile(T, 2, 4, 2; seed=106) + + # block assembly + top = hcat(d11, a12, a13) + mid = hcat(a21, d22, a23) + bot = hcat(a31, a32, d33) + A = vcat(top, mid, bot) + return (; A, d11, d22, d33, a12, a21, a13, a23, a31, a32) +end + +# ── TLR reconstruction and storage assertions ───────────────────────────────── + +function reconstruct_tlr(A_tlr::TileLowRank.TLRMatrix) + T = eltype(A_tlr) + A = zeros(T, size(A_tlr)) + D = Array(TileLowRank.dense_diag(A_tlr)) + D_corner = Array(TileLowRank.dense_diag_corner(A_tlr)) + + for linear in 1:prod(TileLowRank.grid_size(A_tlr)) + tile_i, tile_j = NextLA.TileLowRank.inverse_tile_index( + NextLA.TileLowRank.tile_order(A_tlr), TileLowRank.grid_size(A_tlr)..., linear) + p0, q0 = TileLowRank.tile_origin_coords(A_tlr, tile_i, tile_j) + tile_m, tile_n = TileLowRank.tile_size(A_tlr, tile_i, tile_j) + rows = p0:(p0 + tile_m - 1) + cols = q0:(q0 + tile_n - 1) + + tile = if tile_i == tile_j + if tile_i <= size(D, 3) + @view D[1:tile_m, 1:tile_n, tile_i] + else + @view D_corner[1:tile_m, 1:tile_n, 1] + end + else + r = Int(TileLowRank.ranks(A_tlr)[ + expected_storage_slot(A_tlr, tile_i, tile_j)]) + U, V = TileLowRank.get_factors(A_tlr, tile_i, tile_j) + r == 0 ? zeros(T, tile_m, tile_n) : Array(U) * Array(V)' + end + + A[rows, cols] .= tile + end + + return A +end + +function reconstruct_tlr(A_tlr::TileLowRank.CompressedFTLRMatrix) + T = eltype(A_tlr) + backend = KernelAbstractions.get_backend(A_tlr) + A = KernelAbstractions.zeros(backend, T, size(A_tlr)) + TileLowRank.uncompress!(A, A_tlr) + return Array(A) +end + +expected_storage_slot(A_tlr::TileLowRank.AbstractTLRMatrix, i::Int, j::Int) = + NextLA.TileLowRank.tile_linear_index( + NextLA.TileLowRank.tile_order(A_tlr), TileLowRank.grid_size(A_tlr)..., i, j) + +function assert_tile_rank_and_error( + A_tlr::TileLowRank.AbstractTLRMatrix, + tile_i::Int, + tile_j::Int, + expected_rank::Int, + tile_ref::AbstractMatrix; + atol_rank::Int=0, + rtol_error=1f-4, +) + batch = expected_storage_slot(A_tlr, tile_i, tile_j) + rank = Int(TileLowRank.ranks(A_tlr)[batch]) + @test abs(rank - expected_rank) <= atol_rank + + tile_m, tile_n = size(tile_ref) + U, V = TileLowRank.get_factors(A_tlr, tile_i, tile_j) + approx = rank == 0 ? zeros(eltype(tile_ref), tile_m, tile_n) : + Array(U) * Array(V)' + relerr = norm(tile_ref - approx) / max(norm(tile_ref), eps(real(eltype(tile_ref)))) + @test relerr <= rtol_error +end + +# ── Random TLR operands for GEMM tests ──────────────────────────────────────── + +function fill_random_tlr!(A_tlr::TileLowRank.TLRMatrix, ArrayType::Type; seed::Integer) + rng = MersenneTwister(seed) + T = eltype(A_tlr) + + # dense diagonal + A_tlr.D .= ArrayType(randn(rng, T, size(A_tlr.D))) + A_tlr.D_corner .= ArrayType(randn(rng, T, size(A_tlr.D_corner))) + + # low-rank off-diagonal factors + qm, qn = TileLowRank.grid_size(A_tlr) + for j in 1:qn, i in 1:qm + i == j && continue + U, V = TileLowRank.get_factors(A_tlr, i, j) + U .= ArrayType(randn(rng, T, size(U))) + V .= ArrayType(randn(rng, T, size(V))) + end + return A_tlr +end + +"""Fill the finalized logical factors of a compressed matrix.""" +function fill_random_tlr!(A_tlr::TileLowRank.CompressedFTLRMatrix, ArrayType::Type; seed::Integer) + rng = MersenneTwister(seed) + T = eltype(A_tlr) + + qm, qn = TileLowRank.grid_size(A_tlr) + for j in 1:qn, i in 1:qm + r = Int(TileLowRank.ranks(A_tlr)[expected_storage_slot(A_tlr, i, j)]) + r == 0 && continue + U, V = TileLowRank.get_factors(A_tlr, i, j) + U .= ArrayType(randn(rng, T, size(U))) + V .= ArrayType(randn(rng, T, size(V))) + end + return A_tlr +end + +function random_tlr_matrix(ArrayType::Type, ::Type{T}, n::Int, b::Int, r::Int; + seed::Integer) where {T} + backend = KernelAbstractions.get_backend(ArrayType(zeros(T, 1))) + q = cld(n, b) + rank_grid = [i == j ? 0 : min(r, min(b, n-(i-1)*b), min(b, n-(j-1)*b)) + for i in 1:q, j in 1:q] + + A = TileLowRank.TLRMatrix(backend, T, n, n, b, rank_grid) + return fill_random_tlr!(A, ArrayType; seed) +end + +function compressed_ftlr_fixture( + ::Type{T}=Float64, + ranks::AbstractMatrix{<:Integer}=Int[1 2 0; 3 1 2]; + rank_multiple::Int=0) where {T} + qm, qn = size(ranks) + b = max(4, NextLA.gemm_alignment_quantum(T)) + + A = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), T, b*qm, b*qn, b, ranks; rank_multiple) + fill_random_tlr!(A, Array; seed=123) + return A +end + +# ── Dense-reference GEMM drivers ────────────────────────────────────────────── + +# Core driver: `gemm!` on prefilled TLR operands against the tile-by-tile dense +# reference `alpha * A * B + beta * C0`. +function assert_gemm_matches_dense(ArrayType::Type, A_tlr, B_tlr, synchronize; + budget::Int, alpha, beta, atol, rtol) + T = eltype(A_tlr) + rng = MersenneTwister(303) + C0_cpu = randn(rng, T, size(A_tlr, 1), size(B_tlr, 2)) + C = ArrayType(C0_cpu) + + workspace = max(budget, TileLowRank.gemm_minimum_workspace_bytes(A_tlr, B_tlr)) + NextLA.gemm!(C, A_tlr, B_tlr; alpha=alpha, beta=beta, workspace) + synchronize(C) + + C_ref = alpha * reconstruct_tlr(A_tlr) * reconstruct_tlr(B_tlr) + beta * C0_cpu + @test isapprox(Array(C), C_ref; atol=atol, rtol=rtol) +end + +# Dense-diagonal container pair (square, tile size `b`, max rank `r`). +function assert_tlr_gemm_matches_dense(ArrayType::Type, T::Type, n::Int, b::Int, r::Int, + orderA, orderB, synchronize; budget::Int, + alpha=T(1.3), beta=T(-0.4), atol=1e-10, rtol=1e-10) + backend = KernelAbstractions.get_backend(ArrayType(zeros(T, 1))) + q = cld(n, b) + rank_grid = [i == j ? 0 : min(r, min(b, n-(i-1)*b), min(b, n-(j-1)*b)) + for i in 1:q, j in 1:q] + + A_tlr = TileLowRank.TLRMatrix(backend, T, n, n, b, rank_grid) + B_tlr = TileLowRank.TLRMatrix(backend, T, n, n, b, rank_grid) + fill_random_tlr!(A_tlr, ArrayType; seed=101) + fill_random_tlr!(B_tlr, ArrayType; seed=202) + + assert_gemm_matches_dense(ArrayType, A_tlr, B_tlr, synchronize; + budget, alpha, beta, atol, rtol) +end + +function assert_dense_diag_transpose_matches(n, b, r, oA, oB, transA, transB; + budget, alpha=1.3, beta=-0.4, + ArrayType=Array, synchronize=_ -> nothing, + atol=1e-9, rtol=1e-9) + backend = KernelAbstractions.get_backend(ArrayType(zeros(Float64, 1))) + q = cld(n, b) + rank_grid = [i == j ? 0 : min(r, min(b, n-(i-1)*b), min(b, n-(j-1)*b)) + for i in 1:q, j in 1:q] + + A = TileLowRank.TLRMatrix(backend, Float64, n, n, b, rank_grid) + B = TileLowRank.TLRMatrix(backend, Float64, n, n, b, rank_grid) + fill_random_tlr!(A, ArrayType; seed=11) + fill_random_tlr!(B, ArrayType; seed=22) + C0 = randn(MersenneTwister(33), Float64, n, n) + C = ArrayType(C0) + + workspace = max( + budget, + TileLowRank.gemm_minimum_workspace_bytes(A, B; transA, transB), + ) + NextLA.gemm!(C, A, B; alpha, beta, transA, transB, workspace) + synchronize(C) + + opd(X, t) = uppercase(t) == 'T' ? transpose(X) : X + ref = alpha .* (opd(reconstruct_tlr(A), transA) * opd(reconstruct_tlr(B), transB)) .+ beta .* C0 + @test isapprox(Array(C), ref; atol, rtol) +end diff --git a/test/tlr/blas/gemm/compressed_accumulation.jl b/test/tlr/blas/gemm/compressed_accumulation.jl new file mode 100644 index 00000000..60b4a5d6 --- /dev/null +++ b/test/tlr/blas/gemm/compressed_accumulation.jl @@ -0,0 +1,142 @@ +# gemm of two CompressedFTLRMatrix operands into a compressed result, +# src/tlr/blas/gemm/compressed_accumulation. +# Helpers: test/setup/tlr.jl. + +function _compressed_output_fixture(::Type{T}, ArrayType; + n=48, b=16, rA=3, rB=4, seed=1200) where {T} + backend = KernelAbstractions.get_backend(ArrayType(zeros(T, 1))) + q = cld(n, b) + + A = TileLowRank.CompressedFTLRMatrix(backend, T, n, n, b, fill(rA, q, q)) + B = TileLowRank.CompressedFTLRMatrix(backend, T, n, n, b, fill(rB, q, q)) + fill_random_tlr!(A, ArrayType; seed=seed+1) + fill_random_tlr!(B, ArrayType; seed=seed+2) + return A, B +end + +function _check_compressed_output_gemm(ArrayType, synchronize; + transA='N', transB='N', + rA=3, rB=4, seed=1200, + rank_multiple=0) + T = Float64 + A, B = _compressed_output_fixture(T, ArrayType; rA, rB, seed) + op(X, t) = uppercase(t) == 'T' ? transpose(X) : X + reference = 1.2 .* (op(reconstruct_tlr(A), transA) * + op(reconstruct_tlr(B), transB)) + C = NextLA.gemm( + A, B; maxrank=16, rank_multiple, alpha=1.2, transA, transB, + tol=1e-7, rel=true, eps_rel=1e-7, r_required=3, block=4) + synchronize(C.outer.data) + got = reconstruct_tlr(C) + @test norm(got-reference) / max(norm(reference), eps(T)) <= 2e-6 + @test all(TileLowRank.ranks(C) .<= 16) + @test TileLowRank.rank_multiple(C) == rank_multiple + return C, A, B +end + +@testset "allocation-returning compressed-output GEMM [CPU]" begin + Random.seed!(3037) + for (transA, transB) in (('N','N'), ('N','T'), ('T','N'), ('T','T')) + _check_compressed_output_gemm( + Array, _ -> nothing; transA, transB, + rA=transA == 'N' ? 2 : 5, + rB=transB == 'N' ? 4 : 3, + seed=1300 + Int(transA) + Int(transB)) + end + C, A, B = _check_compressed_output_gemm( + Array, _ -> nothing; rank_multiple=8, seed=1410) + @test TileLowRank.maximum_storage_rank(C) % 8 == 0 + + # Finalized compressed output cannot be resized in place. + @test_throws MethodError NextLA.gemm!(C, A, B; tol=1e-7) + @test_throws ArgumentError NextLA.gemm(A, B; maxrank=-1) + @test_throws ArgumentError NextLA.gemm(A, B; maxrank=17) + @test_throws ArgumentError NextLA.gemm(A, B; maxrank=16, r_required=0) +end + +@testset "compressed-output GEMM regular-grid boundary [CPU]" begin + Random.seed!(3038) + ranks = ones(Int, 3, 3) + A = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 10, 10, 4, ranks) + B = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 10, 10, 4, ranks) + @test_throws ArgumentError NextLA.gemm(A, B; maxrank=4) +end + +@testset "compressed-output GEMM rolling workspace bounds [CPU]" begin + Random.seed!(3039) + T = Float64 + n, b, rA, rB, maxrank, block = 48, 16, 2, 2, 12, 4 + A, B = _compressed_output_fixture(T, Array; n, b, rA, rB, seed=1500) + reference = reconstruct_tlr(A) * reconstruct_tlr(B) + + # `maxrank` must clear the coupling's true rank (qk * min(rA, rB) = 3*2 = + # 6 here) or the comparison below is checking a lossy truncation, not + # exact recovery, against too tight a tolerance. + + # the same staging shape `gemm` builds internally, used only to size a + # capacity=1 workspace: every member then gets its own rolling-admission + # wave (cold start, then repeated backfill) instead of the default single + # wave sized for every member at once. + qm, qn = TileLowRank.grid_size(A)[1], TileLowRank.grid_size(B)[2] + staging = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), T, n, n, (b, b), fill(maxrank, qm, qn); + outer_order=TileLowRank.TileRowMajor, inner_order=TileLowRank.TileColMajor) + spec = _TLRM.tlr_gemm_workspace_spec(staging, A, B; transA='N', transB='N', block) + tight = _TLRM.tlr_gemm_workspace_bytes(spec, 1) + + C_rolling = NextLA.gemm( + A, B; maxrank, tol=1e-7, rel=true, eps_rel=1e-7, r_required=3, block, + workspace=tight) + C_single = NextLA.gemm( + A, B; maxrank, tol=1e-7, rel=true, eps_rel=1e-7, r_required=3, block) + + @test norm(reconstruct_tlr(C_rolling) - reference) / norm(reference) <= 2e-6 + @test reconstruct_tlr(C_rolling) ≈ reconstruct_tlr(C_single) rtol=1e-8 + @test_throws ArgumentError NextLA.gemm(A, B; maxrank, workspace=tight - 1) +end + +# Product tiles of rank 16 (qk * rA = 4 * 8, capped by the tile size) with +# maxrank 8: every tile stops at the cap, and residuals(C) must report what the +# cap leaves out, not only the truncation (which is zero at the cap). The +# estimate's squared value has relative standard deviation at most √(2/w) with +# w = 8 Gaussian vectors (src/tlr/blas/gemm/compressed_accumulation/ +# rolling_schedule.jl), so a factor of 2 on the norm is several deviations wide. +function _check_capped_residuals(ArrayType, synchronize) + n, b, maxrank = 64, 16, 8 + A, B = _compressed_output_fixture(Float64, ArrayType; n, b, rA=8, rB=8, seed=1600) + C = NextLA.gemm(A, B; maxrank, tol=1e-10, rel=true) + synchronize(C.outer.data) + reference = reconstruct_tlr(A) * reconstruct_tlr(B) + got = reconstruct_tlr(C) + @test all(==(maxrank), TileLowRank.ranks(C)) + qm, qn = TileLowRank.grid_size(C) + for j in 1:qn, i in 1:qm + rows, cols = ((i - 1) * b + 1):(i * b), ((j - 1) * b + 1):(j * b) + actual = norm(got[rows, cols] - reference[rows, cols]) + reported = TileLowRank.residuals(C)[expected_storage_slot(C, i, j)] + @test actual / 2 <= reported <= 2 * actual + end +end + +@testset "compressed-output GEMM residuals at the rank cap [CPU]" begin + Random.seed!(3044) + _check_capped_residuals(Array, _ -> nothing) +end + +@testset "compressed-output GEMM residuals at the rank cap [$backend_name]" for (backend_name, ArrayType, synchronize) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3045) + _check_capped_residuals(ArrayType, synchronize) +end + +@testset "compressed-output GEMM [$backend_name]" for (backend_name, ArrayType, synchronize) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3040) + A, B = _compressed_output_fixture(Float32, ArrayType; n=32, b=16) + C = NextLA.gemm( + A, B; maxrank=16, rank_multiple=8, + tol=1f-4, rel=true, eps_rel=1f-4, r_required=3, block=4) + synchronize(C.outer.data) + reference = reconstruct_tlr(A) * reconstruct_tlr(B) + @test norm(reconstruct_tlr(C)-reference) / norm(reference) <= 5f-3 +end diff --git a/test/tlr/blas/gemm/dense_accumulation.jl b/test/tlr/blas/gemm/dense_accumulation.jl new file mode 100644 index 00000000..4721d61d --- /dev/null +++ b/test/tlr/blas/gemm/dense_accumulation.jl @@ -0,0 +1,556 @@ +# gemm! into a dense C, with TLRMatrix and CompressedFTLRMatrix operands, against +# dense references built from the reconstructed tiles, src/tlr/blas/gemm/dense_accumulation. +# Helpers: test/setup/tlr.jl. + +# +# Parameter sweeps use pairwise coverage: every value of each dimension (tile +# orders, budget extremes, boundary regimes, transpose flags) appears, and every +# pair of dimensions is exercised at least once, without full cross-products. + +@testset "TLR gemm! to dense (dense-diagonal) [CPU]" begin + Random.seed!(3020) + RM = TileLowRank.TileRowMajor(); CM = TileLowRank.TileColMajor() + huge = 128 * 1024 * 1024 + nosync = _ -> nothing + + # (orderA, orderB, budget, n, b, r) — aligned, both boundary regimes + # (tail ≥ Q and tail < Q), and zero rank. Keep these grids small: a tiny + # workspace exercises the same blocked schedule, but its cost grows steeply + # with the number of tiles. + cases = ( + (RM, CM, 1, 12, 4, 2), # aligned grid + (CM, RM, huge, 14, 4, 3), # boundary, tail < Q (Q=3, s=2) + (CM, CM, 1, 15, 4, 3), # boundary, tail ≥ Q (Q=3, s=3) + (RM, RM, huge, 14, 5, 0), # zero rank + boundary + ) + for (oA, oB, budget, n, b, r) in cases + @testset "$(oA) * $(oB), n=$n b=$b r=$r budget=$budget" begin + assert_tlr_gemm_matches_dense(Array, Float64, n, b, r, oA, oB, nosync; budget) + end + end +end + +@testset "TLR compressed workspace bounds [CPU]" begin + Random.seed!(3021) + A = random_tlr_matrix(Array, Float64, 35, 8, 3; seed=71) + B = random_tlr_matrix(Array, Float64, 35, 8, 3; seed=72) + reference = reconstruct_tlr(A) * reconstruct_tlr(B) + for (transA, transB) in (('N', 'N'), ('N', 'T'), ('T', 'N'), ('T', 'T')) + lo = TileLowRank.gemm_minimum_workspace_bytes(A, B; transA, transB) + hi = TileLowRank.gemm_maximum_workspace_bytes(A, B; transA, transB) + @test 0 < lo <= hi + end + lo = TileLowRank.gemm_minimum_workspace_bytes(A, B) + for bytes in unique((lo, TileLowRank.gemm_maximum_workspace_bytes(A, B))) + workspace = TileLowRank.DenseGemmWorkspace(A, B; bytes) + C = zeros(Float64, size(A, 1), size(B, 2)) + NextLA.gemm!(C, A, B; workspace) + @test C ≈ reference + end + @test_throws ArgumentError NextLA.gemm!( + zeros(Float64, size(A, 1), size(B, 2)), A, B; workspace=lo - 1) +end + +@testset "finalized TLR factors remain value-mutable [CPU]" begin + Random.seed!(3022) + A = TileLowRank.TLRMatrix(KernelAbstractions.CPU(), Float64, 8, 8, 4, Int[0 1; 0 0]) + B = TileLowRank.TLRMatrix(KernelAbstractions.CPU(), Float64, 8, 8, 4, Int[0 0; 1 0]) + UA, VA = TileLowRank.get_factors(A, 1, 2) + UB, VB = TileLowRank.get_factors(B, 2, 1) + UA .= 1; VA .= 2; UB .= 3; VB .= 4 + + C = zeros(Float64, 8, 8) + workspace = TileLowRank.gemm_minimum_workspace_bytes(A, B) + NextLA.gemm!(C, A, B; workspace) + @test C ≈ reconstruct_tlr(A) * reconstruct_tlr(B) +end + +# Whole-matrix transpose is a zero-copy container view; the executors consume +# its transposed geometry, factor roles, and tile order directly. +@testset "container-level TLR transpose [CPU]" begin + Random.seed!(3023) + RM = TileLowRank.TileRowMajor(); CM = TileLowRank.TileColMajor() + A = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 11, 14, (4, 3), fill(2, 3, 5)) + At = transpose(A) + @test size(At) == (14, 11) + @test NextLA.TileLowRank.nominal_tile_size(At) == (3, 4) + @test NextLA.TileLowRank.tail_tile_size(At) == (2, 3) + @test NextLA.TileLowRank.grid_size(At) == reverse(TileLowRank.grid_size(A)) + @test NextLA.TileLowRank.tile_order(At) isa typeof(CM) + @test NextLA.TileLowRank.compressed_ftlr_outer_order(At) isa TileLowRank.TileRowMajor + @test NextLA.TileLowRank.compressed_ftlr_inner_order(At) isa TileLowRank.TileColMajor + + D = random_tlr_matrix(Array, Float64, 14, 4, 2; seed=91) + Dt = transpose(D) + @test TileLowRank.offdiagonal(Dt) isa NextLA.TileLowRank.TransposeTLRMatrix + @test size(TileLowRank.dense_diag(Dt))[1:2] == reverse(size(TileLowRank.dense_diag(D))[1:2]) + @test size.(TileLowRank.get_factors(Dt, 2, 1)) == + reverse(size.(TileLowRank.get_factors(D, 1, 2))) + dtile, op = NextLA.TileLowRank.diag_tile_ref(Dt, 1) + @test parent(dtile) === D.D + @test op == 'T' +end + +@testset "dense-diagonal boundary transpose [CPU]" begin + Random.seed!(3024) + RM = TileLowRank.TileRowMajor(); CM = TileLowRank.TileColMajor() + huge = 128 * 1024 * 1024 + + rows = ( + ('N', 'N', RM, CM, 1), + ('N', 'T', CM, CM, huge), + ('T', 'N', RM, RM, huge), + ('T', 'T', CM, RM, 1), + ) + for (tA, tB, oA, oB, budget) in rows + assert_dense_diag_transpose_matches(14, 4, 3, oA, oB, tA, tB; budget) + end + # Dense diagonal remains meaningful when every low-rank tile has rank zero. + assert_dense_diag_transpose_matches(14, 4, 0, RM, CM, 'T', 'T'; budget=1) + +end + +@testset "dense-diagonal TLR mixed dense GEMM [CPU]" begin + Random.seed!(3025) + rng = MersenneTwister(404) + G = random_tlr_matrix(Array, Float64, 9, 4, 2; seed=405) + Gdense = reconstruct_tlr(G) + alpha = 1.25 + beta = -0.5 + + for side in (:tlr_dense, :dense_tlr), + trans_tlr in ('N', 'T'), trans_dense in ('N', 'T') + if side === :tlr_dense + stored_dense = trans_dense == 'N' ? (9, 7) : (7, 9) + X = randn(rng, Float64, stored_dense...) + C0 = randn(rng, Float64, 9, 7) + C = copy(C0) + workspace = TileLowRank.DenseGemmWorkspace(G, 4096) + NextLA.gemm!(C, G, X; workspace, alpha, beta, + transA=trans_tlr, transB=trans_dense) + opG = trans_tlr == 'N' ? Gdense : transpose(Gdense) + opX = trans_dense == 'N' ? X : transpose(X) + reference = alpha .* (opG * opX) .+ beta .* C0 + else + stored_dense = trans_dense == 'N' ? (6, 9) : (9, 6) + X = randn(rng, Float64, stored_dense...) + C0 = randn(rng, Float64, 6, 9) + C = copy(C0) + workspace = TileLowRank.DenseGemmWorkspace(G, 4096) + NextLA.gemm!(C, X, G; workspace, alpha, beta, + transA=trans_dense, transB=trans_tlr) + opX = trans_dense == 'N' ? X : transpose(X) + opG = trans_tlr == 'N' ? Gdense : transpose(Gdense) + reference = alpha .* (opX * opG) .+ beta .* C0 + end + @test C ≈ reference rtol=1e-10 atol=1e-10 + end + + # A zero-rank off-diagonal still carries a nonzero dense diagonal. This + # also verifies that the diagonal updates work with a zero-byte workspace. + D = random_tlr_matrix(Array, Float64, 9, 4, 0; seed=406) + Ddense = reconstruct_tlr(D) + Xright = randn(rng, Float64, 9, 5) + Cright = randn(rng, Float64, 9, 5) + Cright0 = copy(Cright) + NextLA.gemm!(Cright, D, Xright; workspace=0, alpha, beta) + @test Cright ≈ alpha .* (Ddense * Xright) .+ beta .* Cright0 + + Xleft = randn(rng, Float64, 5, 9) + Cleft = randn(rng, Float64, 5, 9) + Cleft0 = copy(Cleft) + NextLA.gemm!(Cleft, Xleft, D; workspace=0, alpha, beta) + @test Cleft ≈ alpha .* (Xleft * Ddense) .+ beta .* Cleft0 +end + +@testset "TLR gemm! to dense [$backend_name]" for (backend_name, ArrayType, synchronize) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3026) + orders = (TileLowRank.TileRowMajor(), TileLowRank.TileColMajor()) + assert_tlr_gemm_matches_dense(ArrayType, Float32, 12, 4, 2, orders..., synchronize; + budget=1, alpha=Float32(1.2), beta=Float32(0.25), + atol=5f-3, rtol=5f-3) +end + +@testset "TF32 backend capability [$backend_name]" for (backend_name, ArrayType, _) in filter(b -> b[1] == "AMDGPU", TLR_BACKENDS) + Random.seed!(3027) + A = random_tlr_matrix(ArrayType, Float32, 8, 4, 2; seed=501) + B = random_tlr_matrix(ArrayType, Float32, 8, 4, 2; seed=502) + C = ArrayType(zeros(Float32, 8, 8)) + @test_throws ArgumentError NextLA.gemm!( + C, A, B; compute=NextLA.TF32(), workspace=1) +end + + + +function _compressed_ftlr_to_backend(A::TileLowRank.CompressedFTLRMatrix, AT) + qm, qn = TileLowRank.grid_size(A) + rank_grid = [Int(TileLowRank.ranks(A)[expected_storage_slot(A, i, j)]) + for i in 1:qm, j in 1:qn] + B = TileLowRank.CompressedFTLRMatrix(KernelAbstractions.get_backend(AT(zeros(eltype(A), 1))), + eltype(A), size(A, 1), size(A, 2), + TileLowRank.nominal_tile_size(A), + rank_grid; + outer_order=typeof(A.outer.order), inner_order=typeof(A.inner.order), + rank_multiple=TileLowRank.rank_multiple(A)) + + copyto!(B.outer.data, AT(Array(A.outer.data))) + copyto!(B.inner.data, AT(Array(A.inner.data))) + return B +end + +@testset "dense × compressed aligned row-run sizing [CPU]" begin + Random.seed!(3028) + height = _TLRM.dense_compressed_row_run_height + @test height(25 * 10, 10, 100, Float16) == 24 + @test height(25 * 10, 10, 100, Float32) == 24 + @test height(25 * 10, 10, 100, Float64) == 24 + @test height(8 * 10, 10, 100, Float16) == 8 + @test height(7 * 10, 10, 100, Float16) == 7 + @test height(23 * 10, 10, 23, Float16) == 23 + @test height(10, 10, 100, Float16) == 1 + @test_throws ArgumentError height(100, 0, 100, Float16) + @test_throws ArgumentError height(100, 10, 0, Float16) + + for (T, quantum) in ((Float16, 8), (Float32, 4), (Float64, 2)), + capacity in quantum:40 + selected = height(capacity * 3, 3, 100, T) + @test selected % quantum == 0 + @test selected <= capacity + @test selected + quantum > capacity + end +end + +@testset "CompressedFTLR mixed dense GEMM [CPU]" begin + Random.seed!(3029) + rank_grid = Int[1 2 1; 2 0 1; 1 1 1] + G = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 9, 9, (4, 4), rank_grid) + rng = MersenneTwister(2026) + for j in 1:3, i in 1:3 + U, V = TileLowRank.get_factors(G, i, j) + U .= randn(rng, Float64, size(U)) + V .= randn(rng, Float64, size(V)) + end + Gdense = zeros(Float64, 9, 9) + TileLowRank.uncompress!(Gdense, G) + + for side in (:compressed_dense, :dense_compressed), + trans_dense in ('N', 'T'), trans_compressed in ('N', 'T') + X = randn(rng, Float64, 9, 9) + C0 = randn(rng, Float64, 9, 9) + C = copy(C0) + if side === :compressed_dense + NextLA.gemm!(C, G, X; workspace=4096, alpha=1.25, beta=-0.5, + transA=trans_compressed, transB=trans_dense) + opG = trans_compressed == 'N' ? Gdense : transpose(Gdense) + opX = trans_dense == 'N' ? X : transpose(X) + product = opG * opX + else + NextLA.gemm!(C, X, G; workspace=4096, alpha=1.25, beta=-0.5, + transA=trans_dense, transB=trans_compressed) + opX = trans_dense == 'N' ? X : transpose(X) + opG = trans_compressed == 'N' ? Gdense : transpose(Gdense) + product = opX * opG + end + @test C ≈ 1.25 .* product .- 0.5 .* C0 rtol=1e-10 atol=1e-10 + end + + X = randn(rng, Float64, 9, 9) + for side in (:compressed_dense, :dense_compressed) + C = zeros(Float64, 9, 9) + workspace = TileLowRank.DenseGemmWorkspace(G, 4096) + analysis = side === :compressed_dense ? + TileLowRank.analyze_compressed_gemm(C, G, X; workspace) : + TileLowRank.analyze_compressed_gemm(C, X, G; workspace) + try + if side === :compressed_dense + NextLA.gemm!(C, G, X; workspace, analysis) + @test C ≈ Gdense * X rtol=1e-10 atol=1e-10 + else + NextLA.gemm!(C, X, G; workspace, analysis) + @test C ≈ X * Gdense rtol=1e-10 atol=1e-10 + end + finally + close(analysis) + end + end + + # Below one fused rank stack, the compressed-only tilewise fallback keeps + # the low-workspace contract without any matrix-shaped staging container. + for side in (:compressed_dense, :dense_compressed) + C = zeros(Float64, 9, 9) + if side === :compressed_dense + NextLA.gemm!(C, G, X; workspace=2 * sizeof(Float64)) + @test C ≈ Gdense * X rtol=1e-10 atol=1e-10 + else + NextLA.gemm!(C, X, G; workspace=2 * sizeof(Float64)) + @test C ≈ X * Gdense rtol=1e-10 atol=1e-10 + end + end + + left_plan = _TLRM.two_stage_rank_plan(G, :left) + right_plan = _TLRM.two_stage_rank_plan(G, :right) + @test all(run.fold === :left for run in + _TLRM.two_stage_schedule(zeros(9, 9), left_plan, 4096, Float64)) + @test all(run.fold === :right for run in + _TLRM.two_stage_schedule(zeros(9, 9), right_plan, 4096, Float64)) +end + +@testset "CompressedFTLR clears T only for uncovered rank holes [CPU]" begin + Random.seed!(3030) + function make_operand(ranks) + return TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float32, 8, 8, 4, ranks) + end + + positive = make_operand(ones(Int, 2, 2)) + positive_plan = _TLRM.compressed_ftlr_rank_plan(positive, positive) + positive_workspace = TileLowRank.DenseGemmWorkspace( + positive, positive_plan.profile.maximum) + positive_arena = _TLRM.GemmArena( + view(positive_workspace.storage, :), 1) + C = zeros(Float32, 8, 8) + + right = _TLRM.build_compressed_ftlr_foldright_run( + C, positive, positive, positive_plan, 1:2, 1:2, 1f0, 0f0, + positive_arena) + @test !right.needs_zero + + left = _TLRM.build_compressed_ftlr_foldleft_run( + C, positive, positive, positive_plan, 1:2, 1:2, 1f0, 0f0, + positive_arena) + @test !left.needs_zero + + # FoldRight gives every active A rank rows across every output column. + # A zero B tile therefore leaves a consumed T block unwritten. + right_B = make_operand(Int[0 1; 1 1]) + right_plan = _TLRM.compressed_ftlr_rank_plan(positive, right_B) + right_workspace = TileLowRank.DenseGemmWorkspace( + positive, right_plan.profile.right_byte_prefix[end]) + right_arena = _TLRM.GemmArena(view(right_workspace.storage, :), 1) + right_hole = _TLRM.build_compressed_ftlr_foldright_run( + C, positive, right_B, right_plan, 1:2, 1:2, 1f0, 0f0, right_arena) + @test right_hole.needs_zero + + # FoldLeft gives every physical output row columns for every active B + # rank. A zero A tile leaves the corresponding rows unwritten. + left_A = make_operand(Int[0 1; 1 1]) + left_plan = _TLRM.compressed_ftlr_rank_plan(left_A, positive) + left_workspace = TileLowRank.DenseGemmWorkspace( + left_A, left_plan.profile.left_byte_prefix[end]) + left_arena = _TLRM.GemmArena(view(left_workspace.storage, :), 1) + left_hole = _TLRM.build_compressed_ftlr_foldleft_run( + C, left_A, positive, left_plan, 1:2, 1:2, 1f0, 0f0, left_arena) + @test left_hole.needs_zero +end + +@testset "CompressedFTLR FoldLeft fuses Stage 3 across a row run [CPU]" begin + Random.seed!(3031) + rank_grid = Int[1 2; 2 1] + A = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float32, 8, 8, 4, rank_grid; + outer_order=TileLowRank.TileColMajor, inner_order=TileLowRank.TileColMajor) + B = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float32, 8, 8, 4, reverse(rank_grid; dims=1)) + plan = _TLRM.compressed_ftlr_rank_plan(A, B) + @test plan.profile.right_byte_prefix === nothing + workspace = TileLowRank.DenseGemmWorkspace(A, plan.profile.maximum) + arena = _TLRM.GemmArena(view(workspace.storage, :), 1) + C = zeros(Float32, 8, 8) + tasks = _TLRM.build_compressed_ftlr_foldleft_run( + C, A, B, plan, 1:2, 1:2, 1f0, 0f0, arena) + + @test length(tasks.stage3) == TileLowRank.grid_size(B)[2] + @test all(size(task.C, 1) == size(C, 1) for task in tasks.stage3) +end + +@testset "CompressedFTLR dense GEMM with tails [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3032) + ranksA = Int[2 1 1; 1 2 1; 1 1 1] + ranksB = Int[1 2 1; 2 1 1; 1 1 1] + Ahost = TileLowRank.CompressedFTLRMatrix(KernelAbstractions.CPU(), Float32, 9, 10, (4, 4), ranksA) + Bhost = TileLowRank.CompressedFTLRMatrix(KernelAbstractions.CPU(), Float32, 10, 11, (4, 4), ranksB) + rng = MersenneTwister(419) + for X in (Ahost, Bhost), j in 1:TileLowRank.grid_size(X)[2], i in 1:TileLowRank.grid_size(X)[1] + U, V = TileLowRank.get_factors(X, i, j) + U .= randn(rng, Float32, size(U)); V .= randn(rng, Float32, size(V)) + end + refA = zeros(Float32, size(Ahost)); refB = zeros(Float32, size(Bhost)) + TileLowRank.uncompress!(refA, Ahost); TileLowRank.uncompress!(refB, Bhost) + A = _compressed_ftlr_to_backend(Ahost, AT); B = _compressed_ftlr_to_backend(Bhost, AT) + for bytes in unique((TileLowRank.gemm_minimum_workspace_bytes(A, B), + TileLowRank.gemm_maximum_workspace_bytes(A, B))) + C0 = rand(rng, Float32, 9, 11); C = AT(copy(C0)) + NextLA.gemm!(C, A, B; workspace=bytes, alpha=1.25f0, beta=-0.5f0) + sync(C) + @test Array(C) ≈ 1.25f0 .* (refA * refB) .- 0.5f0 .* C0 rtol=3f-4 atol=3f-4 + end +end + +@testset "CompressedFTLR logical transpose combinations [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3033) + Ahost = compressed_ftlr_fixture(Float32, Int[1 2; 3 1]) + Bhost = compressed_ftlr_fixture(Float32, Int[2 1; 1 3]) + referenceA = zeros(Float32, size(Ahost)); referenceB = zeros(Float32, size(Bhost)) + TileLowRank.uncompress!(referenceA, Ahost); TileLowRank.uncompress!(referenceB, Bhost) + A = _compressed_ftlr_to_backend(Ahost, AT) + B = _compressed_ftlr_to_backend(Bhost, AT) + for transA in ('N', 'T'), transB in ('N', 'T') + opA = transA == 'N' ? referenceA : transpose(referenceA) + opB = transB == 'N' ? referenceB : transpose(referenceB) + minbytes = TileLowRank.gemm_minimum_workspace_bytes(A, B; transA, transB) + maxbytes = TileLowRank.gemm_maximum_workspace_bytes(A, B; transA, transB) + for bytes in unique((minbytes, maxbytes)) + C0 = rand(Float32, size(opA, 1), size(opB, 2)) + C = AT(copy(C0)) + NextLA.gemm!(C, A, B; workspace=bytes, alpha=1.25f0, beta=-0.5f0, + transA, transB) + sync(C) + @test Array(C) ≈ 1.25f0 .* (opA * opB) .- 0.5f0 .* C0 rtol=2f-4 atol=2f-4 + end + end +end + +@testset "CompressedFTLR dense GEMM, Float32 [CPU]" begin + Random.seed!(3034) + Ahost = compressed_ftlr_fixture(Float32) + Bhost = compressed_ftlr_fixture(Float32, Int[1 0; 2 1; 3 1]) + referenceAhost = zeros(Float32, size(Ahost)) + referenceBhost = zeros(Float32, size(Bhost)) + TileLowRank.uncompress!(referenceAhost, Ahost) + TileLowRank.uncompress!(referenceBhost, Bhost) + Chost = zeros(Float32, 8, 8) + NextLA.gemm!(Chost, Ahost, Bhost; + workspace=TileLowRank.gemm_minimum_workspace_bytes(Ahost, Bhost)) + @test Chost ≈ referenceAhost * referenceBhost rtol=2f-4 atol=2f-4 +end + +@testset "CompressedFTLR dense GEMM [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3041) + Ahost = compressed_ftlr_fixture(Float32) + Bhost = compressed_ftlr_fixture(Float32, Int[1 0; 2 1; 3 1]) + A = _compressed_ftlr_to_backend(Ahost, AT) + B = _compressed_ftlr_to_backend(Bhost, AT) + referenceA = zeros(Float32, size(A)); referenceB = zeros(Float32, size(B)) + TileLowRank.uncompress!(referenceA, Ahost); TileLowRank.uncompress!(referenceB, Bhost) + reconstructed = AT(zeros(Float32, size(A))) + TileLowRank.uncompress!(reconstructed, A) + sync(reconstructed) + @test Array(reconstructed) ≈ referenceA + minbytes = TileLowRank.gemm_minimum_workspace_bytes(A, B) + maxbytes = TileLowRank.gemm_maximum_workspace_bytes(A, B) + for bytes in unique((minbytes, maxbytes)) + C0 = rand(Float32, size(A, 1), size(B, 2)) + C = AT(copy(C0)) + NextLA.gemm!(C, A, B; workspace=bytes, alpha=1.5f0, beta=-0.25f0) + sync(C) + @test Array(C) ≈ 1.5f0 .* (referenceA * referenceB) .- 0.25f0 .* C0 rtol=2f-4 atol=2f-4 + end +end + +# Both two-stage folds slice their T workspace at each output's rank prefix, so +# a member's operands are 16-byte aligned only when every preceding rank is a +# multiple of the backend's alignment quantum. Quantized ranks therefore stay +# fully grouped, while exact ranks route the unaligned members through ordinary +# GEMMEx -- same results either way, so both paths are covered here. +@testset "CompressedFTLR mixed grouped lowering and analysis [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3035) + rank_grid = Int[1 2 1; 2 0 1; 1 1 1] + quantum = NextLA.gemm_alignment_quantum(Float32) + for rank_multiple in (quantum, 0) + H = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float32, 9, 9, (4, 4), rank_grid; + rank_multiple) + rng = MersenneTwister(2026) + for j in 1:3, i in 1:3 + U, V = TileLowRank.get_factors(H, i, j) + U .= randn(rng, Float32, size(U)) + V .= randn(rng, Float32, size(V)) + end + Hdense = zeros(Float32, 9, 9) + TileLowRank.uncompress!(Hdense, H) + + G = _compressed_ftlr_to_backend(H, AT) + for side in (:compressed_dense, :dense_compressed), + trans_dense in ('N', 'T'), trans_compressed in ('N', 'T') + Xhost = randn(rng, Float32, 9, 9) + X = AT(Xhost) + C0 = randn(rng, Float32, 9, 9) + C = AT(C0) + workspace = TileLowRank.DenseGemmWorkspace(G, 4096) + if side === :compressed_dense + analysis = TileLowRank.analyze_compressed_gemm( + C, G, X; workspace, + transA=trans_compressed, transB=trans_dense) + @test analysis.has_fallback == iszero(rank_multiple) + NextLA.gemm!( + C, G, X; workspace, alpha=1.25f0, beta=-0.5f0, + transA=trans_compressed, transB=trans_dense, analysis) + opG = trans_compressed == 'N' ? Hdense : transpose(Hdense) + opX = trans_dense == 'N' ? Xhost : transpose(Xhost) + else + analysis = TileLowRank.analyze_compressed_gemm( + C, X, G; workspace, + transA=trans_dense, transB=trans_compressed) + @test analysis.has_fallback == iszero(rank_multiple) + NextLA.gemm!( + C, X, G; workspace, alpha=1.25f0, beta=-0.5f0, + transA=trans_dense, transB=trans_compressed, analysis) + opX = trans_dense == 'N' ? Xhost : transpose(Xhost) + opG = trans_compressed == 'N' ? Hdense : transpose(Hdense) + end + sync(C) + product = side === :compressed_dense ? opG * opX : opX * opG + @test Array(C) ≈ 1.25f0 .* product .- 0.5f0 .* C0 rtol=3f-4 atol=3f-4 + close(analysis) + end + end +end + +function _compressed_dense32(A) + dense = zeros(Float32, size(A)) + qm, qn = TileLowRank.grid_size(A) + for j in 1:qn, i in 1:qm + rows = _TLRM.tile_axis_range(A, i, 1) + cols = _TLRM.tile_axis_range(A, j, 2) + U, V = TileLowRank.get_factors(A, i, j) + dense[rows, cols] .= Float32.(U) * transpose(Float32.(V)) + end + return dense +end + +@testset "CompressedFTLR arbitrary-rank FP16 and TF32 execution [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3036) + rank_grid = Int[1 2; 3 1] + for (T, compute, tolerance) in ( + (Float16, Float32, 2f-2), + (Float32, NextLA.TF32(), 5f-3), + ) + q = T === Float16 ? 8 : compute isa NextLA.TF32 ? 4 : 0 + Ahost = compressed_ftlr_fixture(T, rank_grid; rank_multiple=q) + Bhost = compressed_ftlr_fixture( + T, reverse(rank_grid; dims=1); rank_multiple=q) + reference = _compressed_dense32(Ahost) * _compressed_dense32(Bhost) + A = _compressed_ftlr_to_backend(Ahost, AT) + B = _compressed_ftlr_to_backend(Bhost, AT) + exact_host = compressed_ftlr_fixture(T, rank_grid) + exact = _compressed_ftlr_to_backend(exact_host, AT) + @test_throws ArgumentError NextLA.gemm!( + AT(zeros(T, size(exact, 1), size(exact, 2))), exact, exact; + workspace=4096, compute) + workspace = TileLowRank.DenseGemmWorkspace( + A, B; bytes=TileLowRank.gemm_maximum_workspace_bytes(A, B)) + C = AT(zeros(T, size(A, 1), size(B, 2))) + analysis = TileLowRank.analyze_compressed_gemm(C, A, B; workspace, compute) + NextLA.gemm!(C, A, B; workspace, compute, analysis) + sync(C) + @test norm(Float32.(Array(C)) - reference) / norm(reference) < tolerance + # Same result through the transient (no-analysis) entry point. + fill!(C, zero(T)) + NextLA.gemm!(C, A, B; workspace, compute) + sync(C) + @test norm(Float32.(Array(C)) - reference) / norm(reference) < tolerance + close(analysis) + end +end diff --git a/test/tlr/core/compressed_ftlr_matrix.jl b/test/tlr/core/compressed_ftlr_matrix.jl new file mode 100644 index 00000000..15eff241 --- /dev/null +++ b/test/tlr/core/compressed_ftlr_matrix.jl @@ -0,0 +1,82 @@ +# CompressedFTLRMatrix, src/tlr/core/compressed_ftlr_matrix.jl. +# Helpers: test/setup/tlr.jl. + +@testset "finalized CompressedFTLRMatrix layout [CPU]" begin + Random.seed!(3003) + ranks = Int[1 3 0; 2 1 1; 1 1 1] + A = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 10, 11, (4, 5), ranks; + rank_multiple=8) + + @test size(A) == (10, 11) + @test TileLowRank.grid_size(A) == (3, 3) + @test TileLowRank.nominal_tile_size(A) == (4, 5) + @test TileLowRank.tail_tile_size(A) == (2, 1) + @test TileLowRank.rank_multiple(A) == 8 + @test TileLowRank.maxrank(A) == 3 + @test TileLowRank.maximum_storage_rank(A) == 8 + @test A.outer.order isa TileLowRank.TileRowMajor + @test A.inner.order isa TileLowRank.TileColMajor + @test length(TileLowRank.get_factors(A, 3, 3)) == 2 + @test size(TileLowRank.get_factors(A, 3, 3)[1]) == (2, 1) + @test size(TileLowRank.get_factors(A, 3, 3)[2]) == (1, 1) + @test size(_TLRM.compressed_ftlr_storage_outer(A, 3, 3)) == (2, 8) + @test size(_TLRM.compressed_ftlr_storage_inner(A, 3, 3)) == (1, 8) + + exact = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float32, 8, 8, 4, Int[1 2; 3 4]) + @test TileLowRank.rank_multiple(exact) == 0 + @test [_TLRM.compressed_ftlr_storage_rank(exact, i, j) + for i in 1:2, j in 1:2] == Int[1 2; 3 4] + + @test_throws ArgumentError TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 8, 8, 4, ones(Int, 2, 2); + rank_multiple=-1) + @test_throws DimensionMismatch TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 8, 8, 4, ones(Int, 3, 2)) +end + +@testset "CompressedFTLR complementary packing and reconstruction [CPU]" begin + Random.seed!(3004) + rank_grid = Int[1 2 0; 2 1 1; 1 1 1] + A = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 9, 10, (4, 4), rank_grid; + rank_multiple=8) + fill_random_tlr!(A, Array; seed=88) + + @test A.outer.offsets[1] == 1 + @test A.inner.offsets[1] == 1 + @test issorted(A.outer.offsets) + @test issorted(A.inner.offsets) + @test A.outer.offsets[end] - 1 == length(A.outer.data) + @test A.inner.offsets[end] - 1 == length(A.inner.data) + + dense = zeros(Float64, size(A)) + TileLowRank.uncompress!(dense, A) + for j in 1:3, i in 1:3 + p0, q0 = TileLowRank.tile_origin_coords(A, i, j) + tm, tn = TileLowRank.tile_size(A, i, j) + U, V = TileLowRank.get_factors(A, i, j) + reference = isempty(U) ? zeros(tm, tn) : Matrix(U) * Matrix(V)' + @test dense[p0:p0+tm-1, q0:q0+tn-1] ≈ reference + end +end + +@testset "rank_multiple replaces symbolic execution policies [CPU]" begin + Random.seed!(3005) + ranks = Int[1 9; 3 8] + exact = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 32, 32, 16, ranks) + q8 = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 32, 32, 16, ranks; + rank_multiple=8) + q16 = TileLowRank.CompressedFTLRMatrix( + KernelAbstractions.CPU(), Float64, 32, 32, 16, ranks; + rank_multiple=16) + @test [_TLRM.compressed_ftlr_storage_rank(exact, i, j) + for i in 1:2, j in 1:2] == ranks + @test [_TLRM.compressed_ftlr_storage_rank(q8, i, j) + for i in 1:2, j in 1:2] == Int[8 16; 8 8] + @test [_TLRM.compressed_ftlr_storage_rank(q16, i, j) + for i in 1:2, j in 1:2] == fill(16, 2, 2) +end diff --git a/test/tlr/core/compression/ara.jl b/test/tlr/core/compression/ara.jl new file mode 100644 index 00000000..da8d8f0c --- /dev/null +++ b/test/tlr/core/compression/ara.jl @@ -0,0 +1,590 @@ +# Adaptive randomized approximation (ARA): convergence, basis, truncation, +# src/tlr/core/compression/ara.jl. +# Helpers: test/setup/tlr.jl. + +# Build the minimal ARA orthogonalization workspace around a batch of panels. +function ara_cholesky_fixture(::Type{T}, ArrayType, X::Array{T,3}) where {T} + m, s, count = size(X) + Thi = _TLRM.tlr_orthogonalization_type(T) + return _TLRM.ARACholeskyWorkspace( + ArrayType(copy(X)), + ArrayType(zeros(Thi, m, s, count)), ArrayType(zeros(Thi, s, s, count)), + ArrayType(zeros(T, s, s, count)), ArrayType(zeros(T, s, s, count)), + ) +end + +@testset "ARA convergence bookkeeping [CPU]" begin + Random.seed!(3008) + rng = MersenneTwister(1301) + + @testset "dR recovers projected norms on a full-rank block" begin + m, s, count = 64, 8, 2 + X = randn(rng, Float64, m, s, count) + ws = ara_cholesky_fixture(Float64, Array, X) + _TLRM.ara_cholesky_pass!(ws, ws.R1, ws.R1_tiles) + _TLRM.ara_cholesky_pass!(ws, ws.R2, ws.R2_tiles) + dR = zeros(Float64, s, count) + _TLRM.ara_block_norms!(dR, ws) + # dR[j] is the residual of column j against columns 1..j-1, i.e. the + # diagonal of the R factor of a plain QR of the same panel. + for b in 1:count + Rref = abs.(diag(qr(X[:, :, b]).R)) + @test dR[:, b] ≈ Rref rtol = 1e-10 + @test norm(ws.Q[:, :, b]' * ws.Q[:, :, b] - I, Inf) <= 1e-12 + end + end + + @testset "convergence state drives per-member sampling" begin + count, block, maxrank = 3, 4, 16 + state = _TLRM.ARAConvergenceState(CPU(), count) + _TLRM.ara_reset!(state, block, maxrank) + @test all(state.samples .== block) + + # Member 1 converges immediately (all columns negligible), member 2 + # keeps producing content, member 3 converges after one more pass. + dR = zeros(Float64, block, count) + dR[:, 1] .= [1.0, 1e-12, 1e-12, 1e-12] + dR[:, 2] .= [1.0, 0.9, 0.8, 0.7] + dR[:, 3] .= [1.0, 1.0, 1e-12, 1e-12] + active = _TLRM.ara_update_convergence!(state, dR, 1e-8, 3, block, maxrank) + @test active == 2 + @test state.samples[1] == 0 # 3 consecutive smalls + @test state.ranks[1] == 1 + @test state.ranks[2] == 4 + @test state.svec[3] == 2 # carries across passes + @test state.jcount == Int32[4, 4, 4] + + # Member 1 is converged and must not advance again. + dR[:, 1] .= 1.0 + dR[:, 3] .= [1e-12, 1.0, 1e-12, 1e-12] + active = _TLRM.ara_update_convergence!(state, dR, 1e-8, 3, block, maxrank) + @test state.samples[1] == 0 + @test state.jcount[1] == 4 # frozen + @test state.ranks[1] == 1 + @test state.jcount[2] == 8 + # Member 3 carried svec=2 and its first column is small, but a later + # column in the same block has genuine content. Convergence is judged on + # the state after the whole block, so the run resets and sampling + # continues -- this is the false-early-stop guard, and it is why the + # count must not short-circuit mid-block. + @test state.svec[3] == 2 + @test state.ranks[3] == 6 + @test state.samples[3] == block + @test active == 2 + + # It does converge once a whole block is negligible. + dR .= 1e-12 + active = _TLRM.ara_update_convergence!(state, dR, 1e-8, 3, block, maxrank) + @test active == 0 + @test state.ranks[2] == 8 && state.ranks[3] == 6 + + # The rank cap stops a member that never converges. + state2 = _TLRM.ARAConvergenceState(CPU(), 1) + _TLRM.ara_reset!(state2, block, block) + big = fill(1.0, block, 1) + @test _TLRM.ara_update_convergence!(state2, big, 1e-8, 3, block, block) == 0 + @test state2.ranks[1] == block + end + + @testset "relative test uses the running maximum" begin + # A block whose norms grow: early columns must not be judged against a + # maximum that has not been seen yet. + count, block, maxrank = 1, 4, 8 + state = _TLRM.ARAConvergenceState(CPU(), count) + _TLRM.ara_reset!(state, block, maxrank) + dR = reshape([1e-3, 1.0, 1e-3, 1e-3], block, count) + _TLRM.ara_update_convergence!(state, dR, 1e-2, 2, block, maxrank) + # Column 1 is large relative to the max so far (itself), so it counts; + # columns 3 and 4 are small relative to 1.0 and terminate the member. + @test state.ranks[1] == 2 + @test state.samples[1] == 0 + end +end + +# Dense black-box sampler: Y .= X[b] * randn. This is the shape A3 needs for +# dense compression, and it keeps the loop tests independent of factor-list apply. +function dense_sampler(X::AbstractArray{T,3}, rng, ArrayType=Array) where {T} + return function (Y, width) + n, count = size(X, 2), size(X, 3) + for b in 1:count + Omega = ArrayType(randn(rng, T, n, width)) + copyto!(view(Y, :, 1:width, b), view(X, :, :, b) * Omega) + end + return Y + end +end + +# Prescribed spectrum: exact rank `r`, then a sharp drop. +function graded_batch(::Type{T}, m, n, ranks, gap, rng) where {T} + count = length(ranks) + X = zeros(T, m, n, count) + for b in 1:count + U = Matrix(qr(randn(rng, T, m, min(m, n))).Q)[:, 1:min(m, n)] + V = Matrix(qr(randn(rng, T, n, min(m, n))).Q)[:, 1:min(m, n)] + sig = [k <= ranks[b] ? one(T) : T(gap) for k in 1:min(m, n)] + X[:, :, b] = U * Diagonal(sig) * V' + end + return X +end + +@testset "ARA basis construction [CPU]" begin + Random.seed!(3009) + rng = MersenneTwister(1401) + + @testset "tolerance below the CholeskyQR2 limit is rejected" begin + # The whole point of the unshifted policy: a tolerance the + # orthogonalizer cannot support must fail loudly, never run to maxrank. + ws = _TLRM.ARAWorkspace(Float64, CPU(), 32, 16, 1; block=4) + floor_rel = _TLRM.ara_stopping_floor(Float64) + @test floor_rel ≈ sqrt(eps(Float64) / 2) + @test 1e-8 < floor_rel < 1e-7 # ~1.05e-8, the sqrt(u) bound + sampler = dense_sampler(randn(rng, Float64, 32, 32, 1), rng) + @test_throws ArgumentError _TLRM.ara_build_basis!( + ws, sampler; eps_rel=1e-12) + @test_throws ArgumentError _TLRM.ara_build_basis!(ws, sampler; eps_rel=0) + end + + @testset "recovers prescribed ranks" begin + m, n = 64, 64 + ranks = [5, 12, 20] + X = graded_batch(Float64, m, n, ranks, 1e-12, rng) + ws = _TLRM.ARAWorkspace(Float64, CPU(), m, 48, length(ranks); block=8) + res = _TLRM.ara_build_basis!(ws, dense_sampler(X, rng); + eps_rel=1e-6, r_required=4) + got = Array(res.ranks) + for b in eachindex(ranks) + # ARA overshoots by design (sampling proceeds in units of `block`); + # A2's final truncation is what recovers the exact rank. + @test ranks[b] <= got[b] <= ranks[b] + ws.block + end + # The basis must be orthonormal and must span the range of each operator. + Q = Array(res.Q) + for b in eachindex(ranks) + Qb = Q[:, 1:got[b], b] + @test norm(Qb' * Qb - I, Inf) <= 1e-12 + resid = X[:, :, b] - Qb * (Qb' * X[:, :, b]) + @test norm(resid) / norm(X[:, :, b]) <= 1e-6 + end + @test res.passes >= 1 + end + + @testset "breakdown retires a member instead of throwing" begin + # A member that is exactly rank 1 makes the block singular almost at + # once. Unshifted, `potrf` breaks down -- that must be read as "nothing + # left to capture", not raised as PosDefException. + m, n = 32, 32 + X = zeros(Float64, m, n, 2) + v = randn(rng, Float64, m) + X[:, :, 1] = v * randn(rng, Float64, n)' # exact rank 1 + X[:, :, 2] = graded_batch(Float64, m, n, [6], 1e-12, rng)[:, :, 1] + ws = _TLRM.ARAWorkspace(Float64, CPU(), m, 24, 2; block=8) + res = _TLRM.ara_build_basis!(ws, dense_sampler(X, rng); + eps_rel=1e-6, r_required=3) + got = Array(res.ranks) + @test got[1] == 1 + @test 6 <= got[2] <= 6 + ws.block + Q = Array(res.Q) + @test norm(Q[:, 1:1, 1]' * Q[:, 1:1, 1] - I, Inf) <= 1e-12 + end + + @testset "a full-rank operator runs to the cap and reports it" begin + m, n = 24, 24 + X = reshape(Matrix(qr(randn(rng, Float64, m, n)).Q), m, n, 1) + ws = _TLRM.ARAWorkspace(Float64, CPU(), m, 16, 1; block=4) + res = _TLRM.ara_build_basis!(ws, dense_sampler(X, rng); + eps_rel=1e-6, r_required=3) + # Saturation is visible in the rank vector alone -- this is why no + # residual is computed. + @test Array(res.ranks)[1] == 16 + end + + @testset "block size is a performance knob, not an accuracy one" begin + m, n = 48, 48 + X = graded_batch(Float64, m, n, [10], 1e-12, rng) + got = map((2, 5, 16)) do blk + ws = _TLRM.ARAWorkspace(Float64, CPU(), m, 40, 1; block=blk) + r = _TLRM.ara_build_basis!(ws, dense_sampler(X, rng); + eps_rel=1e-6, r_required=3) + Q = Array(r.Q) + k = Array(r.ranks)[1] + (k, norm(X[:, :, 1] - Q[:, 1:k, 1] * (Q[:, 1:k, 1]' * X[:, :, 1])) / + norm(X[:, :, 1])) + end + for (k, err) in got + @test 10 <= k <= 10 + 16 # rank found regardless of block size + @test err <= 1e-6 # accuracy independent of block size + end + end +end + +# A member that stops early (here an exact rank-r member, stopped by Cholesky +# breakdown on its first block) still draws a block on every pass while others +# sample. Those blocks are rounding noise; kept, their normalization turned a +# rounding-level overlap with the basis into an O(1) one and the basis held its +# leading direction twice. The cut is now against the member's own scale too. +@testset "a stopped member takes no rounding-noise columns [CPU]" begin + Random.seed!(3046) + rng = MersenneTwister(1701) + m, maxrank, block = 128, 96, 8 + @testset "rank $r" for r in (1, 3, 5) + U1 = Matrix(qr(randn(rng, m, r)).Q)[:, 1:r] + V1 = Matrix(qr(randn(rng, m, r)).Q)[:, 1:r] + X1 = U1 * Diagonal(10.0 .^ -(0:r-1)) * V1' + Q2 = Matrix(qr(randn(rng, m, m)).Q); W2 = Matrix(qr(randn(rng, m, m)).Q) + X2 = Q2 * Diagonal(0.9 .^ (0:m-1)) * W2' # samples to maxrank + X = cat(X1, X2; dims=3) + ws = _TLRM.ARAWorkspace(Float64, KernelAbstractions.CPU(), m, maxrank, 2; block) + res = _TLRM.ara_build_basis!(ws, dense_sampler(X, rng); eps_rel=1e-6, r_required=4) + @test res.passes == maxrank ÷ block + Q = Array(res.Q)[:, :, 1] + kept = Q[:, [norm(Q[:, j]) > 0 for j in axes(Q, 2)]] + @test r <= size(kept, 2) <= r + block + @test norm(kept' * kept - I) <= 1e-7 # √u-level, as CholeskyQR2 at its cut + @test norm(X1 - kept * (kept' * X1)) <= 1e-12 * norm(X1) + end +end + +@testset "rolling ARA slot-local progress [CPU]" begin + Random.seed!(3010) + rng = MersenneTwister(1477) + m = n = 16 + maxrank, block = 10, 4 + X = cat( + Matrix(qr(randn(rng, Float64, m, n)).Q), + Matrix(qr(randn(rng, Float64, m, n)).Q); + dims=3, + ) + ws = _TLRM.ARAWorkspace( + Float64, CPU(), m, maxrank, 2; block) + member_ids = [1, 2] + progress = [0, 0] + sampler = function (Y, width, ids) + for p in eachindex(ids) + Ω = randn(rng, Float64, n, width) + view(Y, :, 1:width, p) .= view(X, :, :, ids[p]) * Ω + end + return Y + end + + _TLRM.ara_reset_slots!(ws, 1, 1) + for _ in 1:2 + info = _TLRM.ara_packed_pass!( + ws, sampler, 1, member_ids, progress; + eps_rel=1e-7, r_required=3) + @test info.nactive == 1 + end + @test progress[1] == 8 + + # A late member starts at offset zero while the older member enters its + # terminal width. This exercises the full-prefix/terminal-suffix split. + _TLRM.ara_reset_slots!(ws, 2, 1) + progress[2] = 0 + info = _TLRM.ara_packed_pass!( + ws, sampler, 2, member_ids, progress; + eps_rel=1e-7, r_required=3) + @test info.discarded == block - (maxrank % block) + @test progress[findfirst(==(1), member_ids)] == maxrank + @test progress[findfirst(==(2), member_ids)] == block + + # Recycle the retired slot for another hard member: admission resets its + # local offset, so it retains the complete rank budget. + retired_slot = first(info.retired) + _TLRM.ara_reset_slots!(ws, retired_slot, 1) + member_ids[retired_slot] = 2 + progress[retired_slot] = 0 + nactive = info.nactive + 1 + while nactive > 0 + info = _TLRM.ara_packed_pass!( + ws, sampler, nactive, member_ids, progress; + eps_rel=1e-7, r_required=3) + nactive = info.nactive + end + @test maximum(progress) == maxrank +end + +@testset "ARA convergence bookkeeping on backend arrays [$backend_name]" for (backend_name, ArrayType, synchronize) in TLR_BACKENDS + Random.seed!(3011) + s, count = 8, 2 + dR = ArrayType(hcat( + [1.0, 0.8, 0.7, fill(1e-12, 5)...], + [1.0, 0.9, 0.8, 0.7, fill(1e-12, 4)...], + )) + state = _TLRM.ARAConvergenceState(get_backend(dR), count) + _TLRM.ara_reset!(state, s, 2 * s) + active = _TLRM.ara_update_convergence!(state, dR, 1e-8, 3, s, 2 * s) + @test active == 0 # both members converged + @test Array(state.ranks) == Int32[3, 4] +end + +@testset "ARA basis construction on backend arrays [$backend_name]" for (backend_name, ArrayType, synchronize) in TLR_BACKENDS + Random.seed!(3012) + rng = MersenneTwister(1403) + m, n = 64, 64 + ranks = [5, 12, 20] + Xh = graded_batch(Float64, m, n, ranks, 1e-12, rng) + X = ArrayType(Xh) + ws = _TLRM.ARAWorkspace(Float64, get_backend(X), m, 48, + length(ranks); block=8) + res = _TLRM.ara_build_basis!(ws, dense_sampler(X, rng, ArrayType); + eps_rel=1e-6, r_required=4) + synchronize(ws.Q) + got = Array(res.ranks) + Q = Array(res.Q) + for b in eachindex(ranks) + @test ranks[b] <= got[b] <= ranks[b] + ws.block + Qb = Q[:, 1:got[b], b] + @test norm(Qb' * Qb - I, Inf) <= 1e-12 + @test norm(Xh[:, :, b] - Qb * (Qb' * Xh[:, :, b])) / + norm(Xh[:, :, b]) <= 1e-6 + end + # Breakdown must be handled on device too, not just on the host path. + @test _TLRM.ara_stopping_floor(Float64) ≈ sqrt(eps(Float64) / 2) +end + +# A2: optimal truncation of X ≈ Q Zᵀ. + +# Build (Q, Z) representing a matrix with a prescribed spectrum, so the optimal +# truncation error is known in closed form from Eckart-Young. +function truncation_fixture(::Type{T}, bm, bn, sQ, sigmas, rng) where {T} + Q = Matrix(qr(randn(rng, T, bm, sQ)).Q)[:, 1:sQ] + P = Matrix(qr(randn(rng, T, bn, sQ)).Q)[:, 1:sQ] + W = Matrix(qr(randn(rng, T, sQ, sQ)).Q) + Z = P * Diagonal(T.(sigmas)) * W' # so Q*Z' has singular values σ + return Q, Z +end + +@testset "ARA truncation [CPU]" begin + Random.seed!(3013) + rng = MersenneTwister(1501) + bm, bn, sQ = 48, 40, 12 + + @testset "empty co-range bypasses the SVD backend" begin + U0, S0, V0 = _TLRM.batched_thin_svd!(zeros(Float64, bn, 0, 3)) + @test size(U0) == (bn, 0, 3) + @test size(S0) == (0, 3) + @test size(V0) == (0, 0, 3) + end + + @testset "matches the Eckart-Young optimum" begin + sigmas = [2.0^(-k) for k in 0:(sQ-1)] # smooth decay + Q, Z = truncation_fixture(Float64, bm, bn, sQ, sigmas, rng) + X = Q * Z' + for tol in (1e-1, 1e-3, 1e-6) + U = zeros(Float64, bm, sQ, 1) + V = zeros(Float64, bn, sQ, 1) + ranks = zeros(Int32, 1); err = zeros(Float64, 1) + _TLRM.ara_truncate!(U, V, ranks, err, + reshape(copy(Q), bm, sQ, 1), + reshape(copy(Z), bn, sQ, 1); + tol, relative=true, maxrank=sQ) + r = Int(ranks[1]) + Ur, Vr = U[:, 1:r, 1], V[:, 1:r, 1] + achieved = norm(X - Ur * Vr') + optimal = sqrt(sum(abs2, sigmas[(r+1):end])) + # Optimality: the achieved error equals the Eckart-Young bound for + # the rank chosen, to round-off. + @test achieved ≈ optimal atol = 1e-12 rtol = 1e-8 + # The budget is met, and one rank less would have missed it. + @test achieved <= tol * norm(X) * (1 + 1e-8) + @test r == 1 || sqrt(sum(abs2, sigmas[r:end])) > tol * norm(X) + # The reported error is the achieved one, not a bound. + @test sqrt(err[1]) ≈ optimal atol = 1e-12 rtol = 1e-8 + @test norm(Ur' * Ur - I, Inf) <= 1e-12 + end + end + + @testset "orthonormal output despite zero columns in Q" begin + # ara_mask_breakdown! leaves exact zero columns in Q, so QᵀQ ≠ I. The + # retained right singular vectors must vanish on those rows, which is + # what keeps U = QW orthonormal. + sigmas = [1.0, 0.5, 0.25, 0.1, 0.0, 0.0] + s = length(sigmas) + Q, Z = truncation_fixture(Float64, bm, bn, s, sigmas, rng) + Q[:, 5:6] .= 0.0 # dead columns + Z[:, :] = Z * Diagonal([1, 1, 1, 1, 0, 0]) + @test norm(Q' * Q - I, Inf) > 0.5 # Q really is not orthonormal + U = zeros(Float64, bm, s, 1); V = zeros(Float64, bn, s, 1) + ranks = zeros(Int32, 1); err = zeros(Float64, 1) + _TLRM.ara_truncate!(U, V, ranks, err, reshape(Q, bm, s, 1), + reshape(copy(Z), bn, s, 1); + tol=1e-8, relative=true, maxrank=s) + r = Int(ranks[1]) + @test r == 4 + Ur = U[:, 1:r, 1] + @test norm(Ur' * Ur - I, Inf) <= 1e-12 + @test norm(Q * Z' - Ur * V[:, 1:r, 1]') / norm(Q * Z') <= 1e-12 + end + + @testset "ragged ranks stay in one batched call" begin + count = 3 + specs = ([1.0, 1e-9, 1e-9, 1e-9], [1.0, 0.5, 0.25, 1e-9], [1.0, 0.5, 0.25, 0.125]) + s = 4 + Qs = zeros(Float64, bm, s, count); Zs = zeros(Float64, bn, s, count) + for b in 1:count + q, z = truncation_fixture(Float64, bm, bn, s, specs[b], rng) + Qs[:, :, b] = q; Zs[:, :, b] = z + end + U = zeros(Float64, bm, s, count); V = zeros(Float64, bn, s, count) + ranks = zeros(Int32, count); err = zeros(Float64, count) + _TLRM.ara_truncate!(U, V, ranks, err, copy(Qs), copy(Zs); + tol=1e-6, relative=true, maxrank=s) + @test ranks == Int32[1, 3, 4] + for b in 1:count + r = Int(ranks[b]) + @test norm(U[:, 1:r, b]' * U[:, 1:r, b] - I, Inf) <= 1e-12 + # Surplus columns must be exactly zero, so the padded batch is safe + # to consume without per-member bookkeeping downstream. + @test all(iszero, U[:, (r+1):s, b]) + @test all(iszero, V[:, (r+1):s, b]) + end + end + + @testset "maxrank cap is authoritative and self-reporting" begin + sigmas = fill(1.0, 8) # flat: nothing is truncatable + s = 8 + Q, Z = truncation_fixture(Float64, bm, bn, s, sigmas, rng) + U = zeros(Float64, bm, 3, 1); V = zeros(Float64, bn, 3, 1) + ranks = zeros(Int32, 1); err = zeros(Float64, 1) + _TLRM.ara_truncate!(U, V, ranks, err, reshape(Q, bm, s, 1), + reshape(copy(Z), bn, s, 1); + tol=1e-8, relative=true, maxrank=3) + @test ranks[1] == 3 # saturation visible in the rank + @test sqrt(err[1]) ≈ sqrt(5.0) rtol = 1e-10 # 5 discarded unit values + end +end + +# `capture` adds an estimate of what the basis missed to the reported error and +# changes nothing else: zero leaves a member exactly as without it. +@testset "ARA truncation with a capture estimate [CPU]" begin + Random.seed!(3043) + rng = MersenneTwister(1601) + bm, bn, sQ = 24, 20, 8 + Q, Z = truncation_fixture(Float64, bm, bn, sQ, [10.0^-k for k in 0:sQ-1], rng) + Q3, Z3 = reshape(Q, bm, sQ, 1), reshape(Z, bn, sQ, 1) + outputs() = (zeros(Float64, bm, sQ, 1), zeros(Float64, bn, sQ, 1), + zeros(Int32, 1), zeros(Float64, 1)) + U0, V0, r0, e0 = outputs() + _TLRM.ara_truncate!(U0, V0, r0, e0, copy(Q3), copy(Z3); tol=1e-4, maxrank=sQ) + + @testset "capture = $c" for c in (0.0, 0.25) + U, V, r, e = outputs() + e .= c # the err_sq array itself + _TLRM.ara_truncate!(U, V, r, e, copy(Q3), copy(Z3); + tol=1e-4, maxrank=sQ, capture=e) + @test r == r0 && U == U0 && V == V0 + @test e[1] == e0[1] + c + end + + @test_throws ArgumentError _TLRM.ara_truncate!( + outputs()..., copy(Q3), copy(Z3); tol=1e-4, maxrank=sQ, + energy=[1.0], capture=[0.0]) +end + +@testset "ARA truncation on backend arrays [$backend_name]" for (backend_name, ArrayType, synchronize) in TLR_BACKENDS + Random.seed!(3014) + rng = MersenneTwister(1502) + bm, bn, sQ = 48, 40, 12 + sigmas = [2.0^(-k) for k in 0:(sQ-1)] + Qh, Zh = truncation_fixture(Float64, bm, bn, sQ, sigmas, rng) + X = Qh * Zh' + U = ArrayType(zeros(Float64, bm, sQ, 1)) + V = ArrayType(zeros(Float64, bn, sQ, 1)) + ranks = ArrayType(zeros(Int32, 1)); err = ArrayType(zeros(Float64, 1)) + _TLRM.ara_truncate!(U, V, ranks, err, + ArrayType(reshape(Qh, bm, sQ, 1)), + ArrayType(reshape(Zh, bn, sQ, 1)); + tol=1e-6, relative=true, maxrank=sQ) + synchronize(U) + r = Int(Array(ranks)[1]) + Ur = Array(U)[:, 1:r, 1]; Vr = Array(V)[:, 1:r, 1] + optimal = sqrt(sum(abs2, sigmas[(r+1):end])) + @test norm(X - Ur * Vr') ≈ optimal atol = 1e-12 rtol = 1e-6 + @test norm(Ur' * Ur - I, Inf) <= 1e-11 + @test sqrt(Array(err)[1]) ≈ optimal atol = 1e-12 rtol = 1e-6 + + # The batched SVD must run on device. The generic fallback copies to + # the host and would pass every numerical check above while quietly + # costing a round trip per tile, so assert residency directly. + Zd = ArrayType(reshape(Zh, bn, sQ, 1)) + Ud, Sd, Vd = _TLRM.batched_thin_svd!(Zd) + @test Ud isa typeof(Zd) && Vd isa typeof(Zd) + @test Array(Sd)[:, 1] ≈ svd(Zh).S rtol = 1e-12 + + U0, S0, V0 = _TLRM.batched_thin_svd!( + ArrayType(zeros(Float64, bn, 0, 2)), + ) + @test size(U0) == (bn, 0, 2) + @test size(S0) == (0, 2) + @test size(V0) == (0, 0, 2) + @test backend_name == "CPU" || U0 isa typeof(Zd) +end + +# Regression: the projection must be INTERLEAVED with the two Cholesky passes, +# `(P·CQR)²` as in Algorithm 2.3 lines 22-27 -- not `P²·CQR²`. +# +# The two are different algorithms in finite precision. A column numerically +# dependent on the rest of its block has a within-block residual of size +# `O(u‖Y‖)`, the same order as the `O(u‖Y‖)` overlap with `Q` that BCGS leaves; +# so its direction has an `O(1)` fraction inside `span(Q)`. The first Cholesky +# normalizes it to unit length, freezing that fraction at `O(1)`. Only a +# projection placed *after* that amplification removes it. +# +# The exposure needs a mixed (part-genuine, part-null) block in a pass *after* +# the first -- pass 1 has no basis to lose orthogonality against -- and is worst +# when the block has just 1-2 null columns. Batched ordering failed ~1/3 of +# seeds here with `‖QᵀQ−I‖` up to 1.0; interleaved is clean. +# ara_mask_breakdown! leaves exact zero columns in Q, so Z = XᴴQ has some and +# its SVD has zero singular values. cuSOLVER's gesvda (the CUDA batched_thin_svd!) +# returns NaN left vectors for those; V = P·σ must still be zero there. +@testset "ARA truncation with zero singular values [$backend_name]" for (backend_name, ArrayType, synchronize) in TLR_BACKENDS + Random.seed!(3047) + rng = MersenneTwister(1801) + bm, bn, s, live = 48, 40, 12, 8 + Qh, Zh = truncation_fixture(Float64, bm, bn, s, [2.0^(-k) for k in 0:(s-1)], rng) + Qh[:, (live+1):s] .= 0.0 # dead columns, as the mask leaves them + Zh[:, (live+1):s] .= 0.0 + X = Qh * Zh' + @testset "maxrank $maxrank, tol $tol" for (maxrank, tol) in ((s, 1e-6), (s, 0.0), (live, 1e-6)) + U = ArrayType(zeros(Float64, bm, maxrank, 1)) + V = ArrayType(zeros(Float64, bn, maxrank, 1)) + ranks = ArrayType(zeros(Int32, 1)); err = ArrayType(zeros(Float64, 1)) + _TLRM.ara_truncate!(U, V, ranks, err, ArrayType(reshape(Qh, bm, s, 1)), + ArrayType(reshape(copy(Zh), bn, s, 1)); tol, maxrank) + synchronize(U) + Uh, Vh = Array(U)[:, :, 1], Array(V)[:, :, 1] + @test all(isfinite, Uh) && all(isfinite, Vh) && isfinite(Array(err)[1]) + @test norm(X - Uh * Vh') <= max(tol, 1e-12) * norm(X) + end +end + +@testset "ARA interleaves projection with the Cholesky passes [CPU]" begin + Random.seed!(3015) + T = Float64 + bm, bn = 32, 34 + for (r_true, block) in ((6, 4), (7, 4), (20, 8)) + worst_orth = 0.0 + worst_rank = 0 + for seed in 1:40 + rng = MersenneTwister(seed) + Uo = Matrix(qr(randn(rng, T, bm, r_true)).Q)[:, 1:r_true] + Vo = Matrix(qr(randn(rng, T, bn, r_true)).Q)[:, 1:r_true] + X = Uo * Diagonal(collect(range(1.0, 0.6; length=r_true))) * Vo' + ws = _TLRM.ARAWorkspace(T, CPU(), bm, 32, 1; block) + omega = zeros(T, bn, ws.block, 1) + sampler = function (Y, width) + Om = view(omega, :, 1:width, 1) + Random.randn!(Om) + copyto!(view(Y, :, 1:width, 1), X * Om) + return Y + end + res = _TLRM.ara_build_basis!(ws, sampler; eps_rel=1e-7, r_required=4) + r = Int(Array(res.ranks)[1]) + Qr = Array(res.Q)[:, 1:r, 1] + worst_orth = max(worst_orth, opnorm(Qr' * Qr - I, Inf)) + worst_rank = max(worst_rank, abs(r - r_true)) + end + # Batched ordering gave ~1e0 here; interleaved must stay at round-off. + @test worst_orth <= 1e-10 + @test worst_rank == 0 + end +end diff --git a/test/tlr/core/compression/compress.jl b/test/tlr/core/compression/compress.jl new file mode 100644 index 00000000..513ff8db --- /dev/null +++ b/test/tlr/core/compression/compress.jl @@ -0,0 +1,138 @@ +# Dense to TLR and FTLR: constructors, reusable ARA staging, boundary batches and +# packed tile compression, src/tlr/core/compression/compress.jl and workspace.jl. +# Helpers: test/setup/tlr.jl. + +function full_tlr_rectangular_fixture(::Type{T}) where {T} + tile_size = (3, 4) + m, n, maxrank = 8, 11, 3 + A = zeros(T, m, n) + for j in 1:cld(n, tile_size[2]), i in 1:cld(m, tile_size[1]) + p0, q0 = (i-1)*tile_size[1]+1, (j-1)*tile_size[2]+1 + tm, tn = min(tile_size[1], m-p0+1), min(tile_size[2], n-q0+1) + r = min(maxrank, tm, tn, mod(i + 2j, maxrank) + 1) + A[p0:p0+tm-1, q0:q0+tn-1] .= + make_rect_lowrank_tile(T, tm, tn, r; seed=100i+j) + end + return (; A, tile_size, maxrank) +end + +@testset "dense to finalized TLR/FTLR [CPU]" begin + Random.seed!(3016) + boundary = boundary_dense_fixture(Float64) + ws = TileLowRank.FTLRCompressionWorkspace( + boundary.A, 4; maxrank=3, diagonal=:dense) + A = TileLowRank.TLRMatrix( + boundary.A, 4; maxrank=3, tol=1e-7, workspace=ws, + rank_multiple=8) + @test TileLowRank.rank_multiple(A) == 8 + @test all(k -> TileLowRank.ranks(A)[expected_storage_slot(A, k, k)] == 0, + 1:TileLowRank.ndiag_tiles(A)) + @test norm(reconstruct_tlr(A) - boundary.A) / norm(boundary.A) <= 1e-7 + assert_tile_rank_and_error(A, 1, 2, 2, boundary.a12; atol_rank=1, rtol_error=1e-7) + assert_tile_rank_and_error(A, 2, 1, 3, boundary.a21; atol_rank=1, rtol_error=1e-7) + + # The same numerical staging can be reused; the returned packed matrix is + # newly allocated because its offsets depend on this pass's ranks. + B = TileLowRank.TLRMatrix( + boundary.A, 4; maxrank=3, tol=1e-7, workspace=ws) + @test B !== A + @test B.offdiag.outer.data !== A.offdiag.outer.data + @test reconstruct_tlr(B) ≈ boundary.A rtol=1e-7 + + full = full_tlr_rectangular_fixture(Float64) + C = TileLowRank.CompressedFTLRMatrix( + full.A, full.tile_size; maxrank=full.maxrank, tol=1e-9, + rank_multiple=8) + @test TileLowRank.grid_size(C) == (3, 3) + @test TileLowRank.tile_size(C, 3, 3) == (2, 3) + @test norm(reconstruct_tlr(C) - full.A) / norm(full.A) <= 1e-9 + @test all(r -> r <= full.maxrank, TileLowRank.ranks(C)) + + small = Float64[2 1; -1 3] + S = TileLowRank.TLRMatrix(small, 4; maxrank=2, tol=1e-12) + @test size(TileLowRank.dense_diag(S), 3) == 0 + @test size(TileLowRank.dense_diag_corner(S)) == (2, 2, 1) + @test reconstruct_tlr(S) == small + @test_throws ArgumentError TileLowRank.TLRMatrix( + small, 4; maxrank=2, r_required=0) +end + +@testset "compression residual and rank-cap semantics [CPU]" begin + Random.seed!(3017) + b, maxr = 32, 16 + rng = MersenneTwister(7) + Q1 = Matrix(qr(randn(rng, b, b)).Q) + Q2 = Matrix(qr(randn(rng, b, b)).Q) + hard = Q1 * Diagonal(10.0 .^ range(0, -6, length=b)) * Q2' + easy = make_lowrank_tile(Float64, b, 4; seed=2) + dense = assemble_block_matrix( + make_dense_tile(Float64, b; seed=1), hard, + easy, make_dense_tile(Float64, b; seed=3)) + A = TileLowRank.TLRMatrix(dense, b; maxrank=maxr, tol=1e-3) + hard_idx = expected_storage_slot(A, 1, 2) + easy_idx = expected_storage_slot(A, 2, 1) + @test Int(TileLowRank.ranks(A)[hard_idx]) == maxr + @test TileLowRank.residuals(A)[hard_idx] > 1e-3 + @test Int(TileLowRank.ranks(A)[easy_idx]) == 4 + @test TileLowRank.residuals(A)[easy_idx] <= 1e-3 + + zero_dense = assemble_block_matrix( + make_dense_tile(Float64, b; seed=9), zeros(Float64, b, b), + easy, make_dense_tile(Float64, b; seed=11)) + Z = TileLowRank.TLRMatrix(zero_dense, b; maxrank=maxr, tol=0) + zero_idx = expected_storage_slot(Z, 1, 2) + @test TileLowRank.ranks(Z)[zero_idx] == 0 + @test TileLowRank.residuals(Z)[zero_idx] == 0 +end + +@testset "packed tile compression workspace [CPU]" begin + Random.seed!(3018) + rng = MersenneTwister(7) + b, count, cap = 6, 4, 3 + true_ranks = [2, 2, 3, 3] + tiles = zeros(Float64, b, b, count) + for k in 1:count + r = true_ranks[k] + tiles[:, :, k] .= randn(rng, b, r) * randn(rng, r, b) + end + U = zeros(Float64, b, cap, count) + V = zeros(Float64, b, cap, count) + ws = _TLRM.make_category_workspace( + (b, b), [(k, 1) for k in 1:count], U, V) + @test parent(ws.Z) === V + _TLRM.compress_tiles!( + _TLRM.PackedTiles(tiles), ws; eps_sq=1e-12, rel=false, r_required=4) + got = Array(ws.ranks) + @test got == true_ranks + for k in 1:count + r = got[k] + @test norm(tiles[:, :, k] - U[:, 1:r, k] * V[:, 1:r, k]') / + norm(tiles[:, :, k]) <= 1e-8 + @test sqrt(ws.errors_sq[k]) <= 1e-8 * norm(tiles[:, :, k]) + end +end + +# Compression on the device of a matrix whose tiles break down in ARA's +# Cholesky-QR, so the truncation sees zero singular values (see the ARA test +# "ARA truncation with zero singular values"): finite, and as accurate as the CPU. +@testset "compression with breakdown [$backend_name]" for (backend_name, ArrayType, synchronize) in filter(b -> b[1] != "CPU", TLR_BACKENDS) + Random.seed!(3048) + n, b, maxrank = 512, 64, 16 + A = [1 / (1 + abs(i - j)) for i in 1:n, j in 1:n] + I + M = TileLowRank.TLRMatrix(ArrayType(A), b; maxrank, tol=1e-8, rel=true) + D = ArrayType(zeros(n, n)); TileLowRank.uncompress!(D, M); synchronize(D) + Random.seed!(3048) + Mh = TileLowRank.TLRMatrix(A, b; maxrank, tol=1e-8, rel=true) + Dh = zeros(n, n); TileLowRank.uncompress!(Dh, Mh) + @test all(isfinite, Array(D)) + @test norm(Array(D) - A) / norm(A) <= 10 * max(norm(Dh - A) / norm(A), 1e-12) +end + +@testset "dense constructors [$backend_name]" for (backend_name, ArrayType, synchronize) in filter(b -> b[1] in ("CUDA", "AMDGPU"), TLR_BACKENDS) + Random.seed!(3019) + boundary = boundary_dense_fixture(Float32) + dense = ArrayType(boundary.A) + A = TileLowRank.TLRMatrix(dense, 4; maxrank=3, tol=1f-4) + synchronize(A.offdiag.outer.data) + @test norm(reconstruct_tlr(A) - boundary.A) / norm(boundary.A) <= 5f-3 +end diff --git a/test/tlr/core/compression/norms.jl b/test/tlr/core/compression/norms.jl new file mode 100644 index 00000000..9a39a0aa --- /dev/null +++ b/test/tlr/core/compression/norms.jl @@ -0,0 +1,27 @@ +# Batched tile norms and the orthogonalization type, src/tlr/core/compression/norms.jl +# and src/tlr/core/compression/blas_utils.jl. +# Helpers: test/setup/tlr.jl. + +@testset "TLR numerical primitives [CPU]" begin + Random.seed!(3006) + @test _TLRM.tlr_orthogonalization_type(Float16) == Float32 + @test _TLRM.tlr_orthogonalization_type(Float32) == Float64 + @test _TLRM.tlr_orthogonalization_type(Float64) == Float64 + + rng = MersenneTwister(511) + X = randn(rng, Float32, 7, 5, 4) + norm_sq = zeros(Float64, size(X, 3)) + @inferred _TLRM.batch_frobenius_norms_sq!(norm_sq, X) + @test norm_sq ≈ [sum(abs2, X[:, :, k]) for k in axes(X, 3)] +end + +@testset "TLR numerical primitives [$backend_name]" for (backend_name, ArrayType, synchronize) in filter(b -> b[1] == "CUDA", TLR_BACKENDS) + Random.seed!(3007) + rng = MersenneTwister(512) + X = ArrayType(randn(rng, Float32, 7, 5, 4)) + norm_sq = ArrayType(zeros(Float64, size(X, 3))) + _TLRM.batch_frobenius_norms_sq!(norm_sq, X) + synchronize(norm_sq) + @test Array(norm_sq) ≈ + [sum(abs2, Float64.(Array(X[:, :, k]))) for k in axes(X, 3)] rtol=1e-10 +end diff --git a/test/tlr/core/tlr_matrix.jl b/test/tlr/core/tlr_matrix.jl new file mode 100644 index 00000000..b23b034a --- /dev/null +++ b/test/tlr/core/tlr_matrix.jl @@ -0,0 +1,32 @@ +# TLRMatrix and the TileLowRank exports, src/tlr/core/tlr_matrix.jl and src/tlr/core/tlr.jl. +# Helpers: test/setup/tlr.jl. + +@testset "top-level TLR API [CPU]" begin + Random.seed!(3001) + @test TLRMatrix === TileLowRank.TLRMatrix + @test CompressedFTLRMatrix === TileLowRank.CompressedFTLRMatrix + @test uncompress! === TileLowRank.uncompress! +end + +@testset "finalized TLRMatrix layout [CPU]" begin + Random.seed!(3002) + rank_grid = Int[0 2 1; 1 0 1; 1 1 0] + A = TileLowRank.TLRMatrix( + KernelAbstractions.CPU(), Float64, 10, 10, 4, rank_grid; + rank_multiple=8) + @test !ismutable(A) + @test TileLowRank.offdiagonal(A) isa TileLowRank.CompressedFTLRMatrix + @test TileLowRank.rank_multiple(A) == 8 + @test TileLowRank.maxrank(A) == 2 + @test size(TileLowRank.dense_diag(A)) == (4, 4, 2) + @test size(TileLowRank.dense_diag_corner(A)) == (2, 2, 1) + @test length(TileLowRank.get_factors(A, 1, 2)) == 2 + @test size(TileLowRank.get_factors(A, 1, 2)[1]) == (4, 2) + @test size(TileLowRank.get_factors(A, 3, 1)[1]) == (2, 1) + @test_throws ArgumentError TileLowRank.get_factors(A, 1, 1) + + bad = copy(rank_grid) + bad[2, 2] = 1 + @test_throws ArgumentError TileLowRank.TLRMatrix( + KernelAbstractions.CPU(), Float64, 10, 10, 4, bad) +end