diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index b3a4c2d7..b8af1eac 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -15,7 +15,7 @@ jobs: test: name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} - ${{ github.event_name }} runs-on: ${{ matrix.os }} - timeout-minutes: 60 + timeout-minutes: 60 # 1.10 and nightly with coverage take 21-37 min on GitHub runners; Julia 1 runs without it permissions: # needed to allow julia-actions/cache to proactively delete old caches that it has created actions: write contents: read @@ -24,6 +24,7 @@ jobs: matrix: version: - '1.10' + - '1' - 'nightly' os: - ubuntu-latest @@ -38,8 +39,12 @@ jobs: - uses: julia-actions/cache@v2 - uses: julia-actions/julia-buildpkg@v1 - uses: julia-actions/julia-runtest@v1 + with: + coverage: ${{ matrix.version != '1' }} # coverage on Julia 1.13 makes scalar loops 45-1400x slower; 1.10 and nightly report it - uses: julia-actions/julia-processcoverage@v1 + if: matrix.version != '1' - uses: codecov/codecov-action@v4 + if: matrix.version != '1' with: files: lcov.info token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.gitignore b/.gitignore index 95731a59..85e20afa 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,13 @@ *.jl.cov *.jl.mem /Manifest.toml +/test/Manifest.toml /docs/Manifest.toml +/benchmark/Manifest.toml /docs/build/ +/docs/src/citing.md +/docs/src/dev/contributing.md +/docs/src/dev/testing.md +/docs/src/dev/benchmarks.md +/docs/src/index.md +/docs/src/assets/assistant-config.js 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..75078c79 --- /dev/null +++ b/CITATION.md @@ -0,0 +1,107 @@ +# 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) + +Poster, WHPC at ISC 2026: + +[![Hierarchical Recursive Precision for Accelerating Symmetric Linear Solves on MXUs, poster](docs/src/assets/whpc_isc_poster.png)](docs/src/assets/whpc_isc_poster.pdf) + +```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..b13d6798 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,81 @@ +# Contributing + +Contributions are welcome through pull requests on +[GitHub](https://github.com/NextLinearAlgebra/NextLA.jl). + +## Modules + +| Module | Folder | Depends on | Loaded with | +|:------------------------|:------------|:----------------------|:--------------------------------| +| `NextLA` | `src/dense` | nothing in the others | `using NextLA` | +| `NextLA.MixedPrecision` | `src/mxp` | `NextLA` | `using NextLA.MixedPrecision` | + +`MixedPrecision` is a submodule: it lives inside `NextLA`, can use anything from it through +`..NextLA`, and is not re-exported by it. The dependency runs one way only. Code in `src/dense` +never refers to the submodule, so `NextLA` builds and works with its `include` line removed. + +## Repository layout + +``` +src/ +├── NextLA.jl module entry point, includes every feature +├── 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/ +ext/ +├── NextLACUDAExt.jl + ext/cuda/ cuBLAS / cuSOLVER methods +├── NextLAAMDGPUExt.jl + ext/amdgpu/ rocBLAS / rocSOLVER methods +├── NextLAoneAPIExt.jl + ext/oneapi/ oneMKL methods +└── NextLAMetalExt.jl + ext/metal/ MPS methods +test/ mirrors src/ (dense/, mxp/): the test for src/.jl is + test/.jl; shared helpers in test/setup/ +docs/ this documentation (Documenter.jl) +``` + +Each of `dense/` and `mxp/` 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. In `dense/`, 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. `src/NextLA.jl` includes those entry files and a few single files +(`dense/core/NextLAMatrix.jl`, `dense/blas/axpy.jl`, `dense/blas/gerc.jl`). The submodule is +included as a whole: `src/NextLA.jl` includes `mxp/core/mxp.jl`, which includes its own files from +`core/`, `blas/` and `lapack/`. Exports stay in the file that defines the symbol. + +How to run all or some of the tests, on the CPU or a GPU: [`test/README.md`](test/README.md). + +## Adding a routine to this repository structure + +1. Put the code in the matching folder, for example `src/dense/blas/syrk/`, and include it from that + folder's entry file (`syrk/syrk.jl`). In `mxp/`, include it from `mxp/core/mxp.jl`. +2. Export the new name in the file that defines it. +3. Add its test at the same path under `test/`, for example `test/dense/blas/syrk/.jl`. The + test runner finds it automatically. +4. Give it a docstring with a short `# Examples` block. +5. Add the file to the `Pages = [...]` list of its API page in `docs/src/api/`, for example + `docs/src/api/dense/blas/syrk.md`. API pages show only the files they list, and the documentation + build fails if an exported, documented name appears on no page. +6. For GPU support through a vendor library, add a method for that backend's array type + (`CuArray`, `ROCArray`, `oneArray` or `MtlArray`) in `ext//`, one file per routine group + (`ext/cuda/syrk.jl`, `ext/cuda/potrf.jl`, ...), included from `ext/NextLAExt.jl`. Arrays + without such a method use the portable KernelAbstractions code. + +## Reporting a bug + +Open an [issue](https://github.com/NextLinearAlgebra/NextLA.jl/issues) with a short example that +reproduces the problem and the output of `versioninfo()` and `Pkg.status()`. For a GPU problem, also +include the GPU package's version information, such as `CUDA.versioninfo()`. diff --git a/Project.toml b/Project.toml index 895a530d..780cf1b7 100644 --- a/Project.toml +++ b/Project.toml @@ -4,6 +4,7 @@ authors = ["Rabab Alomairy, Evelyne Ringoot, Sophie Xuan, Vicki Carrica, Maxwell version = "0.2.3" [deps] +BFloat16s = "ab4f0b2a-ad5b-11e8-123f-65d77653426b" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" @@ -21,13 +22,8 @@ NextLAMetalExt = "Metal" NextLAoneAPIExt = "oneAPI" [compat] +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..a58e3037 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,171 @@ - # 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. + +## Features + +- **Unified API.** Implements LAPACK/BLAS subroutines in Julia, avoiding type- and hardware-specific implementations. + Supports `Float64`, `Float32`, `Float16`, `Float8` (in mixed precision), 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. See [Benchmarks](docs/src/manual/benchmarks.md). +- **Mixed precision.** Recursive factorizations on matrices that store each block in its own + precision, from `Float64` down to `Float8_E5M2`. See [Mixed precision](docs/src/manual/mixed_precision.md). +- **Future-proof and composable.** Designed for extensibility, allowing new data types and hardware architectures to be + integrated with minimal modifications. + +[![Hierarchical Recursive Precision for Accelerating Symmetric Linear Solves on MXUs, poster](docs/src/assets/whpc_isc_poster.png)](docs/src/assets/whpc_isc_poster.pdf) + +## Why Julia for dense linear algebra? + +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. + +## Installation + +NextLA is registered in the Julia General registry and is tested on Julia 1.10, the latest release and nightly. + +```julia +using Pkg +Pkg.add("NextLA") # latest release + +# development version +Pkg.add(url = "https://github.com/NextLinearAlgebra/NextLA.jl") +``` + +For GPU support, also add the backend package you want (`CUDA`, `AMDGPU`, `oneAPI` or `Metal`). + +## Quick start + +### On the CPU + +```julia +using NextLA # for potrf_recursive!, trsm! +using LinearAlgebra # for I + +n = 2048 +A = rand(n, n) +S = A * A' + n * I # symmetric positive definite +B = rand(n, 256) + +F = copy(S) +potrf_recursive!(F) # Cholesky: S = L * L', L stored in 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 # output: true +``` + +### On a GPU + +```julia +# For AMD GPUs, load AMDGPU and use ROCArray instead. +using NextLA # for potrf_recursive!, trsm! +using CUDA # for CUDA.rand +using LinearAlgebra # for I + +A = CUDA.rand(Float32, 4096, 4096) # on the GPU +S = A * A' + 4096f0 * I +B = CUDA.rand(Float32, 4096, 256) + +F = copy(S) +potrf_recursive!(F) # same call as on the CPU -**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. +X = copy(B) +trsm!('L', 'L', 'N', 'N', 1f0, F, X) # solve L Y = B +trsm!('L', 'L', 'T', 'N', 1f0, F, X) # solve Lᵀ X = Y +S * X ≈ B # output: true +``` -![Handout](handout.png) +### Mixed precision -## 🚀 Features +```julia +using NextLA # for potrf_recursive! +using NextLA.MixedPrecision # for the mixed-precision matrices +using LinearAlgebra # for I, norm -- **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. +A = rand(2048, 2048) +S = A * A' + 2048I -## 📌 Why Julia for Dense Linear Algebra? +# off-diagonal block stored in Float32, diagonal blocks in Float64 +M = SymmMixedPrec(S, 'L'; precisions = DataType[Float32, Float64]) +potrf_recursive!(M) # Cholesky on the mixed-precision matrix -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. +L = reconstruct_matrix(TriMixedPrec(M)) # the factor as a dense matrix +norm(L * L' - S) / norm(S) < 1e-6 # output: true +``` -## 📈 Performance +See the [documentation](https://nextlinearalgebra.github.io/NextLA.jl/dev/) for the full guide and API reference. -Benchmarks indicate that **NextLA.jl** achieves performance **comparable to or better than** state-of-art for medium to large problem sizes. Key highlights: +## Documentation -- **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**. +The documentation is built with [Documenter.jl](https://documenter.juliadocs.org/). To build it locally: -## 📚 References +```bash +julia --project=docs -e 'using Pkg; Pkg.develop(PackageSpec(path=pwd()))' +julia --project=docs -e 'using Pkg; Pkg.instantiate()' +julia --project=docs docs/make.jl +``` -```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} -} +Then open `docs/build/index.html`. -@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} -} +## Running the tests + +```bash +julia --project -e 'using Pkg; Pkg.test()' ``` -## 👥 Contributors - -- **Rabab Alomairy** (@Rabab53) -- **Sophie Xuan** (@Azura-yuwi) -- **Evelyne Ringoot** (@evelyne-ringoot) -- **Vicki Carrica** (@vickicarrica) -- **Maxwell Onyango** (@maxmlewa) -- **Julian Samaroo** (@jpsamaroo) + +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). + +## Getting help + +Questions, bug reports and feature requests go to the +[GitHub issues](https://github.com/NextLinearAlgebra/NextLA.jl/issues). + +## Citing + +If you use NextLA.jl in your research, please cite the papers listed in [CITATION.md](CITATION.md). +GitHub's "Cite this repository" button uses [CITATION.cff](CITATION.cff). + +## Contributing + +Pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) describes the repository layout and the +modules, and [test/README.md](test/README.md) explains how to run all or some of the tests, on the CPU +or a GPU. + +### 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 + +NextLA.jl is released under the [MIT License](LICENSE) (copyright 2024 Rabab Alomairy). diff --git a/benchmark/Project.toml b/benchmark/Project.toml new file mode 100644 index 00000000..b59be1c2 --- /dev/null +++ b/benchmark/Project.toml @@ -0,0 +1,9 @@ +[deps] +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +NextLA = "d37ed344-79c4-486d-9307-6d11355a15a3" +Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" + +[sources] +NextLA = {path = ".."} diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 00000000..7cf4f8ea --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,116 @@ +# NextLA benchmarks + +`benchmark/run.jl` times NextLA's recursive routines against the vendor libraries, dense and +mixed precision. These are the runs behind the Manual's +[Benchmarks](../docs/src/manual/benchmarks.md) page, so the same command reproduces it on your +machine. + +## Setup + +Once, from the NextLA folder: + +```bash +julia --project=benchmark -e 'using Pkg; Pkg.develop(path="."); Pkg.instantiate()' +``` + +To benchmark on an NVIDIA GPU, also add CUDA.jl to the benchmark environment: + +```bash +julia --project=benchmark -e 'using Pkg; Pkg.add("CUDA")' +``` + +## Running + +```bash +julia --project=benchmark benchmark/run.jl # every routine, on one device: the GPU if CUDA works, else the CPU +julia --project=benchmark benchmark/run.jl gemm potrf # some routines +julia --project=benchmark benchmark/run.jl '!lu' # all but LU +julia --project=benchmark benchmark/run.jl --list # what would run +julia --project=benchmark benchmark/run.jl potrf --backends=CUDA --n=4096,8192,16384 +julia --project=benchmark benchmark/run.jl trsm --types=Float32 --mixed=F16/F32 +julia --project=benchmark benchmark/run.jl --backends=CPU --n=1024,2048 --leaf=512 +``` + +A run uses one device, never both: the GPU when CUDA.jl is installed and finds one, otherwise the +CPU. `--backends=CPU` or `--backends=CUDA` chooses it; to compare the two, run twice. + +Run with one Julia thread (the default), as the docs page does. The BLAS library uses its own +threads. + +The script is three files: `run.jl` reads the command line and starts the run; `routines.jl` has +the six routines, their test matrices and exactly what each line calls; `harness.jl` measures the +points (the timing rule, the GPU waits) and writes the results. + +## Routines + +| Name | NextLA (dense) | NextLA (mixed precision) | Vendor | +|---|---|---|---| +| `gemm` | `recgemm!`; `gemmEx!` with `Float16` inputs | `recgemm!` into `FullMixedPrec` | `mul!` (cuBLAS, BLAS) | +| `syrk` | `recsyrk!`; `recsyrk!` with `Float16` `A` | `recsyrk!` into `SymmMixedPrec` | `syrk!` | +| `trsm` | `unified_rectrxm!` (solve) | the same with `TriMixedPrec` | `trsm!` | +| `trmm` | `unified_rectrxm!` (multiply) | the same with `TriMixedPrec` | `trmm!` | +| `potrf` | `potrf_recursive!` | `potrf_recursive!` on `SymmMixedPrec` | `LAPACK.potrf!` (cuSOLVER, LAPACK) | +| `lu` | `lu_recursive_nopiv!` (no pivoting) | `lu_recursive!` on `FullMixedPrec` | `LAPACK.getrf!` (pivoting) | + +All on square `n × n` matrices: triangles from the lower side, without transposes. The test +matrices are random and made well conditioned: `n` added to the diagonal (triangles, LU), or +`A + Aᵀ + 2n I` (Cholesky). + +## Options + +| Option | Meaning | Default | +|---|---|---| +| `--backends=` | `CPU` or `CUDA`, one per run | `CUDA` if CUDA.jl is installed and works, else `CPU` | +| `--types=` | dense lines: `Float64`, `Float32`, `Float16` (`Float16` inputs with `Float32` accumulation, `gemm` and `syrk` only) | all three | +| `--mixed=` | container lines: `F32/F64`, `F16/F64`, `F16/F32`, or `none` | all three | +| `--n=` | sizes | `4096,8192,16384,32768` (CUDA), `2048,4096,8192,16384` (CPU) | +| `--leaf=` | leaf size of the containers | 4096 (CUDA), 2048 (CPU) | +| `--reps=` | at most this many timed calls per point; the fastest is kept | 5 | +| `--tmax=` | optional cap: skip a line's larger sizes after a call longer than this (seconds) | none: every size runs | +| `--casemax=` | optional cap: skip a line's larger sizes once it has used this much time (seconds) | none | +| `--cool=` | CUDA: before each size, wait until the GPU is at or below this temperature (°C) | off | +| `--no-vendor` | leave out the vendor lines | | +| `--out=` | results file | `benchmark--.jsonl` | + +`F16/F32` means the off-diagonal blocks are stored in `Float16` and the diagonal leaves in +`Float32`, with `log₂(n / leaf)` levels; at `n ≤ leaf` the container is one leaf. + +## How each point is timed + +- The inputs, and any mixed-precision container, are rebuilt before every call, outside the timer. +- The time is the fastest of at least 2 calls, with the device synchronized, so a first call that + compiles never stands alone. More calls are made, up to `--reps`, only while they are short: the + timing stops once a call takes more than 0.3 s or the calls add up to 1 s. +- Every size runs, however long it takes. `Float64` is much slower than `Float32` on many GPUs, + so a full run with `Float64` up to `n = 32768` can take hours there; `--n`, `--types` or `--tmax` + make it shorter. +- On CUDA, each size first waits until no other process uses the GPU. +- Random inputs are seeded per size (`Random.seed!` and `CUDA.seed!`). +- GFLOP/s use the standard flop counts: + + | Routine | Flops | + |---|---| + | GEMM | `2n³` | + | SYRK, TRSM, TRMM | `n³` | + | Cholesky | `n³/3` | + | LU | `2n³/3` | +- For the mixed-precision lines, the time to build the container is recorded separately + (`"kind":"build"`), since converting a matrix is not free. + +## Results + +The run prints each point as it goes, then a GFLOP/s table per routine. Every point is also written +to the results file, one JSON object per line: +- `id`, `backend`, `setting`, `impl`, `variant`, `n`, `depth`, `precisions`, `kind` (`time` or + `build`), `time_s`, `gflops`, `reps`, `status`, and `msg` for an error; +- a first line, `"id":"__env__"`, with the device, the Julia version, the NextLA version and the + thread counts. + +These are the fields of the files behind the docs page. + +## Notes + +- Julia 1.10 is the version the docs page was run with; newer versions work too. A point that + fails is reported as an error and the run goes on. +- Only the CPU and CUDA are supported for now. NextLA's routines run on AMDGPU, oneAPI and Metal + too, but the vendor comparisons there are not in this runner yet. diff --git a/benchmark/harness.jl b/benchmark/harness.jl new file mode 100644 index 00000000..8ec3b767 --- /dev/null +++ b/benchmark/harness.jl @@ -0,0 +1,173 @@ +# How the benchmarks are run: device helpers, the timing rule, waiting for the GPU, and the results file. +# +# How one point (one line at one size n) is measured +# 1. The inputs are made fresh for this size, from a fixed seed (the same data every run). +# 2. On CUDA: wait until no other process uses the GPU, and (with --cool) until it is cool enough. +# 3. Time single calls: before each, reset the inputs (and rebuild any container) OUTSIDE the timer; +# the call is timed with the device synchronized. Keep the FASTEST call. +# 4. At least MIN_CALLS calls, at most CFG.reps; stop early once a call is slow enough +# (> ENOUGH_ONE s) or the calls add up (> ENOUGH_ALL s) that more would only cost time. + +const GPU = CFG.gpu + +# ---------------------------------------------------------------------------- device helpers +sync() = GPU ? CUDA.device_synchronize() : nothing # wait for every stream: NextLA's tasks run on their own +dev(A) = GPU ? CuArray(A) : A # host matrix -> the benchmark device +rnd(T, d...) = GPU ? CUDA.rand(T, d...) : rand(T, d...) +freemem() = GPU ? (GC.gc(true); CUDA.reclaim()) : GC.gc(true) +seed(n) = (Random.seed!(n); GPU && CUDA.seed!(n)) # CUDA.rand needs its own seed +const VBLAS, VLAPACK = GPU ? ("cuBLAS", "cuSOLVER") : ("BLAS", "LAPACK") +const DEVICE = GPU ? CUDA.name(CUDA.device()) : Sys.cpu_info()[1].model + +# ---------------------------------------------------------------------------- lines and points +# A point: what to call before each timed call (reset), the timed call (run), and optionally +# a container build that is timed once on its own (build, written as kind = "build"). +Base.@kwdef struct Point + reset::Function + run::Function + build::Union{Nothing,Function} = nothing +end + +# A line: one curve on the docs page, timed at every size. +struct Line + routine::String # "gemm", ... + label::String # legend name, as on the docs page + setting::String # results-file code: S0 dense F64, S4 dense F32, S2/S3/S5 mixed, S6 F16 inputs + impl::String # what is called (results file) + mixed::Union{Nothing,String} # "F16/F32" etc. for container lines + make::Function # (n, precisions) -> Point +end + +# Container depth and precision list for a mixed line: off-diagonal precision at every level, then the leaf. +depth(n) = n <= CFG.leaf ? 0 : round(Int, log2(n / CFG.leaf)) +function precisions(m, d) + off, leaf = Dict("F32/F64" => (Float32, Float64), "F16/F64" => (Float16, Float64), "F16/F32" => (Float16, Float32))[m] + return DataType[fill(off, d); leaf] +end +pstr(P) = P === nothing ? "" : join(string.(nameof.(P)), ",") + +# ---------------------------------------------------------------------------- the timing rule +const MIN_CALLS = 2 # never trust a single call +const ENOUGH_ONE = 0.3 # seconds: one call this long is enough to stop early (after MIN_CALLS) +const ENOUGH_ALL = 1.0 # seconds: or once the calls add up to this + +function time_point(p::Point) + ts = Float64[] + for _ in 1:CFG.reps + p.reset(); sync() # outside the timer + push!(ts, @elapsed (p.run(); sync())) + length(ts) >= MIN_CALLS && (ts[end] > ENOUGH_ONE || sum(ts) > ENOUGH_ALL) && break + end + return minimum(ts), length(ts) +end + +# ---------------------------------------------------------------------------- waiting for the GPU +function gpu_others() # other processes holding the GPU + me = getpid() + s = try read(`nvidia-smi --query-compute-apps=pid,process_name --format=csv,noheader`, String) catch; return String[] end + return [strip(l) for l in split(s, '\n') if !isempty(strip(l)) && tryparse(Int, strip(split(l, ',')[1])) != me] +end + +function wait_idle() + said = false + while !isempty(gpu_others()) + said || (println(" waiting for the GPU to be free: ", join(gpu_others(), "; ")); said = true) + sleep(5) + end +end + +gpu_temp() = something(tryparse(Float64, strip(first(split(read(`nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader`, String), '\n')))), 0.0) + +function wait_cool() + CFG.cool === nothing && return + said = false + while gpu_temp() > CFG.cool + said || (println(" waiting for the GPU to cool to $(CFG.cool) °C"); said = true) + sleep(10) + end +end + +# ---------------------------------------------------------------------------- the results file +# One JSON object per line; the field names are the ones the docs page reads. +jsonvalue(v) = v isa Number && !(v isa Bool) ? (isfinite(v) ? string(v) : "null") : + v === nothing ? "null" : "\"" * replace(string(v), "\\" => "\\\\", "\"" => "\\\"", "\n" => " ") * "\"" +emit(io; kw...) = (println(io, "{" * join(("\"$k\":" * jsonvalue(v) for (k, v) in kw), ",") * "}"); flush(io)) + +# ---------------------------------------------------------------------------- running +function run_line(io, l::Line, results) + t0 = time() + for n in CFG.sizes + d = depth(n) + P = l.mixed === nothing ? nothing : precisions(l.mixed, d) + record(; kw...) = emit(io; id=ROUTINE_ID[l.routine], backend=GPU ? "gpu" : "cpu", setting=l.setting, impl=l.impl, + variant=get(ROUTINE_VARIANT, l.routine, ""), n=n, depth=d, precisions=pstr(P), kw...) + try + seed(n) + p = l.make(n, P); sync() + GPU && (wait_idle(); wait_cool()) + t, calls = time_point(p) + gf = ROUTINE_FLOPS[l.routine](n) / t / 1e9 + record(; kind="time", time_s=t, gflops=gf, reps=calls, status="ok") + results[(l.routine, l.label, n)] = (t, gf) + @printf(" %-24s n = %-6d %10.2f ms %10.0f GFLOP/s\n", l.label, n, 1e3t, gf) + if p.build !== nothing + tb = @elapsed (p.build(); sync()) + record(; kind="build", time_s=tb, status="ok") + end + freemem() + if t > CFG.tmax + println(" (larger sizes skipped: that call took more than $(CFG.tmax) s)"); break + end + time() - t0 > CFG.casemax && (println(" (larger sizes skipped: this line used $(CFG.casemax) s)"); break) + catch e + msg = first(sprint(showerror, e), 300) + record(; kind="time", status="error", msg=msg) + println(" $(l.label) n = $n: ERROR $msg") + freemem(); break + end + end +end + +function summary(results) + println("\nGFLOP/s (higher is better):") + for r in CFG.routines + ls = lines_for(r) + println("\n", r) + @printf(" %-8s", "n") + foreach(l -> @printf("%14s", first(l.label, 13)), ls) + println() + for n in CFG.sizes + @printf(" %-8d", n) + for l in ls + v = get(results, (r, l.label, n), nothing) + @printf("%14s", v === nothing ? "—" : @sprintf("%.0f", v[2])) + end + println() + end + end +end + +function main() + backend = GPU ? "CUDA" : "CPU" + println("NextLA benchmarks on $backend ($DEVICE), Julia $VERSION, $(Threads.nthreads()) thread(s), ", + "BLAS threads $(BLAS.get_num_threads())") + println("routines: ", join(CFG.routines, " "), "; sizes: ", join(CFG.sizes, ", "), "; leaf: $(CFG.leaf)") + if CFG.list + for r in CFG.routines, l in lines_for(r) + println(" ", rpad(r, 6), rpad(l.label, 24), l.impl, l.mixed === nothing ? "" : " ($(l.mixed) containers)") + end + return + end + results = Dict{Tuple{String,String,Int},Tuple{Float64,Float64}}() + open(CFG.out, "w") do io + emit(io; id="__env__", backend=GPU ? "gpu" : "cpu", julia=string(VERSION), device=DEVICE, leaf=CFG.leaf, + jthreads=Threads.nthreads(), blas_threads=BLAS.get_num_threads(), date=string(now()), + nextla=string(pkgversion(NextLA))) + for r in CFG.routines + println("\n", r) + foreach(l -> run_line(io, l, results), lines_for(r)) + end + end + summary(results) + println("\nresults written to ", CFG.out) +end diff --git a/benchmark/routines.jl b/benchmark/routines.jl new file mode 100644 index 00000000..380f8a0c --- /dev/null +++ b/benchmark/routines.jl @@ -0,0 +1,143 @@ +# The six routines: their test matrices, and what each line calls. +# +# Every routine has up to four kinds of line (curves on the docs page): +# vendor the vendor library on a dense matrix (cuBLAS / cuSOLVER, or BLAS / LAPACK on the CPU) +# dense NextLA's routine on a dense matrix, in Float64 or Float32 +# mixed NextLA's routine on a mixed-precision container ("F16/F32": Float16 off-diagonal blocks, Float32 leaves) +# f16 Float16 inputs with Float32 accumulation (gemm and syrk only) +# Each make_* function returns a Point (harness.jl): its inputs are made when it is called, at one size n. + +# ---------------------------------------------------------------------------- results-file names +const ROUTINE_ID = Dict("gemm" => "M2", "syrk" => "M3", "trsm" => "M4", "trmm" => "M4", "potrf" => "M5", "lu" => "M6") +const ROUTINE_VARIANT = Dict("syrk" => "uplo=L", "trsm" => "solve side=L uplo=L trans=N", "trmm" => "mult side=L uplo=L trans=N") +const ROUTINE_FLOPS = Dict("gemm" => n -> 2.0n^3, "syrk" => n -> 1.0n^3, "trsm" => n -> 1.0n^3, "trmm" => n -> 1.0n^3, + "potrf" => n -> n^3 / 3, "lu" => n -> 2n^3 / 3) +const SETTING = Dict("Float64" => "S0", "Float32" => "S4", "F32/F64" => "S2", "F16/F64" => "S3", "F16/F32" => "S5") + +# ---------------------------------------------------------------------------- test matrices +# Random entries, made well conditioned, as in the docs page's runs. +random_matrix(T, n) = rnd(T, n, n) +symmetric_matrix(T, n) = (X = rnd(T, n, n); X + X') +spd_matrix(T, n) = (A = rnd(T, n, n); A + A' + T(2n) * I) # Cholesky +diag_dominant(T, n) = rnd(T, n, n) + T(n) * I # LU without pivoting +function lower_triangular(T, n) # TRSM / TRMM; built on the host + L = tril(rand(T, n, n)) + @inbounds for i in 1:n + L[i, i] += T(n) + end + return dev(L) +end + +leaftype(m) = endswith(m, "F32") ? Float32 : Float64 # the leaf precision of a mixed line + +# ---------------------------------------------------------------------------- GEMM: C = A*B + C +function make_gemm(T, n, how) + A = random_matrix(T, n); B = random_matrix(T, n); C0 = random_matrix(T, n); C = similar(C0) + call = how == :vendor ? () -> mul!(C, A, B, true, true) : () -> NextLA.recgemm!(one(T), A, B, one(T), C) + return Point(reset = () -> copyto!(C, C0), run = call) +end +function make_gemm_mixed(T, n, P) + A = random_matrix(T, n); B = random_matrix(T, n); C0 = random_matrix(T, n); C = Ref{Any}() + build = () -> (C[] = FullMixedPrec(copy(C0); precisions = P)) + return Point(reset = build, run = () -> recgemm!(1.0, A, B, 1.0, C[]), build = build) +end +function make_gemm_f16(n) + A = random_matrix(Float16, n); B = random_matrix(Float16, n); C0 = random_matrix(Float32, n); C = similar(C0) + return Point(reset = () -> copyto!(C, C0), run = () -> NextLA.gemmEx!('N', 'N', 1f0, A, B, 1f0, C)) +end + +# ---------------------------------------------------------------------------- SYRK: C = A*A' + C (lower) +vendor_syrk!(A, C) = GPU ? CUBLAS.syrk!('L', 'N', one(eltype(A)), A, one(eltype(C)), C) : + BLAS.syrk!('L', 'N', one(eltype(A)), A, one(eltype(C)), C) +function make_syrk(T, n, how) + A = random_matrix(T, n); C0 = symmetric_matrix(T, n); C = similar(C0) + call = how == :vendor ? () -> vendor_syrk!(A, C) : () -> NextLA.recsyrk!(one(T), A, one(T), C, 256; uplo='L') + return Point(reset = () -> copyto!(C, C0), run = call) +end +function make_syrk_mixed(T, n, P) + A = random_matrix(T, n); C0 = symmetric_matrix(T, n); C = Ref{Any}() + build = () -> (C[] = SymmMixedPrec(copy(C0), 'L'; precisions = P)) + return Point(reset = build, run = () -> recsyrk!(1.0, A, 1.0, C[]), build = build) +end +function make_syrk_f16(n) + A = random_matrix(Float16, n); C0 = symmetric_matrix(Float32, n); C = similar(C0) + return Point(reset = () -> copyto!(C, C0), run = () -> NextLA.recsyrk!(1f0, A, 1f0, C, 256; uplo='L')) +end + +# ---------------------------------------------------------------------------- TRSM / TRMM: B = L \ B, B = L*B +vendor_trsm!(L, B) = GPU ? CUBLAS.trsm!('L', 'L', 'N', 'N', one(eltype(L)), L, B) : BLAS.trsm!('L', 'L', 'N', 'N', one(eltype(L)), L, B) +vendor_trmm!(L, B, C) = GPU ? CUBLAS.trmm!('L', 'L', 'N', 'N', one(eltype(L)), L, B, C) : BLAS.trmm!('L', 'L', 'N', 'N', one(eltype(L)), L, B) +function make_trxm(T, n, how, f) # f = 'S' (solve) or 'M' (multiply) + L = lower_triangular(T, n); B0 = random_matrix(T, n); B = similar(B0); C = similar(B0) + call = how == :vendor ? (f == 'S' ? () -> vendor_trsm!(L, B) : () -> vendor_trmm!(L, B, C)) : + () -> unified_rectrxm!('L', 'L', 'N', 'N', one(T), f, L, B) + return Point(reset = () -> copyto!(B, B0), run = call) +end +function make_trxm_mixed(T, n, P, f) # the container is built once (its build is timed separately) + L0 = lower_triangular(T, n); Lc = TriMixedPrec(L0, 'L'; precisions = P); B0 = random_matrix(T, n); B = similar(B0) + return Point(reset = () -> copyto!(B, B0), run = () -> unified_rectrxm!('L', 'L', 'N', 'N', 1.0, f, Lc, B), + build = () -> TriMixedPrec(L0, 'L'; precisions = P)) +end + +# ---------------------------------------------------------------------------- Cholesky: A = L*L' +function make_potrf(T, n, how) + A0 = spd_matrix(T, n); A = similar(A0) + call = how == :vendor ? () -> LAPACK.potrf!('L', A) : () -> NextLA.potrf_recursive!(A; uplo='L') # cuSOLVER on a CuMatrix + return Point(reset = () -> copyto!(A, A0), run = call) +end +function make_potrf_mixed(T, n, P) + A0 = spd_matrix(T, n); S = Ref{Any}() + build = () -> (S[] = SymmMixedPrec(copy(A0), 'L'; precisions = P)) + return Point(reset = build, run = () -> potrf_recursive!(S[]), build = build) +end + +# ---------------------------------------------------------------------------- LU: A = L*U +function make_lu(T, n, how) + A0 = diag_dominant(T, n); A = similar(A0) + call = how == :vendor ? () -> LAPACK.getrf!(A) : () -> NextLA.lu_recursive_nopiv!(A) # the vendor LU pivots + return Point(reset = () -> copyto!(A, A0), run = call) +end +function make_lu_mixed(T, n, P) + A0 = diag_dominant(T, n); F = Ref{Any}() + build = () -> (F[] = FullMixedPrec(copy(A0); precisions = P)) + return Point(reset = build, run = () -> lu_recursive!(F[], NextLA.LU_BLOCK_SIZE), build = build) +end + +# ---------------------------------------------------------------------------- which function makes which line +make_dense(r, T, n, how) = + r == "gemm" ? make_gemm(T, n, how) : r == "syrk" ? make_syrk(T, n, how) : + r == "trsm" ? make_trxm(T, n, how, 'S') : r == "trmm" ? make_trxm(T, n, how, 'M') : + r == "potrf" ? make_potrf(T, n, how) : make_lu(T, n, how) +make_mixed(r, T, n, P) = + r == "gemm" ? make_gemm_mixed(T, n, P) : r == "syrk" ? make_syrk_mixed(T, n, P) : + r == "trsm" ? make_trxm_mixed(T, n, P, 'S') : r == "trmm" ? make_trxm_mixed(T, n, P, 'M') : + r == "potrf" ? make_potrf_mixed(T, n, P) : make_lu_mixed(T, n, P) + +# What each kind of line is called in the results file. +vendor_impl(r) = r == "gemm" ? "$VBLAS mul!" : r == "syrk" ? "$VBLAS syrk!" : r in ("trsm", "trmm") ? "$VBLAS $(r)!" : + r == "potrf" ? "$VLAPACK potrf!" : "$VLAPACK getrf! (pivoting)" +dense_impl(r) = r == "gemm" ? "NextLA dense recgemm!" : r == "syrk" ? "NextLA dense recsyrk!" : + r in ("trsm", "trmm") ? "NextLA dense unified_rectrxm!" : + r == "potrf" ? "NextLA dense potrf_recursive!" : "NextLA dense lu_recursive_nopiv!" + +# The lines of one routine, in the order of the docs page: Float64 (vendor, NextLA), Float32 (vendor, +# NextLA), the mixed containers, then Float16 inputs. +function lines_for(r) + out = Line[] + for (t, T) in (("Float64", Float64), ("Float32", Float32)) + t in CFG.types || continue + tag = T == Float64 ? "FP64" : "FP32" + vlib = r in ("potrf", "lu") ? VLAPACK : VBLAS + CFG.vendor && push!(out, Line(r, "$tag $vlib", SETTING[t], vendor_impl(r), nothing, (n, P) -> make_dense(r, T, n, :vendor))) + push!(out, Line(r, "$tag NextLA", SETTING[t], dense_impl(r), nothing, (n, P) -> make_dense(r, T, n, :nextla))) + end + for m in CFG.mixed + push!(out, Line(r, m, SETTING[m], "NextLA mxp", m, (n, P) -> make_mixed(r, leaftype(m), n, P))) + end + if "Float16" in CFG.types && r in ("gemm", "syrk") + push!(out, Line(r, "F16 dense, F32 accum.", "S6", + r == "gemm" ? "NextLA dense gemmEx! F16xF16->F32" : "NextLA dense recsyrk! F16 A", nothing, + (n, P) -> r == "gemm" ? make_gemm_f16(n) : make_syrk_f16(n))) + end + return out +end diff --git a/benchmark/run.jl b/benchmark/run.jl new file mode 100644 index 00000000..1e251891 --- /dev/null +++ b/benchmark/run.jl @@ -0,0 +1,144 @@ +# NextLA benchmarks: NextLA's recursive routines against the vendor libraries, dense and mixed +# precision. These are the runs behind the Manual's Benchmarks page; see benchmark/README.md. +# +# julia --project=benchmark benchmark/run.jl [routines...] [options] (--help for the options) +# +# The script is in three files: +# run.jl this file: the command line, then main() +# routines.jl the six routines: their test matrices and what each line calls +# harness.jl how one point is timed, waiting for an idle (and cool) GPU, and the results file + +using LinearAlgebra, Printf, Random, Dates +using NextLA +using NextLA.MixedPrecision + +const ROUTINES = ["gemm", "syrk", "trsm", "trmm", "potrf", "lu"] +const MIXED_ALL = ["F32/F64", "F16/F64", "F16/F32"] # off-diagonal precision / leaf precision + +usage() = """ + julia --project=benchmark benchmark/run.jl [routines...] [options] + + routines $(join(ROUTINES, " ")) (default: all); a prefix selects every routine that starts + with it, and '!name' leaves one out + --backends= CPU or CUDA (default: CUDA if CUDA.jl is installed and works, else CPU) + --types= dense lines: Float64, Float32, Float16 (Float16: gemm and syrk only, + Float16 inputs with Float32 accumulation); default all three + --mixed= container lines: $(join(MIXED_ALL, ", ")) or none; default all three + --n= sizes, comma-separated (default 4096,8192,16384,32768 on CUDA, + 2048,4096,8192,16384 on the CPU) + --leaf= leaf size of the containers (default 4096 on CUDA, 2048 on the CPU) + --reps= at most this many timed calls per point, the fastest is kept (default 5) + --tmax= optional: skip a line's larger sizes after a call longer than this (seconds) + --casemax= optional: skip a line's larger sizes once it has used this many seconds + --cool= CUDA: before each size, wait until the GPU is at or below this many °C + --no-vendor leave out the vendor library lines + --out= results file, one JSON object per line (default benchmark--.jsonl) + --list print what would run, and stop + --help this text +""" + +# Everything the command line decides, in one place. +struct Config + routines::Vector{String} + gpu::Bool + types::Vector{String} # dense lines + mixed::Vector{String} # container lines + sizes::Vector{Int} + leaf::Int + reps::Int + tmax::Float64 # Inf: every size runs + casemax::Float64 + cool::Union{Nothing,Float64} + vendor::Bool + out::String + list::Bool +end + +commalist(s) = String.(strip.(split(s, ','))) + +# Reads the arguments into option => value (strings), plus the routine names given and left out. +function read_args(args) + opts = Dict{String,String}(); picked = String[]; dropped = String[]; flags = Set{String}() + for a in args + if a in ("--help", "-h") + print(usage()); exit(0) + elseif a in ("--list", "--no-vendor") + push!(flags, a) + elseif startswith(a, "--") + k, v = occursin('=', a) ? split(a[3:end], '='; limit=2) : (a[3:end], "") + k in ("backends", "types", "mixed", "n", "leaf", "reps", "tmax", "casemax", "cool", "out") || + error("unknown option --$k; see --help") + isempty(strip(v)) && error("--$k needs a value; see --help") + opts[k] = String(v) + elseif startswith(a, "!") + push!(dropped, lowercase(a[2:end])) + else + push!(picked, lowercase(a)) + end + end + return opts, picked, dropped, flags +end + +function select_routines(picked, dropped) + for p in picked + any(startswith(r, p) for r in ROUTINES) || error("unknown routine '$p'; choose from $(join(ROUTINES, ", "))") + end + sel = isempty(picked) ? copy(ROUTINES) : [r for r in ROUTINES if any(startswith(r, p) for p in picked)] + filter!(r -> !any(startswith(r, p) for p in dropped), sel) + isempty(sel) && error("no routine selected") + return sel +end + +# CUDA if asked for (or, by default, if CUDA.jl is installed and finds a GPU). Loads CUDA.jl into Main. +function choose_gpu(opts) + if haskey(opts, "backends") + b = uppercase(opts["backends"]) + b in ("CPU", "CUDA") || error("--backends: CPU or CUDA (other GPU backends are not in this runner yet), got $(opts["backends"])") + b == "CPU" && return false + Base.find_package("CUDA") === nothing && error("""--backends=CUDA needs CUDA.jl in the benchmark environment: + julia --project=benchmark -e 'using Pkg; Pkg.add("CUDA")'""") + @eval Main using CUDA + Base.invokelatest(() -> Main.CUDA.functional()) || error("CUDA.jl is installed but no working GPU was found") + return true + end + Base.find_package("CUDA") === nothing && return false + try + @eval Main using CUDA + return Base.invokelatest(() -> Main.CUDA.functional()) + catch + return false + end +end + +function parse_config(args) + opts, picked, dropped, flags = read_args(args) + gpu = choose_gpu(opts) + types = haskey(opts, "types") ? commalist(opts["types"]) : ["Float64", "Float32", "Float16"] + for t in types + t in ("Float64", "Float32", "Float16") || error("--types: Float64, Float32 or Float16, got $t") + end + mixed = !haskey(opts, "mixed") ? copy(MIXED_ALL) : lowercase(opts["mixed"]) == "none" ? String[] : commalist(opts["mixed"]) + for m in mixed + m in MIXED_ALL || error("--mixed: $(join(MIXED_ALL, ", ")) or none, got $m") + end + sizes = haskey(opts, "n") ? parse.(Int, commalist(opts["n"])) : gpu ? [4096, 8192, 16384, 32768] : [2048, 4096, 8192, 16384] + all(n -> n >= 1, sizes) || error("--n: sizes must be positive") + cool = haskey(opts, "cool") ? parse(Float64, opts["cool"]) : nothing + cool !== nothing && !gpu && error("--cool is for --backends=CUDA") + backend = gpu ? "cuda" : "cpu" + return Config(select_routines(picked, dropped), gpu, types, mixed, sizes, + haskey(opts, "leaf") ? parse(Int, opts["leaf"]) : gpu ? 4096 : 2048, + max(2, haskey(opts, "reps") ? parse(Int, opts["reps"]) : 5), + haskey(opts, "tmax") ? parse(Float64, opts["tmax"]) : Inf, + haskey(opts, "casemax") ? parse(Float64, opts["casemax"]) : Inf, + cool, !("--no-vendor" in flags), + get(opts, "out", "benchmark-$backend-$(Dates.format(now(), "yyyymmdd-HHMM")).jsonl"), + "--list" in flags) +end + +const CFG = parse_config(ARGS) + +include("harness.jl") +include("routines.jl") + +main() diff --git a/docs/Project.toml b/docs/Project.toml index 1ec50b00..3cbd697d 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 = ".."} + +[compat] +Documenter = "1" diff --git a/docs/make.jl b/docs/make.jl index cea3ea95..01c8bcc2 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -1,24 +1,189 @@ 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", + "benchmark/README.md" => "dev/benchmarks.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"^\[!\[[^\]]*\]\(https?://.*\n"m => "") # the badges (web images), not local pictures + text = replace(text, r"\n{3,}" => "\n\n") + text = replace(text, r"^See the \[documentation\]\(https://nextlinearalgebra\.github\.io/[^)]*\).*\n"m => + "## Where to go next\n\n" * + "Continue with [Getting started](@ref) for examples, read the [Manual](@ref \"Dense matrices\") " * + "to learn how backends and mixed precision work, or look up a routine's " * + "arguments and examples in the [API reference](@ref \"Dense core\").\n") + for section in README_ONLY_SECTIONS + text = replace(text, Regex("^## \\Q$section\\E\\n(?:(?!## ).*\\n)*", "m") => "") + end + return rstrip(readme_doctests(text)) * "\n" +end +# README examples end in a line marked "# output: true". On the Home page those blocks become +# doctests, so every full docs build runs them. GPU examples (using CUDA) stay plain code: the +# build machines have no GPU. +function readme_doctests(text) + return replace(text, r"```julia\n(?:(?!```)[\s\S])*?# output: true\n```" => function (block) + occursin("using CUDA", block) && return block + lines = split(chopsuffix(chopprefix(block, "```julia\n"), "\n```"), "\n") + lines[end] = rstrip(replace(lines[end], r"\s*# output: true$" => "")) + return "```jldoctest\n" * join(lines, "\n") * "\n\n# output\n\ntrue\n```" + end) +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)", + "](benchmark/README.md)" => "](" * up * "dev/benchmarks.md)", + "](" * GITHUB_BLOB * "benchmark/README.md)" => "](" * up * "dev/benchmarks.md)", + "](../docs/src/" => "](" * up, # links from benchmark/README.md to the docs pages + "](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 testing only: NEXTLA_ASSISTANT_URL adds the "Ask NextLA" chat panel +# (assets/assistant.js), which talks to a separate assistant server at that address. Without +# it (CI, normal builds) the panel is not loaded and assistant-config.js is removed. +const ASSISTANT_URL = get(ENV, "NEXTLA_ASSISTANT_URL", "") +const ASSISTANT_CONFIG = joinpath(@__DIR__, "src", "assets", "assistant-config.js") +if isempty(ASSISTANT_URL) + rm(ASSISTANT_CONFIG; force=true) +else + write(ASSISTANT_CONFIG, "window.NEXTLA_ASSISTANT_URL = $(repr(ASSISTANT_URL));\n") +end +const ASSISTANT_ASSETS = isempty(ASSISTANT_URL) ? String[] : + ["assets/assistant.css", "assets/assistant-config.js", "assets/assistant.js"] + +# 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[], + # sidebar.{css,js}: a top-bar button that hides and shows the sidebar on wide screens. + assets=vcat(["assets/bibtex.css", "assets/sidebar.css", "assets/sidebar.js"], ASSISTANT_ASSETS), + 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" => [ + "Dense matrices" => "manual/dense.md", + "Mixed precision" => "manual/mixed_precision.md", + "Backends and GPUs" => "manual/backends.md", + "Benchmarks" => "manual/benchmarks.md", + ], + # Mirrors src/: dense/{core,blas,lapack}, mxp/{core,blas,lapack}. + "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", + ], + ], + "Developer documentation" => [ + "Contributing" => "dev/contributing.md", + "Running the tests" => "dev/testing.md", + "Running the benchmarks" => "dev/benchmarks.md", + "Roadmap" => "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..ae594011 --- /dev/null +++ b/docs/src/api/dense/blas/gemm.md @@ -0,0 +1,173 @@ +```@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) — one GEMM that picks the accumulation type by itself (`Float32` for `Float16` + storage); its recursive 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..e9a29bb2 --- /dev/null +++ b/docs/src/api/dense/core.md @@ -0,0 +1,66 @@ +```@meta +CurrentModule = NextLA +``` + +# Dense core + +Types and helpers in `src/dense/core` that the rest of NextLA builds on. + +## `NextLAMatrix` + +`NextLAMatrix(data)` (or `NextLAMatrix{T}(data)`) wraps a dense matrix so that `LinearAlgebra.lu!` on +it runs NextLA's own pivoted LU ([`getrf2!`](@ref)) for `Float32`, `Float64`, `ComplexF32` and +`ComplexF64`, and `LinearAlgebra.BLAS.axpy!` runs NextLA's `axpy!`. The BLAS calls `gemm!`, `syrk!`, +`herk!`, `syr2k!` and `her2k!` on it 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` + +For `Float32`, `Float64`, `ComplexF32` and `ComplexF64` with the default pivoting, `lu!` on a +`NextLAMatrix` returns an ordinary `LinearAlgebra.LU`, so `\` solves with it; other types and pivot +choices return a `NextLA.LU`. + +```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..35ccfe2d --- /dev/null +++ b/docs/src/api/dense/lapack/lu.md @@ -0,0 +1,161 @@ +```@meta +CurrentModule = NextLA +``` + +# LU + +| Routine | Pivoting | Notes | +|:---------------------------------------|:----------|:-------------------------------------------------| +| `LinearAlgebra.lu!(::NextLAMatrix)` | partial (default), complete, row-nonzero or none | `getrf2!` for the default; NextLA's generic loop for the others | +| [`getrf2!`](@ref) | partial | recursive LAPACK `getrf2` | +| [`lu_recursive!`](@ref) | none | recursive, square matrices | +| [`lu_recursive_nopiv!`](@ref) | none | recursive, any shape | +| [`lu_base!`](@ref) | partial | single-workgroup kernel for one block | +| [`tile_lu_factor!`](@ref) | partial, within each tile | 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 +trsm!('L', 'L', 'N', 'U', 1.0, F, x) # solve L y = P b (unit diagonal) +trsm!('L', 'U', 'N', 'N', 1.0, F, x) # solve U x = y +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, 1) +x = copy(b) +trsm!('L', 'L', 'N', 'U', 1.0, F, x) # solve L y = b (unit diagonal) +trsm!('L', 'U', 'N', 'N', 1.0, F, x) # solve U x = y +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..8297b5c6 --- /dev/null +++ b/docs/src/api/dense/lapack/qr.md @@ -0,0 +1,181 @@ +```@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, except `parfb!` +and `pemv!`; call the others 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 = c[1:n, :] +trsm!('L', 'U', 'N', 'N', 1.0, F[1:n, :], x) # solve R x = Qᴴ b +norm(A' * (A * x - b)) / norm(A' * b) < 1e-10 # least-squares condition + +# 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..1801e651 --- /dev/null +++ b/docs/src/api/mxp/lapack.md @@ -0,0 +1,96 @@ +```@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) +Lf = reconstruct_matrix(L) +relerr(Lf * Lf', S) < 1e-5 && relerr(S * X, 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(A * X - B) / norm(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/assets/benchmarks/v4-gemm.svg b/docs/src/assets/benchmarks/v4-gemm.svg new file mode 100644 index 00000000..c7d627ae --- /dev/null +++ b/docs/src/assets/benchmarks/v4-gemm.svg @@ -0,0 +1,2220 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/src/assets/benchmarks/v4-lu.svg b/docs/src/assets/benchmarks/v4-lu.svg new file mode 100644 index 00000000..c0e27360 --- /dev/null +++ b/docs/src/assets/benchmarks/v4-lu.svg @@ -0,0 +1,3293 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/src/assets/benchmarks/v4-potrf.svg b/docs/src/assets/benchmarks/v4-potrf.svg new file mode 100644 index 00000000..6b576d61 --- /dev/null +++ b/docs/src/assets/benchmarks/v4-potrf.svg @@ -0,0 +1,3568 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/src/assets/benchmarks/v4-syrk.svg b/docs/src/assets/benchmarks/v4-syrk.svg new file mode 100644 index 00000000..c8853a1c --- /dev/null +++ b/docs/src/assets/benchmarks/v4-syrk.svg @@ -0,0 +1,2039 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/src/assets/benchmarks/v4-trsm.svg b/docs/src/assets/benchmarks/v4-trsm.svg new file mode 100644 index 00000000..05af9f92 --- /dev/null +++ b/docs/src/assets/benchmarks/v4-trsm.svg @@ -0,0 +1,2007 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/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/assets/sidebar.css b/docs/src/assets/sidebar.css new file mode 100644 index 00000000..babd8d0d --- /dev/null +++ b/docs/src/assets/sidebar.css @@ -0,0 +1,11 @@ +/* The sidebar button from sidebar.js: only on wide screens, where Documenter always shows the sidebar. */ +#documenter .docs-main header.docs-navbar #docs-sidebar-collapse { + font-size: 1.3rem; + margin-right: 1rem; + padding-bottom: 0.1rem; +} +@media screen and (min-width: 1056px) { + #documenter .docs-main { transition: margin-left 0.3s; } + html.docs-sidebar-collapsed #documenter .docs-sidebar { left: -18rem; } + html.docs-sidebar-collapsed #documenter .docs-main { margin-left: auto; margin-right: auto; } +} diff --git a/docs/src/assets/sidebar.js b/docs/src/assets/sidebar.js new file mode 100644 index 00000000..88f5efe3 --- /dev/null +++ b/docs/src/assets/sidebar.js @@ -0,0 +1,40 @@ +// A button in the top bar that hides and shows the left sidebar on wide screens. +// (On narrow screens Documenter's own menu button already does this.) The choice is +// remembered in this browser. +(function () { + "use strict"; + var KEY = "nextla-docs-sidebar-collapsed"; + var root = document.documentElement; + var collapsed = false; + try { collapsed = localStorage.getItem(KEY) === "1"; } catch (e) { /* ignore */ } + // Set the class before the page is drawn, so a collapsed sidebar does not flash open. + root.classList.toggle("docs-sidebar-collapsed", collapsed); + + function update(button) { + var c = root.classList.contains("docs-sidebar-collapsed"); + button.title = c ? "Show the sidebar" : "Hide the sidebar"; + button.setAttribute("aria-label", button.title); + button.setAttribute("aria-expanded", c ? "false" : "true"); + } + + function addButton() { + var navbar = document.querySelector("#documenter .docs-main header.docs-navbar"); + if (!navbar || document.getElementById("docs-sidebar-collapse")) return; + var b = document.createElement("a"); + b.id = "docs-sidebar-collapse"; + b.href = "#"; + b.className = "docs-navbar-link fa-solid fa-bars is-hidden-touch"; + update(b); + b.addEventListener("click", function (e) { + e.preventDefault(); + var c = !root.classList.contains("docs-sidebar-collapsed"); + root.classList.toggle("docs-sidebar-collapsed", c); + try { localStorage.setItem(KEY, c ? "1" : "0"); } catch (err) { /* ignore */ } + update(b); + }); + navbar.insertBefore(b, navbar.firstChild); + } + + if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", addButton); + else addButton(); +})(); diff --git a/docs/src/assets/whpc_isc_poster.pdf b/docs/src/assets/whpc_isc_poster.pdf new file mode 100644 index 00000000..aa3c82a9 Binary files /dev/null and b/docs/src/assets/whpc_isc_poster.pdf differ diff --git a/docs/src/assets/whpc_isc_poster.png b/docs/src/assets/whpc_isc_poster.png new file mode 100644 index 00000000..98e31989 Binary files /dev/null and b/docs/src/assets/whpc_isc_poster.png differ diff --git a/docs/src/dev/todo.md b/docs/src/dev/todo.md new file mode 100644 index 00000000..f678bc0a --- /dev/null +++ b/docs/src/dev/todo.md @@ -0,0 +1,137 @@ +# Roadmap + +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 | | | | 4 | +| Singular values | 0 of 3 | | | 3 | | +| Auxiliary | 2 of 3 | 2 | | | 1 | +| Mixed precision (NextLA.MixedPrecision) | 4 of 6 | 4 | | 1 | 1 | +| **All** | **22 of 60** | 22 | 4 | 5 | 29 | + +## BLAS level 3 (matrix–matrix) + +| | Routine | In NextLA | +|:-:|:--|:--| +| ✅ | gemm | `gemm!`, `recgemm!`, `gemmEx!`, `gemm_batched!`, `GEMM_ADD!`/`GEMM_SUB!` (tiled kernel), `precision_gemm_grouped!` (unexported) | +| ✅ | trsm | `trsm!`, `unified_rectrxm!`, `trsm_batched!` | +| ✅ | trmm | `trmm!`, `unified_rectrxm!` | +| ✅ | syrk | `syrk!`, `recsyrk!`, `SYRK_KERNEL!`, `syrk_batched!` (unexported) | +| ⬜ | 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 on a GPU), `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!`, `pamm!` (unexported), `parfb!`, `pemv!` | +| ⬜ | 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 | on branches `fda/caqr`, `fda/scqr3-schur` | + +## 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) | on branches `er/gbbrd`, `gbbrd`, `svd_ka` | +| 🔄 | bdsqr / bdsdc (bidiagonal SVD) | bdsdc on branch `daka/sbdsdc` | +| 🔄 | gesvd / gesdd (driver) | gesvd on branch `svd_ka` | + +## 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 | on branch `el/mpir` | +| ⬜ | mixed-precision QR | — | diff --git a/docs/src/getting_started.md b/docs/src/getting_started.md new file mode 100644 index 00000000..24956c26 --- /dev/null +++ b/docs/src/getting_started.md @@ -0,0 +1,201 @@ +```@meta +CurrentModule = NextLA +``` + +# Getting started + +This page shows how to install NextLA and use it. The examples in [Using NextLA](@ref) cover the +two parts of the library (dense matrices and mixed precision), then show NextLA on +NVIDIA, AMD, Intel and Apple GPUs. + +## Installation + +```julia +using Pkg +Pkg.add("NextLA") # latest registered release + +# development version (main) +Pkg.add(url = "https://github.com/NextLinearAlgebra/NextLA.jl") +``` + +NextLA needs Julia 1.10 or later and is tested on 1.10, the latest release 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). + +## Using NextLA + +In-place routines (names ending in `!`) overwrite their inputs and follow the BLAS/LAPACK argument +conventions, including the character flags `side`, `uplo`, `trans` and `diag`. + +### 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 # for syrk!, potrf_recursive!, trsm!, gemm! +using LinearAlgebra # for I, norm + +n = 2048 +A = rand(n, n) +B = rand(n, 256) + +S = Matrix{Float64}(n * I, n, n) # start from n I +syrk!('L', 'N', 1.0, A, 1.0, S) # lower triangle: S = A Aᵀ + n I +potrf_recursive!(S) # Cholesky: L in the lower triangle + +X = copy(B) +trsm!('L', 'L', 'N', 'N', 1.0, S, X) # solve L Y = B +trsm!('L', 'L', 'T', 'N', 1.0, S, X) # solve Lᵀ X = Y + +R = copy(B) # residual R = B - (A Aᵀ + n I) X +gemm!(R, A * A' + n * I, X; alpha = -1.0, beta = 1.0) +norm(R) / norm(B) < 1e-10 + +# output + +true +``` + +The same dense part of NextLA covers other kinds of systems: + +- **General square matrix:** [`getrf2!`](@ref) computes an LU factorization with row pivoting, + `laswp` applies the same row swaps to `B`, and two calls to [`trsm!`](@ref) solve `A X = B`. See + [LU](api/dense/lapack/lu.md). +- **Least squares:** `NextLA.geqrt!` computes a QR factorization of `A`, `NextLA.unmqr!` applies `Qᵀ` + to the right-hand side, and a triangular solve with `R` gives the solution. See + [QR](api/dense/lapack/qr.md). + +The [Dense matrices](@ref) manual page explains this in detail: which routine to choose, how the +recursive routines work, and pivoting. + +### 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 # for potrf_recursive!, unified_rectrxm! +using NextLA.MixedPrecision # for adaptive_precisions, mixed-precision types +using LinearAlgebra # for I, norm + +n = 2048 +A = rand(n, n) +S = A * A' + n * I # symmetric positive definite +B = rand(n, 256) + +# pick a precision for each block level, store S that way, and factor it +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 + +X = copy(B) +unified_rectrxm!('L', 'L', 'N', 1.0, 'S', L, X) # solve L Y = B +unified_rectrxm!('L', 'L', 'T', 1.0, 'S', L, X) # solve Lᵀ X = Y +norm(S * X - B) / norm(B) < 1e-5 # residual of the solve + +# output + +true +``` + +The [Mixed precision](@ref) manual page explains this in detail: how the matrix is split into +blocks, how to choose their precisions, and the other mixed-precision routines. + +### On a GPU + +Build the matrices on the GPU and call the same routines: NextLA uses the vendor library where it +wraps one and its own portable kernels otherwise, and mixed-precision matrices keep their data on +the device. + +#### NVIDIA GPUs (CUDA) + +```julia +using NextLA # for potrf_recursive!, trsm! +using CUDA # for CUDA.rand +using LinearAlgebra # for I + +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)) # solve L Y = B +trsm!('L', 'L', 'T', 'N', 1.0, F, X) # solve Lᵀ X = Y +S * X ≈ B # output: true +``` + +#### AMD GPUs (AMDGPU) + +```julia +using NextLA # for lu_recursive!, unified_rectrxm! +using NextLA.MixedPrecision # for FullMixedPrec +using AMDGPU # for ROCArray +using LinearAlgebra # for I, norm + +n = 4096 +A = ROCArray(rand(n, n) + n * I) # diagonally dominant, on the GPU +B = ROCArray(rand(n, 256)) + +# A = L U in mixed precision: the off-diagonal blocks are stored in Float32 +M = FullMixedPrec(A; precisions = DataType[Float32, Float64]) +lu_recursive!(M) + +X = copy(B) +unified_rectrxm!('L', 'L', 'N', 'U', 1.0, 'S', M, X) # solve L Y = B +unified_rectrxm!('L', 'U', 'N', 'N', 1.0, 'S', M, X) # solve U X = Y +norm(A * X - B) / norm(B) < 1e-5 # output: true +``` + +#### Intel GPUs (oneAPI) + +```julia +using NextLA # for trsm!, trmm! +using oneAPI # for oneArray +using LinearAlgebra # for I + +n = 4096 +L = oneArray(rand(Float32, n, n) + n * I) # only its lower triangle is used +B = oneArray(rand(Float32, n, 256)) + +X = copy(B) +trsm!('L', 'L', 'N', 'N', 1f0, L, X) # solve L X = B +Y = copy(X) +trmm!('L', 'L', 'N', 'N', 1f0, L, Y) # multiply back: Y = L X +Y ≈ B # output: true +``` + +#### Apple GPUs (Metal) + +```julia +using NextLA # for unified_rectrxm! +using Metal # for MtlArray +using LinearAlgebra # for I + +n = 4096 +L = MtlArray(rand(Float32, n, n) + n * I) # Metal GPUs work in Float32 +B = MtlArray(rand(Float32, n, 256)) + +X = copy(B) +unified_rectrxm!('L', 'L', 'N', 1f0, 'M', L, X) # multiply: X = L B +unified_rectrxm!('L', 'L', 'N', 1f0, 'S', L, X) # solve L Z = X: back to B +X ≈ B # output: 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 + +- [Dense matrices](@ref): choosing a routine, how the recursive routines work, pivoting, tile QR + and batched routines. +- [Mixed precision](@ref): the full guide to `NextLA.MixedPrecision`. +- [Backends and GPUs](@ref): which routine runs on which backend, and with which element types. +- [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..bc01c2c4 --- /dev/null +++ b/docs/src/manual/backends.md @@ -0,0 +1,157 @@ +```@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 except [`cholesky_blocked!`](@ref) and +[`tile_lu_factor!`](@ref) 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 | vendor (`Float32`), `mul!` otherwise | `mul!` | `mul!` | `mul!` | +| [`gemmEx!`](@ref) (mixed types) | portable | vendor | vendor | — | — | +| [`gemm_batched!`](@ref) | loop | vendor | vendor | vendor (no pointer form) | vendor (3-D only) | +| [`trsm!`](@ref), [`unified_rectrxm!`](@ref) | portable | vendor + portable | vendor + portable | portable | portable | +| [`trsm_batched!`](@ref) | loop | vendor | vendor | vendor | — | +| [`syrk!`](@ref) | BLAS | vendor | vendor | vendor | MPS GEMM | +| [`recsyrk!`](@ref), [`SYRK_KERNEL!`](@ref) | portable | portable | portable | portable | portable | +| [`potrf!`](@ref) | LAPACK | vendor | vendor | — | — | +| [`potrf_batched!`](@ref) | loop | vendor | vendor | vendor | — | +| [`potrf_recursive!`](@ref) | recursive | recursive | recursive | needs `potrf!` | needs `potrf!` | +| [`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) (3-D only) | +| [`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; `larfb!` (so `unmqr!`) vendor for `Float32`, `ComplexF32` | 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 on AMDGPU and the other backends take the recursion; + on CUDA, views go to cuBLAS too (a view whose rows are not consecutive is copied first). When the + recursion runs on CUDA (`Float16`, and the leaves of the mixed-precision solve), its leaf solves + and multiplies are cuBLAS `trsm!`/`trmm!` and its updates are cuBLAS GEMMs; `Float16` is worked in + `Float32` copies, as cuBLAS has no `Float16` TRSM. +- [`gemm!`](@ref) on CUDA sends `Float32` matrices, views and transposes to cuBLAS, and `Float16` + too, through `gemmEx!` with `Float32` sums. Other types call `mul!`, which for a view of a device + array can reach a generic GPU kernel, except when the output shares a device buffer with an input + without overlapping it (a one-column block of a recursion, which newer Julia versions' `mul!` + refuses): that case goes to cuBLAS too. +- `larfb!`, and so `unmqr!`, applies the block reflector with cuBLAS GEMM/TRMM on CUDA for `Float32` + and `ComplexF32` (`side = 'L'`); `Float64` keeps the portable code, which is faster there. +- [`potrf!`](@ref) has no generic device fallback, so on oneAPI and Metal, where NextLA has no + wrapper for it, it throws instead of silently copying to the host. [`potrf_recursive!`](@ref) calls + it at its leaves, so it needs [`potrf!`](@ref) too. Metal also throws for [`potrf_batched!`](@ref) and + [`trsm_batched!`](@ref). +- [`gemm_batched!`](@ref) takes a 3-D array on every GPU backend. Metal does not take a vector of + matrices, and neither Metal nor oneAPI takes the pointer form; both throw `ArgumentError`. Metal's + [`syrk_batched!`](@ref) goes through [`gemm_batched!`](@ref), so it also needs a 3-D array. +- `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: its single-matrix [`syrk!`](@ref) is a full GEMM (MPS `matmul!`), so it also overwrites 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, except `parfb!` and `pemv!` (call the others 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, and `potrf_recursive!` is correct only when the matrix fits in one leaf (`n` ≤ `block_size`). | +| `Float16` | Portable kernels. `recgemm!`, `recsyrk!` and the triangular solve and multiply accumulate in `Float32`; `gemm!` accumulates `Float16` in `Float32` on the CPU and CUDA (strided matrices); on AMDGPU, Metal and oneAPI it calls `mul!`, which may accumulate in `Float16`. `gemmEx!` with only `Float16` operands accumulates in `Float16` unless it is given `compute_type = Float32`. Not in `syrk!`, 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!` | ✓ | ✓ | *refused* | *refused* | ✓ | ✓ | +| `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..52707e90 --- /dev/null +++ b/docs/src/manual/benchmarks.md @@ -0,0 +1,238 @@ +# Benchmarks + +NextLA's mixed-precision routines against the vendor libraries on one GPU, an NVIDIA GB10 (DGX Spark). How it was measured is at [the end](@ref bench-method). + +## [Mixed precision: Cholesky, SYRK and TRSM](@id bench-paper3) + +The routines of paper [3] ([Citing NextLA](@ref citing-citing-nextla)) on recursively split matrices whose blocks are stored in different precisions ([Mixed precision](@ref)), as NextLA's speed over the vendor library at the leaf precision. A configuration lists the off-diagonal precision at each level, then the leaf: `[F16, F16, F32]` has two levels of `Float16` off-diagonal blocks and `Float32` leaves. The table gives the configurations paper [3] reports, at ``n = 65536`` wherever it fits in the GB10's memory. + +| Configuration | n | NextLA (× vendor) | Error (n) | +|:---|---:|---:|---:| +| Cholesky [F16, F32, F64] | 64K | **2.69×** | 2.7e-08 (32K) | +| Cholesky [F16, F16, F16, F32] | 64K | **2.29×** | 9.6e-08 (32K) | +| Cholesky [F16×6, F32] | 64K | **2.43×** | 9.7e-08 (32K) | +| Cholesky Pure F16 | 64K | **4.41×** | 6.0e-04 (32K) | +| SYRK [F16, F16, F32] | 64K | **1.19×** | 1.0e-04 (16K) | +| SYRK [F16×4, F32] | 64K | **1.20×** | 1.2e-04 (16K) | +| SYRK Pure F16 | 64K | **4.89×** | 2.2e-04 (16K) | +| TRSM [F16×4, F32] | 64K | **2.52×** | 6.7e-04 (16K) | +| TRSM Pure F16 | 64K | **3.12×** | 7.0e-04 (16K) | + +Two choices trade speed for accuracy. `Float16` products are summed in `Float32`, and every update is checked for overflow, raising the block's scale instead of storing `Inf`. A `Float64` leaf updated from `Float16` or `Float32` rows sums that update in `Float32` (see [Mixed precision](@ref)): on the matrices these errors are measured on, which add ``10nI``, that changes the error by at most 3%; on less diagonally dominant matrices it grows, about 9× with `[F32, F64]` on ``AA^T + nI``. + +### [Cholesky: `potrf_recursive!` on `SymmMixedPrec`](@id bench-potrf) + +NextLA's speed over cuSOLVER `potrf` at the leaf precision, one panel per configuration (log scale; above 1× is faster than the vendor library, timed in the same run). + +![Cholesky: NextLA's speed over cuSOLVER potrf](../assets/benchmarks/v4-potrf.svg) + +```@raw html +
The numbers behind the Cholesky chart +``` + +| Configuration | n | NextLA | cuSOLVER `potrf` | × vendor | Build | Error | +|:---|---:|---:|---:|---:|---:|---:| +| Pure F32 | 16K | 0.14 s | 0.137 s | **0.98×** | – | 2.3e-08 | +| Pure F32 | 32K | 0.859 s | 1.02 s | **1.18×** | – | 5.6e-08 | +| Pure F32 | 64K | 6.99 s | 7.75 s | **1.11×** | – | – | +| Pure F16 | 16K | 0.0585 s | 0.137 s | **2.34×** | – | 6.0e-04 | +| Pure F16 | 32K | 0.286 s | 1.02 s | **3.55×** | – | 6.0e-04 | +| Pure F16 | 64K | 1.76 s | 7.75 s | **4.41×** | – | – | +| Pure F64 | 16K | 3.8 s | 3.64 s | **0.96×** | – | 3.3e-16 | +| Pure F64 | 32K | 29.6 s | 29.2 s | **0.99×** | – | 3.4e-16 | +| [F16, F32] | 16K | 0.146 s | 0.139 s | **0.95×** | 0.0444 s | 6.4e-08 | +| [F16, F32] | 32K | 0.827 s | 1.02 s | **1.23×** | 0.152 s | 9.2e-08 | +| [F16, F32] | 64K | 5.14 s | 7.73 s | **1.50×** | 0.601 s | – | +| [F16, F16, F32] | 16K | 0.136 s | 0.139 s | **1.02×** | 0.0382 s | 7.1e-08 | +| [F16, F16, F32] | 32K | 0.646 s | 1.02 s | **1.58×** | 0.127 s | 9.4e-08 | +| [F16, F16, F32] | 64K | 4.05 s | 7.73 s | **1.91×** | 0.493 s | – | +| [F16, F16, F16, F32] | 16K | 0.137 s | 0.139 s | **1.02×** | 0.0324 s | 7.6e-08 | +| [F16, F16, F16, F32] | 32K | 0.587 s | 1.02 s | **1.73×** | 0.118 s | 9.6e-08 | +| [F16, F16, F16, F32] | 64K | 3.38 s | 7.73 s | **2.29×** | 0.432 s | – | +| [F16×5, F32] | 16K | 0.163 s | 0.138 s | **0.85×** | 0.0304 s | 8.0e-08 | +| [F16×5, F32] | 32K | 0.629 s | 1.01 s | **1.61×** | 0.106 s | 9.7e-08 | +| [F16×5, F32] | 64K | 3.09 s | 7.84 s | **2.53×** | 0.408 s | – | +| [F16×6, F32] | 16K | 0.196 s | 0.139 s | **0.71×** | 0.0303 s | 8.0e-08 | +| [F16×6, F32] | 32K | 0.691 s | 1.02 s | **1.47×** | 0.104 s | 9.7e-08 | +| [F16×6, F32] | 64K | 3.18 s | 7.73 s | **2.43×** | 0.37 s | – | +| [F16×7, F32] | 16K | 0.229 s | 0.138 s | **0.60×** | 0.0413 s | 8.0e-08 | +| [F16×7, F32] | 32K | 0.712 s | 1.01 s | **1.42×** | 0.115 s | 9.7e-08 | +| [F16×7, F32] | 64K | 3.28 s | 7.84 s | **2.39×** | 0.379 s | – | +| [F32, F32, F32, F64] | 16K | 0.997 s | 3.64 s | **3.65×** | 0.05 s | 6.6e-12 | +| [F32, F32, F32, F64] | 32K | 6.69 s | 29.2 s | **4.37×** | 0.17 s | 3.5e-12 | +| [F32, F32, F32, F64] | 64K | 51.2 s | 233 s | **4.54×** | 1.01 s | – | +| [F16, F32, F64] | 16K | 1.53 s | 3.64 s | **2.38×** | 0.0499 s | 4.4e-08 | +| [F16, F32, F64] | 32K | 11.2 s | 29.2 s | **2.61×** | 0.182 s | 2.7e-08 | +| [F16, F32, F64] | 64K | 86.5 s | 233 s | **2.69×** | 1.38 s | – | + +```@raw html +
+``` + +Error: ``\|A - LL^T\|_F / \|A\|_F`` in `Float64`, on ``(R/\sqrt{n})(R/\sqrt{n})^T + 10nI`` with ``R`` uniform random. Build is the container build alone; it is also inside every timed call. + +### [SYRK: `recsyrk!` into `SymmMixedPrec`](@id bench-syrk) + +NextLA's speed over cuBLAS `syrk` at the leaf precision, one panel per configuration (log scale; above 1× is faster than the vendor library, timed in the same run). + +![SYRK: NextLA's speed over cuBLAS syrk](../assets/benchmarks/v4-syrk.svg) + +```@raw html +
The numbers behind the SYRK chart +``` + +| Configuration | n | NextLA | cuBLAS `syrk` | × vendor | Build | Error | +|:---|---:|---:|---:|---:|---:|---:| +| Pure F32 | 16K | 0.241 s | 0.31 s | **1.28×** | – | 1.0e-06 | +| Pure F32 | 32K | 1.91 s | 2.51 s | **1.31×** | – | – | +| Pure F32 | 64K | 21.3 s | 27.1 s | **1.27×** | – | – | +| Pure F16 | 16K | 0.0884 s | 0.317 s | **3.59×** | – | 2.2e-04 | +| Pure F16 | 32K | 0.413 s | 3.04 s | **7.37×** | – | – | +| Pure F16 | 64K | 5.57 s | 27.2 s | **4.89×** | – | – | +| [F16, F16, F32] | 16K | 0.323 s | 0.309 s | **0.96×** | 0.0807 s | 1.0e-04 | +| [F16, F16, F32] | 32K | 2.26 s | 2.49 s | **1.10×** | 0.281 s | – | +| [F16, F16, F32] | 64K | 22.6 s | 27 s | **1.19×** | 1.1 s | – | +| [F16×4, F32] | 16K | 0.324 s | 0.309 s | **0.95×** | 0.0698 s | 1.2e-04 | +| [F16×4, F32] | 32K | 2.28 s | 2.49 s | **1.09×** | 0.264 s | – | +| [F16×4, F32] | 64K | 22.5 s | 27 s | **1.20×** | 1.01 s | – | + +```@raw html +
+``` + +Error: Frobenius error of the lower triangle against a `Float64` reference. Build is the container build alone; it is also inside every timed call. + +### [TRSM: `unified_rectrxm!` with `TriMixedPrec`](@id bench-trsm) + +NextLA's speed over cuBLAS `trsm` at the leaf precision, one panel per configuration (log scale; above 1× is faster than the vendor library, timed in the same run). + +![TRSM: NextLA's speed over cuBLAS trsm](../assets/benchmarks/v4-trsm.svg) + +```@raw html +
The numbers behind the TRSM chart +``` + +| Configuration | n | NextLA | cuBLAS `trsm` | × vendor | Build | Error | +|:---|---:|---:|---:|---:|---:|---:| +| Pure F32 | 16K | 0.32 s | 0.316 s | **0.99×** | – | 2.2e-07 | +| Pure F32 | 32K | 2.51 s | 2.49 s | **0.99×** | – | – | +| Pure F32 | 64K | 18.3 s | 19.8 s | **1.09×** | – | – | +| Pure F16 | 16K | 0.122 s | 0.313 s | **2.57×** | – | 7.0e-04 | +| Pure F16 | 32K | 0.67 s | 2.44 s | **3.63×** | – | – | +| Pure F16 | 64K | 5.87 s | 18.3 s | **3.12×** | – | – | +| [F16, F16, F32] | 16K | 0.224 s | 0.308 s | **1.37×** | 0.0366 s | 6.4e-04 | +| [F16, F16, F32] | 32K | 1.26 s | 2.46 s | **1.96×** | 0.125 s | – | +| [F16, F16, F32] | 64K | 10.2 s | 18.2 s | **1.79×** | 0.471 s | – | +| [F16×4, F32] | 16K | 0.172 s | 0.308 s | **1.79×** | 0.032 s | 6.7e-04 | +| [F16×4, F32] | 32K | 0.927 s | 2.46 s | **2.65×** | 0.117 s | – | +| [F16×4, F32] | 64K | 7.23 s | 18.2 s | **2.52×** | 0.409 s | – | + +```@raw html +
+``` + +Error: Frobenius error of ``X`` against a `Float64` reference solve. Left side, upper triangle, no transpose. Build is the container build alone; it is also inside every timed call. + +## [Mixed precision: GEMM and LU](@id bench-gemm-lu) + +### [GEMM: `recgemm!` into `FullMixedPrec`](@id bench-gemm) + +NextLA's speed over cuBLAS `gemm` at the leaf precision, one panel per configuration (log scale; above 1× is faster than the vendor library, timed in the same run). + +![GEMM: NextLA's speed over cuBLAS gemm](../assets/benchmarks/v4-gemm.svg) + +```@raw html +
The numbers behind the GEMM chart +``` + +| Configuration | n | NextLA | cuBLAS `gemm` | × vendor | Build | Error | +|:---|---:|---:|---:|---:|---:|---:| +| [F16, F32] | 8K | 0.0421 s | 0.061 s | **1.45×** | 0.0168 s | 1.5e-04 | +| [F16, F32] | 16K | 0.161 s | 0.553 s | **3.44×** | 0.0598 s | 1.5e-04 | +| [F16, F32] | 32K | 1.01 s | 4.95 s | **4.90×** | 0.223 s | – | +| [F16, F16, F32] | 8K | 0.0431 s | 0.061 s | **1.41×** | 0.0178 s | 1.8e-04 | +| [F16, F16, F32] | 16K | 0.175 s | 0.553 s | **3.16×** | 0.054 s | 1.8e-04 | +| [F16, F16, F32] | 32K | 1.04 s | 4.95 s | **4.74×** | 0.203 s | – | +| [F16×4, F32] | 8K | 0.0475 s | 0.061 s | **1.28×** | 0.0191 s | 2.0e-04 | +| [F16×4, F32] | 16K | 0.184 s | 0.553 s | **3.01×** | 0.0584 s | 2.0e-04 | +| [F16×4, F32] | 32K | 1.15 s | 4.95 s | **4.31×** | 0.202 s | – | +| [F16, F32, F64] | 8K | 0.76 s | 2.72 s | **3.57×** | 0.0227 s | 1.5e-04 | +| [F16, F32, F64] | 16K | 5.68 s | 21.7 s | **3.82×** | 0.0734 s | 1.5e-04 | + +```@raw html +
+``` + +Error: ``\|C - C_{64}\|_F / \|C_{64}\|_F`` against `Float64` cuBLAS. NextLA sums the `Float16` blocks in `Float32`. + +### [LU: `lu_recursive!` on `FullMixedPrec`](@id bench-lu) + +NextLA's speed over cuSOLVER `getrf` at the leaf precision, one panel per configuration (log scale; above 1× is faster than the vendor library, timed in the same run). + +![LU: NextLA's speed over cuSOLVER getrf](../assets/benchmarks/v4-lu.svg) + +```@raw html +
The numbers behind the LU chart +``` + +| Configuration | n | NextLA | cuSOLVER `getrf` | × vendor | Build | Error | +|:---|---:|---:|---:|---:|---:|---:| +| Pure F32 | 8K | 0.0368 s | 0.0579 s | **1.57×** | – | 7.8e-08 | +| Pure F32 | 16K | 0.218 s | 0.288 s | **1.32×** | – | 7.4e-08 | +| Pure F32 | 32K | 1.61 s | 1.91 s | **1.18×** | – | – | +| Pure F16 | 8K | 0.0231 s | 0.0579 s | **2.51×** | – | 3.2e-05 | +| Pure F16 | 16K | 0.101 s | 0.288 s | **2.85×** | – | 1.6e-05 | +| Pure F16 | 32K | 0.503 s | 1.91 s | **3.79×** | – | – | +| [F16, F32] | 8K | 0.0547 s | 0.0579 s | **1.06×** | 0.0178 s | 9.3e-07 | +| [F16, F32] | 16K | 0.211 s | 0.288 s | **1.37×** | 0.0593 s | 1.2e-06 | +| [F16, F32] | 32K | 1.11 s | 1.91 s | **1.73×** | 0.214 s | – | +| [F16, F16, F32] | 8K | 0.0771 s | 0.0579 s | **0.75×** | 0.0209 s | 1.2e-06 | +| [F16, F16, F32] | 16K | 0.222 s | 0.288 s | **1.30×** | 0.059 s | 1.4e-06 | +| [F16, F16, F32] | 32K | 1.02 s | 1.91 s | **1.88×** | 0.202 s | – | +| [F16, F16, F16, F32] | 8K | 0.122 s | 0.0579 s | **0.47×** | 0.0154 s | 1.3e-06 | +| [F16, F16, F16, F32] | 16K | 0.281 s | 0.288 s | **1.03×** | 0.0628 s | 1.5e-06 | +| [F16, F16, F16, F32] | 32K | 1.03 s | 1.91 s | **1.85×** | 0.195 s | – | +| [F16×4, F32] | 8K | 0.156 s | 0.0579 s | **0.37×** | 0.0189 s | 1.3e-06 | +| [F16×4, F32] | 16K | 0.312 s | 0.288 s | **0.93×** | 0.0568 s | 1.6e-06 | +| [F16×4, F32] | 32K | 1.06 s | 1.91 s | **1.80×** | 0.209 s | – | +| [F32, F64] | 8K | 1 s | 0.979 s | **0.98×** | 0.026 s | 7.1e-11 | +| [F32, F64] | 16K | 7.52 s | 7.5 s | **1.00×** | 0.09 s | 5.0e-11 | +| [F16, F64] | 8K | 0.998 s | 0.979 s | **0.98×** | 0.0219 s | 9.3e-07 | +| [F16, F64] | 16K | 7.51 s | 7.5 s | **1.00×** | 0.0781 s | 1.2e-06 | +| [F16, F16, F32, F64] | 8K | 0.471 s | 0.979 s | **2.08×** | 0.024 s | 1.2e-06 | +| [F16, F16, F32, F64] | 16K | 2.93 s | 7.5 s | **2.56×** | 0.0723 s | 1.4e-06 | +| [F16, F16, F16, F32, F64] | 8K | 0.42 s | 0.979 s | **2.33×** | 0.0189 s | 1.3e-06 | +| [F16, F16, F16, F32, F64] | 16K | 1.83 s | 7.5 s | **4.10×** | 0.0626 s | 1.5e-06 | + +```@raw html +
+``` + +Error: ``\|LU - A\|_F / \|A\|_F``. + +## [How it was measured](@id bench-method) + +- **Machine:** an NVIDIA DGX Spark: a GB10 GPU (compute capability 12.1) with 121 GB of memory shared with the CPU. +- **Code:** NextLA as in this release, on Julia 1.10.14 and CUDA.jl 6.4.2. Each point is divided by the vendor routine timed in the same run. +- **Timing:** one untimed warm-up call, then up to 5 timed calls (2 when a call takes over 10 s, 1 when it takes over 60 s); the fastest is kept. Each call ends with `CUDA.device_synchronize()`, so work started in `@async` tasks is inside the time. The mixed-precision container is built inside the timed call; its build is also timed on its own. The GPU is idle before each call. +- **Inputs** (those of paper [3]'s experiments): Cholesky, uniform random plus ``nI`` (Pure `Float16`: scaled to the `Float16` range, plus ``100I``); SYRK, ``0.1\,\mathrm{randn}`` in the leaf type, ``C = 0``, ``\alpha = -1``, ``\beta = 1``; TRSM, left side, upper triangle, no transpose, ``\alpha = 1``; GEMM, ``C \leftarrow C - AB`` into a `FullMixedPrec` with ``A`` and ``B`` in the off-diagonal precision; LU, uniform random plus ``2nI``, unpivoted. Standard flop counts. +- **Sizes:** 16K, 32K and 64K; GEMM and LU 8K, 16K and 32K. `Float64` SYRK and TRSM at 64K are not measured: they need 120–137 GB. Errors are measured outside the timing, up to 16K (32K for Cholesky). +- **Not measured:** mixed-precision TRMM, adaptive precision and real-world matrices. + +## [Run it on your machine](@id bench-run) + +`benchmark/run.jl` in the repository times NextLA's routines, dense and mixed precision, against the vendor libraries on your machine, synchronized the same way (`CUDA.device_synchronize()`) and keeping the fastest of several calls. From the NextLA folder, set up the benchmark environment once (add CUDA.jl for an NVIDIA GPU): + +```bash +julia --project=benchmark -e 'using Pkg; Pkg.develop(path="."); Pkg.instantiate()' +julia --project=benchmark -e 'using Pkg; Pkg.add("CUDA")' +``` + +Then run every routine, or name some: + +```bash +julia --project=benchmark benchmark/run.jl # every routine, on one device: the GPU if CUDA works, else the CPU +julia --project=benchmark benchmark/run.jl potrf trsm --mixed=F16/F32 # some routines, one mixed configuration +``` + +It prints a GFLOP/s table per routine and writes every point to a results file. The options and the timing rule are in [Running the benchmarks](../dev/benchmarks.md) (`benchmark/README.md`). diff --git a/docs/src/manual/dense.md b/docs/src/manual/dense.md new file mode 100644 index 00000000..fd70e071 --- /dev/null +++ b/docs/src/manual/dense.md @@ -0,0 +1,143 @@ +```@meta +CurrentModule = NextLA +``` + +# Dense matrices + +The dense part of NextLA, loaded with `using NextLA`, works on ordinary matrices that hold one +element type: `Matrix` on the CPU, or a GPU array such as `CuArray`. It provides BLAS-style +routines (multiply, triangular solve and multiply, rank-k update) and LAPACK-style factorizations +(Cholesky, LU, QR), each written once in Julia and run on every backend. This page explains which +routine to choose and how they work; the [API reference](@ref "Dense core") documents each one. + +## Choosing a routine + +| Task | Routines | Use it when | +|:--|:--|:--| +| Multiply, `C = αAB + βC` | [`gemm!`](@ref) | one product, any backend | +| | [`gemmEx!`](@ref) | inputs and output in different types, such as `Float16` inputs with `Float32` accumulation | +| | [`gemm_batched!`](@ref) | many small products of the same shape | +| Triangular solve or multiply | [`trsm!`](@ref), [`trmm!`](@ref) | the BLAS calls, any backend | +| | [`unified_rectrxm!`](@ref) | the recursive version of both, one call for solve (`'S'`) or multiply (`'M'`) | +| | [`trsm_batched!`](@ref) | many small triangular solves | +| Rank-k update, `C = αAAᵀ + βC` | [`syrk!`](@ref) | one update, any backend | +| | [`recsyrk!`](@ref) | the recursive version, also for `Float16` | +| | [`syrk_batched!`](@ref) | many small updates | +| Cholesky, `A = LLᵀ` | [`potrf_recursive!`](@ref) | large matrices, CPU or GPU | +| | [`potrf!`](@ref) | the LAPACK-style call; the recursion uses it for its leaves | +| | [`cholesky_blocked!`](@ref) | blocked Cholesky on a GPU | +| | [`potrf_batched!`](@ref) | many small matrices | +| LU, `PA = LU` | [`getrf2!`](@ref) | general matrices, partial (row) pivoting | +| | [`getc2!`](@ref) | complete pivoting, rows and columns | +| | [`lu_recursive!`](@ref), [`lu_recursive_nopiv!`](@ref) | large matrices that need no pivoting | +| | [`tile_lu_factor!`](@ref) | on a GPU, pivoting within `n × n` tiles (`n` ≤ 32) | +| QR, `A = QR` | `NextLA.geqrt!`, `NextLA.unmqr!` | a QR of one tile, and applying `Q` | +| | `NextLA.tsqrt!`, `NextLA.ttqrt!` and their `*mqr!` partners | tile QR, one tile at a time (see below) | + +In-place routines (names ending in `!`) overwrite their inputs and follow the BLAS/LAPACK argument +conventions: the character flags `side` (`'L'` or `'R'`), `uplo` (`'L'` or `'U'`), `trans` +(`'N'`, `'T'` or `'C'`) and `diag` (`'N'` or `'U'`). The flags are accepted in either case +(`'l'` is the same as `'L'`). Which backend runs which routine, and +with which element types, is on [Backends and GPUs](@ref). + +## How the recursive routines work + +[`potrf_recursive!`](@ref), [`lu_recursive!`](@ref), [`unified_rectrxm!`](@ref) and [`recsyrk!`](@ref) +all use the same idea ([`recgemm!`](@ref) too, on a mixed-precision matrix; on a plain matrix it is +one GEMM call). The matrix is split into a 2 × 2 block partition, + +``` +┌─────┬─────┐ +│ A11 │ A12 │ +├─────┼─────┤ +│ A21 │ A22 │ +└─────┴─────┘ +``` + +the routine calls itself on the diagonal blocks `A11` and `A22`, and the off-diagonal block is +handled by large matrix products (GEMM). For Cholesky, for example: factor `A11 = L11 L11ᵀ`, solve +for `L21` with a triangular solve, update `A22 -= L21 L21ᵀ`, then factor `A22`. + +- **Where it splits.** At `n ÷ 2` when `n` is a power of two, otherwise at the largest power of + two below `n`, so most blocks have power-of-two sizes. +- **Where it stops.** When a block is small enough it goes to a direct method, the *leaf*: + [`potrf!`](@ref) for blocks of at most 4096 rows in `potrf_recursive!`, an unpivoted LU of at + most 2048 rows in `lu_recursive!`, and a direct kernel of at most 256 rows (solve) or 16 rows + (multiply) in `unified_rectrxm!` (on CUDA, cuBLAS at both leaves, with the multiply leaf at 256 + rows). The leaf size of the two factorizations is their second + argument. +- **Why.** Almost all the work ends up in large GEMMs, which run near peak speed on CPUs and GPUs, + and the same code runs on every backend. + +The leaf size changes the speed, not the result: + +```jldoctest +using NextLA # for potrf_recursive! +using LinearAlgebra # for I + +n = 2048 +A = rand(n, n) +S = A * A' + n * I # symmetric positive definite + +F1 = potrf_recursive!(copy(S)) # default leaf: one potrf! call +F2 = potrf_recursive!(copy(S), 256) # leaves of at most 256 rows +F1 ≈ F2 + +# output + +true +``` + +## Pivoting + +| Routine | Pivoting | Matrices it suits | +|:--|:--|:--| +| [`getrf2!`](@ref), `lu!(NextLAMatrix(A))` | partial: rows | any square or rectangular matrix | +| [`getc2!`](@ref) | complete: rows and columns | small matrices where stability matters most | +| [`tile_lu_factor!`](@ref) | partial, within each `n × n` tile (`n` ≤ 32) | GPU only; diagonally dominant matrices, or ones that need only in-tile pivoting | +| [`lu_base!`](@ref) | partial, over the whole matrix | any size on the CPU; `n` ≤ 32 on a GPU | +| [`lu_recursive!`](@ref), [`lu_recursive_nopiv!`](@ref) | none | matrices that need no pivoting, such as diagonally dominant ones | + +Without pivoting, a zero pivot throws `ZeroPivotException`, and a small one is not checked, so use +the unpivoted routines only when the matrix is known to be safe. + +## Tile QR + +The QR routines follow the tile algorithms of PLASMA: the matrix is cut into square tiles, and +each step works on one or two tiles. + +1. `NextLA.geqrt!` computes the QR factorization of a diagonal tile, storing `R` in its upper + triangle and the Householder reflectors below it (compact WY form, with the factor `T`). +2. `NextLA.tsqrt!` (triangle on square) or `NextLA.ttqrt!` (triangle on triangle) eliminates a + tile below the diagonal against the `R` above it. +3. `NextLA.unmqr!`, `NextLA.tsmqr!` and `NextLA.ttmqr!` apply the same transformations to the + tiles to the right, or to a right-hand side. + +These routines are not exported. A least-squares solve with `geqrt!` and `unmqr!`, and examples of +the tile kernels, are on the [QR](@ref "QR and Householder kernels") API page. + +## Batched routines + +[`gemm_batched!`](@ref), [`trsm_batched!`](@ref), [`syrk_batched!`](@ref) and +[`potrf_batched!`](@ref) apply one operation to many matrices of the same size at once. The batch is +given as a 3-D array, with the matrices along the third dimension, or as a vector of matrices +([`potrf_batched!`](@ref) takes a vector only on CUDA). On the CPU the batch is a loop; on a GPU it +is one vendor call where the vendor has one. On CUDA, a vector batch whose matrices differ in size +or stride is done one matrix at a time. Which layouts each GPU accepts is on +[Backends and GPUs](@ref). + +```jldoctest +using NextLA # for gemm_batched! + +A = rand(256, 256, 32) # 32 matrices of 256 × 256 +B = rand(256, 256, 32) +C = zeros(256, 256, 32) + +# C[:, :, k] = A[:, :, k] * B[:, :, k] for every k +gemm_batched!('N', 'N', 1.0, A, B, 0.0, C) +all(C[:, :, k] ≈ A[:, :, k] * B[:, :, k] for k in 1:32) + +# output + +true +``` diff --git a/docs/src/manual/mixed_precision.md b/docs/src/manual/mixed_precision.md new file mode 100644 index 00000000..798819f5 --- /dev/null +++ b/docs/src/manual/mixed_precision.md @@ -0,0 +1,250 @@ +```@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 for a `FullMixedPrec`, +`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`. A +`SymmMixedPrec` or `TriMixedPrec` stores one off-diagonal block per split: one in `Float16` and two +in `Float32`. + +### 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, except for a `SymmMixedPrec`, which is its +own transpose: they return `M` itself. + +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`, when the + container is built and when an update would raise the scale that far. +- Updates (GEMM, SYRK) of an off-diagonal block narrower than `Float32`, and solves of an + off-diagonal block narrower than the leaves, raise the block's scale when the result passes the + range of its type. Leaves and wider blocks keep their scale, and an update whose result overflows + the `Float32` working copy itself is stored as `Inf` without an error. +- Leaves of [`lu_recursive!`](@ref) and [`potrf_recursive!`](@ref) must be unscaled: one scale + cannot hold both `L` and `U`, and a Cholesky factor does not scale with its block. 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 or a +triangular solve on the off-diagonal blocks. [`recgemm!`](@ref), [`recsyrk!`](@ref) and +[`lu_recursive!`](@ref) run independent parts as concurrent tasks for large matrices: on a GPU each +task has its own stream, so their kernels can overlap; on the CPU they take turns, so they do not +compete with BLAS's own threads. + +| 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'`) | + +With an off-diagonal block narrower than `Float32`, [`recgemm!`](@ref) (and so the updates of +[`lu_recursive!`](@ref)) first rounds wider operands to the block's type, each with a scale, so the +product's error is that of the block's storage. A `Float16` block is then updated in place with +`Float32` sums, on tensor cores on a GPU, and its scale is raised if the result overflows. On Metal +and oneAPI, which have no mixed-type GEMM, the operands are not rounded and the product runs in +`Float32`. When the top-level off-diagonal blocks are narrower than `Float32`, the `Float32` GEMMs of +`recgemm!` and `lu_recursive!` may run on TF32 tensor cores on CUDA, which keeps the error at the +level the `Float16` blocks already cost. + +[`recsyrk!`](@ref) updates a `Float64` leaf from `Float16` or `Float32` rows by forming the product in +`Float32` (summed in `Float32`) and adding it into the leaf in `Float64`; the leaf itself is never +rounded. This runs at the speed of a `Float32` update but adds `Float32` rounding to it. In a +Cholesky with `Float64` leaves directly under `Float32` blocks (`precisions = [Float32, Float64]`), +the error can grow several-fold: about 9× on ``AA^T + nI`` with uniform random ``A``, to about +``2 \times 10^{-7}``. With `Float16` blocks above the leaves, their error dominates and the update +adds nothing visible. + +### 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) # the factor as triangular: shares M's blocks, copies their scales +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)`. + [`unified_rectrxm!`](@ref) and [`lu_recursive!`](@ref) throw an `ArgumentError` for a transposed + container (a `SymmMixedPrec` is its own transpose, so it passes unchanged), and so does + [`recgemm!`](@ref) for a transposed `C`. +- **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. +- **Build `TriMixedPrec(M)` after the factorization.** It shares `M`'s blocks but copies their + scales, so build it after the last in-place update of `M` ([`potrf_recursive!`](@ref), + [`recsyrk!`](@ref)). One built before reads the updated blocks with the old scales, which can be + far off. +- **`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/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/amdgpu/common.jl b/ext/amdgpu/common.jl index 41a92877..7f225f4e 100644 --- a/ext/amdgpu/common.jl +++ b/ext/amdgpu/common.jl @@ -9,7 +9,7 @@ const NATIVE_STRIDED_BATCHED_TYPES = Union{Float32, Float64, ComplexF32, Complex @inline NextLA.supports_pointer_batched(::Type{<:AMDGPU.ROCBackend}) = true @inline _rocblas_datatype(::Type{Float16}) = rocBLAS.rocblas_datatype_f16_r -@inline _rocblas_datatype(::Type{NextLA._BFloat16}) = rocBLAS.rocblas_datatype_bf16_r +@inline _rocblas_datatype(::Type{NextLA.BFloat16}) = rocBLAS.rocblas_datatype_bf16_r @inline _rocblas_datatype(::Type{Float32}) = rocBLAS.rocblas_datatype_f32_r @inline _rocblas_datatype(::Type{Float64}) = rocBLAS.rocblas_datatype_f64_r @inline _rocblas_datatype(::Type{ComplexF32}) = rocBLAS.rocblas_datatype_f32_c @@ -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/gemm.jl b/ext/amdgpu/gemm.jl index edbf3251..e89ab9ac 100644 --- a/ext/amdgpu/gemm.jl +++ b/ext/amdgpu/gemm.jl @@ -6,6 +6,7 @@ function NextLA.gemmEx!(transA::Char, beta, C::AMDGPU.StridedROCMatrix; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case NextLA._check_compute_type(compute_type) if NextLA._supports_native_gemm(eltype(A), eltype(B), eltype(C)) && compute_type == eltype(C) return rocBLAS.gemm!(transA, transB, eltype(C)(alpha), A, B, eltype(C)(beta), C) @@ -33,6 +34,7 @@ function NextLA.gemm_batched!(transA::Char, B::AbstractVector{<:AMDGPU.ROCArray{T, 2}}, beta, C::AbstractVector{<:AMDGPU.ROCArray{T, 2}}) where {T} + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return rocBLAS.gemm_batched!(transA, transB, T(alpha), A, B, T(beta), C) end @@ -43,6 +45,7 @@ function NextLA.gemm_batched!(transA::Char, B::AbstractVector{<:AMDGPU.StridedROCMatrix{T}}, beta, C::AbstractVector{<:AMDGPU.StridedROCMatrix{T}}) where {T} + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case NextLA._check_batch_lengths(A, B, C) isempty(A) && return C @@ -73,6 +76,7 @@ function NextLA.gemm_batched!(transA::Char, B::AMDGPU.StridedROCArray{<:Any, 3}, beta, C::AMDGPU.StridedROCArray{<:Any, 3}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case if _supports_native_strided_batched(eltype(A), eltype(B), eltype(C)) m, n, k, lda, ldb, ldc, strideA, strideB, strideC, batchC = NextLA._strided_batch_layout(transA, transB, A, B, C) @@ -112,6 +116,7 @@ function NextLA.gemm_batched_ptrs!(transA::Char, Cptrs::AMDGPU.ROCArray, Cref::AbstractMatrix{T}, batch_count::Integer) where {T} + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case batch_count <= 0 && return Cptrs m, n, k, lda, ldb, ldc = NextLA._gemm_dims(transA, transB, Aref, Bref, Cref) @@ -142,6 +147,7 @@ function NextLA.gemmEx_batched_ptrs!(transA::Char, Cref::AbstractMatrix, batch_count::Integer; compute_type::Type = NextLA.default_compute_type(alpha, Aref, Bref, beta, Cref)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case batch_count <= 0 && return Cptrs NextLA._check_compute_type(compute_type) @@ -169,6 +175,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:AMDGPU.ROCArray{<:Any, 2}}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return _gemmEx_batched_vector!(transA, transB, alpha, A, B, beta, C, compute_type) end @@ -198,6 +205,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:AMDGPU.StridedROCMatrix{<:Any}}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return _gemmEx_batched_vector!(transA, transB, alpha, A, B, beta, C, compute_type) end @@ -209,6 +217,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AMDGPU.StridedROCArray{<:Any, 3}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case NextLA._check_compute_type(compute_type) if eltype(A) == eltype(B) == eltype(C) && compute_type == eltype(C) diff --git a/ext/amdgpu/potrf.jl b/ext/amdgpu/potrf.jl index 8783ffb4..225568f8 100644 --- a/ext/amdgpu/potrf.jl +++ b/ext/amdgpu/potrf.jl @@ -17,6 +17,7 @@ end function NextLA.potrf_batched!(uplo::Char, A::AMDGPU.StridedROCArray{T,3}) where {T} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them return _potrf_batched_amdgpu!(uplo, A) end @@ -24,6 +25,7 @@ end # -- a recursive Cholesky's leaf -- is factored in a contiguous copy and written # back. Never executed: no AMD device here. function NextLA.potrf!(uplo::Char, A::AMDGPU.StridedROCMatrix{T}) where {T<:Union{Float32,Float64,ComplexF32,ComplexF64}} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them NextLA._potrf_dims(uplo, A) A isa AMDGPU.ROCMatrix && return AMDGPU.rocSOLVER.potrf!(uplo, A) B = similar(parent(A), T, size(A)) diff --git a/ext/amdgpu/rectrxm.jl b/ext/amdgpu/rectrxm.jl index 92894e59..1a946c08 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,23 +28,19 @@ function NextLA.unified_rectrxm!(side::Char, uplo::Char, - transpose::Char, + trans::Char, diag::Char, alpha::Number, func::Char, A::AMDGPU.ROCMatrix{T}, B::AMDGPU.ROCMatrix{T}) where {T<:Union{Float32,Float64,ComplexF32,ComplexF64}} - if diag != 'N' && diag != 'U' - throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) - end + side, uplo, trans, diag, func = NextLA._trxm_flags(side, uplo, trans, diag, func) 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'")) end return B end diff --git a/ext/amdgpu/syrk.jl b/ext/amdgpu/syrk.jl index 5dd51ae7..c024d846 100644 --- a/ext/amdgpu/syrk.jl +++ b/ext/amdgpu/syrk.jl @@ -52,6 +52,7 @@ function _syrk_batched_native!(uplo::Char, C::AMDGPU.StridedROCArray{<:Any, 3}) size(A, 3) == size(C, 3) || size(A, 3) == 1 || throw(DimensionMismatch("syrk_batched!: A and C batch sizes are incompatible")) + size(C, 3) == 0 && return C # an empty batch: nothing to read (B51) n, k = NextLA._syrk_dims(uplo, trans, @view(A[:, :, 1]), @view(C[:, :, 1])) lda = max(1, stride(A, 2)) ldc = max(1, stride(C, 2)) @@ -69,6 +70,7 @@ function NextLA.syrk!(uplo::Char, A::AMDGPU.StridedROCMatrix{<:Any}, beta, C::AMDGPU.StridedROCMatrix{<:Any}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them return _syrk_native!(uplo, trans, alpha, A, beta, C) end @@ -78,6 +80,7 @@ function NextLA.syrk_batched!(uplo::Char, A::AbstractVector{<:AMDGPU.ROCArray{<:Any, 2}}, beta, C::AbstractVector{<:AMDGPU.ROCArray{<:Any, 2}}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them return _syrk_batched_native!(uplo, trans, alpha, A, beta, C) end @@ -87,5 +90,6 @@ function NextLA.syrk_batched!(uplo::Char, A::AMDGPU.StridedROCArray{<:Any, 3}, beta, C::AMDGPU.StridedROCArray{<:Any, 3}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them return _syrk_batched_native!(uplo, trans, alpha, A, beta, C) end diff --git a/ext/cuda/common.jl b/ext/cuda/common.jl index be8866b9..8b11f248 100644 --- a/ext/cuda/common.jl +++ b/ext/cuda/common.jl @@ -7,7 +7,7 @@ const CUSOLVER = CUDA.CUSOLVER @inline NextLA.supports_pointer_batched(::Type{<:CUDA.CUDABackend}) = true @inline _cublas_compute_type(::Type{Float16}) = CUBLAS.CUBLAS_COMPUTE_16F -@inline _cublas_compute_type(::Type{NextLA._BFloat16}) = CUBLAS.CUBLAS_COMPUTE_32F +@inline _cublas_compute_type(::Type{NextLA.BFloat16}) = CUBLAS.CUBLAS_COMPUTE_32F @inline _cublas_compute_type(::Type{Float32}) = CUBLAS.CUBLAS_COMPUTE_32F @inline _cublas_compute_type(::Type{Float64}) = CUBLAS.CUBLAS_COMPUTE_64F @inline _cublas_compute_type(::Type{ComplexF32}) = CUBLAS.CUBLAS_COMPUTE_32F @@ -15,7 +15,7 @@ const CUSOLVER = CUDA.CUSOLVER @inline _cublas_compute_type(::Type{Int32}) = CUBLAS.CUBLAS_COMPUTE_32I @inline _cublas_scalar_type(::Type{Float16}) = Float16 -@inline _cublas_scalar_type(::Type{NextLA._BFloat16}) = Float32 +@inline _cublas_scalar_type(::Type{NextLA.BFloat16}) = Float32 @inline _cublas_scalar_type(::Type{Float32}) = Float32 @inline _cublas_scalar_type(::Type{Float64}) = Float64 @inline _cublas_scalar_type(::Type{ComplexF32}) = ComplexF32 @@ -41,3 +41,25 @@ end @inline NextLA._build_batch_ptrs(batch::AbstractVector{<:CUDA.StridedCuMatrix}) = _unsafe_batch_strided(batch) + +# cuBLAS and cuSOLVER take one leading dimension, so a view whose rows are not consecutive would be read +# and written at the wrong places; such arguments are copied to contiguous arrays and the results back. +_rowstrided(X) = stride(X, 1) != 1 +_contig(X) = _rowstrided(X) ? copy(X) : X + +# The vendor batched calls take every size and leading dimension from the first member: a batch whose +# members differ in size or stride, or have rows that are not consecutive, is done member by member. +_batch_uniform(Xs...) = all(X -> all(x -> size(x) == size(first(X)) && stride(x, 2) == stride(first(X), 2) && stride(x, 1) == 1, X), Xs) + +# A device matrix behind a Transpose/Adjoint wrapper (or a view of one), with the cuBLAS flag that +# undoes the wrapper: (parent array, 'T' / 'C'), or (X, 'N') for anything else. +using LinearAlgebra: Transpose, Adjoint +_untrans(X::Transpose) = (parent(X), 'T') +_untrans(X::Adjoint) = (parent(X), 'C') +_untrans(X::SubArray{<:Any,2,<:Transpose}) = (view(parent(parent(X)), reverse(parentindices(X))...), 'T') +_untrans(X::SubArray{<:Any,2,<:Adjoint}) = (view(parent(parent(X)), reverse(parentindices(X))...), 'C') +_untrans(X) = (X, 'N') + +NextLA._release!(x::CUDA.CuArray) = CUDA.unsafe_free!(x) +# The inverse: the wrapper again around a (possibly copied) parent. +_retrans(X, t::Char) = t == 'N' ? X : t == 'T' ? transpose(X) : adjoint(X) diff --git a/ext/cuda/gemm.jl b/ext/cuda/gemm.jl index 8b94e205..ff1397eb 100644 --- a/ext/cuda/gemm.jl +++ b/ext/cuda/gemm.jl @@ -251,6 +251,8 @@ function NextLA.gemm_batched!(transA::Char, B::AbstractVector{<:CUDA.CuArray{T,2}}, beta, C::AbstractVector{<:CUDA.CuArray{T,2}}) where {T} + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case + isempty(A) && (NextLA._check_batch_lengths(A, B, C); return C) # an empty batch: nothing to do # CUBLAS.gemm_batched! covers only the five native types. A plain CuArray is # a StridedCuMatrix too, but this signature is the more specific of the two, # so BFloat16 landed here and raised a MethodError instead of reaching the @@ -262,9 +264,18 @@ function NextLA.gemm_batched!(transA::Char, AbstractVector{<:CUDA.StridedCuMatrix{T}},Any, AbstractVector{<:CUDA.StridedCuMatrix{T}}}, transA, transB, alpha, A, B, beta, C) + _batch_uniform(A, B, C) || return _gemm_batched_each!(transA, transB, alpha, A, B, beta, C) return CUBLAS.gemm_batched!(transA, transB, alpha, A, B, beta, C) end +function _gemm_batched_each!(transA, transB, alpha, A, B, beta, C) + NextLA._check_batch_lengths(A, B, C) + for i in eachindex(A, B, C) + NextLA.gemmEx!(transA, transB, alpha, A[i], B[i], beta, C[i]) + end + return C +end + function NextLA.gemm_batched!(transA::Char, transB::Char, alpha, @@ -272,8 +283,10 @@ function NextLA.gemm_batched!(transA::Char, B::AbstractVector{<:CUDA.StridedCuMatrix{T}}, beta, C::AbstractVector{<:CUDA.StridedCuMatrix{T}}) where {T} + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case NextLA._check_batch_lengths(A, B, C) isempty(A) && return C + _batch_uniform(A, B, C) || return _gemm_batched_each!(transA, transB, alpha, A, B, beta, C) m, n, k, lda, ldb, ldc = NextLA._gemm_dims(transA, transB, A[1], B[1], C[1]) @@ -306,6 +319,13 @@ function NextLA.gemm_batched!(transA::Char, B::CUDA.StridedCuArray{<:Any,3}, beta, C::CUDA.StridedCuArray{<:Any,3}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case + if _rowstrided(A) || _rowstrided(B) || _rowstrided(C) + Cc = _contig(C) + CUBLAS.gemm_strided_batched!(transA, transB, alpha, _contig(A), _contig(B), beta, Cc) + Cc === C || (C .= Cc) + return C + end return CUBLAS.gemm_strided_batched!(transA, transB, alpha, A, B, beta, C) end @@ -320,6 +340,7 @@ function NextLA.gemm_batched_ptrs!(transA::Char, Cptrs::CUDA.CuArray, Cref::AbstractMatrix{T}, batch_count::Integer) where {T} + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case batch_count <= 0 && return Cptrs m, n, k, lda, ldb, ldc = NextLA._gemm_dims(transA, transB, Aref, Bref, Cref) @@ -347,6 +368,7 @@ function NextLA.gemmEx_batched_ptrs!(transA::Char, Cref::AbstractMatrix, batch_count::Integer; compute_type::Type=NextLA.default_compute_type(alpha, Aref, Bref, beta, Cref)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case batch_count <= 0 && return Cptrs NextLA._check_compute_type(compute_type) @@ -371,6 +393,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:CUDA.CuArray{<:Any,2}}; compute_type::Type=NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return _gemmEx_batched_vector!(transA, transB, alpha, A, B, beta, C, compute_type) end @@ -382,6 +405,12 @@ function _gemmEx_batched_vector!(transA::Char, transB::Char, alpha, compute_type::Type) NextLA._check_batch_lengths(A, B, C) isempty(A) && return C + if !_batch_uniform(A, B, C) # members that differ in size or stride: one gemmEx! each + for i in eachindex(A, B, C) + NextLA.gemmEx!(transA, transB, alpha, A[i], B[i], beta, C[i]; compute_type) + end + return C + end Aptrs = _unsafe_batch_strided(A) Bptrs = _unsafe_batch_strided(B) @@ -409,6 +438,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:CUDA.StridedCuMatrix{<:Any}}; compute_type::Type=NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return _gemmEx_batched_vector!(transA, transB, alpha, A, B, beta, C, compute_type) end @@ -420,6 +450,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::CUDA.StridedCuArray{<:Any,3}; compute_type::Type=NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case NextLA._check_compute_type(compute_type) m, n, k, lda, ldb, ldc, strideA, strideB, strideC, batchC = NextLA._strided_batch_layout(transA, transB, A, B, C) @@ -442,15 +473,25 @@ function NextLA.gemmEx!(transA::Char, beta, C::CUDA.StridedCuMatrix; compute_type::Type=NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case + if _rowstrided(A) || _rowstrided(B) || _rowstrided(C) + Cc = _contig(C) + NextLA.gemmEx!(transA, transB, alpha, _contig(A), _contig(B), beta, Cc; compute_type) + Cc === C || (C .= Cc) + return C + end NextLA._check_compute_type(compute_type) m, n, k, lda, ldb, ldc = NextLA._gemm_dims(transA, transB, A, B, C) scalar_type = _cublas_scalar_type(compute_type) + # Inside NextLA._with_tf32 (the mixed-precision LU), a Float32 x Float32 product may use TF32 tensor cores. + compute = (compute_type == Float32 && eltype(A) == eltype(B) == eltype(C) == Float32 && NextLA._tf32_on()) ? + CUBLAS.CUBLAS_COMPUTE_32F_FAST_TF32 : _cublas_compute_type(compute_type) CUBLAS.cublasGemmEx( CUBLAS.handle(), transA, transB, m, n, k, CUDA.CuRef{scalar_type}(alpha), A, eltype(A), lda, B, eltype(B), ldb, CUDA.CuRef{scalar_type}(beta), - C, eltype(C), ldc, _cublas_compute_type(compute_type), CUBLAS.CUBLAS_GEMM_DEFAULT, + C, eltype(C), ldc, compute, CUBLAS.CUBLAS_GEMM_DEFAULT, ) return C end @@ -458,6 +499,12 @@ end function NextLA._gemm_compute!(::NextLA.TF32, transA, transB, alpha, A::CUDA.StridedCuMatrix, B::CUDA.StridedCuMatrix, beta, C::CUDA.StridedCuMatrix) + if _rowstrided(A) || _rowstrided(B) || _rowstrided(C) + Cc = _contig(C) + NextLA._gemm_compute!(NextLA.TF32(), transA, transB, alpha, _contig(A), _contig(B), beta, Cc) + Cc === C || (C .= Cc) + return C + end m, n, k, lda, ldb, ldc = NextLA._gemm_dims(transA, transB, A, B, C) CUBLAS.cublasGemmEx( CUBLAS.handle(), transA, transB, m, n, k, CUDA.CuRef{Float32}(alpha), @@ -470,8 +517,8 @@ end # TF32 over a pointer batch. Without this method the generic # _gemm_compute_batched_ptrs!(::TF32, ...) throws "TF32 GEMM is supported only # on CUDA" -- on CUDA. The other two TF32 modes were overridden here and this -# one was not, so TLR's compressed accumulation, which passes the caller's mode -# straight through to precision_gemm_batched_ptrs!, could not use TF32 at all. +# one was not, so a caller passing its mode straight through to +# precision_gemm_batched_ptrs! could not use TF32 at all. function NextLA._gemm_compute_batched_ptrs!(::NextLA.TF32, transA, transB, alpha, Aptrs::CUDA.CuArray, Aref::AbstractMatrix, Bptrs::CUDA.CuArray, Bref::AbstractMatrix, @@ -496,6 +543,12 @@ function NextLA._gemm_compute_batched!(::NextLA.TF32, transA, transB, alpha, C::AbstractVector{<:CUDA.StridedCuMatrix}) NextLA._check_batch_lengths(A, B, C) isempty(C) && return C + if !_batch_uniform(A, B, C) # members that differ in size or stride: one TF32 GEMM each + for i in eachindex(A, B, C) + NextLA._gemm_compute!(NextLA.TF32(), transA, transB, alpha, A[i], B[i], beta, C[i]) + end + return C + end m, n, k, lda, ldb, ldc = NextLA._gemm_dims(transA, transB, A[1], B[1], C[1]) Aptrs = _unsafe_batch_strided(A) @@ -531,3 +584,104 @@ function NextLA._gemm_compute_batched!(::NextLA.TF32, transA, transB, alpha, ) return C end + +# gemm! on Float32 device matrices, views and transposes: a cuBLAS GEMM. The generic method calls +# mul!, which for a view of a CuArray reaches GPUArrays' generic matmul kernel, 13-15x slower +# than cuBLAS (the recursive Float32 SYRK is built on it). Float64 also goes to cuBLAS (Dgemm), +# as in the other branches (method below). +function NextLA.gemm!(C::CUDA.StridedCuMatrix{Float32}, A::AbstractMatrix{Float32}, B::AbstractMatrix{Float32}, + alpha::Number, beta::Number) + Am, tA = _untrans(A) + Bm, tB = _untrans(B) + (Am isa CUDA.StridedCuMatrix && Bm isa CUDA.StridedCuMatrix) || + return invoke(NextLA.gemm!, Tuple{AbstractMatrix,AbstractMatrix,AbstractMatrix,Number,Number}, C, A, B, alpha, beta) + return _cublas_gemm!(tA, tB, Float32(alpha), Am, Bm, Float32(beta), C) +end + +# CUBLAS.gemm! with views whose rows are not consecutive copied to contiguous first (and C copied +# back), as gemmEx! does: cuBLAS takes only unit-stride columns. +function _cublas_gemm!(tA, tB, alpha, A, B, beta, C) + if _rowstrided(A) || _rowstrided(B) || _rowstrided(C) + Cc = _contig(C) + _cublas_gemm!(tA, tB, alpha, _contig(A), _contig(B), beta, Cc) + Cc === C || (C .= Cc) + return C + end + # Inside NextLA._with_tf32 a Float32 GEMM goes through gemmEx!, which then picks TF32. + NextLA._tf32_on() && eltype(C) == eltype(A) == eltype(B) == Float32 && + return NextLA.gemmEx!(tA, tB, alpha, A, B, beta, C; compute_type=Float32) + return CUBLAS.gemm!(tA, tB, alpha, A, B, beta, C) +end + +# The block reflector C <- H*C or H^H*C (side 'L', forward, columnwise) with cuBLAS, the same steps +# as larfb! (W = C1^H V1 + C2^H V2; W *= T^H or T; C2 -= V2 W^H; C1 -= (W V1^H)^H), where the +# portable code's mul!/rmul! on views reach generic kernels. Float32 and ComplexF32 only: in +# Float64 the portable code already beats cuSOLVER ormqr and this path measured 5-12% slower. +function NextLA._larfb_vendor!(side, trans, m, n, k, V::CUDA.StridedCuMatrix{T}, Tm::CUDA.StridedCuMatrix{T}, + C::CUDA.StridedCuMatrix{T}, work::CUDA.StridedCuMatrix{T}) where {T<:Union{Float32,ComplexF32}} + side == 'L' || return false + # cuBLAS takes unit-stride columns only; other views keep the portable code + (_rowstrided(V) || _rowstrided(Tm) || _rowstrided(C) || _rowstrided(work)) && return false + o = one(T) + W = view(work, 1:n, 1:k) + C1 = view(C, 1:k, 1:n) + V1 = view(V, 1:k, 1:k) + Tb = view(Tm, 1:k, 1:k) + W .= conj.(transpose(C1)) + CUBLAS.trmm!('R', 'L', 'N', 'U', o, V1, W, W) + m > k && CUBLAS.gemm!('C', 'N', o, view(C, k+1:m, 1:n), view(V, k+1:m, 1:k), o, W) + CUBLAS.trmm!('R', 'U', trans == 'N' ? 'C' : 'N', 'N', o, Tb, W, W) + m > k && CUBLAS.gemm!('N', 'C', -o, view(V, k+1:m, 1:k), W, o, view(C, k+1:m, 1:n)) + CUBLAS.trmm!('R', 'L', 'C', 'U', o, V1, W, W) + C1 .-= conj.(transpose(W)) + return true +end + +# gemm! where the output shares a device buffer with an input but no element overlaps, as when a +# recursion's trailing block is one column (LU at n = 2^k + 1): CUDA.jl turns a one-column view into +# a CuArray on the parent's memory, and newer Julia versions' mul! (nightly) refuses any shared +# buffer. Only that case goes to cuBLAS; every other call keeps mul!, and operands that really +# overlap still reach mul!, which refuses them. Float32 already goes to cuBLAS in every case (method +# above), so this covers Float16, Float64, ComplexF32 and ComplexF64. +# Float16 goes to cuBLAS on every call, shared buffer or not: mul! sums Float16 in Float16 (CUDA.jl's +# gemmExComputeType picks CUBLAS_COMPUTE_16F), where the library's rule is Float32 sums (gemmEx!, compute 32F). +# Float64 goes to cuBLAS Dgemm on every call too, as in the other branches (user, 2026-12-03); mul! would take +# cublasGemmEx with 64F compute. +function NextLA.gemm!(C::CUDA.StridedCuMatrix{T}, A::AbstractMatrix{T}, B::AbstractMatrix{T}, + alpha::Number, beta::Number) where {T<:Union{Float16,Float64,ComplexF32,ComplexF64}} + Am, tA = _untrans(A) + Bm, tB = _untrans(B) + if Am isa CUDA.StridedCuMatrix && Bm isa CUDA.StridedCuMatrix + shared = Base.mightalias(C, Am) || Base.mightalias(C, Bm) + # Operands that really overlap the output are left to mul!, which refuses them. + apart = !(Base.mightalias(C, Am) && _may_overlap(C, Am)) && !(Base.mightalias(C, Bm) && _may_overlap(C, Bm)) + T == Float16 && apart && return NextLA.gemmEx!(tA, tB, 1f0 * alpha, Am, Bm, 1f0 * beta, C; compute_type=Float32) + T == Float64 && apart && return _cublas_gemm!(tA, tB, Float64(alpha), Am, Bm, Float64(beta), C) + shared && apart && return _cublas_gemm!(tA, tB, T(alpha), Am, Bm, T(beta), C) + end + return invoke(NextLA.gemm!, Tuple{AbstractMatrix,AbstractMatrix,AbstractMatrix,Number,Number}, C, A, B, alpha, beta) +end + +# Whether two column-major device matrices may share an element (true when unsure). Column jx of X +# covers offsets [jx*ld, jx*ld + mx) from X's first element and column jy of Y covers +# [d + jy*ld, d + jy*ld + my), d being Y's offset from X; a one-column matrix takes the other's ld. +function _may_overlap(X, Y) + s = sizeof(eltype(X)) + s == sizeof(eltype(Y)) || return true + (stride(X, 1) == 1 && stride(Y, 1) == 1) || return true + mx, nx = size(X) + my, ny = size(Y) + (mx == 0 || nx == 0 || my == 0 || ny == 0) && return false + dbytes = Int(UInt(pointer(Y))) - Int(UInt(pointer(X))) + dbytes % s == 0 || return true + d = dbytes ÷ s + nx == 1 && ny == 1 && return d < mx && -d < my + ld = nx == 1 ? stride(Y, 2) : stride(X, 2) + (ny == 1 || stride(Y, 2) == ld) || return true + ld >= max(mx, my) || return true + for t in fld(-my - d, ld):cld(mx - d, ld) # t = jy - jx + -(nx - 1) <= t <= ny - 1 || continue + -my < d + t * ld < mx && return true + end + return false +end diff --git a/ext/cuda/lu.jl b/ext/cuda/lu.jl index 389772b8..600c4627 100644 --- a/ext/cuda/lu.jl +++ b/ext/cuda/lu.jl @@ -12,6 +12,15 @@ for (bname, fname, elty) in ((:cusolverDnSgetrf_bufferSize, :cusolverDnSgetrf, : (:cusolverDnCgetrf_bufferSize, :cusolverDnCgetrf, :ComplexF32), (:cusolverDnZgetrf_bufferSize, :cusolverDnZgetrf, :ComplexF64)) @eval function NextLA._lu_leaf!(A::CUDA.StridedCuMatrix{$elty}) + if _rowstrided(A) # cuSOLVER takes one leading dimension: factor a contiguous copy + Ac = copy(A) + try + NextLA._lu_leaf!(Ac) + finally + A .= Ac + end + return A + end m, n = size(A) lda = max(1, stride(A, 2)) dh = CUSOLVER.dense_handle() diff --git a/ext/cuda/potrf.jl b/ext/cuda/potrf.jl index 90db1971..27a907f4 100644 --- a/ext/cuda/potrf.jl +++ b/ext/cuda/potrf.jl @@ -1,5 +1,10 @@ function NextLA.potrf_batched!(uplo::Char, Av::AbstractVector{<:CUDA.StridedCuMatrix{T}}) where {T} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them + isempty(Av) && return Av, Cint[] # an empty batch: nothing to factor + # Members of different sizes: one factorization each (the batched call reads Av[1]'s size). + T <: Union{Float32, Float64, ComplexF32, ComplexF64} && !all(A -> size(A) == size(first(Av)), Av) && + return Av, Cint[Cint(last(NextLA.potrf!(uplo, A))) for A in Av] eltype(Av) <: CUDA.CuArray && return CUSOLVER.potrfBatched!(uplo, Av) # CUSOLVER's batched-pointer path (`unsafe_batch`) only accepts literal @@ -15,11 +20,20 @@ end function NextLA.potrf_batched!(uplo::Char, A::CUDA.StridedCuArray{T,3}) where {T} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them Av = [@view A[:, :, bid] for bid in axes(A, 3)] - return NextLA.potrf_batched!(uplo, Av) + _, info = NextLA.potrf_batched!(uplo, Av) # the slices are views of A, so A holds the factors + return A, info # (A, status), as the CPU and AMDGPU methods and the docstring end function NextLA.potrf!(uplo::Char, A::CUDA.StridedCuMatrix{T}) where {T<:Union{Float32,Float64,ComplexF32,ComplexF64}} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them NextLA._potrf_dims(uplo, A) + if _rowstrided(A) + Ac = copy(A) + _, info = CUSOLVER.potrf!(uplo, Ac) + A .= Ac + return A, info + end return CUSOLVER.potrf!(uplo, A) end diff --git a/ext/cuda/rectrxm.jl b/ext/cuda/rectrxm.jl index 1cc303a5..156b854e 100644 --- a/ext/cuda/rectrxm.jl +++ b/ext/cuda/rectrxm.jl @@ -1,51 +1,73 @@ -# CUBLAS fast path for unified_rectrxm!. -# -# src/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: -# 7.47 ms vs 2.92 ms at n=512, and 32.45 ms vs 5.10 ms at n=2048. -# -# The approach is from vicki-development, which routes the base case to -# 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 -# 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 -# 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 -# scales after. CUBLAS takes alpha directly, so neither scaling is applied -# here. -# -# 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 -# backend. Float16 keeps the portable path, which widens it to Float32. +# CUDA (cuBLAS) pieces of NextLA's recursive triangular solve and multiply (unified_rectrxm!). -function NextLA.unified_rectrxm!(side::Char, - uplo::Char, - transpose::Char, - diag::Char, - alpha::Number, - func::Char, - A::CUDA.StridedCuMatrix{T}, - B::CUDA.StridedCuMatrix{T}) where {T<:Union{Float32,Float64,ComplexF32,ComplexF64}} - if diag != 'N' && diag != 'U' - throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) +# CUDA methods for the recursion in src/dense/blas/trsm/rectrxm.jl. unified_rectrxm! itself is not +# overridden here: on CUDA, as on every backend, it recurses for every element type, Float32 and +# Float64 included, down to 256-row blocks (16 for the multiply), and only those blocks and the updates between them go +# to cuBLAS (the paper's design, as vicki-development's dispatch_trsm!/dispatch_trmm!). The +# whole-call cuBLAS method that was here (PR #22) is removed so the routine is the recursive +# algorithm on CUDA too (user, 2026-12-02). The same holds for the leaves of the mixed-precision TRSM. +# There, as in vicki-development's dispatch_trsm! and GEMM_SUB!, +# the leaf solve is cuBLAS trsm! and the update C -= X*Y is a cuBLAS GEMM (Sgemm/Dgemm through _cublas_gemm!, +# TF32 inside _with_tf32). cuBLAS has no Float16 +# TRSM, so a Float16 leaf is solved in Float32 copies, and a Float16 update accumulates in Float32 (gemmEx!). +# Operands that are not plain strided device arrays keep the portable methods. +function NextLA._rec_solve_leaf!(side, uplo, A, B::CUDA.StridedCuMatrix{T}, unitdiag) where {T<:Union{Float16,Float32,Float64}} + Am, tA = _untrans(A) + Am isa CUDA.StridedCuMatrix || return NextLA._trxm_base!('S', side, uplo, A, B, unitdiag) + if _rowstrided(Am) || _rowstrided(B) # cuBLAS takes unit-stride columns only: copy, solve, copy back + Bc = _contig(B) + NextLA._rec_solve_leaf!(side, uplo, _retrans(_contig(Am), tA), Bc, unitdiag) + Bc === B || (B .= Bc) + return B end - if func == 'S' - CUBLAS.trsm!(side, uplo, transpose, 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) + # The recursion flipped uplo when it wrapped A in a transpose; cuBLAS takes the stored triangle. + upl = tA == 'N' ? uplo : (uplo == 'L' ? 'U' : 'L') + diag = unitdiag ? 'U' : 'N' + if T == Float16 + B32 = NextLA._widened(B, Float32, :leaf32_B) + CUBLAS.trsm!(side, upl, tA == 'C' ? 'T' : tA, diag, 1f0, NextLA._widened(Am, Float32, :leaf32_A), B32) + B .= Float16.(B32) else - throw(ArgumentError("func must be 'S' or 'M', got '$func'")) + CUBLAS.trsm!(side, upl, tA, diag, one(T), Am, B) end return B end + +function NextLA._rec_solve_update!(C::CUDA.StridedCuMatrix{T}, X, Y) where {T<:Union{Float16,Float32,Float64}} + Xm, tX = _untrans(X) + Ym, tY = _untrans(Y) + (Xm isa CUDA.StridedCuMatrix && Ym isa CUDA.StridedCuMatrix) || return NextLA.GEMM_SUB!(C, X, Y) + T == Float16 ? NextLA.gemmEx!(tX, tY, -1f0, Xm, Ym, 1f0, C; compute_type=Float32) : + _cublas_gemm!(tX, tY, -one(T), Xm, Ym, one(T), C) # as #7's GEMM_SUB! (user, 2026-12-03) + return C +end + +function NextLA._rec_mult_leaf!(side, uplo, A, B::CUDA.StridedCuMatrix{T}, unitdiag) where {T<:Union{Float16,Float32,Float64}} + Am, tA = _untrans(A) + Am isa CUDA.StridedCuMatrix || return NextLA._trxm_base!('M', side, uplo, A, B, unitdiag) + if _rowstrided(Am) || _rowstrided(B) # as the solve leaf: cuBLAS takes unit-stride columns only + Bc = _contig(B) + NextLA._rec_mult_leaf!(side, uplo, _retrans(_contig(Am), tA), Bc, unitdiag) + Bc === B || (B .= Bc) + return B + end + upl = tA == 'N' ? uplo : (uplo == 'L' ? 'U' : 'L') + diag = unitdiag ? 'U' : 'N' + if T == Float16 + B32 = NextLA._widened(B, Float32, :leaf32_B) + CUBLAS.trmm!(side, upl, tA == 'C' ? 'T' : tA, diag, 1f0, NextLA._widened(Am, Float32, :leaf32_A), B32, B32) + B .= Float16.(B32) + else + CUBLAS.trmm!(side, upl, tA, diag, one(T), Am, B, B) + end + return B +end + +function NextLA._rec_mult_update!(X, Y, C::CUDA.StridedCuMatrix{T}) where {T<:Union{Float16,Float32,Float64}} + Xm, tX = _untrans(X) + Ym, tY = _untrans(Y) + (Xm isa CUDA.StridedCuMatrix && Ym isa CUDA.StridedCuMatrix) || return NextLA.GEMM_ADD!(X, Y, C) + T == Float16 ? NextLA.gemmEx!(tX, tY, 1f0, Xm, Ym, 1f0, C; compute_type=Float32) : + _cublas_gemm!(tX, tY, one(T), Xm, Ym, one(T), C) # as #7's GEMM_ADD! + return C +end diff --git a/ext/cuda/syrk.jl b/ext/cuda/syrk.jl index 8471c628..afc528f0 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 @@ -15,6 +15,14 @@ function NextLA.syrk!(uplo::Char, A::CUDA.StridedCuMatrix{<:Any}, beta, C::CUDA.StridedCuMatrix{<:Any}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them + trans in ('N', 'T', 'C') || throw(ArgumentError("Unsupported transpose flag `$trans`")) # the vendor wrapper reads any other as 'T' + if _rowstrided(A) || _rowstrided(C) + Cc = _contig(C) + CUBLAS.syrk!(uplo, trans, alpha, _contig(A), beta, Cc) + Cc === C || (C .= Cc) + return C + end return CUBLAS.syrk!(uplo, trans, alpha, A, beta, C) end @@ -24,6 +32,7 @@ function NextLA.syrk_batched!(uplo::Char, A::AbstractVector{<:CUDA.CuArray{<:Any,2}}, beta, C::AbstractVector{<:CUDA.CuArray{<:Any,2}}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them @warn "syrk_batched! has no native batched SYRK here; looping syrk!" backend = "CUDA" layout = :pointer return NextLA._syrk_batched_fallback!(uplo, trans, alpha, A, beta, C) end @@ -34,6 +43,7 @@ function NextLA.syrk_batched!(uplo::Char, A::CUDA.StridedCuArray{<:Any,3}, beta, C::CUDA.StridedCuArray{<:Any,3}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them @warn "syrk_batched! has no native batched SYRK here; looping syrk!" backend = "CUDA" layout = :strided return NextLA._syrk_batched_fallback!(uplo, trans, alpha, A, beta, C) end diff --git a/ext/cuda/trsm.jl b/ext/cuda/trsm.jl index 932b5e8f..91174ab3 100644 --- a/ext/cuda/trsm.jl +++ b/ext/cuda/trsm.jl @@ -7,6 +7,12 @@ function NextLA.trsm_batched!(side::Char, alpha=one(T)) where {T} length(A) == length(B) || throw(DimensionMismatch("trsm_batched!: matrix batches must have matching lengths")) isempty(A) && return B + if !(_batch_uniform(A, B)) # members that differ in size or stride: one solve each (the batched call reads A[1]'s) + for i in eachindex(A, B) + NextLA.trsm!(side, uplo, transa, diag, alpha, A[i], B[i]) + end + return B + end nA = size(A[1], 1) size(A[1], 2) == nA || throw(DimensionMismatch("trsm_batched!: A must be square")) m, n = size(B[1]) @@ -48,3 +54,19 @@ function NextLA.trsm_batched!(side::Char, NextLA.trsm_batched!(side, uplo, transa, diag, Av, Bv, alpha) return B end + +# Public trsm! on CUDA: one cuBLAS call for the four cuBLAS types, as in the other branches (recpotrf's +# Float32/Float64 panel solve uses it); unified_rectrxm! itself recurses (rectrxm.jl). Flags are checked as +# in rectrxm.jl, and row-strided views are copied, since cuBLAS reads only stride(A, 2). +function NextLA.trsm!(side::Char, uplo::Char, transa::Char, diag::Char, alpha::Number, + A::CUDA.StridedCuMatrix{T}, B::CUDA.StridedCuMatrix{T}) where {T<:Union{Float32,Float64,ComplexF32,ComplexF64}} + side, uplo, transa, diag, _ = NextLA._trxm_flags(side, uplo, transa, diag, 'S') + if _rowstrided(A) || _rowstrided(B) + Bc = _contig(B) + NextLA.trsm!(side, uplo, transa, diag, alpha, _contig(A), Bc) + Bc === B || (B .= Bc) + return B + end + CUBLAS.trsm!(side, uplo, transa, diag, T(alpha), A, B) + return B +end 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..4314132f 100644 --- a/ext/metal/gemm.jl +++ b/ext/metal/gemm.jl @@ -40,6 +40,7 @@ function NextLA.gemm_batched!(transA::Char, B::Metal.MtlArray{<:Any, 3}, beta, C::Metal.MtlArray{<:Any, 3}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return _gemm_batched_mps!(transA, transB, alpha, A, B, beta, C) end @@ -50,6 +51,7 @@ function NextLA.gemm_batched!(transA::Char, B::MtlMatrixBatchView, beta, C::MtlMatrixBatchView) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case Adense = _dense_mtl_batch(A) Bdense = _dense_mtl_batch(B) Cdense = _dense_mtl_batch(C) @@ -64,6 +66,7 @@ function NextLA.gemm_batched!(transA::Char, B::Union{Metal.MtlArray{<:Any, 3}, MtlMatrixBatchView}, beta, C::Union{Metal.MtlArray{<:Any, 3}, MtlMatrixBatchView}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case Adense = _dense_mtl_batch(A) Bdense = _dense_mtl_batch(B) Cdense = _dense_mtl_batch(C) @@ -79,6 +82,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::Metal.MtlArray{<:Any, 3}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case r = NextLA._try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r throw(ArgumentError("NextLA.gemmEx_batched! mixed-type batched GEMM is not supported on Metal")) @@ -92,6 +96,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::MtlMatrixBatchView; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case r = NextLA._try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r throw(ArgumentError("NextLA.gemmEx_batched! mixed-type batched GEMM is not supported on Metal")) @@ -101,7 +106,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, @@ -110,6 +115,7 @@ function NextLA.gemm_batched!(transA::Char, B::AbstractVector{<:Metal.MtlArray{<:Any, 2}}, beta, C::AbstractVector{<:Metal.MtlArray{<:Any, 2}}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case throw(ArgumentError("NextLA.gemm_batched! for a vector of matrices is not supported on Metal; use a 3-D MtlArray")) end @@ -121,6 +127,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:Metal.MtlArray{<:Any, 2}}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case r = NextLA._try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r throw(ArgumentError("NextLA.gemmEx_batched! mixed-type batched GEMM is not supported on Metal")) @@ -137,6 +144,7 @@ function NextLA.gemm_batched!(transA::Char, Cptrs::Metal.MtlArray, Cref::AbstractMatrix, batch_count::Integer) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case throw(ArgumentError("NextLA.gemm_batched! pointer-batched GEMM is not supported on Metal")) end @@ -152,5 +160,9 @@ function NextLA.gemmEx_batched!(transA::Char, Cref::AbstractMatrix, batch_count::Integer; compute_type::Type = NextLA.default_compute_type(alpha, Aref, Bref, beta, Cref)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case throw(ArgumentError("NextLA.gemmEx_batched! pointer-batched mixed-type GEMM is not supported on Metal")) end + +# gemmEx! is refused here: recgemm! keeps wider operands wide, Float16 products go to _half_gemm_widened! (B50). +NextLA._half_gemm_ok(::Metal.MetalBackend) = false diff --git a/ext/metal/potrf.jl b/ext/metal/potrf.jl index e8292603..5688b11f 100644 --- a/ext/metal/potrf.jl +++ b/ext/metal/potrf.jl @@ -1,14 +1,17 @@ function NextLA.potrf_batched!(uplo::Char, A::Metal.MtlArray{<:Any,3}) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them throw(ArgumentError("NextLA.potrf_batched! is not supported on Metal")) end function NextLA.potrf!(uplo::Char, A::Metal.MtlMatrix) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them throw(ArgumentError("NextLA.potrf! is not supported on Metal")) end # Named separately so it is not ambiguous with the generic Float16 method, # which would otherwise make the same promise for an MtlMatrix it cannot keep. function NextLA.potrf!(uplo::Char, A::Metal.MtlMatrix{Float16}) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them throw(ArgumentError("NextLA.potrf! is not supported on Metal")) end diff --git a/ext/metal/syrk.jl b/ext/metal/syrk.jl index aa57cf34..d472eab3 100644 --- a/ext/metal/syrk.jl +++ b/ext/metal/syrk.jl @@ -17,6 +17,7 @@ function NextLA.syrk!(uplo::Char, A::Metal.MtlArray{<:Any, 2}, beta, C::Metal.MtlArray{<:Any, 2}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them NextLA._syrk_dims(uplo, trans, A, C) if _supports_mps_matmul(eltype(A), eltype(A), eltype(C)) return MPS.matmul!( @@ -48,6 +49,8 @@ function NextLA.syrk_batched!(uplo::Char, A::Metal.MtlArray{<:Any, 3}, beta, C::Metal.MtlArray{<:Any, 3}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them + size(C, 3) == 0 && return C # an empty batch: nothing to read (B51) NextLA._syrk_dims(uplo, trans, @view(A[:, :, 1]), @view(C[:, :, 1])) @warn "syrk_batched! falling back to batched gemm!" backend = "Metal" layout = :strided return NextLA.gemm_batched!(trans, trans == 'N' ? 'T' : 'N', alpha, A, A, beta, C) @@ -59,6 +62,7 @@ function NextLA.syrk_batched!(uplo::Char, A::MtlMatrixBatchView, beta, C::MtlMatrixBatchView) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them throw(ArgumentError("Metal batched SYRK does not support 3D MtlArray views; use dense MtlArray batches")) end @@ -68,6 +72,7 @@ function NextLA.syrk_batched!(uplo::Char, A::AbstractVector{<:Metal.MtlArray{<:Any, 2}}, beta, C::AbstractVector{<:Metal.MtlArray{<:Any, 2}}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them length(A) == length(C) || throw(DimensionMismatch("syrk_batched!: matrix batches must have matching lengths")) @warn "syrk_batched! falling back to batched gemm!" backend = "Metal" layout = :pointer isempty(A) || NextLA._syrk_dims(uplo, trans, A[1], C[1]) 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/gemm.jl b/ext/oneapi/gemm.jl index ef95e029..4bbde78b 100644 --- a/ext/oneapi/gemm.jl +++ b/ext/oneapi/gemm.jl @@ -16,6 +16,7 @@ function NextLA.gemm_batched!(transA::Char, B::AbstractVector{<:oneAPI.oneArray{<:Any,2}}, beta, C::AbstractVector{<:oneAPI.oneArray{<:Any,2}}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case NextLA._check_batch_lengths(A, B, C) oneMKL.gemm_batched!(transA, transB, alpha, A, B, beta, C) return C @@ -28,6 +29,7 @@ function NextLA.gemm_batched!(transA::Char, B::oneAPI.oneStridedArray{<:Any,3}, beta, C::oneAPI.oneStridedArray{<:Any,3}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case # Every other backend validates the batch shape before handing it to the # vendor; this one did not, so a mismatched batch reached oneMKL as an # opaque failure instead of a DimensionMismatch naming the sizes. @@ -44,6 +46,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:oneAPI.oneArray{<:Any, 2}}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case r = NextLA._try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r throw(ArgumentError("NextLA.gemmEx_batched! mixed-type batched GEMM is not supported on oneAPI")) @@ -57,6 +60,7 @@ function NextLA.gemmEx_batched!(transA::Char, beta, C::oneAPI.oneStridedArray{<:Any, 3}; compute_type::Type = NextLA.default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case r = NextLA._try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r throw(ArgumentError("NextLA.gemmEx_batched! mixed-type batched GEMM is not supported on oneAPI")) @@ -73,6 +77,7 @@ function NextLA.gemm_batched!(transA::Char, Cptrs::oneAPI.oneArray, Cref::AbstractMatrix, batch_count::Integer) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case throw(ArgumentError("NextLA.gemm_batched! pointer-batched GEMM is not supported on oneAPI")) end @@ -88,5 +93,9 @@ function NextLA.gemmEx_batched!(transA::Char, Cref::AbstractMatrix, batch_count::Integer; compute_type::Type = NextLA.default_compute_type(alpha, Aref, Bref, beta, Cref)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case throw(ArgumentError("NextLA.gemmEx_batched! pointer-batched mixed-type GEMM is not supported on oneAPI")) end + +# gemmEx! is refused here: recgemm! keeps wider operands wide, Float16 products go to _half_gemm_widened! (B50). +NextLA._half_gemm_ok(::oneAPI.oneAPIBackend) = false diff --git a/ext/oneapi/potrf.jl b/ext/oneapi/potrf.jl index 130a9027..8e9a97d6 100644 --- a/ext/oneapi/potrf.jl +++ b/ext/oneapi/potrf.jl @@ -17,5 +17,6 @@ end function NextLA.potrf_batched!(uplo::Char, A::oneAPI.oneStridedArray{T,3}) where {T} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them return _potrf_batched_oneapi!(uplo, A) end diff --git a/ext/oneapi/syrk.jl b/ext/oneapi/syrk.jl index 2409f21a..52347a5d 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 @@ -17,6 +17,7 @@ function _syrk_strided_batched_native!(uplo::Char, C::oneAPI.oneStridedArray{T,3}) where {T} size(A, 3) == size(C, 3) || size(A, 3) == 1 || throw(DimensionMismatch("syrk_batched!: A and C batch sizes are incompatible")) + size(C, 3) == 0 && return C # an empty batch: nothing to read (B51) n, k = NextLA._syrk_dims(uplo, trans, @view(A[:, :, 1]), @view(C[:, :, 1])) lda = max(1, stride(A, 2)) ldc = max(1, stride(C, 2)) @@ -48,6 +49,8 @@ function NextLA.syrk!(uplo::Char, A::oneAPI.oneStridedVecOrMat{<:Any}, beta, C::oneAPI.oneStridedMatrix{<:Any}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them + trans in ('N', 'T', 'C') || throw(ArgumentError("Unsupported transpose flag `$trans`")) # the vendor wrapper reads any other as 'T' oneMKL.syrk!(uplo, trans, alpha, A, beta, C) return C end @@ -58,6 +61,7 @@ function NextLA.syrk_batched!(uplo::Char, A::AbstractVector{<:oneAPI.oneArray{<:Any,2}}, beta, C::AbstractVector{<:oneAPI.oneArray{<:Any,2}}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them @warn "syrk_batched! has no native batched SYRK here; looping syrk!" backend = "oneAPI" layout = :pointer return NextLA._syrk_batched_fallback!(uplo, trans, alpha, A, beta, C) end @@ -68,12 +72,7 @@ function NextLA.syrk_batched!(uplo::Char, A::oneAPI.oneStridedArray{<:Any,3}, beta, C::oneAPI.oneStridedArray{<:Any,3}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them _syrk_strided_batched_native!(uplo, trans, alpha, A, beta, C) return C end - -# recsyrk!'s Float16 updates (src/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) = - NextLA.gemm!('N', 'T', alpha, A, B, beta, C) diff --git a/handout.png b/handout.png deleted file mode 100644 index 058ae431..00000000 Binary files a/handout.png and /dev/null differ diff --git a/src/NextLA.jl b/src/NextLA.jl index cfb8c0e6..cfc1b5c3 100644 --- a/src/NextLA.jl +++ b/src/NextLA.jl @@ -9,12 +9,12 @@ import LinearAlgebra: BLAS, LAPACK import LinearAlgebra.BLAS: @blasfunc using Random: Random using KernelAbstractions -# @unroll: chol_kernel_register! unrolls over its register strip. TLRmodule -# imports it separately, being its own module. +# @unroll: chol_kernel_register! unrolls over its register strip. using KernelAbstractions.Extras: @unroll -# Core.BFloat16 exists from Julia 1.11; before that, no type (Union{}). -const _BFloat16 = isdefined(Core, :BFloat16) ? Core.BFloat16 : Union{} +# BFloat16s.jl's BFloat16: Core.BFloat16 with its conversions and arithmetic from Julia +# 1.11, and a software BFloat16 before that, so one working type on every version. +using BFloat16s: BFloat16 """ lamch(::Type{T}, cmach) where{T<: Number} @@ -32,6 +32,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) @@ -58,42 +67,23 @@ function lamch(::Type{T}, cmach) where {T <: Number} end end -# Backend capability traits. First, because both the GEMM machinery and TLR -# read them, and the vendor extensions add methods to them. -include("backend_traits.jl") -include("recursion.jl") -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") +@inline SUBGROUP_SIZE(::Type{<:KernelAbstractions.CPU}) = Val(1) +@inline unwrap(::Val{x}) where {x} = x +@inline supports_pointer_batched(backend) = supports_pointer_batched(typeof(backend)) +@inline supports_pointer_batched(::Type) = false + +@inline _rec_split(n::Integer) = ispow2(n) ? n ÷ 2 : prevpow(2, n) -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("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") end diff --git a/src/backend_traits.jl b/src/backend_traits.jl deleted file mode 100644 index 7cef86c6..00000000 --- a/src/backend_traits.jl +++ /dev/null @@ -1,14 +0,0 @@ -# Backend capability traits, taken verbatim from alecarraro-dev @ 0f1ac84, -# where they sat inline in src/NextLA.jl. -# -# They are module-level rather than a feature's: every method is added by a -# vendor extension in ext/*/common.jl, and every caller is somewhere else -# again. SUBGROUP_SIZE and unwrap are read by TLR's norm reduction -# (TLR/compression/norms.jl), supports_pointer_batched by TLR's compressed -# accumulation (TLR/gemm/compressed_accumulation/run_coupling.jl). Nothing -# under src/gemm/ uses any of them, so that is not where they belong. - -@inline SUBGROUP_SIZE(::Type{<:KernelAbstractions.CPU}) = Val(1) -@inline unwrap(::Val{x}) where {x} = x -@inline supports_pointer_batched(backend) = supports_pointer_batched(typeof(backend)) -@inline supports_pointer_batched(::Type) = false diff --git a/src/axpy.jl b/src/dense/blas/axpy.jl similarity index 84% rename from src/axpy.jl rename to src/dense/blas/axpy.jl index 02a465a2..5a3e652e 100644 --- a/src/axpy.jl +++ b/src/dense/blas/axpy.jl @@ -2,13 +2,14 @@ function axpy!(a::T, x::AbstractVector{T}, y::AbstractVector{T}) where {T} n = length(x) if n <= 0 - return + return y end if abs(real(a)) + abs(imag(a)) == zero(eltype(x)) - return + return y end # Broadcast is GPU-agnostic (no scalar indexing) y .= y .+ a .* x + return y end \ No newline at end of file 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 72% rename from src/gemm/gemmEx.jl rename to src/dense/blas/gemm/gemmEx.jl index bea0056a..7fe8f853 100644 --- a/src/gemm/gemmEx.jl +++ b/src/dense/blas/gemm/gemmEx.jl @@ -4,8 +4,10 @@ export gemmEx! """ gemm(A, B; kwargs...) -Allocation-returning matrix product. Structured matrix formats specialize this -generic when the result's storage layout depends on ranks discovered at runtime. +Generic function for an allocating matrix product, for structured matrix types +whose result layout depends on ranks found at runtime. It has no dense method: +`gemm(A, B)` on plain matrices throws a `MethodError`. Use [`gemm!`](@ref) for +dense matrices. """ function gemm end @@ -15,8 +17,21 @@ function gemm end 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. +products. Dense matrix products forward to `LinearAlgebra.mul!`, except Float16 +on the CPU and CUDA, which goes to `gemmEx!` so that it sums in Float32; 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 @@ -25,6 +40,14 @@ gemm!(C::AbstractMatrix, A::AbstractMatrix, B::AbstractMatrix; alpha::Number=tru function gemm!(C::AbstractMatrix, A::AbstractMatrix, B::AbstractMatrix, alpha::Number, beta::Number) + # Float16 on the CPU sums in Float32 (gemmEx!), as in the rest of the library: mul! sums Float16 in + # Float16, so 16 terms of 40000 and 16 of -40000 gave Inf instead of 0. The CUDA method does the same. + # Only strided arrays: gemmEx! reads strides, so other matrices (triangular, sparse, index views) keep mul!. + if eltype(C) == eltype(A) == eltype(B) == Float16 && C isa StridedMatrix && get_backend(C) isa KernelAbstractions.CPU + (tA, Ap), (tB, Bp) = _gemm_flag(A), _gemm_flag(B) + Ap isa StridedMatrix && Bp isa StridedMatrix && + return gemmEx!(tA, tB, alpha, Ap, Bp, beta, C; compute_type=Float32) + end return LinearAlgebra.mul!(C, A, B, alpha, beta) end @@ -32,20 +55,29 @@ end gemm!(transA, transB, alpha, A, B, beta, C) -> C The BLAS argument order: `C := alpha * op(A) * op(B) + beta * C`, where `op` is -the identity, `transpose` or `adjoint` for `'N'`, `'T'` or `'C'`. +the identity, `transpose` or `adjoint` for `'N'`, `'T'` or `'C'`. The flags +are accepted in either case. + +It forwards to the output-first method, so it runs on every backend and +reaches cuBLAS/rocBLAS (through `mul!`, or `gemmEx!` for Float16) on GPU arrays. + +# Examples +```jldoctest +julia> A = rand(1024, 1024); B = rand(1024, 1024); C = zeros(1024, 1024); -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. +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) return gemm!(C, _gemm_op(transA, A), _gemm_op(transB, B), alpha, beta) end -@inline _gemm_op(t::Char, X) = - t == 'N' ? X : t == 'T' ? transpose(X) : t == 'C' ? adjoint(X) : +@inline _gemm_op(t::Char, X) = # either case, as BLAS + uppercase(t) == 'N' ? X : uppercase(t) == 'T' ? transpose(X) : uppercase(t) == 'C' ? adjoint(X) : throw(ArgumentError("trans must be 'N', 'T' or 'C', got '$t'")) @inline function _gemm_dims(transA::Char, @@ -66,8 +98,7 @@ end end # op(A) as a lazy wrapper. 'C' is the adjoint and differs from 'T' only for -# complex operands, but the two must not be collapsed: TLR passes -# adjoint_blas_char(T), which is 'C' precisely when that difference matters. +# complex operands, so the two must not be collapsed. @inline _op(A::AbstractMatrix, t::Char) = t == 'N' ? A : (t == 'C' ? adjoint(A) : transpose(A)) @@ -96,6 +127,8 @@ unqualified (it is exported) and as `NextLA.gemmEx!`. - `'T'`: transpose - `'C'`: adjoint +The flags are accepted in either case. + ## Notes - The accumulation type can be selected explicitly with `compute_type`; by default [`default_compute_type`](@ref) chooses it from the storage types of @@ -107,6 +140,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, @@ -116,6 +161,7 @@ function gemmEx!(transA::Char, beta, C::AbstractMatrix; compute_type::Type = default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case _check_compute_type(compute_type) get_backend(C) isa KernelAbstractions.CPU || throw(ArgumentError("NextLA.gemmEx! has no method for $(typeof(get_backend(C)))")) diff --git a/src/gemm/gemm_batched.jl b/src/dense/blas/gemm/gemm_batched.jl similarity index 91% rename from src/gemm/gemm_batched.jl rename to src/dense/blas/gemm/gemm_batched.jl index 88f00973..1f16afb5 100644 --- a/src/gemm/gemm_batched.jl +++ b/src/dense/blas/gemm/gemm_batched.jl @@ -98,9 +98,21 @@ Each batch entry applies where `op(A)` and `op(B)` are determined by `transA` and `transB`. ## Notes -- On the CPU, `gemm_batched!` falls back to a loop of standard GEMMs. +- On the CPU, `gemm_batched!` falls back to a loop of standard GEMMs. Each + member must be same-type `Float32`, `Float64`, `ComplexF32` or `ComplexF64`; + any other member throws `ArgumentError`. - 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, @@ -109,6 +121,7 @@ function gemm_batched!(transA::Char, B::AbstractArray{<:Any, 3}, beta, C::AbstractArray{<:Any, 3}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case batchA, batchB, batchC = _check_batch_dims(A, B, C) for i in 1:batchC @@ -131,6 +144,7 @@ function gemm_batched!(transA::Char, Cptrs, Cref::AbstractMatrix, batch_count::Integer) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return gemm_batched_ptrs!( transA, transB, alpha, Aptrs, Aref, Bptrs, Bref, beta, Cptrs, Cref, batch_count, ) @@ -154,6 +168,7 @@ function gemm_batched_ptrs!(transA::Char, Cptrs, Cref::AbstractMatrix, batch_count::Integer) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case throw(ArgumentError("NextLA.gemm_batched_ptrs! is supported only on CUDA and AMDGPU")) end @@ -177,6 +192,7 @@ function gemmEx_batched_ptrs!(transA::Char, Cref::AbstractMatrix, batch_count::Integer; compute_type::Type = default_compute_type(alpha, Aref, Bref, beta, Cref)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case _check_compute_type(compute_type) throw(ArgumentError("NextLA.gemmEx_batched_ptrs! is supported only on CUDA and AMDGPU")) end @@ -188,6 +204,7 @@ function gemm_batched!(transA::Char, B::AbstractVector{<:AbstractArray{<:Any, 2}}, beta, C::AbstractVector{<:AbstractArray{<:Any, 2}}) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case _check_batch_lengths(A, B, C) for i in eachindex(A, B, C) _batched_member!(transA, transB, alpha, A[i], B[i], beta, C[i]) @@ -212,8 +229,8 @@ exported surface. ## Notes - The accumulation type can be selected explicitly with `compute_type`; by - default it is inferred from `alpha`, `beta`, and the operand/result element - types using [`default_compute_type`](@ref). + default [`default_compute_type`](@ref) infers it from the element types of + `A`, `B` and `C` only. `alpha` and `beta` take no part. - Same-type batched calls may fall back to `gemm_batched!` on backends that do not expose a mixed-type batched GEMM primitive. - Mixed-type batched GEMM is currently implemented for CUDA and AMDGPU. @@ -221,6 +238,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, @@ -230,6 +259,7 @@ function gemmEx_batched!(transA::Char, beta, C::AbstractArray{<:Any, 3}; compute_type::Type = default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case _check_compute_type(compute_type) r = _try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r @@ -244,6 +274,7 @@ function gemmEx_batched!(transA::Char, beta, C::AbstractVector{<:AbstractArray{<:Any, 2}}; compute_type::Type = default_compute_type(alpha, A, B, beta, C)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case _check_compute_type(compute_type) r = _try_same_type_batched!(transA, transB, alpha, A, B, beta, C, compute_type) r === nothing || return r @@ -262,6 +293,7 @@ function gemmEx_batched!(transA::Char, Cref::AbstractMatrix, batch_count::Integer; compute_type::Type = default_compute_type(alpha, Aref, Bref, beta, Cref)) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case return gemmEx_batched_ptrs!( transA, transB, alpha, Aptrs, Aref, Bptrs, Bref, beta, Cptrs, Cref, batch_count; compute_type, @@ -284,7 +316,7 @@ end export BatchPtrDescriptor, swap_batch_ptrs!, set_batch_ptrs! """ - BatchPtrDescriptor(ptrs) + BatchPtrDescriptor(ptrs, host) BatchPtrDescriptor(batch::AbstractVector{<:AbstractMatrix}) A device array of matrix base pointers built once and reused across many 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..225fdd2a 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 (one call over a batch of differently sized products). + +# 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 84% rename from src/gemm/gemm_precision.jl rename to src/dense/blas/gemm/gemm_precision.jl index 24ceb53e..312dbbaa 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 @@ -31,12 +43,10 @@ Float32 compute type, and native Float32/Float64. T === Float16 && return TA === TB === TC === Float16 T === Float32 && return (TA === TB === Float16 && TC in (Float16, Float32)) || # BFloat16 into Float32 was missing while the - # identical Float16 case above was allowed. Both - # vendors do it, and TLR's own precision check reads - # this table, so the omission refused a BFloat16 TLR - # GEMM writing into a Float32 destination. - (TA === TB === _BFloat16 && - TC in (_BFloat16, Float32)) || + # identical Float16 case above was allowed; both + # vendors do it. + (TA === TB === BFloat16 && + TC in (BFloat16, Float32)) || (TA === TB === TC === Float32) T === Float64 && return TA === TB === TC === Float64 # Int8 into Int32 is in the gemm_types.jl table and was in no backend's @@ -101,9 +111,20 @@ 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) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case isempty(C) && return C backend = _batch_backend(C) validate_gemm_signature( @@ -137,6 +158,7 @@ function precision_gemm_batched_ptrs!(transA, transB, alpha, Cd::BatchPtrDescriptor, Cref::AbstractMatrix, batch_count::Integer, mode::AbstractGEMMComputeMode) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case batch_count <= 0 && return Cd backend = get_backend(Cref) validate_gemm_signature(backend, eltype(Aref), eltype(Bref), eltype(Cref), mode) @@ -146,9 +168,21 @@ 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) + transA, transB = uppercase(transA), uppercase(transB) # BLAS takes either case backend = get_backend(C) validate_gemm_signature(backend, eltype(A), eltype(B), eltype(C), mode) return _gemm_compute!(mode, transA, transB, alpha, A, B, beta, C) diff --git a/src/gemm/gemm_types.jl b/src/dense/blas/gemm/gemm_types.jl similarity index 78% rename from src/gemm/gemm_types.jl rename to src/dense/blas/gemm/gemm_types.jl index af946971..c9c6e26a 100644 --- a/src/gemm/gemm_types.jl +++ b/src/dense/blas/gemm/gemm_types.jl @@ -13,9 +13,8 @@ other fast-math settings. `NextLA` separates its primary BLAS surface from the advanced `Ex` interfaces: -1. Ordinary dense GEMM is intentionally left to the backend itself, e.g. - `C = A * B` for dense matrices. -2. `gemm_batched!` provides the batched GEMM surface used by TLR algorithms. +1. Ordinary dense GEMM is `gemm!`, which forwards to `mul!` (Float16 on the CPU and CUDA to `gemmEx!`, for Float32 sums). +2. `gemm_batched!` provides the batched GEMM surface, for many independent products. 3. `NextLA.gemmEx!` and `NextLA.gemmEx_batched!` are advanced APIs for mixed-type GEMM where the result storage may differ from the operand storage. @@ -77,7 +76,6 @@ not run on a device. TF32 is reached through `precision_gemm!` and its batched siblings with the `TF32()` mode rather than a `compute_type`, and only CUDA implements it. -these APIs for now. """ const GEMM_COMPUTE_TYPES = ( Float16, @@ -113,6 +111,26 @@ const NATIVE_GEMM_TYPES = Union{Float16, Float32, Float64, ComplexF32, ComplexF6 return Float32 end +# TF32 for Float32 GEMMs, scoped to one task: inside _with_tf32, a backend's Float32 x Float32 GEMM with a +# Float32 sum may use TF32 tensor cores (CUDA: CUBLAS_COMPUTE_32F_FAST_TF32: inputs rounded to a 10-bit +# fraction, Float32 sum). Only routines whose error is already set by Float16 storage open the scope (the +# mixed-precision LU); child tasks start without it, so the LU and the recgemm! inside it reopen it in theirs. +# Outside it nothing changes. +_tf32_on() = get(task_local_storage(), :nextla_tf32, false)::Bool +_with_tf32(f, on::Bool=true) = (!on || _tf32_on()) ? f() : task_local_storage(f, :nextla_tf32, true) + +# Whether a Float16 x Float16 product written into this Float16 array sums in Float32 (gemmEx! with +# compute_type = Float32, or _half_gemm_widened! on Metal and oneAPI). A backend that returns false keeps the +# mixed-precision update's Float32 copy; none does since oneAPI's products went to _half_gemm_widened! (B50). +_inplace_half_ok(::KernelAbstractions.Backend) = true +_inplace_half_ok(A::AbstractArray) = _inplace_half_ok(get_backend(A)) # by backend, so views count too + +# Whether gemmEx! takes a Float16 x Float16 product into this array's backend. Metal and oneAPI refuse gemmEx! +# (their extensions return false for their backends), so recgemm! does not round wider operands to Float16 +# there (_recgemm_round), and the dense Float16 products go to _half_gemm_widened! (B50). +_half_gemm_ok(::KernelAbstractions.Backend) = true +_half_gemm_ok(A::AbstractArray) = _half_gemm_ok(get_backend(A)) # by backend: C is often a view (recsyrk!, rectrxm) + @inline function _check_compute_type(compute_type::Type) compute_type in GEMM_COMPUTE_TYPES || throw(ArgumentError("unsupported GEMM compute_type `$compute_type`; supported compute types are $(join(string.(GEMM_COMPUTE_TYPES), ", "))")) @@ -136,6 +154,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 +190,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 +211,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 +237,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 89% rename from src/gemm/matmul.jl rename to src/dense/blas/gemm/matmul.jl index df0fedcd..e63c87ae 100644 --- a/src/gemm/matmul.jl +++ b/src/dense/blas/gemm/matmul.jl @@ -121,9 +121,22 @@ end """ GEMM_ADD!(A, B, C, scale=1) -> C -`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`. +`C .+= scale * A * B`. `A` or `B` may be a `Transpose` or an `Adjoint`. When `A`, +`B` and `C` are all `Float16`, the sum is kept in `Float32`; a result beyond +`floatmax(Float16)` is stored as `Inf`. Otherwise it is kept in `eltype(C)`. 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 +148,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 63% rename from src/gemm/recgemm.jl rename to src/dense/blas/gemm/recgemm.jl index b9fa4d57..f4b6b574 100644 --- a/src/gemm/recgemm.jl +++ b/src/dense/blas/gemm/recgemm.jl @@ -22,6 +22,21 @@ export recgemm! # per feature, and that method arrives with it. This file is the dense half and # depends on nothing above it. +# A transposed (for a real type, also an adjoint) operand as a BLAS flag on its parent. +_gemm_flag(X::Union{Transpose{<:Real}, Adjoint{<:Real}}) = ('T', parent(X)) +_gemm_flag(X::AbstractMatrix) = ('N', X) + +# Metal and oneAPI refuse gemmEx! (B50). There a Float16 x Float16 product is formed in Float32 instead: the +# operands widened (exact), one Float32 gemm!, C rounded once on store -- the sums gemmEx! gives elsewhere. +function _half_gemm_widened!(tA::Char, tB::Char, alpha, A, B, beta, C) + # alpha = 0 reads neither A nor B (an Inf there would give 0 * Inf = NaN), as gemmEx! on the CPU + iszero(alpha) && return iszero(beta) ? fill!(C, zero(eltype(C))) : (C .= Float32(beta) .* C) + W = eltype(C) === Float32 ? C : iszero(beta) ? similar(C, Float32) : Float32.(C) + gemm!(tA, tB, Float32(alpha), Float32.(A), Float32.(B), Float32(beta), W) + W === C || (C .= W) + return C +end + # The compute type is stated rather than inferred. Inferred from the storage, # a Float16 triple would accumulate in Float16. # Float32 is the accumulation _tensor_core_gemm_supported blesses for Float16 @@ -37,7 +52,11 @@ function _gemm_dispatch!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::A if TA == TB == TC && TC in (Float32, Float64, ComplexF32, ComplexF64) gemm!(C, A, B, TC(alpha), TC(beta)) elseif TA == Float16 && TB == Float16 && TC in (Float16, Float32) - gemmEx!('N', 'N', alpha, A, B, beta, C; compute_type=Float32) + _half_gemm_ok(C) || return _half_gemm_widened!('N', 'N', alpha, A, B, beta, C) # Metal, oneAPI (B50) + # A transposed operand goes to gemmEx! as a 'T' flag on its parent: the vendor methods take plain arrays + # only (B48: a transposed Float16 CuArray block had no CUDA method), and cuBLAS and rocBLAS transpose natively. + (tA, A), (tB, B) = _gemm_flag(A), _gemm_flag(B) + gemmEx!(tA, tB, alpha, A, B, beta, C; compute_type=Float32) else # Converting the operands to the destination type first throws away # precision the destination never needed to lose: Float32 operands into @@ -65,12 +84,31 @@ function _gemm_dispatch!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::A end # Accumulate in at least Float32: BFloat16 and Float8 carry too few # bits to hold a running sum, as Float16 does. + _half_gemm_ok(C) || return _half_gemm_widened!('N', 'N', alpha, A, B, beta, C) # Metal, oneAPI (B50) gemmEx!('N', 'N', alpha, A, B, beta, C; compute_type=promote_type(W, Float32)) end end end +""" + recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::AbstractMatrix) -> C + +Compute `C := alpha * A * B + beta * C` in place, for dense matrices. This +method does not recurse: it makes one GEMM call, chosen by element type. + +- Same-type `Float32`, `Float64`, `ComplexF32` or `ComplexF64`: [`gemm!`](@ref). +- `Float16` `A` and `B` into a `Float16` or `Float32` `C`: [`gemmEx!`](@ref) + with a `Float32` sum. On Metal and oneAPI, which have no `gemmEx!`, the same + sum comes from one `Float32` [`gemm!`](@ref) on widened copies. +- Other mixes: when `C` is at least as wide as `A` and `B`, the operands are + widened to `eltype(C)` and passed to `gemm!`. Otherwise `gemmEx!` sums in at + least `Float32` and rounds once on store. On a GPU, when `C` is narrower + than `A` and `B`, they are first rounded to `eltype(C)`. + +No transpose is applied. Sizes that do not fit throw `DimensionMismatch`. The +method for a mixed-precision `C` is documented separately. +""" function recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::AbstractMatrix) _gemm_dispatch!(alpha, A, B, beta, C) end diff --git a/src/gerc.jl b/src/dense/blas/gerc.jl similarity index 62% rename from src/gerc.jl rename to src/dense/blas/gerc.jl index c0aa1a3d..77d805a5 100644 --- a/src/gerc.jl +++ b/src/dense/blas/gerc.jl @@ -17,29 +17,24 @@ conjugate of y is used in the outer product. - `A`: m×n matrix to be updated in-place # Algorithm -The algorithm efficiently computes the outer product by: -1. For each column j, compute temp = alpha * conj(y[j]) -2. If temp ≠ 0, update column j: A[:,j] += temp * x -3. Skip columns where y[j] = 0 to avoid unnecessary computation +The update is one broadcast, so it runs on GPU arrays. It returns early when +`alpha == 0` or `A` is empty. # Input Validation -- Matrix A must have non-negative dimensions -- Vectors x and y must have lengths matching A dimensions -- All inputs must have compatible numeric types +- The lengths of `x` and `y` must match the rows and columns of `A`; otherwise + it throws `ArgumentError`. +- `alpha`, `x`, `y` and `A` must share one element type. -# Performance Notes -- Optimized for cache efficiency by operating column-wise -- Skips zero elements in y to minimize operations -- In-place operation minimizes memory allocation +# Examples +```jldoctest +julia> x = rand(ComplexF64, 1024); y = rand(ComplexF64, 1024); -# 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 +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} @@ -56,7 +51,7 @@ function gerc!(alpha::T, x::AbstractVector{T}, y::AbstractVector{T}, A::Abstract # Early return for degenerate cases if m == 0 || n == 0 || alpha == zero(T) - return + return A end # Rank-1 update: A := A + alpha * x * y^H (GPU-agnostic: broadcast instead of scalar indexing) diff --git a/src/syrk/recsyrk.jl b/src/dense/blas/syrk/recsyrk.jl similarity index 72% rename from src/syrk/recsyrk.jl rename to src/dense/blas/syrk/recsyrk.jl index 50a5a572..b9f533d1 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. @@ -49,7 +49,8 @@ function _syrk_half_tri!(uplo::Char, alpha, A, beta, C) end _syrk_half_gemm!(alpha, A, B, beta, C) = - gemmEx!('N', 'T', alpha, A, B, beta, C; compute_type=Float32) + _half_gemm_ok(C) ? gemmEx!('N', 'T', alpha, A, B, beta, C; compute_type=Float32) : + _half_gemm_widened!('N', 'T', alpha, A, B, beta, C) # Metal, oneAPI (B50) function _syrk_dispatch!( op::Symbol, @@ -64,30 +65,15 @@ function _syrk_dispatch!( syrk!(uplo, 'N', TC(alpha), A, TC(beta), C) elseif TA == Float16 && TC in (Float16, Float32) _syrk_half_tri!(uplo, alpha, A, beta, C) - elseif TC in (Float32, Float64, ComplexF32, ComplexF64) - # A and C differ in type: compute in C's type, as the branch's - # recsyrk_dev.jl does. A wider C takes A widened exactly, a - # narrower one takes A rounded once; C itself is never rounded. - # The Float32 fallback below used to take these, rounding a - # Float64 C to Float32 and throwing on mismatched complex types. - syrk!(uplo, 'N', TC(alpha), TC.(A), TC(beta), C) else - compute_type = Float32 - - C_temp = (TC == compute_type) ? C : compute_type.(C) - - if TA == Float32 - syrk!(uplo, 'N', compute_type(alpha), A, compute_type(beta), C_temp) - elseif TA == Float16 - _syrk_half_tri!(uplo, alpha, A, beta, C_temp) - else - A_temp = compute_type.(A) - syrk!(uplo, 'N', compute_type(alpha), A_temp, compute_type(beta), C_temp) - end - - if C !== C_temp - copy!(C, C_temp) - end + # A and C differ in type: compute in the wider of the two (at least Float32), as the other branches + # (#2's recsyrk.jl, #4/#7's ext/cuda/syrk.jl; user, 2026-12-03). Widening is exact, so only the result + # is rounded, once, on the copy back; the other triangle of C goes out and back unchanged. + W = promote_type(Float32, TA, TC) + A_W = TA == W ? A : W.(A) + C_W = TC == W ? C : W.(C) + syrk!(uplo, 'N', W(alpha), A_W, W(beta), C_W) + C_W === C || copyto!(C, C_W) end elseif op === :GEMM @@ -97,13 +83,13 @@ function _syrk_dispatch!( elseif TA == Float16 && TB == Float16 && TC in (Float16, Float32) _syrk_half_gemm!(alpha, A, B, beta, C) else - A_final = (TA == TC) ? A : TC.(A) - B_final = (TB == TC) ? B : TC.(B) - if TC in (Float32, Float64, ComplexF32, ComplexF64) - gemm!('N', 'T', TC(alpha), A_final, B_final, TC(beta), C) - else - _syrk_half_gemm!(alpha, A_final, B_final, beta, C) - end + # Mixed types: a GEMM in the widest of them (at least Float32), C rounded once on the copy back, as #7. + W = promote_type(Float32, TA, TB, TC) + A_W = TA == W ? A : W.(A) + B_W = TB == W ? B : W.(B) + C_W = TC == W ? C : W.(C) + gemm!('N', 'T', W(alpha), A_W, B_W, W(beta), C_W) + C_W === C || copyto!(C, C_W) end end end @@ -142,8 +128,8 @@ function _recsyrk_impl!( if parallel @sync begin - Threads.@spawn _recsyrk_impl!(alpha, A1, beta, C11, threshold, uplo, parallel=false) - Threads.@spawn _recsyrk_impl!(alpha, A2, beta, C22, threshold, uplo, parallel=false) + @async _recsyrk_impl!(alpha, A1, beta, C11, threshold, uplo, parallel=false) + @async _recsyrk_impl!(alpha, A2, beta, C22, threshold, uplo, parallel=false) end else _recsyrk_impl!(alpha, A1, beta, C11, threshold, uplo, parallel=false) @@ -160,13 +146,29 @@ 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; uplo::Char='L' ) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U', got '$uplo'")) - # Spawn when the first half has the work, the rule the mixed-precision SYRK uses. - should_parallelize = _rec_split(size(C, 1)) > RECSYRK_PARALLEL_THRESHOLD + isempty(C) && (size(A, 1) == size(C, 1) == size(C, 2) || + throw(DimensionMismatch("recsyrk!: A has $(size(A, 1)) rows, C is $(size(C, 1))×$(size(C, 2))")); return C) # n = 0: nothing to update + # Spawn when C has more than RECSYRK_PARALLEL_THRESHOLD rows, as vicki-development's recsyrk! does. + should_parallelize = size(C, 1) > RECSYRK_PARALLEL_THRESHOLD _recsyrk_impl!(alpha, A, beta, C, threshold, uplo, parallel=should_parallelize) + return C end 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 73% rename from src/syrk/syrk_batched.jl rename to src/dense/blas/syrk/syrk_batched.jl index 808098bf..2b5d77d4 100644 --- a/src/syrk/syrk_batched.jl +++ b/src/dense/blas/syrk/syrk_batched.jl @@ -9,7 +9,7 @@ Two storage forms are supported: Each batch entry applies -`C[i] := alpha * op(A[i]) * op(A[i])' + beta * C[i]` +`C[i] := alpha * op(A[i]) * transpose(op(A[i])) + beta * C[i]` where `op(A)` is determined by `trans`. @@ -19,8 +19,26 @@ exported surface. ## Notes - If a backend does not provide a native batched SYRK kernel, `syrk_batched!` 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. + exception: both its strided and its vector paths go through + [`gemm_batched!`](@ref) instead. On Metal that takes only the 3-D form, so + the vector form throws `ArgumentError`. - 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, @@ -28,6 +46,7 @@ function syrk_batched!(uplo::Char, A::AbstractArray{<:Any, 3}, beta, C::AbstractArray{<:Any, 3}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them size(A, 3) == size(C, 3) || size(A, 3) == 1 || throw(DimensionMismatch("syrk_batched!: A and C batch sizes are incompatible")) @warn "syrk_batched! has no native batched SYRK here; looping syrk!" backend=string(typeof(A)) layout=:strided @@ -58,6 +77,7 @@ function syrk_batched!(uplo::Char, A::AbstractVector{<:AbstractMatrix}, beta, C::AbstractVector{<:AbstractMatrix}) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them length(A) == length(C) || throw(DimensionMismatch("syrk_batched!: matrix batches must have matching lengths")) @warn "syrk_batched! has no native batched SYRK here; looping syrk!" backend=string(typeof(A)) layout=:pointer return _syrk_batched_fallback!(uplo, trans, alpha, A, beta, C) diff --git a/src/syrk/syrk_dispatch.jl b/src/dense/blas/syrk/syrk_dispatch.jl similarity index 62% rename from src/syrk/syrk_dispatch.jl rename to src/dense/blas/syrk/syrk_dispatch.jl index 250c6be0..dd8a56e5 100644 --- a/src/syrk/syrk_dispatch.jl +++ b/src/dense/blas/syrk/syrk_dispatch.jl @@ -1,6 +1,8 @@ export syrk! @inline function _syrk_dims(uplo::Char, trans::Char, A::AbstractMatrix, C::AbstractMatrix) + # Checked first: any flag but 'N' would otherwise be read as a transpose. + trans in ('N', 'T', 'C') || throw(ArgumentError("Unsupported transpose flag `$trans`")) n = size(A, trans == 'N' ? 1 : 2) k = size(A, trans == 'N' ? 2 : 1) size(C, 1) == size(C, 2) || throw(DimensionMismatch("syrk!: C must be square")) @@ -14,9 +16,10 @@ end Perform a symmetric rank-k update and store the result in `C`: -`C := alpha * op(A) * op(A)' + beta * C` +`C := alpha * op(A) * transpose(op(A)) + beta * C` -where `op(A)` is determined by `trans`. +where `op(A)` is determined by `trans`. SYRK uses a transpose, not an adjoint, +also for complex `A`. `uplo` selects which triangle of `C` is updated: - `'U'`: upper triangle @@ -25,11 +28,23 @@ where `op(A)` is determined by `trans`. `trans` may be: - `'N'`: no transpose - `'T'`: transpose -- `'C'`: adjoint +- `'C'`: for real types only, where it means `'T'` ## 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, @@ -37,6 +52,7 @@ function syrk!(uplo::Char, A::AbstractMatrix, beta, C::AbstractMatrix) + uplo, trans = uppercase(uplo), uppercase(trans) # flags in either case, as BLAS and LAPACK take them _syrk_dims(uplo, trans, A, C) return BLAS.syrk!(uplo, trans, eltype(C)(alpha), A, eltype(C)(beta), C) end diff --git a/src/syrk/syrk_kernel.jl b/src/dense/blas/syrk/syrk_kernel.jl similarity index 80% rename from src/syrk/syrk_kernel.jl rename to src/dense/blas/syrk/syrk_kernel.jl index 50713068..845be768 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. @@ -45,12 +45,14 @@ export SYRK_KERNEL! i, j = @index(Local, NTuple) TILE_DIM = @uniform @groupsize()[1] + # Float16 is summed in Float32 and rounded once on store, as the matmul kernel does. + TAcc = @uniform eltype(C) === Float16 ? Float32 : eltype(C) - tile1 = @localmem eltype(C) (TILE_DIM + BANK, TILE_DIM) - tile2 = @localmem eltype(C) (TILE_DIM + BANK, TILE_DIM) + tile1 = @localmem TAcc (TILE_DIM + BANK, TILE_DIM) + tile2 = @localmem TAcc (TILE_DIM + BANK, TILE_DIM) - outval = @private eltype(C) 1 - @inbounds outval[1] = zero(eltype(C)) + outval = @private TAcc 1 + @inbounds outval[1] = zero(TAcc) @uniform NUM_TILES = ceil(Int, M / TILE_DIM) @@ -62,14 +64,14 @@ export SYRK_KERNEL! if I <= N && K <= M @inbounds tile1[i, j] = (trans == 'N' || trans == 'n') ? A[I, K] : A[K, I] else - @inbounds tile1[i, j] = zero(eltype(C)) + @inbounds tile1[i, j] = zero(TAcc) end K = t * TILE_DIM + i if K <= M && J <= N @inbounds tile2[i, j] = (trans == 'N' || trans == 'n') ? A[J, K] : A[K, J] else - @inbounds tile2[i, j] = zero(eltype(C)) + @inbounds tile2[i, j] = zero(TAcc) end @synchronize @@ -77,7 +79,7 @@ export SYRK_KERNEL! I = (gi - 1) * TILE_DIM + i J = (gj - 1) * TILE_DIM + j if I <= N && J <= N - tmp = zero(eltype(C)) + tmp = zero(TAcc) @simd for k in 1:TILE_DIM @inbounds tmp += tile1[i, k] * tile2[k, j] end @@ -91,18 +93,22 @@ export SYRK_KERNEL! J = (gj - 1) * TILE_DIM + j in_triangle = (uplo == 'L' || uplo == 'l') ? I >= J : I <= J if I <= N && J <= N && in_triangle - @inbounds C[I, J] = alpha * outval[1] + beta * C[I, J] + # beta = 0 never reads C (it may hold NaN), as BLAS; a Float16 C is widened so the sum rounds once. + c = iszero(beta) ? zero(TAcc) : TAcc(@inbounds C[I, J]) + @inbounds C[I, J] = alpha * outval[1] + beta * c end end """ SYRK_KERNEL!(uplo, trans, alpha, A, beta, C) -Symmetric rank-k update `C := alpha * op(A) * op(A)' + beta * C`, computed with +Symmetric rank-k update `C := alpha * op(A) * transpose(op(A)) + beta * C`, computed with KernelAbstractions rather than a vendor BLAS. Only the `uplo` triangle of `C` is written; the other is left exactly as it -was. `trans` selects `op(A) = A` (`'N'`) or `op(A) = Aᵀ` (`'T'`). +was. `trans` selects `op(A) = A` (`'N'`) or `op(A) = Aᵀ` (`'T'`). The flags +are accepted in either case. `beta = 0` does not read `C`, and Float16 is +summed in Float32 and rounded once. Unlike [`syrk!`](@ref) this needs no backend library, so it is the path to use on a backend with no native SYRK, or for an element type the vendor does not diff --git a/src/trsm/rectrxm.jl b/src/dense/blas/trsm/rectrxm.jl similarity index 62% rename from src/trsm/rectrxm.jl rename to src/dense/blas/trsm/rectrxm.jl index a8fca0bb..d8f53b2e 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,48 @@ 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 + +# The flags in upper case, checked: BLAS reads flag letters regardless of case (Reference BLAS LSAME). +function _trxm_flags(side::Char, uplo::Char, trans::Char, diag::Char, func::Char) + side, uplo, trans, diag, func = uppercase(side), uppercase(uplo), uppercase(trans), uppercase(diag), uppercase(func) + side in ('L', 'R') || throw(ArgumentError("side must be 'L' or 'R', got '$side'")) + uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U', got '$uplo'")) + trans in ('N', 'T', 'C') || throw(ArgumentError("trans must be 'N', 'T' or 'C', got '$trans'")) + diag in ('N', 'U') || throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) + func in ('S', 'M') || throw(ArgumentError("func must be 'S' or 'M', got '$func'")) + return side, uplo, trans, diag, func 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,66 +93,45 @@ unaffected. function unified_rectrxm!( side::Char, uplo::Char, - transpose::Char, + trans::Char, diag::Char, alpha::Number, func::Char, A::AbstractMatrix, B::AbstractMatrix ) - if diag != 'N' && diag != 'U' - throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) - end + side, uplo, trans, diag, func = _trxm_flags(side, uplo, trans, diag, func) unitdiag = diag == 'U' - threshold = 16 # Default threshold for TRMM operations + threshold = _rec_mult_leafmax(A, B) # Default threshold for TRMM operations n = size(A, 1) + size(A, 2) == n || throw(DimensionMismatch("A must be square, got $(size(A, 1))×$(size(A, 2))")) + size(B, side == 'L' ? 1 : 2) == n || + throw(DimensionMismatch("B must have $n $(side == 'L' ? "rows" : "columns") for this A, got $(size(B, 1))×$(size(B, 2))")) + isempty(B) && return B # 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 # TRSM operations require different handling and larger threshold if func == 'S' threshold = 256 # Larger threshold for solve operations - B .= alpha .* B # Apply scaling before solve + isone(alpha) || (B .= alpha .* B) # Apply scaling before solve (a full pass over B, skipped for alpha == 1) end - # Call recursive kernel - unified_rec(func, side, uplo, A, n, B, threshold; unitdiag=unitdiag) + # Call recursive kernel; its Float16 leaves widen into reused buffers (_with_workspace) + _with_workspace(() -> unified_rec(func, side, uplo, A, n, B, threshold; unitdiag=unitdiag)) # TRMM operations apply scaling after multiplication - if func == 'M' + if func == 'M' && !isone(alpha) B .= alpha .* B end return B end -""" - unified_rec(func, side, uplo, A, n, B, threshold; unitdiag=false) - -Recursive kernel for unified triangular matrix operations. - -This function implements the divide-and-conquer recursive algorithm that partitions -matrices into 2x2 block structure and applies the appropriate sequence of operations. - -# Arguments -- `func::Char`: Operation type ('S' for solve, 'M' for multiply) -- `side::Char`: Operation side ('L' for left, 'R' for right) -- `uplo::Char`: Triangular part ('U' for upper, 'L' for lower) -- `A::AbstractMatrix{T}`: Triangular coefficient matrix -- `n::Int`: Matrix dimension to process -- `B::AbstractMatrix{T}`: Target matrix (modified in-place) -- `threshold::Int`: Recursion base case threshold (default: 256) - -# Algorithm -The recursion follows different orderings based on the operation type: -1. For forward substitution: A11 → GEMM → A22 -2. For backward substitution: A22 → GEMM → A11 -This ensures numerical stability and correctness of the triangular solve. -""" # The base case, with the kernels called at the element type they are given. function _trxm_base!(func::Char, side::Char, uplo::Char, A::AbstractMatrix, B::AbstractMatrix, unitdiag::Bool) @@ -194,15 +200,85 @@ function _trxm_base!(func::Char, side::Char, uplo::Char, A::AbstractMatrix{Float return B end +# Working memory reused within one call. The mixed-precision TRSM and Cholesky allocate the same +# temporaries (widened leaves, the partial product of an off-diagonal update, the widened block +# of an off-diagonal solve) at every level of the recursion. Inside _with_workspace, _scratch hands +# back one buffer per (call site, type, size, backend) instead; the buffers belong to the calling +# task and are dropped when the outermost call returns, so memory is not held between calls and +# concurrent tasks never share one. Outside it, _scratch is a plain allocation. A call site may use +# its buffer again only after its previous contents are no longer needed. +function _with_workspace(f) + tls = task_local_storage() + haskey(tls, :nextla_workspace) && return f() + ws = Dict{Any,Any}() + try + return task_local_storage(f, :nextla_workspace, ws) + finally + foreach(_release!, values(ws)) # back to the backend's memory pool now, not at the next GC + end +end + +# Frees a workspace buffer early where the backend can (the CUDA extension: CUDA.unsafe_free!, which is +# stream-ordered, so kernels already queued on the buffer finish first). Elsewhere the GC frees it. +_release!(x) = nothing + +function _scratch(like::AbstractArray, ::Type{T}, dims::Dims, site::Symbol) where {T} + ws = get(task_local_storage(), :nextla_workspace, nothing) + ws === nothing && return similar(like, T, dims) + key = (site, T, dims, typeof(KernelAbstractions.get_backend(like))) + return get!(() -> similar(like, T, dims), ws, key) +end + +# A copy of X converted to T, in the call site's reused buffer. +_widened(X::AbstractMatrix, ::Type{T}, site::Symbol) where {T} = (W = _scratch(X, T, size(X), site); W .= X; W) + +# The leaf solve and the update step of the solve recursion. These portable methods run on every +# backend; the CUDA extension adds cuBLAS methods (ext/cuda/rectrxm.jl), as the code of the +# mixed-precision paper does (vicki-development: dispatch_trsm! at the leaf, GEMM_SUB! through +# gemmEx!). +_rec_solve_leaf!(side, uplo, A, B, unitdiag) = _trxm_base!('S', side, uplo, A, B, unitdiag) +_rec_solve_update!(C, X, Y) = GEMM_SUB!(C, X, Y) +# The same for the multiply recursion: the leaf multiply, the update C += X*Y (GEMM_ADD! argument +# order), and the widest leaf the leaf method can take. The portable multiply kernels index one +# 16-row tile; the CUDA extension's cuBLAS leaf keeps that size too. +_rec_mult_leaf!(side, uplo, A, B, unitdiag) = _trxm_base!('M', side, uplo, A, B, unitdiag) +_rec_mult_update!(X, Y, C) = GEMM_ADD!(X, Y, C) +_rec_mult_leafmax(A, B) = 16 + +""" + unified_rec(func, side, uplo, A, n, B, threshold; unitdiag=false) + +Recursive kernel for unified triangular matrix operations. + +This function implements the divide-and-conquer recursive algorithm that partitions +matrices into 2x2 block structure and applies the appropriate sequence of operations. + +# Arguments +- `func::Char`: Operation type ('S' for solve, 'M' for multiply) +- `side::Char`: Operation side ('L' for left, 'R' for right) +- `uplo::Char`: Triangular part ('U' for upper, 'L' for lower) +- `A::AbstractMatrix{T}`: Triangular coefficient matrix +- `n::Int`: Matrix dimension to process +- `B::AbstractMatrix{T}`: Target matrix (modified in-place) +- `threshold::Int`: Recursion base case threshold (default: 256) + +# Algorithm +The recursion follows different orderings based on the operation type: +1. For forward substitution: A11 → GEMM → A22 +2. For backward substitution: A22 → GEMM → A11 +This ensures numerical stability and correctness of the triangular solve. +""" 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. - func == 'M' && (threshold = min(threshold, 16)) + # covers every caller, not only unified_rectrxm!. A backend with a vendor leaf multiply raises + # the limit through _rec_mult_leafmax. + func == 'M' && (threshold = min(threshold, _rec_mult_leafmax(A, B))) # Base case: use optimized kernel functions for small matrices if n <= threshold - return _trxm_base!(func, side, uplo, A, B, unitdiag) + func == 'S' && return _rec_solve_leaf!(side, uplo, A, B, unitdiag) + return _rec_mult_leaf!(side, uplo, A, B, unitdiag) end # Determine partition size for optimal cache performance @@ -241,15 +317,15 @@ function unified_rec(func::Char, side::Char, uplo::Char, A::AbstractMatrix{T}, n # Apply rank-k update between recursive calls if side == 'L' if func == 'S' - GEMM_SUB!(B2, A21, B1) # B2 := B2 - A21 * B1 + _rec_solve_update!(B2, A21, B1) # B2 := B2 - A21 * B1 else - GEMM_ADD!(A12, B2, B1) # B1 := B1 + A12 * B2 + _rec_mult_update!(A12, B2, B1) # B1 := B1 + A12 * B2 end else if func == 'S' - GEMM_SUB!(B2, B1, A12) # B2 := B2 - B1 * A12 + _rec_solve_update!(B2, B1, A12) # B2 := B2 - B1 * A12 else - GEMM_ADD!(B2, A21, B1) # B2 := B2 + A21 * B1 + _rec_mult_update!(B2, A21, B1) # B1 := B1 + B2 * A21 end end @@ -261,15 +337,15 @@ function unified_rec(func::Char, side::Char, uplo::Char, A::AbstractMatrix{T}, n # Apply rank-k update between recursive calls if side == 'L' if func == 'S' - GEMM_SUB!(B1, A12, B2) # B1 := B1 - A12 * B2 + _rec_solve_update!(B1, A12, B2) # B1 := B1 - A12 * B2 else - GEMM_ADD!(A21, B1, B2) # B2 := B2 + A21 * B1 + _rec_mult_update!(A21, B1, B2) # B2 := B2 + A21 * B1 end else if func == 'S' - GEMM_SUB!(B1, B2, A21) # B1 := B1 - B2 * A21 + _rec_solve_update!(B1, B2, A21) # B1 := B1 - B2 * A21 else - GEMM_ADD!(B1, A12, B2) # B1 := B1 + A12 * B2 + _rec_mult_update!(B1, A12, B2) # B2 := B2 + B1 * A12 end end diff --git a/src/trsm/trmm.jl b/src/dense/blas/trsm/trmm.jl similarity index 83% rename from src/trsm/trmm.jl rename to src/dense/blas/trsm/trmm.jl index bcd95f16..1d7faebd 100644 --- a/src/trsm/trmm.jl +++ b/src/dense/blas/trsm/trmm.jl @@ -22,7 +22,7 @@ export LeftLowerTRMM!, LeftUpperTRMM!, RightLowerTRMM!, RightUpperTRMM! # A is limited to matrix size 16×16 due to shared memory constraints """ - LeftLowerTRMM_kernel!(A, B, ::Val{BANK}=Val(1)) + LeftLowerTRMM_kernel!(A, B, ::Val{U}, ::Val{BANK}=Val(1)) GPU kernel for left-sided lower triangular matrix multiplication. @@ -32,6 +32,7 @@ Uses shared memory tiling with configurable bank offset to avoid conflicts. # Arguments - `A::AbstractMatrix`: N×N lower triangular coefficient matrix - `B::AbstractMatrix`: N×M target matrix (modified in-place) +- `U::Bool`: if `true`, the diagonal of `A` is taken as one (unit diagonal) - `BANK::Int`: Memory bank offset to avoid conflicts (default: 1) # Implementation Notes @@ -314,22 +315,34 @@ end +# The kernels hold the triangle in one tile of n_threads[1] rows: A is k×k with k ≤ n_threads[1]. +function _trmm_driver_check(A, k, n_threads) + size(A) == (k, k) || throw(DimensionMismatch("A must be $k×$k for this B, got $(size(A, 1))×$(size(A, 2))")) + k <= n_threads[1] || throw(ArgumentError("the TRMM kernels take a triangle of at most $(n_threads[1]) rows, got $k; trmm! and unified_rectrxm! recurse for larger ones")) + return nothing +end + """ - LeftLowerTRMM!(A, B; n_threads=(16,16)) + LeftLowerTRMM!(A, B, unitdiag=false; n_threads=(16,16)) Perform left-sided lower triangular matrix multiplication: B := A * B # Arguments - `A::AbstractMatrix`: N×N lower triangular coefficient matrix - `B::AbstractMatrix`: N×M target matrix (modified in-place) +- `unitdiag::Bool`: if `true`, the diagonal of `A` is taken as one (default: `false`) - `n_threads::Tuple`: Thread block dimensions (default: (16,16)) +`A` may have at most `n_threads[1]` (16) rows; a larger `A` throws `ArgumentError`. +Use [`trmm!`](@ref) for larger triangles. + # Implementation Notes - Uses GPU acceleration with optimized kernel - Thread block size should not exceed hardware limits - NDRange is padded to handle boundary conditions """ function LeftLowerTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) + _trmm_driver_check(A, size(B, 1), n_threads) backend = get_backend(A) # Calculate NDRange with padding to handle boundary threads Ndrange = max(size(A), size(B)) @@ -338,16 +351,21 @@ function LeftLowerTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) end """ - LeftUpperTRMM!(A, B; n_threads=(16,16)) + LeftUpperTRMM!(A, B, unitdiag=false; n_threads=(16,16)) Perform left-sided upper triangular matrix multiplication: B := A * B # Arguments - `A::AbstractMatrix`: N×N upper triangular coefficient matrix - `B::AbstractMatrix`: N×M target matrix (modified in-place) +- `unitdiag::Bool`: if `true`, the diagonal of `A` is taken as one (default: `false`) - `n_threads::Tuple`: Thread block dimensions (default: (16,16)) + +`A` may have at most `n_threads[1]` (16) rows; a larger `A` throws `ArgumentError`. +Use [`trmm!`](@ref) for larger triangles. """ function LeftUpperTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) + _trmm_driver_check(A, size(B, 1), n_threads) backend = get_backend(A) Ndrange = max(size(A), size(B)) Ndrange = (Ndrange[1] + 16, Ndrange[2] + 16) @@ -355,16 +373,21 @@ function LeftUpperTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) end """ - RightLowerTRMM!(A, B; n_threads=(16,16)) + RightLowerTRMM!(A, B, unitdiag=false; n_threads=(16,16)) Perform right-sided lower triangular matrix multiplication: B := B * A # Arguments - `A::AbstractMatrix`: N×N lower triangular coefficient matrix - `B::AbstractMatrix`: M×N target matrix (modified in-place) +- `unitdiag::Bool`: if `true`, the diagonal of `A` is taken as one (default: `false`) - `n_threads::Tuple`: Thread block dimensions (default: (16,16)) + +`A` may have at most `n_threads[1]` (16) rows; a larger `A` throws `ArgumentError`. +Use [`trmm!`](@ref) for larger triangles. """ function RightLowerTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) + _trmm_driver_check(A, size(B, 2), n_threads) backend = get_backend(A) Ndrange = max(size(A), size(B)) Ndrange = (Ndrange[1] + 16, Ndrange[2] + 16) @@ -372,16 +395,21 @@ function RightLowerTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) end """ - RightUpperTRMM!(A, B; n_threads=(16,16)) + RightUpperTRMM!(A, B, unitdiag=false; n_threads=(16,16)) Perform right-sided upper triangular matrix multiplication: B := B * A # Arguments - `A::AbstractMatrix`: N×N upper triangular coefficient matrix - `B::AbstractMatrix`: M×N target matrix (modified in-place) +- `unitdiag::Bool`: if `true`, the diagonal of `A` is taken as one (default: `false`) - `n_threads::Tuple`: Thread block dimensions (default: (16,16)) + +`A` may have at most `n_threads[1]` (16) rows; a larger `A` throws `ArgumentError`. +Use [`trmm!`](@ref) for larger triangles. """ function RightUpperTRMM!(A, B, unitdiag::Bool=false; n_threads = (16,16)) + _trmm_driver_check(A, size(B, 2), n_threads) backend = get_backend(A) Ndrange = max(size(A), size(B)) Ndrange = (Ndrange[1] + 16, Ndrange[2] + 16) @@ -391,8 +419,8 @@ end """ trmm(side, uplo, transa, diag, A, B, alpha=1.0) -> B -Performs triangular matrix multiplication with automatic parameter detection. -This is a simplified interface for triangular matrix multiplication operations. +Short form of [`trmm!`](@ref): the arguments are forwarded unchanged, with +`alpha` last. # Arguments - `side::Char`: Operation side @@ -405,47 +433,34 @@ This is a simplified interface for triangular matrix multiplication operations. - 'N': op(A) = A (no transpose) - 'T': op(A) = A^T (transpose) - 'C': op(A) = A^H (conjugate transpose) -- `diag::Char`: Diagonal type (currently unused in GPU implementation) +- `diag::Char`: Diagonal type - 'N': non-unit diagonal - 'U': unit diagonal - `A::AbstractMatrix`: Triangular coefficient matrix - `B::AbstractMatrix`: Target matrix (modified in-place) -- `alpha`: Scalar multiplier (default: 1.0) +- `alpha`: Scalar multiplier (default: `one(eltype(A))`) # 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; + +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 + +julia> B ≈ UpperTriangular(A) * B0 +true ``` # Implementation Notes -- Currently supports 'N' (no transpose) operations only -- Uses GPU-accelerated kernels for computation -- The transa and diag parameters are provided for interface compatibility +- The same as `trmm!(side, uplo, transa, diag, alpha, A, B)`, which it calls """ -function trmm(side, uplo, transa, diag, A, B, alpha=one(eltype(A))) - # Apply scaling if alpha != 1 - if alpha != one(eltype(A)) - B .*= alpha - end - - # Dispatch to appropriate GPU kernel based on operation parameters - if side == 'L' && uplo == 'L' - LeftLowerTRMM!(A, B) - elseif side == 'L' && uplo == 'U' - LeftUpperTRMM!(A, B) - elseif side == 'R' && uplo == 'L' - RightLowerTRMM!(A, B) - elseif side == 'R' && uplo == 'U' - RightUpperTRMM!(A, B) - else - error("Unsupported combination of side='$side', uplo='$uplo'") - end -end +trmm(side, uplo, transa, diag, A, B, alpha=one(eltype(A))) = trmm!(side, uplo, transa, diag, alpha, A, B) # The BLAS-order entry points. They live here, beside the kernels, rather than # in rectrxm.jl: unified_rectrxm! is the engine (recursion plus vendor fast @@ -461,6 +476,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) = @@ -471,8 +502,8 @@ trmm!(side::Char, uplo::Char, transa::Char, diag::Char, alpha::Number, Triangular multiply into a separate output: `C := alpha * op(A) * B` (`side = 'L'`) or `C := alpha * B * op(A)` (`side = 'R'`), leaving `B` as it -was. This is the argument list of cuBLAS / rocBLAS `trmm!` and of -vicki-development's `wrappers.jl`; passing `C = B` gives the in-place form. +was. This is the argument list of cuBLAS / rocBLAS `trmm!`; passing `C = B` +gives the in-place form. `B` is copied into `C` and multiplied there by the in-place method, so it runs wherever that does. """ 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 58% rename from src/trsm/trsm.jl rename to src/dense/blas/trsm/trsm_kernels.jl index 696f2e96..98d8c13b 100644 --- a/src/trsm/trsm.jl +++ b/src/dense/blas/trsm/trsm_kernels.jl @@ -125,35 +125,98 @@ end end end +# The kernels hold one line of B in 1024 elements of local memory: the triangle has k ≤ 1024 rows. +function _trsm_driver_check(A, k) + size(A) == (k, k) || throw(DimensionMismatch("A must be $k×$k for this B, got $(size(A, 1))×$(size(A, 2))")) + k <= 1024 || throw(ArgumentError("the TRSM kernels take a triangle of at most 1024 rows, got $k; trsm! and unified_rectrxm! recurse for larger ones")) + return nothing +end + +""" + LeftLowerTRSM!(A, B, unitdiag=false) -> nothing + +Solve `A * X = B` in place for a lower triangular `A` (left side): `B` is +overwritten with `X`. Only the lower triangle of `A` is read. With +`unitdiag = true` the diagonal is taken as one and not read. + +This is one GPU kernel launch, with no `alpha` and no transpose. `A` must be +`k×k`, where `k` is the number of rows of `B`; otherwise it throws +`DimensionMismatch`. `k` may be at most 1024; a larger triangle throws +`ArgumentError`. Use [`trsm!`](@ref) for larger triangles. Returns `nothing` +and does not synchronize. +""" function LeftLowerTRSM!(A, B, unitdiag::Bool=false) n, m = size(B) + _trsm_driver_check(A, n); isempty(B) && return nothing 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 +""" + LeftUpperTRSM!(A, B, unitdiag=false) -> nothing + +Solve `A * X = B` in place for a upper triangular `A` (left side): `B` is +overwritten with `X`. Only the upper triangle of `A` is read. With +`unitdiag = true` the diagonal is taken as one and not read. + +This is one GPU kernel launch, with no `alpha` and no transpose. `A` must be +`k×k`, where `k` is the number of rows of `B`; otherwise it throws +`DimensionMismatch`. `k` may be at most 1024; a larger triangle throws +`ArgumentError`. Use [`trsm!`](@ref) for larger triangles. Returns `nothing` +and does not synchronize. +""" function LeftUpperTRSM!(A, B, unitdiag::Bool=false) n, m = size(B) + _trsm_driver_check(A, n); isempty(B) && return nothing backend = get_backend(A) upper_left_kernel(backend, (n,))(A, B, n, Val(unitdiag), ndrange=(n, m)) end +""" + RightLowerTRSM!(A, B, unitdiag=false) -> nothing + +Solve `X * A = B` in place for a lower triangular `A` (right side): `B` is +overwritten with `X`. Only the lower triangle of `A` is read. With +`unitdiag = true` the diagonal is taken as one and not read. + +This is one GPU kernel launch, with no `alpha` and no transpose. `A` must be +`k×k`, where `k` is the number of columns of `B`; otherwise it throws +`DimensionMismatch`. `k` may be at most 1024; a larger triangle throws +`ArgumentError`. Use [`trsm!`](@ref) for larger triangles. Returns `nothing` +and does not synchronize. +""" function RightLowerTRSM!(A, B, unitdiag::Bool=false) n, m = size(B) + _trsm_driver_check(A, m); isempty(B) && return nothing backend = get_backend(A) right_lower_kernel(backend, (m,))(A, B, m, Val(unitdiag), ndrange=(m, n)) end +""" + RightUpperTRSM!(A, B, unitdiag=false) -> nothing + +Solve `X * A = B` in place for a upper triangular `A` (right side): `B` is +overwritten with `X`. Only the upper triangle of `A` is read. With +`unitdiag = true` the diagonal is taken as one and not read. + +This is one GPU kernel launch, with no `alpha` and no transpose. `A` must be +`k×k`, where `k` is the number of columns of `B`; otherwise it throws +`DimensionMismatch`. `k` may be at most 1024; a larger triangle throws +`ArgumentError`. Use [`trsm!`](@ref) for larger triangles. Returns `nothing` +and does not synchronize. +""" function RightUpperTRSM!(A, B, unitdiag::Bool=false) n, m = size(B) + _trsm_driver_check(A, m); isempty(B) && return nothing 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 """ trsm(side, uplo, transa, diag, A, B, alpha=1.0) -> B -Solves triangular matrix systems with automatic parameter detection. -This is a simplified interface for triangular system solving. +Short form of [`trsm!`](@ref): the arguments are forwarded unchanged, with +`alpha` last. # Arguments - 'side': @@ -171,38 +234,26 @@ This is a simplified interface for triangular system solving. - 'U': unit diagonal - 'A': triangular matrix - 'B': right-hand side matrix (will be overwritten with solution) -- 'alpha': scalar multiplier (default: 1.0) +- 'alpha': scalar multiplier (default: `one(eltype(A))`) # 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 + +julia> UpperTriangular(A) * B ≈ B0 +true ``` """ -function trsm(side, uplo, transa, diag, A, B, alpha=one(eltype(A))) - # Scale B if alpha != 1 - if alpha != one(eltype(A)) - B .*= alpha - end - - # Apply the appropriate kernel based on parameters - if side == 'L' && uplo == 'L' - LeftLowerTRSM!(A, B) - elseif side == 'L' && uplo == 'U' - LeftUpperTRSM!(A, B) - elseif side == 'R' && uplo == 'L' - RightLowerTRSM!(A, B) - elseif side == 'R' && uplo == 'U' - RightUpperTRSM!(A, B) - else - error("Unsupported combination of side='$side', uplo='$uplo'") - end - -end +trsm(side, uplo, transa, diag, A, B, alpha=one(eltype(A))) = trsm!(side, uplo, transa, diag, alpha, A, B) # The BLAS-order entry point. It lives here, beside the kernels, rather than in # rectrxm.jl: unified_rectrxm! is the engine (recursion plus vendor fast paths) @@ -220,8 +271,24 @@ A thin entry point over [`unified_rectrxm!`](@ref) with `func = 'S'`, so it runs wherever that does, for real and complex element types. On `CuMatrix` and `ROCMatrix` of `Float32`, `Float64`, `ComplexF32` or `ComplexF64` it 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. +the CPU, oneAPI, Metal and `Float16` it runs the portable recursive kernels. +CUDA views go to cuBLAS too; AMDGPU views take the portable path. `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 59% rename from src/NextLAMatrix.jl rename to src/dense/core/NextLAMatrix.jl index 6b57357f..690303c7 100644 --- a/src/NextLAMatrix.jl +++ b/src/dense/core/NextLAMatrix.jl @@ -1,6 +1,27 @@ export NextLAMatrix +""" + NextLAMatrix(data::Matrix{T}) + NextLAMatrix{T}(data::Matrix{T}) + +A wrapper around a dense `Matrix` that sends some LinearAlgebra calls to NextLA's own +routines. It is not an `AbstractMatrix`. `size`, `length`, and `getindex`/`setindex!` with +integer indices forward to the wrapped matrix. + +# Fields +- `data::Matrix{T}`: the wrapped matrix. Calls on the wrapper change it in place. + +# Methods +- `lu!(A::NextLAMatrix)` runs `getrf2!` for `Float32`, `Float64`, `ComplexF32` and + `ComplexF64` with the default pivoting (`RowMaximum()`), and returns a `LinearAlgebra.LU`. + Other element types, or other pivots (`NoPivot()`, `RowNonZero()`, `CompletePivoting()`), + use NextLA's generic loop and return a `NextLA.LU`. +- `BLAS.axpy!(α, x::NextLAMatrix, y::NextLAMatrix)` runs NextLA's `axpy!` on the wrapped + matrices, updating `y` in place. +- `BLAS.gemm!`, `BLAS.syrk!`, `BLAS.herk!`, `BLAS.syr2k!` and `BLAS.her2k!` on + `NextLAMatrix` arguments pass the wrapped matrices through to the system BLAS. +""" mutable struct NextLAMatrix{T} data::Matrix{T} function NextLAMatrix{T}(data::Matrix{T}) where {T} @@ -8,7 +29,7 @@ mutable struct NextLAMatrix{T} end end -#NextLAMatrix(data::Matrix{T}) where {T} = NextLAMatrix{T}(data) +NextLAMatrix(data::Matrix{T}) where {T} = NextLAMatrix{T}(data) Base.size(A::NextLAMatrix) = size(A.data) Base.size(A::NextLAMatrix, i::Integer) = size(A.data, i) @@ -22,10 +43,7 @@ Base.setindex!(A::NextLAMatrix, v, i::Integer, j::Integer) = A.data[i,j] = v #This temp LinearAlgebra.BLAS.axpy!(α::Number, x::NextLAMatrix, y::NextLAMatrix) = axpy!(α, vec(x.data), vec(y.data)) -LinearAlgebra.BLAS.gemv!(tA::Char, α::Number, A::NextLAMatrix, x::NextLAMatrix, β::Number, y::NextLAMatrix) = LinearAlgebra.BLAS.gemv!(tA, α, A.data, x.data, β, y.data) LinearAlgebra.BLAS.gemm!(tA::Char, tB::Char, α::Number, A::NextLAMatrix, B::NextLAMatrix, β::Number, C::NextLAMatrix) = LinearAlgebra.BLAS.gemm!(tA, tB, α, A.data, B.data, β, C.data) -LinearAlgebra.BLAS.trmm!(tA::Char, tB::Char, tC::Char, α::Number, A::NextLAMatrix, B::NextLAMatrix) = LinearAlgebra.BLAS.trmm!(tA, tB, tC, α, A.data, B.data) -LinearAlgebra.BLAS.trsm!(tA::Char, tB::Char, tC::Char, α::Number, A::NextLAMatrix, B::NextLAMatrix) = LinearAlgebra.BLAS.trsm!(tA, tB, tC, α, A.data, B.data) LinearAlgebra.BLAS.syrk!(tA::Char, tC::Char, α::Number, A::NextLAMatrix, β::Number, C::NextLAMatrix) = LinearAlgebra.BLAS.syrk!(tA, tC, α, A.data, β, C.data) LinearAlgebra.BLAS.herk!(tA::Char, tC::Char, α::Number, A::NextLAMatrix, β::Number, C::NextLAMatrix) = LinearAlgebra.BLAS.herk!(tA, tC, α, A.data, β, C.data) LinearAlgebra.BLAS.syr2k!(tA::Char, tC::Char, α::Number, A::NextLAMatrix, B::NextLAMatrix, β::Number, C::NextLAMatrix) = LinearAlgebra.BLAS.syr2k!(tA, tC, α, A.data, B.data, β, C.data) diff --git a/src/cholesky/cholesky.jl b/src/dense/lapack/cholesky/cholesky.jl similarity index 85% rename from src/cholesky/cholesky.jl rename to src/dense/lapack/cholesky/cholesky.jl index 2c4b7731..70313c93 100644 --- a/src/cholesky/cholesky.jl +++ b/src/dense/lapack/cholesky/cholesky.jl @@ -6,13 +6,13 @@ # `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 -# is its only caller. +# potrf_batched! (src/dense/lapack/cholesky/potrf_batched.jl) is the batch entry point, for +# many independent matrices; nothing inside the library calls it. # # potrf_kernel.jl and recpotrf.jl are Vicki's, ported off CUDA. Her # SymmMixedPrec method is not here: mixed precision owns its own tree under @@ -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 79% rename from src/cholesky/potrf.jl rename to src/dense/lapack/cholesky/potrf.jl index c5fba468..de1bda8b 100644 --- a/src/cholesky/potrf.jl +++ b/src/dense/lapack/cholesky/potrf.jl @@ -28,14 +28,34 @@ Convenience form, equivalent to `potrf!('L', A)`. ## Notes - On the CPU, `potrf!` is a thin wrapper around `LinearAlgebra.LAPACK.potrf!`. - GPU backends dispatch to native Cholesky routines when available; see - `ext/{cuda,amdgpu}/potrf.jl`. There is no generic device fallback, so a - backend without a wrapper raises rather than silently copying to the host. + `ext/{cuda,amdgpu}/potrf.jl`. Metal's wrapper throws, and oneAPI has none. + There is no generic device fallback, so a backend without a working wrapper + raises rather than silently copying to the host. - This is the single-matrix entry point. For a batch of independent matrices 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) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them backend = KernelAbstractions.get_backend(A) backend isa KernelAbstractions.CPU || throw(ArgumentError("NextLA.potrf! has no generic non-CPU implementation; use a backend wrapper")) _potrf_dims(uplo, A) @@ -50,6 +70,7 @@ end # gives Float16; without it the recursive Cholesky's Float16 leaves had no # method at all. function potrf!(uplo::Char, A::AbstractMatrix{Float16}) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them _potrf_dims(uplo, A) A32, info = potrf!(uplo, Float32.(A)) A .= Float16.(A32) # broadcast, so the copy back stays on the device diff --git a/src/cholesky/potrf_batched.jl b/src/dense/lapack/cholesky/potrf_batched.jl similarity index 75% rename from src/cholesky/potrf_batched.jl rename to src/dense/lapack/cholesky/potrf_batched.jl index 7c91b4e8..47e1ecd2 100644 --- a/src/cholesky/potrf_batched.jl +++ b/src/dense/lapack/cholesky/potrf_batched.jl @@ -15,8 +15,25 @@ 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} + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them backend = KernelAbstractions.get_backend(A) backend isa KernelAbstractions.CPU || throw(ArgumentError("NextLA.potrf_batched! has no generic non-CPU implementation; use a backend wrapper")) size(A, 1) == size(A, 2) || diff --git a/src/cholesky/potrf_blocked.jl b/src/dense/lapack/cholesky/potrf_blocked.jl similarity index 82% rename from src/cholesky/potrf_blocked.jl rename to src/dense/lapack/cholesky/potrf_blocked.jl index ecbacf30..7c73346d 100644 --- a/src/cholesky/potrf_blocked.jl +++ b/src/dense/lapack/cholesky/potrf_blocked.jl @@ -1,6 +1,6 @@ export cholesky_blocked! -# Right-looking blocked Cholesky: the panel form of the factorisation, driving a +# Left-looking blocked Cholesky: the panel form of the factorisation, driving a # shared-memory kernel on each diagonal block. # # Source: vicki-development @ 694d019, src/potrf.jl -- the live third of it; the @@ -11,7 +11,7 @@ export cholesky_blocked! # This is the blocked counterpart to potrf_recursive!: same factorisation, a # panel sweep instead of a subdivision. For a single diagonal block, cholesky_lower! # in potrf_kernel.jl is the portable choice; this is for a matrix large enough -# that the trailing update dominates. +# that the block-column GEMMs dominate. # The branch tiles a 64-wide block into shared memory with one column of padding, # so that column c lands at (c-1)*CHOL_STRIDE and consecutive rows fall in @@ -46,7 +46,7 @@ const CHOL_STRIDE = CHOL_BLOCK + 1 for k in 1:N diag_idx = (k - 1) * CHOL_STRIDE + k if tx == 1 - @inbounds tile[diag_idx] = sqrt(tile[diag_idx]) + @inbounds tile[diag_idx] = _chol_sqrt(tile[diag_idx]) end @synchronize @@ -103,12 +103,16 @@ end """ cholesky_blocked!(A; block = 64, threads = 512, kernel = :shared) -> A -In-place right-looking blocked Cholesky, `A = L * Lᵀ`, writing `L` into the lower -triangle of `A` and leaving the strict upper triangle untouched. +In-place left-looking blocked Cholesky, `A = L * Lᵀ`, writing `L` into the lower +triangle of `A`. The strict upper triangle outside the diagonal blocks is left +untouched. Inside each diagonal block after the first, the GEMM also updates the +strict upper triangle, so those entries no longer hold their input values. -Each pass factors one diagonal block with a kernel, updates the panel below it -with a triangular solve, and applies the trailing rank-`block` update. `block` -must not exceed 64, the width both kernels are sized for. +Each pass works on one block column. It first updates the whole block column (the +diagonal block and the panel below it) with one GEMM against the columns already +factored, then factors the diagonal block with a kernel, then solves for the panel +below it with a triangular solve. There is no trailing update. `block` must not +exceed 64, the width both kernels are sized for. `kernel` picks how a diagonal block is factored, and only that -- the panel solve and the trailing update are the same either way: @@ -124,10 +128,20 @@ GPU only: the kernel is declared `cpu=false` on the branch this came from, and the CPU backend cannot run it. Use [`potrf!`](@ref) or [`potrf_recursive!`](@ref) there. -!!! warning - 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`. +A matrix that is not positive definite throws `PosDefException(k)` at the first +pivot that is not positive, with `A` partly factored (`NaN` from that column on). + +# 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) @@ -177,5 +191,6 @@ function cholesky_blocked!(A::AbstractMatrix; block::Integer = CHOL_BLOCK, end end KernelAbstractions.synchronize(backend) + _chol_check_diag(A) return A end diff --git a/src/cholesky/potrf_kernel.jl b/src/dense/lapack/cholesky/potrf_kernel.jl similarity index 66% rename from src/cholesky/potrf_kernel.jl rename to src/dense/lapack/cholesky/potrf_kernel.jl index 9e9505a5..2bb406dd 100644 --- a/src/cholesky/potrf_kernel.jl +++ b/src/dense/lapack/cholesky/potrf_kernel.jl @@ -9,19 +9,32 @@ const MAX_CHOL_THREADS = 512 # counterpart to lu_base!. One thread does the square root and the column # scaling; the rest share the trailing rank-1 update, with a barrier on either # side. Suited to a diagonal block, not a whole large matrix -- use -# potrf_recursive! for that, which drives this at its leaves. +# potrf_recursive! (whose leaves call potrf!) for that. # # Structure is verbatim, including the single @index read at the top. That is # worth a note: a plain local assigned before a @synchronize does not survive # the CPU backend's split of the body into separate ndrange loops, which has # bitten this repo four times. @index is not a plain local and does survive -- # checked by running the unported kernel on the CPU, where it factors to 1.6e-16. +# A pivot that is not positive gives NaN instead of a DomainError, which on a GPU would break the +# device context; the drivers then report the first NaN on the diagonal as a PosDefException. +@inline _chol_sqrt(x::Real) = x > zero(x) ? sqrt(x) : zero(x) / zero(x) +@inline _chol_sqrt(x) = sqrt(x) + +# Throws PosDefException(k) for the first diagonal entry of A that is NaN (a pivot that was not positive). +function _chol_check_diag(A) + d = Array(A[LinearAlgebra.diagind(A)]) + k = findfirst(isnan, d) + k === nothing || throw(LinearAlgebra.PosDefException(k)) + return nothing +end + @kernel function chol_kernel_lower!(A, N, ops_per_thread) tx = @index(Global, Linear) for k in 1:N if tx == 1 - @inbounds A[k, k] = sqrt(A[k, k]) + @inbounds A[k, k] = _chol_sqrt(A[k, k]) for j in (k + 1):N @inbounds A[j, k] /= A[k, k] end @@ -59,17 +72,34 @@ overwriting the lower triangle with `L` and explicitly zeroing the upper triangle. Unblocked and confined to a single workgroup, so it is intended for a diagonal -block rather than a full matrix; [`potrf_recursive!`](@ref) uses it that way. +block rather than a full matrix. For a one-shot factorization of a general matrix prefer [`potrf!`](@ref), which 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. +Unlike [`potrf!`](@ref) this zeroes the opposite triangle. A matrix that is not +positive definite throws `PosDefException(k)` at the first pivot that is not +positive, with `A` partly factored (`NaN` from that column on). + +# 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) N == size(A, 2) || throw(DimensionMismatch("cholesky_lower!: A must be square")) + N == 0 && return A # nothing to factor, as LAPACK backend = get_backend(A) num_threads = min(N, MAX_CHOL_THREADS) @@ -77,5 +107,6 @@ function cholesky_lower!(A) chol_kernel_lower!(backend, num_threads)(A, N, ops_per_thread; ndrange = num_threads) KernelAbstractions.synchronize(backend) + _chol_check_diag(A) return A end diff --git a/src/cholesky/potrf_register.jl b/src/dense/lapack/cholesky/potrf_register.jl similarity index 97% rename from src/cholesky/potrf_register.jl rename to src/dense/lapack/cholesky/potrf_register.jl index 05eae0be..1e5c3979 100644 --- a/src/cholesky/potrf_register.jl +++ b/src/dense/lapack/cholesky/potrf_register.jl @@ -80,7 +80,7 @@ const CHOL_REG_SPLIT = CHOL_BLOCK ÷ (2 * CHOL_REG_STRIP) # Prime the pipeline with the first diagonal; every later square root is # taken inside the loop, one iteration ahead of its use. if tx == 1 - @inbounds my_vals[1] = sqrt(my_vals[1]) + @inbounds my_vals[1] = _chol_sqrt(my_vals[1]) @inbounds diag_val_next[1] = my_vals[1] end @@ -132,7 +132,7 @@ const CHOL_REG_SPLIT = CHOL_BLOCK ÷ (2 * CHOL_REG_STRIP) if k_next >= col_start && k_next < (col_start + CHOL_REG_STRIP) && my_row == k_next local_idx_next = (k_next - col_start) + 1 - @inbounds my_vals[local_idx_next] = sqrt(my_vals[local_idx_next]) + @inbounds my_vals[local_idx_next] = _chol_sqrt(my_vals[local_idx_next]) @inbounds diag_val_next[1] = my_vals[local_idx_next] end end diff --git a/src/cholesky/recpotrf.jl b/src/dense/lapack/cholesky/recpotrf.jl similarity index 71% rename from src/cholesky/recpotrf.jl rename to src/dense/lapack/cholesky/recpotrf.jl index 8629a811..472c3477 100644 --- a/src/cholesky/recpotrf.jl +++ b/src/dense/lapack/cholesky/recpotrf.jl @@ -14,19 +14,35 @@ for `uplo = 'L'`, or `A = Uᵀ * U` with `U` in the upper triangle for `'U'`. The recursion splits `A` into a 2x2 block scheme and stops once a sub-block is `block_size` or smaller, at which point it falls back to [`potrf!`](@ref). -The panel solve always goes through [`unified_rectrxm!`](@ref), main's portable -triangular solve. The branch called a vendor `trsm!` from `src/wrappers.jl` for -everything but `Float16`; that file is not merged, and `BLAS.trsm!` would pin -this routine to the CPU, so the recursive path is used throughout. The rank-k -update still splits: `syrk!` reaches BLAS or the vendor library, but has no -`Float16` method anywhere, so half precision takes [`recsyrk!`](@ref). +The panel solve goes through [`trsm!`](@ref) (one vendor call on CUDA, the portable +recursive [`unified_rectrxm!`](@ref) elsewhere); `Float16` takes `unified_rectrxm!` +directly, as no vendor library has a `Float16` TRSM. The rank-k update uses +`syrk!`, which reaches BLAS or the vendor library; `syrk!` has no `Float16` +method, so half precision takes [`recsyrk!`](@ref). The other triangle is not referenced and is left as it was on entry. A matrix that is not 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). +`n` at the largest power of two below it (at `n ÷ 2` when `n` is a power of two). + +# 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 = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U', got '$uplo'")) block_size >= 1 || throw(ArgumentError("block_size must be at least 1")) size(A, 1) == size(A, 2) || throw(DimensionMismatch("potrf_recursive!: A must be square, got $(size(A))")) @@ -54,7 +70,8 @@ function _potrf_recursive!(A, block_size, uplo::Char, offset::Int) if uplo == 'L' # L21 = A21 * L11⁻ᵀ, then A22 -= L21 * L21ᵀ A21 = @view A[(n1 + 1):end, 1:n1] - unified_rectrxm!('R', 'L', 'T', 'N', one(eltype(A11)), 'S', A11, A21) + eltype(A11) == Float16 ? unified_rectrxm!('R', 'L', 'T', 'N', one(eltype(A11)), 'S', A11, A21) : + trsm!('R', 'L', 'T', 'N', one(eltype(A11)), A11, A21) if eltype(A21) == Float16 recsyrk!(-1.0, A21, 1.0, A22) else @@ -63,7 +80,8 @@ function _potrf_recursive!(A, block_size, uplo::Char, offset::Int) else # U12 = U11⁻ᵀ * A12, then A22 -= U12ᵀ * U12 A12 = @view A[1:n1, (n1 + 1):end] - unified_rectrxm!('L', 'U', 'T', 'N', one(eltype(A11)), 'S', A11, A12) + eltype(A11) == Float16 ? unified_rectrxm!('L', 'U', 'T', 'N', one(eltype(A11)), 'S', A11, A12) : + trsm!('L', 'U', 'T', 'N', one(eltype(A11)), A11, A12) if eltype(A12) == Float16 recsyrk!(-1.0, copy(transpose(A12)), 1.0, A22; uplo='U') else 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 80% rename from src/lu.jl rename to src/dense/lapack/lu/lu_pivot.jl index 55da29e2..85332e4e 100644 --- a/src/lu.jl +++ b/src/dense/lapack/lu/lu_pivot.jl @@ -1,5 +1,15 @@ export CompletePivoting, RowMaximum, RowNonZero, NoPivot, lupivottype, lu!, getrf2!, laswp, geru!, getc2! +import LinearAlgebra: lupivottype # exported above; the default pivot for lu!(A::NextLAMatrix) + +""" + CompletePivoting() + +Pivoting strategy for LU with row and column interchanges, giving `A = P * L * U * Q` with +`P` and `Q` permutation matrices. It has no fields. Pass it to +`lu!(A::NextLAMatrix, CompletePivoting())` or to `getc2!`; both return a `NextLA.LU`, which +holds the row pivots in `ipiv` and the column pivots in `jpiv`. +""" struct CompletePivoting <: PivotingStrategy end struct LU{T,S<:AbstractMatrix{T},P<:AbstractVector{<:Integer}} @@ -13,12 +23,6 @@ struct LU{T,S<:AbstractMatrix{T},P<:AbstractVector{<:Integer}} end end -LU(factors::AbstractMatrix{T}, ipiv::AbstractVector{<:Integer}, jpiv::AbstractVector{<:Integer}, info::BlasInt) where {T} = - LU{T,typeof(factors),typeof(ipiv)}(factors, ipiv, info) - -LU{T}(factors::AbstractMatrix, ipiv::AbstractVector{<:Integer}, jpiv::AbstractVector{<:Integer}, info::Integer) where {T} = - LU(convert(AbstractMatrix{T}, factors), ipiv, BlasInt(info)) - checknozeropivot(info) = info == 0 || throw(LinearAlgebra.ZeroPivotException(info)) checknonsingular(info) = info == 0 || throw(LinearAlgebra.SingularException(info)) @@ -42,9 +46,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) @@ -158,7 +173,7 @@ end """ - getrf2!(A::AbstractMatrix{T}, ipiv::AbstractVector{Int}, info::Ref{Int}) + getrf2!(A::AbstractMatrix{T}, ipiv::AbstractVector{Int}, info::Int) -> (A, ipiv, info) Computes an LU factorization of a general M-by-N matrix A using partial pivoting with row exchanges. The factorization has form @@ -166,7 +181,8 @@ 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. `T` must be a BLAS float: `Float32`, `Float64`, +`ComplexF32` or `ComplexF64`. The call returns `(A, ipiv, info)`. # Arguments - 'A' : matrix, dimension (m,n) @@ -176,12 +192,26 @@ This is the recursive form of the algorithm. - 'ipiv' : dimension (min(m,n)) - the pivot indicies; for 1 <= i <= min(m,n), row i of the matrix was interchanged with row ipiv[i] -- 'info' : +- 'info' : an `Int`; the value passed in is ignored. The status comes back as the third + element of the returned tuple: - =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} @@ -308,10 +338,12 @@ function getrf2!(A::AbstractMatrix{T}, ipiv::AbstractVector{Int}, info::Int) wh end """ -lu!(A::DLAArray{T}, ::CompletePivoting; check::Bool = true, allowsingular::Bool = false) where {T<:BlasFloat} + getc2!(A::NextLAMatrix{T}, ::CompletePivoting; check::Bool = true, allowsingular::Bool = false) where {T<:BlasFloat} -> NextLA.LU Computes an LU factorization with complete pivoting of the n-by-n matrix A. The factorization has the form A = P * L * U * Q, where P and Q are permutation matrices, L is lower triangular with unit diagonal elements and U is upper triangular. +It returns a `NextLA.LU` holding the factors, the row pivots `ipiv` and the column pivots `jpiv`. +A pivot smaller than `smin` throws `SingularException`, unless `check = false` or `allowsingular = true`. # Arguments - 'A' : matrix, dimension (n,n) @@ -319,8 +351,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) @@ -333,10 +377,9 @@ function getc2!(A::NextLAMatrix{T}, ::CompletePivoting; check::Bool = true, all ipiv = Vector{Int}(undef, minmn) jpiv = Vector{Int}(undef, minmn) - realt = typeof(real(A[1,1])) - if n == 0 - return - end + realt = real(T) # not real(A[1,1]), which an empty A does not have + # An empty A returns its empty factorization, as for n >= 1 (it returned nothing). + n == 0 && return LU{T,typeof(A),typeof(ipiv)}(A, ipiv, jpiv, convert(LinearAlgebra.BlasInt, 0)) ep = lamch(realt, 'P') smlnum = lamch(realt, 'S') / ep @@ -347,16 +390,19 @@ function getc2!(A::NextLAMatrix{T}, ::CompletePivoting; check::Bool = true, all bignum = sqrt(bignum) end + # n = 1 as LAPACK's ?getc2: a pivot below smlnum is set to smlnum with info = 1. It returned nothing, and a + # tiny pivot raised a MethodError (info[] on an Int); now it returns the factorization and checks it like n >= 2. if n == 1 ipiv[1] = 1 jpiv[1] = 1 if abs(A[1,1]) < smlnum - info[] = 1 + info = 1 A[1,1] = T(smlnum) end - return + check && _check_lu_success(info, allowsingular) + return LU{T,typeof(A),typeof(ipiv)}(A, ipiv, jpiv, convert(LinearAlgebra.BlasInt, info)) end # factorize A using complete pivoting @@ -441,8 +487,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 @@ -475,6 +530,22 @@ function geru!(alpha::T, x::AbstractVector{T}, y::AbstractVector{T}, A::Abstract return end +""" + laswp(A::AbstractMatrix, first::Integer, last::Integer, ipiv::AbstractVector{Int}, incx::Integer) -> nothing + +Applies the row interchanges in `ipiv` to `A`, in place, as LAPACK's `laswp` does: for each +`i` from `first` to `last`, row `i` of `A` is swapped with row `ipiv[i]`, over all columns. + +# Arguments +- `A`: the matrix whose rows are swapped, in place. +- `first`, `last`: the first and last entries of `ipiv` to apply. +- `ipiv`: the pivot indices, as `getrf2!` returns them. +- `incx`: `1` applies the interchanges in order, from `first` to `last`; `-1` applies them in + reverse order, from `last` to `first`; `0` does nothing. The code always steps through + `ipiv` one entry at a time, so use `1` or `-1`. + +Returns `nothing`. +""" function laswp(A::AbstractMatrix{T}, first::Integer, last::Integer, ipiv::AbstractVector{Int}, incx::Integer) where T m, n = size(A) k1 = first diff --git a/src/lu/lu_tiled.jl b/src/dense/lapack/lu/lu_tiled.jl similarity index 91% rename from src/lu/lu_tiled.jl rename to src/dense/lapack/lu/lu_tiled.jl index 9893d2e6..9408c28b 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,25 @@ 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. + +It never pivots across tiles, so it is not stable on general matrices: about 1 random matrix in +1000 hits a tiny or zero pivot, giving a wrong result or `info > 0` with no warning. Use it for +diagonally dominant matrices, or ones that need only in-tile pivoting. + +# 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) + 1024I; # diagonally dominant + +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 83% rename from src/lu/reclu.jl rename to src/dense/lapack/lu/reclu.jl index 851e53c3..5b448691 100644 --- a/src/lu/reclu.jl +++ b/src/dense/lapack/lu/reclu.jl @@ -24,6 +24,18 @@ _lu_leaf!(A::AbstractMatrix) = (LinearAlgebra.lu!(A, LinearAlgebra.NoPivot()); A # unpivoted leaf factorisation. vicki-development's value; not tuned. const LU_BLOCK_SIZE = 2048 +# A failure found in a trailing block is reported at its place in the whole matrix: the block starts +# after `offset` rows and columns (LAPACK's INFO counts from the matrix's first column). +function _with_info_offset(f, offset::Integer) + try + return f() + catch e + e isa LinearAlgebra.ZeroPivotException && throw(LinearAlgebra.ZeroPivotException(e.info + offset)) + e isa LinearAlgebra.PosDefException && throw(LinearAlgebra.PosDefException(e.info + offset)) + rethrow() + end +end + export lu_recursive! """ @@ -31,7 +43,7 @@ export lu_recursive! Recursive unpivoted LU of a square matrix, in place: `A = L * U` with `L` unit lower triangular and `U` upper triangular, packed into `A`. The recursion splits `n` at the largest -power of two below it (at `n ÷ 2` when `n` is one) and factors blocks of at most `block_size` +power of two below it (at `n ÷ 2` when `n` is a power of two) and factors blocks of at most `block_size` rows without pivoting, keeping the bulk of operations in `A`'s precision. [`lu_recursive_nopiv!`](@ref) takes a matrix of any shape. @@ -39,6 +51,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")) @@ -73,7 +97,7 @@ function lu_recursive!(A::AbstractMatrix, block_size::Integer=LU_BLOCK_SIZE) recgemm!(-one(T), A21, A12, one(T), A22) - lu_recursive!(A22, block_size) + _with_info_offset(() -> lu_recursive!(A22, block_size), n1) return A end @@ -108,7 +132,7 @@ export lu_recursive_nopiv! Recursive unpivoted LU of a matrix of any shape, in place: `A = L * U` with `L` unit lower trapezoidal and `U` upper trapezoidal, packed into `A`. -Halves the columns, factors the left panel over the full height, solves for the +Splits at half the shorter side, factors the left panel over the full height, solves for the `U` block to its right and updates the trailing block before recurring into it. [`lu_recursive!`](@ref) is the square-only counterpart; prefer it when `A` is square, and this when it is not. @@ -117,6 +141,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")) @@ -163,7 +201,7 @@ function lu_recursive_nopiv!(A::AbstractMatrix, block_size::Integer=LU_BLOCK_SIZ # A22 -= L21 * U12, then the same recursion on what is left. recgemm!(-one(T), A21, A12, one(T), A22) - lu_recursive_nopiv!(A22, block_size) + _with_info_offset(() -> lu_recursive_nopiv!(A22, block_size), n1) return A end diff --git a/src/geqr2.jl b/src/dense/lapack/qr/geqr2.jl similarity index 82% rename from src/geqr2.jl rename to src/dense/lapack/qr/geqr2.jl index c0a841fd..c2f687ae 100644 --- a/src/geqr2.jl +++ b/src/dense/lapack/qr/geqr2.jl @@ -1,23 +1,3 @@ -""" - geqr2!(m, n, A, tau, work) - -Compute unblocked QR factorization of an m-by-n matrix A using Householder reflectors. -The matrix A is overwritten with the Q and R factors. - -# Arguments -- `m`: Number of rows in matrix A -- `n`: Number of columns in matrix A -- `A`: Input matrix (m × n), modified in place to contain Q and R factors -- `tau`: Output vector of scalar factors (length min(m,n)) -- `work`: Workspace vector (length n) - -# Algorithm -Uses Householder reflectors H(i) to zero out elements below the diagonal. -For each column i, generates H(i) and applies it to remaining columns. - -Implemented as a KernelAbstractions kernel (single work item), runs on any KA backend -(CPU, CUDA, ROCm, oneAPI, Metal) without CPU copies. -""" # Kernel: single work item runs full sequential QR (larfg + larf inlined) # unsafe_indices=true: no @index(Global) needed for single work-item @kernel unsafe_indices=true function geqr2_kernel!(A, tau, work, m::Int, n::Int) @@ -38,19 +18,18 @@ Implemented as a KernelAbstractions kernel (single work item), runs on any KA ba alpha = @inbounds A[i, i] alphar = real(alpha) alphai = imag(alpha) - xnorm_sq = zero(real(T)) + xnorm_sq = zero(_hh_acc(real(T))) # Float32 for Float16 (B37) for p in 1:len-1 vp = @inbounds A[i+p, i] - xnorm_sq += real(vp)^2 + imag(vp)^2 + xnorm_sq += _hh_acc(real(T))(real(vp))^2 + _hh_acc(real(T))(imag(vp))^2 end - xnorm = sqrt(xnorm_sq) - if xnorm == zero(real(T)) && alphai == zero(real(T)) + if iszero(xnorm_sq) && alphai == zero(real(T)) @inbounds tau[i] = zero0 continue end - beta = -copysign(sqrt(alphar^2 + alphai^2 + xnorm_sq), alphar) + beta = _hh_beta(alphar, alphai, xnorm_sq) tau_val = if T <: Complex # Avoid global `im` - oneAPI SPIR-V rejects addrspacecast of @_j_const_1. # Use Base.Complex(re, im) to avoid T(...) which KA may treat as calling a value. @@ -58,13 +37,13 @@ Implemented as a KernelAbstractions kernel (single work item), runs on any KA ba im_part = -alphai / beta Complex(re, im_part) else - (beta - alphar) / beta + _hh_tau(beta, alphar) end # Avoid complex division - it can emit @_j_const_1. Use explicit 1/z = conj(z)/abs2(z) denom = alpha - beta dr, di = real(denom), imag(denom) abs2_d = dr * dr + di * di - scale = T <: Complex ? Complex(dr / abs2_d, -di / abs2_d) : one / denom + scale = T <: Complex ? Complex(dr / abs2_d, -di / abs2_d) : _hh_rcp(alpha, beta) for p in 1:len-1 @inbounds A[i+p, i] *= scale @@ -104,6 +83,28 @@ Implemented as a KernelAbstractions kernel (single work item), runs on any KA ba end end +""" + geqr2!(m, n, A, tau, work) + +Compute unblocked QR factorization of an m-by-n matrix A using Householder reflectors. +The matrix A is overwritten with the Q and R factors. + +# Arguments +- `m`: Number of rows in matrix A +- `n`: Number of columns in matrix A +- `A`: Input matrix (m × n), modified in place to contain Q and R factors +- `tau`: Output vector of scalar factors (length min(m,n)) +- `work`: Workspace vector (length n) + +Returns `nothing`. Negative `m` or `n` throws `ArgumentError`. + +# Algorithm +Uses Householder reflectors H(i) to zero out elements below the diagonal. +For each column i, generates H(i) and applies it to remaining columns. + +Implemented as a KernelAbstractions kernel (single work item), runs on any KA backend +(CPU, CUDA, ROCm, oneAPI, Metal) without CPU copies. +""" function geqr2!(m::Integer, n::Integer, A::AbstractMatrix{T}, tau::AbstractVector{T}, work::AbstractVector{T}) where {T} if m < 0 throw(ArgumentError("illegal value of m: $m")) @@ -121,17 +122,31 @@ function geqr2!(m::Integer, n::Integer, A::AbstractMatrix{T}, tau::AbstractVecto end """ - geqr2!(A) -> (A, tau) + geqr2!(A, tau) Helper function for unblocked QR factorization using Householder reflectors. +Allocates the workspace and calls `geqr2!(m, n, A, tau, work)`. # Arguments -- `A`: Input matrix (m × n), modified in place -- `tau`: Output vector of scalar factors (length min(m,n)) +- `A`: Input matrix (m × n), modified in place to contain Q and R factors +- `tau`: Output vector of scalar factors (length min(m,n)), filled in place # Returns -- Modified `A` containing Q and R factors -- `tau`: Vector of scalar factors (length min(m,n)) +- `nothing`. The results are in `A` and `tau`. + +# 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 84% rename from src/geqrt.jl rename to src/dense/lapack/qr/geqrt.jl index f1e070ba..3b41508e 100644 --- a/src/geqrt.jl +++ b/src/dense/lapack/qr/geqrt.jl @@ -68,18 +68,32 @@ function geqrt!(m::Integer, n::Integer, ib::Integer, A::AbstractMatrix{T}, T_mat end """ - geqrt!(A, ib) -> (A, T, tau) + geqrt!(A, T) Helper function for blocked QR factorization. Computes A = Q*R where Q is orthogonal and R is upper triangular. # Arguments - `A`: Input matrix (m × n), modified in place to contain R in upper triangle and Q factors below -- `ib`: Block size for the factorization +- `T`: Output matrix (ib × n) for the block reflector factors, filled in place. + The block size is `ib = size(T, 1)`. # Returns -- 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) +- `nothing`. The results are in `A` and `T`. The scalar factors `tau` are + computed in a temporary vector and not returned. + +# 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 81% rename from src/larf.jl rename to src/dense/lapack/qr/larf.jl index 1180703c..e6a571b8 100644 --- a/src/larf.jl +++ b/src/dense/lapack/qr/larf.jl @@ -21,9 +21,10 @@ where tau is a scalar and v is a vector. - `work`: Workspace array # Algorithm -The elementary reflector H is applied optimally by exploiting the structure -of the reflector. The algorithm scans for the effective length of the reflector -vector and the effective dimensions of the matrix to minimize operations. +The reflector is applied with full sizes: all m (side = 'L') or n (side = 'R') +entries of v and the whole of C are used. There is no scan for trailing zeros, +so no scalar indexing is needed on a GPU. (`ilazlc` and `ilazlr`, which did that +scan, are no longer called.) For side = 'L': Computes C := H * C = (I - tau * v * v^H) * C For side = 'R': Computes C := C * H = C * (I - tau * v * v^H) @@ -33,11 +34,13 @@ This is a low-level computational routine used internally by higher-level QR factorization algorithms. The workspace array must be properly allocated. """ function larf!(side::Char, m::Integer, n::Integer, v::AbstractVector{T}, incv::Integer, tau::T, C::AbstractMatrix{T}, work::AbstractVector{T}) where {T} + side = uppercase(side) # flags in either case, as BLAS and LAPACK take them + side in ('L', 'R') || throw(ArgumentError("Invalid side parameter: '$side'. Must be 'L' or 'R'")) # any other side would be read as 'R' one0 = oneunit(eltype(C)) zero0 = zero(eltype(C)) if tau == zero0 - return + return C end # Use full dimensions (GPU-agnostic: avoids scalar indexing in ilazlc/ilazlr and v-scan) @@ -68,6 +71,7 @@ function larf!(side::Char, m::Integer, n::Integer, v::AbstractVector{T}, incv::I # Step 2: C := C - tau * w * v^H (rank-1 update) gerc!(-tau, wv, vv, cv) end + return C end """ @@ -148,16 +152,17 @@ function ilazlr(m, n, a) end """ - larf!(side, A, tau, C) -> C + larf!(side, v, incv, tau, C) -> C -Apply an elementary reflector H to a matrix C, where H = I - tau * A * A^H. +Apply an elementary reflector H to a matrix C, where H = I - tau * v * v^H. This is a high-level interface to the elementary reflector application routine. The reflector can be applied from either the left (H*C) or right (C*H) side. # Arguments - `side`: Character specifying application side ('L' for left, 'R' for right) -- `A`: Vector defining the elementary reflector +- `v`: Vector defining the elementary reflector +- `incv`: Increment for the elements of v (typically 1) - `tau`: Scalar factor for the reflector - `C`: Matrix to be transformed in-place @@ -165,19 +170,26 @@ The reflector can be applied from either the left (H*C) or right (C*H) side. - The modified matrix `C` # Input Validation -- For side='L': length(A) must equal number of rows in C -- For side='R': length(A) must equal number of columns in C +- For side='L': length(v) must equal number of rows in C +- For side='R': length(v) must equal number of columns in C +- Otherwise, or if `side` is not 'L' or 'R', throws `ArgumentError` + +# Examples +```jldoctest +julia> using LinearAlgebra + +julia> C = rand(1024, 1024); v = rand(1024); tau = 2 / (v' * v); + +julia> HC = (I - tau * v * v') * C; -# Example -```julia -# Apply reflector from left: C := H * C -larf!('L', v, tau, C) +julia> NextLA.larf!('L', v, 1, tau, C); # C := H * C -# Apply reflector from right: C := C * H -larf!('R', v, tau, C) +julia> C ≈ HC +true ``` """ function larf!(side::Char, v::AbstractVector{T}, incv::Integer, tau::T, C::AbstractMatrix{T}) where {T} + side = uppercase(side) # flags in either case, as BLAS and LAPACK take them m, n = size(C) # Input validation with descriptive error messages if side == 'L' diff --git a/src/larfb.jl b/src/dense/lapack/qr/larfb.jl similarity index 78% rename from src/larfb.jl rename to src/dense/lapack/qr/larfb.jl index 55b0e466..2ae77a1c 100644 --- a/src/larfb.jl +++ b/src/dense/lapack/qr/larfb.jl @@ -1,3 +1,6 @@ +# Hook for a vendor block-reflector update; the portable code below runs when it returns false. +_larfb_vendor!(side, trans, m, n, k, V, T_mat, C, work) = false + """ larfb!(side, trans, direct, storev, m, n, k, v, ldv, t, c, work) @@ -12,11 +15,11 @@ Implemented with Julia internal functions for matrix multiplication - 'N' : apply H - 'C' : apply H^H - 'direct': indicates how H is formed from product of elementary reflectors - - 'F' : H = H(1) H(2) ... H(k) (Forward) - - 'B' : H = H(k) ... H(2) H(1) (Backward) + - 'F' : H = H(1) H(2) ... H(k) (Forward); the only value implemented + - 'B' : H = H(k) ... H(2) H(1) (Backward); not implemented, throws `ArgumentError` - 'storev': indcicates how the vectors which define the elementary reflectors are stored - - 'C' : columnwise - - 'R' : rowwise + - 'C' : columnwise; the only value implemented + - 'R' : rowwise; not implemented, throws `ArgumentError` - 'm': the number of rows of matrix c - 'n': the number of columns of matrix c - 'k': the order of marix t (= the number of elementary reflectors whose roduct defines the block reflector) @@ -35,6 +38,7 @@ Implemented with Julia internal functions for matrix multiplication - 'work': dimension (ldwork, k) """ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, n::Integer, k::Integer, V::AbstractMatrix{T}, ldv::Integer, T_mat::AbstractMatrix{T}, C::AbstractMatrix{T}, work::AbstractMatrix{T}) where {T} + side, trans, direct, storev = uppercase(side), uppercase(trans), uppercase(direct), uppercase(storev) # flags in either case, as BLAS and LAPACK take them if m <= 0 || n <= 0 || k <= 0 return end @@ -51,6 +55,9 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, throw(ArgumentError("trans must be 'N', 'C', or 'T', got '$trans'")) end + # A backend extension may apply the block reflector with its vendor BLAS (returns true). + _larfb_vendor!(side, trans, m, n, k, V, T_mat, C, work) && return + Tzero = zero(T) one = oneunit(T) @@ -88,7 +95,7 @@ function larfb!(side::Char, trans::Char, direct::Char, storev::Char, m::Integer, 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' @@ -163,11 +170,11 @@ block reflector coefficient matrix. - 'N': Apply H (no conjugate transpose) - 'C': Apply H^H (conjugate transpose) - `direct`: Character indicating how H is formed from elementary reflectors - - 'F': H = H(1) H(2) ... H(k) (Forward - first k reflectors) - - 'B': H = H(k) ... H(2) H(1) (Backward - last k reflectors) + - 'F': H = H(1) H(2) ... H(k) (Forward); the only value implemented + - 'B': H = H(k) ... H(2) H(1) (Backward); not implemented, throws `ArgumentError` - `storev`: Character indicating how reflector vectors are stored in V - - 'C': Reflector vectors stored columnwise in V - - 'R': Reflector vectors stored rowwise in V + - 'C': Reflector vectors stored columnwise in V; the only value implemented + - 'R': Reflector vectors stored rowwise in V; not implemented, throws `ArgumentError` - `V`: Matrix containing the elementary reflector vectors - `T`: Upper triangular k×k matrix with block reflector coefficients - `C`: m×n matrix to be transformed in-place @@ -181,16 +188,24 @@ 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} + side, trans, direct, storev = uppercase(side), uppercase(trans), uppercase(direct), uppercase(storev) # flags in either case, as BLAS and LAPACK take them # Determine dimensions m, n = size(C) k = size(T_mat, 1) diff --git a/src/larfg.jl b/src/dense/lapack/qr/larfg.jl similarity index 55% rename from src/larfg.jl rename to src/dense/lapack/qr/larfg.jl index e7d3ae99..37855a33 100644 --- a/src/larfg.jl +++ b/src/dense/lapack/qr/larfg.jl @@ -1,3 +1,19 @@ +# Float16 squares leave Float16's range (entries below about 2e-4 underflow, column norms above 256 +# overflow), so a Float16 reflector sums its squares in Float32 and rounds β once. +@inline _hh_acc(::Type{Float16}) = Float32 +@inline _hh_acc(::Type{R}) where {R} = R + +# β = -sign(αr) ‖[α; x]‖ from α's parts and ‖x‖² (in the type _hh_acc gives), rounded to αr's type. +@inline function _hh_beta(alphar::R, alphai::R, xnorm_sq) where {R} + W = typeof(xnorm_sq) + return R(-copysign(sqrt(W(alphar)^2 + W(alphai)^2 + xnorm_sq), W(alphar))) +end + +# τ = (β - αr)/β and 1/(α - β) for a real reflector, in the type _hh_acc gives: in Float16, |α - β| can +# exceed floatmax or fall below 1/floatmax. +@inline _hh_tau(beta::R, alphar::R) where {R} = (W = _hh_acc(R); R((W(beta) - W(alphar)) / W(beta))) +@inline _hh_rcp(alpha::R, beta::R) where {R} = (W = _hh_acc(R); Base.one(W) / (W(alpha) - W(beta))) + """ larfg!(n, alpha, x, incx, tau) @@ -14,7 +30,7 @@ and produces [beta; 0] where beta has the same magnitude as the original vector. - `n`: Order of the reflector (length of full vector [alpha; x]) - `alpha`: Scalar element, the first component of the vector - `x`: Vector of length n-1, remaining components of the vector -- `incx`: Increment for elements of x (typically 1) +- `incx`: Ignored; all of `x` is used with unit stride (kept for the LAPACK calling sequence) - `tau`: Output scalar factor for the reflector # Returns @@ -39,6 +55,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)) @@ -59,9 +87,9 @@ function larfg!(n::Integer, alpha::T, x::AbstractVector{T}, incx::Integer, tau:: tau = zero0 else # Compute beta = -sign(alphr) * ||[alpha, x]|| - beta = -copysign(sqrt(alphr^2 + alphi^2 + xnorm^2), alphr) + beta = _hh_beta(alphr, alphi, _hh_acc(typeof(alphr))(xnorm)^2) # Machine parameters for safe scaling - safmin = lamch(eltype(alphr), 'S') / lamch(eltype(alphr), 'E') + safmin = lamch(eltype(alphr), 'S') / eltype(alphr)(lamch(eltype(alphr), 'E')) # lamch 'E' is Float64 for Float16/Float32 rsafmn = one / safmin knt = 0 @@ -81,18 +109,18 @@ function larfg!(n::Integer, alpha::T, x::AbstractVector{T}, incx::Integer, tau:: if T <: Complex alpha = alphr + im * alphi end - beta = -copysign(sqrt(alphr^2 + alphi^2 + xnorm^2), alphr) + beta = _hh_beta(alphr, alphi, _hh_acc(typeof(alphr))(xnorm)^2) end # Compute tau based on number type if T <: Complex tau = (beta - alphr) / beta - im * alphi / beta else - tau = (beta - alphr) / beta + tau = _hh_tau(beta, alphr) end # Scale x to form the reflector vector - x .*= (one / (alpha - beta)) + x .*= (T <: Complex ? one / (alpha - beta) : _hh_rcp(alpha, beta)) # Scale beta back if we scaled up for j in 1:knt @@ -106,36 +134,41 @@ function larfg!(n::Integer, alpha::T, x::AbstractVector{T}, incx::Integer, tau:: end """ - larfg!(x) -> (alpha, tau, x_updated) + larfg!(alpha, x, incx, tau) -> (alpha, tau) -Generate an elementary reflector H such that H * x produces a vector -with all but the first element equal to zero. +Generate an elementary reflector H such that H * [alpha; x] = [beta; 0]. -This is a high-level interface to the elementary reflector generation routine. -Given a vector x, it computes a Householder reflector H = I - tau * v * v^H -that zeros out all but the first component. +This is a short form of `larfg!(n, alpha, x, incx, tau)` with `n = length(x) + 1`. +It computes a Householder reflector H = I - tau * v * v^H with v = [1; x_out]. # Arguments -- `x`: Vector to be transformed (will be modified in-place) +- `alpha`: First component of the vector +- `x`: Remaining components; overwritten with v[2:end] +- `incx`: Ignored; all of `x` is used with unit stride +- `tau`: Input scalar; its value is not used # Returns -- `alpha`: The resulting first component (beta) +- `alpha`: The new first component (beta) - `tau`: Scalar factor of the elementary reflector -- `x_updated`: The updated vector with first component as alpha, rest as reflector vector -# Input Validation -- Vector must have at least one element +If `x` is empty, `alpha` is returned unchanged and `tau` is zero. + +# 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]; -# 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 +julia> y - tau * v * (v' * y) ≈ [beta; zeros(1023)] # H * y = [beta; 0] +true ``` # Mathematical Background -Creates H such that H * x = [||x||; 0; 0; ...] where the sign is chosen -to avoid cancellation. The reflector vector is stored in x_new[2:end]. +Creates H such that H * [alpha; x] = [beta; 0; 0; ...] with +beta = -sign(real(alpha)) * ||[alpha; x]||. The sign is chosen to avoid +cancellation. On return, `x` holds v[2:end]. """ function larfg!(alpha::T, x::AbstractVector{T}, incx::Integer, tau::T) where {T} n = length(x) + 1 diff --git a/src/larft.jl b/src/dense/lapack/qr/larft.jl similarity index 86% rename from src/larft.jl rename to src/dense/lapack/qr/larft.jl index b96b2c6d..ea069f4f 100644 --- a/src/larft.jl +++ b/src/dense/lapack/qr/larft.jl @@ -1,48 +1,3 @@ -""" - larft!(direct, storev, n, k, v, tau, T_mat) - -Form the triangular factor T of a complex block reflector H of order n, -where H is defined as a product of k elementary reflectors. - -The block reflector H has the form: -H = I - V * T * V^H - -where V is n-by-k and contains the elementary reflector vectors, and T is -the k-by-k upper triangular factor computed by this routine. - -Implemented as a KernelAbstractions kernel (single work item), runs on any KA backend -(CPU, CUDA, ROCm, oneAPI, Metal) without CPU copies. - -# Arguments -- `direct`: Character indicating the order of the elementary reflectors - - 'F': H = H(1) H(2) ... H(k) (Forward) - - 'B': H = H(k) ... H(2) H(1) (Backward) -- `storev`: Character indicating how the reflector vectors are stored in V - - 'C': Columnwise storage (V is n-by-k) - - 'R': Rowwise storage (V is k-by-n) -- `n`: Order of the reflector H -- `k`: Number of elementary reflectors (order of T) -- `v`: Matrix containing the elementary reflector vectors -- `tau`: Array containing the scalar factors of the elementary reflectors -- `T_mat`: k-by-k matrix where the triangular factor T will be stored - -# Algorithm -The algorithm computes T such that H = I - V * T * V^H where each column -(or row) of V represents an elementary reflector. The triangular structure -ensures efficient application of the block reflector. - -For forward direction (direct='F'): -- T[i,i] = tau[i] (diagonal elements) -- T[j,i] = -tau[i] * V[i,j] * T[j,j:i-1] for j < i (upper triangular part) - -For backward direction (direct='B'): -- T[i,i] = tau[i] (diagonal elements) -- T[j,i] = -tau[i] * V[j,i] * T[i+1:j,i] for j > i (lower triangular part) - -# Notes -This is the core computational routine for forming block reflector coefficients. -The matrix T enables efficient application of multiple reflectors simultaneously. -""" # Kernel: single work item runs full sequential larft loop (no scalar indexing from host) # unsafe_indices=true: no @index(Global) needed for single work-item @kernel unsafe_indices=true function larft_kernel!(direct::Char, storev::Char, V, tau, T_mat, work, n::Int, k::Int) @@ -202,7 +157,59 @@ The matrix T enables efficient application of multiple reflectors simultaneously end end +""" + larft!(direct, storev, n, k, v, tau, T_mat) + +Form the triangular factor T of a complex block reflector H of order n, +where H is defined as a product of k elementary reflectors. + +The block reflector H has the form: +H = I - V * T * V^H + +where V is n-by-k and contains the elementary reflector vectors, and T is +the k-by-k triangular factor computed by this routine: upper triangular for +direct = 'F', lower triangular for direct = 'B'. + +Implemented as a KernelAbstractions kernel (single work item), runs on any KA backend +(CPU, CUDA, ROCm, oneAPI, Metal) without CPU copies. + +# Arguments +- `direct`: Character indicating the order of the elementary reflectors + - 'F': H = H(1) H(2) ... H(k) (Forward) + - 'B': H = H(k) ... H(2) H(1) (Backward) +- `storev`: Character indicating how the reflector vectors are stored in V + - 'C': Columnwise storage (V is n-by-k) + - 'R': Rowwise storage (V is k-by-n) +- `n`: Order of the reflector H +- `k`: Number of elementary reflectors (order of T) +- `v`: Matrix containing the elementary reflector vectors +- `tau`: Array containing the scalar factors of the elementary reflectors +- `T_mat`: k-by-k matrix where the triangular factor T will be stored + +Writes T into `T_mat` and returns `nothing`. + +# Algorithm +The algorithm computes T such that H = I - V * T * V^H where each column +(or row) of V represents an elementary reflector. The triangular structure +ensures efficient application of the block reflector. + +For forward direction (direct='F'): +- T[i,i] = tau[i] (diagonal elements) +- T[j,i] = -tau[i] * V[i,j] * T[j,j:i-1] for j < i (upper triangular part) + +For backward direction (direct='B'): +- T[i,i] = tau[i] (diagonal elements) +- T[j,i] = -tau[i] * V[j,i] * T[i+1:j,i] for j > i (lower triangular part) + +# Notes +This is the core computational routine for forming block reflector coefficients. +The matrix T enables efficient application of multiple reflectors simultaneously. +""" function larft!(direct::Char, storev::Char, n::Integer, k::Integer, V::AbstractMatrix{T}, tau::AbstractVector{T}, T_mat::AbstractMatrix{T}) where {T} + direct, storev = uppercase(direct), uppercase(storev) # flags in either case, as BLAS and LAPACK take them + # Checked: the kernel reads any direct but 'F' as 'B' and any storev but 'C' as 'R'. + direct in ('F', 'B') || throw(ArgumentError("direct must be 'F' or 'B', got '$direct'")) + storev in ('C', 'R') || throw(ArgumentError("storev must be 'C' or 'R', got '$storev'")) if n == 0 return end @@ -213,13 +220,13 @@ function larft!(direct::Char, storev::Char, n::Integer, k::Integer, V::AbstractM end """ - larft(direct, storev, V, tau) -> T + larft!(direct, storev, V, tau, T_mat) Form the triangular factor T of a complex block reflector H from elementary reflectors and their scalar factors. -This is a high-level interface that automatically determines dimensions and -allocates the output matrix. The block reflector H has the form: +This is a high-level interface that determines n and k from the size of V. +It writes T into `T_mat` and returns `nothing`. The block reflector H has the form: H = I - V * T * V^H # Arguments @@ -231,29 +238,43 @@ H = I - V * T * V^H - 'R': Rowwise storage (V is k-by-n) - `V`: Matrix containing the elementary reflector vectors - `tau`: Vector containing scalar factors of the elementary reflectors +- `T_mat`: k-by-k matrix where the triangular factor T is written # Returns -- `T`: k-by-k upper triangular matrix (triangular factor of block reflector) +- `nothing`. `T_mat` holds T: upper triangular for direct = 'F', + lower triangular for direct = 'B'. # Input Validation - Matrix V and vector tau must have compatible dimensions - 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 -``` +- Otherwise throws `ArgumentError` # 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} + direct, storev = uppercase(direct), uppercase(storev) # flags in either case, as BLAS and LAPACK take them + direct in ('F', 'B') || throw(ArgumentError("direct must be 'F' or 'B', got '$direct'")) + storev in ('C', 'R') || throw(ArgumentError("storev must be 'C' or 'R', got '$storev'")) # Determine dimensions based on storage format if storev == 'C' n, k = size(V) diff --git a/src/pamm.jl b/src/dense/lapack/qr/pamm.jl similarity index 92% rename from src/pamm.jl rename to src/dense/lapack/qr/pamm.jl index c7ca2913..baffc932 100644 --- a/src/pamm.jl +++ b/src/dense/lapack/qr/pamm.jl @@ -6,14 +6,14 @@ Parallel matrix multiplication kernel for block reflector applications. This routine performs specialized matrix operations needed in blocked orthogonal factorizations. It computes either: - W = A1 + op(V) * A2 (when op='W') -- A2 = A2 + op(V) * W (when op='A') +- A2 = A2 - op(V) * W (when op='A') where op(V) is V, V^H, V^T depending on the storage and direction parameters. # Arguments - `op`: Operation type - 'W': Compute W = A1 + op(V) * A2 or W = A1 + A2 * op(V) - - 'A': Update A2 = A2 + op(V) * W or A2 = A2 + W * op(V) + - 'A': Update A2 = A2 - op(V) * W or A2 = A2 - W * op(V) - `side`: Which side V is applied - 'L': Left multiplication (op(V) * A2) - 'R': Right multiplication (A2 * op(V)) @@ -45,8 +45,19 @@ 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} + op, side, storev, direct = uppercase(op), uppercase(side), uppercase(storev), uppercase(direct) # flags in either case, as BLAS and LAPACK take them # Input validation with descriptive error messages if op ∉ ('W', 'A') throw(ArgumentError("op must be 'W' or 'A', got '$op'")) @@ -471,51 +482,3 @@ function pamm_a!(left::Bool, colmajor::Bool, forward::Bool, m::Integer, n::Integ end end end - -""" - pamm(op, side, storev, direct, A1, A2, V) -> (A1, A2) - -Performs panel matrix multiplication with automatic workspace allocation. -This is a simplified interface that automatically computes required parameters. - -# Arguments -- 'op': operation type - - 'W': compute workspace - - 'A': apply operation -- 'side': - - 'L' : apply from the left - - 'R' : apply from the right -- 'storev': indicates how the vectors are stored - - 'C' : columnwise - - 'R' : rowwise -- 'direct': indicates direction - - 'F' : forward - - 'B' : backward -- 'A1': first matrix to be updated -- 'A2': second matrix to be updated -- 'V': matrix containing the vectors - -# 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 - m, k = size(A1) - n = size(A2, 2) - l = n - - W = similar(A1, m, k) - - # Call the underlying kernel - pamm(op, side, storev, direct, m, n, k, l, A1, A2, V, W) -end - diff --git a/src/parfb.jl b/src/dense/lapack/qr/parfb.jl similarity index 77% rename from src/parfb.jl rename to src/dense/lapack/qr/parfb.jl index 1e344131..ccfa1d37 100644 --- a/src/parfb.jl +++ b/src/dense/lapack/qr/parfb.jl @@ -21,15 +21,17 @@ or C (conjugate transpose). - `m2::Int`: Number of rows in second matrix block A2 - `n2::Int`: Number of columns in second matrix block A2 - `k::Int`: Number of elementary reflectors -- `l::Int`: Order of the triangular factor in T +- `l::Int`: Size of the triangular part of V: its last `l` rows (storev = 'C') or columns + (storev = 'R') are triangular. Use 0 when V is a full rectangle, as from `tsqrt!`. + Must satisfy 0 ≤ l ≤ k. - `A1::Matrix`: First m1×n1 matrix block to be transformed (modified in-place) - `A2::Matrix`: Second m2×n2 matrix block to be transformed (modified in-place) - `V::Matrix`: Matrix containing elementary reflectors in compact form - `T::Matrix`: Upper triangular factor matrix -- `work::Vector`: Workspace array +- `work::Matrix`: Workspace matrix, at least k×n2 (side = 'L') or m2×k (side = 'R') # Returns -- `Int`: Status code (0 for success, negative for invalid arguments) +- `nothing`. There is no status code: bad input throws `ArgumentError`. # Algorithm The function uses the compact WY representation where H = I - V·T·V^H, performing efficient @@ -40,9 +42,26 @@ 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} + side, trans, direct, storev = uppercase(side), uppercase(trans), uppercase(direct), uppercase(storev) # flags in either case, as BLAS and LAPACK take them if side != 'L' && side != 'R' throw(ArgumentError("illegal value of side")) @@ -84,9 +103,9 @@ function parfb!(side::Char, trans::Char, direct::Char, storev::Char, m1::Integer throw(ArgumentError("illegal value of l")) end - # Quick return if any dimension is zero - if m1 == 0 || n1 == 0 || n2 == 0 || k == 0 - return + # Quick return if any dimension is zero (m2 too: work is not formed then, as in LAPACK dtprfb and PLASMA core_zparfb) + if m1 == 0 || n1 == 0 || m2 == 0 || n2 == 0 || k == 0 + return end # Define scalar constants @@ -191,10 +210,16 @@ function parfb!(side::Char, trans::Char, direct::Char, storev::Char, m1::Integer end """ - parfb(side, trans, direct, storev, A1, A2, V, T) -> (A1, A2) + parfb!(side, trans, direct, storev, A1, A2, V, T) Applies a block reflector or its transpose to a pair of matrices A1 and A2. -This is a simplified interface that automatically computes required parameters. +This is a simplified interface that takes `k = size(T, 1)` and `l = size(V, 2)`, +allocates the workspace and calls the long form. + +Because it sets `l = size(V, 2)`, it treats V as triangular (as from `ttqrt!`). +It gives wrong results when V is a full rectangle, as from `tsqrt!`. For that case +call the long form `parfb!(side, trans, direct, storev, m1, n1, m2, n2, k, l, A1, A2, V, T, work)` +with `l = 0`. # Arguments - `side::Char`: Determines the side of multiplication ('L' for left, 'R' for right) @@ -207,19 +232,26 @@ This is a simplified interface that automatically computes required parameters. - `T::Matrix`: Upper triangular matrix of the block reflector # 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) +- `nothing`. `A1` and `A2` are updated in place. + +# 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} + side, trans, direct, storev = uppercase(side), uppercase(trans), uppercase(direct), uppercase(storev) # flags in either case, as BLAS and LAPACK take them # Determine dimensions m1, n1 = size(A1) m2, n2 = size(A2) diff --git a/src/pemv.jl b/src/dense/lapack/qr/pemv.jl similarity index 80% rename from src/pemv.jl rename to src/dense/lapack/qr/pemv.jl index a801df7c..08ef273d 100644 --- a/src/pemv.jl +++ b/src/dense/lapack/qr/pemv.jl @@ -7,7 +7,13 @@ This function implements efficient matrix-vector multiplication for structured p commonly used in block QR factorization algorithms. It performs operations of the form: Y := alpha * op(A) * X + beta * Y -where op(A) can be A, A^T, or A^H depending on the trans parameter. +where op(A) can be A, A^T, or A^H depending on the trans parameter, and A is a +pentagonal panel: for storev = 'C' its last `l` rows are upper triangular, and for +storev = 'R' its last `l` columns are lower triangular. Entries outside the +triangle in that part are not read. + +Only storev = 'C' with trans = 'T' or 'C', and storev = 'R' with trans = 'N', are +accepted. Other combinations throw `ArgumentError`. # Arguments - `trans::Char`: Transpose operation ('N' for none, 'T' for transpose, 'C' for conjugate transpose) @@ -23,7 +29,8 @@ where op(A) can be A, A^T, or A^H depending on the trans parameter. - `work::Vector`: Workspace array for intermediate computations # Returns -- `Int`: Status code (0 for success, negative for invalid arguments) +- No status code; the result is in `Y`, and the return value is not meaningful. + Bad input throws `ArgumentError`. # Algorithm The function uses block-structured algorithms that partition the matrix and vectors @@ -35,8 +42,23 @@ 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} + trans, storev = uppercase(trans), uppercase(storev) # flags in either case, as BLAS and LAPACK take them # Input validation if trans != 'N' && trans != 'T' && trans != 'C' throw(ArgumentError("illegal value of trans")) @@ -181,34 +203,40 @@ function pemv!(trans::Char, storev::Char, m::Integer, n::Integer, l::Integer, al end """ - pemv(trans, storev, A, X, Y, alpha=1.0, beta=0.0) -> Y + pemv!(trans, storev, alpha, A, x, beta, y) Performs panel matrix-vector multiplication with automatic workspace allocation. -This is a simplified interface that automatically computes required parameters. +This is a simplified interface that takes `m, n = size(A)` and `l = min(m, n)`, +allocates the workspace and calls the long form. # Arguments - `trans::Char`: Transpose operation ('N' for none, 'T' for transpose, 'C' for conjugate transpose) - `storev::Char`: Storage format for vectors ('C' for columnwise, 'R' for rowwise) +- `alpha`: Scalar multiplier for op(A)*x (required; no default) - `A::Matrix`: Matrix for multiplication -- `X::Vector`: Input vector -- `Y::Vector`: Output vector (modified in-place) -- `alpha`: Scalar multiplier for A*X (default: 1.0) -- `beta`: Scalar multiplier for Y (default: 0.0) +- `x::Vector`: Input vector +- `beta`: Scalar multiplier for y (required; no default) +- `y::Vector`: Output vector (modified in-place) # 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) +- The result is in `y`; the return value is not meaningful. + +# 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} + trans, storev = uppercase(trans), uppercase(storev) # flags in either case, as BLAS and LAPACK take them # Determine dimensions m, n = size(A) l = min(m, n) # Default panel size 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 89% rename from src/tsmqr.jl rename to src/dense/lapack/qr/tsmqr.jl index 69be308b..d18e5c5c 100644 --- a/src/tsmqr.jl +++ b/src/dense/lapack/qr/tsmqr.jl @@ -46,6 +46,7 @@ in blocked QR algorithms. The compact WY form enables efficient block updates. """ function tsmqr!(side::Char, trans::Char, m1::Integer, n1::Integer, m2::Integer, n2::Integer, k::Integer, ib::Integer, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, T_mat::AbstractMatrix{T}, work::AbstractVector{T}) where {T} + side, trans = uppercase(side), uppercase(trans) # flags in either case, as BLAS and LAPACK take them # Input validation with descriptive error messages if side != 'L' && side != 'R' @@ -146,7 +147,7 @@ function tsmqr!(side::Char, trans::Char, m1::Integer, n1::Integer, m2::Integer, end """ - tsmqr!(side, trans, A1, A2, V, T, ib) -> (A1, A2) + tsmqr!(side, trans, A1, A2, V, T) Apply orthogonal matrix Q (stored in compact WY form) to triangular-pentagonal matrices. @@ -164,37 +165,42 @@ combined matrix [A1; A2]. - `A1`: Triangular part of matrix (modified in-place) - `A2`: Pentagonal part of matrix (modified in-place) - `V`: Matrix containing elementary reflector vectors -- `T_matrix`: Upper triangular block reflector coefficient matrix -- `ib`: Block size for the compact WY representation +- `T`: Upper triangular block reflector coefficient matrix. The block size is + `ib = size(T, 1)`. # Returns -- Modified `A1`: Triangular part after transformation -- Modified `A2`: Pentagonal part after transformation +- `nothing`. `A1` and `A2` are transformed in place. # Input Validation - For side='L': n2 must equal n1 (same number of columns) - 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) -``` +- Block size ib = size(T, 1) must be positive +- Otherwise throws `ArgumentError` # 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} + side, trans = uppercase(side), uppercase(trans) # flags in either case, as BLAS and LAPACK take them m1, n1 = size(A1) m2, n2 = size(A2) ib, k = size(T_matrix) diff --git a/src/tsqrt.jl b/src/dense/lapack/qr/tsqrt.jl similarity index 84% rename from src/tsqrt.jl rename to src/dense/lapack/qr/tsqrt.jl index e1a290fa..19d9d3d8 100644 --- a/src/tsqrt.jl +++ b/src/dense/lapack/qr/tsqrt.jl @@ -1,47 +1,3 @@ -""" - tsqrt!(m, n, ib, A1, A2, T, tau, work) - -Compute the QR factorization of an (m+n)-by-n triangular-pentagonal matrix -using the compact WY representation. - -This routine computes the QR factorization of a triangular-pentagonal matrix: - [ A1 ] - [ A2 ] -where A1 is n-by-n upper triangular and A2 is m-by-n general. - -The factorization has the form: - [ A1 ] = Q * [ R ] - [ A2 ] [ 0 ] -where Q is orthogonal and R is upper triangular. - -# Arguments -- `m`: Number of rows of the pentagonal part A2 -- `n`: Number of columns of the triangular-pentagonal matrix -- `ib`: Block size for the compact WY representation -- `A1`: n×n upper triangular matrix (modified in-place) -- `A2`: m×n general matrix (modified in-place) -- `T`: ib×n matrix to store block reflector coefficients -- `tau`: Vector of length n to store reflector scalar factors -- `work`: Workspace array of length ib×n - -# Algorithm -The algorithm proceeds in blocks of size ib: -1. For each block, generate elementary reflectors to zero the pentagonal part -2. Apply reflectors to remaining columns using efficient block updates -3. Store reflector coefficients in compact WY form in matrix T - -The compact WY representation allows for efficient application of the -orthogonal factor Q using block operations. - -# Input Validation -All dimension parameters must be non-negative and leading dimensions -must satisfy minimum requirements for valid matrix storage. - -# Notes -This is a low-level computational routine typically called by higher-level -QR factorization interfaces. The matrices A1, A2 are modified in-place -to store the R factor and reflector vectors respectively. -""" # Kernel: single work item runs one block (avoids host-side scalar indexing on GPU) @kernel unsafe_indices=true function tsqrt_block_kernel!(A1, A2, T_matrix, tau, work, m::Int, n::Int, ib::Int, ii::Int, sb::Int) @uniform T = eltype(A1) @@ -52,22 +8,21 @@ to store the R factor and reflector vectors respectively. r = ii + i - 1 alpha = @inbounds A1[r, r] alphar, alphai = real(alpha), imag(alpha) - xnorm_sq = zero(real(T)) + xnorm_sq = zero(_hh_acc(real(T))) # Float32 for Float16 (B37) for p in 1:m vp = @inbounds A2[p, r] - xnorm_sq += real(vp)^2 + imag(vp)^2 + xnorm_sq += _hh_acc(real(T))(real(vp))^2 + _hh_acc(real(T))(imag(vp))^2 end - xnorm = sqrt(xnorm_sq) - if xnorm == zero(real(T)) && alphai == zero(real(T)) + if iszero(xnorm_sq) && alphai == zero(real(T)) @inbounds tau[r] = zero0 continue end - beta = -copysign(sqrt(alphar^2 + alphai^2 + xnorm_sq), alphar) - tau_val = T <: Complex ? Complex((beta - alphar) / beta, -alphai / beta) : (beta - alphar) / beta + beta = _hh_beta(alphar, alphai, xnorm_sq) + tau_val = T <: Complex ? Complex((beta - alphar) / beta, -alphai / beta) : _hh_tau(beta, alphar) denom = alpha - beta dr, di = real(denom), imag(denom) abs2_d = dr * dr + di * di - scale = T <: Complex ? Complex(dr / abs2_d, -di / abs2_d) : one / denom + scale = T <: Complex ? Complex(dr / abs2_d, -di / abs2_d) : _hh_rcp(alpha, beta) for p in 1:m @inbounds A2[p, r] *= scale end @@ -125,6 +80,50 @@ to store the R factor and reflector vectors respectively. end end +""" + tsqrt!(m, n, ib, A1, A2, T, tau, work) + +Compute the QR factorization of an (m+n)-by-n triangular-pentagonal matrix +using the compact WY representation. + +This routine computes the QR factorization of a triangular-pentagonal matrix: + [ A1 ] + [ A2 ] +where A1 is n-by-n upper triangular and A2 is m-by-n general. + +The factorization has the form: + [ A1 ] = Q * [ R ] + [ A2 ] [ 0 ] +where Q is orthogonal and R is upper triangular. + +# Arguments +- `m`: Number of rows of the pentagonal part A2 +- `n`: Number of columns of the triangular-pentagonal matrix +- `ib`: Block size for the compact WY representation +- `A1`: n×n upper triangular matrix (modified in-place) +- `A2`: m×n general matrix (modified in-place) +- `T`: ib×n matrix to store block reflector coefficients +- `tau`: Vector of length n to store reflector scalar factors +- `work`: Workspace array of length ib×n + +# Algorithm +The algorithm proceeds in blocks of size ib: +1. For each block, generate elementary reflectors to zero the pentagonal part +2. Apply reflectors to remaining columns using efficient block updates +3. Store reflector coefficients in compact WY form in matrix T + +The compact WY representation allows for efficient application of the +orthogonal factor Q using block operations. + +# Input Validation +`m`, `n` and `ib` must be non-negative; otherwise throws `ArgumentError`. +Returns `nothing`. + +# Notes +This is a low-level computational routine typically called by higher-level +QR factorization interfaces. The matrices A1, A2 are modified in-place +to store the R factor and reflector vectors respectively. +""" function tsqrt!(m::Integer, n::Integer, ib::Integer, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, T_matrix::AbstractMatrix{T}, tau::AbstractVector{T}, work::AbstractVector{T}) where {T} if m < 0 throw(ArgumentError("m must be non-negative, got $m")) @@ -156,7 +155,7 @@ function tsqrt!(m::Integer, n::Integer, ib::Integer, A1::AbstractMatrix{T}, A2:: end """ - tsqrt!(A1, A2, ib) -> (A1, A2, T, tau) + tsqrt!(A1, A2, T) Compute QR factorization of a triangular-pentagonal matrix using block algorithm. @@ -167,31 +166,36 @@ upper triangular and A2 is general. # Arguments - `A1`: n×n upper triangular matrix (modified in-place to store R factor) - `A2`: m×n general matrix (modified in-place to store reflector vectors) -- `ib`: Block size for the algorithm (typically 32-64 for good performance) +- `T`: ib×n matrix, filled in place with the block reflector coefficients. + The block size is `ib = size(T, 1)` (typically 32-64 for good performance). # Returns -- Modified `A1`: Contains the R factor of the QR factorization -- Modified `A2`: Contains the elementary reflector vectors -- `T`: ib×n matrix containing block reflector coefficients -- `tau`: Length-n vector containing reflector scaling factors +- `nothing`. `A1` holds R, `A2` holds the reflector vectors and `T` holds the + block reflector coefficients. The scalar factors `tau` are computed in a + temporary vector and not returned. # Input Validation -- A1 must be square (n×n) -- 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) -``` +- A1 should be square (n×n) and A2 should have the same number of columns (m×n); + these are not checked +- Block size ib = size(T, 1) must be positive; otherwise throws `ArgumentError` # 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 80% rename from src/ttmqr.jl rename to src/dense/lapack/qr/ttmqr.jl index 57f152c1..9e2b79af 100644 --- a/src/ttmqr.jl +++ b/src/dense/lapack/qr/ttmqr.jl @@ -1,4 +1,5 @@ function ttmqr!(side::Char, trans::Char, m1::Integer, n1::Integer, m2::Integer, n2::Integer, k::Integer, ib::Integer, A1::AbstractMatrix{T}, A2::AbstractMatrix{T}, V::AbstractMatrix{T}, T_mat::AbstractMatrix{T}, work::AbstractVector{T}) where {T} + side, trans = uppercase(side), uppercase(trans) # flags in either case, as BLAS and LAPACK take them # check input arguments if side != 'L' && side != 'R' throw(ArgumentError("illegal value of side")) @@ -65,7 +66,7 @@ function ttmqr!(side::Char, trans::Char, m1::Integer, n1::Integer, m2::Integer, mi = kb mi2 = min(i + kb - 1, m2) ic = i - l = min(kb, max(0, m2 - i)) + l = min(kb, max(0, m2 - i + 1)) # PLASMA core_zttmqr's min(kb, max(0, M2-i)) with i 0-based # Workspace as kb x ni W = reshape(@view(work[1:kb*ni]), kb, ni) parfb!('L', trans, 'F', 'C', mi, ni, mi2, ni2, kb, l, @@ -79,7 +80,7 @@ function ttmqr!(side::Char, trans::Char, m1::Integer, n1::Integer, m2::Integer, ni = kb ni2 = min(i + kb - 1, n2) jc = i - l = min(kb, max(0, n2 - i)) + l = min(kb, max(0, n2 - i + 1)) # PLASMA core_zttmqr's min(kb, max(0, N2-i)) with i 0-based # Workspace as mi x kb W = reshape(@view(work[1:mi*kb]), mi, kb) parfb!('R', trans, 'F', 'C', mi, ni, mi2, ni2, kb, l, @@ -95,7 +96,7 @@ function ttmqr!(side::Char, trans::Char, m1::Integer, n1::Integer, m2::Integer, end """ - ttmqr!(side, trans, A1, A2, V, T, ib) -> (A1, A2) + ttmqr!(side, trans, A1, A2, V, T) Helper function for triangular-trapezoidal matrix transformation. @@ -105,14 +106,30 @@ Helper function for triangular-trapezoidal matrix transformation. - `A1`: Upper triangular matrix to be updated - `A2`: Trapezoidal matrix to be updated - `V`: Reflector vectors matrix -- `T`: Block reflector matrix -- `ib`: Block size +- `T`: Block reflector matrix. The block size is `ib = size(T, 1)`. -# Returns -- Modified `A1` and `A2` +# Returns +- `nothing`. `A1` and `A2` are transformed 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); 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 + side, trans = uppercase(side), uppercase(trans) # flags in either case, as BLAS and LAPACK take them m1, n1 = size(A1) m2, n2 = size(A2) ib = size(T_matrix, 1) diff --git a/src/ttqrt.jl b/src/dense/lapack/qr/ttqrt.jl similarity index 86% rename from src/ttqrt.jl rename to src/dense/lapack/qr/ttqrt.jl index 1ef37a62..d18f0b7d 100644 --- a/src/ttqrt.jl +++ b/src/dense/lapack/qr/ttqrt.jl @@ -9,22 +9,21 @@ mi = min(r, m) # rows from A2 for this column alpha = @inbounds A1[r, r] alphar, alphai = real(alpha), imag(alpha) - xnorm_sq = zero(real(T)) + xnorm_sq = zero(_hh_acc(real(T))) # Float32 for Float16 (B37) for p in 1:mi vp = @inbounds A2[p, r] - xnorm_sq += real(vp)^2 + imag(vp)^2 + xnorm_sq += _hh_acc(real(T))(real(vp))^2 + _hh_acc(real(T))(imag(vp))^2 end - xnorm = sqrt(xnorm_sq) - if xnorm == zero(real(T)) && alphai == zero(real(T)) + if iszero(xnorm_sq) && alphai == zero(real(T)) @inbounds tau[r] = zero0 continue end - beta = -copysign(sqrt(alphar^2 + alphai^2 + xnorm_sq), alphar) - tau_val = T <: Complex ? Complex((beta - alphar) / beta, -alphai / beta) : (beta - alphar) / beta + beta = _hh_beta(alphar, alphai, xnorm_sq) + tau_val = T <: Complex ? Complex((beta - alphar) / beta, -alphai / beta) : _hh_tau(beta, alphar) denom = alpha - beta dr, di = real(denom), imag(denom) abs2_d = dr * dr + di * di - scale = T <: Complex ? Complex(dr / abs2_d, -di / abs2_d) : one / denom + scale = T <: Complex ? Complex(dr / abs2_d, -di / abs2_d) : _hh_rcp(alpha, beta) for p in 1:mi @inbounds A2[p, r] *= scale end @@ -55,10 +54,9 @@ end if i > 1 - mj = min(r - 1, m) # effective rows for triangular A2 (pemv uses min(j-1, m)) for p in 1:i-1 acc = zero0 - for q in 1:mj + for q in 1:min(ii + p - 1, m) # column ii+p-1 of V only down to its diagonal (PLASMA core_zpemv's trapezoid) acc += Complex(real(@inbounds A2[q, ii+p-1]), -imag(@inbounds A2[q, ii+p-1])) * @inbounds A2[q, r] end @inbounds T_matrix[p, r] = (-tau_val) * acc @@ -129,6 +127,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 90% rename from src/unmqr.jl rename to src/dense/lapack/qr/unmqr.jl index 50c69306..4a82bb49 100644 --- a/src/unmqr.jl +++ b/src/dense/lapack/qr/unmqr.jl @@ -50,6 +50,7 @@ This is a core computational routine for applying orthogonal transformations from QR factorizations. It is typically called by higher-level interfaces. """ function unmqr!(side::Char, trans::Char, m::Integer, n::Integer, k::Integer, ib::Integer, A::AbstractMatrix{T}, lda::Integer, T_matrix::AbstractMatrix{T}, C::AbstractMatrix{T}, work::AbstractMatrix{T}) where {T} + side, trans = uppercase(side), uppercase(trans) # flags in either case, as BLAS and LAPACK take them # Input validation with descriptive error messages if side != 'L' && side != 'R' throw(ArgumentError("side must be 'L' or 'R', got '$side'")) @@ -149,7 +150,7 @@ function unmqr!(side::Char, trans::Char, m::Integer, n::Integer, k::Integer, ib: end """ - unmqr!(side, trans, A_qr, T, C, ib) -> C + unmqr!(side, trans, A, T, C) -> C Apply orthogonal matrix Q from QR factorization to matrix C. @@ -164,37 +165,42 @@ to a general matrix C. - `trans`: Character specifying transpose operation - 'N': Apply Q (no transpose) - 'C': Apply Q^H (conjugate transpose) -- `A_qr`: QR factorization result from geqrt! (contains reflector vectors) -- `T_matrix`: Block reflector coefficient matrix from geqrt! +- `A`: QR factorization result from geqrt! (contains reflector vectors) +- `T`: Block reflector coefficient matrix from geqrt!. The block size is `ib = size(T, 1)`. - `C`: Matrix to transform (modified in-place) -- `ib`: Block size used in QR factorization # Returns - Modified matrix `C` after applying the orthogonal transformation # Input Validation - Matrix dimensions must be compatible with the QR factorization -- Block size ib must be positive and consistent with T matrix dimensions +- Block size ib = size(T, 1) must be positive - 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} + side, trans = uppercase(side), uppercase(trans) # flags in either case, as BLAS and LAPACK take them m, n = size(C) ib, k = size(T_matrix) @@ -234,4 +240,5 @@ function unmqr!(side::Char, trans::Char, A::AbstractMatrix{T}, T_matrix::Abstrac # Call the core computational routine unmqr!(side, trans, m, n, k, ib, A, lda, T_matrix, C, work) + return C end diff --git a/src/rotations/lartg.jl b/src/dense/lapack/rotations/lartg.jl similarity index 90% rename from src/rotations/lartg.jl rename to src/dense/lapack/rotations/lartg.jl index f05382d6..62b900c4 100644 --- a/src/rotations/lartg.jl +++ b/src/dense/lapack/rotations/lartg.jl @@ -3,8 +3,8 @@ Generate a plane rotation (Givens rotation) such that: - [ c s ]' * [ f ] = [ r ] - [-s c ] [ g ] [ 0 ] + [ c s ] * [ f ] = [ r ] + [ -conj(s) c ] [ g ] [ 0 ] where `c` is real and `s` may be real or complex. The scalar `r` has the phase of `f` when `f` is nonzero. @@ -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/adaptive.jl b/src/mxp/adaptive.jl deleted file mode 100644 index abad468d..00000000 --- a/src/mxp/adaptive.jl +++ /dev/null @@ -1,68 +0,0 @@ -""" - adaptive_precisions(A, U=DataType[Float32, Float64], n_min=4, epsilon=1e-8; uplo='L') - -Chooses a working precision for each level of the recursive splitting of `A`, and returns them -as a `Vector{DataType}` that can be passed as `precisions` to `FullMixedPrec`, `SymmMixedPrec` -or `TriMixedPrec`. `uplo` is 'L' or 'U' for a triangular or symmetric `A`, of which only that -triangle is read, and 'F' for a full one. `adaptive_precision_LT` is the same function under -its original name. - -`A` is split as those containers split it. At level `k`, counted from 0 at the top, `E_k` is -the largest Frobenius norm of the level's off-diagonal blocks -- the `uplo` one, or both for -'F' -- relative to the norm of the part of `A` that is read, and the target unit roundoff is -`epsilon / (2^((k+1)/2) * E_k)`. The level gets -the coarsest type in `U` whose unit roundoff `eps(T)/2` does not exceed the target, or the -finest if none does. Splitting stops before any block would have fewer than `n_min` rows on -either side, and the result ends with the finest type in `U` for the leaves, so a matrix too -small to split returns that type alone. - -`U` may list `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`, in any -order. The part of `A` that is read must be finite and not zero, `A` square and non-empty, -`uplo` 'L', 'U' or 'F', `n_min` at least 1 and `epsilon` positive. -""" -function adaptive_precisions( - A::AbstractMatrix, - U::AbstractVector{DataType}=DataType[Float32, Float64], - n_min::Integer=4, - epsilon::Real=1e-8; - uplo::Char='L' -) - n = size(A, 1) - n == size(A, 2) || throw(DimensionMismatch("A must be square")) - isempty(A) && throw(ArgumentError("A must not be empty")) - uplo in ('L', 'U', 'F') || throw(ArgumentError("uplo must be 'L', 'U' or 'F'")) - isempty(U) && throw(ArgumentError("U must not be empty")) - all(_supported, U) || - throw(ArgumentError("U must be Float8_E5M2, BFloat16, Float16, Float32 or Float64")) - n_min >= 1 || throw(ArgumentError("n_min must be at least 1")) - epsilon > 0 || throw(ArgumentError("epsilon must be positive")) - norm_A = norm(uplo == 'L' ? LowerTriangular(A) : uplo == 'U' ? UpperTriangular(A) : A) - isfinite(norm_A) || throw(ArgumentError("A must be finite")) - iszero(norm_A) && throw(ArgumentError("A must not be zero")) - - types = sort(unique(U); by=T -> Float64(eps(T)), rev=true) - roundoffs = [Float64(eps(T)) / 2 for T in types] - levels = DataType[] - blocks = [1:n] - k = 0 - while all(r -> length(r) >= 2 && length(r) - _rec_split(length(r)) >= n_min, blocks) - next = UnitRange{Int}[] - level_norm = 0.0 - for r in blocks - mid = _rec_split(length(r)) - top, bottom = r[1:mid], r[mid+1:end] - uplo == 'U' || (level_norm = max(level_norm, norm(view(A, bottom, top)))) - uplo == 'L' || (level_norm = max(level_norm, norm(view(A, top, bottom)))) - push!(next, top, bottom) - end - target = epsilon / (2^((k + 1) / 2) * (level_norm / norm_A)) - i = findfirst(<=(target), roundoffs) - push!(levels, i === nothing ? types[end] : types[i]) - blocks = next - k += 1 - end - push!(levels, types[end]) - return levels -end - -const adaptive_precision_LT = adaptive_precisions diff --git a/src/mxp/blas/gemm/recgemm_mixedprec.jl b/src/mxp/blas/gemm/recgemm_mixedprec.jl new file mode 100644 index 00000000..d8ae20f6 --- /dev/null +++ b/src/mxp/blas/gemm/recgemm_mixedprec.jl @@ -0,0 +1,134 @@ +const RECGEMM_PARALLEL_THRESHOLD = 512 + +# The checks recgemm! makes before it changes C: matching sizes, and A, B and C on one backend. +function _recgemm_check(A, B, C::FullMixedPrec) + n = size(C, 1) + size(A, 1) == n && size(B, 2) == n && size(A, 2) == size(B, 1) || + throw(DimensionMismatch("A must be $n×k and B k×$n, for C $n×$n; got A $(size(A, 1))×$(size(A, 2)) and B $(size(B, 1))×$(size(B, 2))")) + backend = get_backend(C.Base !== nothing ? C.Base : C.A21) + get_backend(A) == backend && get_backend(B) == backend || + throw(ArgumentError("recgemm!: A, B and C must be on one backend; got $(get_backend(A)), $(get_backend(B)) and $backend")) + return nothing +end + + +# The block GEMMs need strided operands: one whose strides are missing or throw (Diagonal, Symmetric, +# sparse, a view of one, ...) is copied to a dense matrix on its backend, before C is changed. +_recgemm_strided(X) = applicable(strides, X) && try strides(X); true catch e; e isa Union{MethodError, ArgumentError} || rethrow(); false end +_recgemm_dense(X::AbstractMatrix) = _recgemm_strided(X) ? X : (allocate(get_backend(X), eltype(X), size(X)) .= X) + +# Operands wider than a Float16 off-diagonal block are rounded to the block's type, each with a scale (a value +# past floatmax is scaled, as the containers store a block), and the scales join alpha: the product then runs on +# Float16 tensor cores with Float32 sums, in place (_update_offdiag!). Measured 2026-11-29: [F16, F16, F32] at +# n = 16384, 2.0x; error 1.8e-4 to 3.1e-4, below Float16's unit roundoff 4.9e-4, which the block's storage costs. +function _recgemm_round(alpha, X, Y, block, site::Symbol) + T = eltype(block) + (sizeof(T) < 4 && (sizeof(eltype(X)) > sizeof(T) || sizeof(eltype(Y)) > sizeof(T))) || return alpha, X, Y + _half_gemm_ok(block) || return alpha, X, Y # Metal and oneAPI: no gemmEx!, so the wider product (as before T47) + Xq, sX = _round_scaled(X, T, Symbol(site, :_X)) + Yq, sY = _round_scaled(Y, T, Symbol(site, :_Y)) + return alpha * Float64(sX) * Float64(sY), Xq, Yq +end + +# X rounded to T in a reused buffer, with a scale when its values pass floatmax(T); non-finite values as they are. +function _round_scaled(X, ::Type{T}, site::Symbol) where {T} + q = _scratch(X, T, size(X), site) + amax = isempty(X) ? 0f0 : maximum(x -> abs(float(x)), X) + isfinite(amax) && !isempty(X) || return (q .= X; (q, 1f0)) + return _quantize_with_amax!(q, X, amax) +end + +""" + recgemm!(alpha, A, B, beta, C::FullMixedPrec; + parallel=size(C, 1) > RECGEMM_PARALLEL_THRESHOLD) -> C + +Computes `C = alpha * A * B + beta * C` in place, where `C` is an `n × n` `FullMixedPrec`, `A` +is `n × k` and `B` is `k × n` for any `k`, else `DimensionMismatch`. It walks `C`'s block tree: +`A` is split by rows and `B` by columns at `C`'s split, so each quadrant of `C` takes one +product over the whole `k`, `A[1:mid, :] * B[:, 1:mid]` for `C11`. Off-diagonal blocks are +updated by a GEMM and diagonal blocks recursively. A block stored with a scale factor `s` +holds `C / s`, so its update uses `alpha / s`. Operands wider than a `Float16` off-diagonal +block are rounded to `Float16` first, each with a scale, so the product runs on `Float16` tensor +cores with `Float32` sums; that block is then updated in place (otherwise an off-diagonal block +with less range than `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. This keeps +the error within `Float16`'s unit roundoff, which the `Float16` blocks already cost. The `Float32` +GEMMs run in `Float32`; only inside the mixed-precision `lu_recursive!`, whose TF32 scope they +inherit, may they run on TF32 tensor cores on CUDA. With `parallel`, the four +quadrant updates of the top level run as concurrent tasks (`@async`): on a GPU each task has its +own stream, so their kernels can overlap; on the CPU they take turns and leave the cores to BLAS. + +`C` is the container itself: its `transpose` throws an `ArgumentError` (for `Cᵀ`, pass the +transposed operands into `C`). An `A` or `B` without strides (`Diagonal`, `Symmetric`, a +triangular wrapper, sparse, ...) is first copied to a dense matrix on its backend. Operands on +another backend than `C` throw an `ArgumentError`. + +# 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)) + # No TF32 scope of its own: the Float32 GEMMs stay Float32, as #1-#7 (user, 2026-12-03); inside the mixed LU + # they keep the LU's TF32 scope. + return _recgemm_mixed!(alpha, A, B, beta, C, parallel) +end + +function _recgemm_mixed!(alpha, A, B, beta, C::FullMixedPrec, parallel::Bool) + _recgemm_check(A, B, C) + A, B = _recgemm_dense(A), _recgemm_dense(B) + n = size(C, 1) + + if C.Base !== nothing + _gemm_dispatch!(alpha / C.Base_scale, A, B, beta, C.Base) + return C + end + + mid = size(C.A11, 1) + A1, A2 = view(A, 1:mid, :), view(A, mid+1:n, :) + B1, B2 = view(B, :, 1:mid), view(B, :, mid+1:n) + a12 = alpha / C.A12_scale + a21 = alpha / C.A21_scale + + # Each off-diagonal block takes its product through _update_offdiag!, which raises the block's scale if + # the product took it past floatmax of its type (in place for Float16 blocks with Float16 operands). + function update12() + a, X, Y = _recgemm_round(a12, A1, B2, C.A12, :recgemm_12) + C.A12_scale = _update_offdiag!(P -> _gemm_dispatch!(a, X, Y, beta, P), C.A12, C.A12_scale, X, Y) + end + function update21() + a, X, Y = _recgemm_round(a21, A2, B1, C.A21, :recgemm_21) + C.A21_scale = _update_offdiag!(P -> _gemm_dispatch!(a, X, Y, beta, P), C.A21, C.A21_scale, X, Y) + end + + if parallel + tf = _tf32_on() # task storage is not inherited: inside the mixed LU each task reopens its TF32 scope + @sync begin + @async _with_tf32(() -> recgemm!(alpha, A1, B1, beta, C.A11; parallel=false), tf) + @async _with_tf32(update12, tf) + @async _with_tf32(update21, tf) + @async _with_tf32(() -> recgemm!(alpha, A2, B2, beta, C.A22; parallel=false), tf) + end + else + recgemm!(alpha, A1, B1, beta, C.A11; parallel=false) + update12() + update21() + recgemm!(alpha, A2, B2, beta, C.A22; parallel=false) + end + return C +end + +# Cᵀ = alpha * A * B + beta * Cᵀ is C = alpha * Bᵀ * Aᵀ + beta * C: the container is passed, not its transpose. +recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::TransposedMixedPrec; parallel::Bool=false) = + throw(ArgumentError("recgemm!: C must be the container itself, not its transpose; for Cᵀ use " * + "recgemm!(alpha, copy(transpose(B)), copy(transpose(A)), beta, C)")) diff --git a/src/mxp/blas/syrk/recsyrk_mixedprec.jl b/src/mxp/blas/syrk/recsyrk_mixedprec.jl new file mode 100644 index 00000000..feb6be3c --- /dev/null +++ b/src/mxp/blas/syrk/recsyrk_mixedprec.jl @@ -0,0 +1,84 @@ +# The SymmMixedPrec methods of recsyrk!. Source: vicki-development @ 694d019, +# by Vicki , where they sat in src/recsyrk.jl. + +""" + recsyrk!(alpha, A, beta, C::SymmMixedPrec) -> C + +Computes `C = alpha * A * transpose(A) + beta * C` in place on the stored triangle (`C.uplo`) +of the `n × n` `SymmMixedPrec` `C`, where `A` is `n × k`. It walks `C`'s block tree: each +off-diagonal block takes one GEMM, and each leaf the dense `recsyrk!`. +A `Float64` leaf updated by `Float16` or `Float32` `A` instead takes `A * transpose(A)` in +`Float32` (summed in `Float32`) and adds it into the leaf in `Float64`. A +block stored with a scale factor `s` holds `C / s`, so its update uses `alpha / s`; an +off-diagonal block with less range than `Float32` is updated in a `Float32` copy (in place, +still summed in `Float32`, when it and `A` are `Float16`) and stored back with its scale raised +when the update took it past `floatmax` of its type. When the first +diagonal block of the top level has more than `RECSYRK_PARALLEL_THRESHOLD` rows, the two +diagonal halves run as concurrent tasks (`@async`), and a leaf follows the dense `recsyrk!` rule; 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")) + parallel = C.Base === nothing && size(C.A11, 1) > RECSYRK_PARALLEL_THRESHOLD + return _recsyrk_mixed!(alpha, A, beta, C; parallel=parallel) +end + +function _recsyrk_mixed!(alpha::Number, A::AbstractMatrix, beta::Number, C::SymmMixedPrec; + parallel::Bool) + if C.Base !== nothing + B = C.Base + if eltype(B) == Float64 && eltype(A) in (Float16, Float32) + # A Float64 leaf updated by narrower rows: the product A*A' runs in Float32 (Float16 A on tensor cores, + # Float32 sums) and is added into the Float64 leaf, which is never rounded (the paper's code rounds the + # leaf to Float32 for the update and back). The Float32 sums cost accuracy where only Float32 blocks feed the + # leaf and the update is large next to the diagonal: README's [Float32, Float64] Cholesky, 2e-8 -> 1.8e-7. + # With a Float16 block, its error dominates and nothing changes. + P = _scratch(B, Float32, size(B), :syrk_leaf_product) + recsyrk!(1f0, A, 0f0, P, size(P, 1); uplo=C.uplo) + a, b, lo = Float64(alpha) / Float64(C.Base_scale), Float64(beta), C.uplo == 'L' + # beta = 0 does not read the leaf, as BLAS syrk (0 * NaN would be NaN). The mask stays inside each + # fused broadcast, so it is computed on the device, not as a host BitMatrix. + r, c = axes(B, 1), axes(B, 2)' + if iszero(b) + B .= ifelse.(_in_stored_triangle.(lo, r, c), a .* P, B) + else + B .= ifelse.(_in_stored_triangle.(lo, r, c), b .* B .+ a .* P, B) + end + return C + end + # The dense SYRK on the leaf with 4096-row leaves, as the other branches' mixed SYRK (not its default 256). + recsyrk!(alpha / C.Base_scale, A, beta, B, 4096; uplo=C.uplo) + return C + end + + n1 = size(C.A11, 1) + A1, A2 = view(A, 1:n1, :), view(A, n1+1:size(A, 1), :) + a = alpha / C.OffDiag_scale + X, Y = C.uplo == 'L' ? (A2, A1) : (A1, A2) + C.OffDiag_scale = _update_offdiag!(P -> _syrk_dispatch!(:GEMM, a, X, Y, beta, P), C.OffDiag, C.OffDiag_scale, X, Y) + + if parallel + @sync begin + @async _recsyrk_mixed!(alpha, A1, beta, C.A11; parallel=false) + @async _recsyrk_mixed!(alpha, A2, beta, C.A22; parallel=false) + end + else + _recsyrk_mixed!(alpha, A1, beta, C.A11; parallel=false) + _recsyrk_mixed!(alpha, A2, beta, C.A22; parallel=false) + end + return C +end diff --git a/src/mxp/trsm/rectrxm_mixed.jl b/src/mxp/blas/trsm/rectrxm_mixed.jl similarity index 55% rename from src/mxp/trsm/rectrxm_mixed.jl rename to src/mxp/blas/trsm/rectrxm_mixed.jl index 225886f0..e083e933 100644 --- a/src/mxp/trsm/rectrxm_mixed.jl +++ b/src/mxp/blas/trsm/rectrxm_mixed.jl @@ -16,8 +16,8 @@ # # Every other case has the same three steps: recurse into one half, update the # other half with the off-diagonal block, recurse into the other half. Only two -# things change between cases, and each has its own helper below: -# - which half goes first (_top_half_first), and +# things change between cases, and _rec_mixed! below decides both: +# - which half goes first, and # - which half the off-diagonal update reads and which it writes. # # Precision @@ -25,13 +25,12 @@ # An off-diagonal block is stored narrow because its precision matters least, # so its update runs at that narrow type (_offdiag_update!). A leaf is a # diagonal block, whose precision matters, so it runs at the wider of its own -# type and B's (_leaf!). B, which accumulates the result, is never rounded. +# type and B's (the leaf branch of _rec_mixed!). B, which accumulates the +# result, is never rounded. const _RecMixedPrec = Union{FullMixedPrec, SymmMixedPrec, TriMixedPrec} const _RecMixedPrecOrTransposed = Union{_RecMixedPrec, TransposedMixedPrec{<:Any, <:_RecMixedPrec}} -_flip(uplo::Char) = uplo == 'L' ? 'U' : 'L' - # --------------------------------------------------------------------------- # Reading one node of the tree. A transposed container is read through its # parent: its children are the parent's children transposed, and its lower @@ -60,35 +59,12 @@ function _children(A::_RecMixedPrec, uplo::Char) end function _children(A::TransposedMixedPrec, uplo::Char) P = parent(A) - offdiag, scale = _offdiag(P, _flip(uplo)) - return (transpose(P.A11), transpose(P.A22), transpose(offdiag), scale, size(P.A11, 1)) -end - -# --------------------------------------------------------------------------- -# Which half goes first -# --------------------------------------------------------------------------- - -# A solve must finish the half that does not depend on the other one first; a -# multiply must finish the half that the other one is added into first, before -# that half is overwritten. Worked out case by case: -# -# func side uplo first half -# 'S' 'L' 'L' top X1 = A11 \ B1 needs nothing else -# 'S' 'L' 'U' bottom X2 = A22 \ B2 needs nothing else -# 'S' 'R' 'L' right X2 = B2 / A22 needs nothing else -# 'S' 'R' 'U' left X1 = B1 / A11 needs nothing else -# 'M' any any the opposite half to the solve with the same side and uplo -# -# "Top" and "left" are both the A11 half, so the rule is: the A11 half goes -# first exactly when (it is a solve) == (side and uplo agree). -function _top_half_first(func::Char, side::Char, uplo::Char) - side_and_uplo_agree = (side == 'L') == (uplo == 'L') - is_solve = func == 'S' - return is_solve == side_and_uplo_agree + offdiag, scale = _offdiag(P, uplo == 'L' ? 'U' : 'L') + return (TransposedMixedPrec(P.A11), TransposedMixedPrec(P.A22), transpose(offdiag), scale, size(P.A11, 1)) end # --------------------------------------------------------------------------- -# The two kinds of work +# The off-diagonal update # --------------------------------------------------------------------------- # C = alpha * block * X + beta * C on the left, or alpha * X * block + beta * C @@ -101,44 +77,6 @@ function _side_gemm!(side::Char, alpha, block, X, beta, C) end end -# Divides (solve) or multiplies (multiply) B by a block's scale: the block holds -# its values divided by that scale, so the result computed from it is off by it. -function _unscale!(func::Char, B::AbstractMatrix, scale) - isone(scale) && return B - if func == 'S' - B ./= scale - else - B .*= scale - end - return B -end - -# The leaf: one dense diagonal block, solved or multiplied by the dense kernels. -# Its precision matters, so the work runs in the wider of the block's type and -# B's and neither is rounded; the kernels take one element type, so whichever of -# the two is narrower is widened for the call. The leaf's scale is applied -# before the result goes back into B, so a narrow B only sees the final values. -function _leaf!(func::Char, side::Char, uplo::Char, diag::Char, block::AbstractMatrix, scale, - B::AbstractMatrix, threshold::Integer) - T_block, T_B = eltype(block), eltype(B) - T_work = promote_type(T_block, T_B) - block_work = T_block == T_work ? block : T_work.(block) - B_work = T_B == T_work ? B : T_work.(B) - - unified_rec(func, side, uplo, block_work, size(block_work, 1), B_work, threshold; unitdiag=(diag == 'U')) - _unscale!(func, B_work, scale) - - B_work === B || copy!(B, B_work) - return B -end - -# B's part X of an off-diagonal product, rounded to the block's storage type T -# the way the containers store a block: with its own scale when its values pass -# floatmax(T), so they are not clipped. A non-finite X, left by an overflowed -# multiply before it, converts as it is. -_narrow(X::AbstractMatrix, ::Type{T}, ::Type{S}) where {T, S} = - all(isfinite, X) ? quantize(X, T, S) : (T.(X), one(S)) - # The off-diagonal update: target = target - scale * block * source for a solve, # target = target + scale * block * source for a multiply (source * block on the # right). `scale` is the block's scale, which turns its stored values back into @@ -162,18 +100,26 @@ function _offdiag_update!(func::Char, side::Char, target::AbstractMatrix, block: end # Case 2: the block is narrower than target, the usual case. The product - # runs at the block's type: source is rounded to it (with a scale of its - # own, which joins the block's in alpha), which adds an error of the order - # the block's storage already carries. The sum accumulates in at least - # Float32 -- gemmEx does this for Float16 -- and is added into target, - # which is never rounded. - source_narrow, source_scale = _narrow(source, T_block, T_target) + # runs at the block's type: source is rounded to it the way the containers + # store a block, with a scale of its own when its values pass floatmax, which + # joins the block's in alpha. That adds an error of the order the block's + # storage already carries. A non-finite source, left by an overflowed multiply + # before it, converts as it is. The sum accumulates in at least Float32 -- + # gemmEx does this for Float16 -- and is added into target, which is never + # rounded. + # One reduction, max |x|, decides both questions: a NaN or Inf comes out as a non-finite max + # (converted as it is), and a finite max gives the scale. Each reduction is a device-to-host + # sync, and all(isfinite) followed by quantize's own max took two. + amax = isempty(source) ? 0f0 : maximum(x -> abs(float(x)), source) + narrow = _scratch(source, T_block, size(source), :offdiag_narrow) + source_narrow, source_scale = + isfinite(amax) && !isempty(source) ? _quantize_with_amax!(narrow, source, amax) : (narrow .= source; (narrow, 1f0)) T_accumulate = sizeof(T_block) < 4 ? Float32 : T_block alpha = T_accumulate(sign * Float64(scale) * Float64(source_scale)) if T_accumulate == T_target _side_gemm!(side, alpha, block, source_narrow, one(T_target), target) else - partial = similar(target, T_accumulate, size(target)) + partial = _scratch(target, T_accumulate, size(target), :offdiag_partial) _side_gemm!(side, alpha, block, source_narrow, zero(T_accumulate), partial) target .+= partial end @@ -187,8 +133,25 @@ end function _rec_mixed!(func::Char, side::Char, uplo::Char, diag::Char, A::_RecMixedPrecOrTransposed, B::AbstractMatrix, threshold::Integer) if _is_leaf(A) + # The leaf: one dense diagonal block, solved or multiplied by the dense + # kernels. Its precision matters, so the work runs in the wider of the + # block's type and B's and neither is rounded; the kernels take one element + # type, so whichever of the two is narrower is widened for the call. The + # block holds its values divided by its scale, so a solve then divides by + # the scale and a multiply multiplies by it, before the result goes back + # into B, so a narrow B only sees the final values. block, scale = _leaf_block(A) - return _leaf!(func, side, uplo, diag, block, scale, B, threshold) + T_block, T_B = eltype(block), eltype(B) + T_work = promote_type(T_block, T_B) + block_work = T_block == T_work ? block : _widened(block, T_work, :leaf_A) + B_work = T_B == T_work ? B : _widened(B, T_work, :leaf_B) + unified_rec(func, side, uplo, block_work, size(block_work, 1), B_work, threshold; + unitdiag=(diag == 'U')) + if !isone(scale) + func == 'S' ? (B_work ./= scale) : (B_work .*= scale) + end + B_work === B || copy!(B, B_work) + return B end A11, A22, offdiag, scale, mid = _children(A, uplo) @@ -202,7 +165,20 @@ function _rec_mixed!(func::Char, side::Char, uplo::Char, diag::Char, A::_RecMixe B1, B2 = view(B, :, 1:mid), view(B, :, mid+1:n) end - if _top_half_first(func, side, uplo) + # A solve must finish the half that does not depend on the other one first; a + # multiply must finish the half that the other one is added into first, before + # that half is overwritten. Worked out case by case: + # + # func side uplo first half + # 'S' 'L' 'L' top X1 = A11 \ B1 needs nothing else + # 'S' 'L' 'U' bottom X2 = A22 \ B2 needs nothing else + # 'S' 'R' 'L' right X2 = B2 / A22 needs nothing else + # 'S' 'R' 'U' left X1 = B1 / A11 needs nothing else + # 'M' any any the opposite half to the solve with the same side and uplo + # + # "Top" and "left" are both the A11 half, so the rule is: the A11 half goes + # first exactly when (it is a solve) == (side and uplo agree). + if (func == 'S') == ((side == 'L') == (uplo == 'L')) A_first, B_first, A_second, B_second = A11, B1, A22, B2 else A_first, B_first, A_second, B_second = A22, B2, A11, B1 @@ -226,65 +202,63 @@ function _rec_mixed!(func::Char, side::Char, uplo::Char, diag::Char, A::_RecMixe end """ - unified_rec_mixed(func, side, uplo, diag, A, B, threshold=256) + unified_rectrxm!(side, uplo, trans, diag, alpha, func, A, B) -> B + unified_rectrxm!(side, uplo, trans, alpha, func, A, B) -> B -Solves (`func = 'S'`) or multiplies (`func = 'M'`) `B` in place by the triangle `uplo` of the -mixed-precision container `A`, or of its `transpose`, on side `side`, without densifying `A`. -`diag = 'U'` takes the diagonal as ones. Each block is used with its scale factor. +`unified_rectrxm!` for a mixed-precision container `A`: solves `op(A) X = alpha B` for `func = +'S'`, or computes `B = alpha op(A) B` for `func = 'M'`, on side `side` (`B * op(A)` for +`'R'`), in place in `B`. `op` is the identity for `trans = 'N'` and the transpose for `'T'` or +`'C'`; `uplo` names the triangle of `A` that is read, and must be `A.uplo` for a +`SymmMixedPrec` or `TriMixedPrec`, which store only that triangle. `diag = 'U'` takes the +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)`, which +throws an `ArgumentError` (a `SymmMixedPrec` is its own transpose, so `transpose(A)` is `A`). +Any other `side`, `uplo`, `trans`, `diag` or `func` throws an `ArgumentError`, and a `B` whose +size does not match `A` a `DimensionMismatch`. -Each block's arithmetic runs at the precision the block is stored in, the precision its values -were chosen to need. An off-diagonal product takes `B`'s part rounded to the block's type, -through a scaled copy so that values past `floatmax` do not overflow, accumulates in at least -`Float32` and is added into `B` without rounding `B`; rounding that part adds an error of the -order the block's storage already carries, and no off-diagonal block is widened. A leaf, a -diagonal block, works in the wider of its type and `B`'s, so neither is rounded. -""" -function unified_rec_mixed( - func::Char, side::Char, uplo::Char, diag::Char, - A::_RecMixedPrecOrTransposed, - B::AbstractMatrix, - threshold::Integer=256 -) - return _rec_mixed!(func, side, uplo, diag, A, B, threshold) -end +# Examples +```jldoctest +julia> using NextLA.MixedPrecision, LinearAlgebra -function unified_rec_mixed( - func::Char, side::Char, uplo::Char, - A::_RecMixedPrecOrTransposed, - B::AbstractMatrix, - threshold::Integer=256 -) - return unified_rec_mixed(func, side, uplo, 'N', A, B, threshold) -end +julia> T = tril(rand(1024, 1024)) + 1024I; B = rand(1024, 512); -""" - unified_rectrxm!(side, uplo, trans, diag, alpha, func, A, B) -> B +julia> M = TriMixedPrec(T, 'L'; precisions = DataType[Float32, Float64]); -`unified_rectrxm!` for a mixed-precision container `A`: solves `op(A) X = alpha B` for -`func = 'S'`, or computes `B = alpha op(A) B` for `func = 'M'`, on side `side` (`B * op(A)` -for `'R'`), in place in `B`. `op` is the identity for `trans = 'N'` and the transpose for `'T'` -or `'C'`; `uplo` names the triangle of `A` that is read and `diag = 'U'` takes its diagonal as -ones. +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, A::_RecMixedPrec, B::AbstractMatrix ) + side, uplo, trans, diag, func = uppercase(side), uppercase(uplo), uppercase(trans), uppercase(diag), uppercase(func) # BLAS takes either case side in ('L', 'R') || throw(ArgumentError("side must be 'L' or 'R', got '$side'")) uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U', got '$uplo'")) trans in ('N', 'T', 'C') || throw(ArgumentError("trans must be 'N', 'T' or 'C', got '$trans'")) diag in ('N', 'U') || throw(ArgumentError("diag must be 'N' or 'U', got '$diag'")) func in ('S', 'M') || throw(ArgumentError("func must be 'S' or 'M', got '$func'")) - op_A, op_uplo = trans == 'N' ? (A, uplo) : (transpose(A), uplo == 'L' ? 'U' : 'L') - func == 'S' && (B .= alpha .* B) - unified_rec_mixed(func, side, op_uplo, diag, op_A, B) - func == 'M' && (B .= alpha .* B) + A isa FullMixedPrec || uplo == A.uplo || + throw(ArgumentError("uplo must be A.uplo, '$(A.uplo)', for a $(nameof(typeof(A))), got '$uplo'")) + size(B, side == 'L' ? 1 : 2) == size(A, 1) || + throw(DimensionMismatch("B must have $(size(A, 1)) $(side == 'L' ? "rows" : "columns") for this A, got $(size(B, 1))×$(size(B, 2))")) + op_A, op_uplo = trans == 'N' ? (A, uplo) : (TransposedMixedPrec(A), uplo == 'L' ? 'U' : 'L') + func == 'S' && !isone(alpha) && (B .= alpha .* B) # alpha == 1: B is already scaled + _with_workspace(() -> _rec_mixed!(func, side, op_uplo, diag, op_A, B, 256)) + func == 'M' && !isone(alpha) && (B .= alpha .* B) return B end +# The container is passed with trans = 'T', not as its transpose. +unified_rectrxm!(side::Char, uplo::Char, trans::Char, diag::Char, alpha::Number, func::Char, + A::TransposedMixedPrec, B::AbstractMatrix) = + throw(ArgumentError("unified_rectrxm!: pass the container itself, not its transpose, with trans flipped and uplo = A.uplo")) + function unified_rectrxm!( side::Char, uplo::Char, trans::Char, alpha::Number, func::Char, - A::_RecMixedPrec, B::AbstractMatrix + A::Union{_RecMixedPrec, TransposedMixedPrec}, B::AbstractMatrix ) return unified_rectrxm!(side, uplo, trans, 'N', alpha, func, A, B) end diff --git a/src/mxp/blocks.jl b/src/mxp/blocks.jl deleted file mode 100644 index d1ff5599..00000000 --- a/src/mxp/blocks.jl +++ /dev/null @@ -1,100 +0,0 @@ -@inline _supported(T) = T in (Float16, _BFloat16, Float32, Float64) || nameof(T) === :Float8_E5M2 - -function _check_args(A::AbstractMatrix, precisions::Vector{DataType}, ::Type{S}) where {S} - size(A, 1) == size(A, 2) || throw(DimensionMismatch("A must be square")) - isempty(precisions) && - throw(ArgumentError("precisions must not be empty")) - all(_supported, precisions) || - throw(ArgumentError("precisions must be Float8_E5M2, BFloat16, Float16, Float32 or Float64")) - S in (Float16, Float32, Float64) || - throw(ArgumentError("scale_type must be Float16, Float32 or Float64")) - isempty(A) && throw(ArgumentError("A must not be empty")) - return nothing -end - -function _store(B::AbstractMatrix, ::Type{T}, ::Type{S}) where {T<:AbstractFloat, S<:AbstractFloat} - alpha = float(maximum(abs, B)) - isfinite(alpha) || throw(ArgumentError("A must be finite")) - limit = convert(typeof(alpha), floatmax(T)) - alpha > limit || return (T.(B), one(S)) - - scale = S(alpha / limit) - scale * limit < alpha && (scale = nextfloat(scale)) - isfinite(scale) || - throw(ArgumentError("A block of A has values too large for $T storage with a $S scale")) - return (T.(clamp.(B ./ convert(typeof(alpha), scale), -limit, limit)), scale) -end - -@inline _unscaled(x, s, ::Type{T}) where {T} = T(x * T(s)) - -# Stores W -- a block's values over its current scale s, held in a type with more -# range than the block's -- back into block, and returns the block's scale. Values -# within floatmax of the block's type keep s; larger ones take a scale raised just -# enough that none is clipped. A non-finite W, or a scale past floatmax of its own -# type, is stored as it is under s, so such an overflow still gives Inf. -function _requantize!(block::AbstractMatrix, W::AbstractMatrix, s::S) where {S<:AbstractFloat} - R = eltype(W) - limit = R(floatmax(eltype(block))) - alpha = maximum(abs, W) - if isfinite(alpha) && alpha > limit - s_new = S(Float64(s) * Float64(alpha) / Float64(limit)) - Float64(s_new) * Float64(limit) < Float64(s) * Float64(alpha) && (s_new = nextfloat(s_new)) - if isfinite(s_new) - g = R(Float64(s_new) / Float64(s)) - block .= clamp.(W ./ g, -limit, limit) - return s_new - end - end - block .= W - return s -end - -# Runs update!(P) on a block's stored values and returns the block's scale. A block -# with less range than Float32 (Float16, Float8) is updated in a Float32 copy P and -# stored back through _requantize!, so an update past floatmax of its type raises its -# scale instead of leaving Inf; a wider block is updated in place and keeps its scale. -function _update_block!(update!, block::AbstractMatrix, scale) - Float64(floatmax(eltype(block))) < Float64(floatmax(Float32)) || (update!(block); return scale) - P = similar(block, Float32, size(block)) - P .= block - update!(P) - return _requantize!(block, P, scale) -end - -@inline _stored(i::Int, j::Int, uplo::Char) = uplo == 'L' ? i >= j : i <= j - -function _triangular_tree(::Type{C}, A::AbstractMatrix, uplo::Char, precisions::AbstractVector{DataType}, ::Type{S}) where {C, S<:AbstractFloat} - n = size(A, 1) - T_Base = precisions[end] - unit_scale = one(S) - if length(precisions) == 1 || n == 1 - base, base_scale = _store(uplo == 'L' ? tril(A) : triu(A), T_Base, S) - return C{T_Base, S}( - nothing, nothing, nothing, - unit_scale, base_scale, base, uplo, n - ) - end - mid = _rec_split(n) - remaining_precisions = @view precisions[2:end] - A11 = _triangular_tree(C, view(A, 1:mid, 1:mid), uplo, remaining_precisions, S) - A22 = _triangular_tree(C, view(A, mid+1:n, mid+1:n), uplo, remaining_precisions, S) - offdiag = uplo == 'L' ? view(A, mid+1:n, 1:mid) : view(A, 1:mid, mid+1:n) - OffDiag, OffDiag_scale = _store(offdiag, precisions[1], S) - return C{T_Base, S}( - A11, A22, OffDiag, - OffDiag_scale, unit_scale, nothing, uplo, n - ) -end - -# Solves an off-diagonal block in place against a factored diagonal block and -# returns the block's scale. The solve is linear, so it runs on the stored values -# under that scale. The diagonal block is T_Base and the solve takes one element -# type, so a narrower block is solved in a T_Base copy and stored back through -# _requantize!, which raises the scale if the solution outgrew the block's type. -function _solve_block!(solve!, block::AbstractMatrix, scale, ::Type{T_Base}) where {T_Base} - eltype(block) == T_Base && (solve!(block); return scale) - W = similar(block, T_Base, size(block)) - W .= block - solve!(W) - return _requantize!(block, W, scale) -end diff --git a/src/mxp/core/adaptive.jl b/src/mxp/core/adaptive.jl new file mode 100644 index 00000000..eaf7a196 --- /dev/null +++ b/src/mxp/core/adaptive.jl @@ -0,0 +1,108 @@ +_norm_mixedprec_block(X) = sizeof(eltype(X)) < 4 ? sqrt(sum(x -> Float64(x)^2, X)) : norm(X) + +""" + adaptive_precisions(A, U=DataType[Float32, Float64], n_min=4, epsilon=1e-8; + uplo='L') -> Vector{DataType} + +Chooses a working precision for each level of the recursive splitting of `A`, and returns them +as a `Vector{DataType}` that can be passed as `precisions` to `FullMixedPrec`, `SymmMixedPrec` +or `TriMixedPrec`. `uplo` is 'L' or 'U' for a triangular or symmetric `A`, of which only that +triangle is read, and 'F' for a full one. + +`A` is split as those containers split it. At level `k`, counted from 0 at the top, `E_k` is +the largest Frobenius norm of the level's off-diagonal blocks -- the `uplo` one, or both for +'F' -- relative to the norm of the part of `A` that is read, both taken in `Float64` for a +16- or 8-bit `A` so they neither overflow nor underflow, and the target unit roundoff is +`epsilon / (2^((k+1)/2) * E_k)`. The level gets the coarsest type, no finer than the leaves', +whose unit roundoff `eps(T)/2` does not exceed the target, or the leaves' type if none does. +Splitting stops before any block would have fewer than `n_min` rows on either side, and the +result ends with the leaves' type, so a matrix too small to split returns that type alone. + +The leaves get the coarsest type in `U` that is at least as fine as `eltype(A)` and has the +range of `Float32`, so a `Float32` matrix gets `Float32` leaves with the default `U`; no level +uses a type finer than the leaves', since `A` has no digits for it. When `eltype(A)` is not a +floating-point type or no type in `U` qualifies, the leaves get the finest type in `U`. + +`U` may list `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`, in any +order. The part of `A` that is read must be finite and not zero, `A` square and non-empty, +`uplo` 'L', 'U' or 'F', `U` non-empty, `n_min` at least 1 and `epsilon` positive; a non-square +`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, + U::AbstractVector{DataType}=DataType[Float32, Float64], + n_min::Integer=4, + epsilon::Real=1e-8; + uplo::Char='L' +) + n = size(A, 1) + n == size(A, 2) || throw(DimensionMismatch("A must be square")) + isempty(A) && throw(ArgumentError("A must not be empty")) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them + uplo in ('L', 'U', 'F') || throw(ArgumentError("uplo must be 'L', 'U' or 'F'")) + isempty(U) && throw(ArgumentError("U must not be empty")) + all(_is_block_precision, U) || + throw(ArgumentError("U must be Float8_E5M2, BFloat16, Float16, Float32 or Float64")) + n_min >= 1 || throw(ArgumentError("n_min must be at least 1")) + epsilon > 0 || throw(ArgumentError("epsilon must be positive")) + + types = sort(unique(U); by=T -> Float64(eps(T)), rev=true) + data_eps = eltype(A) <: AbstractFloat ? Float64(eps(eltype(A))) : 0.0 + i_leaf = findfirst(T -> Float64(eps(T)) <= data_eps && floatmax(T) >= floatmax(Float32), types) + types = types[1:something(i_leaf, end)] + + level_norms = Float64[] + norm_A = 0.0 + blocks = [1:n] + while all(r -> length(r) >= 2 && length(r) - _rec_split(length(r)) >= n_min, blocks) + next = UnitRange{Int}[] + level_norm = 0.0 + for r in blocks + mid = _rec_split(length(r)) + top, bottom = r[1:mid], r[mid+1:end] + if uplo != 'U' + b = _norm_mixedprec_block(view(A, bottom, top)) + level_norm, norm_A = max(level_norm, b), hypot(norm_A, b) + end + if uplo != 'L' + b = _norm_mixedprec_block(view(A, top, bottom)) + level_norm, norm_A = max(level_norm, b), hypot(norm_A, b) + end + push!(next, top, bottom) + end + push!(level_norms, level_norm) + blocks = next + end + for r in blocks + leaf = view(A, r, r) + 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")) + + roundoffs = [Float64(eps(T)) / 2 for T in types] + levels = DataType[] + for (k, level_norm) in enumerate(level_norms) + target = epsilon / (2^(k / 2) * (level_norm / norm_A)) + i = findfirst(<=(target), roundoffs) + push!(levels, i === nothing ? types[end] : types[i]) + end + push!(levels, types[end]) + return levels +end diff --git a/src/mxp/core/blocks.jl b/src/mxp/core/blocks.jl new file mode 100644 index 00000000..f518a509 --- /dev/null +++ b/src/mxp/core/blocks.jl @@ -0,0 +1,141 @@ +@inline _is_block_precision(T) = T in (Float16, BFloat16, Float32, Float64) || nameof(T) === :Float8_E5M2 + +function _check_mixedprec_args(A::AbstractMatrix, precisions::Vector{DataType}) + isempty(A) && throw(ArgumentError("input matrix must not be empty")) + size(A, 1) == size(A, 2) || throw(DimensionMismatch("input matrix must be square")) + isempty(precisions) && + throw(ArgumentError("precisions must not be empty")) + all(_is_block_precision, precisions) || + throw(ArgumentError("precisions must be Float8_E5M2, BFloat16, Float16, Float32 or Float64")) + floatmax(precisions[end]) >= floatmax(Float32) || + throw(ArgumentError("the leaf precision, precisions[end], must be Float32 or Float64")) + return nothing +end + +function _quantize_mixedprec_block(B::AbstractMatrix, ::Type{T}) where {T<:AbstractFloat} + blockamax = maximum(x -> abs(float(x)), B) + isfinite(blockamax) || throw(ArgumentError("input matrix must be finite")) + return _quantize_with_amax(B, T, blockamax) +end + +# The same, writing into dest (a matrix of the narrow type, B's size) instead of a new array. +function _quantize_with_amax!(dest::AbstractMatrix{T}, B::AbstractMatrix, blockamax) where {T<:AbstractFloat} + limit = convert(typeof(blockamax), floatmax(T)) + blockamax > limit || (dest .= B; return (dest, 1f0)) + scale = Float32(blockamax / limit) + scale * limit < blockamax && (scale = nextfloat(scale)) + isfinite(scale) || + throw(ArgumentError("A block of the input matrix has values too large for $T storage with a Float32 scale")) + dest .= B ./ convert(typeof(blockamax), scale) + return (dest, scale) +end + +# The rest of _quantize_mixedprec_block, for a caller that already has the block's finite max |x|. +function _quantize_with_amax(B::AbstractMatrix, ::Type{T}, blockamax) where {T<:AbstractFloat} + limit = convert(typeof(blockamax), floatmax(T)) + blockamax > limit || return (T.(B), 1f0) + scale = Float32(blockamax / limit) + scale * limit < blockamax && (scale = nextfloat(scale)) + isfinite(scale) || + throw(ArgumentError("A block of the input matrix has values too large for $T storage with a Float32 scale")) + return (T.(B ./ convert(typeof(blockamax), scale)), scale) +end + +function _requantize_mixedprec_offdiag_block!(block::AbstractMatrix{T}, W::AbstractMatrix{R}, scale::Float32) where {T<:AbstractFloat, R<:AbstractFloat} + blockamax = maximum(abs, W) + limit = R(floatmax(T)) + (isfinite(blockamax) && blockamax > limit) || (block .= W; return scale) + growth = Float64(blockamax) / limit + newscale = Float32(scale * growth) + newscale < scale * growth && (newscale = nextfloat(newscale)) + isfinite(newscale) || + throw(ArgumentError("an update or solve took an off-diagonal block past what $T storage with a Float32 scale can hold")) + block .= W ./ R(Float64(newscale) / scale) + return newscale +end + +function _update_mixedprec_offdiag_block!(update!, block::AbstractMatrix{T}, scale::Float32) where {T<:AbstractFloat} + floatmax(T) < floatmax(Float32) || (update!(block); return scale) + P = _scratch(block, Float32, size(block), :offdiag_update) + P .= block + update!(P) + return _requantize_mixedprec_offdiag_block!(block, P, scale) +end + +# A Float16 block whose operands are Float16 too is updated in place: gemmEx sums in Float32 and rounds once on +# store, as the Float32 copy would, without the copy and its range pass (measured 2026-11-29: recgemm! with +# Float16 operands 1.12-1.30x, identical error). A Float16 backup lets an update that reached floatmax(Float16) +# (an Inf, or a value that rounded to floatmax and would have raised the scale) be undone and redone through +# the Float32 copy, which raises the scale, so the scales are exactly as before. Other operand types keep the +# copy: cuBLAS takes no wider operand into a Float16 output without rounding it first. A backend whose Float16 +# x Float16 product into a Float16 array does not sum in Float32 keeps the copy too (_inplace_half_ok). +function _update_offdiag!(update!, block::AbstractMatrix, scale::Float32, X, Y) + (eltype(block) == Float16 && eltype(X) == Float16 && eltype(Y) == Float16 && _inplace_half_ok(block)) || + return _update_mixedprec_offdiag_block!(update!, block, scale) + backup = _scratch(block, Float16, size(block), :offdiag_backup) + backup .= block + update!(block) + m = maximum(x -> abs(Float32(x)), block) + (isfinite(m) && m < floatmax(Float16)) && return scale + block .= backup + return _update_mixedprec_offdiag_block!(update!, block, scale) +end + +# Whether the top-level off-diagonal blocks are stored narrower than Float32 (a leaf never is). Where they are, +# that storage sets the error, and the mixed LU and recgemm! let their Float32 GEMMs use TF32 (_with_tf32). +# (A is a FullMixedPrec, defined after this file, so the argument is not annotated.) +_top_narrow(A) = A.Base === nothing && (sizeof(real(eltype(A.A21))) < 4 || sizeof(real(eltype(A.A12))) < 4) + +function _solve_mixedprec_offdiag_block!(solve!, block::AbstractMatrix{T}, scale::Float32, ::Type{T_Base}) where {T<:AbstractFloat, T_Base<:AbstractFloat} + T == T_Base && (solve!(block); return scale) + W = _scratch(block, T_Base, size(block), :offdiag_solve) + W .= block + solve!(W) + return _requantize_mixedprec_offdiag_block!(block, W, scale) +end + +@inline _in_stored_triangle(lo::Bool, i, j) = lo ? i >= j : i <= j + +# The stored triangle of A (lower when lo) in T with zeros in the other half, and its Float32 scale: what +# _quantize_mixedprec_block(tril!(copy(A)), T) gives, in one masked max pass and one masked convert pass over A and +# one allocation, instead of a copy, a tril!, a max pass and a convert (two n x n allocations). The other half of A +# is never read into the result or the scale, so it may hold anything. Both passes are broadcasts, so they run where +# A is, and a view of a GPU array needs no copy first. +function _quantize_triangle_block(A::AbstractMatrix, lo::Bool, ::Type{T}) where {T<:AbstractFloat} + r, c = axes(A, 1), axes(A, 2) + blockamax = maximum(Broadcast.instantiate(Broadcast.broadcasted( + (x, i, j) -> _in_stored_triangle(lo, i, j) ? abs(float(x)) : zero(float(x)), A, r, c'))) + isfinite(blockamax) || throw(ArgumentError("input matrix must be finite")) + limit = convert(typeof(blockamax), floatmax(T)) + dest = similar(A, T, size(A)) + if !(blockamax > limit) + dest .= ifelse.(_in_stored_triangle.(lo, r, c'), A, zero(T)) + return (dest, 1f0) + end + scale = Float32(blockamax / limit) + scale * limit < blockamax && (scale = nextfloat(scale)) + isfinite(scale) || + throw(ArgumentError("A block of the input matrix has values too large for $T storage with a Float32 scale")) + s = convert(typeof(blockamax), scale) + dest .= ifelse.(_in_stored_triangle.(lo, r, c'), A ./ s, zero(T)) + return (dest, scale) +end + +function _triangular_mixedprec(::Type{C}, A::AbstractMatrix, uplo::Char, precisions::AbstractVector{DataType}) where {C} + n = size(A, 1) + T_Base = precisions[end] + if length(precisions) == 1 || n == 1 + # Masked broadcasts, 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. + # tiledtrimixedprec.jl and adaptive.jl take tril!(copy(A)) for the same reason. + base, base_scale = _quantize_triangle_block(A, uplo == 'L', T_Base) + return C{T_Base}(nothing, nothing, nothing, 1f0, base_scale, base, uplo, n) + end + mid = _rec_split(n) + remaining_precisions = @view precisions[2:end] + A11 = _triangular_mixedprec(C, view(A, 1:mid, 1:mid), uplo, remaining_precisions) + A22 = _triangular_mixedprec(C, view(A, mid+1:n, mid+1:n), uplo, remaining_precisions) + offdiag_view = uplo == 'L' ? view(A, mid+1:n, 1:mid) : view(A, 1:mid, mid+1:n) + OffDiag, OffDiag_scale = _quantize_mixedprec_block(offdiag_view, precisions[1]) + return C{T_Base}(A11, A22, OffDiag, OffDiag_scale, 1f0, nothing, uplo, n) +end diff --git a/src/mxp/core/fullmixedprec.jl b/src/mxp/core/fullmixedprec.jl new file mode 100644 index 00000000..b005b618 --- /dev/null +++ b/src/mxp/core/fullmixedprec.jl @@ -0,0 +1,127 @@ +""" + FullMixedPrec{T_Base<:AbstractFloat} <: AbstractMixedPrec{T_Base} + +A hierarchical, recursive mixed-precision data structure that maps to full dense square +matrices. It recursively partitions a matrix into four sub-blocks (`A11`, `A22`, `A21`, +`A12`), enabling varying precision levels to be stored dynamically at different depths of the +recursive hierarchy. A node holds either `A11`, `A22`, `A21` and `A12`, or a leaf block +`Base`, never both. Every stored block carries a `Float32` scale factor, 1 when it is +unscaled. The struct is mutable so that a block an update takes past `floatmax` of its type +can be stored back with a larger scale. +""" +mutable struct FullMixedPrec{T_Base<:AbstractFloat} <: AbstractMixedPrec{T_Base} + A11::Union{FullMixedPrec{T_Base}, Nothing} + A22::Union{FullMixedPrec{T_Base}, Nothing} + A21::Union{AbstractMatrix{<:AbstractFloat}, Nothing} + A12::Union{AbstractMatrix{<:AbstractFloat}, Nothing} + A21_scale::Float32 + A12_scale::Float32 + Base_scale::Float32 + Base::Union{AbstractMatrix{T_Base}, Nothing} + n::Int +end + +""" + FullMixedPrec(A::AbstractMatrix; precisions::Vector{DataType}) -> FullMixedPrec + +Constructs a `FullMixedPrec` representation of the dense square matrix `A`. + +The matrix is partitioned using a base-2 recursive splitting scheme. If the dimension `n` is a +power of 2, it splits evenly; otherwise, it splits at the largest power of 2 less than `n`. +Each level stores `A21` and `A12` in `precisions[1]` and recurses on `A11` and `A22` with the +rest. The recursion stops when one precision remains or the block is 1×1; that block +is stored in `precisions[end]`, which is also `T_Base`. + +`precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`. +The last, `precisions[end]`, must be `Float32` or `Float64`, which have the range of the scale +factors. A block whose largest magnitude exceeds `floatmax` of its storage type is divided by +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; + precisions::Vector{DataType} +) + _check_mixedprec_args(A, precisions) + return _fullmixedprec(A, precisions) +end + +function _fullmixedprec(A::AbstractMatrix, precisions::AbstractVector{DataType}) + n = size(A, 1) + T_Base = precisions[end] + if length(precisions) == 1 || n == 1 + base, base_scale = _quantize_mixedprec_block(A, T_Base) + return FullMixedPrec{T_Base}(nothing, nothing, nothing, nothing, 1f0, 1f0, base_scale, base, n) + end + mid = _rec_split(n) + remaining_precisions = @view precisions[2:end] + A11 = _fullmixedprec(view(A, 1:mid, 1:mid), remaining_precisions) + A22 = _fullmixedprec(view(A, mid+1:n, mid+1:n), remaining_precisions) + A21, A21_scale = _quantize_mixedprec_block(view(A, mid+1:n, 1:mid), precisions[1]) + A12, A12_scale = _quantize_mixedprec_block(view(A, 1:mid, mid+1:n), precisions[1]) + return FullMixedPrec{T_Base}(A11, A22, A21, A12, A21_scale, A12_scale, 1f0, nothing, n) +end + +Base.size(A::FullMixedPrec) = (A.n, A.n) + +Base.@propagate_inbounds function Base.getindex(A::FullMixedPrec{T_Base}, i::Int, j::Int) where {T_Base} + @boundscheck checkbounds(A, i, j) + A.Base !== nothing && return T_Base(A.Base[i, j] * T_Base(A.Base_scale)) + mid = size(A.A11, 1) + i <= mid && j <= mid && return @inbounds A.A11[i, j] + i > mid && j > mid && return @inbounds A.A22[i - mid, j - mid] + return i <= mid ? T_Base(A.A12[i, j - mid] * T_Base(A.A12_scale)) : + T_Base(A.A21[i - mid, j] * T_Base(A.A21_scale)) +end + +""" + reconstruct_matrix(A::FullMixedPrec{T_Base}) -> AbstractMatrix{T_Base} + +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. For +`transpose(A)` or `adjoint(A)` of a container it returns the transpose of that dense array. + +# 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 + return _reconstruct!(similar(B, T_Base, A.n, A.n), A) +end + +function _reconstruct!(C::AbstractMatrix, A::FullMixedPrec{T_Base}) where {T_Base} + if A.Base !== nothing + C .= T_Base.(A.Base .* T_Base(A.Base_scale)) + return C + end + mid, n = size(A.A11, 1), A.n + @inbounds _reconstruct!(view(C, 1:mid, 1:mid), A.A11) + @inbounds _reconstruct!(view(C, mid+1:n, mid+1:n), A.A22) + @inbounds @views C[mid+1:n, 1:mid] .= T_Base.(A.A21 .* T_Base(A.A21_scale)) + @inbounds @views C[1:mid, mid+1:n] .= T_Base.(A.A12 .* T_Base(A.A12_scale)) + return C +end \ No newline at end of file diff --git a/src/mxp/core/mxp.jl b/src/mxp/core/mxp.jl new file mode 100644 index 00000000..96142eab --- /dev/null +++ b/src/mxp/core/mxp.jl @@ -0,0 +1,39 @@ +""" + MixedPrecision + +Mixed-precision matrix containers and the routines that work over them. +Not re-exported by NextLA; opt in with `using NextLA.MixedPrecision`. +""" +module MixedPrecision + +using LinearAlgebra: norm, tril!, triu!, Transpose, Adjoint + +import ..NextLA: recgemm!, recsyrk!, potrf_recursive!, lu_recursive!, unified_rectrxm! + +using ..NextLA: _gemm_dispatch!, _syrk_dispatch!, _rec_split, _with_info_offset, unified_rec, LU_BLOCK_SIZE, POTRF_BLOCK_SIZE, RECSYRK_PARALLEL_THRESHOLD, BFloat16, + _scratch, _widened, _with_workspace, _with_tf32, _tf32_on, _inplace_half_ok, _half_gemm_ok +using ..NextLA.KernelAbstractions: get_backend, allocate + +abstract type AbstractMixedPrec{T} <: AbstractMatrix{T} end + +include("transposedmixedprec.jl") +include("blocks.jl") +include("fullmixedprec.jl") +include("symmmixedprec.jl") +include("trimixedprec.jl") +include("tiledtrimixedprec.jl") +include("adaptive.jl") +include("quantize.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 +export quantize, dequantize +export recgemm!, recsyrk!, potrf_recursive!, lu_recursive!, unified_rectrxm! + +end diff --git a/src/mxp/core/quantize.jl b/src/mxp/core/quantize.jl new file mode 100644 index 00000000..2b8b0c74 --- /dev/null +++ b/src/mxp/core/quantize.jl @@ -0,0 +1,46 @@ +""" + quantize(A, T=Float16) -> (Q, s) + +Stores `A` in `T` with one `Float32` scale factor, as the containers store each block: +`Q = A / s`, with `s = 1` unless the values of `A` exceed `floatmax(T)`. `A` must have a +floating-point element type. 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) + return _quantize_mixedprec_block(A, T) +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/core/symmmixedprec.jl b/src/mxp/core/symmmixedprec.jl new file mode 100644 index 00000000..73e4efe3 --- /dev/null +++ b/src/mxp/core/symmmixedprec.jl @@ -0,0 +1,113 @@ +""" + SymmMixedPrec{T_Base<:AbstractFloat} <: AbstractMixedPrec{T_Base} + +A hierarchical, recursive mixed-precision data structure that maps to symmetric matrices. Only +one triangle (specified by `uplo` as 'U' or 'L') is explicitly stored. It recursively +partitions the symmetric matrix into two symmetric diagonal sub-blocks (`A11`, `A22`) and one +corresponding off-diagonal block (`OffDiag`). A node holds either `A11`, `A22` and `OffDiag`, +or a leaf block `Base`, never both. Every stored block carries a `Float32` scale factor, 1 +when it is unscaled. The struct is mutable so that a block an update takes past `floatmax` of +its type can be stored back with a larger scale. +""" +mutable struct SymmMixedPrec{T_Base<:AbstractFloat} <: AbstractMixedPrec{T_Base} + A11::Union{SymmMixedPrec{T_Base}, Nothing} + A22::Union{SymmMixedPrec{T_Base}, Nothing} + OffDiag::Union{AbstractMatrix{<:AbstractFloat}, Nothing} + OffDiag_scale::Float32 + Base_scale::Float32 + Base::Union{AbstractMatrix{T_Base}, Nothing} + uplo::Char + n::Int +end + +""" + SymmMixedPrec(A::AbstractMatrix, uplo::Char; precisions::Vector{DataType}) -> SymmMixedPrec + +Constructs a `SymmMixedPrec` representation of the symmetric matrix `A`. + +The matrix is partitioned using a base-2 recursive splitting scheme, as for `FullMixedPrec`. +Each level stores the off-diagonal block of the `uplo` triangle in `precisions[1]` and +recurses on `A11` and `A22` with the rest. The recursion stops when one precision remains or +the block is 1×1; that block's `uplo` triangle is stored in `precisions[end]`, which is +also `T_Base`, with zeros in the other half. +`A` is assumed symmetric: only its `uplo` triangle is read back. + +`precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`. +The last, `precisions[end]`, must be `Float32` or `Float64`, which have the range of the scale +factors. A block whose largest magnitude exceeds `floatmax` of its storage type is divided by +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, + uplo::Char; + precisions::Vector{DataType} +) + _check_mixedprec_args(A, precisions) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them + uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U'")) + return _triangular_mixedprec(SymmMixedPrec, A, uplo, precisions) +end + +Base.size(A::SymmMixedPrec) = (A.n, A.n) + +Base.transpose(A::SymmMixedPrec) = A + +Base.@propagate_inbounds function Base.getindex(A::SymmMixedPrec{T_Base}, i::Int, j::Int) where {T_Base} + @boundscheck checkbounds(A, i, j) + if A.Base !== nothing + (A.uplo == 'L' ? i >= j : i <= j) || ((i, j) = (j, i)) + return T_Base(A.Base[i, j] * T_Base(A.Base_scale)) + end + mid = size(A.A11, 1) + i <= mid && j <= mid && return @inbounds A.A11[i, j] + i > mid && j > mid && return @inbounds A.A22[i - mid, j - mid] + r, c = i > mid ? (i - mid, j) : (j - mid, i) + x = A.uplo == 'L' ? A.OffDiag[r, c] : A.OffDiag[c, r] + return T_Base(x * T_Base(A.OffDiag_scale)) +end + +""" + reconstruct_matrix(A::SymmMixedPrec{T_Base}) -> AbstractMatrix{T_Base} + +Copies the symmetric mixed-precision matrix back into one dense array with element type +`T_Base`, of the same array type as the stored blocks, with both triangles filled from the +stored one and each block's scale applied. +""" +function reconstruct_matrix(A::SymmMixedPrec{T_Base}) where {T_Base} + B = A.Base !== nothing ? A.Base : A.OffDiag + return _reconstruct!(similar(B, T_Base, A.n, A.n), A) +end + +function _reconstruct!(C::AbstractMatrix, A::SymmMixedPrec{T_Base}) where {T_Base} + if A.Base !== nothing + # 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 + @inbounds _reconstruct!(view(C, 1:mid, 1:mid), A.A11) + @inbounds _reconstruct!(view(C, mid+1:n, mid+1:n), A.A22) + lo, up = A.uplo == 'L' ? (A.OffDiag, transpose(A.OffDiag)) : (transpose(A.OffDiag), A.OffDiag) + @inbounds @views C[mid+1:n, 1:mid] .= T_Base.(lo .* T_Base(A.OffDiag_scale)) + @inbounds @views C[1:mid, mid+1:n] .= T_Base.(up .* T_Base(A.OffDiag_scale)) + return C +end diff --git a/src/mxp/tiledtrimixedprec.jl b/src/mxp/core/tiledtrimixedprec.jl similarity index 51% rename from src/mxp/tiledtrimixedprec.jl rename to src/mxp/core/tiledtrimixedprec.jl index e10841af..a29c828f 100644 --- a/src/mxp/tiledtrimixedprec.jl +++ b/src/mxp/core/tiledtrimixedprec.jl @@ -1,26 +1,27 @@ """ - TiledTriMixedPrec{T_Diag, T_OffDiag, T_Scale, M_Diag, M_OffDiag} <: AbstractMixedPrec{T_Diag} + TiledTriMixedPrec{T_Diag, T_OffDiag, M_Diag, M_OffDiag} <: AbstractMixedPrec{T_Diag} A triangular matrix stored as a flat grid of tiles. The tile sizes come from the same recursive splitting as `TriMixedPrec`, stopped at `threshold`; diagonal tiles are stored in `T_Diag` and the off-diagonal tiles of the `uplo` triangle in `T_OffDiag`, one tile per grid -cell, each with its own scale factor of type `T_Scale`. The other triangle is not stored and -reads as zero. +cell, each with its own `Float32` scale factor. The other triangle is not stored and reads as +zero. """ -struct TiledTriMixedPrec{T_Diag<:AbstractFloat, T_OffDiag<:AbstractFloat, T_Scale<:AbstractFloat, +struct TiledTriMixedPrec{T_Diag<:AbstractFloat, T_OffDiag<:AbstractFloat, M_Diag<:AbstractMatrix{T_Diag}, M_OffDiag<:AbstractMatrix{T_OffDiag}} <: AbstractMixedPrec{T_Diag} diag::Vector{M_Diag} off::Matrix{Union{Nothing, M_OffDiag}} - diag_scales::Vector{T_Scale} - off_scales::Matrix{T_Scale} + diag_scales::Vector{Float32} + off_scales::Matrix{Float32} offsets::Vector{Int} uplo::Char n::Int end """ - TiledTriMixedPrec(A::AbstractMatrix, uplo::Char; precisions::Vector{DataType}, threshold, scale_type=Float32) + TiledTriMixedPrec(A::AbstractMatrix, uplo::Char; precisions::Vector{DataType}, + threshold) -> TiledTriMixedPrec Constructs a `TiledTriMixedPrec` representation of the triangular matrix `A`. @@ -28,70 +29,80 @@ Constructs a `TiledTriMixedPrec` representation of the triangular matrix `A`. those blocks set the tile sizes. As in the other containers, off-diagonal tiles are stored in `precisions[1]` and diagonal tiles in `precisions[end]`, which is also `T_Diag`; `precisions` holds one or two types. Only the `uplo` triangle of `A` is read. A tile whose largest -magnitude exceeds `floatmax` of its storage type is divided by a scale factor, clamped and -stored with that factor; a tile beyond `floatmax(scale_type) * floatmax` of its storage type -throws an `ArgumentError`. `precisions` may contain `Float8_E5M2` (q52), `BFloat16`, -`Float16`, `Float32` and `Float64`, and `scale_type` be `Float16`, `Float32` or `Float64`. `A` must -be square, non-empty and finite, `uplo` 'L' or 'U' and `threshold` at least 1. +magnitude exceeds `floatmax` of its storage type is divided by a `Float32` scale factor and +stored with it; a tile beyond `floatmax(Float32) * floatmax` of its storage type throws an +`ArgumentError`. `precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, +`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, uplo::Char; precisions::Vector{DataType}, - threshold::Integer, - scale_type::Type{T_Scale}=Float32 -) where {T_Scale<:AbstractFloat} - _check_args(A, precisions, T_Scale) + threshold::Integer +) + _check_mixedprec_args(A, precisions) length(precisions) <= 2 || throw(ArgumentError("precisions must hold one or two types: off-diagonal, then diagonal")) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U'")) threshold >= 1 || throw(ArgumentError("threshold must be at least 1")) T_OffDiag, T_Diag = precisions[1], precisions[end] - sizes = Int[] - _tile_sizes!(sizes, size(A, 1), Int(threshold)) - offsets = cumsum([1; sizes]) - t = length(sizes) - tile(k) = offsets[k]:offsets[k+1]-1 + offsets = _tile_offsets!([1], size(A, 1), Int(threshold)) + t = length(offsets) - 1 M_Diag = typeof(similar(A, T_Diag, 0, 0)) M_OffDiag = typeof(similar(A, T_OffDiag, 0, 0)) diag = Vector{M_Diag}(undef, t) - diag_scales = Vector{T_Scale}(undef, t) + diag_scales = Vector{Float32}(undef, t) for k in 1:t - block = view(A, tile(k), tile(k)) - diag[k], diag_scales[k] = _store(uplo == 'L' ? tril(block) : triu(block), T_Diag, T_Scale) + 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!(copy(block)) : triu!(copy(block)), T_Diag) end off = Matrix{Union{Nothing, M_OffDiag}}(nothing, t, t) - off_scales = ones(T_Scale, t, t) + off_scales = ones(Float32, t, t) for r in 1:t, c in 1:t - r != c && _stored(r, c, uplo) || continue - off[r, c], off_scales[r, c] = _store(view(A, tile(r), tile(c)), T_OffDiag, T_Scale) + r != c && (uplo == 'L' ? r >= c : r <= c) || continue + off[r, c], off_scales[r, c] = _quantize_mixedprec_block(view(A, offsets[r]:offsets[r+1]-1, offsets[c]:offsets[c+1]-1), T_OffDiag) end - return TiledTriMixedPrec{T_Diag, T_OffDiag, T_Scale, M_Diag, M_OffDiag}( + return TiledTriMixedPrec{T_Diag, T_OffDiag, M_Diag, M_OffDiag}( diag, off, diag_scales, off_scales, offsets, uplo, size(A, 1) ) end -function _tile_sizes!(sizes::Vector{Int}, n::Int, threshold::Int) - n <= threshold && return push!(sizes, n) +function _tile_offsets!(offsets::Vector{Int}, n::Int, threshold::Int) + n <= threshold && return push!(offsets, offsets[end] + n) mid = _rec_split(n) - _tile_sizes!(sizes, mid, threshold) - _tile_sizes!(sizes, n - mid, threshold) - return sizes + _tile_offsets!(offsets, mid, threshold) + _tile_offsets!(offsets, n - mid, threshold) + return offsets end Base.size(A::TiledTriMixedPrec) = (A.n, A.n) Base.@propagate_inbounds function Base.getindex(A::TiledTriMixedPrec{T_Diag}, i::Int, j::Int) where {T_Diag} @boundscheck checkbounds(A, i, j) - _stored(i, j, A.uplo) || return zero(T_Diag) + (A.uplo == 'L' ? i >= j : i <= j) || return zero(T_Diag) r, c = searchsortedlast(A.offsets, i), searchsortedlast(A.offsets, j) li, lj = i - A.offsets[r] + 1, j - A.offsets[c] + 1 - r == c && return _unscaled(A.diag[r][li, lj], A.diag_scales[r], T_Diag) - return _unscaled(A.off[r, c][li, lj], A.off_scales[r, c], T_Diag) + r == c && return T_Diag(A.diag[r][li, lj] * T_Diag(A.diag_scales[r])) + return T_Diag(A.off[r, c][li, lj] * T_Diag(A.off_scales[r, c])) end """ - reconstruct_matrix(A::TiledTriMixedPrec{T_Diag}) + reconstruct_matrix(A::TiledTriMixedPrec{T_Diag}) -> AbstractMatrix{T_Diag} Copies the tiled matrix back into one dense array with element type `T_Diag`, of the same array type as the stored tiles, with each tile's scale applied and zeros in the other @@ -101,11 +112,10 @@ function reconstruct_matrix(A::TiledTriMixedPrec{T_Diag}) where {T_Diag} C = fill!(similar(first(A.diag), T_Diag, A.n, A.n), zero(T_Diag)) t = length(A.diag) for r in 1:t, c in 1:t - rows, cols = A.offsets[r]:A.offsets[r+1]-1, A.offsets[c]:A.offsets[c+1]-1 if r == c - @views C[rows, cols] .= _unscaled.(A.diag[r], A.diag_scales[r], T_Diag) + @views C[A.offsets[r]:A.offsets[r+1]-1, A.offsets[c]:A.offsets[c+1]-1] .= T_Diag.(A.diag[r] .* T_Diag(A.diag_scales[r])) elseif A.off[r, c] !== nothing - @views C[rows, cols] .= _unscaled.(A.off[r, c], A.off_scales[r, c], T_Diag) + @views C[A.offsets[r]:A.offsets[r+1]-1, A.offsets[c]:A.offsets[c+1]-1] .= T_Diag.(A.off[r, c] .* T_Diag(A.off_scales[r, c])) end end return C diff --git a/src/mxp/transposedmixedprec.jl b/src/mxp/core/transposedmixedprec.jl similarity index 61% rename from src/mxp/transposedmixedprec.jl rename to src/mxp/core/transposedmixedprec.jl index c0231eb9..12963e38 100644 --- a/src/mxp/transposedmixedprec.jl +++ b/src/mxp/core/transposedmixedprec.jl @@ -4,8 +4,12 @@ end Base.transpose(A::AbstractMixedPrec) = TransposedMixedPrec(A) Base.transpose(A::TransposedMixedPrec) = parent(A) +Base.adjoint(A::AbstractMixedPrec) = transpose(A) Base.parent(A::TransposedMixedPrec) = A.parent Base.size(A::TransposedMixedPrec) = reverse(size(parent(A))) Base.getindex(A::TransposedMixedPrec, i::Int, j::Int) = parent(A)[j, i] + +# The dense transpose of the parent's matrix, on the parent's device (no element is read one by one). +reconstruct_matrix(A::TransposedMixedPrec) = copy(transpose(reconstruct_matrix(parent(A)))) diff --git a/src/mxp/core/trimixedprec.jl b/src/mxp/core/trimixedprec.jl new file mode 100644 index 00000000..a6409fe0 --- /dev/null +++ b/src/mxp/core/trimixedprec.jl @@ -0,0 +1,140 @@ +""" + TriMixedPrec{T_Base<:AbstractFloat} <: AbstractMixedPrec{T_Base} + +A hierarchical, recursive mixed-precision data structure that maps to triangular matrices. It +partitions the matrix into two recursive diagonal blocks (`A11`, `A22`) and a single dense +off-diagonal block (`OffDiag`), placed by its `uplo` character ('U' for upper, 'L' for lower). +A node holds either `A11`, `A22` and `OffDiag`, or a leaf block `Base`, never both. Every +stored block carries a `Float32` scale factor, 1 when it is unscaled. The struct is mutable so +that a block an update takes past `floatmax` of its type can be stored back with a larger +scale. +""" +mutable struct TriMixedPrec{T_Base<:AbstractFloat} <: AbstractMixedPrec{T_Base} + A11::Union{TriMixedPrec{T_Base}, Nothing} + A22::Union{TriMixedPrec{T_Base}, Nothing} + OffDiag::Union{AbstractMatrix{<:AbstractFloat}, Nothing} + OffDiag_scale::Float32 + Base_scale::Float32 + Base::Union{AbstractMatrix{T_Base}, Nothing} + uplo::Char + n::Int +end + +""" + TriMixedPrec(A::AbstractMatrix, uplo::Char; precisions::Vector{DataType}) -> TriMixedPrec + +Constructs a `TriMixedPrec` representation of the triangular matrix `A`. + +The matrix is partitioned using a base-2 recursive splitting scheme, as for `FullMixedPrec`. +Each level stores the off-diagonal block of the `uplo` triangle in `precisions[1]` and +recurses on `A11` and `A22` with the rest. The recursion stops when one precision remains or +the block is 1×1; that block's `uplo` triangle is stored in `precisions[end]`, which is +also `T_Base`, with zeros in the other half. +Only the `uplo` triangle of `A` is read back; the other triangle reads as zero. Every block +is a copy, so later changes to `A` do not show through. + +`precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`. +The last, `precisions[end]`, must be `Float32` or `Float64`, which have the range of the scale +factors. A block whose largest magnitude exceeds `floatmax` of its storage type is divided by +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, + uplo::Char; + precisions::Vector{DataType} +) + _check_mixedprec_args(A, precisions) + uplo = uppercase(uplo) # flags in either case, as BLAS and LAPACK take them + uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U'")) + return _triangular_mixedprec(TriMixedPrec, A, uplo, precisions) +end + +Base.size(A::TriMixedPrec) = (A.n, A.n) + +Base.@propagate_inbounds function Base.getindex(A::TriMixedPrec{T_Base}, i::Int, j::Int) where {T_Base} + @boundscheck checkbounds(A, i, j) + (A.uplo == 'L' ? i >= j : i <= j) || return zero(T_Base) + A.Base !== nothing && return T_Base(A.Base[i, j] * T_Base(A.Base_scale)) + mid = size(A.A11, 1) + i <= mid && j <= mid && return @inbounds A.A11[i, j] + i > mid && j > mid && return @inbounds A.A22[i - mid, j - mid] + x = A.uplo == 'L' ? A.OffDiag[i - mid, j] : A.OffDiag[i, j - mid] + return T_Base(x * T_Base(A.OffDiag_scale)) +end + +""" + reconstruct_matrix(A::TriMixedPrec{T_Base}) -> AbstractMatrix{T_Base} + +Copies the triangular 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 and +zeros in the other triangle. +""" +function reconstruct_matrix(A::TriMixedPrec{T_Base}) where {T_Base} + B = A.Base !== nothing ? A.Base : A.OffDiag + return _reconstruct!(similar(B, T_Base, A.n, A.n), A) +end + +function _reconstruct!(C::AbstractMatrix, A::TriMixedPrec{T_Base}) where {T_Base} + if A.Base !== nothing + # 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 + @inbounds _reconstruct!(view(C, 1:mid, 1:mid), A.A11) + @inbounds _reconstruct!(view(C, mid+1:n, mid+1:n), A.A22) + if A.uplo == 'L' + @inbounds @views C[mid+1:n, 1:mid] .= T_Base.(A.OffDiag .* T_Base(A.OffDiag_scale)) + @inbounds @views C[1:mid, mid+1:n] .= zero(T_Base) + else + @inbounds @views C[1:mid, mid+1:n] .= T_Base.(A.OffDiag .* T_Base(A.OffDiag_scale)) + @inbounds @views C[mid+1:n, 1:mid] .= zero(T_Base) + end + return C +end + +""" + TriMixedPrec(A::SymmMixedPrec{T_Base}) -> TriMixedPrec{T_Base} + +Builds a `TriMixedPrec` over the same stored blocks as `A`, without copying them. The result +reads only the `uplo` triangle, so a `SymmMixedPrec` factored in place can be used as its +triangular factor. + +The blocks are shared but each block's scale factor is copied when the result is built. Build +it after the last in-place update of `A` (`potrf_recursive!`, `recsyrk!`): an update can store +a block with a larger scale, and a result built before it reads the new values with the old +scale. + +# 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 && + return TriMixedPrec{T_Base}(nothing, nothing, nothing, 1f0, A.Base_scale, A.Base, A.uplo, A.n) + return TriMixedPrec{T_Base}(TriMixedPrec(A.A11), TriMixedPrec(A.A22), A.OffDiag, + A.OffDiag_scale, 1f0, nothing, A.uplo, A.n) +end diff --git a/src/mxp/fullmixedprec.jl b/src/mxp/fullmixedprec.jl deleted file mode 100644 index 6a259096..00000000 --- a/src/mxp/fullmixedprec.jl +++ /dev/null @@ -1,111 +0,0 @@ -""" - FullMixedPrec{T_Base<:AbstractFloat, T_Scale<:AbstractFloat} <: AbstractMixedPrec{T_Base} - -A hierarchical, recursive mixed-precision data structure that maps to full dense square matrices. -It recursively partitions a matrix into four sub-blocks (`A11`, `A22`, `A21`, `A12`), enabling -varying precision levels to be stored dynamically at different depths of the recursive hierarchy. -A node holds either `A11`, `A22`, `A21` and `A12`, or a leaf block `Base`, never both. Every -stored block carries a scale factor of type `T_Scale`, `one(T_Scale)` when it is unscaled. -The struct is mutable so that a block an update takes past `floatmax` of its type can be -stored back with a larger scale. -""" -mutable struct FullMixedPrec{T_Base<:AbstractFloat, T_Scale<:AbstractFloat} <: - AbstractMixedPrec{T_Base} - A11::Union{FullMixedPrec{T_Base, T_Scale}, Nothing} - A22::Union{FullMixedPrec{T_Base, T_Scale}, Nothing} - A21::Union{AbstractMatrix{<:AbstractFloat}, Nothing} - A12::Union{AbstractMatrix{<:AbstractFloat}, Nothing} - A21_scale::T_Scale - A12_scale::T_Scale - Base_scale::T_Scale - Base::Union{AbstractMatrix{T_Base}, Nothing} - n::Int -end - -""" - FullMixedPrec(A::AbstractMatrix; precisions::Vector{DataType}, scale_type=Float32) - -Constructs a `FullMixedPrec` representation of the dense square matrix `A`. - -The matrix is partitioned using a base-2 recursive splitting scheme. If the dimension `n` is a -power of 2, it splits evenly; otherwise, it splits at the largest power of 2 less than `n`. -Each level stores `A21` and `A12` in `precisions[1]` and recurses on `A11` and `A22` with the -rest. The recursion stops when one precision remains or the block is 1×1; that block -is stored in `precisions[end]`, which is also `T_Base`. - -`precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`. -A block whose largest magnitude exceeds `floatmax` of its storage type is divided by a scale -factor, clamped and stored with that factor, of type `scale_type` (`Float16`, `Float32` or -`Float64`). A block whose largest magnitude exceeds `floatmax(scale_type) * floatmax` of its -storage type cannot be represented and throws an `ArgumentError`. `A` must be square, -non-empty and finite. -""" -function FullMixedPrec( - A::AbstractMatrix; - precisions::Vector{DataType}, - scale_type::Type{T_Scale}=Float32 -) where {T_Scale<:AbstractFloat} - _check_args(A, precisions, T_Scale) - return _fullmixedprec(A, precisions, T_Scale) -end - -function _fullmixedprec(A::AbstractMatrix, precisions::AbstractVector{DataType}, ::Type{S}) where {S<:AbstractFloat} - n = size(A, 1) - T_Base = precisions[end] - unit_scale = one(S) - if length(precisions) == 1 || n == 1 - base, base_scale = _store(A, T_Base, S) - return FullMixedPrec{T_Base, S}( - nothing, nothing, nothing, nothing, - unit_scale, unit_scale, base_scale, base, n - ) - end - mid = _rec_split(n) - T_OffDiag = precisions[1] - remaining_precisions = @view precisions[2:end] - A11 = _fullmixedprec(view(A, 1:mid, 1:mid), remaining_precisions, S) - A22 = _fullmixedprec(view(A, mid+1:n, mid+1:n), remaining_precisions, S) - A21, A21_scale = _store(view(A, mid+1:n, 1:mid), T_OffDiag, S) - A12, A12_scale = _store(view(A, 1:mid, mid+1:n), T_OffDiag, S) - return FullMixedPrec{T_Base, S}( - A11, A22, A21, A12, - A21_scale, A12_scale, unit_scale, nothing, n - ) -end - -Base.size(A::FullMixedPrec) = (A.n, A.n) - -Base.@propagate_inbounds function Base.getindex(A::FullMixedPrec{T_Base}, i::Int, j::Int) where {T_Base} - @boundscheck checkbounds(A, i, j) - A.Base !== nothing && return _unscaled(A.Base[i, j], A.Base_scale, T_Base) - mid = size(A.A11, 1) - if i <= mid - return j <= mid ? (@inbounds A.A11[i, j]) : _unscaled(A.A12[i, j - mid], A.A12_scale, T_Base) - else - return j <= mid ? _unscaled(A.A21[i - mid, j], A.A21_scale, T_Base) : (@inbounds A.A22[i - mid, j - mid]) - end -end - -""" - reconstruct_matrix(A::FullMixedPrec{T_Base}) - -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. -""" -function reconstruct_matrix(A::FullMixedPrec{T_Base}) where {T_Base} - A.Base !== nothing && return _unscaled.(A.Base, A.Base_scale, T_Base) - return _reconstruct!(similar(A.A21, T_Base, A.n, A.n), A) -end - -function _reconstruct!(C::AbstractMatrix, A::FullMixedPrec{T_Base}) where {T_Base} - if A.Base !== nothing - C .= _unscaled.(A.Base, A.Base_scale, T_Base) - return C - end - mid, n = size(A.A11, 1), A.n - @inbounds _reconstruct!(view(C, 1:mid, 1:mid), A.A11) - @inbounds _reconstruct!(view(C, mid+1:n, mid+1:n), A.A22) - @inbounds @views C[mid+1:n, 1:mid] .= _unscaled.(A.A21, A.A21_scale, T_Base) - @inbounds @views C[1:mid, mid+1:n] .= _unscaled.(A.A12, A.A12_scale, T_Base) - return C -end \ No newline at end of file diff --git a/src/mxp/gemm/recgemm_mixedprec.jl b/src/mxp/gemm/recgemm_mixedprec.jl deleted file mode 100644 index 3f9854c3..00000000 --- a/src/mxp/gemm/recgemm_mixedprec.jl +++ /dev/null @@ -1,80 +0,0 @@ -const RECGEMM_PARALLEL_THRESHOLD = 512 - -""" - recgemm!(alpha, A, B, beta, C::FullMixedPrec; parallel=size(C, 1) > RECGEMM_PARALLEL_THRESHOLD) - -Computes `C = alpha * A * B + beta * C` in place and returns `C`, where `C` is an `n × n` -`FullMixedPrec`, `A` is `n × k` and `B` is `k × n`. It walks `C`'s block tree as -`vicki-development` did: `A` and `B` are split into quadrants at `C`'s split, and each quadrant -of `C` takes two products, `A11 * B11 + A12 * B21` for `C11`, the first with `beta` and the -second added to it. Off-diagonal blocks are updated through `_gemm_dispatch!` at their own -precision and diagonal blocks recursively. Where `C` is split, `A` and `B` must therefore be -square, `n × n`, else `DimensionMismatch`; a leaf of `C` takes any `k`. A block stored with a -scale factor `s` holds `C / s`, so its update uses `alpha / s`. An off-diagonal block -with less range than `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. -""" -function recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::FullMixedPrec; - parallel::Bool=(size(C, 1) > RECGEMM_PARALLEL_THRESHOLD)) - n = size(C, 1) - size(A, 1) == n && size(B, 2) == n && size(A, 2) == size(B, 1) || - throw(DimensionMismatch("A must be $n×k and B k×$n, for C $n×$n")) - return _recgemm_mixed!(alpha, A, B, beta, C; parallel=parallel) -end - -function _recgemm_mixed!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::FullMixedPrec; parallel::Bool) - if C.Base !== nothing - _gemm_dispatch!(alpha / C.Base_scale, A, B, beta, C.Base) - return C - end - - n, mid = size(C, 1), size(C.A11, 1) - size(A, 2) == n || - throw(DimensionMismatch("recgemm!: where C is split, A and B must be $n×$n, got k = $(size(A, 2))")) - A11, A12 = view(A, 1:mid, 1:mid), view(A, 1:mid, mid+1:n) - A21, A22 = view(A, mid+1:n, 1:mid), view(A, mid+1:n, mid+1:n) - B11, B12 = view(B, 1:mid, 1:mid), view(B, 1:mid, mid+1:n) - B21, B22 = view(B, mid+1:n, 1:mid), view(B, mid+1:n, mid+1:n) - a12 = alpha / C.A12_scale - a21 = alpha / C.A21_scale - one_ = one(beta) - - # Each off-diagonal block takes its two products through _update_block!, which - # raises the block's scale if they took it past floatmax of its type. - function update12() - C.A12_scale = _update_block!(C.A12, C.A12_scale) do P - _gemm_dispatch!(a12, A11, B12, beta, P) - _gemm_dispatch!(a12, A12, B22, one_, P) - end - end - function update21() - C.A21_scale = _update_block!(C.A21, C.A21_scale) do P - _gemm_dispatch!(a21, A21, B11, beta, P) - _gemm_dispatch!(a21, A22, B21, one_, P) - end - end - - if parallel - @sync begin - Threads.@spawn begin - _recgemm_mixed!(alpha, A11, B11, beta, C.A11; parallel=false) - _recgemm_mixed!(alpha, A12, B21, one_, C.A11; parallel=false) - end - Threads.@spawn update12() - Threads.@spawn update21() - Threads.@spawn begin - _recgemm_mixed!(alpha, A21, B12, beta, C.A22; parallel=false) - _recgemm_mixed!(alpha, A22, B22, one_, C.A22; parallel=false) - end - end - else - _recgemm_mixed!(alpha, A11, B11, beta, C.A11; parallel=false) - _recgemm_mixed!(alpha, A12, B21, one_, C.A11; parallel=false) - update12() - update21() - _recgemm_mixed!(alpha, A21, B12, beta, C.A22; parallel=false) - _recgemm_mixed!(alpha, A22, B22, one_, C.A22; parallel=false) - end - return C -end diff --git a/src/mxp/cholesky/recpotrf_mixedprec.jl b/src/mxp/lapack/cholesky/recpotrf_mixedprec.jl similarity index 56% rename from src/mxp/cholesky/recpotrf_mixedprec.jl rename to src/mxp/lapack/cholesky/recpotrf_mixedprec.jl index 068f9c1c..82124b37 100644 --- a/src/mxp/cholesky/recpotrf_mixedprec.jl +++ b/src/mxp/lapack/cholesky/recpotrf_mixedprec.jl @@ -9,18 +9,38 @@ the lower triangle when `A.uplo == 'L'`, or `A = transpose(U) * U` with `U` in t triangle when it is `'U'`. It walks the block tree of `A`: each leaf is factored by the dense `potrf_recursive!` with `block_size` and `A.uplo`, each off-diagonal block is solved against the factored diagonal block before it, and the trailing block is updated with `recsyrk!`. A -matrix that is not positive definite throws `PosDefException` from a leaf; its `info` counts -within that leaf. +matrix that is not positive definite throws `PosDefException` from a leaf; its `info` is the +order of the first leading minor that is not positive definite, counted in the whole matrix, and +`A` is then partly factored, as with the dense `potrf_recursive!`. An off-diagonal block is solved against the `T_Base` diagonal block on its stored values, -since the solve is linear and its scale carries through, in a `T_Base` copy rounded back -once when it is narrower; a result past `floatmax` of the block's type is stored with the -block's 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. +since the solve is linear and its scale carries through, in a `T_Base` copy rounded back once +when it is narrower; a result past `floatmax` of the block's type is stored with the block's +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} + return _with_workspace(() -> _potrf_recursive_mixed!(A, block_size)) +end + +function _potrf_recursive_mixed!(A::SymmMixedPrec{T_Base}, block_size::Integer) where {T_Base} if A.Base !== nothing isone(A.Base_scale) || throw(ArgumentError("potrf_recursive!: a leaf stored with a scale factor cannot hold its Cholesky factor; " * @@ -29,13 +49,13 @@ function potrf_recursive!(A::SymmMixedPrec{T_Base}, block_size::Integer=POTRF_BL return A end - potrf_recursive!(A.A11, block_size) + _potrf_recursive_mixed!(A.A11, block_size) side, tri = A.uplo == 'L' ? ('R', 'L') : ('L', 'U') - A.OffDiag_scale = _solve_block!(A.OffDiag, A.OffDiag_scale, T_Base) do W + A.OffDiag_scale = _solve_mixedprec_offdiag_block!(A.OffDiag, A.OffDiag_scale, T_Base) do W unified_rectrxm!(side, tri, 'T', 'N', one(T_Base), 'S', TriMixedPrec(A.A11), W) end X = A.uplo == 'L' ? A.OffDiag : copy(transpose(A.OffDiag)) recsyrk!(-(Float64(A.OffDiag_scale)^2), X, one(T_Base), A.A22) - potrf_recursive!(A.A22, block_size) + _with_info_offset(() -> _potrf_recursive_mixed!(A.A22, block_size), size(A.A11, 1)) return A end diff --git a/src/mxp/lapack/lu/reclu_mixedprec.jl b/src/mxp/lapack/lu/reclu_mixedprec.jl new file mode 100644 index 00000000..dc39b1f0 --- /dev/null +++ b/src/mxp/lapack/lu/reclu_mixedprec.jl @@ -0,0 +1,102 @@ +# The mixed-precision lu_recursive! runs a level's two off-diagonal solves as +# concurrent tasks while the level has more than this many rows, by default. +# recgemm!'s value for the same decision; not tuned. +const RECLU_PARALLEL_THRESHOLD = 512 + +# The LU of Aᵀ has its diagonal in L (Aᵀ = Uᵀ Lᵀ), so no flag on A's own factors gives it. +lu_recursive!(::TransposedMixedPrec, block_size::Integer=LU_BLOCK_SIZE; parallel::Bool=false) = + throw(ArgumentError("lu_recursive! factors a FullMixedPrec, not its transpose; build the container " * + "from the transposed matrix, or factor A and solve with trans = 'T'")) + +""" + lu_recursive!(A::FullMixedPrec, block_size::Integer=LU_BLOCK_SIZE; + parallel=size(A, 1) > RECLU_PARALLEL_THRESHOLD) -> A + +Factors `A = L * U` in place without pivoting, walking the block tree of `A`: each leaf is +factored by the dense `lu_recursive!` with `block_size`, each off-diagonal block is solved +against the factored diagonal block before it, and the trailing block is updated with +`recgemm!`. `L` has a unit diagonal and is stored below it, `U` on and above it, as LAPACK's +`getrf` stores them without pivots, so `A` must not need pivoting -- a diagonally dominant +matrix, for example. A zero pivot throws `ZeroPivotException` from a leaf, with `info` the +column of that pivot counted in the whole matrix; `A` is then partly factored. + +An off-diagonal block is solved against the `T_Base` diagonal block on its stored values, +since the solve is linear and its scale carries through, in a `T_Base` copy rounded back once +when it is narrower; a result past `floatmax` of the block's type is stored with the block's +scale raised. A leaf stored with a scale factor throws `ArgumentError`, since one scale cannot +hold both `L` and `U`. + +When the top-level off-diagonal blocks are stored narrower than `Float32`, the `Float32` GEMMs +inside the factorization (leaves, solves and trailing updates) may run on TF32 tensor cores on +CUDA: their inputs are rounded to a 10-bit fraction, as `Float16` storage already rounds, and the +sums stay `Float32`. + +With `parallel`, the two off-diagonal solves of a level, which are independent, run as +concurrent tasks (`@async`) 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 them one after the other. + +`transpose(A)` throws `ArgumentError`: its factors are not the factors of `A` stored another +way. Build the container from the transposed matrix, or factor `A` and solve with `trans = 'T'`. + +# 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} + # When the top-level off-diagonal blocks (half the matrix) are narrower than Float32, the error is set by that + # storage, so the Float32 GEMMs may use TF32 (measured 2026-11-29: LU [F16, F16, F32] 1.33x at n = 16384, + # error unchanged). Otherwise they stay Float32. + return _with_tf32(() -> _lu_recursive_mixed!(A, block_size, parallel), _top_narrow(A)) +end + +function _lu_recursive_mixed!(A::FullMixedPrec{T_Base}, block_size::Integer, parallel::Bool) where {T_Base} + if A.Base !== nothing + isone(A.Base_scale) || + throw(ArgumentError("lu_recursive!: a leaf stored with a scale factor cannot hold both L and U; " * + "build A with a wider precision for the leaves (precisions[end])")) + lu_recursive!(A.Base, block_size) + return A + end + + _lu_recursive_mixed!(A.A11, block_size, parallel && size(A.A11, 1) > RECLU_PARALLEL_THRESHOLD) + function solve12() + A.A12_scale = _solve_mixedprec_offdiag_block!(A.A12, A.A12_scale, T_Base) do W + unified_rectrxm!('L', 'L', 'N', 'U', one(T_Base), 'S', A.A11, W) + end + end + function solve21() + A.A21_scale = _solve_mixedprec_offdiag_block!(A.A21, A.A21_scale, T_Base) do W + unified_rectrxm!('R', 'U', 'N', 'N', one(T_Base), 'S', A.A11, W) + end + end + if parallel + @sync begin + tf = _tf32_on() # task storage is not inherited: each task opens the scope itself + @async _with_tf32(solve12, tf) + @async _with_tf32(solve21, tf) + end + else + solve12() + solve21() + end + recgemm!(-(Float64(A.A21_scale) * Float64(A.A12_scale)), A.A21, A.A12, one(T_Base), A.A22; + parallel=parallel && size(A.A22, 1) > RECGEMM_PARALLEL_THRESHOLD) + _with_info_offset(size(A.A11, 1)) do + _lu_recursive_mixed!(A.A22, block_size, parallel && size(A.A22, 1) > RECLU_PARALLEL_THRESHOLD) + end + return A +end diff --git a/src/mxp/lu/reclu_mixedprec.jl b/src/mxp/lu/reclu_mixedprec.jl deleted file mode 100644 index 302fe092..00000000 --- a/src/mxp/lu/reclu_mixedprec.jl +++ /dev/null @@ -1,63 +0,0 @@ -# The mixed-precision lu_recursive! spawns a level's two off-diagonal solves on -# separate threads while the level has more than this many rows, by default. -# recgemm!'s value for the same decision; not tuned. -const RECLU_PARALLEL_THRESHOLD = 512 - -""" - lu_recursive!(A::FullMixedPrec, block_size::Integer=LU_BLOCK_SIZE; - parallel=size(A, 1) > RECLU_PARALLEL_THRESHOLD) -> A - -Factors `A = L * U` in place without pivoting, walking the block tree of `A`: each leaf is -factored by the dense `lu_recursive!` with `block_size`, each off-diagonal block is solved against the -factored diagonal block before it, and the trailing block is updated with `recgemm!`. `L` has a -unit diagonal and is stored below it, `U` on and above it, as LAPACK's `getrf` stores them -without pivots, so `A` must not need pivoting -- a diagonally dominant matrix, for example. - -An off-diagonal block is solved against the `T_Base` diagonal block on its stored values, -since the solve is linear and its scale carries through, in a `T_Base` copy rounded back -once when it is narrower; a result past `floatmax` of the block's type is stored with the -block's scale raised. -A leaf stored with a scale factor throws `ArgumentError`, since one scale cannot hold both `L` and `U`. -With `parallel`, the two off-diagonal solves of a level, which are independent, run on -separate threads while the level has more than `RECLU_PARALLEL_THRESHOLD` rows, and the -trailing `recgemm!` uses its own threshold; `parallel = false` runs the whole factorization -on the calling thread. `lu_recursive_mixed!` is the same function, under the name -`vicki-development` gave it. -""" -function lu_recursive!(A::FullMixedPrec{T_Base}, block_size::Integer=LU_BLOCK_SIZE; - parallel::Bool=(size(A, 1) > RECLU_PARALLEL_THRESHOLD)) where {T_Base} - return _lu_recursive_mixed!(A, block_size, parallel) -end - -# parallel is the caller's flag narrowed level by level: a block spawns only while -# the flag is set and it has more than RECLU_PARALLEL_THRESHOLD rows. -function _lu_recursive_mixed!(A::FullMixedPrec{T_Base}, block_size::Integer, parallel::Bool) where {T_Base} - if A.Base !== nothing - isone(A.Base_scale) || - throw(ArgumentError("lu_recursive!: a leaf stored with a scale factor cannot hold both L and U; " * - "build A with a wider precision for the leaves (precisions[end])")) - lu_recursive!(A.Base, block_size) - return A - end - - _lu_recursive_mixed!(A.A11, block_size, parallel && size(A.A11, 1) > RECLU_PARALLEL_THRESHOLD) - solve12() = (A.A12_scale = _solve_block!(W -> unified_rectrxm!('L', 'L', 'N', 'U', one(T_Base), 'S', A.A11, W), - A.A12, A.A12_scale, T_Base)) - solve21() = (A.A21_scale = _solve_block!(W -> unified_rectrxm!('R', 'U', 'N', 'N', one(T_Base), 'S', A.A11, W), - A.A21, A.A21_scale, T_Base)) - if parallel - @sync begin - Threads.@spawn solve12() - Threads.@spawn solve21() - end - else - solve12() - solve21() - end - recgemm!(-(Float64(A.A21_scale) * Float64(A.A12_scale)), A.A21, A.A12, one(T_Base), A.A22; - parallel=parallel && size(A.A22, 1) > RECGEMM_PARALLEL_THRESHOLD) - _lu_recursive_mixed!(A.A22, block_size, parallel && size(A.A22, 1) > RECLU_PARALLEL_THRESHOLD) - return A -end - -const lu_recursive_mixed! = lu_recursive! diff --git a/src/mxp/mxp.jl b/src/mxp/mxp.jl deleted file mode 100644 index 37b91cee..00000000 --- a/src/mxp/mxp.jl +++ /dev/null @@ -1,38 +0,0 @@ -""" - MixedPrecision - -Mixed-precision matrix containers and the routines that work over them. -Not re-exported by NextLA; opt in with `using NextLA.MixedPrecision`. -""" -module MixedPrecision - -using LinearAlgebra - -import ..NextLA: recgemm!, recsyrk!, potrf_recursive!, lu_recursive!, - unified_rectrxm! - -using ..NextLA: _gemm_dispatch!, _syrk_dispatch!, _rec_split, unified_rec, - LU_BLOCK_SIZE, POTRF_BLOCK_SIZE, RECSYRK_PARALLEL_THRESHOLD, _BFloat16 - -abstract type AbstractMixedPrec{T} <: AbstractMatrix{T} end - -include("transposedmixedprec.jl") -include("blocks.jl") -include("fullmixedprec.jl") -include("symmmixedprec.jl") -include("trimixedprec.jl") -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") - -export FullMixedPrec, SymmMixedPrec, TriMixedPrec, TiledTriMixedPrec -export reconstruct_matrix, adaptive_precisions, adaptive_precision_LT -export dequantize, lu_recursive_mixed!, quantize, unified_rec_mixed - -end diff --git a/src/mxp/quantize.jl b/src/mxp/quantize.jl deleted file mode 100644 index d95c5a9d..00000000 --- a/src/mxp/quantize.jl +++ /dev/null @@ -1,18 +0,0 @@ -""" - quantize(A, T=Float16, S=Float32) -> (Q, s) - -Stores `A` in `T` with one scale factor of type `S`, as the containers store each block: -`Q = A / s`, with `s = 1` unless the values of `A` exceed `floatmax(T)`. -""" -function quantize(A::AbstractMatrix{<:AbstractFloat}, ::Type{T}=Float16, - ::Type{S}=Float32) where {T<:AbstractFloat, S<:AbstractFloat} - isempty(A) && return (similar(A, T), one(S)) - return _store(A, T, S) -end - -""" - dequantize(Q, s, T) -> Matrix of T - -Inverse of `quantize`: returns `Q * s` in `T`. -""" -dequantize(Q::AbstractMatrix, s::Real, ::Type{T}) where {T<:AbstractFloat} = T.(Q) .* T(s) diff --git a/src/mxp/symmmixedprec.jl b/src/mxp/symmmixedprec.jl deleted file mode 100644 index 5dd53879..00000000 --- a/src/mxp/symmmixedprec.jl +++ /dev/null @@ -1,98 +0,0 @@ -""" - SymmMixedPrec{T_Base<:AbstractFloat, T_Scale<:AbstractFloat} <: AbstractMixedPrec{T_Base} - -A hierarchical, recursive mixed-precision data structure that maps to symmetric matrices. -Only one triangle (specified by `uplo` as 'U' or 'L') is explicitly stored. It recursively -partitions the symmetric matrix into two symmetric diagonal sub-blocks (`A11`, `A22`) and -one corresponding off-diagonal block (`OffDiag`). -A node holds either `A11`, `A22` and `OffDiag`, or a leaf block `Base`, never both. Every -stored block carries a scale factor of type `T_Scale`, `one(T_Scale)` when it is unscaled. -The struct is mutable so that a block an update takes past `floatmax` of its type can be -stored back with a larger scale. -""" -mutable struct SymmMixedPrec{T_Base<:AbstractFloat, T_Scale<:AbstractFloat} <: - AbstractMixedPrec{T_Base} - A11::Union{SymmMixedPrec{T_Base, T_Scale}, Nothing} - A22::Union{SymmMixedPrec{T_Base, T_Scale}, Nothing} - OffDiag::Union{AbstractMatrix{<:AbstractFloat}, Nothing} - OffDiag_scale::T_Scale - Base_scale::T_Scale - Base::Union{AbstractMatrix{T_Base}, Nothing} - uplo::Char - n::Int -end - -""" - SymmMixedPrec(A::AbstractMatrix, uplo::Char; precisions::Vector{DataType}, scale_type=Float32) - -Constructs a `SymmMixedPrec` representation of the symmetric matrix `A`. - -The matrix is partitioned using a base-2 recursive splitting scheme, as for `FullMixedPrec`. -Each level stores the off-diagonal block of the `uplo` triangle in `precisions[1]` and -recurses on `A11` and `A22` with the rest. The recursion stops when one precision remains or -the block is 1×1; that block's `uplo` triangle is stored in `precisions[end]`, which is -also `T_Base`, with zeros in the other half. -`A` is assumed symmetric: only its `uplo` triangle is read back. - -`precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`. -A block whose largest magnitude exceeds `floatmax` of its storage type is divided by a scale -factor, clamped and stored with that factor, of type `scale_type` (`Float16`, `Float32` or -`Float64`). A block whose largest magnitude exceeds `floatmax(scale_type) * 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'. -""" -function SymmMixedPrec( - A::AbstractMatrix, - uplo::Char; - precisions::Vector{DataType}, - scale_type::Type{T_Scale}=Float32 -) where {T_Scale<:AbstractFloat} - _check_args(A, precisions, T_Scale) - uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U'")) - return _triangular_tree(SymmMixedPrec, A, uplo, precisions, T_Scale) -end - -Base.size(A::SymmMixedPrec) = (A.n, A.n) - -Base.transpose(A::SymmMixedPrec) = A - -Base.@propagate_inbounds function Base.getindex(A::SymmMixedPrec{T_Base}, i::Int, j::Int) where {T_Base} - @boundscheck checkbounds(A, i, j) - if A.Base !== nothing - _stored(i, j, A.uplo) || ((i, j) = (j, i)) - return _unscaled(A.Base[i, j], A.Base_scale, T_Base) - end - mid = size(A.A11, 1) - i <= mid && j <= mid && return @inbounds A.A11[i, j] - i > mid && j > mid && return @inbounds A.A22[i - mid, j - mid] - r, c = i > mid ? (i - mid, j) : (j - mid, i) - x = A.uplo == 'L' ? A.OffDiag[r, c] : A.OffDiag[c, r] - return _unscaled(x, A.OffDiag_scale, T_Base) -end - -""" - reconstruct_matrix(A::SymmMixedPrec{T_Base}) - -Copies the symmetric mixed-precision matrix back into one dense array with element type -`T_Base`, of the same array type as the stored blocks, with both triangles filled from the -stored one and each block's scale applied. -""" -function reconstruct_matrix(A::SymmMixedPrec{T_Base}) where {T_Base} - B = A.Base !== nothing ? A.Base : A.OffDiag - return _reconstruct!(similar(B, T_Base, A.n, A.n), A) -end - -function _reconstruct!(C::AbstractMatrix, A::SymmMixedPrec{T_Base}) where {T_Base} - if A.Base !== nothing - r = 1:size(C, 1) - C .= _unscaled.(ifelse.(_stored.(r, r', A.uplo), A.Base, transpose(A.Base)), A.Base_scale, T_Base) - return C - end - mid, n = size(A.A11, 1), A.n - @inbounds _reconstruct!(view(C, 1:mid, 1:mid), A.A11) - @inbounds _reconstruct!(view(C, mid+1:n, mid+1:n), A.A22) - lo, up = A.uplo == 'L' ? (A.OffDiag, transpose(A.OffDiag)) : (transpose(A.OffDiag), A.OffDiag) - @inbounds @views C[mid+1:n, 1:mid] .= _unscaled.(lo, A.OffDiag_scale, T_Base) - @inbounds @views C[1:mid, mid+1:n] .= _unscaled.(up, A.OffDiag_scale, T_Base) - return C -end diff --git a/src/mxp/syrk/recsyrk_mixedprec.jl b/src/mxp/syrk/recsyrk_mixedprec.jl deleted file mode 100644 index 1bd4df9f..00000000 --- a/src/mxp/syrk/recsyrk_mixedprec.jl +++ /dev/null @@ -1,47 +0,0 @@ -# The SymmMixedPrec methods of recsyrk!. Source: vicki-development @ 694d019, -# by Vicki , where they sat in src/recsyrk.jl. - -""" - recsyrk!(alpha, A, beta, C::SymmMixedPrec) -> C - -Computes `C = alpha * A * transpose(A) + beta * C` in place on the stored triangle (`C.uplo`) -of the `n × n` `SymmMixedPrec` `C`, where `A` is `n × k`. It walks `C`'s block tree: each -off-diagonal block takes one GEMM through `_syrk_dispatch!` at its own precision, and each -leaf the dense `recsyrk!`. A block stored with a scale factor `s` holds `C / s`, so its update -uses `alpha / s`; an off-diagonal block with less range than `Float32` is updated in a -`Float32` copy and stored back with its scale raised when the update took it past `floatmax` -of its type. When the first diagonal block of the top level -has more than `RECSYRK_PARALLEL_THRESHOLD` rows, the two diagonal halves run on separate threads, -so a task is spawned only when it has that much work. -""" -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")) - parallel = C.Base === nothing && size(C.A11, 1) > RECSYRK_PARALLEL_THRESHOLD - return _recsyrk_mixed!(alpha, A, beta, C; parallel=parallel) -end - -function _recsyrk_mixed!(alpha::Number, A::AbstractMatrix, beta::Number, C::SymmMixedPrec; - parallel::Bool) - if C.Base !== nothing - recsyrk!(alpha / C.Base_scale, A, beta, C.Base; uplo=C.uplo) - return C - end - - n1 = size(C.A11, 1) - A1, A2 = view(A, 1:n1, :), view(A, n1+1:size(A, 1), :) - a = alpha / C.OffDiag_scale - C.OffDiag_scale = _update_block!(C.OffDiag, C.OffDiag_scale) do P - C.uplo == 'L' ? _syrk_dispatch!(:GEMM, a, A2, A1, beta, P) : _syrk_dispatch!(:GEMM, a, A1, A2, beta, P) - end - - if parallel - @sync begin - Threads.@spawn _recsyrk_mixed!(alpha, A1, beta, C.A11; parallel=false) - Threads.@spawn _recsyrk_mixed!(alpha, A2, beta, C.A22; parallel=false) - end - else - _recsyrk_mixed!(alpha, A1, beta, C.A11; parallel=false) - _recsyrk_mixed!(alpha, A2, beta, C.A22; parallel=false) - end - return C -end diff --git a/src/mxp/trimixedprec.jl b/src/mxp/trimixedprec.jl deleted file mode 100644 index 98d1db7d..00000000 --- a/src/mxp/trimixedprec.jl +++ /dev/null @@ -1,115 +0,0 @@ -""" - TriMixedPrec{T_Base<:AbstractFloat, T_Scale<:AbstractFloat} <: AbstractMixedPrec{T_Base} - -A hierarchical, recursive mixed-precision data structure that maps to triangular matrices. -It partitions the matrix into two recursive diagonal blocks (`A11`, `A22`) and a single dense -off-diagonal block (`OffDiag`), structured according to its `uplo` ('U' for upper, 'L' for lower) character. -A node holds either `A11`, `A22` and `OffDiag`, or a leaf block `Base`, never both. Every -stored block carries a scale factor of type `T_Scale`, `one(T_Scale)` when it is unscaled. -The struct is mutable so that a block an update takes past `floatmax` of its type can be -stored back with a larger scale. -""" -mutable struct TriMixedPrec{T_Base<:AbstractFloat, T_Scale<:AbstractFloat} <: - AbstractMixedPrec{T_Base} - A11::Union{TriMixedPrec{T_Base, T_Scale}, Nothing} - A22::Union{TriMixedPrec{T_Base, T_Scale}, Nothing} - OffDiag::Union{AbstractMatrix{<:AbstractFloat}, Nothing} - OffDiag_scale::T_Scale - Base_scale::T_Scale - Base::Union{AbstractMatrix{T_Base}, Nothing} - uplo::Char - n::Int -end - -""" - TriMixedPrec(A::AbstractMatrix, uplo::Char; precisions::Vector{DataType}, scale_type=Float32) - -Constructs a `TriMixedPrec` representation of the triangular matrix `A`. - -The matrix is partitioned using a base-2 recursive splitting scheme, as for `FullMixedPrec`. -Each level stores the off-diagonal block of the `uplo` triangle in `precisions[1]` and -recurses on `A11` and `A22` with the rest. The recursion stops when one precision remains or -the block is 1×1; that block's `uplo` triangle is stored in `precisions[end]`, which is -also `T_Base`, with zeros in the other half. -Only the `uplo` triangle of `A` is read back; the other triangle reads as zero. Every block -is a copy, so later changes to `A` do not show through. - -`precisions` may contain `Float8_E5M2` (q52), `BFloat16`, `Float16`, `Float32` and `Float64`. -A block whose largest magnitude exceeds `floatmax` of its storage type is divided by a scale -factor, clamped and stored with that factor, of type `scale_type` (`Float16`, `Float32` or -`Float64`). A block whose largest magnitude exceeds `floatmax(scale_type) * 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'. -""" -function TriMixedPrec( - A::AbstractMatrix, - uplo::Char; - precisions::Vector{DataType}, - scale_type::Type{T_Scale}=Float32 -) where {T_Scale<:AbstractFloat} - _check_args(A, precisions, T_Scale) - uplo in ('L', 'U') || throw(ArgumentError("uplo must be 'L' or 'U'")) - return _triangular_tree(TriMixedPrec, A, uplo, precisions, T_Scale) -end - -Base.size(A::TriMixedPrec) = (A.n, A.n) - -Base.@propagate_inbounds function Base.getindex(A::TriMixedPrec{T_Base}, i::Int, j::Int) where {T_Base} - @boundscheck checkbounds(A, i, j) - _stored(i, j, A.uplo) || return zero(T_Base) - A.Base !== nothing && return _unscaled(A.Base[i, j], A.Base_scale, T_Base) - mid = size(A.A11, 1) - i <= mid && j <= mid && return @inbounds A.A11[i, j] - i > mid && j > mid && return @inbounds A.A22[i - mid, j - mid] - x = A.uplo == 'L' ? A.OffDiag[i - mid, j] : A.OffDiag[i, j - mid] - return _unscaled(x, A.OffDiag_scale, T_Base) -end - -""" - reconstruct_matrix(A::TriMixedPrec{T_Base}) - -Copies the triangular 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 and -zeros in the other triangle. -""" -function reconstruct_matrix(A::TriMixedPrec{T_Base}) where {T_Base} - B = A.Base !== nothing ? A.Base : A.OffDiag - return _reconstruct!(similar(B, T_Base, A.n, A.n), A) -end - -function _reconstruct!(C::AbstractMatrix, A::TriMixedPrec{T_Base}) where {T_Base} - if A.Base !== nothing - r = 1:size(C, 1) - C .= ifelse.(_stored.(r, r', A.uplo), _unscaled.(A.Base, A.Base_scale, T_Base), zero(T_Base)) - return C - end - mid, n = size(A.A11, 1), A.n - @inbounds _reconstruct!(view(C, 1:mid, 1:mid), A.A11) - @inbounds _reconstruct!(view(C, mid+1:n, mid+1:n), A.A22) - if A.uplo == 'L' - @inbounds @views C[mid+1:n, 1:mid] .= _unscaled.(A.OffDiag, A.OffDiag_scale, T_Base) - @inbounds @views C[1:mid, mid+1:n] .= zero(T_Base) - else - @inbounds @views C[1:mid, mid+1:n] .= _unscaled.(A.OffDiag, A.OffDiag_scale, T_Base) - @inbounds @views C[mid+1:n, 1:mid] .= zero(T_Base) - end - return C -end - -""" - TriMixedPrec(A::SymmMixedPrec{T_Base, T_Scale}) - -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. -""" -function TriMixedPrec(A::SymmMixedPrec{T_Base, T_Scale}) where {T_Base, T_Scale} - A.Base !== nothing && return TriMixedPrec{T_Base, T_Scale}( - nothing, nothing, nothing, - one(T_Scale), A.Base_scale, A.Base, A.uplo, A.n - ) - return TriMixedPrec{T_Base, T_Scale}( - TriMixedPrec(A.A11), TriMixedPrec(A.A22), A.OffDiag, - A.OffDiag_scale, one(T_Scale), nothing, A.uplo, A.n - ) -end diff --git a/src/recursion.jl b/src/recursion.jl deleted file mode 100644 index 0e97e4cb..00000000 --- a/src/recursion.jl +++ /dev/null @@ -1,6 +0,0 @@ -# The split point every recursive routine uses: the largest power of two below -# n, or n ÷ 2 when n is itself a power of two. Power-of-two leading blocks keep -# the kernels on aligned tile sizes, and one rule means the dense drivers and the -# mixed-precision containers cut a matrix the same way. Callers recurse only -# for n >= 2. -@inline _rec_split(n::Integer) = ispow2(n) ? n ÷ 2 : prevpow(2, n) 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/NextLAMatrix.jl b/test/NextLAMatrix.jl deleted file mode 100644 index 338f9fbf..00000000 --- a/test/NextLAMatrix.jl +++ /dev/null @@ -1,16 +0,0 @@ -@testset "NextLAMatrix" begin - for T in (Float32, Float64, ComplexF32, ComplexF64) - n = 10 - A = rand(T, 10, 10) - DLA_A = NextLAMatrix{T}(A) - @test A == DLA_A.data - @test size(DLA_A) == (10, 10) - @test size(DLA_A, 1) == 10 - @test size(DLA_A, 2) == 10 - @test length(DLA_A) == 100 - @test size(A) == (10, 10) - @test size(A, 1) == 10 - @test size(A, 2) == 10 - @test length(A) == 100 - end -end \ No newline at end of file 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..5f6d873c --- /dev/null +++ b/test/README.md @@ -0,0 +1,228 @@ +# 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 and mxp +nlatest --list # the test names; × marks those that failed last time +nlatest mxp # one part: dense or mxp +nlatest dense/lapack/qr # one folder +nlatest mxp/blas/trsm/rectrxm_mixed # one file +nlatest dense/lapack/qr/geqrt mxp/core # several +nlatest '!mxp' # everything except mxp +``` + +`--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. the +blocked Cholesky of `dense/lapack/cholesky/potrf_blocked` 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. + +### Choosing cases inside the tests + +Most tests loop over sizes, types and flags. These options set what those loops +run; anything not given keeps the test's own values. + +Types and flags work on any selection, and run only the values a test has: + +```bash +nlatest --types=Float32,ComplexF32 mxp # only these element types +nlatest --uplo=L --side=R dense/blas/trsm # only these flag values +nlatest --trans=N,T --diag=U # trans N, T or C; diag N or U +nlatest --precisions=Float16,Float32,Float64 mxp # mixed precision: this precision list in place of the test's +nlatest --threads=8 # threads for the checks of parallel routines (default 4) +``` + +Sizes and block sizes are your own numbers, for one test at a time, since `n` +means something different in each test. `--params` lists what a test takes, +what each number means and its default values: + +```bash +nlatest --params dense/blas/trsm/trsm # the test's options +nlatest --m=4,8 --n=300,1000 dense/blas/trsm/trsm # every combination of m and n +nlatest --m=500 --n=200 --ib=16 dense/lapack/qr/geqrt # sizes and the inner block size +nlatest --n=128 --tile=16 dense/lapack/lu/lu_tiled # the order and the tile size (a GPU test) +``` + +The number options are `--m`, `--n`, `--k` (sizes), `--ib` (inner block +size), `--block` (block size), `--tile` and `--batch` (matrices in a batch). +A test's sizes go together: a test of `m` and `n` needs both. A combination +the test cannot take (for example an `ib` larger than LAPACK allows) is +skipped, and the output says why; so is a type or flag the test does not run. +Checks written for one fixed case (an edge case, an error check, a fixed +size inside the check) keep their values. The first lines of the run list the +options in force; several values are separated by commas. + +### Speed and output + +```bash +nlatest --jobs=4 # 4 tests at once +nlatest --jobs=1 # one test at a time +nlatest --quickfail # stop at the first failing test file +nlatest --failfast # stop each test file at its first failing check +nlatest --verbose # more output (start and set-up times) +nlatest --gpu-debug # say why a GPU backend was skipped +nlatest --no-float64 --backends=CUDA # run a GPU as one without Float64 (as Metal) +``` + +### 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=`'!mxp'`) # everything except mxp +Pkg.test("NextLA"; test_args=`--backends=CUDA mxp`) # mxp on CUDA only +Pkg.test("NextLA"; test_args=`--jobs=4 mxp`) # 4 tests at once +Pkg.test("NextLA"; test_args=`--types=Float32 mxp`) # only Float32 +Pkg.test("NextLA"; test_args=`--m=500 --n=200 dense/lapack/qr/geqrt`) # your own sizes, one test +``` + +### Results + +The summary lists every file with its time and memory, and the command ends +with an error if any test fails. Broken counts known NextLA bugs, marked so the +run still passes; when one is fixed, its test shows as an error until the mark +is removed. + +Each run prints its random seed. `nlatest --seed=1234 mxp/core/blocks` gives +that test the same random inputs again, on the same Julia version, so a failure +can be repeated alone. + +## What the tests check + +- **Types.** Float32, Float64, ComplexF32 and ComplexF64 on every backend, and Float16 + where the routine supports it. Float8 and BFloat16 are not tested for now. +- **GPU.** By default, if the GPU package is missing, fails to load or finds no usable + GPU, that GPU is skipped without an error message, and the tests run on the CPU only and still pass; the first + lines of the run say which backends are tested. With `--backends=CPU,CUDA` (AMDGPU, oneAPI or Metal in place of CUDA) + the run stops with an error instead. +- **Metal.** Metal has no Float64, so it runs the Float16, Float32 and ComplexF32 tests. + `--no-float64` makes every GPU backend run only those types, to check this + without a Metal GPU. +- **Accuracy.** The allowed error depends on the precision: about 1e-3 for Float16, + 1e-7 for Float32, 1e-16 for Float64 (complex as its real type), growing with the matrix size. +- **Inputs.** Test matrices are randomly generated with values between 0 and 1 + (between -1 and 1 in the mixed-precision tests), or + Gaussian where a routine needs both signs. For values too close to 0 to be stored + exactly, the allowed error also includes half the smallest step the precision can store, + the bound given by [Higham's rounding model](https://doi.org/10.1137/1.9780898718027). +- **Reference.** Results are compared with the exact answer, computed in higher + precision, or checked the way LAPACK's own tests check them (for example, how well + L·U rebuilds A). +- **Threads.** By default each test runs with one thread. Routines that run work in + parallel are also tested with 4 threads. +- **CI.** Every test runs on Julia 1.10, the latest release and nightly, on Linux, CPU only. + +## 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`: + +| Folder | Tests | +|---|---| +| `dense/core` | `NextLAMatrix` | +| `dense/blas` | `axpy`, `gerc` | +| `dense/blas/gemm` | `matmul`, `recgemm`, `gemmEx`, `gemm_types`, `gemm_precision`, `gemm_batched`, `gemm_grouped` | +| `dense/blas/trsm` | `trsm`, `trmm`, `rectrxm`, `rectrxm_complex`, `rectrxm_float16`, `trsm_batched` | +| `dense/blas/syrk` | `syrk`, `syrk_kernel`, `recsyrk` | +| `dense/lapack/lu` | `lu_base`, `lu_pivot`, `lu_tiled`, `reclu` | +| `dense/lapack/cholesky` | `potrf`, `potrf_kernel`, `potrf_register`, `potrf_blocked`, `recpotrf`, `potrf_batched` | +| `dense/lapack/qr` | `geqr2`, `geqrt`, `larfg`, `larf`, `larft`, `larfb`, `unmqr`, `tsqrt`, `tsmqr`, `ttqrt`, `ttmqr`, `parfb`, `pamm`, `pemv` | +| `dense/lapack/rotations` | `lartg` | + +A test with a suffix is one part of a larger test, e.g. +`dense/blas/trsm/rectrxm_complex`. Their shared +helpers (LAPACK reference wrappers, tolerances, backend helpers) are in +`test/setup/` and 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 lists the +error bounds. diff --git a/test/axpy.jl b/test/axpy.jl deleted file mode 100644 index 3f33a9ac..00000000 --- a/test/axpy.jl +++ /dev/null @@ -1,30 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "AXPY [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "n=$n, α=$α" for n in [0, 1, 10, 100, 1023], - α in [zero(T), one(T), T(0.7)] - x = ArrayType(rand(T, n)) - y = ArrayType(rand(T, n)) - y_ref = Array(copy(y)) - n > 0 && BLAS.axpy!(α, Array(x), y_ref) - - NextLA.axpy!(α, x, y) - synchronize(y) - - if n == 0 || α == zero(T) - @test Array(y) == y_ref - else - @test Array(y) ≈ y_ref rtol=rtol - end - end - end - end -end - -@testset "AXPY Edge cases" begin - @test_nowarn NextLA.axpy!(0.0, Float64[], Float64[]) - x = rand(10); y = rand(10) - @test_nowarn NextLA.axpy!(0.0, x, copy(y)) -end diff --git a/test/cholesky/cholesky.jl b/test/cholesky/cholesky.jl deleted file mode 100644 index 2d323c61..00000000 --- a/test/cholesky/cholesky.jl +++ /dev/null @@ -1,113 +0,0 @@ -# Cholesky: the unblocked single-workgroup kernel and the recursive driver. -# -# Written from scratch. The ten Cholesky files on vicki-development are all -# benchmark or plotting scripts with a top-level call at EOF, and the sole -# @testset among them is commented out, so there is nothing to adapt. See -# KNOWN_ISSUES.md. -# -# SPD input is built as R*R' + n*I, matching the branch's own fixtures: well -# conditioned, and positive definite by construction. - -@testset "CHOLESKY_LOWER [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "n=$n" for n in (4, 8, 16, 32, 64) - R = rand(T, n, n) - A0 = R * R' + T(n) * I - Ad = ArrayType(copy(A0)) - - NextLA.cholesky_lower!(Ad) - synchronize(Ad) - A = Array(Ad) - - L = LowerTriangular(A) - @test norm(L * L' - A0) / norm(A0) < rtol - # this kernel zeroes the upper triangle, unlike potrf! - @test all(iszero, triu(A, 1)) - end - end - - @testset "rejects a non-square matrix" begin - @test_throws DimensionMismatch NextLA.cholesky_lower!(ArrayType(rand(Float64, 4, 5))) - end -end - -@testset "POTRF_RECURSIVE [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "n=$n block=$bs" for n in (32, 64, 128), bs in (8, 16, 32) - R = rand(T, n, n) - A0 = R * R' + T(n) * I - Ad = ArrayType(copy(A0)) - - NextLA.potrf_recursive!(Ad, bs) - synchronize(Ad) - - L = LowerTriangular(Array(Ad)) - @test norm(L * L' - A0) / norm(A0) < rtol - end - - # A block size at or above n must take the potrf! base case directly - # and agree with it exactly. - @testset "block_size >= n falls through to potrf!" begin - n = 32 - R = rand(T, n, n) - A0 = R * R' + T(n) * I - a = ArrayType(copy(A0)); b = ArrayType(copy(A0)) - NextLA.potrf_recursive!(a, 64) - NextLA.potrf!('L', b) - synchronize(a); synchronize(b) - @test tril(Array(a)) == tril(Array(b)) - end - end -end - -@testset "POTRF_RECURSIVE uplo and errors [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - @testset "uplo='U', $T n=$n block=$bs" for T in (Float32, Float64), n in (32, 50, 64), bs in (8, 32) - R = rand(T, n, n) - A0 = R * R' + T(n) * I - Ad = ArrayType(copy(A0)) - @test NextLA.potrf_recursive!(Ad, bs; uplo='U') === Ad - synchronize(Ad) - U = UpperTriangular(Array(Ad)) - @test norm(U' * U - A0) / norm(A0) < test_rtol(T) - end - - # The leaf whose minor fails is not the first one, so the offset is checked. - @testset "not positive definite throws PosDefException, uplo=$uplo" for uplo in ('L', 'U') - A0 = Matrix{Float64}(I, 12, 12) - A0[10, 10] = -1 - err = try NextLA.potrf_recursive!(ArrayType(A0), 4; uplo=uplo); nothing catch e; e end - @test err isa PosDefException - @test err.info == 10 - end - - @testset "rejects a block_size below one" begin - @test_throws ArgumentError NextLA.potrf_recursive!(ArrayType(Matrix{Float64}(I, 4, 4)), 0) - end - - @testset "rejects a non-square matrix" begin - @test_throws DimensionMismatch NextLA.potrf_recursive!(ArrayType(zeros(Float64, 4, 6)), 2) - end -end - -# Half precision. The leaves go through potrf!'s Float16 method and the panel -# solve through the Float16 TRSM base case, which here is handed a transposed -# view of A. The residual is taken in Float64 so that it measures the factor -# rather than Float16 arithmetic in the check. Metal has no potrf! at all. -@testset "POTRF_RECURSIVE Float16 [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - backend_name in ("CPU", "CUDA", "AMDGPU") || continue - @testset "n=$n block=$bs" for n in (32, 64, 128), bs in (8, 16, 32) - R = rand(n, n) - A0 = Float16.(R * R' + n * I) - Ad = ArrayType(copy(A0)) - - NextLA.potrf_recursive!(Ad, bs) - synchronize(Ad) - - L = LowerTriangular(Float64.(Array(Ad))) - @test norm(L * L' - Float64.(A0)) / norm(Float64.(A0)) < 5e-3 - end -end diff --git a/test/cholesky/cholesky_blocked.jl b/test/cholesky/cholesky_blocked.jl deleted file mode 100644 index 40e7ba31..00000000 --- a/test/cholesky/cholesky_blocked.jl +++ /dev/null @@ -1,137 +0,0 @@ -# Blocked right-looking Cholesky. GPU only: the kernel is declared cpu=false on -# the branch it came from, so the CPU path is asserted to refuse rather than to -# return numbers. -# -# Diagonally dominant input throughout. There is no positive-definiteness check -# in the kernel -- it takes sqrt as it goes -- so an indefinite matrix would -# produce NaN rather than an error, which is recorded rather than tested for. - -@testset "CHOLESKY_BLOCKED [GPU]" begin - gpus = available_gpu_backends() - if isempty(gpus) - @test_skip "no GPU backend available" - end - - for (backend_name, ArrayType, synchronize) in gpus - @testset "[$backend_name] $T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "n=$n block=$bs" for (n, bs) in [ - (32, 32), (64, 32), (64, 64), (128, 64), (100, 64), - ] - A0 = rand(T, n, n) - A0 = A0 * A0' + T(n) * I # symmetric positive definite - Ad = ArrayType(copy(A0)) - - NextLA.cholesky_blocked!(Ad; block = bs) - synchronize(Ad) - - L = LowerTriangular(Array(Ad)) - @test norm(L * L' - A0) / norm(A0) < rtol - end - - # The register kernel is the other way of factoring a diagonal - # block: same driver, same panel solve and trailing update. It is - # checked over the same shapes, and against the shared kernel -- - # both walk k in the same order, so they agree bit for bit and a - # mere tolerance check would not notice one of them drifting. - @testset "register kernel n=$n block=$bs" for (n, bs) in [ - (32, 32), (64, 32), (64, 64), (128, 64), (100, 64), - ] - A0 = rand(T, n, n) - A0 = A0 * A0' + T(n) * I - Ad = ArrayType(copy(A0)) - Ashared = ArrayType(copy(A0)) - - NextLA.cholesky_blocked!(Ad; block = bs, kernel = :register) - NextLA.cholesky_blocked!(Ashared; block = bs, kernel = :shared) - synchronize(Ad) - synchronize(Ashared) - - L = LowerTriangular(Array(Ad)) - @test norm(L * L' - A0) / norm(A0) < rtol - @test Array(Ad) == Array(Ashared) - end - - # Launched on its own, without the driver's panel sweep around it. - @testset "register kernel alone on one block, n=$n" for n in (16, 33, 48, 64) - A0 = rand(T, n, n) - A0 = A0 * A0' + T(n) * I - Ad = ArrayType(copy(A0)) - before = triu(Array(Ad), 1) - - backend = KernelAbstractions.get_backend(Ad) - NextLA.chol_kernel_register!(backend, NextLA.CHOL_REG_THREADS)( - Ad, Val(n); ndrange = NextLA.CHOL_REG_THREADS) - synchronize(Ad) - - L = LowerTriangular(Array(Ad)) - @test norm(L * L' - A0) / norm(A0) < rtol - @test triu(Array(Ad), 1) == before - end - - @testset "leaves the strict upper triangle alone" begin - n = 64 - A0 = rand(T, n, n) - A0 = A0 * A0' + T(n) * I - Ad = ArrayType(copy(A0)) - before = triu(Array(Ad), 1) - - NextLA.cholesky_blocked!(Ad; block = 64) - synchronize(Ad) - - @test triu(Array(Ad), 1) == before - end - end - end - - # The kernel cannot run on the CPU backend, so the entry point refuses there - # instead of failing somewhere inside KernelAbstractions. - @testset "refuses the CPU backend" begin - A = rand(Float64, 32, 32) - A = A * A' + 32I - @test_throws ArgumentError NextLA.cholesky_blocked!(A) - end - - @testset "rejects an unknown kernel" begin - for (_, AT, _) in available_gpu_backends() - A = AT(rand(Float64, 64, 64) + 64I) - @test_throws ArgumentError NextLA.cholesky_blocked!(A; kernel = :nosuch) - break - end - end - - @testset "rejects a block wider than the shared tile" begin - for (_, AT, _) in available_gpu_backends() - A = AT(rand(Float64, 64, 64) + 64I) - @test_throws ArgumentError NextLA.cholesky_blocked!(A; block = 128) - break - end - end -end - -# Half precision, with both diagonal-block kernels. The panel solve hands the -# Float16 TRSM base case a transposed view of A, which is the case that has to -# stay on the device. -@testset "CHOLESKY_BLOCKED Float16 [GPU]" begin - gpus = available_gpu_backends() - if isempty(gpus) - @test_skip "no GPU backend available" - end - - for (backend_name, ArrayType, synchronize) in gpus - @testset "[$backend_name] kernel=$kernel n=$n block=$bs" for - kernel in (:shared, :register), - (n, bs) in [(32, 32), (64, 32), (128, 64), (100, 64)] - R = rand(n, n) - A0 = Float16.(R * R' + n * I) - Ad = ArrayType(copy(A0)) - - NextLA.cholesky_blocked!(Ad; block = bs, kernel = kernel) - synchronize(Ad) - - L = LowerTriangular(Float64.(Array(Ad))) - @test norm(L * L' - Float64.(A0)) / norm(Float64.(A0)) < 5e-3 - end - end -end diff --git a/test/cholesky/potrf.jl b/test/cholesky/potrf.jl deleted file mode 100644 index 9cae2547..00000000 --- a/test/cholesky/potrf.jl +++ /dev/null @@ -1,124 +0,0 @@ -# Single-matrix Cholesky. potrf! returns (A, info) and overwrites only the -# triangle named by uplo, so the tests assert both: the factor reconstructs the -# input, and the untouched triangle still holds what it did on entry. -# -# LinearAlgebra.cholesky is the oracle. It raises PosDefException on an -# indefinite input where potrf! reports info > 0 instead, so that case is -# checked directly rather than against it. - -@testset "POTRF [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "uplo=$uplo n=$n" for uplo in ('L', 'U'), n in (1, 2, 8, 32, 64) - R = rand(T, n, n) - A0 = R * R' + T(n) * I # symmetric/Hermitian positive definite - Ad = ArrayType(copy(A0)) - - F, info = NextLA.potrf!(uplo, Ad) - synchronize(F) - @test info == 0 - - A = Array(F) - if uplo == 'L' - L = LowerTriangular(A) - @test norm(L * L' - A0) / norm(A0) < rtol - else - U = UpperTriangular(A) - @test norm(U' * U - A0) / norm(A0) < rtol - end - end - - # The opposite triangle is neither read nor written by LAPACK, so it - # must survive untouched. Easy to break by "helpfully" zeroing it. - @testset "leaves the opposite triangle alone (uplo=$uplo)" for uplo in ('L', 'U') - n = 16 - R = rand(T, n, n) - A0 = R * R' + T(n) * I - Ad = ArrayType(copy(A0)) - NextLA.potrf!(uplo, Ad) - A = Array(Ad) - if uplo == 'L' - @test triu(A, 1) == triu(A0, 1) - else - @test tril(A, -1) == tril(A0, -1) - end - end - end - - @testset "defaults to lower" begin - n = 16 - R = rand(Float64, n, n) - A0 = R * R' + n * I - a = ArrayType(copy(A0)); b = ArrayType(copy(A0)) - NextLA.potrf!(a) - NextLA.potrf!('L', b) - @test Array(a) == Array(b) - end - - @testset "argument errors" begin - A = ArrayType(rand(Float64, 4, 4) + 4I) - @test_throws ArgumentError NextLA.potrf!('X', A) - @test_throws DimensionMismatch NextLA.potrf!('L', ArrayType(rand(Float64, 4, 5))) - end -end - -@testset "POTRF non-positive-definite reports info" begin - # Indefinite: LinearAlgebra.cholesky would raise, potrf! returns info > 0 - # naming the order of the failing leading minor. - A = Matrix{Float64}([1.0 2.0; 2.0 1.0]) - _, info = NextLA.potrf!('L', copy(A)) - @test info > 0 - @test_throws PosDefException cholesky(A) -end - -@testset "POTRF dispatches to the right implementation" begin - # The generic method is CPU-only on purpose -- no silent host round-trip -- - # so each backend must reach its own wrapper rather than falling through. - for (name, AT, _) in available_backends() - A = AT(rand(Float64, 8, 8) + 8I) - @test occursin(_expected_potrf_file(name), _method_file(NextLA.potrf!, 'L', A)) - end -end - -# Float16 has no LAPACK, cuSOLVER or rocSOLVER routine, so potrf! factors a -# Float32 copy and rounds back once. On the CPU the claim is exact: the result -# is the Float32 factor rounded to Float16. On a GPU the vendor factor can -# differ from LAPACK in the last Float32 bit, so there the factor is held to -# reconstructing the input at Float16 accuracy instead. Both keep the opposite -# triangle untouched and return (A, info) in place. -@testset "POTRF Float16 [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - backend_name in ("CPU", "CUDA", "AMDGPU") || continue - @testset "uplo=$uplo n=$n" for uplo in ('L', 'U'), n in (1, 8, 32) - R = rand(Float32, n, n) - A0 = Float16.(R * R' + Float32(n) * I) - Ad = ArrayType(copy(A0)) - - F, info = NextLA.potrf!(uplo, Ad) - synchronize(F) - @test info == 0 - @test F === Ad && eltype(F) == Float16 - - A = Array(F) - if backend_name == "CPU" - want, _ = NextLA.potrf!(uplo, Float32.(A0)) - @test A == Float16.(want) - end - A32, A032 = Float32.(A), Float32.(A0) - if uplo == 'L' - L = LowerTriangular(A32) - @test norm(L * L' - A032) / norm(A032) < 1e-2 - @test triu(A, 1) == triu(A0, 1) - else - U = UpperTriangular(A32) - @test norm(U' * U - A032) / norm(A032) < 1e-2 - @test tril(A, -1) == tril(A0, -1) - end - end - - @testset "reports info on an indefinite Float16 matrix" begin - A = ArrayType(Float16[1 2; 2 1]) - _, info = NextLA.potrf!('L', A) - @test info > 0 - end -end diff --git a/test/cholesky/potrf_batched.jl b/test/cholesky/potrf_batched.jl deleted file mode 100644 index b06df87d..00000000 --- a/test/cholesky/potrf_batched.jl +++ /dev/null @@ -1,49 +0,0 @@ -using LinearAlgebra -using Random -using Test - -function _potrf_batched_spd(::Type{T}, n::Int, batch::Int) where {T} - rng = MersenneTwister(73) - A = Array{T}(undef, n, n, batch) - for bid in 1:batch - X = randn(rng, T, n, n) - A[:, :, bid] = X * X' + T(n) * I - end - return A -end - -@testset "batched POTRF wrappers" begin - A = _potrf_batched_spd(Float32, 16, 3) - expected = map(axes(A, 3)) do bid - Matrix(cholesky(Hermitian(view(A, :, :, bid), :U)).U) - end - - for (name, AT, sync) in backends - @testset "$name" begin - Adev = _to_backend(AT, copy(A)) - @test occursin(_expected_potrf_batched_file(name), - _method_file(NextLA.potrf_batched!, 'U', Adev)) - if name == "Metal" - @test_throws ArgumentError NextLA.potrf_batched!('U', Adev) - continue - end - - result = NextLA.potrf_batched!('U', Adev) - sync(Adev) - if result isa Tuple - @test Array(result[2]) == zeros(Int32, size(A, 3)) - end - actual = Array(Adev) - for bid in axes(A, 3) - @test UpperTriangular(view(actual, :, :, bid)) ≈ - UpperTriangular(expected[bid]) rtol=2f-5 - end - end - end - - failure = zeros(Float32, 8, 8, 2) - failure[:, :, 1] = Matrix(Diagonal(fill(2f0, 8))) - failure[:, :, 2] = Matrix(Diagonal(vcat(fill(2f0, 4), -1f0, fill(2f0, 3)))) - _, status = NextLA.potrf_batched!('U', failure) - @test status == Int32[0, 5] -end diff --git a/test/dense/blas/axpy.jl b/test/dense/blas/axpy.jl new file mode 100644 index 00000000..4f3e3f4e --- /dev/null +++ b/test/dense/blas/axpy.jl @@ -0,0 +1,74 @@ +# axpy! (src/dense/blas/axpy.jl): y = y + a x, checked per element, Float16 included (B14, unchecked lengths, untested). + +test_params(n = "length of x and y") # the number options it takes (--params) + +# Per-element error bound of y + a x against a BigFloat reference. +_axpy_bound(::Type{T}) where {T} = (T <: Complex ? 4 : 2) * eps(real(T)) / 2 + +function _axpy_ok(y_computed, y0, α, x0) + exact = big.(y0) .+ big(α) .* big.(x0) + scale = abs.(big.(y0)) .+ abs(big(α)) .* abs.(big.(x0)) + return all(abs.(big.(y_computed) .- exact) .<= _axpy_bound(eltype(y0)) .* scale) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "AXPY [$backend_name]" begin + # Mixed signs, so cancellation in y + a x is part of what is checked. + @testset "$T, n=$n, α=$α" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), n in test_values(:n, (0, 1, 10, 100, 1023)), + α in (zero(T), one(T), T(0.7), T <: Complex ? T(-0.7 + 0.3im) : T(-0.7)) + x0, y0 = rand(T, n) .- T(0.5), rand(T, n) .- T(0.5) + y = ArrayType(copy(y0)) + NextLA.axpy!(α, ArrayType(x0), y) + synchronize(y) + if n == 0 || iszero(α) + @test Array(y) == y0 + else + @test _axpy_ok(Array(y), y0, α, x0) + end + end + + # a = 0 does not read x, so NaN or Inf there does not reach y; every path returns y, empty vectors included. + @testset "a = 0 leaves y unchanged even with NaN and Inf in x, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + y0 = rand(T, 4) + y = ArrayType(copy(y0)) + @test NextLA.axpy!(zero(T), ArrayType(T[NaN, Inf, -Inf, 1]), y) === y # y is returned on every path + synchronize(y) + @test Array(y) == y0 + e = ArrayType(T[]) + @test NextLA.axpy!(one(T), ArrayType(T[]), e) === e + end + + @testset "NaN and Inf in x reach y, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + y = ArrayType(T[1, 1, 1]) + NextLA.axpy!(one(T), ArrayType(T[NaN, Inf, 1]), y) + synchronize(y) + yh = Array(y) + @test isnan(yh[1]) && isinf(yh[2]) && yh[3] == 2 + end + + @testset "strided views of one vector, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + v0, α = rand(T, 20) .- T(0.5), T(0.7) + v = ArrayType(copy(v0)) + NextLA.axpy!(α, view(v, 1:2:19), view(v, 2:2:20)) + synchronize(v) + vh = Array(v) + @test vh[1:2:19] == v0[1:2:19] + @test _axpy_ok(vh[2:2:20], v0[2:2:20], α, v0[1:2:19]) + end + + @testset "x and y the same vector, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + z0, α = rand(T, 16) .- T(0.5), T(0.7) + z = ArrayType(copy(z0)) + NextLA.axpy!(α, z, z) + synchronize(z) + @test _axpy_ok(Array(z), z0, α, z0) + end + + # a must have the element type of x and y. + @testset "a of another type throws MethodError" begin + @test_throws MethodError NextLA.axpy!(2, ArrayType(rand(Float32, 3)), ArrayType(rand(Float32, 3))) + @test_throws MethodError NextLA.axpy!(2.0, ArrayType(rand(Float32, 3)), ArrayType(rand(Float32, 3))) + @test_throws MethodError NextLA.axpy!(Float16(2), ArrayType(rand(Float32, 3)), ArrayType(rand(Float32, 3))) + end + end +end diff --git a/test/dense/blas/gemm/gemmEx.jl b/test/dense/blas/gemm/gemmEx.jl new file mode 100644 index 00000000..4545d510 --- /dev/null +++ b/test/dense/blas/gemm/gemmEx.jl @@ -0,0 +1,313 @@ +# gemmEx! and gemm! (src/dense/blas/gemm/gemmEx.jl): mixed-storage GEMM on CPU, CUDA and AMDGPU, refused elsewhere (B16 untested). + +test_params(m = "rows of C", n = "columns of C", k = "inner dimension") # the number options it takes (--params) + +# gemm_ratio against a Float64 reference, for sizes where BigFloat is too slow. +function _gx_ratio64(C, ta, tb, α, A, B, β, C0; eps) + opA, opB, C0h = _test_op(Float64.(Array(A)), ta), _test_op(Float64.(Array(B)), tb), Float64.(Array(C0)) + exact = Float64(α) .* (opA * opB) .+ Float64(β) .* C0h + gauge = abs(Float64(α)) .* (abs.(opA) * abs.(opB)) .+ abs(Float64(β)) .* abs.(C0h) + return maximum(_elem_ratio.(abs.(Float64.(Array(C)) .- exact), gauge); init=0.0) / eps +end + +# gemm_ratio (BigFloat) on the top-left 4x4 block of C: for Float64 data the Float64 reference is the same dgemm as the CPU path. +function _gx_block(C, ta, tb, α, A, B, β, C0; eps) + r, c = 1:min(4, size(C0, 1)), 1:min(4, size(C0, 2)) + return gemm_ratio(Array(C)[r, c], ta, tb, α, ta == 'N' ? A[r, :] : A[:, r], tb == 'N' ? B[:, c] : B[c, :], β, C0[r, c]; eps) +end + +# Long sums: the element ratio grows like sqrt(n) (probabilistic bound λ√n·u, Higham & Mary 2019), so the bound does too. +_gx_bound(n) = BLAS_TEST_THRESHOLD * max(1, sqrt(n / 256)) + +# q in each position of p + q - p: |p| = 1.5 * 2^e absorbs q in a narrow sum taken in any order, in two rows at least. +_gx_absorb(p, q) = Float16[q p -p; p q -p; p -p q] + +for (backend_name, ArrayType, synchronize) in available_backends() + if !(backend_name in ("CPU", "CUDA", "AMDGPU")) # Metal and oneAPI have no gemmEx! + @testset "GEMMEX [$backend_name] refuses" begin + A = ArrayType(rand(Float32, 4, 4)) + C = ArrayType(zeros(Float32, 4, 4)) + @test_throws ArgumentError NextLA.gemmEx!('N', 'N', 1.0f0, A, A, 0.0f0, C) + end + continue + end + @testset "GEMMEX [$backend_name]" begin + + # Same type: every type, nine transpose pairs, mixed signs, k from 5 to 64. + @testset "same type $T, trans $ta$tb, m=$m n=$n k=$k" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), + ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')), + (m, n, k) in test_cases((:m, :n, :k), ((16, 16, 16), (32, 16, 8), (17, 9, 5), (16, 16, 64))) + A = ta == 'N' ? rand(T, m, k) .- T(0.5) : rand(T, k, m) .- T(0.5) + B = tb == 'N' ? rand(T, k, n) .- T(0.5) : rand(T, n, k) .- T(0.5) + C0 = rand(T, m, n) .- T(0.5) + alpha, beta = T(1.5), T(-0.5) + Cd = ArrayType(copy(C0)) + NextLA.gemmEx!(ta, tb, alpha, ArrayType(A), ArrayType(B), beta, Cd) + synchronize(Cd) + @test gemm_ratio(Cd, ta, tb, alpha, A, B, beta, C0; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + + # Lowercase flags mean the same as uppercase on every path (BLAS takes either case). + @testset "lowercase flags, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)) + A, B, C0 = rand(T, 9, 7) .- T(0.5), rand(T, 5, 7) .- T(0.5), rand(T, 9, 5) .- T(0.5) + lo, up = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.gemmEx!('n', 't', T(1.5), ArrayType(A), ArrayType(B), T(-0.5), lo) + NextLA.gemmEx!('N', 'T', T(1.5), ArrayType(A), ArrayType(B), T(-0.5), up) + @test Array(lo) == Array(up) + end + + @testset "alpha=0 scales C only, $T" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)) + n = 8 + A, B, C0 = rand(T, n, n), rand(T, n, n), rand(T, n, n) + Cd = ArrayType(copy(C0)) + NextLA.gemmEx!('N', 'N', zero(T), ArrayType(A), ArrayType(B), T(2), Cd) + synchronize(Cd) + @test Array(Cd) == 2 .* C0 + end + + # beta = 0: C is not read, so a NaN already in it does not reach the result. + @testset "beta=0 overwrites C, NaN in it ignored, $T" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)) + n = 8 + A, B = rand(T, n, n), rand(T, n, n) + Cd = ArrayType(fill(T(NaN), n, n)) + NextLA.gemmEx!('N', 'N', one(T), ArrayType(A), ArrayType(B), zero(T), Cd) + synchronize(Cd) + @test gemm_ratio(Cd, 'N', 'N', one(T), A, B, zero(T), zeros(T, n, n); eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + + # Empty, 1x1 and thin shapes; k = 0 leaves exactly beta C. + @testset "edge $T, trans $ta$tb, m=$m n=$n k=$k" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')), + (m, n, k) in ((1, 1, 1), (2, 1, 2), (0, 3, 2), (3, 0, 2), (2, 2, 0)) + A = ta == 'N' ? rand(T, m, k) .- T(0.5) : rand(T, k, m) .- T(0.5) + B = tb == 'N' ? rand(T, k, n) .- T(0.5) : rand(T, n, k) .- T(0.5) + C0 = rand(T, m, n) .- T(0.5) + Cd = ArrayType(copy(C0)) + NextLA.gemmEx!(ta, tb, T(1.5), ArrayType(A), ArrayType(B), T(0.5), Cd) + synchronize(Cd) + @test size(Cd) == (m, n) + if k == 0 + @test Array(Cd) == T(0.5) .* C0 + else + @test gemm_ratio(Cd, ta, tb, 1.5, A, B, 0.5, C0; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + end + + # Blocks of larger parents as A and B (leading dimension > rows), as recgemm! passes them; Float16 computes in Float32 as there. + @testset "block views as A and B, $T, $ta$tb" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')) + m, n, k = 9, 7, 5 + PA, PB, C0 = rand(T, 20, 20) .- T(0.5), rand(T, 20, 20) .- T(0.5), rand(T, m, n) .- T(0.5) + ia, ja = ta == 'N' ? (3:2+m, 4:3+k) : (3:2+k, 4:3+m) + ib, jb = tb == 'N' ? (5:4+k, 2:1+n) : (5:4+n, 2:1+k) + Cd = ArrayType(copy(C0)) + NextLA.gemmEx!(ta, tb, 1.5, view(ArrayType(PA), ia, ja), view(ArrayType(PB), ib, jb), -0.5, Cd; + compute_type=T === Float16 ? Float32 : T) + synchronize(Cd) + @test gemm_ratio(Cd, ta, tb, 1.5, PA[ia, ja], PB[ib, jb], -0.5, C0; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + + # The callers' update C - A B (untyped -1.0, 1.0) into a nonzero C: recgemm! ('N','N') and recsyrk! ('N','T'). + @testset "C - A B, $TA -> $TC, compute $W, $ta$tb" for (TA, TC, W) in ((Float16, Float16, Float32), (Float16, Float32, Float32), + (Float32, Float32, Float32), (Float64, Float64, Float64)), + (ta, tb) in (('N', 'N'), ('N', 'T')) + length(backend_types(ArrayType, unique((TA, TC)))) == length(unique((TA, TC))) || continue + m, n, k = 24, 17, 40 + A = rand(TA, m, k) .- TA(0.5) + B = tb == 'N' ? rand(TA, k, n) .- TA(0.5) : rand(TA, n, k) .- TA(0.5) + C0 = rand(TC, m, n) .- TC(0.5) + Cd = ArrayType(copy(C0)) + NextLA.gemmEx!(ta, tb, -1.0, ArrayType(A), ArrayType(B), 1.0, Cd; compute_type=W) + synchronize(Cd) + @test gemm_ratio(Cd, ta, tb, -1, A, B, 1, C0; eps=gemm_eps(W, TC)) <= BLAS_TEST_THRESHOLD + end + + # Big sizes n, 2n, 4n of the same update, Float64 reference; positive entries, so the sums grow with n. + @testset "C - A B, n=$n, $T, $ta$tb" for n in test_values(:n, (512, 1024, 2048)), T in backend_types(ArrayType, (Float16, Float32, Float64)), + (ta, tb) in (('N', 'N'), ('N', 'T')) + A, B, C0 = rand(T, n, n), rand(T, n, n), rand(T, n, n) + Cd = ArrayType(copy(C0)) + NextLA.gemmEx!(ta, tb, -1.0, ArrayType(A), ArrayType(B), 1.0, Cd; compute_type=T === Float16 ? Float32 : T) + synchronize(Cd) + @test _gx_ratio64(Cd, ta, tb, -1, A, B, 1, C0; eps=gemm_eps(T, T)) <= _gx_bound(n) + T === Float64 && @test _gx_block(Cd, ta, tb, -1, A, B, 1, C0; eps=gemm_eps(T, T)) <= _gx_bound(n) + end + + # A view with consecutive rows as C: the rest of the parent is not touched. + @testset "a column-block view as C" begin + M0, A, B = rand(Float32, 10, 10), rand(Float32, 4, 3) .- 0.5f0, rand(Float32, 3, 5) .- 0.5f0 + M = ArrayType(copy(M0)) + NextLA.gemmEx!('N', 'N', 1.5f0, ArrayType(A), ArrayType(B), -0.5f0, view(M, 2:5, 3:7)) + synchronize(M) + Mh = Array(M) + @test gemm_ratio(Mh[2:5, 3:7], 'N', 'N', 1.5f0, A, B, -0.5f0, M0[2:5, 3:7]; eps=gemm_eps(Float32, Float32)) <= BLAS_TEST_THRESHOLD + Mh[2:5, 3:7] .= M0[2:5, 3:7] + @test Mh == M0 + end + + # 'C' (adjoint) is not collapsed into 'T'. + @testset "adjoint is not transpose, $T" for T in backend_types(ArrayType, (ComplexF32, ComplexF64)) + n = 12 + A, B = rand(T, n, n), rand(T, n, n) + Cc = ArrayType(zeros(T, n, n)) + Ct = ArrayType(zeros(T, n, n)) + NextLA.gemmEx!('C', 'N', one(T), ArrayType(A), ArrayType(B), zero(T), Cc) + NextLA.gemmEx!('T', 'N', one(T), ArrayType(A), ArrayType(B), zero(T), Ct) + synchronize(Cc); synchronize(Ct) + Z = zeros(T, n, n) + @test gemm_ratio(Cc, 'C', 'N', 1, A, B, 0, Z; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + @test gemm_ratio(Ct, 'T', 'N', 1, A, B, 0, Z; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + @test !(Array(Cc) ≈ Array(Ct)) + end + + @testset "Float16 storage, C $TC" for TC in test_types((Float16, Float32)) + n = 16 + A, B = rand(Float16, n, n) .- Float16(0.5), rand(Float16, n, n) .- Float16(0.5) + Z = zeros(TC, n, n) + Cd = ArrayType(copy(Z)) + # Storage, not the scalars, decides the compute type: Float16, or Float32 once C is Float32. + NextLA.gemmEx!('N', 'N', 1.0f0, ArrayType(A), ArrayType(B), 0.0f0, Cd) + synchronize(Cd) + @test gemm_ratio(Cd, 'N', 'N', 1, A, B, 0, Z; eps=gemm_eps(TC, TC)) <= BLAS_TEST_THRESHOLD + end + + # compute_type=Float32 over Float16 storage and C: 0.5 survives 3072 + 0.5 - 3072 exactly (Float16 compute loses it). + @testset "compute_type is honoured, $ta$tb" for (ta, tb) in (('N', 'N'), ('N', 'T')) + A = ta == 'N' ? _gx_absorb(3072, 0.5) : permutedims(_gx_absorb(3072, 0.5)) + B = tb == 'N' ? ones(Float16, 3, 2) : ones(Float16, 2, 3) + Cd = ArrayType(zeros(Float16, 3, 2)) + NextLA.gemmEx!(ta, tb, -1.0, ArrayType(A), ArrayType(B), 1.0, Cd; compute_type=Float32) + synchronize(Cd) + @test Array(Cd) == fill(Float16(-0.5), 3, 2) + end + + # CPU: Float64 compute over Float16 storage: 2^-10 survives 49152 + 2^-10 - 49152 exactly (Float32 compute loses it). + if backend_name == "CPU" + @testset "Float64 compute over Float16 storage, $ta$tb" for (ta, tb) in (('N', 'N'), ('N', 'T')) + A = ta == 'N' ? _gx_absorb(49152, 2.0^-10) : permutedims(_gx_absorb(49152, 2.0^-10)) + B = tb == 'N' ? ones(Float16, 3, 2) : ones(Float16, 2, 3) + C = zeros(Float16, 3, 2) + NextLA.gemmEx!(ta, tb, -1.0, A, B, 1.0, C; compute_type=Float64) + @test C == fill(Float16(-2.0^-10), 3, 2) + end + + # A zero scalar does not read its operand, so an Inf or NaN there does not give NaN. + @testset "a zero scalar does not read its operand" begin + n = 4 + Binf = ones(Float16, n, n) + + # wide path: alpha = 0 ignores an Inf in A + Ainf = fill(Float16(Inf), n, n) + C = fill(Float16(2), n, n) + NextLA.gemmEx!('N', 'N', 0.0, Ainf, Binf, 3.0, C; compute_type=Float32) + @test all(C .== 6) + + # wide path: beta = 0 ignores a NaN already in C + Cnan = fill(Float16(NaN), n, n) + NextLA.gemmEx!('N', 'N', 1.0, ones(Float16, n, n), Binf, 0.0, Cnan; + compute_type=Float32) + @test all(Cnan .== n) + + # both zero: C is zeroed, operands untouched + Cz = fill(Float16(7), n, n) + NextLA.gemmEx!('N', 'N', 0.0, Ainf, Binf, 0.0, Cz; compute_type=Float32) + @test all(iszero, Cz) + + # BLAS-type operands: alpha = 0 does not reach BLAS + Ad = fill(Inf, n, n) + Cd = fill(2.0, n, n) + NextLA.gemmEx!('N', 'N', 0.0, Ad, ones(n, n), 3.0, Cd) + @test all(Cd .== 6) + end + + @testset "argument errors" begin + n = 8 + A, B = rand(Float32, n, n), rand(Float32, n, n) + @test_throws DimensionMismatch NextLA.gemmEx!( + 'N', 'N', 1.0f0, A, B, 0.0f0, zeros(Float32, n + 1, n)) + @test_throws ArgumentError NextLA.gemmEx!( + 'N', 'N', 1.0f0, A, B, 0.0f0, zeros(Float32, n, n); + compute_type=Int8) + end + end + end +end + +# gemm! (output first, keyword scalars) and gemmEx! are NextLA's own, exported. +cpu_wanted() && @testset "gemm! and gemmEx! are NextLA's, exported" begin + @test :gemmEx! in names(NextLA) + @test NextLA.gemm! !== LinearAlgebra.mul! + @test parentmodule(NextLA.gemm!) === NextLA + A = Float64[1 2; 3 4] + B = Float64[5 6; 7 8] + C = zeros(2, 2) + @test NextLA.gemm!(C, A, B) === C + @test C == A * B + @test NextLA.gemm!(C, A, B; alpha=2.0, beta=3.0) === C + @test C == 5 .* (A * B) +end + +# gemm! in BLAS argument order, every type, all transposes, alpha and beta away from 1 and 0. +@testset "gemm! flag form [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() + types = backend_name in ("CPU", "CUDA", "AMDGPU") ? + (Float32, Float64, ComplexF32, ComplexF64, Float16) : (Float32, Float64, Float16) + @testset "$T $ta$tb" for T in backend_types(ArrayType, types), ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')) + m, k, n = 7, 5, 6 + A0 = ta == 'N' ? rand(T, m, k) : rand(T, k, m) + B0 = tb == 'N' ? rand(T, k, n) : rand(T, n, k) + C0 = rand(T, m, n) + alpha, beta = T(1.5), T(-0.5) + C = ArrayType(copy(C0)) + out = gemm!(ta, tb, alpha, ArrayType(A0), ArrayType(B0), beta, C) + synchronize(C) + @test out === C + @test gemm_ratio(C, ta, tb, alpha, A0, B0, beta, C0; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + @testset "rejects a bad flag" begin + A = ArrayType(rand(Float32, 2, 2)) + @test_throws ArgumentError gemm!('X', 'N', 1f0, A, A, 0f0, similar(A)) + end +end + +# The compute type follows the storage types; an untyped Float64 alpha or beta does not raise it. +@testset "compute type follows the data [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() + backend_name in ("CPU", "CUDA", "AMDGPU") || continue + A0, B0, C0 = rand(Float32, 6, 4), rand(Float32, 4, 5), rand(Float32, 6, 5) + A, B, C = ArrayType(A0), ArrayType(B0), ArrayType(copy(C0)) + @test NextLA.default_compute_type(0.5, A, B, 2.0, C) == Float32 + @test NextLA.default_compute_type(1.0, A0, B0, 0.0, zeros(Float64, 6, 5)) == Float64 + NextLA.gemmEx!('N', 'N', 0.5, A, B, 2.0, C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 0.5, A0, B0, 2.0, C0; eps=gemm_eps(Float32, Float32)) <= BLAS_TEST_THRESHOLD +end + +# A device view whose rows are not consecutive (as A or as C): the vendor call runs on a contiguous copy (B15). +@testset "row-strided device views [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", available_backends()) + P, A, B = rand(Float32, 16, 5), rand(Float32, 8, 3), rand(Float32, 3, 5) + Pd = AT(copy(P)) + NextLA.gemmEx!('N', 'N', 1.5f0, AT(A), AT(B), 0.5f0, view(Pd, 1:2:16, :)) + R = Array(Pd) + @test R[1:2:16, :] ≈ 1.5f0 * A * B + 0.5f0 * P[1:2:16, :] && R[2:2:16, :] == P[2:2:16, :] + D = rand(Float32, 16, 3); Cd = AT(zeros(Float32, 8, 5)) + NextLA.gemmEx!('N', 'N', 1f0, view(AT(D), 1:2:16, :), AT(B), 0f0, Cd) + @test Array(Cd) ≈ D[1:2:16, :] * B +end + +# TF32 is scoped: Float32 GEMMs use it only inside _with_tf32 (the mixed LU opens it), and child tasks start without it. +@testset "TF32 scope [$name]" for (name, AT, sync) in filter(b -> b[1] in ("CPU", "CUDA"), available_backends()) + @test !NextLA._tf32_on() + @test NextLA._with_tf32(NextLA._tf32_on) && !NextLA._with_tf32(NextLA._tf32_on, false) + @test NextLA._with_tf32(() -> fetch(@async NextLA._tf32_on())) == false + @test !NextLA._tf32_on() + if name == "CUDA" # TF32 rounds the inputs to a 10-bit fraction: error near 2^-11, far above Float32's + n = 512 + A, B = rand(Float32, n, n), rand(Float32, n, n) + ref = Float64.(A) * Float64.(B) + err(C) = maximum(abs.(Float64.(Array(C)) .- ref) ./ ref) + C32, Ctf = AT(zeros(Float32, n, n)), AT(zeros(Float32, n, n)) + NextLA.gemmEx!('N', 'N', 1f0, AT(A), AT(B), 0f0, C32; compute_type=Float32) + NextLA._with_tf32(() -> NextLA.gemmEx!('N', 'N', 1f0, AT(A), AT(B), 0f0, Ctf; compute_type=Float32)) + @test err(C32) < 1e-5 && err(Ctf) < 1e-2 + get(ENV, "NVIDIA_TF32_OVERRIDE", "") == "0" || @test err(Ctf) > 1e-5 # TF32 ran (unless disabled globally) + end +end diff --git a/test/gemm/gemm_batched.jl b/test/dense/blas/gemm/gemm_batched.jl similarity index 60% rename from test/gemm/gemm_batched.jl rename to test/dense/blas/gemm/gemm_batched.jl index 79d1defd..308d5477 100644 --- a/test/gemm/gemm_batched.jl +++ b/test/dense/blas/gemm/gemm_batched.jl @@ -1,30 +1,17 @@ +# gemm_batched!, gemmEx_batched!, pointer batches and BatchPtrDescriptor (src/dense/blas/gemm/gemm_batched.jl). + +test_params(batch = "matrices in a batch") # the number options it takes (--params) + using Test using LinearAlgebra using Logging -@test NextLA.GEMM_COMPUTE_TYPES == (Float16, Float32, Float64, ComplexF32, ComplexF64, Int32) -@test :gemmEx! in names(NextLA) -@test !(:gemmEx_batched! in names(NextLA)) -@test NextLA.gemm! !== LinearAlgebra.mul! -@test parentmodule(NextLA.gemm!) === NextLA - -let - A = Float64[1 2; 3 4] - B = Float64[5 6; 7 8] - C = zeros(2, 2) - @test NextLA.gemm!(C, A, B) === C - @test C == A * B - @test NextLA.gemm!(C, A, B; alpha=2.0, beta=3.0) === C - @test C == 5 .* (A * B) +cpu_wanted() && @testset "gemmEx_batched! is not exported" begin + @test !(:gemmEx_batched! in names(NextLA)) end -@test NextLA.default_compute_type(Float16(1), Float16[1 2; 3 4], Float16[1 0; 0 1], Float16(0), Float16[0 0; 0 0]) == Float16 - -_apply_transpose(A::AbstractMatrix, trans::Char) = - trans == 'N' ? A : trans == 'T' ? transpose(A) : trans == 'C' ? adjoint(A) : - throw(ArgumentError("Unsupported transpose flag `$trans`")) @testset "batched gemm" begin - # tiny fixture so every backend runs the same arithmetic path cheaply. + # Tiny fixture, so every backend runs the same arithmetic path cheaply. transA_batch = 'N' transB_batch = 'N' alpha_batch = Float32(2) @@ -40,17 +27,17 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = C_batch_mixed = [zeros(Float32, 2, 2), zeros(Float32, 2, 2)] C_batch_half = [zeros(Float16, 2, 2), zeros(Float16, 2, 2)] - # reuse the pointer-batch reference for the equivalent strided layout. + # Reference of the pointer batch, reused for the equivalent strided layout. expected_batch = [ - alpha_batch * _apply_transpose(A_batch[i], transA_batch) * - _apply_transpose(B_batch[i], transB_batch) + + alpha_batch * _test_op(A_batch[i], transA_batch) * + _test_op(B_batch[i], transB_batch) + beta_batch * C_batch[i] for i in eachindex(A_batch) ] expected_batch3 = cat(expected_batch..., dims = 3) expected_batch_mixed = [ - Float32(alpha_batch) .* Float32.(_apply_transpose(A_batch_mixed[i], transA_batch) * _apply_transpose(B_batch_mixed[i], transB_batch)) + Float32(alpha_batch) .* Float32.(_test_op(A_batch_mixed[i], transA_batch) * _test_op(B_batch_mixed[i], transB_batch)) for i in eachindex(A_batch_mixed) ] expected_batch3_mixed = cat(expected_batch_mixed..., dims = 3) @@ -63,6 +50,46 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = expected_single = alpha_batch * A_single * B_single + beta_batch * C_single for (name, AT, sync) in backends + # A vector batch whose members differ in size gives each member's own product (B17). + name in ("CPU", "CUDA") && @testset "$name members of different sizes" begin + As = [rand(Float32, 2, 3), rand(Float32, 4, 5)]; Bs = [rand(Float32, 3, 2), rand(Float32, 5, 4)] + C0 = [rand(Float32, 2, 2), rand(Float32, 4, 4)] + Cd = [_to_backend(AT, copy(c)) for c in C0] + NextLA.gemm_batched!('N', 'N', 1.5f0, [_to_backend(AT, a) for a in As], [_to_backend(AT, b) for b in Bs], 0.5f0, Cd) + for i in 1:2 + @test Array(Cd[i]) ≈ 1.5f0 * As[i] * Bs[i] + 0.5f0 * C0[i] + end + # Same sizes, different leading dimensions: views of a 4-row and a 9-row parent. + P1, P2, B = rand(Float32, 4, 3), rand(Float32, 9, 3), rand(Float32, 3, 2) + Cs = [_to_backend(AT, zeros(Float32, 3, 2)) for _ in 1:2] + NextLA.gemm_batched!('N', 'N', 1f0, [view(_to_backend(AT, P1), 1:3, :), view(_to_backend(AT, P2), 2:4, :)], [_to_backend(AT, B), _to_backend(AT, B)], 0f0, Cs) + @test Array(Cs[1]) ≈ P1[1:3, :] * B && Array(Cs[2]) ≈ P2[2:4, :] * B + end + + # gemmEx_batched! and TF32 batches with members of different sizes; an empty batch; lowercase flags. + name in ("CPU", "CUDA") && @testset "$name gemmEx_batched!, TF32, empty and lowercase" begin + As = [rand(Float32, 2, 3), rand(Float32, 4, 5)]; Bs = [rand(Float32, 3, 2), rand(Float32, 5, 4)] + Cd = [_to_backend(AT, zeros(Float32, 2, 2)), _to_backend(AT, zeros(Float32, 4, 4))] + NextLA.gemmEx_batched!('N', 'N', 1f0, [_to_backend(AT, a) for a in As], [_to_backend(AT, b) for b in Bs], 0f0, Cd) + @test all(Array(Cd[i]) ≈ As[i] * Bs[i] for i in 1:2) + if name == "CUDA" + Ct = [_to_backend(AT, zeros(Float32, 2, 2)), _to_backend(AT, zeros(Float32, 4, 4))] + NextLA.precision_gemm_batched!('N', 'N', 1f0, [_to_backend(AT, a) for a in As], [_to_backend(AT, b) for b in Bs], 0f0, Ct, NextLA.TF32()) + @test all(isapprox(Array(Ct[i]), As[i] * Bs[i]; rtol=1e-2) for i in 1:2) + end + E = typeof(_to_backend(AT, zeros(Float32, 2, 2)))[] + @test NextLA.gemm_batched!('N', 'N', 1f0, copy(E), copy(E), 0f0, E) === E + A, B = rand(Float32, 3, 4), rand(Float32, 5, 4) + lo, up = [_to_backend(AT, zeros(Float32, 3, 5))], [_to_backend(AT, zeros(Float32, 3, 5))] + NextLA.gemm_batched!('n', 't', 1f0, [_to_backend(AT, A)], [_to_backend(AT, B)], 0f0, lo) + NextLA.gemm_batched!('N', 'T', 1f0, [_to_backend(AT, A)], [_to_backend(AT, B)], 0f0, up) + @test Array(lo[1]) == Array(up[1]) + c1, c2 = _to_backend(AT, zeros(Float32, 3, 5)), _to_backend(AT, zeros(Float32, 3, 5)) + NextLA.gemm!('n', 't', 1f0, _to_backend(AT, A), _to_backend(AT, B), 0f0, c1) + NextLA.gemm!('N', 'T', 1f0, _to_backend(AT, A), _to_backend(AT, B), 0f0, c2) + @test Array(c1) == Array(c2) + end + @testset "$name dispatch" begin A_single_dev = _to_backend(AT, copy(A_single)) B_single_dev = _to_backend(AT, copy(B_single)) @@ -90,7 +117,7 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = sync(C_single_half) @test Array(C_single_half) ≈ Float16.(expected_single_mixed) else - # unsupported backends should fail visibly + # Metal and oneAPI have no gemmEx!. @test_throws ArgumentError NextLA.gemmEx!( transA_batch, transB_batch, alpha_batch, A_single_dev, B_single_dev, beta_batch, C_single_dev ) @@ -100,7 +127,7 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = B_batch_dev = _to_backend(AT, deepcopy(B_batch)) C_batch_dev = _to_backend(AT, deepcopy(C_batch)) - # check that GPU backends do not quietly drop to the generic CPU loop. + # GPU backends do not fall back to the generic CPU loop. @test occursin(_expected_gemm_batched_file(name), _method_file(NextLA.gemm_batched!, transA_batch, transB_batch, alpha_batch, A_batch_dev, B_batch_dev, beta_batch, C_batch_dev)) @test_logs min_level=Logging.Warn NextLA.gemm_batched!( transA_batch, transB_batch, alpha_batch, A_batch_dev, B_batch_dev, beta_batch, C_batch_dev @@ -111,27 +138,6 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = @test Array(C_batch_dev[i]) ≈ expected_batch[i] end - if name == "CUDA" - cuda = Base.require(Main, :CUDA) - # Ampere or newer is necessary but not sufficient: NextLA's - # gemm_batched! forwards straight to CUBLAS.gemm_batched!, and - # CUDA.jl 5.9.2 has no BFloat16 method for it. Check the - # library, not just the device. See KNOWN_ISSUES.md. - cublas_has_bf16 = any(m -> occursin("BFloat16", string(m.sig)), - methods(cuda.CUBLAS.gemm_batched!)) - if isdefined(Core, :BFloat16) && cuda.capability(cuda.device()) >= v"8.0" && cublas_has_bf16 - Ab = _to_backend(AT, reshape(Core.BFloat16[1 2; 3 4], 2, 2, 1)) - Bb = _to_backend(AT, reshape(Core.BFloat16[1 0; 0 1], 2, 2, 1)) - Cb = _to_backend(AT, zeros(Core.BFloat16, 2, 2, 1)) - NextLA.gemm_batched!( - 'N', 'N', one(Core.BFloat16), [view(Ab, :, :, 1)], - [view(Bb, :, :, 1)], zero(Core.BFloat16), - [view(Cb, :, :, 1)]) - sync(Cb) - @test Float32.(Array(Cb[:, :, 1])) ≈ Float32[1 2; 3 4] - end - end - A_batch_ex_dev = _to_backend(AT, deepcopy(A_batch)) B_batch_ex_dev = _to_backend(AT, deepcopy(B_batch)) C_batch_ex_dev = _to_backend(AT, deepcopy(C_batch)) @@ -181,7 +187,7 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = B_batch3_dev = _to_backend(AT, copy(B_batch3)) C_batch3_dev = _to_backend(AT, copy(C_batch3)) - # strided 3d batches should resolve to the backend-specific implementation. + # Strided 3-D batches resolve to the backend-specific method. @test occursin(_expected_gemm_batched_file(name), _method_file(NextLA.gemm_batched!, transA_batch, transB_batch, alpha_batch, A_batch3_dev, B_batch3_dev, beta_batch, C_batch3_dev)) @test_logs min_level=Logging.Warn NextLA.gemm_batched!( transA_batch, transB_batch, alpha_batch, A_batch3_dev, B_batch3_dev, beta_batch, C_batch3_dev @@ -218,7 +224,7 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = sync(C_batch3_half_dev) @test Array(C_batch3_half_dev) ≈ expected_batch3_half else - # unsupported backends should fail visibly + # No mixed-type batches on the CPU, Metal or oneAPI. @test_throws ArgumentError NextLA.gemmEx_batched!( transA_batch, transB_batch, alpha_batch, _to_backend(AT, cat(A_batch_mixed..., dims = 3)), @@ -287,17 +293,7 @@ _apply_transpose(A::AbstractMatrix, trans::Char) = end @testset "persistent batch pointer descriptors" begin - # `BatchPtrDescriptor` exists so a caller issuing the same batched-GEMM - # shape on many successive calls (one per ARA sampling pass, say) can - # build the device pointer table once instead of paying a fresh - # allocate/upload/free on every call, as the `Vector`-of-matrix - # `gemm_batched!`/`gemmEx_batched!` methods do. These tests check: (1) a - # descriptor drives a batched GEMM to the same result as the transient - # pointer-batch path, (2) `swap_batch_ptrs!` moves which address a slot - # refers to without touching the underlying data, single-slot and block - # forms, and (3) CPU (and any backend without a `_build_batch_ptrs` - # method) fails to construct one, since CPU batched GEMM never needs a - # pointer array. + # BatchPtrDescriptor: same result as a pointer batch, slot and block swaps, refused on the CPU. transA_d, transB_d = 'N', 'N' alpha_d, beta_d = Float32(2), Float32(0.5) mode_d = NextLA.GEMMCompute{Float32}() @@ -330,13 +326,7 @@ end @test Array(C_dev[i]) ≈ expected_d[i] end - # Single-slot swap: only Cd2 is swapped, not Ad/Bd, so slot k - # still computes with A[k]/B[k] but accumulates into whatever - # C address slot k's swapped pointer now targets. Swapping - # slots 1 and 3 means slot 1 writes alpha*A[1]*B[1] + - # beta*C_batch_d[3] into C_dev2[3]'s memory (untouched by the - # swap itself), and slot 3 writes alpha*A[3]*B[3] + - # beta*C_batch_d[1] into C_dev2[1]'s memory. + # Single-slot swap of C slots 1 and 3: each slot writes its product into the other's C memory. C_dev2 = _to_backend(AT, deepcopy(C_batch_d)) Cd2 = BatchPtrDescriptor(C_dev2) swap_batch_ptrs!(Cd2, 1, 3) @@ -351,9 +341,7 @@ end @test Array(C_dev2[2]) ≈ expected_d[2] @test Array(C_dev2[1]) ≈ mix(3, 1) - # Block swap (blocklen=2): descriptor slots [1,2,3,4] holding - # members [D1,D2,D3,D4] become [D3,D4,D1,D2] after swapping - # the two-slot blocks at member offsets 1 and 2. + # Block swap (blocklen = 2): slots holding D1, D2, D3, D4 hold D3, D4, D1, D2 afterwards. D_batch = [Float32[1 0; 0 1], Float32[2 0; 0 2], Float32[0 1; 1 0], Float32[1 1; 0 1]] D_dev = _to_backend(AT, deepcopy(D_batch)) @@ -379,9 +367,8 @@ end end end -# A batch member the CPU cannot hand to BLAS is refused by name rather than -# reaching BLAS.gemm! as a MethodError. -@testset "CPU batch refuses members BLAS cannot take" begin +# The CPU refuses a batch member BLAS cannot take by name, not with a MethodError from BLAS.gemm!. +cpu_wanted() && @testset "CPU batch refuses members BLAS cannot take" begin @test_throws ArgumentError NextLA.gemm_batched!( 'N', 'N', 1.0, rand(Float64, 6, 6, 2), rand(Float32, 6, 6, 2), 0.0, zeros(Float64, 6, 6, 2)) @@ -390,10 +377,7 @@ end [zeros(Float16, 3, 3)]) end -# swap_batch_ptrs! moves a slot on the device; set_batch_ptrs! republishes the -# whole host table to bring one slot across. If the swap is not mirrored into -# the host table, the set silently reverts it and the batch multiplies the -# wrong members -- with no error anywhere. +# A swap of slots stays in place after a later set_batch_ptrs! of another slot. @testset "a swap survives a later set" begin for (name, AT, sync) in backends name in ("CUDA", "AMDGPU") || continue @@ -407,66 +391,19 @@ end @test Array(d.ptrs)[1] == before[2] @test Array(d.ptrs)[2] == before[1] - # touch an unrelated slot; slots 1 and 2 must stay swapped + # Set an unrelated slot; slots 1 and 2 stay swapped. NextLA.set_batch_ptrs!(d, 3, [mats[3]]) @test Array(d.ptrs)[1] == before[2] @test Array(d.ptrs)[2] == before[1] @test Array(d.ptrs)[3] == before[3] - # the two tables agree, which is what makes the next set safe + # The device and host pointer tables agree. @test Array(d.ptrs) == Array(d.host) end end end -# The precision policy is a table, and the table disagreed with itself: the -# BFloat16 row rejected a Float32 destination that the identical Float16 row -# allowed, and Int8 was documented as supported while every backend's answer -# was no. These assert the shared table CUDA and AMDGPU read, not a -# computation, so they run anywhere. -@testset "precision signatures the table claims" begin - sig(TA, TB, TC, W) = NextLA._tensor_core_gemm_supported(TA, TB, TC, W) - - @test sig(Float32, Float32, Float32, Float32) - @test sig(Float64, Float64, Float64, Float64) - @test sig(Float16, Float16, Float16, Float16) - @test sig(Float16, Float16, Float32, Float32) - - # the two that were refused - # Core.BFloat16 exists from Julia 1.11. - isdefined(Core, :BFloat16) && @test sig(Core.BFloat16, Core.BFloat16, Float32, Float32) - @test sig(Int8, Int8, Int32, Int32) - - # and things that must still be refused - @test !sig(Float32, Float32, Float64, Float64) - @test !sig(Float64, Float64, Float64, Float32) -end - -# Widening, not narrowing, when the destination is the narrow one. Rounding the -# operands to Float16 before multiplying loses roughly an order of magnitude -# more than accumulating wide and rounding once on store. -@testset "a narrow destination does not narrow the operands" begin - n = 32 - A = rand(Float32, n, n) - B = rand(Float32, n, n) - C = zeros(Float16, n, n) - NextLA.recgemm!(1.0, A, B, 0.0, C) - ref = Float64.(A) * Float64.(B) - err = maximum(abs.(Float64.(C) .- ref)) / maximum(abs, ref) - # Float16 storage alone costs ~1e-3; rounding the operands first costs an - # order of magnitude more than that. - @test err < 2e-3 -end - -# Backend coverage of the batched entry points. -# -# These run wherever the backend exists. On the machine this was integrated on -# only CPU and CUDA do, so the oneAPI and Metal branches have never executed -- -# they are written so that the first person with the hardware finds out -# immediately rather than discovering it through a wrong result. Metal refuses -# the vector-of-matrices form outright; what matters there is that the refusal -# comes from its own method, not from the generic CPU fallback handing -# BLAS.gemm! a device matrix. +# The batched entry points run on each backend's own method, not the generic CPU fallback. @testset "batched GEMM stays on its backend" begin for (name, AT, sync) in backends name == "CPU" && continue @@ -478,17 +415,12 @@ end Bd = [AT(b) for b in Bh] 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 - # 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. + # The vector-of-matrices form is served by the backend's own method, not the generic loop. @test occursin(_expected_gemm_batched_file(name), _method_file(NextLA.gemm_batched!, 'N', 'N', 1.0f0, Ad, Bd, 0.0f0, Cd)) - # and the same shape through gemmEx_batched!, which reaches - # gemm_batched! via _try_same_type_batched! for a same-type batch + # The same shape through gemmEx_batched!, which reaches gemm_batched! for a same-type batch. Cd2 = [AT(zeros(Float32, n, n)) for _ in 1:nb] if name == "Metal" @test_throws ArgumentError NextLA.gemm_batched!('N', 'N', 1.0f0, Ad, Bd, 0.0f0, Cd) @@ -507,10 +439,117 @@ end end end - # an invalid compute type is diagnosed rather than accepted; oneAPI - # and Metal skipped this check while CUDA and AMDGPU made it + # An invalid compute type throws ArgumentError on every GPU backend. @test_throws ArgumentError NextLA.gemmEx_batched!( 'N', 'N', 1.0f0, Ad, Bd, 0.0f0, Cd2; compute_type=Int8) end end end + +# Accuracy of every member: both entry points, every layout and type, nine transpose pairs, batch 1 and 3. +for (backend_name, ArrayType, synchronize) in available_backends() + backend_name in ("CPU", "CUDA", "AMDGPU") || continue + # Float16 is refused on the CPU (tested below); pointer batches are GPU only. + types = backend_name == "CPU" ? TEST_TYPES : (TEST_TYPES..., Float16) + layouts = backend_name == "CPU" ? (:vector, :array3) : (:vector, :array3, :pointers) + @testset "batched accuracy [$backend_name]" begin + @testset "$(nameof(f)), $layout, $T, $ta$tb, batch $nb" for f in (NextLA.gemm_batched!, NextLA.gemmEx_batched!), + layout in layouts, T in backend_types(ArrayType, types), ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')), nb in test_values(:batch, (1, 3)) + m, n, k = 17, 9, 5 + As = [ta == 'N' ? rand(T, m, k) .- T(0.5) : rand(T, k, m) .- T(0.5) for _ in 1:nb] + Bs = [tb == 'N' ? rand(T, k, n) .- T(0.5) : rand(T, n, k) .- T(0.5) for _ in 1:nb] + Cs = [rand(T, m, n) .- T(0.5) for _ in 1:nb] + α, β = T(1.5), T(-0.5) + if layout == :vector + Cd = [ArrayType(copy(c)) for c in Cs] + f(ta, tb, α, [ArrayType(a) for a in As], [ArrayType(b) for b in Bs], β, Cd) + synchronize(Cd[1]) + res = [Array(c) for c in Cd] + elseif layout == :pointers + Ad, Bd, Cd = [ArrayType(a) for a in As], [ArrayType(b) for b in Bs], [ArrayType(copy(c)) for c in Cs] + Ap, Bp, Cp = (_device_pointer_batch(backend_name, X) for X in (Ad, Bd, Cd)) + f(ta, tb, α, Ap, Ad[1], Bp, Bd[1], β, Cp, Cd[1], nb) + synchronize(Cd[1]) + res = [Array(c) for c in Cd] + else + Cd = ArrayType(cat(Cs..., dims=3)) + f(ta, tb, α, ArrayType(cat(As..., dims=3)), ArrayType(cat(Bs..., dims=3)), β, Cd) + synchronize(Cd) + res = [Array(Cd)[:, :, i] for i in 1:nb] + end + @test maximum(gemm_ratio(res[i], ta, tb, α, As[i], Bs[i], β, Cs[i]; eps=gemm_eps(T, T)) for i in 1:nb) <= BLAS_TEST_THRESHOLD + end + + # A 3-D batch of one A (or one B) against three C: the single member is reused for each C (batch stride 0). + @testset "$(nameof(f)), one $single against three C, $T" for f in (NextLA.gemm_batched!, NextLA.gemmEx_batched!), + single in (:A, :B), T in backend_types(ArrayType, filter(T -> !(T <: Complex), types)) + m, n, k = 17, 9, 5 + A = rand(T, m, k, single == :A ? 1 : 3) .- T(0.5) + B = rand(T, k, n, single == :B ? 1 : 3) .- T(0.5) + C0 = rand(T, m, n, 3) .- T(0.5) + Cd = ArrayType(copy(C0)) + f('N', 'N', T(1.5), ArrayType(A), ArrayType(B), T(-0.5), Cd) + synchronize(Cd) + res = Array(Cd) + @test maximum(gemm_ratio(res[:, :, i], 'N', 'N', 1.5, A[:, :, min(i, end)], B[:, :, min(i, end)], -0.5, C0[:, :, i]; + eps=gemm_eps(T, T)) for i in 1:3) <= BLAS_TEST_THRESHOLD + end + + @testset "a 3-D batch with no members" begin + C = ArrayType(zeros(Float32, 3, 3, 0)) + @test NextLA.gemm_batched!('N', 'N', 1f0, ArrayType(zeros(Float32, 3, 3, 0)), ArrayType(zeros(Float32, 3, 3, 0)), 0f0, C) === C + end + + @testset "members with k = 0 leave beta C" begin + C = ArrayType(ones(Float32, 3, 3, 2)) + NextLA.gemm_batched!('N', 'N', 1f0, ArrayType(zeros(Float32, 3, 0, 2)), ArrayType(zeros(Float32, 0, 3, 2)), 0.5f0, C) + synchronize(C) + @test all(Array(C) .== 0.5f0) + end + + @testset "batches of different lengths throw DimensionMismatch" begin + @test_throws DimensionMismatch NextLA.gemm_batched!('N', 'N', 1f0, [ArrayType(rand(Float32, 2, 2))], + [ArrayType(rand(Float32, 2, 2)), ArrayType(rand(Float32, 2, 2))], 0f0, [ArrayType(zeros(Float32, 2, 2))]) + end + end +end + +# The batched and precision entry points refuse Float16 on the CPU; only single-matrix gemmEx! widens. +cpu_wanted() && @testset "batched and precision refuse Float16" begin + n = 4 + A, B = rand(Float16, n, n), rand(Float16, n, n) + mode = NextLA.GEMMCompute{Float32}() + @test !NextLA.gemm_signature_supported( + KernelAbstractions.CPU(), Float16, Float16, Float32, mode) + @test_throws ArgumentError NextLA.precision_gemm!( + 'N', 'N', 1.0f0, A, B, 0.0f0, zeros(Float32, n, n), mode) + @test_throws ArgumentError NextLA.gemmEx_batched!( + 'N', 'N', 1.0, rand(Float16, n, n, 2), rand(Float16, n, n, 2), + 0.0, zeros(Float32, n, n, 2)) + @test_throws ArgumentError NextLA.gemm_batched!( + 'N', 'N', 1.0f0, rand(Float16, n, n, 2), rand(Float16, n, n, 2), + 0.0f0, zeros(Float16, n, n, 2)) + @test_throws ArgumentError NextLA.gemmEx_batched!( + 'N', 'N', 1.0f0, rand(Float16, n, n, 2), rand(Float16, n, n, 2), + 0.0f0, zeros(Float16, n, n, 2)) + @test_throws ArgumentError NextLA.gemmEx_batched!( + 'N', 'N', 1.0f0, [rand(Float16, n, n)], [rand(Float16, n, n)], 0.0f0, [zeros(Float16, n, n)]) +end + +# The precision entry points take real Float32 and Float64 only; complex is refused by name on every backend. +@testset "precision GEMM refuses complex, $T [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends(), + T in backend_types(ArrayType, (ComplexF32, ComplexF64)) + A, B, C = ArrayType(rand(T, 4, 4)), ArrayType(rand(T, 4, 4)), ArrayType(zeros(T, 4, 4)) + @test_throws ArgumentError NextLA.precision_gemm!('N', 'N', one(T), A, B, zero(T), C, NextLA.GEMMCompute{T}()) + @test_throws ArgumentError NextLA.precision_gemm_batched!('N', 'N', one(T), [A], [B], zero(T), [C], NextLA.GEMMCompute{T}()) +end + +# Pointer batches are refused on the CPU, as intended (no CPU _build_batch_ptrs). +cpu_wanted() && @testset "pointer batches remain unsupported" begin + n = 4 + A, B = rand(Float32, n, n), rand(Float32, n, n) + C = zeros(Float32, n, n) + @test !NextLA.supports_pointer_batched(KernelAbstractions.CPU()) + @test_throws ArgumentError NextLA.gemm_batched_ptrs!( + 'N', 'N', 1.0f0, nothing, A, nothing, B, 0.0f0, nothing, C, 1) +end diff --git a/test/dense/blas/gemm/gemm_grouped.jl b/test/dense/blas/gemm/gemm_grouped.jl new file mode 100644 index 00000000..e38c8754 --- /dev/null +++ b/test/dense/blas/gemm/gemm_grouped.jl @@ -0,0 +1,192 @@ +# precision_gemm_grouped!, prepared grouped GEMM (src/dense/blas/gemm/gemm_grouped.jl); B19 untested. + +using Test + +# Small fixed tasks: the CPU loop and its prepared replay; on CUDA two groups, Float16 storage and a misaligned operand. +@testset "grouped GEMM" begin + @test NextLA.supports_grouped_gemm(KernelAbstractions.CPU()) + A_cpu = Float32[1 2; 3 4] + B_cpu = Float32[2 0 1; 1 3 4] + C_cpu = fill(0.5f0, 2, 3) + cpu_task = NextLA.GroupedGemmTask( + 'N', 'N', 2.0f0, A_cpu, B_cpu, 0.5f0, C_cpu) + cpu_expected = 2f0 .* (A_cpu * B_cpu) .+ 0.5f0 .* fill(0.5f0, 2, 3) + NextLA.precision_gemm_grouped!([cpu_task], NextLA.GEMMCompute{Float32}()) + @test C_cpu ≈ cpu_expected + + prepared_cpu = NextLA.prepare_precision_gemm_grouped( + [cpu_task], NextLA.GEMMCompute{Float32}()) + @test prepared_cpu isa NextLA.CPUPreparedGroupedGemm + fill!(C_cpu, 1f0) + NextLA.precision_gemm_grouped_prepared!(prepared_cpu, 3f0, -0.25f0) + @test C_cpu ≈ 3f0 .* (A_cpu * B_cpu) .- 0.25f0 + NextLA.destroy_prepared_grouped_gemm!(prepared_cpu) + + for (name, AT, sync) in backends + name == "CUDA" || continue + A1 = _to_backend(AT, Float32[1 2; 3 4]) + B1 = _to_backend(AT, Float32[2 0 1; 1 3 4]) + C1 = _to_backend(AT, fill(0.5f0, 2, 3)) + C3 = _to_backend(AT, fill(0.25f0, 2, 3)) + A2 = _to_backend(AT, Float32[1 2 3]) + B2 = _to_backend(AT, reshape(Float32[2, 4, 1], 3, 1)) + C2 = _to_backend(AT, reshape(Float32[3], 1, 1)) + expected1 = 2f0 .* (Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4]) .+ 0.5f0 .* fill(0.5f0, 2, 3) + expected3 = Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4] + expected2 = 3f0 .* (Float32[1 2 3] * Float32[2; 4; 1]) .+ 0.25f0 .* reshape(Float32[3], 1, 1) + tasks = [ + NextLA.GroupedGemmTask('N', 'N', 2f0, A1, B1, 0.5f0, C1), + NextLA.GroupedGemmTask('N', 'N', 3f0, A2, B2, 0.25f0, C2), + # Same shape as the first task, other alpha/beta: a second cuBLAS group. + NextLA.GroupedGemmTask('N', 'N', 1f0, A1, B1, 0f0, C3), + ] + NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float32}()) + sync(C1) + @test Array(C1) ≈ expected1 + @test Array(C2) ≈ expected2 + @test Array(C3) ≈ expected3 + + Ah = _to_backend(AT, Float16[1 2; 3 4]) + Bh = _to_backend(AT, Float16[2 0 1; 1 3 4]) + Ch = _to_backend(AT, fill(Float16(0.5), 2, 3)) + mixed = [NextLA.GroupedGemmTask('N', 'N', 2f0, Ah, Bh, 0.5f0, Ch)] + NextLA.precision_gemm_grouped!(mixed, NextLA.GEMMCompute{Float32}()) + sync(Ch) + @test Float32.(Array(Ch)) ≈ 2f0 .* (Float32.(Float16[1 2; 3 4]) * + Float32.(Float16[2 0 1; 1 3 4])) .+ 0.25f0 + + # An operand offset by one Float32 element goes through ordinary GEMMEx, not grouped cuBLAS. + Astore = _to_backend(AT, Float32[0 0; 1 2; 3 4]) + Aunsafe = view(Astore, 2:3, :) + Cunsafe = _to_backend(AT, zeros(Float32, 2, 3)) + unsafe = [NextLA.GroupedGemmTask('N', 'N', 1f0, Aunsafe, B1, 0f0, Cunsafe)] + NextLA.precision_gemm_grouped!(unsafe, NextLA.GEMMCompute{Float32}()) + sync(Cunsafe) + @test Array(Cunsafe) ≈ Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4] + prepared_unsafe = NextLA.prepare_precision_gemm_grouped( + unsafe, NextLA.GEMMCompute{Float32}()) + @test prepared_unsafe isa NextLA.PreparedGroupedGemmBundle + fill!(Cunsafe, 0f0) + NextLA.precision_gemm_grouped_prepared!(prepared_unsafe) + sync(Cunsafe) + @test Array(Cunsafe) ≈ Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4] + NextLA.destroy_prepared_grouped_gemm!(prepared_unsafe) + end +end + +# Random heterogeneous tasks: sizes 1 to 40, every transpose pair, mixed signs. +function _grouped_tasks(ArrayType, TA, TC, ntask) + host, tasks = [], [] + for _ in 1:ntask + ta, tb = rand(('N', 'T', 'C')), rand(('N', 'T', 'C')) + m, n, k = rand(1:40), rand(1:40), rand(1:40) + A = ta == 'N' ? rand(TA, m, k) .- TA(0.5) : rand(TA, k, m) .- TA(0.5) + B = tb == 'N' ? rand(TA, k, n) .- TA(0.5) : rand(TA, n, k) .- TA(0.5) + C = rand(TC, m, n) .- TC(0.5) + push!(host, (ta, tb, A, B, copy(C))) + push!(tasks, NextLA.GroupedGemmTask(ta, tb, 1.5f0, ArrayType(A), ArrayType(B), -0.5f0, ArrayType(C))) + end + return host, [t for t in tasks] +end + +_grouped_ratio(host, tasks, α, β, e) = + maximum(gemm_ratio(t.C, h[1], h[2], α, h[3], h[4], β, h[5]; eps=e) for (h, t) in zip(host, tasks)) + +# A backend without grouped GEMM refuses it by name. +for (backend_name, ArrayType, synchronize) in available_backends() + NextLA.supports_grouped_gemm(NextLA.get_backend(ArrayType(zeros(Float32, 1, 1)))) && continue + @testset "grouped GEMM is refused [$backend_name]" begin + t = NextLA.GroupedGemmTask('N', 'N', 1f0, ArrayType(rand(Float32, 2, 2)), ArrayType(rand(Float32, 2, 2)), + 0f0, ArrayType(zeros(Float32, 2, 2))) + @test_throws ArgumentError NextLA.precision_gemm_grouped!([t], NextLA.GEMMCompute{Float32}()) + end +end + +for (backend_name, ArrayType, synchronize) in available_backends() + NextLA.supports_grouped_gemm(NextLA.get_backend(ArrayType(zeros(Float32, 1, 1)))) || continue + @testset "grouped GEMM accuracy and edge cases [$backend_name]" begin + @testset "$T, GEMMCompute{$T}" for T in backend_types(ArrayType, (Float32, Float64)) + host, tasks = _grouped_tasks(ArrayType, T, T, 12) + NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{T}()) + synchronize(tasks[1].C) + @test _grouped_ratio(host, tasks, 1.5, -0.5, gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + + if backend_name == "CUDA" + # TF32 rounds the operands to 10 fraction bits. + @testset "Float32, TF32" begin + host, tasks = _grouped_tasks(ArrayType, Float32, Float32, 12) + NextLA.precision_gemm_grouped!(tasks, NextLA.TF32()) + synchronize(tasks[1].C) + @test _grouped_ratio(host, tasks, 1.5, -0.5, 2.0^-10) <= BLAS_TEST_THRESHOLD + end + # Float16 storage accumulates in Float32. + @testset "Float16 storage, Float32 compute" begin + host, tasks = _grouped_tasks(ArrayType, Float16, Float16, 12) + NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float32}()) + synchronize(tasks[1].C) + @test _grouped_ratio(host, tasks, 1.5, -0.5, gemm_eps(Float32, Float16)) <= BLAS_TEST_THRESHOLD + end + # Float16 compute is computed or refused by name; cuBLAS throws NOT_SUPPORTED instead (B47). + @testset "Float16 storage, Float16 compute" begin + host, tasks = _grouped_tasks(ArrayType, Float16, Float16, 4) + outcome = try + NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float16}()) + synchronize(tasks[1].C) + _grouped_ratio(host, tasks, 1.5, -0.5, gemm_eps(Float16, Float16)) <= BLAS_TEST_THRESHOLD + catch e + e isa ArgumentError + end + @test_broken outcome + end + end + + if backend_name == "CPU" + @testset "Float16 tasks are refused, GEMMCompute{$W}" for W in (Float16, Float32) + host, tasks = _grouped_tasks(ArrayType, Float16, Float16, 2) + @test_throws ArgumentError NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{W}()) + end + end + + # The prepared group replays its tasks with new scalars (CUDA needs host pointer mode: B18). + @testset "prepared replay with new α and β" begin + host, tasks = _grouped_tasks(ArrayType, Float32, Float32, 10) + P = NextLA.prepare_precision_gemm_grouped(tasks, NextLA.GEMMCompute{Float32}()) + NextLA.with_grouped_host_pointer_mode(NextLA.get_backend(tasks[1].C)) do + NextLA.precision_gemm_grouped_prepared!(P, 2f0, 0.25f0) + end + synchronize(tasks[1].C) + @test _grouped_ratio(host, tasks, 2.0, 0.25, gemm_eps(Float32, Float32)) <= BLAS_TEST_THRESHOLD + NextLA.destroy_prepared_grouped_gemm!(P) + end + + # The signature table refuses complex grouped GEMM on every backend. + @testset "complex tasks are refused, $T" for T in backend_types(ArrayType, (ComplexF32, ComplexF64)) + t = NextLA.GroupedGemmTask('N', 'N', 1f0, ArrayType(rand(T, 2, 2)), ArrayType(rand(T, 2, 2)), + 0f0, ArrayType(zeros(T, 2, 2))) + @test_throws ArgumentError NextLA.precision_gemm_grouped!([t], NextLA.GEMMCompute{T}()) + end + + @testset "no tasks, an empty task, k = 0" begin + empty = NextLA.GroupedGemmTask[] + @test NextLA.precision_gemm_grouped!(empty, NextLA.GEMMCompute{Float32}()) === empty + t0 = NextLA.GroupedGemmTask('N', 'N', 1f0, ArrayType(zeros(Float32, 0, 3)), ArrayType(zeros(Float32, 3, 2)), + 0f0, ArrayType(zeros(Float32, 0, 2))) + NextLA.precision_gemm_grouped!([t0], NextLA.GEMMCompute{Float32}()) + @test size(t0.C) == (0, 2) + tk = NextLA.GroupedGemmTask('N', 'N', 1f0, ArrayType(zeros(Float32, 3, 0)), ArrayType(zeros(Float32, 0, 2)), + 0.5f0, ArrayType(ones(Float32, 3, 2))) + NextLA.precision_gemm_grouped!([tk], NextLA.GEMMCompute{Float32}()) + synchronize(tk.C) + @test all(Array(tk.C) .== 0.5f0) + end + + if backend_name != "CPU" + @testset "operands on two backends are refused" begin + t = NextLA.GroupedGemmTask('N', 'N', 1f0, rand(Float32, 2, 2), ArrayType(rand(Float32, 2, 2)), + 0f0, ArrayType(zeros(Float32, 2, 2))) + @test_throws ArgumentError NextLA.precision_gemm_grouped!([t], NextLA.GEMMCompute{Float32}()) + end + end + end +end diff --git a/test/dense/blas/gemm/gemm_precision.jl b/test/dense/blas/gemm/gemm_precision.jl new file mode 100644 index 00000000..7e1ec8e2 --- /dev/null +++ b/test/dense/blas/gemm/gemm_precision.jl @@ -0,0 +1,103 @@ +# precision_gemm!, precision_gemm_batched! and the signature table (src/dense/blas/gemm/gemm_precision.jl). + +test_params(m = "rows of C", n = "columns of C", k = "inner dimension") # the number options it takes (--params) + +# gemm_ratio against a Float64 reference, for sizes where BigFloat is too slow. +function _gp_ratio64(C, ta, tb, α, A, B, β, C0; eps) + opA, opB, C0h = _test_op(Float64.(Array(A)), ta), _test_op(Float64.(Array(B)), tb), Float64.(Array(C0)) + exact = Float64(α) .* (opA * opB) .+ Float64(β) .* C0h + gauge = abs(Float64(α)) .* (abs.(opA) * abs.(opB)) .+ abs(Float64(β)) .* abs.(C0h) + return maximum(_elem_ratio.(abs.(Float64.(Array(C)) .- exact), gauge); init=0.0) / eps +end + +# gemm_ratio (BigFloat) on the top-left 4x4 block of C: for Float64 data the Float64 reference is the same dgemm as the CPU path. +function _gp_block(C, ta, tb, α, A, B, β, C0; eps) + r, c = 1:min(4, size(C0, 1)), 1:min(4, size(C0, 2)) + return gemm_ratio(Array(C)[r, c], ta, tb, α, ta == 'N' ? A[r, :] : A[:, r], tb == 'N' ? B[:, c] : B[c, :], β, C0[r, c]; eps) +end + +# q in each position of p + q - p: |p| = 1.5 * 2^e absorbs q in a narrow sum taken in any order, in two rows at least. +_gp_absorb(p, q) = Float16[q p -p; p q -p; p -p q] + +# (operand type, C type, mode, bound eps) per signature: GEMMCompute{W} in eps of W and C; TF32 (10 fraction bits) in 2^-10. +function _gp_modes(name, AT) + modes = Any[(Float32, Float32, NextLA.GEMMCompute{Float32}(), gemm_eps(Float32, Float32)), + (Float64, Float64, NextLA.GEMMCompute{Float64}(), gemm_eps(Float64, Float64))] + if name in ("CUDA", "AMDGPU") + push!(modes, (Float16, Float16, NextLA.GEMMCompute{Float16}(), gemm_eps(Float16, Float16)), + (Float16, Float16, NextLA.GEMMCompute{Float32}(), gemm_eps(Float32, Float16)), + (Float16, Float32, NextLA.GEMMCompute{Float32}(), gemm_eps(Float32, Float32))) + name == "CUDA" && push!(modes, (Float32, Float32, NextLA.TF32(), Float64(eps(Float16)))) + end + return Tuple(c for c in modes if length(backend_types(AT, unique(c[1:2]))) == length(unique(c[1:2]))) +end + +# Metal and oneAPI have no gemmEx!, which precision_gemm! calls on a device, so they are not run. +for (backend_name, ArrayType, synchronize) in filter(b -> b[1] in ("CPU", "CUDA", "AMDGPU"), available_backends()) + @testset "PRECISION GEMM [$backend_name]" begin + # Accuracy of every signature the backend takes, small and big (n, 2n, 4n), against a Float64 reference. + @testset "precision_gemm! $TA -> $TC, $(typeof(mode)), $ta$tb, m=$m n=$n k=$k" for (TA, TC, mode, ε) in _gp_modes(backend_name, ArrayType), + ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')), + (m, n, k) in test_cases((:m, :n, :k), ((17, 9, 5), (256, 256, 256), (512, 512, 512), (1024, 1024, 1024))) + A = ta == 'N' ? rand(TA, m, k) .- TA(0.5) : rand(TA, k, m) .- TA(0.5) + B = tb == 'N' ? rand(TA, k, n) .- TA(0.5) : rand(TA, n, k) .- TA(0.5) + C0 = rand(TC, m, n) .- TC(0.5) + Cd = ArrayType(copy(C0)) + NextLA.precision_gemm!(ta, tb, TC(1.5), ArrayType(A), ArrayType(B), TC(-0.5), Cd, mode) + synchronize(Cd) + @test _gp_ratio64(Cd, ta, tb, 1.5, A, B, -0.5, C0; eps=ε) <= BLAS_TEST_THRESHOLD + TA === TC === Float64 && @test _gp_block(Cd, ta, tb, 1.5, A, B, -0.5, C0; eps=ε) <= BLAS_TEST_THRESHOLD + end + + # The batched entry point, vector and 3-D batches of three, every member against a Float64 reference. + @testset "precision_gemm_batched! $TA -> $TC, $(typeof(mode)), $layout, $ta$tb, n=$n" for (TA, TC, mode, ε) in _gp_modes(backend_name, ArrayType), + layout in (:vector, :array3), ta in test_flags(:trans, ('N', 'T')), tb in test_flags(:trans, ('N', 'T')), n in test_values(:n, (9, 256)) + m, k = n + 8, n ÷ 2 + 1 + As = [ta == 'N' ? rand(TA, m, k) .- TA(0.5) : rand(TA, k, m) .- TA(0.5) for _ in 1:3] + Bs = [tb == 'N' ? rand(TA, k, n) .- TA(0.5) : rand(TA, n, k) .- TA(0.5) for _ in 1:3] + Cs = [rand(TC, m, n) .- TC(0.5) for _ in 1:3] + if layout == :vector + Cd = [ArrayType(copy(c)) for c in Cs] + NextLA.precision_gemm_batched!(ta, tb, TC(1.5), [ArrayType(a) for a in As], [ArrayType(b) for b in Bs], TC(-0.5), Cd, mode) + synchronize(Cd[1]) + res = [Array(c) for c in Cd] + else + Cd = ArrayType(cat(Cs..., dims=3)) + NextLA.precision_gemm_batched!(ta, tb, TC(1.5), ArrayType(cat(As..., dims=3)), ArrayType(cat(Bs..., dims=3)), TC(-0.5), Cd, mode) + synchronize(Cd) + res = [Array(Cd)[:, :, i] for i in 1:3] + end + @test maximum(_gp_ratio64(res[i], ta, tb, 1.5, As[i], Bs[i], -0.5, Cs[i]; eps=ε) for i in 1:3) <= BLAS_TEST_THRESHOLD + TA === TC === Float64 && @test maximum(_gp_block(res[i], ta, tb, 1.5, As[i], Bs[i], -0.5, Cs[i]; eps=ε) for i in 1:3) <= BLAS_TEST_THRESHOLD + end + + # GEMMCompute{Float32} over Float16 storage and C: 0.5 survives 3072 + 0.5 - 3072 exactly (Float16 compute loses it). + backend_name in ("CUDA", "AMDGPU") && @testset "precision_gemm! Float16 storage, GEMMCompute{Float32}, exact, $ta$tb" for (ta, tb) in (('N', 'N'), ('N', 'T')) + A = ta == 'N' ? _gp_absorb(3072, 0.5) : permutedims(_gp_absorb(3072, 0.5)) + B = tb == 'N' ? ones(Float16, 3, 2) : ones(Float16, 2, 3) + Cd = ArrayType(zeros(Float16, 3, 2)) + NextLA.precision_gemm!(ta, tb, Float16(-1), ArrayType(A), ArrayType(B), Float16(1), Cd, NextLA.GEMMCompute{Float32}()) + synchronize(Cd) + @test Array(Cd) == fill(Float16(-0.5), 3, 2) + end + end +end + +# The signature table CUDA and AMDGPU read; no computation, so it runs anywhere. +cpu_wanted() && @testset "precision signatures the table claims" begin + sig(TA, TB, TC, W) = NextLA._tensor_core_gemm_supported(TA, TB, TC, W) + + @test sig(Float32, Float32, Float32, Float32) + @test sig(Float64, Float64, Float64, Float64) + @test sig(Float16, Float16, Float16, Float16) + @test sig(Float16, Float16, Float32, Float32) + + # Int8 operands into Int32 are allowed. + @test sig(Int8, Int8, Int32, Int32) + + # Signatures that stay refused. + @test !sig(Float32, Float32, Float64, Float64) + @test !sig(Float64, Float64, Float64, Float32) + @test !sig(ComplexF32, ComplexF32, ComplexF32, ComplexF32) + @test !sig(ComplexF64, ComplexF64, ComplexF64, ComplexF64) +end diff --git a/test/dense/blas/gemm/gemm_types.jl b/test/dense/blas/gemm/gemm_types.jl new file mode 100644 index 00000000..bab9b3c5 --- /dev/null +++ b/test/dense/blas/gemm/gemm_types.jl @@ -0,0 +1,12 @@ +# GEMM_COMPUTE_TYPES and default_compute_type (src/dense/blas/gemm/gemm_types.jl). + +cpu_wanted() && @testset "GEMM compute types" begin + @test NextLA.GEMM_COMPUTE_TYPES == (Float16, Float32, Float64, ComplexF32, ComplexF64, Int32) + @test NextLA.default_compute_type(Float16(1), Float16[1 2; 3 4], Float16[1 0; 0 1], Float16(0), Float16[0 0; 0 0]) == Float16 +end + +# Same-type storage computes in its own type, whatever the scalars. +cpu_wanted() && @testset "default compute type of $T storage" for T in test_types((TEST_TYPES..., Float16)) + A = zeros(T, 2, 2) + @test NextLA.default_compute_type(1.0, A, A, 0.0, A) === T +end diff --git a/test/dense/blas/gemm/matmul.jl b/test/dense/blas/gemm/matmul.jl new file mode 100644 index 00000000..6a832c2c --- /dev/null +++ b/test/dense/blas/gemm/matmul.jl @@ -0,0 +1,169 @@ +# GEMM_ADD! (C .+= s A B) and GEMM_SUB! (A .-= s B C), the matmul! kernel of src/dense/blas/gemm/matmul.jl. + +test_params(m = "rows of C", n = "columns of C", k = "inner dimension") # the number options it takes (--params) + +# Float16 sums in Float32 and is rounded once to Float16. +_mm_eps(T) = T === Float16 ? gemm_eps(Float32, Float16) : gemm_eps(T, T) + +# gemm_ratio against a Float64 reference, for sizes where BigFloat is too slow. +function _mm_ratio64(C, ta, tb, α, A, B, β, C0; eps) + opA, opB, C0h = _test_op(Float64.(Array(A)), ta), _test_op(Float64.(Array(B)), tb), Float64.(Array(C0)) + exact = Float64(α) .* (opA * opB) .+ Float64(β) .* C0h + gauge = abs(Float64(α)) .* (abs.(opA) * abs.(opB)) .+ abs(Float64(β)) .* abs.(C0h) + return maximum(_elem_ratio.(abs.(Float64.(Array(C)) .- exact), gauge); init=0.0) / eps +end + +# Long sums: the element ratio grows like sqrt(k) (probabilistic bound λ√n·u, Higham & Mary 2019), so the bound does too. +_mm_bound(k) = BLAS_TEST_THRESHOLD * max(1, sqrt(k / 256)) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "MATMUL [$backend_name]" begin + # Every type, every operand form, sizes off and on the 32 tile, mixed signs, complex scale for complex. + @testset "GEMM_ADD! $T, $ta$tb, n=$n r=$r m=$m" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), + ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')), + (n, r, m) in test_cases((:m, :k, :n), ((16, 16, 16), (33, 17, 9), (64, 32, 16), (16, 96, 16))) + A = ta == 'N' ? rand(T, n, r) .- T(0.5) : rand(T, r, n) .- T(0.5) + B = tb == 'N' ? rand(T, r, m) .- T(0.5) : rand(T, m, r) .- T(0.5) + C0 = rand(T, n, m) .- T(0.5) + sc = T <: Complex ? T(1.5, 0.5) : T(1.5) + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(_test_op(ArrayType(A), ta), _test_op(ArrayType(B), tb), Cd, sc) + synchronize(Cd) + @test gemm_ratio(Cd, ta, tb, sc, A, B, 1, C0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + end + + # A .-= scale B C, every type. + @testset "GEMM_SUB! $T, scale=$sc" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), sc in (1, 0.5) + A0, B, C = rand(T, 30, 20) .- T(0.5), rand(T, 30, 25) .- T(0.5), rand(T, 25, 20) .- T(0.5) + Ad = ArrayType(copy(A0)) + NextLA.GEMM_SUB!(Ad, ArrayType(B), ArrayType(C), sc) + synchronize(Ad) + @test gemm_ratio(Ad, 'N', 'N', -sc, B, C, 1, A0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + end + + @testset "GEMM_ADD! scale=$sc, $T" for T in (supports_float64(ArrayType) ? Float64 : Float32,), sc in (1, 2.5, -0.5) + A, B, C0 = rand(T, 32, 24), rand(T, 24, 16), rand(T, 32, 16) + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(ArrayType(A), ArrayType(B), Cd, sc) + synchronize(Cd) + @test gemm_ratio(Cd, 'N', 'N', sc, A, B, 1, C0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + end + + # Partial second row, column and inner tiles of 32 (m, k, n = 33, 40, 40), every operand form. + @testset "GEMM_ADD! $T, $ta$tb, m=33 k=40 n=40" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + ta in test_flags(:trans, ('N', 'T', 'C')), tb in test_flags(:trans, ('N', 'T', 'C')) + n, r, m = 33, 40, 40 + A = ta == 'N' ? rand(T, n, r) .- T(0.5) : rand(T, r, n) .- T(0.5) + B = tb == 'N' ? rand(T, r, m) .- T(0.5) : rand(T, m, r) .- T(0.5) + C0 = rand(T, n, m) .- T(0.5) + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(_test_op(ArrayType(A), ta), _test_op(ArrayType(B), tb), Cd, T(1.5)) + synchronize(Cd) + @test gemm_ratio(Cd, ta, tb, 1.5, A, B, 1, C0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + end + + # Long sums k = 1024, 2048, 4096 (32 to 128 inner tiles), Float64 reference; positive entries, so the sums grow with k. + @testset "GEMM_ADD! $T, m=64 k=$k n=64" for T in backend_types(ArrayType, (Float16, Float32, Float64)), k in test_values(:k, (1024, 2048, 4096)) + A, B, C0 = rand(T, 64, k), rand(T, k, 64), rand(T, 64, 64) + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(ArrayType(A), ArrayType(B), Cd) + synchronize(Cd) + @test _mm_ratio64(Cd, 'N', 'N', 1, A, B, 1, C0; eps=_mm_eps(T)) <= _mm_bound(k) + end + + # Big squares n = 256, 512, 1024 (8 to 32 tiles a side), plain and with a transposed A, Float64 reference. + @testset "GEMM_ADD! $T, $ta, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), ta in test_flags(:trans, ('N', 'T')), n in test_values(:n, (256, 512, 1024)) + A, B, C0 = rand(T, n, n) .- T(0.5), rand(T, n, n) .- T(0.5), rand(T, n, n) .- T(0.5) + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(_test_op(ArrayType(A), ta), ArrayType(B), Cd, T(-1)) + synchronize(Cd) + @test _mm_ratio64(Cd, ta, 'N', -1, A, B, 1, C0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + end + + # An empty dimension: nothing to add for r = 0, nothing to do for n or m = 0. + @testset "n=$n r=$r m=$m" for (n, r, m) in ((0, 4, 5), (4, 0, 5), (4, 5, 0), (1, 1, 1)) + A, B, C0 = rand(Float32, n, r), rand(Float32, r, m), rand(Float32, n, m) + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(ArrayType(A), ArrayType(B), Cd) + synchronize(Cd) + @test size(Cd) == (n, m) + if r == 0 || n * m == 0 + @test Array(Cd) == C0 + else + @test gemm_ratio(Cd, 'N', 'N', 1, A, B, 1, C0; eps=_mm_eps(Float32)) <= BLAS_TEST_THRESHOLD + end + end + + # Strided views as an operand and as the output; the rest of the output's parent is unchanged. + @testset "strided views" begin + P, M0, B = rand(Float32, 20, 20), rand(Float32, 40, 40), rand(Float32, 6, 5) + M = ArrayType(copy(M0)) + Av = view(ArrayType(P), 1:2:15, 1:6) + NextLA.GEMM_ADD!(Av, ArrayType(B), view(M, 2:2:16, 3:7)) + synchronize(M) + Mh = Array(M) + @test gemm_ratio(Mh[2:2:16, 3:7], 'N', 'N', 1, P[1:2:15, 1:6], B, 1, M0[2:2:16, 3:7]; eps=_mm_eps(Float32)) <= BLAS_TEST_THRESHOLD + Mh[2:2:16, 3:7] .= M0[2:2:16, 3:7] + @test Mh == M0 + end + + # Views of a transpose or adjoint as operands, as rectrxm's recursion passes them (_untranspose sees a SubArray). + @testset "views of $(nameof(w)) as operands, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)), w in (transpose, adjoint) + P, Q, C0 = rand(T, 50, 50) .- T(0.5), rand(T, 50, 50) .- T(0.5), rand(T, 33, 9) .- T(0.5) + Av, Bv = view(w(ArrayType(P)), 3:35, 2:41), view(w(ArrayType(Q)), 5:44, 1:9) + Ah, Bh = Matrix(w(P))[3:35, 2:41], Matrix(w(Q))[5:44, 1:9] + Cd = ArrayType(copy(C0)) + NextLA.GEMM_ADD!(Av, Bv, Cd, T(1.5)) + synchronize(Cd) + @test gemm_ratio(Cd, 'N', 'N', 1.5, Ah, Bh, 1, C0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + Cd = ArrayType(copy(C0)) + NextLA.GEMM_SUB!(Cd, Av, Bv) + synchronize(Cd) + @test gemm_ratio(Cd, 'N', 'N', -1, Ah, Bh, 1, C0; eps=_mm_eps(T)) <= BLAS_TEST_THRESHOLD + end + + # 16 terms of +40000 then 16 of -40000 sum to 0; a Float16 running sum overflows at the second term. + @testset "Float16 destination accumulates in Float32" begin + A = ArrayType(fill(Float16(200), 32, 32)) + B = ArrayType(Float16[k <= 16 ? 200 : -200 for k in 1:32, j in 1:32]) + C = ArrayType(zeros(Float16, 32, 32)) + NextLA.GEMM_ADD!(A, B, C) + synchronize(C) + @test all(iszero, Array(C)) + end + + # NextLA.gemm! itself on Float16 sums in Float32 on the CPU and CUDA (mul! summed in Float16: Inf here). + backend_name in ("CPU", "CUDA") && @testset "gemm! on Float16 accumulates in Float32, $ta$tb" for ta in ('N', 'T'), tb in ('N', 'T') + A0 = fill(Float16(200), 32, 32) + B0 = Float16[k <= 16 ? 200 : -200 for k in 1:32, j in 1:32] + A = ta == 'N' ? ArrayType(A0) : transpose(ArrayType(copy(transpose(A0)))) + B = tb == 'N' ? ArrayType(B0) : transpose(ArrayType(copy(transpose(B0)))) + C = ArrayType(fill(Float16(NaN), 32, 32)) # beta = 0: C is not read + NextLA.gemm!(C, A, B, 1, 0) + synchronize(C) + @test all(iszero, Array(C)) + end + + # 32 * 200 * 200 is beyond floatmax(Float16): it is Inf, not clamped. + @testset "a Float16 result past floatmax is Inf" begin + A = ArrayType(fill(Float16(200), 32, 32)) + B = ArrayType(fill(Float16(200), 32, 32)) + C = ArrayType(zeros(Float16, 32, 32)) + NextLA.GEMM_ADD!(A, B, C) + synchronize(C) + @test all(isinf, Array(C)) + end + + @testset "shapes that do not fit throw" begin + @test_throws DimensionMismatch NextLA.GEMM_ADD!(ArrayType(rand(Float32, 8, 3)), + ArrayType(rand(Float32, 5, 8)), + ArrayType(zeros(Float32, 8, 8))) + @test_throws DimensionMismatch NextLA.GEMM_ADD!(ArrayType(rand(Float32, 8, 5)), + ArrayType(rand(Float32, 5, 8)), + ArrayType(zeros(Float32, 4, 4))) + @test_throws DimensionMismatch NextLA.GEMM_SUB!(ArrayType(zeros(Float32, 4, 4)), + ArrayType(rand(Float32, 8, 5)), + ArrayType(rand(Float32, 5, 8))) + end + end +end diff --git a/test/dense/blas/gemm/recgemm.jl b/test/dense/blas/gemm/recgemm.jl new file mode 100644 index 00000000..1d47a624 --- /dev/null +++ b/test/dense/blas/gemm/recgemm.jl @@ -0,0 +1,175 @@ +# recgemm! on dense matrices (src/dense/blas/gemm/recgemm.jl): the type dispatch of _gemm_dispatch!. + +test_params(m = "rows of C", n = "columns of C", k = "inner dimension") # the number options it takes (--params) + +# A Float16 triple accumulates in Float32 and is rounded once to Float16. +_rg_eps(T) = T === Float16 ? gemm_eps(Float32, Float16) : gemm_eps(T, T) + +# gemm_ratio against a Float64 reference, for sizes where BigFloat is too slow. +function _rg_ratio64(C, α, A, B, β, C0; eps) + Ah, Bh, C0h = Float64.(Array(A)), Float64.(Array(B)), Float64.(Array(C0)) + exact = Float64(α) .* (Ah * Bh) .+ Float64(β) .* C0h + gauge = abs(Float64(α)) .* (abs.(Ah) * abs.(Bh)) .+ abs(Float64(β)) .* abs.(C0h) + return maximum(_elem_ratio.(abs.(Float64.(Array(C)) .- exact), gauge); init=0.0) / eps +end + +# gemm_ratio (BigFloat) on the top-left 4x4 block of C: for Float64 data the Float64 reference is the same dgemm as the CPU path. +function _rg_block(C, ta, tb, α, A, B, β, C0; eps) + r, c = 1:min(4, size(C0, 1)), 1:min(4, size(C0, 2)) + return gemm_ratio(Array(C)[r, c], ta, tb, α, ta == 'N' ? A[r, :] : A[:, r], tb == 'N' ? B[:, c] : B[c, :], β, C0[r, c]; eps) +end + +# Long sums: the element ratio grows like sqrt(n) (probabilistic bound λ√n·u, Higham & Mary 2019), so the bound does too. +_rg_bound(n) = BLAS_TEST_THRESHOLD * max(1, sqrt(n / 256)) + +# The (A, B, C) types of each _gemm_dispatch! path: same type, Float16 operands, a wider C, a narrower C. +const _RG_PATHS = ((Float16, Float16, Float16), (Float32, Float32, Float32), (Float64, Float64, Float64), + (Float16, Float16, Float32), (Float32, Float32, Float64), (Float16, Float32, Float64), + (Float64, Float64, Float32), (Float64, Float32, Float32), (Float32, Float32, Float16), + (Float32, Float16, Float16)) +_rg_paths(AT, paths = _RG_PATHS) = Tuple(p for p in paths if all(T -> !isempty(backend_types(AT, (T,))), p)) + +# q in each position of p + q - p: |p| = 1.5 * 2^e absorbs q in a narrow sum taken in any order, in two rows at least. +_rg_absorb(p, q) = Float16[q p -p; p q -p; p -p q] + +for (backend_name, ArrayType, synchronize) in filter(b -> b[1] in ("CPU", "CUDA", "AMDGPU"), available_backends()) + @testset "RECGEMM [$backend_name]" begin + @testset "$T, m=$m k=$k n=$n" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), (m, k, n) in test_cases((:m, :k, :n), ((4, 4, 4), (16, 8, 32), (33, 17, 9))) + A, B, C0 = rand(T, m, k) .- T(0.5), rand(T, k, n) .- T(0.5), rand(T, m, n) .- T(0.5) + C = ArrayType(copy(C0)) + NextLA.recgemm!(T(1.5), ArrayType(A), ArrayType(B), T(-0.5), C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 1.5, A, B, -0.5, C0; eps=_rg_eps(T)) <= BLAS_TEST_THRESHOLD + end + + # Empty, 1x1 and k = 0 shapes on every path; k = 0 leaves exactly beta C. + @testset "$TA, $TB -> $TC, m=$m k=$k n=$n" for (TA, TB, TC) in _rg_paths(ArrayType), + (m, k, n) in ((1, 1, 1), (0, 3, 4), (3, 4, 0), (3, 0, 4)) + A, B, C0 = rand(TA, m, k) .- TA(0.5), rand(TB, k, n) .- TB(0.5), rand(TC, m, n) .- TC(0.5) + C = ArrayType(copy(C0)) + NextLA.recgemm!(1.5, ArrayType(A), ArrayType(B), 0.5, C) + synchronize(C) + @test size(C) == (m, n) + if k == 0 + @test Array(C) == TC.(0.5 .* C0) + else + @test gemm_ratio(C, 'N', 'N', 1.5, A, B, 0.5, C0; eps=gemm_eps(TC, TC)) <= BLAS_TEST_THRESHOLD + end + end + + # Big sizes n, 2n, 4n on the main paths, Float64 reference; positive entries, so the sums grow with n. + @testset "n=$n, $TA, $TB -> $TC" for n in test_values(:n, (512, 1024, 2048)), + (TA, TB, TC) in _rg_paths(ArrayType, ((Float16, Float16, Float16), (Float32, Float32, Float32), (Float64, Float64, Float64), + (Float16, Float16, Float32), (Float32, Float32, Float16), (Float64, Float64, Float32))) + A, B, C0 = rand(TA, n, n), rand(TB, n, n), rand(TC, n, n) + C = ArrayType(copy(C0)) + NextLA.recgemm!(-1.0, ArrayType(A), ArrayType(B), 1.0, C) + synchronize(C) + # Device Float16 × Float16 → Float32 runs on tensor cores, which accumulate with round-toward-zero (Fasi et al. 2021): deterministic bound k + 1. + bound = ArrayType !== Array && TA === Float16 && TC === Float32 ? n + 1 : _rg_bound(n) + @test _rg_ratio64(C, -1, A, B, 1, C0; eps=gemm_eps(TC, TC)) <= bound + TA === TC === Float64 && @test _rg_block(C, 'N', 'N', -1, A, B, 1, C0; eps=gemm_eps(TC, TC)) <= _rg_bound(n) + end + + @testset "beta=0 overwrites C, NaN in it ignored, $T" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)) + A, B = rand(T, 8, 8), rand(T, 8, 8) + C = ArrayType(fill(T(NaN), 8, 8)) + NextLA.recgemm!(one(T), ArrayType(A), ArrayType(B), zero(T), C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 1, A, B, 0, zeros(T, 8, 8); eps=_rg_eps(T)) <= BLAS_TEST_THRESHOLD + end + + @testset "alpha=0 scales C only, $T" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)) + A, B, C0 = rand(T, 8, 8), rand(T, 8, 8), rand(T, 8, 8) + C = ArrayType(copy(C0)) + NextLA.recgemm!(zero(T), ArrayType(A), ArrayType(B), T(2), C) + synchronize(C) + @test Array(C) == 2 .* C0 + end + + # Float16 operands, Float32 accumulation, rounded once to C's type. + @testset "$TA operands into $TC" for (TA, TC) in ((Float16, Float16), (Float16, Float32)) + A, B, C0 = rand(TA, 16, 24) .- TA(0.5), rand(TA, 24, 8) .- TA(0.5), rand(TC, 16, 8) .- TC(0.5) + C = ArrayType(copy(C0)) + NextLA.recgemm!(1.5, ArrayType(A), ArrayType(B), -0.5, C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 1.5, A, B, -0.5, C0; eps=gemm_eps(Float32, TC)) <= BLAS_TEST_THRESHOLD + end + + # Float16 operands sum in Float32, exactly: 300*300 - 300*300 is 0 (each product overflows Float16), and 0.5 survives 3072 + 0.5 - 3072. + @testset "Float16 operands into $TC sum in Float32, exact" for TC in (Float16, Float32) + C = ArrayType(fill(TC(7), 1, 1)) + NextLA.recgemm!(1.0, ArrayType(Float16[300 300]), ArrayType(reshape(Float16[300, -300], 2, 1)), 0.0, C) + synchronize(C) + @test Array(C) == zeros(TC, 1, 1) + C = ArrayType(zeros(TC, 3, 2)) + NextLA.recgemm!(1.0, ArrayType(_rg_absorb(3072, 0.5)), ArrayType(ones(Float16, 3, 2)), 0.0, C) + synchronize(C) + @test Array(C) == fill(TC(0.5), 3, 2) + end + + # The untyped literals recgemm!'s own callers use (-1.0, 1.0) over Float16 storage. + @testset "accumulate and subtract, Float16" begin + A, B, C0 = rand(Float16, 16, 16), rand(Float16, 16, 16), rand(Float16, 16, 16) + C = ArrayType(copy(C0)) + NextLA.recgemm!(-1.0, ArrayType(A), ArrayType(B), 1.0, C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', -1, A, B, 1, C0; eps=gemm_eps(Float32, Float16)) <= BLAS_TEST_THRESHOLD + end + + # A destination wider than both operands takes them exactly, so the result carries C's precision. + supports_float64(ArrayType) && @testset "$TA, $TB -> wider $TC" for (TA, TB, TC) in ((Float32, Float32, Float64), (Float16, Float16, Float64), + (Float16, Float32, Float64), (ComplexF32, ComplexF32, ComplexF64)) + A, B, C0 = rand(TA, 32, 32) .- TA(0.5), rand(TB, 32, 32) .- TB(0.5), rand(TC, 32, 32) .- TC(0.5) + C = ArrayType(copy(C0)) + NextLA.recgemm!(2, ArrayType(A), ArrayType(B), 3, C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 2, A, B, 3, C0; eps=gemm_eps(TC, TC)) <= BLAS_TEST_THRESHOLD + end + + # A destination narrower than the operands: the result has C's precision. + @testset "$TA, $TB -> narrower $TC" for (TA, TB, TC) in ((Float64, Float64, Float32), (Float64, Float32, Float32), + (Float32, Float32, Float16), (Float32, Float16, Float16)) + supports_float64(ArrayType) || all(t -> real(t) !== Float64, (TA, TB, TC)) || continue + A, B, C0 = rand(TA, 32, 32) .- TA(0.5), rand(TB, 32, 32) .- TB(0.5), rand(TC, 32, 32) .- TC(0.5) + C = ArrayType(copy(C0)) + NextLA.recgemm!(2, ArrayType(A), ArrayType(B), 3, C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 2, A, B, 3, C0; eps=gemm_eps(TC, TC)) <= BLAS_TEST_THRESHOLD + end + + # The mixed-precision recgemm! passes row blocks of A and column blocks of B. + @testset "row and column block views as operands, $T" for T in (supports_float64(ArrayType) ? Float64 : Float32,) + P, Q, C0 = rand(T, 20, 7) .- T(0.5), rand(T, 7, 20) .- T(0.5), rand(T, 8, 12) .- T(0.5) + C = ArrayType(copy(C0)) + NextLA.recgemm!(1.5, view(ArrayType(P), 3:10, :), view(ArrayType(Q), :, 5:16), -0.5, C) + synchronize(C) + @test gemm_ratio(C, 'N', 'N', 1.5, P[3:10, :], Q[:, 5:16], -0.5, C0; eps=gemm_eps(T, T)) <= BLAS_TEST_THRESHOLD + end + end +end + +# CPU: a narrower C does not round the operands first, so (1 + s) - 1 gives s exactly; rounding first gives 0 (devices round first). +cpu_wanted() && @testset "$TA, $TB -> narrower $TC keeps the operands' digits" for (TA, TB, TC, s) in + ((Float64, Float64, Float32, 2.0^-30), (Float64, Float32, Float32, 2.0^-30), + (Float32, Float32, Float16, 2.0^-12), (Float32, Float16, Float16, 2.0^-12)) + C = zeros(TC, 1, 1) + NextLA.recgemm!(1.0, reshape(TA[1 + s, -1], 1, 2), ones(TB, 2, 1), 0.0, C) + @test C[1] == TC(s) +end + +# The Float16 path on Metal and oneAPI (B50), checked on the CPU: partial sums pass floatmax(Float16), the result is 0. +cpu_wanted() && @testset "_half_gemm_widened! into $TC, tB=$tB, beta=$beta" for TC in (Float16, Float32), tB in ('N', 'T'), beta in (0.0, 0.5) + A, B = fill(Float16(200), 16, 200), Float16[fill(4, 100, 16); fill(-4, 100, 16)] + C0 = beta == 0 ? fill(TC(NaN), 16, 16) : TC.(rand(-8:8, 16, 16)) + C = copy(C0) + @test NextLA._half_gemm_widened!('N', tB, 1.0, A, tB == 'N' ? B : copy(B'), beta, C) === C + @test Float64.(C) == Float64.(A) * Float64.(B) .+ (beta == 0 ? 0.0 : beta .* Float64.(C0)) +end + +# alpha = 0 on that path reads neither A nor B: an Inf in A leaves beta C (B16 is the cuBLAS case). +cpu_wanted() && @testset "_half_gemm_widened! with alpha = 0, $TC, beta=$beta" for TC in (Float16, Float32), beta in (0.0, 0.5) + A = fill(Float16(Inf), 4, 3); C0 = TC.(rand(-8:8, 4, 4)); C = copy(C0) + @test NextLA._half_gemm_widened!('N', 'N', 0.0, A, ones(Float16, 3, 4), beta, C) === C + @test C == TC.(beta .* C0) +end diff --git a/test/dense/blas/gerc.jl b/test/dense/blas/gerc.jl new file mode 100644 index 00000000..08152633 --- /dev/null +++ b/test/dense/blas/gerc.jl @@ -0,0 +1,64 @@ +# gerc! (src/dense/blas/gerc.jl): A = A + α x yᴴ for Float16 and the four types, checked per element. + +test_params(m = "rows of A", n = "columns of A") # the number options it takes (--params) + +# Per-element error bound of A + α x yᴴ against a BigFloat reference. +_gerc_bound(::Type{T}) where {T} = (T <: Complex ? 8 : 4) * eps(real(T)) / 2 + +function _gerc_ok(A_computed, A0, α, x0, y0) + exact = big.(A0) .+ big(α) .* big.(x0) .* big.(y0)' # y' conjugates + scale = abs.(big.(A0)) .+ abs(big(α)) .* abs.(big.(x0)) .* abs.(big.(y0))' + return all(abs.(big.(A_computed) .- exact) .<= _gerc_bound(eltype(A0)) .* scale) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "GERC [$backend_name]" begin + # Mixed signs, so cancellation in A + α x yᴴ is part of what is checked. + @testset "$T, m=$m, n=$n" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + (m, n) in test_cases((:m, :n), ((0, 0), (0, 3), (3, 0), (1, 1), (2, 3), (5, 4), (10, 8), (50, 40))) + α = T <: Complex ? T(-0.7, 0.3) : T(-0.7) + x0, y0, A0 = rand(T, m) .- T(0.5), rand(T, n) .- T(0.5), rand(T, m, n) .- T(0.5) + A = ArrayType(copy(A0)) + NextLA.gerc!(α, ArrayType(x0), ArrayType(y0), A) + synchronize(A) + if m == 0 || n == 0 + @test Array(A) == A0 + else + @test _gerc_ok(Array(A), A0, α, x0, y0) + end + end + + # α = 0 leaves A untouched (and returns it), so NaN or Inf in x does not reach it. + @testset "α = 0 leaves A unchanged even with NaN and Inf in x, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + A0 = rand(T, 3, 3) + A = ArrayType(copy(A0)) + @test NextLA.gerc!(zero(T), ArrayType(T[NaN, Inf, 1]), ArrayType(rand(T, 3)), A) === A + synchronize(A) + @test Array(A) == A0 + end + + # Strided views of x, y and A, as larf! passes; the rest of the matrix is unchanged. + @testset "views, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + M0, xs, ys = rand(T, 8, 6) .- T(0.5), rand(T, 10) .- T(0.5), rand(T, 6) .- T(0.5) + M = ArrayType(copy(M0)) + α = T(0.5) + NextLA.gerc!(α, view(ArrayType(xs), 1:2:7), view(ArrayType(ys), 2:4), view(M, 2:2:8, 3:5)) + synchronize(M) + Mh = Array(M) + @test _gerc_ok(Mh[2:2:8, 3:5], M0[2:2:8, 3:5], α, xs[1:2:7], ys[2:4]) + @test Mh[1:2:7, :] == M0[1:2:7, :] && Mh[:, [1, 2, 6]] == M0[:, [1, 2, 6]] + end + + @testset "mismatched lengths throw ArgumentError" begin + A = ArrayType(zeros(ComplexF32, 2, 2)) + @test_throws ArgumentError NextLA.gerc!(1.0f0 + 0im, ArrayType(ComplexF32[1]), ArrayType(ComplexF32[1, 2]), A) + @test_throws ArgumentError NextLA.gerc!(1.0f0 + 0im, ArrayType(ComplexF32[1, 2]), ArrayType(ComplexF32[1]), A) + end + + # α must have the element type of A. + @testset "α of another type throws MethodError" begin + @test_throws MethodError NextLA.gerc!(1.0f0, ArrayType(rand(ComplexF32, 2)), ArrayType(rand(ComplexF32, 2)), + ArrayType(rand(ComplexF32, 2, 2))) + end + end +end diff --git a/test/dense/blas/syrk/recsyrk.jl b/test/dense/blas/syrk/recsyrk.jl new file mode 100644 index 00000000..76d08a3d --- /dev/null +++ b/test/dense/blas/syrk/recsyrk.jl @@ -0,0 +1,165 @@ +# recsyrk! (src/dense/blas/syrk/recsyrk.jl): recursive C = alpha A Aᵀ + beta C on one triangle (B25's size and threshold checks untested). + +test_params(n = "order of C", k = "columns of A", block = "size where the recursion stops") # the number options it takes (--params) + +# syrk_ratio against a Float64 reference, for sizes where BigFloat is too slow. +function _recsyrk_ratio64(C, uplo, α, A, β, C0; eps) + Ad, C0d = Float64.(Array(A)), Float64.(Array(C0)) + E = abs.(Float64.(Array(C)) .- (α .* (Ad * Ad') .+ β .* C0d)) + G = abs(α) .* (abs.(Ad) * abs.(Ad)') .+ abs(β) .* abs.(C0d) + return maximum((uplo == 'L' ? tril : triu)(ifelse.(iszero.(G), E, E ./ G)); init=0.0) / eps +end + +# syrk_ratio over the entries I × J of the uplo triangle in BigFloat (on the CPU the Float64 reference is BLAS syrk itself). +function _recsyrk_block_ratio(C, uplo, α, A, β, C0, I, J; eps) + X, Y, Z = big.(Array(A)[I, :]), big.(Array(A)[J, :]), big.(Array(C0)[I, J]) + E = abs.(big.(Array(C)[I, J]) .- (big(α) .* (X * transpose(Y)) .+ big(β) .* Z)) + G = abs(big(α)) .* (abs.(X) * transpose(abs.(Y))) .+ abs(big(β)) .* abs.(Z) + return Float64(maximum((_elem_ratio(E[a, b], G[a, b]) for a in eachindex(I), b in eachindex(J) if (uplo == 'L') == (I[a] >= J[b]) || I[a] == J[b]); init=big(0))) / eps +end + +# The eps of a k-term sum scaled by √k, its probabilistic bound (Higham and Mary 2019); Float16 sums in Float32 and rounds once. +_recsyrk_eps(T, k) = T === Float16 ? Float64(eps(Float16)) + sqrt(k) * eps(Float32) : sqrt(k) * Float64(eps(T)) + +for (backend_name, ArrayType, synchronize) in available_backends() + # Metal: syrk! takes no views, which every leaf past the first is, so the testsets marked metal || skip it. + metal = backend_name == "Metal" + + @testset "RECSYRK [$backend_name]" begin + @testset "$T, uplo=$uplo, n=$n" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), uplo in test_flags(:uplo, ('L', 'U')), + n in test_values(:n, (1, 7, 50, 100, 129)) + for k in test_values(:k, (1, 16)), th in test_values(:block, (1, 16, 256)) + A0, C0 = rand(T, n, k), rand(T, n, n) + Cd = ArrayType(copy(C0)) + NextLA.recsyrk!(T(1.5), ArrayType(A0), T(0.5), Cd, th; uplo) + synchronize(Cd) + @test syrk_ratio(Cd, uplo, 'N', 1.5, A0, 0.5, C0; eps=Float64(eps(real(T)))) <= BLAS_TEST_THRESHOLD + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + end + + # A wider C takes A exactly, a narrower one A rounded once (a Float16 C: computed in Float32). + @testset "A $TA, C $TC, uplo=$uplo" for (TA, TC) in ((Float32, Float64), (Float16, Float64), (Float64, Float32), + (ComplexF32, ComplexF64), (ComplexF64, ComplexF32), + (Float16, Float32), (Float32, Float16), + (Float64, ComplexF64)), + uplo in test_flags(:uplo, ('L', 'U')) + supports_float64(ArrayType) || all(t -> real(t) !== Float64, (TA, TC)) || continue + A0, C0 = rand(TA, 96, 40), rand(TC, 96, 96) + Cd = ArrayType(copy(C0)) + NextLA.recsyrk!(TC(2), ArrayType(A0), TC(3), Cd, 32; uplo) + synchronize(Cd) + @test syrk_ratio(Cd, uplo, 'N', 2, A0, 3, C0; eps=Float64(eps(real(TC)))) <= BLAS_TEST_THRESHOLD + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + + # Signed A with potrf_recursive!'s alpha = -1, beta = 1 (Float64 scalars, as it passes them). + metal || @testset "signed, alpha = -1, beta = 1, $T, uplo=$uplo, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, (1, 7, 50, 100, 129)) + for k in test_values(:k, (1, 16)), th in test_values(:block, (1, 16, 256)) + A0, C0 = randn(T, n, k), randn(T, n, n) + Cd = ArrayType(copy(C0)) + NextLA.recsyrk!(-1.0, ArrayType(A0), 1.0, Cd, th; uplo) + synchronize(Cd) + @test syrk_ratio(Cd, uplo, 'N', -1, A0, 1, C0; eps=Float64(eps(T))) <= BLAS_TEST_THRESHOLD + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + end + + # Float16: A Aᵀ past floatmax(Float16), brought back by alpha; finite only if the sums stay in Float32. + @testset "Float16 sums in Float32, uplo=$uplo" for T in backend_types(ArrayType, (Float16,)), uplo in test_flags(:uplo, ('L', 'U')) + A0, C0 = T.(300 .+ 10 .* rand(40, 16)), rand(T, 40, 40) + Cd = ArrayType(copy(C0)) + NextLA.recsyrk!(T(2)^-10, ArrayType(A0), T(0.5), Cd, 16; uplo) + synchronize(Cd) + @test all(isfinite, Array(Cd)) + @test syrk_ratio(Cd, uplo, 'N', 2.0^-10, A0, 0.5, C0; eps=Float64(eps(T))) <= BLAS_TEST_THRESHOLD + end + + # Views at the top level, as callers pass them: only the view's own triangle changes. + metal || @testset "views, $T, uplo=$uplo" for T in backend_types(ArrayType, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')) + Ap, Cp = randn(T, 60, 20), randn(T, 60, 60) + Ad, Cd = ArrayType(copy(Ap)), ArrayType(copy(Cp)) + V = view(Cd, 5:54, 6:55) + @test NextLA.recsyrk!(-1.0, view(Ad, 3:52, 2:17), 1.0, V, 16; uplo) === V + synchronize(Cd) + C = Array(Cd) + @test syrk_ratio(C[5:54, 6:55], uplo, 'N', -1, Ap[3:52, 2:17], 1, Cp[5:54, 6:55]; eps=Float64(eps(T))) <= BLAS_TEST_THRESHOLD + @test other_triangle(uplo, C[5:54, 6:55]) == other_triangle(uplo, Cp[5:54, 6:55]) + outside = trues(60, 60); outside[5:54, 6:55] .= false + @test C[outside] == Cp[outside] + end + + # k = 0: the triangle becomes beta C exactly (beta = 2 scales without rounding). + metal || @testset "k = 0, $T, uplo=$uplo" for T in backend_types(ArrayType, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')) + C0 = randn(T, 50, 50) + Cd = ArrayType(copy(C0)) + NextLA.recsyrk!(1.5, ArrayType(zeros(T, 50, 0)), 2.0, Cd, 16; uplo) + synchronize(Cd) + keep = uplo == 'L' ? tril : triu + @test keep(Array(Cd)) == keep(2 .* C0) + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + + # Big sizes and multiples with the default threshold (256), k = n/2 as in a Cholesky update. + metal || @testset "n = $n, default threshold, $T, uplo=$uplo" for n in test_values(:n, (600, 1200, 2400)), + T in backend_types(ArrayType, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')) + k = n ÷ 2 + A0, C0 = randn(T, n, k), randn(T, n, n) + Cd = ArrayType(copy(C0)) + NextLA.recsyrk!(-1.0, ArrayType(A0), 1.0, Cd; uplo) + synchronize(Cd) + @test _recsyrk_ratio64(Cd, uplo, -1, A0, 1, C0; eps=_recsyrk_eps(T, k)) <= BLAS_TEST_THRESHOLD + S = [1:4; n÷2-1:n÷2+2; n-3:n] # rows and columns at the start, the middle and the end, in BigFloat + @test _recsyrk_block_ratio(Cd, uplo, -1, A0, 1, C0, S, S; eps=_recsyrk_eps(T, k)) <= BLAS_TEST_THRESHOLD + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + + metal || @testset "beta = 0 ignores NaN in C" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A0 = rand(T, 40, 4) + Cd = ArrayType(fill(T(NaN), 40, 40)) + NextLA.recsyrk!(one(T), ArrayType(A0), zero(T), Cd, 16) + synchronize(Cd) + @test syrk_ratio(Cd, 'L', 'N', 1, A0, 0, zeros(T, 40, 40); eps=eps(T)) <= BLAS_TEST_THRESHOLD + end + + @testset "n = 0 updates nothing" begin + C = ArrayType(zeros(Float32, 0, 0)) + @test NextLA.recsyrk!(1.0f0, ArrayType(zeros(Float32, 0, 3)), 0.0f0, C) === C + end + + @testset "an unknown uplo throws" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + @test_throws ArgumentError NextLA.recsyrk!(one(T), ArrayType(rand(T, 8, 2)), one(T), ArrayType(rand(T, 8, 8)); uplo='X') + end + + # uplo in either case, as BLAS and LAPACK take it. + @testset "lowercase uplo gives the same result, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + T = supports_float64(ArrayType) ? Float64 : Float32 + A, C0 = ArrayType(rand(T, 40, 8)), rand(T, 40, 40) + c, d = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.recsyrk!(one(T), A, one(T), c, 16; uplo=uplo) + NextLA.recsyrk!(one(T), A, one(T), d, 16; uplo=lowercase(uplo)) + @test Array(d) == Array(c) + end + end +end + +# The parallel diagonal-block path equals the sequential one, in a child Julia with test_threads() threads (--threads, default 4). +cpu_wanted() && @testset "RECSYRK parallel with 4 threads [CPU]" begin + code = """ + using NextLA, Random + Random.seed!($(rand(UInt32))) # from this test's seeded RNG, so --seed replays it + same = all(1:20) do i + uplo = isodd(i) ? 'L' : 'U' + A, C0 = rand(200, 24), rand(200, 200) + seq, par = copy(C0), copy(C0) + NextLA._recsyrk_impl!(1.5, A, 0.5, seq, 32, uplo; parallel=false) + NextLA._recsyrk_impl!(1.5, A, 0.5, par, 32, uplo; parallel=true) + seq == par + end + print(Threads.nthreads(), " ", same) + """ + @test with_threads(code; threads=test_threads()) == "$(test_threads()) true" +end diff --git a/test/dense/blas/syrk/syrk.jl b/test/dense/blas/syrk/syrk.jl new file mode 100644 index 00000000..9745558c --- /dev/null +++ b/test/dense/blas/syrk/syrk.jl @@ -0,0 +1,242 @@ +# syrk!, syrk_batched! (src/dense/blas/syrk/syrk_dispatch.jl, syrk_batched.jl, ext/*/syrk.jl); B22 and B23 untested, B25 skipped on CUDA. + +test_params(n = "order of C", k = "columns of A", batch = "matrices in a batch") # the number options it takes (--params) + +# syrk_ratio against a Float64 reference, for sizes where BigFloat is too slow. +function _syrk_ratio64(C, uplo, trans, α, A, β, C0; eps) + Ad, C0d = Float64.(Array(A)), Float64.(Array(C0)) + opA = trans == 'N' ? Ad : transpose(Ad) + E = abs.(Float64.(Array(C)) .- (α .* (opA * transpose(opA)) .+ β .* C0d)) + G = abs(α) .* (abs.(opA) * transpose(abs.(opA))) .+ abs(β) .* abs.(C0d) + return maximum((uplo == 'L' ? tril : triu)(ifelse.(iszero.(G), E, E ./ G)); init=0.0) / eps +end + +# syrk_ratio over the entries I × J of the uplo triangle in BigFloat (on the CPU the Float64 reference is BLAS syrk itself). +function _syrk_block_ratio(C, uplo, trans, α, A, β, C0, I, J; eps) + opA = trans == 'N' ? Array(A) : transpose(Array(A)) + X, Y, Z = big.(opA[I, :]), big.(opA[J, :]), big.(Array(C0)[I, J]) + E = abs.(big.(Array(C)[I, J]) .- (big(α) .* (X * transpose(Y)) .+ big(β) .* Z)) + G = abs(big(α)) .* (abs.(X) * transpose(abs.(Y))) .+ abs(big(β)) .* abs.(Z) + return Float64(maximum((_elem_ratio(E[a, b], G[a, b]) for a in eachindex(I), b in eachindex(J) if (uplo == 'L') == (I[a] >= J[b]) || I[a] == J[b]); init=big(0))) / eps +end + +for (name, AT, sync) in backends + # Metal has no SYRK: its syrk! is a GEMM and writes the whole square (ext/metal/syrk.jl). + metal = name == "Metal" + + @testset "SYRK [$name]" begin + @testset "syrk!, $T, uplo=$uplo, trans=$trans" for T in backend_types(AT, TEST_TYPES), uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, (T <: Real ? ('N', 'T', 'C') : ('N', 'T'))) + for n in test_values(:n, (0, 1, 7, 33)), k in test_values(:k, (0, 1, 5)) + A0 = trans == 'N' ? rand(T, n, k) : rand(T, k, n) + C0 = rand(T, n, n) + Cd = AT(copy(C0)) + @test NextLA.syrk!(uplo, trans, T(1.5), AT(A0), T(0.5), Cd) === Cd + sync(Cd) + @test syrk_ratio(Cd, uplo, trans, 1.5, A0, 0.5, C0; eps=eps(real(T))) <= BLAS_TEST_THRESHOLD + if metal + @test_broken other_triangle(uplo, Cd) == other_triangle(uplo, C0) + else + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + end + end + + # Signed data and the callers' scalars (potrf_recursive!: alpha = -1, beta = 1; alpha = 0 scales C only). + @testset "signed, alpha=$alpha, beta=$beta, $T, uplo=$uplo, trans=$trans" for T in backend_types(AT, (Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')), trans in test_flags(:trans, ('N', 'T', 'C')), (alpha, beta) in ((1.5, 0.5), (-1, 1), (0, 0.5)) + for n in test_values(:n, (7, 33)), k in test_values(:k, (1, 5)) + A0 = trans == 'N' ? randn(T, n, k) : randn(T, k, n) + C0 = randn(T, n, n) + Cd = AT(copy(C0)) + NextLA.syrk!(uplo, trans, T(alpha), AT(A0), T(beta), Cd) + sync(Cd) + @test syrk_ratio(Cd, uplo, trans, alpha, A0, beta, C0; eps=eps(T)) <= BLAS_TEST_THRESHOLD + metal || @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) # Metal writes the whole square + end + end + + # beta = 0: C is not read, so NaN there does not reach the result; the other triangle keeps its NaN. + @testset "beta = 0 ignores NaN in C, $T, uplo=$uplo" for T in backend_types(AT, TEST_TYPES), uplo in test_flags(:uplo, T <: Real ? ('L', 'U') : ('L',)) + A0 = rand(T, 6, 3) + Cd = AT(fill(T(NaN), 6, 6)) + NextLA.syrk!(uplo, 'N', one(T), AT(A0), zero(T), Cd) + sync(Cd) + @test syrk_ratio(Cd, uplo, 'N', 1, A0, 0, zeros(T, 6, 6); eps=eps(real(T))) <= BLAS_TEST_THRESHOLD + metal || @test isequal(other_triangle(uplo, Cd), other_triangle(uplo, fill(T(NaN), 6, 6))) # Metal writes the whole square + end + + @testset "views, $T" for T in backend_types(AT, TEST_TYPES) + Ap, Cp = rand(T, 9, 6), rand(T, 8, 8) + Ad, Cd = AT(copy(Ap)), AT(copy(Cp)) + NextLA.syrk!('L', 'N', T(1.5), view(Ad, 2:7, 2:5), T(0.5), view(Cd, 2:7, 2:7)) + sync(Cd) + C = Array(Cd) + @test syrk_ratio(C[2:7, 2:7], 'L', 'N', 1.5, Ap[2:7, 2:5], 0.5, Cp[2:7, 2:7]; eps=eps(real(T))) <= BLAS_TEST_THRESHOLD + outside = trues(8, 8); outside[2:7, 2:7] .= false + @test C[outside] == Cp[outside] + end + + # Views as potrf_recursive! passes them (('U', 'T'), alpha = -1, beta = 1); not on Metal, whose syrk! takes no views. + metal || @testset "views, $T, uplo=$uplo, trans=$trans" for T in backend_types(AT, (Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T')) + Ap, Cp = randn(T, 9, 8), randn(T, 8, 8) + Ad, Cd = AT(copy(Ap)), AT(copy(Cp)) + ia, ja = trans == 'N' ? (2:7, 2:5) : (2:5, 2:7) + NextLA.syrk!(uplo, trans, -one(T), view(Ad, ia, ja), one(T), view(Cd, 2:7, 2:7)) + sync(Cd) + C = Array(Cd) + @test syrk_ratio(C[2:7, 2:7], uplo, trans, -1, Ap[ia, ja], 1, Cp[2:7, 2:7]; eps=eps(T)) <= BLAS_TEST_THRESHOLD + outside = trues(8, 8); outside[2:7, 2:7] .= false + @test C[outside] == Cp[outside] + @test other_triangle(uplo, C[2:7, 2:7]) == other_triangle(uplo, Cp[2:7, 2:7]) + end + + # Big sizes and multiples, k = n/2; eps scaled by √k, the probabilistic bound of a k-term sum (Higham and Mary 2019). + @testset "n = $n, $T, uplo=$uplo, trans=$trans" for n in test_values(:n, (512, 1024, 2048)), T in backend_types(AT, (Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')), trans in test_flags(:trans, ('N', 'T')) + k = n ÷ 2 + A0 = trans == 'N' ? randn(T, n, k) : randn(T, k, n) + C0 = randn(T, n, n) + Cd = AT(copy(C0)) + NextLA.syrk!(uplo, trans, -one(T), AT(A0), one(T), Cd) + sync(Cd) + @test _syrk_ratio64(Cd, uplo, trans, -1, A0, 1, C0; eps=sqrt(k) * eps(T)) <= BLAS_TEST_THRESHOLD + S = [1:4; n÷2-1:n÷2+2; n-3:n] # rows and columns at the start, the middle and the end, in BigFloat + @test _syrk_block_ratio(Cd, uplo, trans, -1, A0, 1, C0, S, S; eps=sqrt(k) * eps(T)) <= BLAS_TEST_THRESHOLD + metal || @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) # Metal writes the whole square + end + + @testset "Float16 is refused" begin + @test_throws MethodError NextLA.syrk!('L', 'N', one(Float16), AT(rand(Float16, 4, 2)), zero(Float16), AT(rand(Float16, 4, 4))) + end + + # Each backend serves the call with its own ext method, not CPU BLAS. + @testset "dispatches to its own backend" begin + Ad, Cd = AT(rand(Float32, 2, 3)), AT(rand(Float32, 2, 2)) + @test endswith(_method_file(NextLA.syrk!, 'L', 'N', 1.5f0, Ad, 0.25f0, Cd), _expected_syrk_file(name)) + end + + @testset "rejects bad arguments" begin + Ad, Cd = AT(rand(Float32, 2, 3)), AT(rand(Float32, 2, 2)) + @test_throws ArgumentError NextLA.syrk!('X', 'N', 1f0, Ad, 0f0, Cd) + @test_throws "Unsupported transpose flag" NextLA.syrk!('L', 'X', 1f0, Ad, 0f0, Cd) # was read as 'T' + @test_throws DimensionMismatch NextLA.syrk!('L', 'N', 1f0, Ad, 0f0, AT(rand(Float32, 3, 2))) + @test_throws DimensionMismatch NextLA.syrk!('L', 'N', 1f0, Ad, 0f0, AT(rand(Float32, 3, 3))) + end + + # Flags in either case, as BLAS takes them (Metal read 'n' as a transpose). + @testset "lowercase flags, uplo=$uplo, trans=$trans" for uplo in test_flags(:uplo, ('L', 'U')), trans in test_flags(:trans, ('N', 'T')) + A = AT(trans == 'N' ? rand(Float32, 5, 3) : rand(Float32, 3, 5)) + C0 = rand(Float32, 5, 5) + Cu, Cl = AT(copy(C0)), AT(copy(C0)) + NextLA.syrk!(uplo, trans, 2f0, A, 3f0, Cu) + NextLA.syrk!(lowercase(uplo), lowercase(trans), 2f0, A, 3f0, Cl) + @test Array(Cl) == Array(Cu) + end + + # Native batched SYRK: AMDGPU in both layouts, oneAPI strided; elsewhere it warns and falls back. + warns_pointer = name != "AMDGPU" + warns_strided = !(name in ("AMDGPU", "oneAPI")) + batched!(warns, args...) = warns ? + (@test_logs (:warn, r"no native batched SYRK") match_mode = :any NextLA.syrk_batched!(args...)) : + NextLA.syrk_batched!(args...) + + @testset "syrk_batched!, $T, uplo=$uplo, trans=$trans" for T in backend_types(AT, TEST_TYPES), uplo in test_flags(:uplo, ('L', 'U')), trans in test_flags(:trans, ('N', 'T')) + As = [trans == 'N' ? rand(T, 5, 3) : rand(T, 3, 5) for _ in 1:3] + Cs = [rand(T, 5, 5) for _ in 1:3] + Cd = [AT(copy(C)) for C in Cs] + batched!(warns_pointer, uplo, trans, T(2), [AT(A) for A in As], T(3), Cd) + sync(Cd[end]) + C3d = AT(cat(Cs...; dims=3)) + batched!(warns_strided, uplo, trans, T(2), AT(cat(As...; dims=3)), T(3), C3d) + sync(C3d) + C3 = Array(C3d) + for i in 1:3 + @test syrk_ratio(Cd[i], uplo, trans, 2, As[i], 3, Cs[i]; eps=eps(real(T))) <= BLAS_TEST_THRESHOLD + @test syrk_ratio(C3[:, :, i], uplo, trans, 2, As[i], 3, Cs[i]; eps=eps(real(T))) <= BLAS_TEST_THRESHOLD + if metal + @test_broken other_triangle(uplo, C3[:, :, i]) == other_triangle(uplo, Cs[i]) + else + @test other_triangle(uplo, Cd[i]) == other_triangle(uplo, Cs[i]) + @test other_triangle(uplo, C3[:, :, i]) == other_triangle(uplo, Cs[i]) + end + end + end + + # Edge sizes: batches of 0, 1 and 3 members of order 0, 1 and 5 (k = 0 leaves beta C); both layouts; Metal has its own path. + metal || @testset "syrk_batched!: batch=$nb, n=$n, k=$k, $T" for T in backend_types(AT, (Float32, Float64)), nb in test_values(:batch, (0, 1, 3)), + (n, k) in test_cases((:n, :k), ((0, 0), (1, 1), (5, 0), (5, 3))) + As = [randn(T, n, k) for _ in 1:nb] + Cs = [randn(T, n, n) for _ in 1:nb] + Cd = typeof(AT(zeros(T, 0, 0)))[AT(copy(C)) for C in Cs] + @test batched!(warns_pointer, 'L', 'N', T(-1), typeof(AT(zeros(T, 0, 0)))[AT(A) for A in As], T(0.5), Cd) === Cd + C3d = AT(reshape(reduce(hcat, Cs; init=zeros(T, n, 0)), n, n, nb)) + @test batched!(warns_strided, 'L', 'N', T(-1), AT(reshape(reduce(hcat, As; init=zeros(T, n, 0)), n, k, nb)), T(0.5), C3d) === C3d + nb > 0 && sync(Cd[end]); sync(C3d) + C3 = Array(C3d) + for i in 1:nb + @test syrk_ratio(Cd[i], 'L', 'N', -1, As[i], 0.5, Cs[i]; eps=eps(T)) <= BLAS_TEST_THRESHOLD + @test syrk_ratio(C3[:, :, i], 'L', 'N', -1, As[i], 0.5, Cs[i]; eps=eps(T)) <= BLAS_TEST_THRESHOLD + end + end + + metal || @testset "syrk_batched!: lowercase flags" begin + As = [AT(rand(Float32, 5, 3)) for _ in 1:2]; C0 = [rand(Float32, 5, 5) for _ in 1:2] + Cu, Cl = [AT(copy(C)) for C in C0], [AT(copy(C)) for C in C0] + batched!(warns_pointer, 'L', 'N', 2f0, As, 3f0, Cu) + batched!(warns_pointer, 'l', 'n', 2f0, As, 3f0, Cl) + @test all(Array(Cl[i]) == Array(Cu[i]) for i in 1:2) + end + + # An empty strided batch comes back as it is, on every backend (B51, fixed: AMDGPU, oneAPI and Metal read member 1). + @testset "syrk_batched!: an empty strided batch" begin + C3d = AT(zeros(Float32, 5, 5, 0)) + @test Base.CoreLogging.with_logger(Base.CoreLogging.NullLogger()) do + NextLA.syrk_batched!('L', 'N', -1f0, AT(zeros(Float32, 5, 3, 0)), 0.5f0, C3d) + end === C3d + end + + # A strided batch of one A updates every C; a vector batch may mix sizes (Metal has its own path). + metal || @testset "syrk_batched!: one A for every C, members of different sizes" begin + T = supports_float64(AT) ? Float64 : Float32 + A1, Cs = rand(T, 5, 3, 1), rand(T, 5, 5, 3) + C3d = AT(copy(Cs)) + batched!(warns_strided, 'L', 'N', one(T), AT(A1), T(0.5), C3d) + sync(C3d) + C3 = Array(C3d) + for i in 1:3 + @test syrk_ratio(C3[:, :, i], 'L', 'N', 1, A1[:, :, 1], 0.5, Cs[:, :, i]; eps=eps(T)) <= BLAS_TEST_THRESHOLD + end + As, Cv = [rand(T, 4, 2), rand(T, 7, 3)], [rand(T, 4, 4), rand(T, 7, 7)] + Cd = [AT(copy(C)) for C in Cv] + batched!(warns_pointer, 'L', 'N', one(T), [AT(A) for A in As], T(0.5), Cd) + sync(Cd[end]) + for i in 1:2 + @test syrk_ratio(Cd[i], 'L', 'N', 1, As[i], 0.5, Cv[i]; eps=eps(T)) <= BLAS_TEST_THRESHOLD + end + end + + metal || @testset "syrk_batched!: batches of different lengths are refused" begin + T = supports_float64(AT) ? Float64 : Float32 + nolog(f) = Base.CoreLogging.with_logger(f, Base.CoreLogging.NullLogger()) + @test_throws DimensionMismatch nolog(() -> NextLA.syrk_batched!('L', 'N', one(T), + [AT(rand(T, 5, 3)) for _ in 1:2], zero(T), [AT(rand(T, 5, 5)) for _ in 1:3])) + name == "CUDA" || @test_throws DimensionMismatch nolog(() -> NextLA.syrk_batched!('L', 'N', one(T), + AT(rand(T, 5, 3, 2)), zero(T), AT(rand(T, 5, 5, 3)))) # B25 on CUDA + end + end +end + +# A device view whose rows are not consecutive (as A or as C): the vendor call runs on a contiguous copy (B24). +@testset "row-strided device views [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", available_backends()) + D = rand(Float32, 16, 3) + Cd = AT(zeros(Float32, 8, 8)) + NextLA.syrk!('L', 'N', 1f0, view(AT(D), 1:2:16, :), 0f0, Cd) + @test tril(Array(Cd)) ≈ tril(D[1:2:16, :] * D[1:2:16, :]') + P, A = rand(Float32, 16, 8), rand(Float32, 8, 3) + Pd = AT(copy(P)) + NextLA.syrk!('L', 'N', 1f0, AT(A), 0f0, view(Pd, 1:2:16, :)) + R = Array(Pd) + @test tril(R[1:2:16, :]) ≈ tril(A * A') && R[2:2:16, :] == P[2:2:16, :] +end diff --git a/test/dense/blas/syrk/syrk_kernel.jl b/test/dense/blas/syrk/syrk_kernel.jl new file mode 100644 index 00000000..4ff6f630 --- /dev/null +++ b/test/dense/blas/syrk/syrk_kernel.jl @@ -0,0 +1,72 @@ +# SYRK_KERNEL! (src/dense/blas/syrk/syrk_kernel.jl): tiled SYRK on every backend and type; the alpha = 0 part of B23 untested. + +test_params(n = "order of C", k = "columns of A") # the number options it takes (--params) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "SYRK_KERNEL [$backend_name]" begin + @testset "$T, uplo=$uplo, trans=$trans" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + uplo in test_flags(:uplo, ('L', 'U')), trans in test_flags(:trans, ('N', 'T')) + for n in test_values(:n, (1, 31, 33, 100)), k in test_values(:k, (0, 1, 33)) + A0 = trans == 'N' ? rand(T, n, k) : rand(T, k, n) + C0 = rand(T, n, n) + Cd = ArrayType(copy(C0)) + @test NextLA.SYRK_KERNEL!(uplo, trans, T(1.5), ArrayType(A0), T(0.5), Cd) === Cd + synchronize(Cd) + @test syrk_ratio(Cd, uplo, trans, 1.5, A0, 0.5, C0; eps=Float64(eps(real(T)))) <= BLAS_TEST_THRESHOLD + @test other_triangle(uplo, Cd) == other_triangle(uplo, C0) + end + end + + @testset "lower-case flags" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A0, C0 = rand(T, 2, 4), rand(T, 4, 4) + Cd = ArrayType(copy(C0)) + NextLA.SYRK_KERNEL!('l', 't', one(T), ArrayType(A0), one(T), Cd) + synchronize(Cd) + @test syrk_ratio(Cd, 'L', 'T', 1, A0, 1, C0; eps=eps(T)) <= BLAS_TEST_THRESHOLD + @test other_triangle('L', Cd) == other_triangle('L', C0) + end + + # A view with rows two apart and C inside a larger matrix: only the view changes. + @testset "views, $T" for T in backend_types(ArrayType, TEST_TYPES) + Ap, Cp = rand(T, 12, 3), rand(T, 8, 8) + Ad, Cd = ArrayType(copy(Ap)), ArrayType(copy(Cp)) + NextLA.SYRK_KERNEL!('U', 'N', T(1.5), view(Ad, 1:2:12, :), T(0.5), view(Cd, 2:7, 2:7)) + synchronize(Cd) + C = Array(Cd) + @test syrk_ratio(C[2:7, 2:7], 'U', 'N', 1.5, Ap[1:2:12, :], 0.5, Cp[2:7, 2:7]; eps=eps(real(T))) <= BLAS_TEST_THRESHOLD + outside = trues(8, 8); outside[2:7, 2:7] .= false + @test C[outside] == Cp[outside] + @test tril(C[2:7, 2:7], -1) == tril(Cp[2:7, 2:7], -1) + end + + @testset "n = 0" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + @test NextLA.SYRK_KERNEL!('L', 'N', one(T), ArrayType(rand(T, 0, 3)), zero(T), ArrayType(rand(T, 0, 0))) isa AbstractMatrix + end + + # beta = 0 never reads C (NaN there stays out); Float16 sums in Float32 and rounds once; k = 1024 to 4096. + @testset "beta = 0, k = $k, $T" for T in backend_types(ArrayType, (Float16, Float32)), k in (1024, 2048, 4096) + n = 64 + A0 = rand(T, n, k) # positive entries: the running sums grow, so a Float16 sum loses digits + Cd = ArrayType(fill(T(NaN), n, n)) + NextLA.SYRK_KERNEL!('L', 'N', one(T), ArrayType(A0), zero(T), Cd) + synchronize(Cd) + Af = Float64.(A0) + ref = tril(Af * Af') + got = tril(Float64.(Array(Cd))) + tol = T === Float16 ? eps(Float16) + k * eps(Float32) : (k + 1) * eps(Float32) + @test all(isfinite, got) && all(abs.(got .- ref) .<= tol .* ref) + end + + @testset "rejects bad arguments" begin + A = ArrayType(rand(Float32, 8, 4)) + C = ArrayType(rand(Float32, 8, 8)) + @test_throws ArgumentError NextLA.SYRK_KERNEL!('X', 'N', 1f0, A, 0f0, C) + @test_throws ArgumentError NextLA.SYRK_KERNEL!('L', 'X', 1f0, A, 0f0, C) + @test_throws ArgumentError NextLA.SYRK_KERNEL!('L', 'C', 1f0, A, 0f0, C) + @test_throws DimensionMismatch NextLA.SYRK_KERNEL!('L', 'N', 1f0, A, 0f0, ArrayType(rand(Float32, 8, 4))) + @test_throws DimensionMismatch NextLA.SYRK_KERNEL!('L', 'N', 1f0, A, 0f0, ArrayType(rand(Float32, 4, 4))) + end + end +end diff --git a/test/dense/blas/trsm/rectrxm.jl b/test/dense/blas/trsm/rectrxm.jl new file mode 100644 index 00000000..8aaad117 --- /dev/null +++ b/test/dense/blas/trsm/rectrxm.jl @@ -0,0 +1,151 @@ +# unified_rectrxm! (src/dense/blas/trsm/rectrxm.jl): recursive triangular solve ('S') and multiply ('M'), Float32 and Float64 +# (complex: rectrxm_complex.jl; Float16: rectrxm_float16.jl). + +test_params(m = "the other dimension of B", n = "order of the triangle A") # the number options it takes (--params) + +# The triangle the routine reads: stored part in [1, 2), diagonal plus 10. +_urx_triangle(T, n, uplo) = (uplo == 'L' ? tril : triu)(rand(T, n, n) .+ 1) + Diagonal(10 * ones(T, n)) + +# A as callers pass it (recpotrf: a full matrix): NaN in the triangle not referenced, and on the diagonal for diag = 'U' (dblat3's ROGUE value). +function _urx_rogue(A, uplo, diag = 'N') + R = copy(A) + for j in axes(R, 2), i in axes(R, 1) + (uplo == 'L' ? i < j : i > j) && (R[i, j] = NaN) + end + diag == 'U' && (R[LinearAlgebra.diagind(R)] .= NaN) + return R +end + +# Every side, uplo, trans and func on every backend (diag below): portable recursion on the CPU, oneAPI, Metal; vendor library on CUDA, AMDGPU. +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "unified_rectrxm! [$backend_name]" begin + @testset "$T func=$func side=$side uplo=$uplo trans=$trans n=$n m=$m" for + T in backend_types(ArrayType, (Float32, Float64)), + n in test_values(:n, (16, 33, 64)), m in test_values(:m, (1, 8)), side in test_flags(:side, ('L', 'R')), uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T', 'C')), func in ('S', 'M') + A = _urx_triangle(T, n, uplo) + Ar = _urx_rogue(A, uplo) + B = side == 'L' ? rand(T, n, m) .- T(0.5) : rand(T, m, n) .- T(0.5) + X, Ag = ArrayType(copy(B)), ArrayType(Ar) + unified_rectrxm!(side, uplo, trans, one(T), func, Ag, X) + synchronize(X) + @test all(isfinite, Array(X)) + @test trxm_ratio(X, func, side, uplo, trans, 'N', one(T), A, B; eps=eps(T)) <= BLAS_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) # A is not written + end + + # Past the solve's base case (256 rows) the recursion's GEMM updates run: one row over (257), two levels (513), and a big n with multiples. + for T in backend_types(ArrayType, (Float32, Float64)), n in test_values(:n, (257, 300, 513, 1025, 2050, 4100)), uplo in test_flags(:uplo, ('L', 'U')) + A = _urx_triangle(T, n, uplo) + Ar = _urx_rogue(A, uplo) + Ag = ArrayType(Ar) # one A for the cases below, checked unchanged after them + @testset "past the threshold, $T func=$func side=$side uplo=$uplo trans=$trans n=$n" for + func in ('S', 'M'), side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'T', 'C')) + B = side == 'L' ? rand(T, n, 4) .- T(0.5) : rand(T, 4, n) .- T(0.5) + X = ArrayType(copy(B)) + unified_rectrxm!(side, uplo, trans, T(1.5), func, Ag, X) + synchronize(X) + @test all(isfinite, Array(X)) + @test trxm_residual_ratio(X, func, side, uplo, trans, 'N', T(1.5), A, B) <= LAPACK_TEST_THRESHOLD + end + @testset "A not written, $T, n=$n, uplo=$uplo" begin + @test isequal(Array(Ag), Ar) + end + end + end +end + +# Each call lands in the expected source file (src/ or the backend's extension). +@testset "unified_rectrxm! dispatch" begin + n = 8 + A = Matrix(LowerTriangular(rand(Float32, n, n) .+ 1)) + Diagonal(10 * ones(Float32, n)) + B = rand(Float32, n, 2) .+ 1 + # The seven-argument form only delegates, so it lands in src/; extensions specialise the eight-argument one. + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 1.0f0, 'S', A, B), + "src/dense/blas/trsm/rectrxm.jl") + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', 1.0f0, 'S', A, B), + "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") + for (name, AT, _) in available_gpu_backends() + haskey(fast, name) || continue + Ag, Bg = AT(A), AT(B) + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', 1.0f0, 'S', Ag, Bg), + fast[name]) + end +end + +# diag = 'U' does not read the diagonal (NaN there), and the CPU kernels and vendor extensions agree on it. +@testset "unified_rectrxm! unit diagonal" begin + @testset "$T func=$func side=$side uplo=$uplo trans=$trans diag=$dg" for + T in test_types((Float32, Float64)), + func in ['S', 'M'], + side in test_flags(:side, ['L', 'R']), + uplo in test_flags(:uplo, ['L', 'U']), + trans in test_flags(:trans, ['N', 'T']), + dg in ['N', 'U'] + + n, m = 32, 8 + A = uplo == 'L' ? Matrix(LowerTriangular(rand(T, n, n) .+ 1)) : + Matrix(UpperTriangular(rand(T, n, n) .+ 1)) + A += Diagonal(10 * ones(T, n)) + Ar = _urx_rogue(A, uplo, dg) + B = side == 'L' ? rand(T, n, m) .+ 1 : rand(T, m, n) .+ 1 + + B_cpu, A_cpu = copy(B), copy(Ar) + unified_rectrxm!(side, uplo, trans, dg, one(T), func, A_cpu, B_cpu) + @test all(isfinite, B_cpu) + @test trxm_ratio(B_cpu, func, side, uplo, trans, dg, one(T), A, B; eps=eps(T)) <= BLAS_TEST_THRESHOLD + @test isequal(A_cpu, Ar) + + for (name, AT, sync) in available_gpu_backends() + name in ("CUDA", "AMDGPU") || continue + T in backend_types(AT, (T,)) || continue + Ag, Bg = AT(copy(Ar)), AT(copy(B)) + unified_rectrxm!(side, uplo, trans, dg, one(T), func, Ag, Bg) + sync(Bg) + @test all(isfinite, Array(Bg)) + @test trxm_ratio(Bg, func, side, uplo, trans, dg, one(T), A, B; eps=eps(T)) <= BLAS_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) + # both paths give the same answer, within the two paths' error bounds + @test Array(Bg) ≈ B_cpu rtol=1000 * n * eps(T) + end + end +end + +# A B that does not match A is refused before any work; an empty B comes back as it is (n = 0 threw DivideError). +@testset "unified_rectrxm! sizes [$backend_name]" for (backend_name, ArrayType, _) in available_backends() + A = ArrayType(Matrix{Float32}(I, 4, 4)) + @test_throws DimensionMismatch unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', A, ArrayType(zeros(Float32, 5, 2))) + @test_throws DimensionMismatch unified_rectrxm!('R', 'L', 'N', 'N', 1f0, 'M', A, ArrayType(zeros(Float32, 2, 5))) + @testset "empty B, func=$func" for func in ('S', 'M') + @test size(unified_rectrxm!('L', 'L', 'N', 'N', 1f0, func, ArrayType(zeros(Float32, 0, 0)), ArrayType(zeros(Float32, 0, 3)))) == (0, 3) + end +end + +# BLAS reads flag letters regardless of case: lower case gives the upper-case result; any other letter is refused. +@testset "unified_rectrxm! flags [$backend_name]" for (backend_name, ArrayType, _) in available_backends() + A, B = Float32.(tril(rand(8, 8)) + 8I), rand(Float32, 8, 3) + @testset "lower case, side=$s uplo=$u trans=$t diag=$d func=$f" for s in ('L', 'R'), u in ('L', 'U'), t in ('N', 'T'), d in ('N', 'U'), f in ('S', 'M') + Bs = s == 'L' ? B : copy(transpose(B)) + X = unified_rectrxm!(s, u, t, d, 1f0, f, ArrayType(A), ArrayType(copy(Bs))) + @test Array(unified_rectrxm!(lowercase(s), lowercase(u), lowercase(t), lowercase(d), 1f0, lowercase(f), ArrayType(A), ArrayType(copy(Bs)))) == Array(X) + end + Ad, Bd = ArrayType(A), ArrayType(copy(B)) + @test_throws ArgumentError unified_rectrxm!('X', 'L', 'N', 'N', 1f0, 'S', Ad, Bd) + @test_throws ArgumentError unified_rectrxm!('L', 'X', 'N', 'N', 1f0, 'S', Ad, Bd) + @test_throws ArgumentError unified_rectrxm!('L', 'L', 'X', 'N', 1f0, 'S', Ad, Bd) + @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'X', 1f0, 'S', Ad, Bd) + @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'X', Ad, Bd) +end + +# A device view whose rows are not consecutive: the vendor solve runs on a contiguous copy (trsm G1). +@testset "a row-strided device view [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", available_backends()) + A = Float32.(tril(rand(8, 8)) + 8I) + P = rand(Float32, 16, 3) + Pd = AT(copy(P)) + NextLA.trsm!('L', 'L', 'N', 'N', 1f0, AT(A), view(Pd, 1:2:16, :)) + R = Array(Pd) + @test R[1:2:16, :] ≈ LowerTriangular(A) \ P[1:2:16, :] && R[2:2:16, :] == P[2:2:16, :] +end diff --git a/test/dense/blas/trsm/rectrxm_complex.jl b/test/dense/blas/trsm/rectrxm_complex.jl new file mode 100644 index 00000000..340ca6df --- /dev/null +++ b/test/dense/blas/trsm/rectrxm_complex.jl @@ -0,0 +1,45 @@ +# unified_rectrxm! on complex matrices (src/dense/blas/trsm/rectrxm.jl), past the solve's base case. + +# Complex n = 300: recursion, offset views and, on a GPU, the portable method forced with invoke. +@testset "complex: recursion, views and the portable path" begin + GEN = Tuple{Char,Char,Char,Char,Number,Char,AbstractMatrix,AbstractMatrix} + targets = [("CPU", Array, _ -> nothing, (false,)); + [(nm, AT, sy, (false, true)) for (nm, AT, sy) in available_gpu_backends()]] + for (name, AT, sync, portables) in targets + @testset "[$name] portable=$portable $T $fn side=$side uplo=$uplo trans=$trans view=$useview" for + portable in portables, + T in backend_types(AT, (ComplexF32, ComplexF64)), + fn in (trsm!, trmm!), + side in test_flags(:side, ('L', 'R')), + uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T', 'C')), + useview in (false, true) + + n, m = 300, 5 + L = rand(T, n, n) ./ n + A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + + Diagonal(fill(T(2), n)) + B = side == 'L' ? rand(T, n, m) : rand(T, m, n) + alpha = T(1.5 - 0.5im) + + if useview + Abig = AT(zeros(T, n + 3, n + 2)) + Bbig = AT(zeros(T, size(B, 1) + 2, size(B, 2) + 2)) + Ag = view(Abig, 3:n+2, 2:n+1) + Bg = view(Bbig, 2:size(B, 1)+1, 2:size(B, 2)+1) + copyto!(Ag, AT(A)); copyto!(Bg, AT(B)) + else + Ag, Bg = AT(A), AT(B) + end + if portable + invoke(unified_rectrxm!, GEN, side, uplo, trans, 'N', alpha, + fn === trsm! ? 'S' : 'M', Ag, Bg) + else + fn(side, uplo, trans, 'N', alpha, Ag, Bg) + end + sync(Bg) + @test trxm_residual_ratio(Bg, fn === trsm! ? 'S' : 'M', side, uplo, trans, 'N', alpha, A, B) <= LAPACK_TEST_THRESHOLD + end + end +end + diff --git a/test/dense/blas/trsm/rectrxm_float16.jl b/test/dense/blas/trsm/rectrxm_float16.jl new file mode 100644 index 00000000..1f45f59e --- /dev/null +++ b/test/dense/blas/trsm/rectrxm_float16.jl @@ -0,0 +1,77 @@ +# unified_rectrxm! on Float16 (src/dense/blas/trsm/rectrxm.jl): base case widened to Float32, views. + +test_params(n = "order of the triangle A") # the number options it takes (--params) + +@testset "unified_rectrxm! Float16 base case" begin + GEN = Tuple{Char,Char,Char,Char,Number,Char,AbstractMatrix,AbstractMatrix} + # A Float16 base case equals the Float32 solve rounded once at the end, on every backend. + @testset "Float16 accumulates wider than it stores [$name]" for (name, AT, sync) in available_backends() + for n in test_values(:n, (16, 64, 128)), (side, uplo, func) in + test_flags((:side, :uplo, nothing), (('L', 'L', 'S'), ('L', 'U', 'S'), ('R', 'L', 'M'))) + A0 = Matrix(LowerTriangular(rand(Float64, n, n) .+ 1.0)) + uplo == 'U' && (A0 = Matrix(UpperTriangular(rand(Float64, n, n) .+ 1.0))) + B0 = rand(Float64, n, n) + A16, B16 = Float16.(A0), Float16.(B0) + + gotd = AT(copy(B16)) + unified_rectrxm!(side, uplo, 'N', 'N', Float16(1), func, AT(copy(A16)), gotd) + + # The same in Float32 on the portable path, rounded once; equal where the call is one base case. + want32d = AT(Float32.(B16)) + invoke(unified_rectrxm!, GEN, side, uplo, 'N', 'N', Float32(1), func, AT(Float32.(A16)), want32d) + sync(gotd); sync(want32d) + got, want32 = Array(gotd), Array(want32d) + if n <= (func == 'S' ? 256 : 16) + @test got == Float16.(want32) + end + + # It is closer to the exact solve of the rounded inputs than accumulating in Float16. + exact = func == 'S' ? + (side == 'L' ? Float64.(A16) \ Float64.(B16) : + Float64.(B16) / Float64.(A16)) : + (side == 'L' ? Float64.(A16) * Float64.(B16) : + Float64.(B16) * Float64.(A16)) + @test norm(Float64.(got) - exact) / norm(exact) < 1e-3 + end + end +end + +# Transposed Float16 operands and views, both sides of both thresholds, against the Float64 answer. +@testset "Float16 with transposes and views" begin + targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] + for (name, AT, sync) in targets + @testset "[$name] $fn n=$n side=$side uplo=$uplo trans=$trans view=$useview" for + fn in (trsm!, trmm!), + n in test_values(:n, (17, 300)), + side in test_flags(:side, ('L', 'R')), + uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T', 'C')), + useview in (false, true) + + m = 5 + L = rand(n, n) ./ n + A = Float16.((uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + + Diagonal(fill(2.0, n))) + B = Float16.(side == 'L' ? rand(n, m) .+ 1 : rand(m, n) .+ 1) + + ref = Float64.(B) + blas = fn === trsm! ? LinearAlgebra.BLAS.trsm! : LinearAlgebra.BLAS.trmm! + blas(side, uplo, trans, 'N', 1.0, Float64.(A), ref) + + if useview + # offset blocks of larger arrays, so neither operand is a whole array + Abig = AT(zeros(Float16, n + 3, n + 2)) + Bbig = AT(zeros(Float16, size(B, 1) + 2, size(B, 2) + 2)) + Ag = view(Abig, 3:n+2, 2:n+1) + Bg = view(Bbig, 2:size(B, 1)+1, 2:size(B, 2)+1) + copyto!(Ag, AT(A)); copyto!(Bg, AT(B)) + else + Ag, Bg = AT(A), AT(B) + end + fn(side, uplo, trans, 'N', Float16(1), Ag, Bg) + sync(Bg) + @test norm(Float64.(Array(Bg)) - ref) / norm(ref) < 1e-2 + end + end +end + diff --git a/test/dense/blas/trsm/trmm.jl b/test/dense/blas/trsm/trmm.jl new file mode 100644 index 00000000..3a0346d9 --- /dev/null +++ b/test/dense/blas/trsm/trmm.jl @@ -0,0 +1,148 @@ +# TRMM kernel drivers and trmm! (src/dense/blas/trsm/trmm.jl); the short form trmm forwards to trmm!. + +test_params(m = "the other dimension of B", n = "order of the triangle A") # the number options it takes (--params) + +const _TRMM_DRIVERS = Dict(('L', 'L') => LeftLowerTRMM!, ('L', 'U') => LeftUpperTRMM!, + ('R', 'L') => RightLowerTRMM!, ('R', 'U') => RightUpperTRMM!) + +# A as callers pass it: NaN in the triangle not referenced, and on the diagonal for a unit diagonal (dblat3's ROGUE value). +function _trmm_rogue(A, uplo, unit) + R = copy(A) + for j in axes(R, 2), i in axes(R, 1) + (uplo == 'L' ? i < j : i > j) && (R[i, j] = NaN) + end + unit && (R[LinearAlgebra.diagind(R)] .= NaN) + return R +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "TRMM kernel drivers [$backend_name]" begin + @testset "$T, side=$side, uplo=$uplo, unitdiag=$unit, n=$n, m=$m" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), + side in test_flags(:side, ('L', 'R')), uplo in test_flags(:uplo, ('L', 'U')), unit in test_flags(:diag, (false, true)), + n in test_values(:n, (1, 8, 16); valid = n -> n <= 16 || "the kernels hold up to 16 rows"), m in test_values(:m, (1, 5, 16, 17, 40)) + A = (uplo == 'L' ? tril : triu)(rand(T, n, n) .- T(0.5)) + Ar = _trmm_rogue(A, uplo, unit) + B = side == 'L' ? rand(T, n, m) .- T(0.5) : rand(T, m, n) .- T(0.5) + X, Ag = ArrayType(copy(B)), ArrayType(Ar) + _TRMM_DRIVERS[(side, uplo)](Ag, X, unit) + synchronize(X) + @test all(isfinite, Array(X)) + @test trmm_ratio(X, side, uplo, 'N', unit ? 'U' : 'N', 1, A, B; eps=Float64(eps(real(T)))) <= BLAS_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) # A is not written + end + + # The short form trmm honours every flag and returns B, as trmm! does (B3). + @testset "trmm equals trmm!, $T, transa=$ta, diag=$dg" for T in backend_types(ArrayType, (Float16, Float32, Float64)), ta in ('N', 'T'), dg in ('N', 'U') + A, B = ArrayType(T.(triu(rand(40, 40)))), rand(T, 40, 4) + X1, X2 = ArrayType(copy(B)), ArrayType(copy(B)) + @test NextLA.trmm('L', 'U', ta, dg, A, X1, T(2)) === X1 + NextLA.trmm!('L', 'U', ta, dg, T(2), A, X2) + @test Array(X1) == Array(X2) + end + + # A triangle past the 16-row tile, or one that does not match B, is refused before any work. + @testset "driver sizes" begin + @test_throws ArgumentError LeftLowerTRMM!(ArrayType(Matrix{Float32}(I, 17, 17)), ArrayType(zeros(Float32, 17, 2))) + @test_throws DimensionMismatch RightUpperTRMM!(ArrayType(Matrix{Float32}(I, 4, 4)), ArrayType(zeros(Float32, 2, 5))) + end + end +end + +# trmm! on every backend: every flag, every type, alpha != 1, vendor path. +@testset "trmm! (BLAS order, over unified_rectrxm!)" begin + @test :trmm! in names(NextLA) + @test NextLA.trmm! !== LinearAlgebra.BLAS.trmm! + + fast = Dict("CUDA" => "ext/cuda/rectrxm.jl", "AMDGPU" => "ext/amdgpu/rectrxm.jl") + targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] + for (name, AT, sync) in targets + @testset "[$name] $fn T=$T side=$side uplo=$uplo trans=$trans diag=$dg" for + T in backend_types(AT, (Float32, Float64, ComplexF32, ComplexF64, Float16)), + fn in (trmm!,), + side in test_flags(:side, ('L', 'R')), + uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T', 'C')), + dg in test_flags(:diag, ('N', 'U')) + + n, m = 48, 5 + # Small off-diagonal part, so the triangle is well conditioned with or without its diagonal. + L = T(0.1) .* rand(T, n, n) + A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + + Diagonal(fill(T(2), n)) + Ar = _trmm_rogue(A, uplo, dg == 'U') + B = side == 'L' ? rand(T, n, m) .+ 1 : rand(T, m, n) .+ 1 + alpha = T(1.5) + + Ag, Bg = AT(Ar), AT(B) + out = fn(side, uplo, trans, dg, alpha, Ag, Bg) + sync(Bg) + @test out === Bg # in place, like BLAS + @test all(isfinite, Array(Bg)) + @test trxm_ratio(Bg, fn === trsm! ? 'S' : 'M', side, uplo, trans, dg, alpha, A, B; eps=Float64(eps(real(T)))) <= BLAS_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) + end + + if haskey(fast, name) + @testset "[$name] reaches the vendor library" begin + for T in backend_types(AT, (Float32, Float64, ComplexF32, ComplexF64)) + Ag = AT(Matrix(LowerTriangular(rand(T, 8, 8))) + Diagonal(fill(T(2), 8))) + Bg = AT(rand(T, 8, 3)) + # the wrapper is generic; what it calls is the extension method + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', + T(1), 'M', Ag, Bg), fast[name]) + end + # Float16 keeps the portable path. + Ag, Bg = AT(Matrix(LowerTriangular(rand(Float16, 8, 8))) + 2I), AT(rand(Float16, 8, 3)) + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', + Float16(1), 'M', Ag, Bg), "src/dense/blas/trsm/rectrxm.jl") + end + end + end +end + +# trmm! into a separate C: C = alpha op(A) B (or B op(A)), B untouched; C = B is in place. +@testset "trmm! with a separate output" begin + targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] + for (name, AT, sync) in targets + @testset "[$name] $T side=$side uplo=$uplo trans=$trans" for + T in backend_types(AT, (Float32, Float64, ComplexF32, ComplexF64, Float16)), + side in test_flags(:side, ('L', 'R')), + uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T', 'C')) + + n, m = 24, 5 + L = T(0.1) .* rand(T, n, n) + A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + + Diagonal(fill(T(2), n)) + Ar = _trmm_rogue(A, uplo, false) + B = side == 'L' ? rand(T, n, m) : rand(T, m, n) + alpha = T(1.5) + + Ag, Bg = AT(Ar), AT(B) + Cg = AT(zeros(T, size(B))) + out = trmm!(side, uplo, trans, 'N', alpha, Ag, Bg, Cg) + sync(Cg) + e = Float64(eps(real(T))) + @test out === Cg + @test all(isfinite, Array(Cg)) + @test trmm_ratio(Cg, side, uplo, trans, 'N', alpha, A, B; eps=e) <= BLAS_TEST_THRESHOLD + @test Array(Bg) == B # B untouched + + Bi = AT(B) # C = B: the in-place form + trmm!(side, uplo, trans, 'N', alpha, Ag, Bi, Bi) + sync(Bi) + @test trmm_ratio(Bi, side, uplo, trans, 'N', alpha, A, B; eps=e) <= BLAS_TEST_THRESHOLD + end + end + @testset "rejects a C of the wrong size" begin + A = Matrix(LowerTriangular(rand(4, 4))) + 2I + @test_throws DimensionMismatch trmm!('L', 'L', 'N', 'N', 1.0, A, rand(4, 2), zeros(3, 2)) + end +end + +# trmm! takes lower-case flags, as BLAS does (it read 't' as 'N'). +@testset "trmm! lower-case flags [$backend_name]" for (backend_name, ArrayType, _) in available_backends() + A, B = Float32.(tril(rand(8, 8)) + 8I), rand(Float32, 8, 3) + X = NextLA.trmm!('L', 'L', 'T', 'U', 2f0, ArrayType(A), ArrayType(copy(B))) + @test Array(NextLA.trmm!('l', 'l', 't', 'u', 2f0, ArrayType(A), ArrayType(copy(B)))) == Array(X) +end diff --git a/test/dense/blas/trsm/trsm.jl b/test/dense/blas/trsm/trsm.jl new file mode 100644 index 00000000..c55411cc --- /dev/null +++ b/test/dense/blas/trsm/trsm.jl @@ -0,0 +1,147 @@ +# TRSM kernel drivers (src/dense/blas/trsm/trsm_kernels.jl) and trsm!; more than 1024 rows are refused (B20), the short form trsm forwards to trsm!. + +test_params(m = "the other dimension of B", n = "order of the triangle A") # the number options it takes (--params) + +const _TRSM_DRIVERS = Dict(('L', 'L') => LeftLowerTRSM!, ('L', 'U') => LeftUpperTRSM!, + ('R', 'L') => RightLowerTRSM!, ('R', 'U') => RightUpperTRSM!) + +# A well-conditioned triangle: diagonal in [1, 1.5], off-diagonal of size 1/n. +function _trsm_triangle(T, n, uplo) + A = (uplo == 'L' ? tril : triu)((rand(T, n, n) .- T(0.5)) ./ T(n)) + A[LinearAlgebra.diagind(A)] .= one(T) .+ rand(T, n) ./ 2 + return A +end + +# A as callers pass it: NaN in the triangle not referenced, and on the diagonal for a unit diagonal (dblat3's ROGUE value). +function _trsm_rogue(A, uplo, unit) + R = copy(A) + for j in axes(R, 2), i in axes(R, 1) + (uplo == 'L' ? i < j : i > j) && (R[i, j] = NaN) + end + unit && (R[LinearAlgebra.diagind(R)] .= NaN) + return R +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "TRSM kernel drivers [$backend_name]" begin + @testset "$T, side=$side, uplo=$uplo, unitdiag=$unit, n=$n, m=$m" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), + side in test_flags(:side, ('L', 'R')), uplo in test_flags(:uplo, ('L', 'U')), unit in test_flags(:diag, (false, true)), + n in test_values(:n, (1, 16, 33, 256); valid = n -> n <= 1024 || "the kernels hold up to 1024 rows"), m in test_values(:m, (1, 8)) + A = _trsm_triangle(T, n, uplo) + Ar = _trsm_rogue(A, uplo, unit) + B = side == 'L' ? rand(T, n, m) .- T(0.5) : rand(T, m, n) .- T(0.5) + X, Ag = ArrayType(copy(B)), ArrayType(Ar) + _TRSM_DRIVERS[(side, uplo)](Ag, X, unit) + synchronize(X) + @test all(isfinite, Array(X)) + @test trsm_ratio(X, side, uplo, 'N', unit ? 'U' : 'N', 1, A, B; eps=Float64(eps(real(T)))) <= BLAS_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) # A is not written + end + + # The largest size the kernels hold (the normwise LAPACK ratio: the element ratio nears 16 at this n); a fixed size, so not run with --n. + _test_option(:n) === nothing || _test_note("skipped the n = 1024 and n = 1025 limit cases: their sizes are fixed") + _test_option(:n) === nothing && @testset "n = 1024, $T, $(side)$(uplo), unitdiag=$unit" for T in backend_types(ArrayType, (Float32, Float64)), + side in test_flags(:side, ('L', 'R')), uplo in test_flags(:uplo, ('L', 'U')), unit in test_flags(:diag, (false, true)) + A = _trsm_triangle(T, 1024, uplo) + Ar = _trsm_rogue(A, uplo, unit) + B = side == 'L' ? rand(T, 1024, 2) .- T(0.5) : rand(T, 2, 1024) .- T(0.5) + X, Ag = ArrayType(copy(B)), ArrayType(Ar) + _TRSM_DRIVERS[(side, uplo)](Ag, X, unit) + synchronize(X) + @test all(isfinite, Array(X)) + @test trxm_residual_ratio(X, 'S', side, uplo, 'N', unit ? 'U' : 'N', 1, A, B) <= LAPACK_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) + end + + # The short form trsm honours every flag and returns B, as trsm! does (B3). + @testset "trsm equals trsm!, $T, transa=$ta, diag=$dg" for T in backend_types(ArrayType, (Float16, Float32, Float64)), ta in ('N', 'T'), dg in ('N', 'U') + A, B = ArrayType(T.(triu(rand(9, 9)) + 9I)), rand(T, 9, 4) + X1, X2 = ArrayType(copy(B)), ArrayType(copy(B)) + @test NextLA.trsm('L', 'U', ta, dg, A, X1, T(2)) === X1 + NextLA.trsm!('L', 'U', ta, dg, T(2), A, X2) + @test Array(X1) == Array(X2) + end + + # Sizes the kernels cannot hold (1025 rows; 1024 is held, above) or that do not match B are refused before any work (B20); an empty B is a no-op. + @testset "driver sizes" begin + Id(n) = ArrayType(Matrix{Float32}(I, n, n)) + for (side, uplo) in (('L', 'L'), ('L', 'U'), ('R', 'L'), ('R', 'U')) + @test_throws ArgumentError _TRSM_DRIVERS[(side, uplo)](Id(1025), ArrayType(zeros(Float32, side == 'L' ? (1025, 1) : (1, 1025)))) + end + @test_throws DimensionMismatch LeftLowerTRSM!(Id(4), ArrayType(zeros(Float32, 5, 2))) + @test_throws DimensionMismatch RightUpperTRSM!(Id(4), ArrayType(zeros(Float32, 2, 5))) + @test LeftUpperTRSM!(Id(0), ArrayType(zeros(Float32, 0, 3))) === nothing + end + + # trsm! takes the 1025 rows the kernels refuse: it recurses (unified_rectrxm!; larger n in rectrxm.jl). + _test_option(:n) === nothing && @testset "trsm! at n = 1025, $T, $(side)$(uplo)" for T in backend_types(ArrayType, (Float32, Float64)), + side in test_flags(:side, ('L', 'R')), uplo in test_flags(:uplo, ('L', 'U')) + A = _trsm_triangle(T, 1025, uplo) + B = side == 'L' ? rand(T, 1025, 2) .- T(0.5) : rand(T, 2, 1025) .- T(0.5) + X = ArrayType(copy(B)) + NextLA.trsm!(side, uplo, 'N', 'N', T(1.5), ArrayType(_trsm_rogue(A, uplo, false)), X) + synchronize(X) + @test trxm_residual_ratio(X, 'S', side, uplo, 'N', 'N', T(1.5), A, B) <= LAPACK_TEST_THRESHOLD + end + end +end + +# trsm! on every backend: every flag, every type, alpha != 1, vendor path. +@testset "trsm! (BLAS order, over unified_rectrxm!)" begin + @test :trsm! in names(NextLA) + @test NextLA.trsm! !== LinearAlgebra.BLAS.trsm! + @test :unified_rectrxm! in names(NextLA) + + fast = Dict("CUDA" => "ext/cuda/rectrxm.jl", "AMDGPU" => "ext/amdgpu/rectrxm.jl") + targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] + for (name, AT, sync) in targets + @testset "[$name] $fn T=$T side=$side uplo=$uplo trans=$trans diag=$dg" for + T in backend_types(AT, (Float32, Float64, ComplexF32, ComplexF64, Float16)), + fn in (trsm!,), + side in test_flags(:side, ('L', 'R')), + uplo in test_flags(:uplo, ('L', 'U')), + trans in test_flags(:trans, ('N', 'T', 'C')), + dg in test_flags(:diag, ('N', 'U')) + + n, m = 48, 5 + # Small off-diagonal part, so the triangle is well conditioned with or without its diagonal. + L = T(0.1) .* rand(T, n, n) + A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + + Diagonal(fill(T(2), n)) + Ar = _trsm_rogue(A, uplo, dg == 'U') + B = side == 'L' ? rand(T, n, m) .+ 1 : rand(T, m, n) .+ 1 + alpha = T(1.5) + + Ag, Bg = AT(Ar), AT(B) + out = fn(side, uplo, trans, dg, alpha, Ag, Bg) + sync(Bg) + @test out === Bg # in place, like BLAS + @test all(isfinite, Array(Bg)) + @test trxm_ratio(Bg, fn === trsm! ? 'S' : 'M', side, uplo, trans, dg, alpha, A, B; eps=Float64(eps(real(T)))) <= BLAS_TEST_THRESHOLD + @test isequal(Array(Ag), Ar) + end + + if haskey(fast, name) + @testset "[$name] reaches the vendor library" begin + for T in backend_types(AT, (Float32, Float64, ComplexF32, ComplexF64)) + Ag = AT(Matrix(LowerTriangular(rand(T, 8, 8))) + Diagonal(fill(T(2), 8))) + Bg = AT(rand(T, 8, 3)) + # the wrapper is generic; what it calls is the extension method + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', + T(1), 'S', Ag, Bg), fast[name]) + end + # Float16 keeps the portable path. + Ag, Bg = AT(Matrix(LowerTriangular(rand(Float16, 8, 8))) + 2I), AT(rand(Float16, 8, 3)) + @test endswith(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', + Float16(1), 'S', Ag, Bg), "src/dense/blas/trsm/rectrxm.jl") + end + end + end +end + +# trsm! takes lower-case flags, as BLAS does (it read 't' as 'N'). +@testset "trsm! lower-case flags [$backend_name]" for (backend_name, ArrayType, _) in available_backends() + A, B = Float32.(tril(rand(8, 8)) + 8I), rand(Float32, 8, 3) + X = NextLA.trsm!('L', 'L', 'T', 'U', 2f0, ArrayType(A), ArrayType(copy(B))) + @test Array(NextLA.trsm!('l', 'l', 't', 'u', 2f0, ArrayType(A), ArrayType(copy(B)))) == Array(X) +end diff --git a/test/dense/blas/trsm/trsm_batched.jl b/test/dense/blas/trsm/trsm_batched.jl new file mode 100644 index 00000000..79a664e3 --- /dev/null +++ b/test/dense/blas/trsm/trsm_batched.jl @@ -0,0 +1,74 @@ +# trsm_batched! (src/dense/blas/trsm/trsm_batched.jl): batched triangular solves. + +test_params(batch = "matrices in a batch") # the number options it takes (--params) + +# A well-conditioned triangle: diagonal in [1, 1.5], off-diagonal of size 1/n. +function _trsmb_triangle(T, n, uplo) + A = (uplo == 'L' ? tril : triu)((rand(T, n, n) .- T(0.5)) ./ T(n)) + A[LinearAlgebra.diagind(A)] .= one(T) .+ rand(T, n) ./ 2 + return A +end + +@testset "batched TRSM [$name]" for (name, AT, sync) in backends + # Dispatch: each backend serves the call with its own method. + @testset "dispatch" begin + A3, B3 = rand(Float32, 4, 4, 2), rand(Float32, 4, 2, 2) + @test occursin(_expected_trsm_batched_file(name), + _method_file(NextLA.trsm_batched!, 'L', 'U', 'N', 'N', _to_backend(AT, A3), _to_backend(AT, B3))) + end + + if name == "Metal" + @testset "refused" begin + A3, B3 = _to_backend(AT, rand(Float32, 4, 4, 2)), _to_backend(AT, rand(Float32, 4, 2, 2)) + @test_throws ArgumentError NextLA.trsm_batched!('L', 'U', 'N', 'N', A3, B3) + @test_throws ArgumentError NextLA.trsm_batched!('L', 'U', 'N', 'N', [A3[:, :, 1]], [B3[:, :, 1]]) + end + continue + end + + # Every flag combination, both layouts, four types, α ≠ 1, batches of 1 and 3. + @testset "$layout, $T, side=$side uplo=$uplo trans=$tr diag=$dg, batch $nb" for layout in (:array3, :vector), + T in backend_types(AT, TEST_TYPES), side in test_flags(:side, ('L', 'R')), uplo in test_flags(:uplo, ('L', 'U')), tr in test_flags(:trans, ('N', 'T', 'C')), + dg in test_flags(:diag, ('N', 'U')), nb in test_values(:batch, (1, 3)) + n, m, α = 17, 5, T(1.5) + As = [_trsmb_triangle(T, n, uplo) for _ in 1:nb] + Bs = [side == 'L' ? rand(T, n, m) .- T(0.5) : rand(T, m, n) .- T(0.5) for _ in 1:nb] + if layout == :array3 + Bd = AT(cat(Bs..., dims=3)) + NextLA.trsm_batched!(side, uplo, tr, dg, AT(cat(As..., dims=3)), Bd, α) + sync(Bd) + res = [Array(Bd)[:, :, i] for i in 1:nb] + else + Bd = [AT(copy(b)) for b in Bs] + NextLA.trsm_batched!(side, uplo, tr, dg, [AT(a) for a in As], Bd, α) + sync(Bd[1]) + res = [Array(b) for b in Bd] + end + @test maximum(trsm_ratio(res[i], side, uplo, tr, dg, α, As[i], Bs[i]; eps=Float64(eps(real(T)))) for i in 1:nb) <= BLAS_TEST_THRESHOLD + end + + # A vector batch whose members differ in size: each member solved with its own size (B17). + name in ("CPU", "CUDA") && @testset "members of different sizes" begin + As = [Float32.(tril(rand(3, 3)) + 3I), Float32.(tril(rand(5, 5)) + 5I)]; Bs = [rand(Float32, 3, 2), rand(Float32, 5, 2)] + Bd = [AT(copy(b)) for b in Bs] + NextLA.trsm_batched!('L', 'L', 'N', 'N', [AT(a) for a in As], Bd) + for i in 1:2 + @test Array(Bd[i]) ≈ LowerTriangular(As[i]) \ Bs[i] + end + end + + @testset "batches of different lengths throw DimensionMismatch" begin + @test_throws DimensionMismatch NextLA.trsm_batched!('L', 'L', 'N', 'N', AT(rand(Float32, 3, 3, 2)), AT(rand(Float32, 3, 2, 3))) + end + + @testset "a 3-D batch with no members" begin + Bd = AT(zeros(Float32, 3, 2, 0)) + @test NextLA.trsm_batched!('L', 'L', 'N', 'N', AT(zeros(Float32, 3, 3, 0)), Bd) === Bd + end + + # Float16 is refused (CPU: BLAS has no Float16 trsm, a MethodError, B45). + @testset "Float16 is refused" begin + A3, B3 = AT(cat(_trsmb_triangle(Float16, 4, 'L'), _trsmb_triangle(Float16, 4, 'L'); dims=3)), AT(rand(Float16, 4, 2, 2)) + @test_throws (name == "CPU" ? MethodError : name == "CUDA" ? ArgumentError : Exception) NextLA.trsm_batched!('L', 'L', 'N', 'N', A3, B3) + end +end diff --git a/test/dense/core/NextLAMatrix.jl b/test/dense/core/NextLAMatrix.jl new file mode 100644 index 00000000..d4f0d7e0 --- /dev/null +++ b/test/dense/core/NextLAMatrix.jl @@ -0,0 +1,58 @@ +# NextLAMatrix (src/dense/core/NextLAMatrix.jl): a wrapper of a host Matrix with BLAS methods forwarded to it. + +_nlm(A) = NextLAMatrix{eltype(A)}(A) + +cpu_wanted() && @testset "NextLAMatrix [CPU]" begin + # Size, length and indexing read and write the wrapped matrix itself. + @testset "container, $T" for T in test_types((Float16, TEST_TYPES...)) + A = rand(T, 5, 3) + M = _nlm(A) + @test M.data === A + @test size(M) == (5, 3) && size(M, 1) == 5 && size(M, 2) == 3 && length(M) == 15 + @test M[2, 3] == A[2, 3] && M[7] == A[7] + M[2, 3] = T(7); M[1] = T(5) + @test A[2, 3] == T(7) && A[1] == T(5) + @test_throws BoundsError M[6, 1] + end + + # The forwarded BLAS calls give exactly what BLAS gives on the raw matrices. + @testset "BLAS wrappers, $T" for T in test_types(TEST_TYPES) + A, B, C = rand(T, 4, 4), rand(T, 4, 4), rand(T, 4, 4) + y = copy(B); BLAS.axpy!(T(2), _nlm(copy(A)), _nlm(y)) + @test y == reshape(BLAS.axpy!(T(2), vec(copy(A)), vec(copy(B))), 4, 4) + c = copy(C); BLAS.gemm!('N', 'T', T(2), _nlm(A), _nlm(B), T(0.5), _nlm(c)) + @test c == BLAS.gemm!('N', 'T', T(2), A, B, T(0.5), copy(C)) + c = copy(C); BLAS.syrk!('U', 'N', T(2), _nlm(A), T(0.5), _nlm(c)) + @test c == BLAS.syrk!('U', 'N', T(2), A, T(0.5), copy(C)) + c = copy(C); BLAS.syr2k!('U', 'N', T(2), _nlm(A), _nlm(B), T(0.5), _nlm(c)) + @test c == BLAS.syr2k!('U', 'N', T(2), A, B, T(0.5), copy(C)) + if T <: Complex + c = copy(C); BLAS.herk!('U', 'N', real(T)(2), _nlm(A), real(T)(0.5), _nlm(c)) + @test c == BLAS.herk!('U', 'N', real(T)(2), A, real(T)(0.5), copy(C)) + c = copy(C); BLAS.her2k!('U', 'N', T(2), _nlm(A), _nlm(B), real(T)(0.5), _nlm(c)) + @test c == BLAS.her2k!('U', 'N', T(2), A, B, real(T)(0.5), copy(C)) + end + end + + # gemv!, trmm! and trsm! have no NextLAMatrix wrapper (the old ones could not work, B42). + @testset "no gemv!, trmm!, trsm! wrappers" begin + @test all(f -> !any(m -> m.module === NextLA, methods(f)), (BLAS.gemv!, BLAS.trmm!, BLAS.trsm!)) + end + + @testset "the plain constructor" begin + A = rand(Float32, 3, 3) + @test NextLAMatrix(A) isa NextLAMatrix{Float32} && NextLAMatrix(A).data === A + end + + @testset "Float16 has no BLAS" begin + @test_throws MethodError BLAS.gemm!('N', 'N', Float16(1), _nlm(rand(Float16, 3, 3)), _nlm(rand(Float16, 3, 3)), Float16(0), _nlm(zeros(Float16, 3, 3))) + end +end + +# The wrapped matrix is a host Matrix: a device array is refused. +for (backend_name, ArrayType, synchronize) in available_backends() + backend_name == "CPU" && continue + @testset "NextLAMatrix refuses a device array [$backend_name]" begin + @test_throws MethodError NextLAMatrix{Float32}(ArrayType(rand(Float32, 3, 3))) + end +end diff --git a/test/dense/lapack/cholesky/potrf.jl b/test/dense/lapack/cholesky/potrf.jl new file mode 100644 index 00000000..ef790e46 --- /dev/null +++ b/test/dense/lapack/cholesky/potrf.jl @@ -0,0 +1,120 @@ +# potrf! (src/dense/lapack/cholesky/potrf.jl): LAPACK on the CPU, cuSOLVER/rocSOLVER on a GPU. + +test_params(n = "order of A") # the number options it takes (--params) + +_potrf_spd(T, n) = (R = rand(T, n, n) .- T(0.5); S = R * R' + T(n) * I; (S + S') / 2) +# Float16 built in Float32 and rounded (Float16 matmul is slow). +_potrf_spd16(T, n) = T === Float16 ? Float16.(_potrf_spd(Float32, n)) : _potrf_spd(T, n) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "POTRF [$backend_name]" begin + # Factor within dpot01's ratio; the other triangle unchanged. + @testset "$T, uplo=$uplo, n=$n" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, (1, 2, 7, 33, 100)) + A0 = _potrf_spd(T, n) + Ad = ArrayType(copy(A0)) + F, info = NextLA.potrf!(uplo, Ad) + synchronize(F) + @test F === Ad && info == 0 + @test chol_ratio(F, uplo, A0; eps=eps(real(T))) <= LAPACK_TEST_THRESHOLD + @test other_triangle(uplo, F) == other_triangle(uplo, A0) + end + + # info is the order of the first leading minor that is not positive definite. + @testset "not positive definite, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + A = Matrix{T}(I, 6, 6) + A[4, 4] = -1 + @test NextLA.potrf!('L', ArrayType(A))[2] == 4 + end + + # The opposite triangle is not read: NaN there leaves the factor right and stays as it was. + has_device_potrf(backend_name) && @testset "opposite triangle not read, $T, uplo=$uplo, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, (2, 33, 100)) + A0 = _potrf_spd(T, n) + Ain = copy(A0) + Ain[uplo == 'L' ? triu(trues(n, n), 1) : tril(trues(n, n), -1)] .= T(NaN) + F, info = NextLA.potrf!(uplo, ArrayType(copy(Ain))) + synchronize(F) + @test info == 0 + @test chol_ratio(F, uplo, A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test isequal(other_triangle(uplo, F), other_triangle(uplo, Ain)) + end + + # Float16 is exactly the Float32 factor rounded once, computed on the same backend. + has_device_potrf(backend_name) && @testset "Float16 is the rounded Float32 factor, uplo=$uplo" for T in backend_types(ArrayType, (Float16,)), uplo in test_flags(:uplo, ('L', 'U')) + A0 = _potrf_spd16(T, 32) + want, _ = NextLA.potrf!(uplo, ArrayType(Float32.(A0))) + @test Array(NextLA.potrf!(uplo, ArrayType(copy(A0)))[1]) == Float16.(Array(want)) + end + + # Big sizes and multiples; Float16 also exactly the rounded Float32 factor. + has_device_potrf(backend_name) && @testset "n = $n, $T, uplo=$uplo" for n in test_values(:n, (1024, 2048, 4096)), T in backend_types(ArrayType, (Float16, Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')) + A0 = _potrf_spd16(T, n) + F, info = NextLA.potrf!(uplo, ArrayType(copy(A0))) + synchronize(F) + @test info == 0 + @test chol_ratio(F, uplo, A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test other_triangle(uplo, F) == other_triangle(uplo, A0) + T === Float16 && @test Array(F) == Float16.(Array(NextLA.potrf!(uplo, ArrayType(Float32.(A0)))[1])) + end + + has_device_potrf(backend_name) && @testset "n = 0" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + @test NextLA.potrf!('L', ArrayType(zeros(T, 0, 0)))[2] == 0 + end + + # A view inside a larger matrix (a Float16 view is the recursive Cholesky's leaf): only the view's triangle changes. + has_device_potrf(backend_name) && @testset "a view, $T, uplo=$uplo" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), uplo in test_flags(:uplo, T <: Real ? ('L', 'U') : ('L',)) + A0 = _potrf_spd(T, 10) + Big = zeros(T, 12, 13) + Big[2:11, 3:12] .= A0 + Bd = ArrayType(copy(Big)) + V = view(Bd, 2:11, 3:12) + F, info = NextLA.potrf!(uplo, V) + synchronize(Bd) + @test F === V && info == 0 + B = Array(Bd) + @test chol_ratio(B[2:11, 3:12], uplo, A0; eps=eps(real(T))) <= LAPACK_TEST_THRESHOLD + @test other_triangle(uplo, B[2:11, 3:12]) == other_triangle(uplo, A0) + outside = trues(12, 13); outside[2:11, 3:12] .= false + @test B[outside] == Big[outside] + end + + has_device_potrf(backend_name) && @testset "defaults to lower" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A0 = _potrf_spd(T, 16) + a, b = ArrayType(copy(A0)), ArrayType(copy(A0)) + NextLA.potrf!(a) + NextLA.potrf!('L', b) + @test Array(a) == Array(b) + end + + # uplo in either case, as LAPACK takes it. + has_device_potrf(backend_name) && @testset "lowercase uplo, $T, uplo=$uplo" for T in backend_types(ArrayType, (Float16, Float32)), uplo in test_flags(:uplo, ('L', 'U')) + A0 = T.(_potrf_spd(Float32, 16)) + a, b = ArrayType(copy(A0)), ArrayType(copy(A0)) + NextLA.potrf!(uplo, a) + NextLA.potrf!(lowercase(uplo), b) + @test Array(b) == Array(a) + end + + @testset "dispatches to its own backend" begin + @test occursin(_expected_potrf_file(backend_name), _method_file(NextLA.potrf!, 'L', ArrayType(rand(Float32, 8, 8)))) + end + + @testset "argument errors" begin + @test_throws ArgumentError NextLA.potrf!('X', ArrayType(rand(Float32, 4, 4) + 4I)) + @test_throws DimensionMismatch NextLA.potrf!('L', ArrayType(rand(Float32, 4, 5))) + end + end +end + +# A device view whose rows are not consecutive: factored through a contiguous copy, rows outside the view kept (B29). +@testset "a row-strided device view [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", available_backends()) + S = Float32.(_potrf_spd(Float64, 8)) + P = rand(Float32, 16, 8); P[1:2:16, :] .= S + Pd = AT(copy(P)) + _, info = NextLA.potrf!('L', view(Pd, 1:2:16, :)) + R = Array(Pd) + @test info == 0 && chol_ratio(R[1:2:16, :], 'L', S; eps=eps(Float32)) <= LAPACK_TEST_THRESHOLD && R[2:2:16, :] == P[2:2:16, :] +end diff --git a/test/dense/lapack/cholesky/potrf_batched.jl b/test/dense/lapack/cholesky/potrf_batched.jl new file mode 100644 index 00000000..4d3c7d1f --- /dev/null +++ b/test/dense/lapack/cholesky/potrf_batched.jl @@ -0,0 +1,119 @@ +# potrf_batched! (src/dense/lapack/cholesky/potrf_batched.jl): LAPACK loop on the CPU, batched solver on a GPU. + +test_params(n = "order of A") # the number options it takes (--params) + +_potrfb_spd(T, n) = (R = rand(T, n, n) .- T(0.5); S = R * R' + T(n) * I; (S + S') / 2) + +for (name, AT, sync) in backends + @testset "POTRF_BATCHED [$name]" begin + @testset "dispatches to its own backend" begin + @test occursin(_expected_potrf_batched_file(name), _method_file(NextLA.potrf_batched!, 'U', AT(rand(Float32, 4, 4, 2)))) + end + + if name == "Metal" + @testset "refused on Metal" begin + @test_throws ArgumentError NextLA.potrf_batched!('U', AT(rand(Float32, 4, 4, 2))) + end + continue + end + + TF = supports_float64(AT) ? Float64 : Float32 # Float32 on a device without Float64 + + # Each matrix within dpot01's ratio, status 0 (cuSOLVER's 'U' uses the lower triangle as workspace). + @testset "$T, uplo=$uplo, n=$n" for T in backend_types(AT, TEST_TYPES), uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, (1, 9, 33)) + A0 = cat((_potrfb_spd(T, n) for _ in 1:3)...; dims=3) + Ad = AT(copy(A0)) + result = NextLA.potrf_batched!(uplo, Ad) + sync(Ad) + result isa Tuple && @test Array(result[2]) == zeros(Int32, 3) + A = Array(Ad) + for b in 1:3 + @test chol_ratio(A[:, :, b], uplo, A0[:, :, b]; eps=eps(real(T))) <= LAPACK_TEST_THRESHOLD + (uplo == 'L' || name == "CPU") && @test other_triangle(uplo, A[:, :, b]) == other_triangle(uplo, A0[:, :, b]) + end + end + + # The status of each matrix: 0, or the order of its failing minor. + @testset "matrices that are not positive definite" begin + F = cat(Matrix{TF}(2I, 8, 8), Matrix{TF}(2I, 8, 8), Matrix{TF}(2I, 8, 8); dims=3) + F[5, 5, 2] = -1 + F[1, 1, 3] = -1 + result = NextLA.potrf_batched!('L', AT(F)) + result isa Tuple && @test Array(result[2]) == Int32[0, 5, 1] + end + + # The documented return: (A, status) on the CPU, CUDA and AMDGPU, A on oneAPI (C20: CUDA returned its slices). + @testset "returns what its docstring says" begin + Ad = AT(cat(_potrfb_spd(TF, 9), _potrfb_spd(TF, 9); dims=3)) + result = NextLA.potrf_batched!('L', Ad) + if name == "oneAPI" + @test result === Ad + else + @test result[1] === Ad && Array(result[2]) == Int32[0, 0] + end + end + + # A view of a larger array, whose slices are not contiguous: factored in place and the view returned. + @testset "a view of a larger array" begin + S = cat(_potrfb_spd(TF, 9), _potrfb_spd(TF, 9); dims=3) + B = AT(zeros(TF, 12, 9, 2)) + B[1:9, :, :] .= AT(S) + Bv = view(B, 1:9, :, :) + result = NextLA.potrf_batched!('L', Bv) + sync(B) + name == "oneAPI" ? (@test result === Bv) : (@test result[1] === Bv && Array(result[2]) == Int32[0, 0]) + for b in 1:2 + @test chol_ratio(Array(B)[1:9, :, b], 'L', S[:, :, b]; eps=eps(TF)) <= LAPACK_TEST_THRESHOLD + end + end + + @testset "Float16 is refused" begin + @test_throws MethodError NextLA.potrf_batched!('L', AT(cat(Float16.(_potrfb_spd(Float32, 4)), Float16.(_potrfb_spd(Float32, 4)); dims=3))) + end + + @testset "argument errors" begin + @test_throws DimensionMismatch NextLA.potrf_batched!('L', AT(rand(TF, 4, 5, 2))) + @test_throws ArgumentError NextLA.potrf_batched!('X', AT(cat(_potrfb_spd(TF, 4), _potrfb_spd(TF, 4); dims=3))) + end + + # uplo in either case, as LAPACK takes it. + @testset "lowercase uplo, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A0 = cat(_potrfb_spd(TF, 9), _potrfb_spd(TF, 9); dims=3) + a, b = AT(copy(A0)), AT(copy(A0)) + NextLA.potrf_batched!(uplo, a) + NextLA.potrf_batched!(lowercase(uplo), b) + sync(b) + @test Array(b) == Array(a) + end + + name == "CUDA" && @testset "an empty vector batch" begin + E = typeof(AT(zeros(Float32, 2, 2)))[] + F, info = NextLA.potrf_batched!('L', E) + @test F === E && isempty(info) + end + + # A vector batch whose members differ in size: each member factored with its own size (B30). + name == "CUDA" && @testset "members of different sizes" begin + As = [_potrfb_spd(Float32, 4), _potrfb_spd(Float32, 7)] + Av = [AT(A) for A in As] + @test NextLA.potrf_batched!('L', Av)[2] == Cint[0, 0] + for i in 1:2 + @test chol_ratio(Av[i], 'L', As[i]; eps=eps(Float32)) <= LAPACK_TEST_THRESHOLD + end + end + + # CUDA also takes a vector of matrices, views of a larger array included. + name == "CUDA" && @testset "a vector of matrices and of views" begin + As = [_potrfb_spd(TF, 6), _potrfb_spd(TF, 6)] + Av = [AT(A) for A in As] + @test Array(NextLA.potrf_batched!('L', Av)[2]) == Int32[0, 0] + W = AT(zeros(TF, 8, 16)) + W[1:6, 1:6] .= AT(As[1]); W[1:6, 9:14] .= AT(As[2]) + NextLA.potrf_batched!('L', [view(W, 1:6, 1:6), view(W, 1:6, 9:14)]) + for (i, c) in ((1, 1:6), (2, 9:14)) + @test chol_ratio(Av[i], 'L', As[i]; eps=eps(TF)) <= LAPACK_TEST_THRESHOLD + @test chol_ratio(Array(W)[1:6, c], 'L', As[i]; eps=eps(TF)) <= LAPACK_TEST_THRESHOLD + end + end + end +end diff --git a/test/dense/lapack/cholesky/potrf_blocked.jl b/test/dense/lapack/cholesky/potrf_blocked.jl new file mode 100644 index 00000000..b496c3d6 --- /dev/null +++ b/test/dense/lapack/cholesky/potrf_blocked.jl @@ -0,0 +1,97 @@ +# cholesky_blocked! (src/dense/lapack/cholesky/potrf_blocked.jl): blocked Cholesky, GPU only, real types. + +test_params(n = "order of A", block = "block size (at most 64)") # the number options it takes (--params) + +# Float16 built in Float32 and rounded (Float16 matmul is slow at the big sizes). +_cholb_spd(T, n) = T === Float16 ? Float16.(_cholb_spd(Float32, n)) : (R = rand(T, n, n) .- T(0.5); S = R * R' + T(n) * I; (S + S') / 2) + +# Componentwise backward error max |LLᵀ - A| ./ (|L||Lᵀ| + (n+1) η max lᵢᵢ), η the type's smallest subnormal (Higham 2002, §2.1, Thm 10.3). +function _cholb_cw(F, A) + Fd = Float64.(tril(Array(F))); n = size(Fd, 1) + L = LowerTriangular(Fd) + G = abs.(L) * abs.(L') .+ (n + 1) * Float64(nextfloat(zero(eltype(A)))) * maximum(abs, diag(Fd)) + return maximum(abs.(L * L' .- Float64.(Array(A))) ./ G) +end + +# Float16 roundings allowed per entry (a Float16 host model needs at most 10 to n = 2000; a skipped update over 900). +const _CHOLB_F16_ROUNDINGS = 30 + +for (backend_name, ArrayType, synchronize) in available_gpu_backends() + @testset "CHOLESKY_BLOCKED [$backend_name]" begin + TF = supports_float64(ArrayType) ? Float64 : Float32 # Float32 on a device without Float64 (Metal) + + # dpot01's ratio (Float16 also componentwise: dpot01 cannot fail past n = 34), both kernels, which agree exactly; 128 is two full blocks. + @testset "$T, n=$n, block=$bs" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (n, bs) in test_cases((:n, :block), ((1, 1), (7, 4), (32, 32), (64, 64), (65, 64), (100, 64), (128, 64), (129, 16), (200, 1), + (500, 64), (1000, 64), (2000, 64)); + valid = (n, bs) -> bs <= NextLA.CHOL_BLOCK || "the block is at most $(NextLA.CHOL_BLOCK)") + A0 = _cholb_spd(T, n) + As, Ar = ArrayType(copy(A0)), ArrayType(copy(A0)) + @test NextLA.cholesky_blocked!(As; block=bs, kernel=:shared) === As + NextLA.cholesky_blocked!(Ar; block=bs, kernel=:register) + synchronize(As); synchronize(Ar) + @test chol_ratio(As, 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test chol_ratio(Ar, 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test tril(Array(As)) == tril(Array(Ar)) + T === Float16 && @test _cholb_cw(As, A0) <= _CHOLB_F16_ROUNDINGS * Float64(eps(Float16)) / 2 + end + + # One block leaves the strict upper triangle alone (more blocks do not: source issue B28). + @testset "one block leaves the upper triangle, kernel=$kernel" for kernel in (:shared, :register) + A0 = _cholb_spd(TF, 64) + Ad = ArrayType(copy(A0)) + NextLA.cholesky_blocked!(Ad; block=64, kernel) + synchronize(Ad) + @test triu(Array(Ad), 1) == triu(A0, 1) + end + + @testset "threads=$th" for th in (1, 32, 100, 1024) + A0 = _cholb_spd(TF, 100) + Ad = ArrayType(copy(A0)) + NextLA.cholesky_blocked!(Ad; block=64, threads=th) + synchronize(Ad) + @test chol_ratio(Ad, 'L', A0; eps=eps(TF)) <= LAPACK_TEST_THRESHOLD + end + + # A view inside a larger matrix: only the view changes. + @testset "a view" begin + A0 = _cholb_spd(TF, 70) + Big = zeros(TF, 80, 80) + Big[5:74, 6:75] .= A0 + Bd = ArrayType(copy(Big)) + NextLA.cholesky_blocked!(view(Bd, 5:74, 6:75); block=32) + synchronize(Bd) + B = Array(Bd) + @test chol_ratio(B[5:74, 6:75], 'L', A0; eps=eps(TF)) <= LAPACK_TEST_THRESHOLD + outside = trues(80, 80); outside[5:74, 6:75] .= false + @test B[outside] == Big[outside] + end + + @testset "n = 0" begin + @test size(NextLA.cholesky_blocked!(ArrayType(zeros(TF, 0, 0)))) == (0, 0) + end + + # A matrix that is not positive definite throws PosDefException at its first bad pivot; the device stays usable. + @testset "not positive definite, $T, minor $k of $n, kernel=$kernel" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (n, k) in ((64, 5), (200, 150)), kernel in (:shared, :register) + S = Matrix{T}(I, n, n); S[k, k] = -1 + @test_throws LinearAlgebra.PosDefException(k) NextLA.cholesky_blocked!(ArrayType(S); kernel) + A0 = _cholb_spd(T, 100) + L = tril(Array(NextLA.cholesky_blocked!(ArrayType(copy(A0)); kernel))) + @test chol_ratio(L, 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + end + + @testset "argument errors" begin + A = ArrayType(_cholb_spd(TF, 64)) + @test_throws ArgumentError NextLA.cholesky_blocked!(A; kernel=:nosuch) + @test_throws ArgumentError NextLA.cholesky_blocked!(A; block=0) + @test_throws ArgumentError NextLA.cholesky_blocked!(A; block=65) + @test_throws DimensionMismatch NextLA.cholesky_blocked!(ArrayType(rand(TF, 8, 6))) + end + end +end + +# The CPU backend is refused. +cpu_wanted() && @testset "CHOLESKY_BLOCKED refuses the CPU" begin + @test_throws ArgumentError NextLA.cholesky_blocked!(_cholb_spd(Float64, 32)) +end diff --git a/test/dense/lapack/cholesky/potrf_kernel.jl b/test/dense/lapack/cholesky/potrf_kernel.jl new file mode 100644 index 00000000..9db45486 --- /dev/null +++ b/test/dense/lapack/cholesky/potrf_kernel.jl @@ -0,0 +1,50 @@ +# cholesky_lower! (src/dense/lapack/cholesky/potrf_kernel.jl): unblocked Cholesky in one work-group. + +test_params(n = "order of A") # the number options it takes (--params) + +_cholk_spd(T, n) = (R = rand(T, n, n) .- T(0.5); S = R * R' + T(n) * I; (S + S') / 2) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "CHOLESKY_LOWER [$backend_name]" begin + # Factor within dpot01's ratio, upper triangle zeroed; n past the 512 threads too. + @testset "$T, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), n in test_values(:n, (1, 2, 7, 33, 100, 513, 700)) + A0 = _cholk_spd(T, n) + Ad = ArrayType(copy(A0)) + @test NextLA.cholesky_lower!(Ad) === Ad + synchronize(Ad) + @test chol_ratio(Ad, 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test all(iszero, triu(Array(Ad), 1)) + end + + # A view inside a larger matrix: only the view changes. + @testset "a view" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A0 = _cholk_spd(T, 10) + Big = zeros(T, 12, 13) + Big[2:11, 3:12] .= A0 + Bd = ArrayType(copy(Big)) + NextLA.cholesky_lower!(view(Bd, 2:11, 3:12)) + synchronize(Bd) + B = Array(Bd) + @test chol_ratio(B[2:11, 3:12], 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + outside = trues(12, 13); outside[2:11, 3:12] .= false + @test B[outside] == Big[outside] + end + + # A matrix that is not positive definite throws PosDefException at its first bad pivot; the device stays usable. + @testset "not positive definite, $T, minor $k of $n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), (n, k) in ((8, 5), (600, 520)) + S = Matrix{T}(I, n, n); S[k, k] = -1 + @test_throws LinearAlgebra.PosDefException(k) NextLA.cholesky_lower!(ArrayType(S)) + A0 = _cholk_spd(T, 33) + @test chol_ratio(NextLA.cholesky_lower!(ArrayType(copy(A0))), 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + end + + @testset "n = 0 factors nothing" begin + @test size(NextLA.cholesky_lower!(ArrayType(zeros(Float32, 0, 0)))) == (0, 0) + end + + @testset "rejects a non-square matrix" begin + @test_throws DimensionMismatch NextLA.cholesky_lower!(ArrayType(rand(supports_float64(ArrayType) ? Float64 : Float32, 4, 5))) + end + end +end diff --git a/test/dense/lapack/cholesky/potrf_register.jl b/test/dense/lapack/cholesky/potrf_register.jl new file mode 100644 index 00000000..b866be96 --- /dev/null +++ b/test/dense/lapack/cholesky/potrf_register.jl @@ -0,0 +1,19 @@ +# chol_kernel_register! (src/dense/lapack/cholesky/potrf_register.jl), launched alone on one block; GPU only. + +test_params(n = "order of A (at most 64)") # the number options it takes (--params) + +_cholr_spd(T, n) = (R = rand(T, n, n) .- T(0.5); S = R * R' + T(n) * I; (S + S') / 2) + +for (backend_name, ArrayType, synchronize) in available_gpu_backends() + # Factor within dpot01's ratio; the strict upper triangle unchanged. + @testset "CHOL_KERNEL_REGISTER [$backend_name], $T, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), n in test_values(:n, (1, 16, 33, 48, 64); + valid = n -> n <= NextLA.CHOL_BLOCK || "the register kernel takes one block of at most $(NextLA.CHOL_BLOCK)") + A0 = _cholr_spd(T, n) + Ad = ArrayType(copy(A0)) + NextLA.chol_kernel_register!(KernelAbstractions.get_backend(Ad), NextLA.CHOL_REG_THREADS)( + Ad, Val(n); ndrange=NextLA.CHOL_REG_THREADS) + synchronize(Ad) + @test chol_ratio(Ad, 'L', A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test triu(Array(Ad), 1) == triu(A0, 1) + end +end diff --git a/test/dense/lapack/cholesky/recpotrf.jl b/test/dense/lapack/cholesky/recpotrf.jl new file mode 100644 index 00000000..47d6466d --- /dev/null +++ b/test/dense/lapack/cholesky/recpotrf.jl @@ -0,0 +1,135 @@ +# potrf_recursive! (src/dense/lapack/cholesky/recpotrf.jl): recursive Cholesky; potrf! leaves, unified_rectrxm! panels, syrk! updates (recsyrk! for Float16). + +test_params(n = "order of A", block = "size where the recursion stops") # the number options it takes (--params) + +_recp_spd(T, n) = (R = rand(T, n, n) .- T(0.5); S = R * R' + T(n) * I; (S + S') / 2) + +# Componentwise backward error max |LLᵀ - A| ./ (|L||Lᵀ| + (n+1) η max lᵢᵢ), η the type's smallest subnormal (Higham 2002, §2.1, Thm 10.3). +function _recp_cw(F, uplo, A) + Fd = Float64.(Array(F)); n = size(Fd, 1) + L = uplo == 'L' ? LowerTriangular(Fd) : UpperTriangular(Fd)' + G = abs.(L) * abs.(L') .+ (n + 1) * Float64(nextfloat(zero(eltype(A)))) * maximum(abs, diag(Fd)) + return maximum(abs.(L * L' .- Float64.(Array(A))) ./ G) +end + +# Float16 roundings allowed per entry: measured at most 4 up to n = 4353; a skipped trailing update needs over 180. +const _RECP_F16_ROUNDINGS = 30 + +# The bound: γ(n+1) = (n+1)u / (1 - (n+1)u); for Float16, γ(n+1) of Float32 plus _RECP_F16_ROUNDINGS Float16 roundings. +_recp_γ(T, m) = (u = Float64(eps(T)) / 2; m * u / (1 - m * u)) +_recp_cw_bound(T, n) = T === Float16 ? _recp_γ(Float32, n + 1) + _RECP_F16_ROUNDINGS * Float64(eps(Float16)) / 2 : _recp_γ(T, n + 1) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "POTRF_RECURSIVE [$backend_name]" begin + TF = supports_float64(ArrayType) ? Float64 : Float32 # Float32 on a device without Float64 (Metal) + + # Factor within dpot01's ratio, other triangle unchanged; block 1 recurses to 1×1, 256 is one leaf. + @testset "$T, uplo=$uplo, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, (1, 7, 33, 100, 129)) + for bs in test_values(:block, (1, 8, 32, 256)) + A0 = _recp_spd(T, n) + Ad = ArrayType(copy(A0)) + @test NextLA.potrf_recursive!(Ad, bs; uplo) === Ad + synchronize(Ad) + @test chol_ratio(Ad, uplo, A0; eps=eps(T)) <= LAPACK_TEST_THRESHOLD + @test other_triangle(uplo, Ad) == other_triangle(uplo, A0) + end + end + + # Complex within one leaf (potrf!); the recursion is not Hermitian yet (source issue B26). + @testset "$T in one leaf, uplo=$uplo" for T in backend_types(ArrayType, (ComplexF32, ComplexF64)), uplo in test_flags(:uplo, ('L', 'U')) + A0 = _recp_spd(T, 33) + Ad = ArrayType(copy(A0)) + NextLA.potrf_recursive!(Ad, 64; uplo) + synchronize(Ad) + @test chol_ratio(Ad, uplo, A0; eps=eps(real(T))) <= LAPACK_TEST_THRESHOLD + end + + # Signed SPD input of condition 100 rounded to T, where the trailing update matters; a new matrix per uplo and block. + has_device_potrf(backend_name) && @testset "componentwise, condition 100, $T, n=$n" for T in backend_types(ArrayType, (Float16, Float32)), + n in test_values(:n, (7, 33, 100, 129)) + for uplo in test_flags(:uplo, ('L', 'U')), bs in test_values(:block, (1, 8, 32)) + A0 = T.(spd(Float64, n; cond=100)) + Ad = ArrayType(copy(A0)) + NextLA.potrf_recursive!(Ad, bs; uplo) + synchronize(Ad) + @test _recp_cw(Ad, uplo, A0) <= _recp_cw_bound(T, n) + end + end + + # The default block (4096): n = 4353 is a 4096 leaf, a 257-row update and a panel solve past 256 rows. + has_device_potrf(backend_name) && @testset "default block, n = $n, $T" for n in test_values(:n, (4353,); + valid = n -> n > NextLA.POTRF_BLOCK_SIZE || "n must pass the default block $(NextLA.POTRF_BLOCK_SIZE)"), + T in backend_types(ArrayType, (Float16, Float32, Float64)) + for uplo in test_flags(:uplo, ('L', 'U')) + A0 = T.(_recp_spd(T === Float16 ? Float32 : T, n)) # Float16 built in Float32 (Float16 matmul is slow) + Ad = ArrayType(copy(A0)) + @test NextLA.potrf_recursive!(Ad; uplo) === Ad + synchronize(Ad) + @test _recp_cw(Ad, uplo, A0) <= _recp_cw_bound(T, n) + @test other_triangle(uplo, Ad) == other_triangle(uplo, A0) + end + end + + # Big sizes and multiples with block 256: each doubling adds a level and the panel solves pass 256 rows. + has_device_potrf(backend_name) && @testset "n = $n, block 256, $T" for n in test_values(:n, (1000, 2000, 4000)), + T in backend_types(ArrayType, (Float16, Float32, Float64)) + for uplo in test_flags(:uplo, ('L', 'U')) + A0 = T.(_recp_spd(T === Float16 ? Float32 : T, n)) + Ad = ArrayType(copy(A0)) + NextLA.potrf_recursive!(Ad, 256; uplo) + synchronize(Ad) + @test _recp_cw(Ad, uplo, A0) <= _recp_cw_bound(T, n) + @test other_triangle(uplo, Ad) == other_triangle(uplo, A0) + end + end + + @testset "block_size >= n is potrf! exactly, $T" for T in backend_types(ArrayType, (Float32, Float64)) + A0 = _recp_spd(T, 32) + a, b = ArrayType(copy(A0)), ArrayType(copy(A0)) + NextLA.potrf_recursive!(a, 64) + NextLA.potrf!('L', b) + @test tril(Array(a)) == tril(Array(b)) + end + + # A view inside a larger matrix: only the view changes. + has_device_potrf(backend_name) && @testset "a view" begin + A0 = _recp_spd(TF, 33) + Big = zeros(TF, 40, 40) + Big[3:35, 4:36] .= A0 + Bd = ArrayType(copy(Big)) + NextLA.potrf_recursive!(view(Bd, 3:35, 4:36), 8) + synchronize(Bd) + B = Array(Bd) + @test chol_ratio(B[3:35, 4:36], 'L', A0; eps=eps(TF)) <= LAPACK_TEST_THRESHOLD + outside = trues(40, 40); outside[3:35, 4:36] .= false + @test B[outside] == Big[outside] + end + + has_device_potrf(backend_name) && @testset "n = 0" begin + @test size(NextLA.potrf_recursive!(ArrayType(zeros(TF, 0, 0)), 4)) == (0, 0) + end + + # PosDefException names the failing minor in the whole matrix, not in its leaf. + has_device_potrf(backend_name) && @testset "not positive definite throws PosDefException, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A0 = Matrix{TF}(I, 12, 12) + A0[10, 10] = -1 + err = try NextLA.potrf_recursive!(ArrayType(A0), 4; uplo); nothing catch e; e end + @test err isa PosDefException && err.info == 10 + end + + # uplo in either case, as LAPACK takes it. + has_device_potrf(backend_name) && @testset "lowercase uplo gives the same result, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + S = _recp_spd(TF, 40) + a, b = ArrayType(copy(S)), ArrayType(copy(S)) + NextLA.potrf_recursive!(a, 16; uplo=uplo) + NextLA.potrf_recursive!(b, 16; uplo=lowercase(uplo)) + @test Array(b) == Array(a) + end + + @testset "argument errors" begin + @test_throws ArgumentError NextLA.potrf_recursive!(ArrayType(Matrix{TF}(I, 4, 4)), 0) + @test_throws ArgumentError NextLA.potrf_recursive!(ArrayType(Matrix{TF}(I, 4, 4)); uplo='X') + @test_throws DimensionMismatch NextLA.potrf_recursive!(ArrayType(zeros(TF, 4, 6)), 2) + end + end +end diff --git a/test/dense/lapack/lu/lu_base.jl b/test/dense/lapack/lu/lu_base.jl new file mode 100644 index 00000000..597d796c --- /dev/null +++ b/test/dense/lapack/lu/lu_base.jl @@ -0,0 +1,50 @@ +# lu_base! (src/dense/lapack/lu/lu_base.jl): LU with partial pivoting in one work-group (n <= 32 on a GPU). + +test_params(n = "order of A (at most 32 on a GPU)") # the number options it takes (--params) + +# ‖L U - PA‖ / ‖PA‖ in Float64; Float16 checks it against 8 sqrt(n) u, as lu_ratio's 30 n u is above 1 from n = 34 on. +_lu_base_backward_error(L, U, PA) = (A = Float64.(PA); norm(Float64.(L) * Float64.(U) - A) / norm(A)) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "lu_base! [$backend_name]" begin + TF = supports_float64(ArrayType) ? Float64 : Float32 # Float64 data, Float32 on a device without it (Metal) + sizes = backend_name == "CPU" ? (1, 2, 5, 16, 32, 64, 100) : (1, 2, 5, 16, 32) + # A diagonally dominant matrix, and a random one of condition 1e3 where pivoting has work to do. + @testset "$T, n=$n, $kind" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), n in test_values(:n, sizes; valid = n -> backend_name == "CPU" || n <= 32 || "lu_base! takes n ≤ 32 on a GPU"), kind in (:dominant, :random) + A0 = kind == :dominant ? rand(T, n, n) + T(n) * I : randsvd(T, n, n; cond=1e3) + Af, p, info = NextLA.lu_base!(ArrayType(copy(A0))) + synchronize(Af) + A = Array(Af) + @test info == 0 + @test p isa Vector{Int} && sort(p) == 1:n + @test lu_ratio(UnitLowerTriangular(A), UpperTriangular(A), A0[p, :]; eps=Float64(eps(real(T)))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _lu_base_backward_error(UnitLowerTriangular(A), UpperTriangular(A), A0[p, :]) <= 8 * sqrt(n) * eps(Float16) / 2 + end + + # Big sizes on the CPU: the docstring's 1024 and its multiples. + backend_name == "CPU" && @testset "$T, n=$n, random" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + n in test_values(:n, (1024, 2048, 4096)) + A0 = T.(randsvd(Float64, n, n; cond=1e3)) + Af, p, info = NextLA.lu_base!(copy(A0)) + L, U = UnitLowerTriangular(Af), UpperTriangular(Af) + @test info == 0 + @test p isa Vector{Int} && sort(p) == 1:n + @test lu_ratio(L, U, A0[p, :]; eps=Float64(eps(T))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _lu_base_backward_error(L, U, A0[p, :]) <= 8 * sqrt(n) * eps(Float16) / 2 + end + + # An exact zero pivot is reported through info: a zero matrix at column 1, a zero column k at k. + @testset "a zero pivot is reported through info" begin + @test NextLA.lu_base!(ArrayType(zeros(TF, 4, 4)))[3] == 1 + A = rand(TF, 8, 8) + TF(8) * I + A[:, 5] .= 0 + @test NextLA.lu_base!(ArrayType(A))[3] == 5 + end + + if backend_name != "CPU" + @testset "a work-group past 32 × 32 is refused" begin + @test_throws ArgumentError NextLA.lu_base!(ArrayType(rand(TF, 33, 33) + TF(33) * I)) + end + end + end +end diff --git a/test/dense/lapack/lu/lu_pivot.jl b/test/dense/lapack/lu/lu_pivot.jl new file mode 100644 index 00000000..fc3ce64e --- /dev/null +++ b/test/dense/lapack/lu/lu_pivot.jl @@ -0,0 +1,134 @@ +# LU with pivoting on a NextLAMatrix, getrf2!, geru!, laswp (src/dense/lapack/lu/lu_pivot.jl); CPU only; Float16 through the generic path. + +test_params(m = "rows of A", n = "columns of A") # the number options it takes (--params) + +function _lu_factors(F) + m, n = size(F.factors) + L = tril(F.factors[1:m, 1:min(m, n)]) + for i in 1:min(m, n); L[i, i] = 1; end + return L, triu(F.factors[1:min(m, n), 1:n]) +end + +# Diagonally dominant in its leading min(m, n) square, so LU needs no pivoting. +function _lu_dominant(T, m, n) + A = rand(T, m, n) .- T(0.5) + k = min(m, n) + A[1:k, 1:k] += T(2 * max(m, n)) * I + return A +end + +const _LU_SHAPES = ((1, 1), (2, 2), (10, 10), (10, 9), (10, 11), (100, 100), (100, 90), (100, 110), + (257, 257), (20, 1), (1, 20)) + +cpu_wanted() && @testset "LU on a NextLAMatrix" begin + @testset "$entry, $(nameof(typeof(pivot))), $T, $m×$n, $kind" for T in test_types((Float16, TEST_TYPES...)), + (entry, pivot) in (("lu!", NoPivot()), ("lu!", RowNonZero()), ("lu!", RowMaximum()), ("lu!", CompletePivoting()), + ("lu! default", nothing), + ("generic_lufact!", NoPivot()), ("generic_lufact!", RowNonZero()), + ("generic_lufact!", RowMaximum()), ("generic_lufact!", CompletePivoting())), + (m, n) in test_cases((:m, :n), _LU_SHAPES), kind in (:matrix1, :matrix2) + pivots = !(pivot isa Union{NoPivot, RowNonZero}) + big_scale, big_cond = T === Float16 ? (10, 1e3) : (1e3, 1e6) # Float16 overflows past 65504 + A = !pivots ? (kind == :matrix1 ? _lu_dominant(T, m, n) : _lu_dominant(T, m, n) .* T(big_scale)) : + randsvd(T, m, n; cond = kind == :matrix1 ? 1e2 : big_cond, mode = kind == :matrix1 ? :geometric : :one_large) + M = NextLAMatrix{T}(copy(A)) + F = entry == "lu! default" ? LinearAlgebra.lu!(M) : + entry == "lu!" ? LinearAlgebra.lu!(M, pivot) : LinearAlgebra.generic_lufact!(M, pivot) + L, U = _lu_factors(F) + p = LinearAlgebra.ipiv2perm(F.ipiv, m) + q = hasproperty(F, :jpiv) ? LinearAlgebra.ipiv2perm(F.jpiv, n) : (1:n) + @test lu_ratio(L, U, A[p, q]; eps=Float64(eps(real(T)))) <= LAPACK_TEST_THRESHOLD + end + + @testset "empty matrices, $m×$n" for (m, n) in ((0, 0), (0, 3), (3, 0)) + F = LinearAlgebra.lu!(NextLAMatrix{Float64}(zeros(m, n)), RowMaximum()) + @test size(F.factors) == (m, n) + end + + @testset "geru!, $T, $m×$n" for T in test_types((Float16, TEST_TYPES...)), (m, n) in test_cases((:m, :n), ((0, 3), (3, 0), (1, 1), (5, 4), (40, 33))) + α = T <: Complex ? T(-0.7, 0.3) : T(-0.7) + x, y, A0 = rand(T, m) .- T(0.5), rand(T, n) .- T(0.5), rand(T, m, n) .- T(0.5) + A = copy(A0) + NextLA.geru!(α, x, y, A) + exact = big.(A0) .+ big(α) .* big.(x) .* transpose(big.(y)) + scale = abs.(big.(A0)) .+ abs(big(α)) .* abs.(big.(x)) .* transpose(abs.(big.(y))) + # two products and a sum: γ3 for real types, about 6.7u for complex + @test all(abs.(big.(A) .- exact) .<= (T <: Complex ? 8 : 4) * eps(real(T)) / 2 .* scale) + end + + @testset "geru! with α = 0 leaves A unchanged, even with NaN in x, $T" for T in test_types((Float16, TEST_TYPES...)) + A0 = rand(T, 3, 3) + A = copy(A0) + NextLA.geru!(zero(T), T[NaN, Inf, 1], rand(T, 3), A) + @test A == A0 + end + + # laswp applies ipiv[k1:k2] in order (incx = 1), reversed (-1) or not at all (0), as dlaswp. + @testset "laswp, n=$n, incx=$incx" for n in test_values(:n, (5, 40, 70)), incx in (1, -1, 0) + m = 8 + A0, ipiv = rand(m, n), [rand(k:m) for k in 1:m] + A = copy(A0) + NextLA.laswp(A, 2, 6, ipiv, incx) + ref = copy(A0) + for k in (incx > 0 ? (2:6) : incx < 0 ? (6:-1:2) : (1:0)) + ref[[k, ipiv[k]], :] = ref[[ipiv[k], k], :] + end + @test A == ref + end +end + +# getrf2! returns (A, ipiv, info) on every path, including the early exits and singular blocks. +cpu_wanted() && @testset "getrf2! returns (A, ipiv, info) on every path" begin + for T in test_types(TEST_TYPES) + # quick return (0×0) + A = zeros(T, 0, 0) + Af, ipiv, info = NextLA.getrf2!(A, Int[], 0) + @test Af === A + @test info == 0 + + # m == 1 with a zero pivot: singular, reported through info + A = zeros(T, 1, 1) + _, _, info = NextLA.getrf2!(A, Vector{Int}(undef, 1), 0) + @test info == 1 + + # n == 1, all zero: the other single-column exit + A = zeros(T, 4, 1) + _, _, info = NextLA.getrf2!(A, Vector{Int}(undef, 1), 0) + @test info == 1 + + # a singular block inside the recursion: info is the failing column, offset by the split + A = T[1 0; 0 0] + _, _, info = NextLA.getrf2!(A, Vector{Int}(undef, 2), 0) + @test info == 2 + + # and a non-singular matrix still factors, with info == 0 + A0 = T[4 1; 1 3] + A = copy(A0) + Af, ipiv, info = NextLA.getrf2!(A, Vector{Int}(undef, 2), 0) + @test info == 0 + L = UnitLowerTriangular(Af) + U = UpperTriangular(Af) + @test L * U ≈ A0[LinearAlgebra.ipiv2perm(ipiv, 2), :] + + # lu! with check=false reports the singular matrix through info + F = LinearAlgebra.lu!(NextLAMatrix{T}(T[1 0; 0 0]), RowMaximum(); check=false) + @test F.info == 2 + @test_throws LinearAlgebra.SingularException LinearAlgebra.lu!( + NextLAMatrix{T}(T[1 0; 0 0]), RowMaximum()) + end + + # getrf2! takes BLAS types only. + @test_throws MethodError NextLA.getrf2!(Float16[4 1; 1 3], Vector{Int}(undef, 2), 0) +end + +# getc2! on 0×0 and 1×1 returns its LU; a tiny 1×1 pivot is set to smlnum with info = 1. +cpu_wanted() && @testset "getc2! on 0×0 and 1×1, $T" for T in test_types((Float32, Float64)) + F = getc2!(NextLAMatrix{T}(zeros(T, 0, 0)), CompletePivoting()) + @test F isa NextLA.LU && isempty(F.ipiv) && isempty(F.jpiv) && F.info == 0 + F = getc2!(NextLAMatrix{T}(fill(T(3), 1, 1)), CompletePivoting()) + @test F.factors == fill(T(3), 1, 1) && F.ipiv == [1] && F.jpiv == [1] && F.info == 0 + tiny = fill(floatmin(T), 1, 1) # below smlnum = floatmin / eps + @test_throws LinearAlgebra.SingularException getc2!(NextLAMatrix{T}(copy(tiny)), CompletePivoting()) + F = getc2!(NextLAMatrix{T}(copy(tiny)), CompletePivoting(); allowsingular=true) + @test F.info == 1 && F.factors[1, 1] > floatmin(T) +end diff --git a/test/dense/lapack/lu/lu_tiled.jl b/test/dense/lapack/lu/lu_tiled.jl new file mode 100644 index 00000000..55587d21 --- /dev/null +++ b/test/dense/lapack/lu/lu_tiled.jl @@ -0,0 +1,66 @@ +# tile_lu_factor! (src/dense/lapack/lu/lu_tiled.jl): tiled LU with partial pivoting, GPU only. + +test_params(n = "order of A", tile = "tile size (at most 32, divides n)") # the number options it takes (--params) + +# Signed SPD (built in Float32) with rows shuffled inside each tile, and the shuffle q: the in-tile pivoting must undo it. +function _lu_tiled_shuffled(T, N, tile) + q = reduce(vcat, [(t - 1) * tile .+ randperm(tile) for t in 1:(N ÷ tile)]; init=Int[]) + d = rand((-1, 1), N) + return T.(spd(Float32, N) .* (d * d'))[q, :], q +end + +# ‖L U - PA‖ / ‖PA‖ in Float64; Float16 checks it against 8 sqrt(N) u, as lu_ratio's 30 N u is above 1 from N = 34 on. +_lu_tiled_backward_error(L, U, PA) = (A = Float64.(PA); norm(Float64.(L) * Float64.(U) - A) / norm(A)) + +# No :random for real types: tile_lu_factor! pivots only inside each tile, and randsvd input at times needs more; tile 1 pivots nothing. +_lu_tiled_kinds(T, tile) = tile == 1 ? (T <: Complex ? () : (:dominant,)) : + T <: Complex ? (:dominant, :random) : (:dominant, :shuffled) + +@testset "tile_lu_factor! [$backend_name]" for (backend_name, ArrayType, synchronize) in available_gpu_backends() + @testset "$T, N=$N, tile=$tile, $kind" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), (N, tile) in test_cases((:n, :tile), ((8, 1), (16, 4), (16, 8), (32, 8), (64, 16), (96, 32)); + valid = (N, t) -> t > 32 ? "the tile is at most 32" : N % t != 0 ? "the tile must divide n" : true), + kind in _lu_tiled_kinds(T, tile) + A0, q = kind == :shuffled ? _lu_tiled_shuffled(T, N, tile) : + kind == :dominant ? (rand(T, N, N) + T(N) * I, nothing) : (randsvd(T, N, N; cond=1e3), nothing) + Af, p, info = NextLA.tile_lu_factor!(ArrayType(copy(A0)), tile) + synchronize(Af) + A = Array(Af) + @test info == 0 + @test p isa Vector{Int} && sort(p) == 1:N + kind == :shuffled && @test p == invperm(q) + @test lu_ratio(UnitLowerTriangular(A), UpperTriangular(A), A0[p, :]; eps=Float64(eps(real(T)))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _lu_tiled_backward_error(UnitLowerTriangular(A), UpperTriangular(A), A0[p, :]) <= 8 * sqrt(N) * eps(Float16) / 2 + end + + # Big sizes: the docstring's 1024 with tile 32, and its multiples; dominant input needs no swaps (q = 1:N). + @testset "$T, N=$N, tile=$tile, $kind" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (N, tile) in test_cases((:n, :tile), ((1024, 32), (2048, 32), (4096, 32)); + valid = (N, t) -> t > 32 ? "the tile is at most 32" : N % t != 0 ? "the tile must divide n" : true), + kind in (:dominant, :shuffled) + A0, q = kind == :shuffled ? _lu_tiled_shuffled(T, N, tile) : (rand(T, N, N) + T(N) * I, collect(1:N)) + Af, p, info = NextLA.tile_lu_factor!(ArrayType(copy(A0)), tile) + synchronize(Af) + A = Array(Af) + @test info == 0 + @test p == invperm(q) + @test lu_ratio(UnitLowerTriangular(A), UpperTriangular(A), A0[p, :]; eps=Float64(eps(T))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _lu_tiled_backward_error(UnitLowerTriangular(A), UpperTriangular(A), A0[p, :]) <= 8 * sqrt(N) * eps(Float16) / 2 + end + + @testset "a zero pivot is reported through info" begin + @test NextLA.tile_lu_factor!(ArrayType(zeros(Float32, 8, 8)), 4)[3] == 1 + end + + @testset "a work-group past 32 × 32 is refused" begin + @test_throws ArgumentError NextLA.tile_lu_factor!(ArrayType(rand(Float32, 66, 66) + 66I), 33) + end + + @testset "the tile size must divide the matrix" begin + @test_throws ArgumentError NextLA.tile_lu_factor!(ArrayType(rand(Float32, 16, 16) + 16I), 5) + end +end + +# The CPU backend is refused (its path gives wrong numbers; KNOWN_ISSUES.md). +cpu_wanted() && @testset "tile_lu_factor! refuses the CPU backend" begin + @test_throws ArgumentError NextLA.tile_lu_factor!(rand(Float64, 16, 16) + 16I, 4) +end diff --git a/test/dense/lapack/lu/reclu.jl b/test/dense/lapack/lu/reclu.jl new file mode 100644 index 00000000..37ca2bf8 --- /dev/null +++ b/test/dense/lapack/lu/reclu.jl @@ -0,0 +1,149 @@ +# lu_recursive! and lu_recursive_nopiv! (src/dense/lapack/lu/reclu.jl): recursive LU without pivoting. + +test_params(m = "rows of A", n = "columns of A", block = "size where the recursion stops") # the number options it takes (--params) + +function _reclu_dominant(T, m, n) + A = rand(T, m, n) .- T(0.5) + k = min(m, n) + A[1:k, 1:k] += T(2 * max(m, n)) * I + return A +end + +# SPD with random row and column signs, cut to m×n: needs no pivoting, and its trailing update is as large as A. +function _reclu_spd(T, m, n = m) + d = rand((-1, 1), max(m, n)) + return (spd(T, max(m, n)) .* T.(d * d'))[1:m, 1:n] +end + +# Normwise backward error ‖L U - A0‖ / ‖A0‖ in Float64 (as test/setup/mxp.jl's mxp_lu_backward_error). +_reclu_backward_error(L, U, A0) = + (A = Float64.(Array(A0)); norm(Float64.(Array(L)) * Float64.(Array(U)) - A) / norm(A)) + +# Float16's bound on it, 8 sqrt(k) u (mxp_tol): lu_ratio's 30 n u passes any O(1) error in Float16 from n = 34 on. +_reclu_f16_tol(k) = 8 * sqrt(max(k, 1)) * eps(Float16) / 2 + +# The info of the ZeroPivotException that f(A, bs) throws: 0 if none, -1 for another exception. +_reclu_zero_pivot_info(f, A, bs) = try f(A, bs); 0 catch e; e isa ZeroPivotException ? e.info : -1 end + +# L unit lower trapezoidal and U upper trapezoidal, both packed in A. +function _reclu_factors(A, m, n) + k = min(m, n) + L = m >= n ? [UnitLowerTriangular(A[1:k, 1:k]); A[(k + 1):m, 1:k]] : Matrix(UnitLowerTriangular(A[1:k, 1:k])) + U = m >= n ? Matrix(UpperTriangular(A[1:k, 1:k])) : [UpperTriangular(A[1:k, 1:k]) A[1:k, (k + 1):n]] + return L, U +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "RECLU [$backend_name]" begin + TF = supports_float64(ArrayType) ? Float64 : Float32 # Float64 data, Float32 on a device without it (Metal) + + # On dominant input a missing trailing update stays below Float16's resolution; signed SPD input shows it. + @testset "lu_recursive!, $T, n=$n, block=$bs, $kind" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), + n in test_values(:n, (1, 2, 7, 32, 100, 128)), bs in test_values(:block, (1, 16, 32)), kind in (:dominant, :spd) + A0 = kind == :dominant ? _reclu_dominant(T, n, n) : _reclu_spd(T, n) + A = ArrayType(copy(A0)) + NextLA.lu_recursive!(A, bs) + synchronize(A) + F = Array(A) + L, U = UnitLowerTriangular(F), UpperTriangular(F) + @test lu_ratio(L, U, A0; eps=Float64(eps(real(T)))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _reclu_backward_error(L, U, A0) <= _reclu_f16_tol(n) + end + + # The rectangular sibling, square too; the real types also take signed SPD input cut to m×n. + @testset "lu_recursive_nopiv!, $T, $(m)×$(n), block=$bs, $kind" for T in backend_types(ArrayType, (TEST_TYPES..., Float16)), + (m, n) in test_cases((:m, :n), ((64, 64), (128, 64), (64, 128), (100, 60), (48, 200), (1, 5), (5, 1))), bs in test_values(:block, (16, 32)), + kind in (T <: Complex ? (:dominant,) : (:dominant, :spd)) + A0 = kind == :dominant ? _reclu_dominant(T, m, n) : _reclu_spd(T, m, n) + A = ArrayType(copy(A0)) + NextLA.lu_recursive_nopiv!(A, bs) + synchronize(A) + L, U = _reclu_factors(Array(A), m, n) + @test lu_ratio(L, U, A0; eps=Float64(eps(real(T)))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _reclu_backward_error(L, U, A0) <= _reclu_f16_tol(min(m, n)) + end + + # Deeper recursions: block 16 gives depth 3 at n = 128, 4 at 256, 5 at 512. + @testset "lu_recursive_nopiv!, $T, n=$n, block=$bs, $kind" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + n in test_values(:n, (128, 256, 512)), bs in test_values(:block, (16,)), kind in (:dominant, :spd) + A0 = kind == :dominant ? _reclu_dominant(T, n, n) : _reclu_spd(T, n) + A = ArrayType(copy(A0)) + NextLA.lu_recursive_nopiv!(A, bs) + synchronize(A) + L, U = _reclu_factors(Array(A), n, n) + @test lu_ratio(L, U, A0; eps=Float64(eps(T))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _reclu_backward_error(L, U, A0) <= _reclu_f16_tol(n) + end + + # The default block (2048): n = 2049 just past it, then trailing blocks of 1024 (n = 3072), 2048 (4096) and 4096 (8192). + @testset "$(nameof(f)) with the default block, $T, n=$n" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + n in test_values(:n, (2049, 3072, 4096, 8192); valid = n -> n > NextLA.LU_BLOCK_SIZE || "the default block is $(NextLA.LU_BLOCK_SIZE)"), + f in (NextLA.lu_recursive!, NextLA.lu_recursive_nopiv!) + A0 = T.(_reclu_spd(Float32, n)) # signed SPD built in Float32: a Float16 R * R' of this size is slow + A = ArrayType(copy(A0)) + @test f(A) === A + synchronize(A) + L, U = _reclu_factors(Array(A), n, n) + @test lu_ratio(L, U, A0; eps=Float64(eps(T))) <= LAPACK_TEST_THRESHOLD + T === Float16 && @test _reclu_backward_error(L, U, A0) <= _reclu_f16_tol(n) + end + + # Empty matrices come back as they are. + @testset "empty, $T, $(m)×$(n)" for T in backend_types(ArrayType, (Float16, Float32, Float64)), (m, n) in ((0, 0), (0, 5), (5, 0)) + A = ArrayType(zeros(T, m, n)) + @test NextLA.lu_recursive_nopiv!(A, 4) === A && size(A) == (m, n) + if m == n + B = ArrayType(zeros(T, 0, 0)) + @test NextLA.lu_recursive!(B) === B && size(B) == (0, 0) + end + end + + # The unpivoted LU exists, but column 1's largest entry is off the diagonal: a pivoting leaf of any type would swap. + @testset "the leaf does not pivot, $T, block=$bs" for T in backend_types(ArrayType, (Float16, Float32, Float64)), bs in (1, 2, 4) + A0 = T[1 2 3 4; 4 1 2 3; 3 4 1 2; 2 3 4 1] + A = ArrayType(copy(A0)) + @test NextLA.lu_recursive!(A, bs) === A + synchronize(A) + F = Array(A) + @test lu_ratio(UnitLowerTriangular(F), UpperTriangular(F), A0; eps=Float64(eps(T))) <= LAPACK_TEST_THRESHOLD + B = ArrayType(copy(A0)) + NextLA.lu_recursive_nopiv!(B, bs) + synchronize(B) + G = Array(B) + @test lu_ratio(UnitLowerTriangular(G), UpperTriangular(G), A0; eps=Float64(eps(T))) <= LAPACK_TEST_THRESHOLD + end + + @testset "a zero pivot throws ZeroPivotException" begin + @test_throws ZeroPivotException NextLA.lu_recursive!(ArrayType(TF[0 1; 1 0]), 2) + @test_throws ZeroPivotException NextLA.lu_recursive!(ArrayType(zeros(Float32, 16, 16)), 32) + Z = Matrix(1.0f0I, 16, 16); Z[13, 13] = 0 # a zero pivot in a nested trailing block (8 + 4 + 1): info counts in the whole matrix + @test _reclu_zero_pivot_info(NextLA.lu_recursive!, ArrayType(copy(Z)), 4) == 13 + @test _reclu_zero_pivot_info(NextLA.lu_recursive_nopiv!, ArrayType(copy(Z)), 4) == 13 + W = Matrix(1.0f0I, 20, 12); W[9, 9] = 0 # tall: the trailing block of the column split + @test _reclu_zero_pivot_info(NextLA.lu_recursive_nopiv!, ArrayType(copy(W)), 4) == 9 + end + + # A wide matrix does not overrun its rows in the split. + @testset "a wide matrix does not overrun its rows" begin + A = rand(TF, 48, 200) + A[1:48, 1:48] += TF(400) * I + @test NextLA.lu_recursive_nopiv!(ArrayType(A), 32) isa AbstractMatrix + end + + @testset "argument errors" begin + @test_throws ArgumentError NextLA.lu_recursive_nopiv!(ArrayType(rand(TF, 8, 8)), 0) + @test_throws ArgumentError NextLA.lu_recursive!(ArrayType(rand(TF, 8, 8)), 0) + @test_throws DimensionMismatch NextLA.lu_recursive!(ArrayType(rand(TF, 8, 6)), 4) + end + end +end + +# A device view whose rows are not consecutive: the leaf factors a contiguous copy, rows outside the view kept (reclu G2). +@testset "a row-strided device view [$name]" for (name, AT, sync) in filter(b -> b[1] == "CUDA", available_backends()) + A = Float32.(rand(8, 8) + 16I) + P = rand(Float32, 16, 8); P[1:2:16, :] .= A + Pd = AT(copy(P)) + NextLA.lu_recursive!(view(Pd, 1:2:16, :), 4) + R = Array(Pd) + @test R[1:2:16, :] ≈ NextLA.lu_recursive!(copy(A), 4) && R[2:2:16, :] == P[2:2:16, :] +end diff --git a/test/dense/lapack/qr/geqr2.jl b/test/dense/lapack/qr/geqr2.jl new file mode 100644 index 00000000..be7e0536 --- /dev/null +++ b/test/dense/lapack/qr/geqr2.jl @@ -0,0 +1,94 @@ +# geqr2! (src/dense/lapack/qr/geqr2.jl): unblocked Householder QR, A = QR, in one work-item kernel. + +test_params(m = "rows of A", n = "columns of A") # the number options it takes (--params) + +# LAPACK dqrt01's ratios ‖A - QR‖₁ / (m ‖A‖₁ eps) and ‖I - QᴴQ‖₁ / (m eps), Q formed exactly. +function _geqr2_ratios(F, tau, A0) + m, n = size(A0) + k = min(m, n) + W = big.(Array(F)) + Q = Matrix{eltype(W)}(I, m, m) + for i in k:-1:1 + v = [zeros(eltype(W), i - 1); one(eltype(W)); W[i+1:m, i]] + Q -= big(Array(tau)[i]) * v * (v' * Q) + end + Ab, e = big.(A0), big(eps(real(eltype(A0)))) + res = opnorm(Ab - Q[:, 1:k] * triu(W[1:k, :]), 1) / (m * max(opnorm(Ab, 1), big(floatmin(real(eltype(A0))))) * e) + return Float64(res), Float64(opnorm(Q' * Q - I, 1) / (m * e)) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "GEQR2 [$backend_name]" begin + # Tall, wide and square; uniform or Gaussian entries at three scales (Float16 norms are summed in Float32, B37). + @testset "$T, $gen, scale=$sc" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), gen in (rand, randn), + sc in (T === Float16 ? (1, 1e-4, 2e2) : (1, 1e-3, 1e2)) + for (m, n) in test_cases((:m, :n), ((1, 1), (1, 5), (5, 1), (10, 8), (8, 10), (33, 33), (100, 33), (33, 100))) + A0 = T(sc) .* gen(T, m, n) + Ad, tau = ArrayType(copy(A0)), ArrayType(zeros(T, min(m, n))) + NextLA.geqr2!(m, n, Ad, tau, ArrayType(zeros(T, n))) + synchronize(Ad) + res, orth = _geqr2_ratios(Ad, tau, A0) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + end + + # A zero column needs no reflector (τ = 0); a complex α over zeros still needs one (β real). + @testset "zero columns, $T" for T in backend_types(ArrayType, TEST_TYPES) + A0 = randn(T, 6, 4) + A0[:, 2] .= 0 + Ad, tau = ArrayType(copy(A0)), ArrayType(zeros(T, 4)) + NextLA.geqr2!(6, 4, Ad, tau, ArrayType(zeros(T, 4))) + @test Array(tau)[2] == 0 + @test maximum(_geqr2_ratios(Ad, tau, A0)) <= LAPACK_TEST_THRESHOLD + if T <: Complex + A0 = zeros(T, 4, 3); A0[1, 1] = T(3, 4); A0[2:4, 2:3] .= randn(T, 3, 2) + Ad, tau = ArrayType(copy(A0)), ArrayType(zeros(T, 3)) + NextLA.geqr2!(4, 3, Ad, tau, ArrayType(zeros(T, 3))) + @test Array(Ad)[1, 1] == -5 && Array(tau)[1] ≈ T(1.6, 0.8) + end + end + + # A a view inside a larger matrix: only the view changes. + @testset "A a view, $T" for T in backend_types(ArrayType, TEST_TYPES) + Big0 = randn(T, 12, 9) + Bd, tau = ArrayType(copy(Big0)), ArrayType(zeros(T, 4)) + NextLA.geqr2!(6, 4, view(Bd, 3:8, 2:5), tau, ArrayType(zeros(T, 4))) + B = Array(Bd) + @test maximum(_geqr2_ratios(B[3:8, 2:5], tau, Big0[3:8, 2:5])) <= LAPACK_TEST_THRESHOLD + outside = trues(12, 9); outside[3:8, 2:5] .= false + @test B[outside] == Big0[outside] + end + + @testset "the short form equals the long form" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A0 = randn(T, 20, 15) + a, b = ArrayType(copy(A0)), ArrayType(copy(A0)) + ta, tb = ArrayType(zeros(T, 15)), ArrayType(zeros(T, 15)) + NextLA.geqr2!(20, 15, a, ta, ArrayType(zeros(T, 15))) + NextLA.geqr2!(b, tb) + @test Array(a) == Array(b) && Array(ta) == Array(tb) + end + + @testset "m or n = 0 leave A; negative sizes are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A = ArrayType(ones(T, 0, 3)) + NextLA.geqr2!(0, 3, A, ArrayType(zeros(T, 0)), ArrayType(zeros(T, 3))) + @test size(A) == (0, 3) + @test_throws ArgumentError NextLA.geqr2!(-1, 5, ArrayType(zeros(T, 5, 5)), ArrayType(zeros(T, 5)), ArrayType(zeros(T, 5))) + @test_throws ArgumentError NextLA.geqr2!(5, -1, ArrayType(zeros(T, 5, 5)), ArrayType(zeros(T, 5)), ArrayType(zeros(T, 5))) + end + end +end + +# R, the reflectors and τ within 2 max(m, n) eps of LAPACK's geqrf (m > n only; m ≤ n differs: B37). +cpu_wanted() && @testset "GEQR2 against LAPACK, $T, m=$m, n=$n" for T in test_types(TEST_TYPES), (m, n) in test_cases((:m, :n), ((5, 1), (10, 8), (34, 33), (100, 33)); + valid = (m, n) -> m > n || "this comparison takes m > n (m ≤ n differs from LAPACK: B37)") + A0 = randn(T, m, n) + F, tau = copy(A0), zeros(T, n) + NextLA.geqr2!(m, n, F, tau, zeros(T, n)) + G = copy(A0) + _, tl = LAPACK.geqrf!(G) + d = max(maximum(abs.(big.(F) .- big.(G))) / maximum(abs, G), maximum(abs.(big.(tau) .- big.(tl))) / 2) + @test Float64(d) / eps(real(T)) <= 2 * max(m, n) +end diff --git a/test/dense/lapack/qr/geqrt.jl b/test/dense/lapack/qr/geqrt.jl new file mode 100644 index 00000000..7d55726f --- /dev/null +++ b/test/dense/lapack/qr/geqrt.jl @@ -0,0 +1,109 @@ +# geqrt! (src/dense/lapack/qr/geqrt.jl): blocked QR, ib columns at a time, with the T blocks. + +test_params(m = "rows of A", n = "columns of A", ib = "inner block size") # the number options it takes (--params) + +# LAPACK dqrt01's ratios ‖A - QR‖₁/(m ‖A‖₁ eps) and ‖I - QᴴQ‖₁/(m eps), Q formed from the blocks in BigFloat, +# or in Float64 (wide = Float64) for big tiles, where BigFloat is too slow. +function _geqrt_ratios(F, Tm, A0, ib; wide = big) + m, n = size(A0) + k = min(m, n) + W, Tb = wide.(Array(F)), wide.(Array(Tm)) + Q = Matrix{eltype(W)}(I, m, m) + for i in reverse(collect(1:ib:k)) + sb = min(ib, k - i + 1) + V = zeros(eltype(W), m, sb) + for j in 1:sb + V[i+j-1, j] = 1 + V[i+j:m, j] = W[i+j:m, i+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, i:i+sb-1]) * (V' * Q)) + end + Ab, e = wide.(A0), wide(eps(real(eltype(A0)))) + return Float64(opnorm(Ab - Q[:, 1:k] * triu(W[1:k, :]), 1) / (m * opnorm(Ab, 1) * e)), Float64(opnorm(Q' * Q - I, 1) / (m * e)) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "GEQRT [$backend_name]" begin + # Tall, wide, square and odd shapes, block sizes 1 to larger than the matrix. + @testset "$T, ib=$ib" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), ib in test_values(:ib, (1, 3, 8, 32, 64)) + for (m, n) in test_cases((:m, :n), ((1, 1), (5, 1), (1, 5), (20, 15), (15, 20), (33, 33), (64, 32), (32, 64), (100, 37))) + T === Float16 && backend_name != "CPU" && n > min(ib, m) && continue # more than one block reaches larfb! (B36, pinned below) + k = min(m, n) + A0 = randn(T, m, n) + Ad, Td = ArrayType(copy(A0)), ArrayType(zeros(T, ib, k)) + NextLA.geqrt!(m, n, ib, Ad, Td, ArrayType(zeros(T, k)), ArrayType(zeros(T, ib * n))) + synchronize(Ad) + res, orth = _geqrt_ratios(Ad, Td, A0, ib) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + end + + # Float16 with more than one block on a GPU: larfb! falls back to scalar indexing (B36). + backend_name == "CPU" || @testset "Float16, more than one block" begin + @test_broken (NextLA.geqrt!(20, 15, 3, ArrayType(randn(Float16, 20, 15)), ArrayType(zeros(Float16, 3, 15)), + ArrayType(zeros(Float16, 15)), ArrayType(zeros(Float16, 45))); true) + end + + # Tiles of the size tiled QR uses (nb = 256, ib = 32) and its multiples; Float16 on a GPU is skipped (B36). + @testset "tile m=$m, n=$n, ib=$ib, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (m, n, ib) in test_cases((:m, :n, :ib), ((256, 256, 32), (512, 512, 32), (1024, 1024, 32))) + T === Float16 && backend_name != "CPU" && continue + k = min(m, n) + A0 = randn(T, m, n) + Ad, Td = ArrayType(copy(A0)), ArrayType(zeros(T, ib, k)) + NextLA.geqrt!(m, n, ib, Ad, Td, ArrayType(zeros(T, k)), ArrayType(zeros(T, ib * n))) + synchronize(Ad) + res, orth = _geqrt_ratios(Ad, Td, A0, ib; wide = Float64) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + + # A a view inside a larger matrix: only the view changes. + @testset "A a view, $T" for T in backend_types(ArrayType, TEST_TYPES) + Big0 = randn(T, 12, 9) + Bd, Td = ArrayType(copy(Big0)), ArrayType(zeros(T, 2, 4)) + NextLA.geqrt!(8, 4, 2, view(Bd, 3:10, 2:5), Td, ArrayType(zeros(T, 4)), ArrayType(zeros(T, 8))) + B = Array(Bd) + @test maximum(_geqrt_ratios(B[3:10, 2:5], Td, Big0[3:10, 2:5], 2)) <= LAPACK_TEST_THRESHOLD + outside = trues(12, 9); outside[3:10, 2:5] .= false + @test B[outside] == Big0[outside] + end + + @testset "the short form equals the long form" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A0 = randn(T, 30, 20) + a, b = ArrayType(copy(A0)), ArrayType(copy(A0)) + T1, T2 = ArrayType(zeros(T, 8, 20)), ArrayType(zeros(T, 8, 20)) + NextLA.geqrt!(a, T1) + NextLA.geqrt!(30, 20, 8, b, T2, ArrayType(zeros(T, 20)), ArrayType(zeros(T, 160))) + @test Array(a) == Array(b) && Array(T1) == Array(T2) + end + + @testset "m or n = 0 leave A; bad sizes and ib are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A = ArrayType(zeros(T, 0, 3)) + NextLA.geqrt!(0, 3, 2, A, ArrayType(zeros(T, 2, 0)), ArrayType(zeros(T, 0)), ArrayType(zeros(T, 6))) + @test size(A) == (0, 3) + Z, Tz, tz, wz = ArrayType(zeros(T, 5, 5)), ArrayType(zeros(T, 2, 5)), ArrayType(zeros(T, 5)), ArrayType(zeros(T, 10)) + @test_throws ArgumentError NextLA.geqrt!(-1, 5, 2, Z, Tz, tz, wz) + @test_throws ArgumentError NextLA.geqrt!(5, -1, 2, Z, Tz, tz, wz) + @test_throws ArgumentError NextLA.geqrt!(5, 5, -1, Z, Tz, tz, wz) + @test_throws ArgumentError NextLA.geqrt!(5, 5, 0, Z, Tz, tz, wz) + end + end +end + +# A and the T blocks within 2 max(m, n) eps of LAPACK's geqrt, relative (tall shapes, ib <= min(m, n)). +cpu_wanted() && @testset "GEQRT against LAPACK, $T, m=$m, n=$n, ib=$ib" for T in test_types(TEST_TYPES), + (m, n, ib) in test_cases((:m, :n, :ib), ((20, 15, 3), (64, 32, 8), (100, 37, 32), (34, 33, 33)); + valid = (m, n, ib) -> ib > min(m, n) ? "LAPACK's geqrt needs ib ≤ min(m, n)" : + T <: Complex && m <= n ? "complex m ≤ n: the last diagonal entry is not made real as in LAPACK (B37)" : true) + A0 = randn(T, m, n) + F, Tm = copy(A0), zeros(T, ib, n) + NextLA.geqrt!(m, n, ib, F, Tm, zeros(T, n), zeros(T, ib * n)) + G, Tl = copy(A0), zeros(T, ib, n) + LAPACK.geqrt!(G, Tl) + d = max(maximum(abs.(big.(F) .- big.(G))) / maximum(abs, G), maximum(abs.(triu(big.(Tm)) .- triu(big.(Tl)))) / maximum(abs, Tl)) + @test Float64(d) / eps(real(T)) <= 2 * max(m, n) +end diff --git a/test/dense/lapack/qr/larf.jl b/test/dense/lapack/qr/larf.jl new file mode 100644 index 00000000..0adaeaa8 --- /dev/null +++ b/test/dense/lapack/qr/larf.jl @@ -0,0 +1,88 @@ +# larf! (src/dense/lapack/qr/larf.jl): C := (I - τ v vᴴ) C, or C (I - τ v vᴴ). + +test_params(m = "rows of C", n = "columns of C") # the number options it takes (--params) + +# Largest per-element |C - exact| / (gauge eps (k + 2)): the dot-product bound γ_k with a margin, exact in BigFloat. +function _larf_ratio(C, side, v, τ, C0) + Vb, Cb, t = big.(v), big.(C0), big(τ) + k = length(v) + exact = side == 'L' ? Cb .- t .* Vb * (Vb' * Cb) : Cb .- t .* (Cb * Vb) * Vb' + gauge = side == 'L' ? abs.(Cb) .+ abs(t) .* abs.(Vb) * (abs.(Vb)' * abs.(Cb)) : + abs.(Cb) .+ abs(t) .* (abs.(Cb) * abs.(Vb)) * abs.(Vb)' + err = abs.(big.(Array(C)) .- exact) + return Float64(maximum(ifelse.(iszero.(gauge), err, err ./ gauge); init=big(0)) / (big(eps(real(eltype(C0)))) * (k + 2))) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "LARF [$backend_name]" begin + # Both sides, square and rectangular, v with stride 1 and 2. + @testset "$T, side=$side, incv=$incv" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + side in test_flags(:side, ('L', 'R')), incv in (1, 2) + for (m, n) in test_cases((:m, :n), ((1, 1), (5, 4), (4, 5), (33, 20), (100, 7))) + k = side == 'L' ? m : n + vfull = randn(T, 1 + (k - 1) * incv) + τ, C0 = randn(T), randn(T, m, n) + Cd = ArrayType(copy(C0)) + NextLA.larf!(side, m, n, ArrayType(vfull), incv, τ, Cd, ArrayType(zeros(T, side == 'L' ? n : m))) + synchronize(Cd) + @test _larf_ratio(Cd, side, vfull[1:incv:end], τ, C0) <= 1 + end + end + + @testset "τ = 0 leaves C unchanged, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + C0 = randn(T, 6, 5) + Cd = ArrayType(copy(C0)) + @test NextLA.larf!('L', 6, 5, ArrayType(randn(T, 6)), 1, zero(T), Cd, ArrayType(zeros(T, 5))) === Cd # C is returned also for τ = 0 + @test Array(Cd) == C0 + end + + # C a view inside a larger matrix: only the view changes. + @testset "C a view, $T" for T in backend_types(ArrayType, TEST_TYPES) + Big0 = randn(T, 7, 6) + v, τ = randn(T, 4), randn(T) + Bd = ArrayType(copy(Big0)) + NextLA.larf!('L', 4, 3, ArrayType(v), 1, τ, view(Bd, 2:5, 3:5), ArrayType(zeros(T, 3))) + B = Array(Bd) + @test _larf_ratio(B[2:5, 3:5], 'L', v, τ, Big0[2:5, 3:5]) <= 1 + outside = trues(7, 6); outside[2:5, 3:5] .= false + @test B[outside] == Big0[outside] + end + + @testset "m = 0" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + @test (NextLA.larf!('L', 0, 3, ArrayType(zeros(T, 0)), 1, T(0.5), ArrayType(zeros(T, 0, 3)), ArrayType(zeros(T, 3))); true) + end + + @testset "the short form equals the long form, side=$side" for side in test_flags(:side, ('L', 'R')) + T = supports_float64(ArrayType) ? Float64 : Float32 + C0 = randn(T, 10, 8) + v, τ = randn(T, side == 'L' ? 10 : 8), randn(T) + C1, C2 = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.larf!(side, 10, 8, ArrayType(v), 1, τ, C1, ArrayType(zeros(T, side == 'L' ? 8 : 10))) + NextLA.larf!(side, ArrayType(v), 1, τ, C2) + @test Array(C1) == Array(C2) + end + + @testset "the short form checks its arguments" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + @test_throws ArgumentError NextLA.larf!('X', ArrayType(randn(T, 3)), 1, T(0.5), ArrayType(randn(T, 3, 2))) + @test_throws ArgumentError NextLA.larf!('L', ArrayType(randn(T, 4)), 1, T(0.5), ArrayType(randn(T, 3, 2))) + @test_throws ArgumentError NextLA.larf!('R', ArrayType(randn(T, 3)), 1, T(0.5), ArrayType(randn(T, 3, 2))) + end + + @testset "lowercase flags give the same result; the long form refuses a bad side" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + C0 = randn(T, 10, 8) + for side in test_flags(:side, ('L', 'R')) + v, τ, w = ArrayType(randn(T, side == 'L' ? 10 : 8)), randn(T), ArrayType(zeros(T, side == 'L' ? 8 : 10)) + a, b, c, d = (ArrayType(copy(C0)) for _ in 1:4) + NextLA.larf!(side, 10, 8, v, 1, τ, a, w) + NextLA.larf!(lowercase(side), 10, 8, v, 1, τ, b, w) + NextLA.larf!(side, v, 1, τ, c) + NextLA.larf!(lowercase(side), v, 1, τ, d) + @test Array(b) == Array(a) && Array(d) == Array(c) + end + @test_throws "Invalid side parameter" NextLA.larf!('X', 10, 8, ArrayType(randn(T, 10)), 1, T(0.5), ArrayType(copy(C0)), ArrayType(zeros(T, 8))) + end + end +end diff --git a/test/dense/lapack/qr/larfb.jl b/test/dense/lapack/qr/larfb.jl new file mode 100644 index 00000000..f20591ab --- /dev/null +++ b/test/dense/lapack/qr/larfb.jl @@ -0,0 +1,115 @@ +# larfb! (src/dense/lapack/qr/larfb.jl): C := H C, Hᴴ C, C H or C Hᴴ with H = I - V T Vᴴ (forward, columnwise). + +test_params(m = "rows of C", n = "columns of C") # the number options it takes (--params) + +# Returns V (p×k, junk above and on the unit diagonal), W (V as larfb! reads it), Tu = larft's T, Tj = Tu with junk below. +function _larfb_inputs(T, p, k) + V = 3 .* randn(T, p, k) + W = tril(V, -1) + Matrix{T}(I, p, k) + tau = T[2 / real(sum(abs2, W[:, j])) for j in 1:k] + Tm = zeros(T, k, k) + NextLA.larft!('F', 'C', p, k, W, tau, Tm) + return V, W, triu(Tm), triu(Tm) + tril(3 .* randn(T, k, k), -1) +end + +# dqrt03-style ratio ‖C - op(H) C0‖₁ / (max(m, n) ‖C0‖₁ eps), op(H) built exactly in BigFloat. +function _larfb_ratio(C, side, trans, W, Tu, C0) + Wb, Cb = big.(W), big.(C0) + H = I - Wb * big.(Tu) * Wb' + Ht = trans == 'N' ? H : H' + exact = side == 'L' ? Ht * Cb : Cb * Ht + return Float64(opnorm(big.(Array(C)) - exact, 1) / (max(size(C0)...) * opnorm(Cb, 1) * big(eps(real(eltype(C0)))))) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "LARFB [$backend_name]" begin + # Both sides and trans, square and rectangular, k = 1, 4 and the whole panel. + @testset "$T, side=$side, trans=$trans" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + if T === Float16 && backend_name != "CPU" + # Float16 on a GPU: no device triangular multiply, so scalar indexing (B36). + V, W, Tu, Tj = _larfb_inputs(T, 5, 3) + @test_broken (NextLA.larfb!(side, trans, 'F', 'C', ArrayType(V), ArrayType(Tj), ArrayType(randn(T, 5, 5))); true) + continue + end + for (m, n) in test_cases((:m, :n), ((1, 1), (5, 4), (4, 5), (33, 20), (20, 33), (64, 64))) + p = side == 'L' ? m : n + for k in unique((1, min(4, p), p)) + V, W, Tu, Tj = _larfb_inputs(T, p, k) + C0 = randn(T, m, n) + Cd = ArrayType(copy(C0)) + NextLA.larfb!(side, trans, 'F', 'C', ArrayType(V), ArrayType(Tj), Cd) + synchronize(Cd) + @test _larfb_ratio(Cd, side, trans, W, Tu, C0) <= LAPACK_TEST_THRESHOLD + end + end + end + + @testset "trans = 'T' is 'C' for real $T" for T in backend_types(ArrayType, (Float32, Float64)) + V, _, _, Tj = _larfb_inputs(T, 8, 3) + C0 = randn(T, 8, 5) + a, b = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.larfb!('L', 'T', 'F', 'C', ArrayType(V), ArrayType(Tj), a) + NextLA.larfb!('L', 'C', 'F', 'C', ArrayType(V), ArrayType(Tj), b) + @test Array(a) == Array(b) + end + + # C and V views of larger matrices: only C's view changes. + @testset "views, $T" for T in backend_types(ArrayType, TEST_TYPES) + V, W, Tu, Tj = _larfb_inputs(T, 8, 3) + Big0 = randn(T, 12, 9) + Bd = ArrayType(copy(Big0)) + Vb = ArrayType(zeros(T, 10, 5)); Vb[2:9, 2:4] .= ArrayType(V) + NextLA.larfb!('L', 'C', 'F', 'C', view(Vb, 2:9, 2:4), ArrayType(Tj), view(Bd, 3:10, 2:6)) + synchronize(Bd) + B = Array(Bd) + @test _larfb_ratio(B[3:10, 2:6], 'L', 'C', W, Tu, Big0[3:10, 2:6]) <= LAPACK_TEST_THRESHOLD + outside = trues(12, 9); outside[3:10, 2:6] .= false + @test B[outside] == Big0[outside] + end + + @testset "the short form equals the long form, side=$side" for side in test_flags(:side, ('L', 'R')) + T = supports_float64(ArrayType) ? Float64 : Float32 + V, _, _, Tj = _larfb_inputs(T, 10, 3) + C0 = side == 'L' ? randn(T, 10, 8) : randn(T, 8, 10) + a, b = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.larfb!(side, 'N', 'F', 'C', size(C0)..., 3, ArrayType(V), 10, ArrayType(Tj), a, ArrayType(zeros(T, 8, 3))) + NextLA.larfb!(side, 'N', 'F', 'C', ArrayType(V), ArrayType(Tj), b) + @test Array(a) == Array(b) + end + + @testset "m, n or k = 0 leave C" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + C0 = randn(T, 5, 5) + Cd = ArrayType(copy(C0)) + NextLA.larfb!('L', 'N', 'F', 'C', 5, 5, 0, ArrayType(zeros(T, 5, 0)), 5, ArrayType(zeros(T, 0, 0)), Cd, ArrayType(zeros(T, 5, 0))) + NextLA.larfb!('L', 'N', 'F', 'C', 0, 5, 2, ArrayType(zeros(T, 0, 2)), 1, ArrayType(zeros(T, 2, 2)), ArrayType(zeros(T, 0, 5)), ArrayType(zeros(T, 5, 2))) + @test Array(Cd) == C0 + end + + @testset "backward or rowwise reflectors and bad flags are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + V, C = ArrayType(randn(T, 5, 3)), ArrayType(randn(T, 5, 4)) + Tm = ArrayType(randn(T, 3, 3)) + for (d, s) in (('B', 'C'), ('F', 'R'), ('B', 'R')) + @test_throws ArgumentError NextLA.larfb!('L', 'N', d, s, V, Tm, C) + end + @test_throws ArgumentError NextLA.larfb!('X', 'N', 'F', 'C', V, Tm, C) + @test_throws ArgumentError NextLA.larfb!('L', 'X', 'F', 'C', V, Tm, C) + end + + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + V, _, _, Tj = ArrayType.(_larfb_inputs(T, 10, 3)) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C', 'T')) + C0 = side == 'L' ? randn(T, 10, 8) : randn(T, 8, 10) + a, b, c, d = (ArrayType(copy(C0)) for _ in 1:4) + NextLA.larfb!(side, trans, 'F', 'C', size(C0)..., 3, V, 10, Tj, a, ArrayType(zeros(T, 8, 3))) + NextLA.larfb!(lowercase(side), lowercase(trans), 'f', 'c', size(C0)..., 3, V, 10, Tj, b, ArrayType(zeros(T, 8, 3))) + NextLA.larfb!(side, trans, 'F', 'C', V, Tj, c) + NextLA.larfb!(lowercase(side), lowercase(trans), 'f', 'c', V, Tj, d) + @test Array(b) == Array(a) && Array(d) == Array(c) + end + end + end +end diff --git a/test/dense/lapack/qr/larfg.jl b/test/dense/lapack/qr/larfg.jl new file mode 100644 index 00000000..aa3b41b4 --- /dev/null +++ b/test/dense/lapack/qr/larfg.jl @@ -0,0 +1,79 @@ +# larfg! (src/dense/lapack/qr/larfg.jl): the Householder reflector H with Hᴴ [α; x] = [β; 0], β real. + +test_params(n = "length of x") # the number options it takes (--params) + +# dqrt01-style ratio ‖Hᴴ y - [β; 0]‖ / (n ‖y‖ eps), and τ within zlarfg's range. +function _larfg_check(α, x0, β, τ, v) + y, w, t = big.(vcat(α, x0)), big.(vcat(one(eltype(v)), Array(v))), big(τ) + r = y .- conj(t) .* w .* (w' * y) + r[1] -= big(β) + e = big(eps(real(typeof(α)))) + ratio = Float64(norm(r) / (length(y) * max(norm(y), big(floatmin(real(typeof(α))))) * e)) + in_range = iszero(t) || (1 - 4e <= real(t) <= 2 + 4e && abs(t - 1) <= 1 + 4e) + return ratio, in_range && imag(big(β)) == 0 +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "LARFG [$backend_name]" begin + # Every type at three scales (Float16 squares are summed in Float32, B33). + @testset "$T, n=$n, scale=$sc" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), n in test_values(:n, (2, 3, 7, 33, 100)), + sc in (T === Float16 ? (1, 1e-4, 2e2) : (1, 1e-3, 1e2)) + α, x0 = T(sc) * randn(T), T(sc) .* randn(T, n - 1) + x = ArrayType(copy(x0)) + β, τ = NextLA.larfg!(n, α, x, 1, zero(T)) + synchronize(x) + ratio, ok = _larfg_check(α, x0, β, τ, x) + @test ratio <= LAPACK_TEST_THRESHOLD + @test ok + end + + # x = 0: no reflection for real α; a complex α still needs one (τ ≠ 0, β = -|α|). + @testset "x = 0, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + @test NextLA.larfg!(3, T(5), ArrayType(zeros(T, 2)), 1, zero(T)) == (T(5), zero(T)) + if T <: Complex + β, τ = NextLA.larfg!(3, T(3, 4), ArrayType(zeros(T, 2)), 1, zero(T)) + @test β == -5 && τ ≈ T(1.6, 0.8) + end + end + + @testset "n = 1 and n = 0 leave α and x, τ = 0, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + x = ArrayType(T[3, 4]) + @test NextLA.larfg!(1, T(2), x, 1, zero(T)) == (T(2), zero(T)) + @test NextLA.larfg!(0, T(2), x, 1, zero(T)) == (T(2), zero(T)) + @test Array(x) == T[3, 4] + end + + # x a column or a row of a matrix: the view holds v, the rest is unchanged. + @testset "x a view, $T" for T in backend_types(ArrayType, TEST_TYPES) + X0 = randn(T, 6, 4) + Xd = ArrayType(copy(X0)) + β, τ = NextLA.larfg!(6, X0[1, 2], view(Xd, 2:6, 2), 1, zero(T)) + X = Array(Xd) + @test _larfg_check(X0[1, 2], X0[2:6, 2], β, τ, X[2:6, 2])[1] <= LAPACK_TEST_THRESHOLD + @test X[:, [1, 3, 4]] == X0[:, [1, 3, 4]] && X[1, 2] == X0[1, 2] + Xd = ArrayType(copy(X0)) + β, τ = NextLA.larfg!(4, X0[3, 4], view(Xd, 3, 1:3), 1, zero(T)) + X = Array(Xd) + @test _larfg_check(X0[3, 4], X0[3, 1:3], β, τ, X[3, 1:3])[1] <= LAPACK_TEST_THRESHOLD + @test X[[1, 2, 4, 5, 6], :] == X0[[1, 2, 4, 5, 6], :] && X[3, 4] == X0[3, 4] + end + + @testset "the short form equals the n form, $T" for T in backend_types(ArrayType, TEST_TYPES) + α, x0 = randn(T), randn(T, 5) + a, b = ArrayType(copy(x0)), ArrayType(copy(x0)) + @test NextLA.larfg!(α, a, 1, zero(T)) == NextLA.larfg!(6, α, b, 1, zero(T)) + @test Array(a) == Array(b) + end + end +end + +# β, τ and v within 8 eps of LAPACK's ?larfg, relative. +cpu_wanted() && @testset "LARFG against LAPACK, $T, n=$n" for T in test_types(TEST_TYPES), n in test_values(:n, (2, 7, 33)) + α, x0 = randn(T), randn(T, n - 1) + x = copy(x0) + β, τ = NextLA.larfg!(n, α, x, 1, zero(T)) + y = vcat([α], x0) + τr, βr = lapack_larfg!(y) + got, want = big.([β; τ; x]), big.([βr; τr; y[2:end]]) + @test Float64(maximum(abs.(got .- want) ./ max.(abs.(want), 1))) / eps(real(T)) <= 8 +end diff --git a/test/dense/lapack/qr/larft.jl b/test/dense/lapack/qr/larft.jl new file mode 100644 index 00000000..49e6dfbb --- /dev/null +++ b/test/dense/lapack/qr/larft.jl @@ -0,0 +1,130 @@ +# larft! (src/dense/lapack/qr/larft.jl): the triangular T with H = I - V T Vᴴ for k reflectors. + +test_params(n = "length of the reflectors", k = "number of reflectors") # the number options it takes (--params) + +# V as LAPACK reads it: the unit entry and the zeros of each reflector imposed, whatever V holds there. +function _larft_structured(direct, storev, V, n, k) + W = copy(V) + for i in 1:k + p, zr = direct == 'F' ? (i, 1:i-1) : (n - k + i, n-k+i+1:n) + storev == 'C' ? (W[p, i] = 1; W[zr, i] .= 0) : (W[i, p] = 1; W[i, zr] .= 0) + end + return W +end + +# dqrt01-style ratio of I - V T Vᴴ against the product of the k reflectors, in BigFloat. +function _larft_ratio(direct, storev, W, tau, Tm, n, k) + Wb, Tb = big.(W), big.(direct == 'F' ? triu(Tm) : tril(Tm)) + H = Matrix{eltype(Wb)}(I, n, n) + for j in 1:k + v = storev == 'C' ? Wb[:, j] : conj(Wb[j, :]) + Hj = I - big(tau[j]) * v * v' + H = direct == 'F' ? H * Hj : Hj * H + end + Hc = storev == 'C' ? I - Wb * Tb * Wb' : I - Wb' * Tb * Wb + return Float64(opnorm(Hc - H, 1) / (n * opnorm(H, 1) * big(eps(real(eltype(W)))))) +end + +# k reflectors of length n: a given --n, --k pair needs 1 ≤ k ≤ n. +_larft_valid(n, k) = 1 <= k <= n || "needs 1 ≤ k ≤ n" + +# V with junk outside the reflectors (LAPACK does not read it), W as read, and Householder τ = 2/‖v‖². +function _larft_inputs(T, direct, storev, n, k) + V = 3 .* randn(T, storev == 'C' ? (n, k) : (k, n)) + W = _larft_structured(direct, storev, V, n, k) + tau = T[2 / real(sum(abs2, storev == 'C' ? W[:, j] : W[j, :])) for j in 1:k] + return V, W, tau +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "LARFT [$backend_name]" begin + # H = I - V T Vᴴ is the product of the reflectors; the unused triangle of T is left alone. + @testset "$T, direct=$direct, storev=$storev" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + (direct, storev) in (('F', 'C'), ('F', 'R'), ('B', 'R')) + for (n, k) in test_cases((:n, :k), ((1, 1), (5, 3), (10, 4), (20, 8), (33, 33), (40, 7)); valid = _larft_valid) + V, W, tau = _larft_inputs(T, direct, storev, n, k) + Td = ArrayType(fill(T(7), k, k)) + NextLA.larft!(direct, storev, n, k, ArrayType(V), ArrayType(tau), Td) + synchronize(Td) + Tm = Array(Td) + unused = direct == 'F' ? (X -> tril(X, -1)) : (X -> triu(X, 1)) # the triangle T does not use + @test _larft_ratio(direct, storev, W, tau, Tm, n, k) <= LAPACK_TEST_THRESHOLD + @test unused(Tm) == unused(fill(T(7), k, k)) + end + end + + # Backward and columnwise is wrong (B35). + @testset "$T, direct=B, storev=C" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + for (n, k) in test_cases((:n, :k), ((10, 4), (40, 7)); valid = _larft_valid) + V, W, tau = _larft_inputs(T, 'B', 'C', n, k) + Td = ArrayType(zeros(T, k, k)) + NextLA.larft!('B', 'C', n, k, ArrayType(V), ArrayType(tau), Td) + @test_broken _larft_ratio('B', 'C', W, tau, Array(Td), n, k) <= LAPACK_TEST_THRESHOLD + end + end + + # τ = 0 makes its column of T zero; n = 0 leaves T alone. + @testset "τ = 0 and n = 0" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + Td = ArrayType(fill(T(7), 3, 3)) + NextLA.larft!('F', 'C', 5, 3, ArrayType(randn(T, 5, 3)), ArrayType(T[0.5, 0.0, 0.7]), Td) + @test Array(Td)[1:2, 2] == [0, 0] + Td = ArrayType(ones(T, 2, 2)) + NextLA.larft!('F', 'C', 0, 2, ArrayType(zeros(T, 0, 2)), ArrayType(zeros(T, 2)), Td) + @test Array(Td) == ones(T, 2, 2) + end + + # V a view of a larger matrix. + @testset "V a view" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + Big0 = randn(T, 12, 6) + W = _larft_structured('F', 'C', Big0[3:10, 2:4], 8, 3) + tau = T[2 / sum(abs2, W[:, j]) for j in 1:3] + Td = ArrayType(zeros(T, 3, 3)) + NextLA.larft!('F', 'C', 8, 3, view(ArrayType(Big0), 3:10, 2:4), ArrayType(tau), Td) + @test _larft_ratio('F', 'C', W, tau, Array(Td), 8, 3) <= LAPACK_TEST_THRESHOLD + end + + @testset "the short form equals the long form, storev=$storev" for storev in ('C', 'R') + T = supports_float64(ArrayType) ? Float64 : Float32 + V, _, tau = _larft_inputs(T, 'F', storev, 10, 4) + T1, T2 = ArrayType(zeros(T, 4, 4)), ArrayType(zeros(T, 4, 4)) + NextLA.larft!('F', storev, 10, 4, ArrayType(V), ArrayType(tau), T1) + NextLA.larft!('F', storev, ArrayType(V), ArrayType(tau), T2) + @test Array(T1) == Array(T2) + @test_throws ArgumentError NextLA.larft!('F', storev, ArrayType(V), ArrayType(tau[1:3]), T2) + end + + @testset "lowercase flags give the same result; bad direct or storev is refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + for (direct, storev) in (('F', 'C'), ('F', 'R'), ('B', 'R')) + V, _, tau = ArrayType.(_larft_inputs(T, direct, storev, 10, 4)) + a, b, c, d = (ArrayType(zeros(T, 4, 4)) for _ in 1:4) + NextLA.larft!(direct, storev, 10, 4, V, tau, a) + NextLA.larft!(lowercase(direct), lowercase(storev), 10, 4, V, tau, b) + NextLA.larft!(direct, storev, V, tau, c) + NextLA.larft!(lowercase(direct), lowercase(storev), V, tau, d) + @test Array(b) == Array(a) && Array(d) == Array(c) + end + V, _, tau = ArrayType.(_larft_inputs(T, 'F', 'C', 10, 4)) + Td = ArrayType(zeros(T, 4, 4)) + @test_throws "direct must be" NextLA.larft!('X', 'C', 10, 4, V, tau, Td) + @test_throws "storev must be" NextLA.larft!('F', 'X', 10, 4, V, tau, Td) + @test_throws "direct must be" NextLA.larft!('X', 'C', V, tau, Td) + @test_throws "storev must be" NextLA.larft!('F', 'X', V, tau, Td) + end + end +end + +# T within 8 eps of LAPACK's ?larft (relative to its largest entry). +cpu_wanted() && @testset "LARFT against LAPACK, $T, direct=$direct, storev=$storev" for T in test_types(TEST_TYPES), + (direct, storev) in (('F', 'C'), ('F', 'R'), ('B', 'R')) + for (n, k) in test_cases((:n, :k), ((5, 3), (20, 8), (40, 7)); valid = _larft_valid) + V, _, tau = _larft_inputs(T, direct, storev, n, k) + Tm = zeros(T, k, k) + NextLA.larft!(direct, storev, n, k, V, tau, Tm) + keep = direct == 'F' ? triu : tril + Tl = lapack_larft(direct, storev, n, k, V, tau) + @test maximum(abs.(keep(Tm) .- keep(Tl))) / (maximum(abs, Tl) * eps(real(T))) <= 8 + end +end diff --git a/test/dense/lapack/qr/pamm.jl b/test/dense/lapack/qr/pamm.jl new file mode 100644 index 00000000..4c09a7fb --- /dev/null +++ b/test/dense/lapack/qr/pamm.jl @@ -0,0 +1,76 @@ +# pamm! (src/dense/lapack/qr/pamm.jl): W = A1 + op(V) A2 or A2 = A2 - op(V) W, the products inside parfb!. + +test_params(m = "rows of A2", n = "columns of A1 and A2", k = "number of reflectors") # the number options it takes (--params) + +# op(V) and the side it multiplies on, per PLASMA core_zpamm: Vᴴ or V by side and storage, for 'W'; the other for 'A'. +_pamm_opV(op, side, storev, V) = ((side == 'L') == (storev == 'C')) == (op == 'W') ? V' : V + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "PAMM [$backend_name]" begin + # Every op, side, storage and direction (l = 0; the pentagonal l > 0 is checked through parfb!). + @testset "$T, op=$op, $side$storev$direct" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), op in ('W', 'A'), + side in test_flags(:side, ('L', 'R')), storev in ('C', 'R'), direct in ('F', 'B') + T === Float16 && backend_name != "CPU" && VERSION >= v"1.11" && continue # B40, pinned below + for (k, m, n) in test_cases((:k, :m, :n), ((1, 1, 1), (4, 7, 5), (8, 20, 13))) + V = randn(T, storev == 'C' ? (m, k) : (k, m)) + A1, A2, W0 = side == 'L' ? (randn(T, k, n), randn(T, m, n), randn(T, k, n)) : (randn(T, n, k), randn(T, n, m), randn(T, n, k)) + a1, a2, w = ArrayType(copy(A1)), ArrayType(copy(A2)), ArrayType(copy(W0)) + NextLA.pamm!(op, side, storev, direct, size(A2)..., k, 0, a1, a2, ArrayType(V), w) + synchronize(w) + P = big.(_pamm_opV(op, side, storev, V)) + B, X, Y = op == 'W' ? (big.(A1), P, big.(A2)) : (big.(A2), P, big.(W0)) + exact = op == 'W' ? (side == 'L' ? B + X * Y : B + Y * X) : (side == 'L' ? B - X * Y : B - Y * X) + gauge = abs.(B) .+ (side == 'L' ? abs.(X) * abs.(Y) : abs.(Y) * abs.(X)) + got = big.(Array(op == 'W' ? w : a2)) + @test Float64(maximum(abs.(got .- exact) ./ gauge)) / eps(real(T)) <= k + 2 + end + end + + # Float16 on a GPU from Julia 1.11 falls back to scalar indexing (B40; 1.10 works). + (backend_name == "CPU" || VERSION < v"1.11") || @testset "Float16" begin + ok = try + for op in ('W', 'A'), side in test_flags(:side, ('L', 'R')), storev in ('C', 'R') + V = ArrayType(randn(Float16, storev == 'C' ? (7, 4) : (4, 7))) + A1, A2, W = side == 'L' ? (randn(Float16, 4, 5), randn(Float16, 7, 5), randn(Float16, 4, 5)) : + (randn(Float16, 5, 4), randn(Float16, 5, 7), randn(Float16, 5, 4)) + NextLA.pamm!(op, side, storev, 'F', size(A2)..., 4, 0, ArrayType(A1), ArrayType(A2), V, ArrayType(W)) + end + true + catch + false + end + @test_broken ok + end + + @testset "m, n or k = 0 leave W" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A1, A2, V = ArrayType(rand(T, 5, 5)), ArrayType(rand(T, 10, 5)), ArrayType(rand(T, 10, 5)) + W0 = rand(T, 5, 5) + for (m, n, k) in ((0, 5, 5), (10, 0, 5), (10, 5, 0)) + W = ArrayType(copy(W0)) + NextLA.pamm!('W', 'L', 'C', 'F', m, n, k, 3, A1, A2, V, W) + @test Array(W) == W0 + end + end + + @testset "bad flags and negative sizes are refused" begin + Z = ArrayType(zeros(supports_float64(ArrayType) ? Float64 : Float32, 4, 4)) + for args in (('X', 'L', 'C', 'F', 4, 4, 4, 0), ('W', 'X', 'C', 'F', 4, 4, 4, 0), ('W', 'L', 'X', 'F', 4, 4, 4, 0), + ('W', 'L', 'C', 'X', 4, 4, 4, 0), ('W', 'L', 'C', 'F', -1, 4, 4, 0), ('W', 'L', 'C', 'F', 4, 4, 4, -1)) + @test_throws ArgumentError NextLA.pamm!(args..., Z, Z, Z, Z) + end + end + + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + for op in ('W', 'A'), side in test_flags(:side, ('L', 'R')), storev in ('C', 'R'), direct in ('F', 'B') + V = ArrayType(randn(T, storev == 'C' ? (7, 4) : (4, 7))) + A1, A2, W0 = side == 'L' ? (randn(T, 4, 5), randn(T, 7, 5), randn(T, 4, 5)) : (randn(T, 5, 4), randn(T, 5, 7), randn(T, 5, 4)) + (a1, b1), (a2, b2), (w, x) = ((ArrayType(copy(A)) for _ in 1:2) for A in (A1, A2, W0)) + NextLA.pamm!(op, side, storev, direct, size(A2)..., 4, 0, a1, a2, V, w) + NextLA.pamm!(lowercase.((op, side, storev, direct))..., size(A2)..., 4, 0, b1, b2, V, x) + @test Array(x) == Array(w) && Array(b2) == Array(a2) + end + end + end +end diff --git a/test/dense/lapack/qr/parfb.jl b/test/dense/lapack/qr/parfb.jl new file mode 100644 index 00000000..e5cfd3a6 --- /dev/null +++ b/test/dense/lapack/qr/parfb.jl @@ -0,0 +1,98 @@ +# parfb! (src/dense/lapack/qr/parfb.jl): apply a pentagonal block reflector to [A1; A2] or [A1 A2] (LAPACK tprfb). + +test_params(m = "rows of A2", n = "columns of A1 and A2", k = "number of reflectors") # the number options it takes (--params) + +# The exact result for side 'L', direct 'F', storev 'R', used instead of LAPACK's tprfb, which is wrong there for l > 0. +function _parfb_exact_lfr(trans, k, m, l, V, Tm, A1, A2) + Vm = copy(V) + for a in 1:k, b in 1:l + b > a && (Vm[a, m-l+b] = 0) # the last l columns of V are lower trapezoidal + end + Vf = big.([Matrix{eltype(V)}(I, k, k) Vm]) + H = I - Vf' * big.(Tm) * Vf + return (trans == 'N' ? H : H') * big.([A1; A2]) +end + +# Largest |got - ref| relative to the largest |ref|, in eps of T. +_parfb_err(got, ref, T) = Float64(maximum(abs.(big.(got) .- big.(ref))) / maximum(abs.(big.(ref)))) / eps(real(T)) + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "PARFB [$backend_name]" begin + # Every side, trans, direction and storage, against LAPACK tprfb (Float16: tprfb in Float32). + @testset "$T, $side$trans$direct$storev" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')), direct in ('F', 'B'), storev in ('C', 'R') + T === Float16 && backend_name != "CPU" && continue # B40, pinned below + R = T === Float16 ? Float32 : T + for (k, m, n, l) in test_cases((:k, :m, :n, nothing), ((3, 5, 4, 0), (4, 6, 5, 2), (4, 6, 5, 4), (8, 20, 24, 4), (8, 20, 24, 8)); + valid = (k, m, n, l) -> l <= min(k, m) || "needs l = $l ≤ min(k, m)") + V = randn(T, storev == 'C' ? (m, k) : (k, m)) + Tm = (direct == 'F' ? triu : tril)(randn(T, k, k)) + A1, A2 = side == 'L' ? (randn(T, k, n), randn(T, m, n)) : (randn(T, n, k), randn(T, n, m)) + a1, a2 = ArrayType(copy(A1)), ArrayType(copy(A2)) + NextLA.parfb!(side, trans, direct, storev, size(A1)..., size(A2)..., k, l, a1, a2, ArrayType(V), ArrayType(Tm), + ArrayType(zeros(T, side == 'L' ? (k, n) : (n, k)))) + synchronize(a1) + if side == 'L' && direct == 'F' && storev == 'R' && l > 0 + ref = _parfb_exact_lfr(trans, k, m, l, V, Tm, A1, A2) + got = [Array(a1); Array(a2)] + else + L1, L2 = R.(A1), R.(A2) + lapack_tprfb!(R, side, (R <: Real && trans == 'C') ? 'T' : trans, direct, storev, l, R.(V), R.(Tm), L1, L2) + ref, got = [vec(L1); vec(L2)], [vec(Array(a1)); vec(Array(a2))] + end + @test _parfb_err(got, ref, T) <= 4 * (k + m) + end + end + + # Float16 on a GPU: the triangular multiply falls back to scalar indexing (B40). + backend_name == "CPU" || @testset "Float16" begin + ok = try + NextLA.parfb!('L', 'N', 'F', 'C', 4, 5, 6, 5, 4, 2, ArrayType(randn(Float16, 4, 5)), ArrayType(randn(Float16, 6, 5)), + ArrayType(randn(Float16, 6, 4)), ArrayType(triu(randn(Float16, 4, 4))), ArrayType(zeros(Float16, 4, 5))) + true + catch + false + end + @test_broken ok + end + + # No rows in A2 (side 'L') leaves A1 whatever work holds, as LAPACK tprfb (C19); a quick return, so Float16 runs on a GPU too. + @testset "m2 = 0 leaves A1, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + A1, Tm = randn(T, 4, 5), ArrayType(triu(randn(T, 4, 4))) + a1, b1 = ArrayType(copy(A1)), ArrayType(copy(A1)) + NextLA.parfb!('L', 'N', 'F', 'C', 4, 5, 0, 5, 4, 0, a1, ArrayType(zeros(T, 0, 5)), ArrayType(zeros(T, 0, 4)), Tm, ArrayType(fill(T(NaN), 4, 5))) + NextLA.parfb!('L', 'N', 'F', 'C', b1, ArrayType(zeros(T, 0, 5)), ArrayType(zeros(T, 0, 4)), Tm) + @test Array(a1) == A1 && Array(b1) == A1 + end + + @testset "k = 0 leaves A1 and A2; bad flags are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A1, A2 = randn(T, 4, 4), randn(T, 4, 4) + a1, a2 = ArrayType(copy(A1)), ArrayType(copy(A2)) + NextLA.parfb!('L', 'N', 'F', 'C', 4, 4, 4, 4, 0, 0, a1, a2, ArrayType(zeros(T, 4, 0)), ArrayType(zeros(T, 0, 0)), ArrayType(zeros(T, 0, 4))) + @test Array(a1) == A1 && Array(a2) == A2 + Z, V, Tm, W = ArrayType(zeros(T, 4, 4)), ArrayType(zeros(T, 4, 2)), ArrayType(zeros(T, 2, 2)), ArrayType(zeros(T, 2, 4)) + for flags in (('X', 'N', 'F', 'C'), ('L', 'X', 'F', 'C'), ('L', 'N', 'X', 'C'), ('L', 'N', 'F', 'X')) + @test_throws ArgumentError NextLA.parfb!(flags..., 4, 4, 4, 4, 2, 0, Z, Z, V, Tm, W) + end + end + + # Long form over every flag; the short form (l = size(V, 2)) once. + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')), direct in ('F', 'B'), storev in ('C', 'R') + V, Tm = ArrayType(randn(T, storev == 'C' ? (6, 4) : (4, 6))), ArrayType((direct == 'F' ? triu : tril)(randn(T, 4, 4))) + A1, A2 = side == 'L' ? (randn(T, 4, 5), randn(T, 6, 5)) : (randn(T, 5, 4), randn(T, 5, 6)) + (a1, b1), (a2, b2) = ((ArrayType(copy(A)) for _ in 1:2) for A in (A1, A2)) + NextLA.parfb!(side, trans, direct, storev, size(A1)..., size(A2)..., 4, 2, a1, a2, V, Tm, ArrayType(zeros(T, size(A1)))) + NextLA.parfb!(lowercase.((side, trans, direct, storev))..., size(A1)..., size(A2)..., 4, 2, b1, b2, V, Tm, ArrayType(zeros(T, size(A1)))) + @test Array(b1) == Array(a1) && Array(b2) == Array(a2) + end + A1, A2, V, Tm = randn(T, 4, 5), randn(T, 6, 5), ArrayType(randn(T, 6, 4)), ArrayType(triu(randn(T, 4, 4))) + (a1, b1), (a2, b2) = ((ArrayType(copy(A)) for _ in 1:2) for A in (A1, A2)) + NextLA.parfb!('L', 'N', 'F', 'C', a1, a2, V, Tm) + NextLA.parfb!('l', 'n', 'f', 'c', b1, b2, V, Tm) + @test Array(b1) == Array(a1) && Array(b2) == Array(a2) + end + end +end diff --git a/test/dense/lapack/qr/pemv.jl b/test/dense/lapack/qr/pemv.jl new file mode 100644 index 00000000..c4835c18 --- /dev/null +++ b/test/dense/lapack/qr/pemv.jl @@ -0,0 +1,85 @@ +# pemv! (src/dense/lapack/qr/pemv.jl): y = α op(A) x + β y with A pentagonal (PLASMA core_zpemv). + +test_params(m = "rows of A", n = "columns of A") # the number options it takes (--params) + +# A as pemv! reads it: columnwise, the last l rows upper triangular; rowwise, the last l columns lower triangular. +_pemv_pentagon(A, storev, m, n, l) = storev == 'C' ? [A[1:m-l, :]; triu(A[m-l+1:m, :])] : [A[:, 1:n-l] tril(A[:, n-l+1:n])] + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "PEMV [$backend_name]" begin + # Columnwise with (conjugate) transpose and rowwise without, l from 0 to min(m, n); per element within γ. + @testset "$T, storev=$storev" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), storev in ('C', 'R') + T === Float16 && backend_name != "CPU" && continue # B40, pinned below + trans = storev == 'R' ? 'N' : (T <: Complex ? 'C' : 'T') + for (m, n, l) in test_cases((:m, :n, nothing), ((1, 1, 1), (7, 5, 0), (7, 5, 1), (7, 5, 3), (7, 5, 5), (5, 7, 5), (9, 9, 9), (33, 20, 7)); + valid = (m, n, l) -> l <= min(m, n) || "needs l = $l ≤ min(m, n)") + A, α, β = randn(T, m, n), T(1.5), T(-0.5) + x, y = randn(T, storev == 'C' ? m : n), randn(T, storev == 'C' ? n : m) + yd = ArrayType(copy(y)) + NextLA.pemv!(trans, storev, m, n, l, α, ArrayType(A), ArrayType(copy(x)), β, yd, ArrayType(zeros(T, max(m, n)))) + synchronize(yd) + P = big.(_pemv_pentagon(A, storev, m, n, l)) + opP = storev == 'R' ? P : (trans == 'C' ? P' : transpose(P)) + exact = big(α) .* (opP * big.(x)) .+ big(β) .* big.(y) + gauge = abs(big(α)) .* (abs.(opP) * abs.(big.(x))) .+ abs(big(β)) .* abs.(big.(y)) + @test Float64(maximum(abs.(big.(Array(yd)) .- exact) ./ gauge)) / eps(real(T)) <= max(m, n) + 2 + end + end + + # Float16 on a GPU falls back to scalar indexing (B40). + backend_name == "CPU" || @testset "Float16" begin + ok = try + for (trans, storev) in (('T', 'C'), ('N', 'R')) + NextLA.pemv!(trans, storev, 7, 5, 3, Float16(1.5), ArrayType(randn(Float16, 7, 5)), ArrayType(randn(Float16, storev == 'C' ? 7 : 5)), + Float16(0.5), ArrayType(randn(Float16, storev == 'C' ? 5 : 7)), ArrayType(zeros(Float16, 7))) + end + true + catch + false + end + @test_broken ok + end + + @testset "α = 0 gives β y" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + y = ArrayType(T[1, 2, 3, 4]) + NextLA.pemv!('C', 'C', 5, 4, 2, zero(T), ArrayType(randn(T, 5, 4)), ArrayType(randn(T, 5)), T(2), y, ArrayType(zeros(T, 5))) + @test Array(y) == [2, 4, 6, 8] + end + + # The short form uses l = min(m, n). + @testset "the short form equals the long form, storev=$storev" for storev in ('C', 'R') + T = supports_float64(ArrayType) ? ComplexF64 : ComplexF32 + trans, (m, n, l) = storev == 'C' ? 'C' : 'N', (9, 7, 7) + A, x0 = randn(T, m, n), randn(T, storev == 'C' ? m : n) + y0 = randn(T, storev == 'C' ? n : m) + a, b = ArrayType(copy(y0)), ArrayType(copy(y0)) + NextLA.pemv!(trans, storev, m, n, l, T(1.5), ArrayType(A), ArrayType(copy(x0)), T(0.5), a, ArrayType(zeros(T, max(m, n)))) + NextLA.pemv!(trans, storev, T(1.5), ArrayType(A), ArrayType(copy(x0)), T(0.5), b) + @test Array(a) == Array(b) + end + + @testset "bad flags and l are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A, x, y, w = ArrayType(randn(T, 5, 4)), ArrayType(randn(T, 5)), ArrayType(zeros(T, 4)), ArrayType(zeros(T, 5)) + for (trans, storev) in (('X', 'C'), ('C', 'X'), ('N', 'C'), ('C', 'R')) + @test_throws ArgumentError NextLA.pemv!(trans, storev, 5, 4, 2, one(T), A, x, zero(T), y, w) + end + @test_throws ArgumentError NextLA.pemv!('C', 'C', 5, 4, 5, one(T), A, x, zero(T), y, w) + end + + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A = ArrayType(randn(T, 7, 5)) + for (trans, storev) in (('T', 'C'), ('C', 'C'), ('N', 'R')) + x, y0 = ArrayType(randn(T, storev == 'C' ? 7 : 5)), randn(T, storev == 'C' ? 5 : 7) + a, b, c, d = (ArrayType(copy(y0)) for _ in 1:4) + NextLA.pemv!(trans, storev, 7, 5, 3, T(1.5), A, x, T(0.5), a, ArrayType(zeros(T, 7))) + NextLA.pemv!(lowercase(trans), lowercase(storev), 7, 5, 3, T(1.5), A, x, T(0.5), b, ArrayType(zeros(T, 7))) + NextLA.pemv!(trans, storev, T(1.5), A, x, T(0.5), c) + NextLA.pemv!(lowercase(trans), lowercase(storev), T(1.5), A, x, T(0.5), d) + @test Array(b) == Array(a) && Array(d) == Array(c) + end + end + end +end diff --git a/test/dense/lapack/qr/tsmqr.jl b/test/dense/lapack/qr/tsmqr.jl new file mode 100644 index 00000000..204d94b2 --- /dev/null +++ b/test/dense/lapack/qr/tsmqr.jl @@ -0,0 +1,152 @@ +# tsmqr! (src/dense/lapack/qr/tsmqr.jl): apply Q from tsqrt! to [C1; C2] or [C1 C2] (LAPACK tpmqrt, l = 0). + +test_params(m = "rows of A2", n = "order of the triangle A1", ib = "inner block size") # the number options it takes (--params) + +# tpqr_q (test/setup/accuracy.jl) in Float64, for big tiles where BigFloat is too slow (LAPACK's own ratios are in working precision). +function _tpqr_q64(V2, Tm, n, m, ib) + Vb, Tb = Float64.(Array(V2)), Float64.(Array(Tm)) + Q = Matrix{Float64}(I, n + m, n + m) + for ii in reverse(collect(1:ib:n)) + sb = min(ib, n - ii + 1) + V = zeros(n + m, sb) + for j in 1:sb + V[ii+j-1, j] = 1 + V[n+1:n+m, j] = Vb[:, ii+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, ii:ii+sb-1]) * (V' * Q)) + end + return Q +end + +# A tsqrt! factor (V2, T) of [A1; A2], A1 n×n, A2 m×n, and its Q formed exactly (tpqr_q) or in Float64. +function _tsmqr_factor(T, n, m, ib; wide = big) + A1, A2 = triu(randn(T, n, n)) + T(2) * I, randn(T, m, n) + Tm = zeros(T, ib, n) + NextLA.tsqrt!(m, n, ib, A1, A2, Tm, zeros(T, n), zeros(T, ib * n)) + return A2, Tm, wide === big ? tpqr_q(A2, Tm, n, m, ib) : _tpqr_q64(A2, Tm, n, m, ib) +end + +# dqrt03-style ratio ‖C - op(Q) C0‖₁ / ((n + m) ‖C0‖₁ eps) of the stacked [C1; C2] or [C1 C2]. +function _tsmqr_ratio(c1, c2, side, trans, Q, C1, C2; wide = big) + Qt = trans == 'N' ? Q : Q' + C0 = side == 'L' ? wide.([C1; C2]) : wide.([C1 C2]) + got = side == 'L' ? wide.([Array(c1); Array(c2)]) : wide.([Array(c1) Array(c2)]) + exact = side == 'L' ? Qt * C0 : C0 * Qt + return Float64(opnorm(got - exact, 1) / (size(Q, 1) * opnorm(C0, 1) * wide(eps(real(eltype(C1)))))) +end + +# Applies op(Q) of order n + m to C1 (n rows or columns) and C2 (m), with q the other dimension. +function _tsmqr_apply!(side, trans, n, m, q, ib, c1, c2, V2, Tm, AT) + T = eltype(c1) + side == 'L' ? NextLA.tsmqr!('L', trans, n, q, m, q, n, ib, c1, c2, AT(V2), AT(Tm), AT(zeros(T, ib * q))) : + NextLA.tsmqr!('R', trans, q, n, q, m, n, ib, c1, c2, AT(V2), AT(Tm), AT(zeros(T, ib * q))) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "TSMQR [$backend_name]" begin + # Both sides and trans, Q from a real factorization, several shapes and block sizes. + @testset "$T, side=$side, trans=$trans" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + T === Float16 && backend_name != "CPU" && continue # B40, pinned below + for (n, m, ib) in test_cases((:n, :m, :ib), ((1, 1, 1), (5, 1, 2), (7, 5, 3), (24, 20, 8), (16, 16, 4), (5, 12, 8))) + V2, Tm, Q = _tsmqr_factor(T, n, m, ib) + q = 9 + C1, C2 = side == 'L' ? (randn(T, n, q), randn(T, m, q)) : (randn(T, q, n), randn(T, q, m)) + c1, c2 = ArrayType(copy(C1)), ArrayType(copy(C2)) + _tsmqr_apply!(side, trans, n, m, q, ib, c1, c2, V2, Tm, ArrayType) + synchronize(c1) + @test _tsmqr_ratio(c1, c2, side, trans, Q, C1, C2) <= LAPACK_TEST_THRESHOLD + end + end + + # Float16 on a GPU: parfb! falls back to scalar indexing for some or all shapes (B40). + backend_name == "CPU" || @testset "Float16" begin + ok = try + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')), (n, m, ib) in ((1, 1, 1), (5, 1, 2), (7, 5, 3), (24, 20, 8), (16, 16, 4), (5, 12, 8)) + V2, Tm, _ = _tsmqr_factor(Float16, n, m, ib) + C1, C2 = side == 'L' ? (randn(Float16, n, 9), randn(Float16, m, 9)) : (randn(Float16, 9, n), randn(Float16, 9, m)) + _tsmqr_apply!(side, trans, n, m, 9, ib, ArrayType(C1), ArrayType(C2), V2, Tm, ArrayType) + end + true + catch + false + end + @test_broken ok + end + + # Square tiles of the size tiled QR uses (nb = 256, ib = 32) and its multiples, Q in Float64; Float16 on a GPU is skipped (B40). + @testset "tiles n=$n, m=$m, ib=$ib, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (n, m, ib) in test_cases((:n, :m, :ib), ((256, 256, 32), (512, 512, 32), (1024, 1024, 32))) + T === Float16 && backend_name != "CPU" && continue + V2, Tm, Q = _tsmqr_factor(T, n, m, ib; wide = Float64) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + C1, C2 = side == 'L' ? (randn(T, n, n), randn(T, m, n)) : (randn(T, n, n), randn(T, n, m)) + c1, c2 = ArrayType(copy(C1)), ArrayType(copy(C2)) + _tsmqr_apply!(side, trans, n, m, n, ib, c1, c2, V2, Tm, ArrayType) + synchronize(c1) + @test _tsmqr_ratio(c1, c2, side, trans, Q, C1, C2; wide = Float64) <= LAPACK_TEST_THRESHOLD + end + end + + @testset "real trans = 'T' is 'C', $T" for T in backend_types(ArrayType, (Float32, Float64)) + V2, Tm, _ = _tsmqr_factor(T, 7, 5, 3) + C1, C2 = randn(T, 7, 9), randn(T, 5, 9) + a1, a2, b1, b2 = ArrayType(copy(C1)), ArrayType(copy(C2)), ArrayType(copy(C1)), ArrayType(copy(C2)) + _tsmqr_apply!('L', 'T', 7, 5, 9, 3, a1, a2, V2, Tm, ArrayType) + _tsmqr_apply!('L', 'C', 7, 5, 9, 3, b1, b2, V2, Tm, ArrayType) + @test Array(a1) == Array(b1) && Array(a2) == Array(b2) + end + + @testset "the short form equals the long form, side=$side" for side in test_flags(:side, ('L', 'R')) + T = supports_float64(ArrayType) ? Float64 : Float32 + V2, Tm, _ = _tsmqr_factor(T, 7, 5, 3) + C1, C2 = side == 'L' ? (randn(T, 7, 9), randn(T, 5, 9)) : (randn(T, 9, 7), randn(T, 9, 5)) + a1, a2, b1, b2 = ArrayType(copy(C1)), ArrayType(copy(C2)), ArrayType(copy(C1)), ArrayType(copy(C2)) + NextLA.tsmqr!(side, 'C', a1, a2, ArrayType(V2), ArrayType(Tm)) + _tsmqr_apply!(side, 'C', 7, 5, 9, 3, b1, b2, V2, Tm, ArrayType) + @test Array(a1) == Array(b1) && Array(a2) == Array(b2) + end + + @testset "k = 0 leaves C; bad side or trans is refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + C1, C2 = randn(T, 8, 8), randn(T, 8, 8) + a1, a2 = ArrayType(copy(C1)), ArrayType(copy(C2)) + NextLA.tsmqr!('L', 'N', 8, 8, 8, 8, 0, 0, a1, a2, ArrayType(zeros(T, 8, 0)), ArrayType(zeros(T, 0, 0)), ArrayType(zeros(T, 0))) + @test Array(a1) == C1 && Array(a2) == C2 + Z = ArrayType(zeros(T, 8, 8)) + @test_throws ArgumentError NextLA.tsmqr!('X', 'N', 8, 8, 8, 8, 4, 2, Z, Z, ArrayType(zeros(T, 8, 4)), ArrayType(zeros(T, 2, 4)), ArrayType(zeros(T, 16))) + @test_throws ArgumentError NextLA.tsmqr!('L', 'X', 8, 8, 8, 8, 4, 2, Z, Z, ArrayType(zeros(T, 8, 4)), ArrayType(zeros(T, 2, 4)), ArrayType(zeros(T, 16))) + end + + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + V2, Tm, _ = _tsmqr_factor(T, 7, 5, 3) + Vd, Td = ArrayType(V2), ArrayType(Tm) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C', 'T')) + C1, C2 = side == 'L' ? (randn(T, 7, 9), randn(T, 5, 9)) : (randn(T, 9, 7), randn(T, 9, 5)) + (a1, b1, c1, d1), (a2, b2, c2, d2) = ((ArrayType(copy(C)) for _ in 1:4) for C in (C1, C2)) + dims = side == 'L' ? (7, 9, 5, 9) : (9, 7, 9, 5) + NextLA.tsmqr!(side, trans, dims..., 7, 3, a1, a2, Vd, Td, ArrayType(zeros(T, 27))) + NextLA.tsmqr!(lowercase(side), lowercase(trans), dims..., 7, 3, b1, b2, Vd, Td, ArrayType(zeros(T, 27))) + NextLA.tsmqr!(side, trans, c1, c2, Vd, Td) + NextLA.tsmqr!(lowercase(side), lowercase(trans), d1, d2, Vd, Td) + @test Array(b1) == Array(a1) && Array(b2) == Array(a2) + @test Array(d1) == Array(c1) && Array(d2) == Array(c2) + end + end + end +end + +# The same C1, C2 as LAPACK's tpmqrt (l = 0), within 2(n + m) eps relative. +cpu_wanted() && @testset "TSMQR against LAPACK, $T, side=$side, trans=$trans" for T in test_types(TEST_TYPES), side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + for (n, m, ib) in test_cases((:n, :m, :ib), ((7, 5, 3), (24, 20, 8), (16, 16, 4)); valid = (n, m, ib) -> ib <= n || "LAPACK's tpmqrt needs ib ≤ n") + V2, Tm, _ = _tsmqr_factor(T, n, m, ib) + C1, C2 = side == 'L' ? (randn(T, n, 9), randn(T, m, 9)) : (randn(T, 9, n), randn(T, 9, m)) + c1, c2, L1, L2 = copy(C1), copy(C2), copy(C1), copy(C2) + _tsmqr_apply!(side, trans, n, m, 9, ib, c1, c2, V2, Tm, Array) + lapack_tpmqrt!(T, side, (T <: Real && trans == 'C') ? 'T' : trans, 0, V2, Tm, L1, L2) + L = side == 'L' ? [L1; L2] : [L1 L2] + got = side == 'L' ? [c1; c2] : [c1 c2] + @test maximum(abs.(big.(got) .- big.(L))) / (maximum(abs, L) * eps(real(T))) <= 2 * (n + m) + end +end diff --git a/test/dense/lapack/qr/tsqrt.jl b/test/dense/lapack/qr/tsqrt.jl new file mode 100644 index 00000000..3498b638 --- /dev/null +++ b/test/dense/lapack/qr/tsqrt.jl @@ -0,0 +1,115 @@ +# tsqrt! (src/dense/lapack/qr/tsqrt.jl): QR of [A1; A2], A1 n×n upper triangular, A2 m×n (LAPACK tpqrt, l = 0). + +test_params(m = "rows of A2", n = "columns of A1 and A2", ib = "inner block size") # the number options it takes (--params) + +# tpqr_q (test/setup/accuracy.jl) in Float64, for big tiles where BigFloat is too slow (LAPACK's own ratios are in working precision). +function _tpqr_q64(V2, Tm, n, m, ib) + Vb, Tb = Float64.(Array(V2)), Float64.(Array(Tm)) + Q = Matrix{Float64}(I, n + m, n + m) + for ii in reverse(collect(1:ib:n)) + sb = min(ib, n - ii + 1) + V = zeros(n + m, sb) + for j in 1:sb + V[ii+j-1, j] = 1 + V[n+1:n+m, j] = Vb[:, ii+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, ii:ii+sb-1]) * (V' * Q)) + end + return Q +end + +# LAPACK dqrt01's ratios of [A1; A2] = Q R, Q from (A2, T) exactly (tpqr_q, test/setup/accuracy.jl), or in Float64 (wide = Float64). +function _tsqrt_ratios(R, V2, Tm, A0, n, m, ib; wide = big) + Q = wide === big ? tpqr_q(V2, Tm, n, m, ib) : _tpqr_q64(V2, Tm, n, m, ib) + e = wide(eps(real(eltype(A0)))) + res = opnorm(wide.(A0) - Q[:, 1:n] * wide.(triu(Array(R))), 1) / ((n + m) * opnorm(wide.(A0), 1) * e) + return Float64(res), Float64(opnorm(Q' * Q - I, 1) / ((n + m) * e)) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "TSQRT [$backend_name]" begin + # Tall, wide and small shapes, block sizes 1 to larger than n; Float16 also far from 1 (squares summed in Float32, B37). + @testset "$T, ib=$ib, scale=$sc" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), ib in test_values(:ib, (1, 3, 8, 40)), + sc in (T === Float16 ? (1, 1e-4, 2e2) : (1,)) + T === Float16 && backend_name != "CPU" && VERSION >= v"1.11" && continue # B40, pinned below + for (m, n) in test_cases((:m, :n), ((1, 1), (5, 1), (1, 5), (20, 7), (7, 20), (48, 33))) + A1, A2 = T(sc) .* (triu(randn(T, n, n)) + T(2) * I), T(sc) .* randn(T, m, n) + a1, a2, Td = ArrayType(copy(A1)), ArrayType(copy(A2)), ArrayType(zeros(T, ib, n)) + NextLA.tsqrt!(m, n, ib, a1, a2, Td, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + synchronize(a1) + res, orth = _tsqrt_ratios(a1, a2, Td, [A1; A2], n, m, ib) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + end + + # Float16 on a GPU from Julia 1.11 falls back to scalar indexing (B40; 1.10 works). + (backend_name == "CPU" || VERSION < v"1.11") || @testset "Float16" begin + @test_broken (NextLA.tsqrt!(4, 5, 2, ArrayType(triu(randn(Float16, 5, 5)) + 2I), ArrayType(randn(Float16, 4, 5)), + ArrayType(zeros(Float16, 2, 5)), ArrayType(zeros(Float16, 5)), ArrayType(zeros(Float16, 10))); true) + end + + # Square tiles of the size tiled QR uses (nb = 256, ib = 32) and its multiples; Float16 on a GPU is skipped (B40). + @testset "tiles m=$m, n=$n, ib=$ib, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (m, n, ib) in test_cases((:m, :n, :ib), ((256, 256, 32), (512, 512, 32), (1024, 1024, 32))) + T === Float16 && backend_name != "CPU" && continue + A1, A2 = triu(randn(T, n, n)) + T(2) * I, randn(T, m, n) + a1, a2, Td = ArrayType(copy(A1)), ArrayType(copy(A2)), ArrayType(zeros(T, ib, n)) + NextLA.tsqrt!(m, n, ib, a1, a2, Td, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + synchronize(a1) + res, orth = _tsqrt_ratios(a1, a2, Td, [A1; A2], n, m, ib; wide = Float64) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + + # A tall A1 (m1 > n): the top n rows give the square result, the zero rows below stay zero. + @testset "tall A1, $T" for T in backend_types(ArrayType, TEST_TYPES) + n, m, m1, ib = 8, 6, 12, 3 + A1, A2 = triu(randn(T, n, n)) + T(2) * I, randn(T, m, n) + tall, sq = ArrayType([A1; zeros(T, m1 - n, n)]), ArrayType(copy(A1)) + a2t, a2s = ArrayType(copy(A2)), ArrayType(copy(A2)) + Tt, Ts = ArrayType(zeros(T, ib, n)), ArrayType(zeros(T, ib, n)) + NextLA.tsqrt!(m, n, ib, tall, a2t, Tt, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + NextLA.tsqrt!(m, n, ib, sq, a2s, Ts, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + @test Array(tall)[1:n, :] == Array(sq) && iszero(Array(tall)[n+1:m1, :]) + @test Array(a2t) == Array(a2s) && Array(Tt) == Array(Ts) + end + + @testset "the short form equals the long form" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A1, A2 = triu(randn(T, 24, 24)) + 2I, randn(T, 32, 24) + a, b = ArrayType(copy(A1)), ArrayType(copy(A1)) + a2, b2 = ArrayType(copy(A2)), ArrayType(copy(A2)) + Ta, Tb = ArrayType(zeros(T, 8, 24)), ArrayType(zeros(T, 8, 24)) + NextLA.tsqrt!(a, a2, Ta) + NextLA.tsqrt!(32, 24, 8, b, b2, Tb, ArrayType(zeros(T, 24)), ArrayType(zeros(T, 192))) + @test Array(a) == Array(b) && Array(a2) == Array(b2) && Array(Ta) == Array(Tb) + end + + @testset "m, n or ib = 0 leave A; negative sizes are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A1, A2 = ArrayType(triu(ones(T, 4, 4))), ArrayType(ones(T, 3, 4)) + for (m, n, ib) in ((0, 4, 2), (3, 0, 2), (3, 4, 0)) + NextLA.tsqrt!(m, n, ib, A1, A2, ArrayType(zeros(T, 2, 4)), ArrayType(zeros(T, 4)), ArrayType(zeros(T, 8))) + end + @test Array(A1) == triu(ones(T, 4, 4)) && Array(A2) == ones(T, 3, 4) + Z = ArrayType(zeros(T, 8, 8)) + for (m, n, ib) in ((-1, 8, 4), (8, -1, 4), (8, 8, -1)) + @test_throws ArgumentError NextLA.tsqrt!(m, n, ib, Z, Z, ArrayType(zeros(T, 4, 8)), ArrayType(zeros(T, 8)), ArrayType(zeros(T, 32))) + end + end + end +end + +# R, V and T within 2(n + m) eps of LAPACK's tpqrt with l = 0, relative. +cpu_wanted() && @testset "TSQRT against LAPACK, $T, m=$m, n=$n, ib=$ib" for T in test_types(TEST_TYPES), (m, n, ib) in test_cases((:m, :n, :ib), ((20, 7, 3), (7, 20, 8), (48, 33, 8)); + valid = (m, n, ib) -> ib <= n || "LAPACK's tpqrt needs ib ≤ n") + A1, A2 = triu(randn(T, n, n)) + T(2) * I, randn(T, m, n) + a1, a2, Tn = copy(A1), copy(A2), zeros(T, ib, n) + NextLA.tsqrt!(m, n, ib, a1, a2, Tn, zeros(T, n), zeros(T, ib * n)) + L1, L2, Tl = copy(A1), copy(A2), zeros(T, ib, n) + lapack_tpqrt!(T, m, n, 0, ib, L1, n, L2, m, Tl, ib, zeros(T, ib * n)) + d = max(maximum(abs.(big.(triu(a1)) .- big.(triu(L1)))) / maximum(abs, L1), maximum(abs.(big.(a2) .- big.(L2))) / maximum(abs, L2), + maximum(abs.(triu(big.(Tn)) .- triu(big.(Tl)))) / maximum(abs, Tl)) + @test Float64(d) / eps(real(T)) <= 2 * (n + m) +end diff --git a/test/dense/lapack/qr/ttmqr.jl b/test/dense/lapack/qr/ttmqr.jl new file mode 100644 index 00000000..4c740edb --- /dev/null +++ b/test/dense/lapack/qr/ttmqr.jl @@ -0,0 +1,163 @@ +# ttmqr! (src/dense/lapack/qr/ttmqr.jl): apply Q from ttqrt! to [C1; C2] or [C1 C2] (LAPACK tpmqrt, l = n). + +test_params(m = "rows of A2", n = "order of the triangle A1", ib = "inner block size") # the number options it takes (--params) + +# tpqr_q (test/setup/accuracy.jl) in Float64, for big tiles where BigFloat is too slow (LAPACK's own ratios are in working precision). +function _tpqr_q64(V2, Tm, n, m, ib) + Vb, Tb = Float64.(Array(V2)), Float64.(Array(Tm)) + Q = Matrix{Float64}(I, n + m, n + m) + for ii in reverse(collect(1:ib:n)) + sb = min(ib, n - ii + 1) + V = zeros(n + m, sb) + for j in 1:sb + V[ii+j-1, j] = 1 + V[n+1:n+m, j] = Vb[:, ii+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, ii:ii+sb-1]) * (V' * Q)) + end + return Q +end + +# A ttqrt! factor (V2, T) of [A1; A2], A2 m×n upper triangular, and its Q formed exactly (tpqr_q) or in Float64. +function _ttmqr_factor(T, n, m, ib; wide = big) + A1, A2 = triu(randn(T, n, n)) + T(2) * I, triu(randn(T, m, n)) + Tm = zeros(T, ib, n) + NextLA.ttqrt!(m, n, ib, A1, A2, Tm, zeros(T, n), zeros(T, ib * n)) + return A2, Tm, wide === big ? tpqr_q(triu(A2), Tm, n, m, ib) : _tpqr_q64(triu(A2), Tm, n, m, ib) +end + +# dqrt03-style ratio ‖C - op(Q) C0‖₁ / ((n + m) ‖C0‖₁ eps) of the stacked [C1; C2] or [C1 C2]. +function _ttmqr_ratio(c1, c2, side, trans, Q, C1, C2; wide = big) + Qt = trans == 'N' ? Q : Q' + C0 = side == 'L' ? wide.([C1; C2]) : wide.([C1 C2]) + got = side == 'L' ? wide.([Array(c1); Array(c2)]) : wide.([Array(c1) Array(c2)]) + exact = side == 'L' ? Qt * C0 : C0 * Qt + return Float64(opnorm(got - exact, 1) / (size(Q, 1) * opnorm(C0, 1) * wide(eps(real(eltype(C1)))))) +end + +# Applies op(Q) of order n + m to C1 (n rows or columns) and C2 (m), with q the other dimension. +function _ttmqr_apply!(side, trans, n, m, q, ib, c1, c2, V2, Tm, AT) + T = eltype(c1) + side == 'L' ? NextLA.ttmqr!('L', trans, n, q, m, q, n, ib, c1, c2, AT(V2), AT(Tm), AT(zeros(T, ib * q))) : + NextLA.ttmqr!('R', trans, q, n, q, m, n, ib, c1, c2, AT(V2), AT(Tm), AT(zeros(T, ib * q))) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "TTMQR [$backend_name]" begin + # Both sides and trans, Q from a real factorization, several shapes and block sizes. + @testset "$T, side=$side, trans=$trans" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + T === Float16 && backend_name != "CPU" && continue # B40, pinned below + for (n, m, ib) in test_cases((:n, :m, :ib), ((1, 1, 1), (5, 5, 2), (7, 7, 3), (7, 9, 3), (24, 24, 8), (16, 16, 4), (5, 5, 8))) + V2, Tm, Q = _ttmqr_factor(T, n, m, ib) + q = 9 + C1, C2 = side == 'L' ? (randn(T, n, q), randn(T, m, q)) : (randn(T, q, n), randn(T, q, m)) + c1, c2 = ArrayType(copy(C1)), ArrayType(copy(C2)) + _ttmqr_apply!(side, trans, n, m, q, ib, c1, c2, V2, Tm, ArrayType) + synchronize(c1) + @test _ttmqr_ratio(c1, c2, side, trans, Q, C1, C2) <= LAPACK_TEST_THRESHOLD + end + end + + # Float16 on a GPU: parfb! falls back to scalar indexing (B40). + backend_name == "CPU" || @testset "Float16" begin + V2, Tm, _ = _ttmqr_factor(Float16, 7, 7, 3) + @test_broken (_ttmqr_apply!('L', 'N', 7, 7, 9, 3, ArrayType(randn(Float16, 7, 9)), ArrayType(randn(Float16, 7, 9)), V2, Tm, ArrayType); true) + end + + # Square tiles of the size tiled QR uses (nb = 256, ib = 32) and its multiples, Q in Float64; Float16 on a GPU is skipped (B40). + @testset "tiles n=$n, m=$m, ib=$ib, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (n, m, ib) in test_cases((:n, :m, :ib), ((256, 256, 32), (512, 512, 32), (1024, 1024, 32)); + valid = (n, m, ib) -> m >= n || "m < n is factored only partly (B39)") + T === Float16 && backend_name != "CPU" && continue + V2, Tm, Q = _ttmqr_factor(T, n, m, ib; wide = Float64) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + C1, C2 = side == 'L' ? (randn(T, n, n), randn(T, m, n)) : (randn(T, n, n), randn(T, n, m)) + c1, c2 = ArrayType(copy(C1)), ArrayType(copy(C2)) + _ttmqr_apply!(side, trans, n, m, n, ib, c1, c2, V2, Tm, ArrayType) + synchronize(c1) + @test _ttmqr_ratio(c1, c2, side, trans, Q, C1, C2; wide = Float64) <= LAPACK_TEST_THRESHOLD + end + end + + # Only V2's upper triangle is read: junk below it changes nothing (C21; the last block's l was one short). + @testset "junk below V2's diagonal, $T, n=$n, m=$m, ib=$ib" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + (n, m, ib) in test_cases((:n, :m, :ib), ((7, 9, 3), (8, 8, 3), (7, 7, 4), (24, 24, 8), (256, 256, 32), (512, 512, 32))) # 8,8,3 and 7,7,4: a last partial block + T === Float16 && backend_name != "CPU" && continue # B40 + n > 24 && !(T <: Union{Float32, Float64}) && continue # big tiles in the real types, as the tile tests + A1, V2, Tm = triu(randn(T, n, n)) + T(2) * I, triu(randn(T, m, n)), zeros(T, ib, n) + NextLA.ttqrt!(m, n, ib, A1, V2, Tm, zeros(T, n), zeros(T, ib * n)) + Vj = triu(V2) + tril(randn(T, m, n), -1) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + C1, C2 = side == 'L' ? (randn(T, n, 9), randn(T, m, 9)) : (randn(T, 9, n), randn(T, 9, m)) + (a1, b1), (a2, b2) = ((ArrayType(copy(C)) for _ in 1:2) for C in (C1, C2)) + _ttmqr_apply!(side, trans, n, m, 9, ib, a1, a2, triu(V2), Tm, ArrayType) + _ttmqr_apply!(side, trans, n, m, 9, ib, b1, b2, Vj, Tm, ArrayType) + synchronize(b1) + @test Array(b1) == Array(a1) && Array(b2) == Array(a2) + end + end + + @testset "real trans = 'T' is 'C', $T" for T in backend_types(ArrayType, (Float32, Float64)) + V2, Tm, _ = _ttmqr_factor(T, 7, 7, 3) + C1, C2 = randn(T, 7, 9), randn(T, 7, 9) + a1, a2, b1, b2 = ArrayType(copy(C1)), ArrayType(copy(C2)), ArrayType(copy(C1)), ArrayType(copy(C2)) + _ttmqr_apply!('L', 'T', 7, 7, 9, 3, a1, a2, V2, Tm, ArrayType) + _ttmqr_apply!('L', 'C', 7, 7, 9, 3, b1, b2, V2, Tm, ArrayType) + @test Array(a1) == Array(b1) && Array(a2) == Array(b2) + end + + @testset "the short form equals the long form, side=$side" for side in test_flags(:side, ('L', 'R')) + T = supports_float64(ArrayType) ? Float64 : Float32 + V2, Tm, _ = _ttmqr_factor(T, 7, 7, 3) + C1, C2 = side == 'L' ? (randn(T, 7, 9), randn(T, 7, 9)) : (randn(T, 9, 7), randn(T, 9, 7)) + a1, a2, b1, b2 = ArrayType(copy(C1)), ArrayType(copy(C2)), ArrayType(copy(C1)), ArrayType(copy(C2)) + NextLA.ttmqr!(side, 'C', a1, a2, ArrayType(V2), ArrayType(Tm)) + _ttmqr_apply!(side, 'C', 7, 7, 9, 3, b1, b2, V2, Tm, ArrayType) + @test Array(a1) == Array(b1) && Array(a2) == Array(b2) + end + + @testset "k = 0 leaves C; bad side or trans is refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + C1, C2 = randn(T, 8, 8), randn(T, 8, 8) + a1, a2 = ArrayType(copy(C1)), ArrayType(copy(C2)) + NextLA.ttmqr!('L', 'N', 8, 8, 8, 8, 0, 0, a1, a2, ArrayType(zeros(T, 8, 0)), ArrayType(zeros(T, 0, 0)), ArrayType(zeros(T, 0))) + @test Array(a1) == C1 && Array(a2) == C2 + Z = ArrayType(zeros(T, 8, 8)) + @test_throws ArgumentError NextLA.ttmqr!('X', 'N', 8, 8, 8, 8, 4, 2, Z, Z, ArrayType(zeros(T, 8, 4)), ArrayType(zeros(T, 2, 4)), ArrayType(zeros(T, 16))) + @test_throws ArgumentError NextLA.ttmqr!('L', 'X', 8, 8, 8, 8, 4, 2, Z, Z, ArrayType(zeros(T, 8, 4)), ArrayType(zeros(T, 2, 4)), ArrayType(zeros(T, 16))) + end + + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + V2, Tm, _ = _ttmqr_factor(T, 7, 7, 3) + Vd, Td = ArrayType(V2), ArrayType(Tm) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C', 'T')) + C1, C2 = side == 'L' ? (randn(T, 7, 9), randn(T, 7, 9)) : (randn(T, 9, 7), randn(T, 9, 7)) + (a1, b1, c1, d1), (a2, b2, c2, d2) = ((ArrayType(copy(C)) for _ in 1:4) for C in (C1, C2)) + dims = side == 'L' ? (7, 9, 7, 9) : (9, 7, 9, 7) + NextLA.ttmqr!(side, trans, dims..., 7, 3, a1, a2, Vd, Td, ArrayType(zeros(T, 27))) + NextLA.ttmqr!(lowercase(side), lowercase(trans), dims..., 7, 3, b1, b2, Vd, Td, ArrayType(zeros(T, 27))) + NextLA.ttmqr!(side, trans, c1, c2, Vd, Td) + NextLA.ttmqr!(lowercase(side), lowercase(trans), d1, d2, Vd, Td) + @test Array(b1) == Array(a1) && Array(b2) == Array(a2) + @test Array(d1) == Array(c1) && Array(d2) == Array(c2) + end + end + end +end + +# The same C1, C2 as LAPACK's tpmqrt (l = n), within 2(n + m) eps relative. +cpu_wanted() && @testset "TTMQR against LAPACK, $T, side=$side, trans=$trans" for T in test_types(TEST_TYPES), side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + for (n, m, ib) in test_cases((:n, :m, :ib), ((7, 7, 3), (24, 24, 8), (16, 16, 4)); valid = (n, m, ib) -> ib > n ? "LAPACK's tpmqrt needs ib ≤ n" : + m != n ? "this comparison takes m = n (ttqrt!'s triangle is the top of A2, LAPACK's l = n triangle the bottom)" : true) + V2, Tm, _ = _ttmqr_factor(T, n, m, ib) + C1, C2 = side == 'L' ? (randn(T, n, 9), randn(T, m, 9)) : (randn(T, 9, n), randn(T, 9, m)) + c1, c2, L1, L2 = copy(C1), copy(C2), copy(C1), copy(C2) + _ttmqr_apply!(side, trans, n, m, 9, ib, c1, c2, V2, Tm, Array) + lapack_tpmqrt!(T, side, (T <: Real && trans == 'C') ? 'T' : trans, m, V2, Tm, L1, L2) + L = side == 'L' ? [L1; L2] : [L1 L2] + got = side == 'L' ? [c1; c2] : [c1 c2] + @test maximum(abs.(big.(got) .- big.(L))) / (maximum(abs, L) * eps(real(T))) <= 2 * (n + m) + end +end diff --git a/test/dense/lapack/qr/ttqrt.jl b/test/dense/lapack/qr/ttqrt.jl new file mode 100644 index 00000000..3cbfd84c --- /dev/null +++ b/test/dense/lapack/qr/ttqrt.jl @@ -0,0 +1,132 @@ +# ttqrt! (src/dense/lapack/qr/ttqrt.jl): QR of [A1; A2], both upper triangular (LAPACK tpqrt, l = n). + +test_params(n = "order of the triangles A1 and A2", ib = "inner block size") # the number options it takes (--params) + +# tpqr_q (test/setup/accuracy.jl) in Float64, for big tiles where BigFloat is too slow (LAPACK's own ratios are in working precision). +function _tpqr_q64(V2, Tm, n, m, ib) + Vb, Tb = Float64.(Array(V2)), Float64.(Array(Tm)) + Q = Matrix{Float64}(I, n + m, n + m) + for ii in reverse(collect(1:ib:n)) + sb = min(ib, n - ii + 1) + V = zeros(n + m, sb) + for j in 1:sb + V[ii+j-1, j] = 1 + V[n+1:n+m, j] = Vb[:, ii+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, ii:ii+sb-1]) * (V' * Q)) + end + return Q +end + +# LAPACK dqrt01's ratios of [A1; A2] = Q R, Q from (triu(A2), T) exactly (tpqr_q, test/setup/accuracy.jl), or in Float64 (wide = Float64). +function _ttqrt_ratios(R, V2, Tm, A0, n, m, ib; wide = big) + Q = wide === big ? tpqr_q(triu(Array(V2)), Tm, n, m, ib) : _tpqr_q64(triu(Array(V2)), Tm, n, m, ib) + e = wide(eps(real(eltype(A0)))) + res = opnorm(wide.(A0) - Q[:, 1:n] * wide.(triu(Array(R))), 1) / ((n + m) * opnorm(wide.(A0), 1) * e) + return Float64(res), Float64(opnorm(Q' * Q - I, 1) / ((n + m) * e)) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "TTQRT [$backend_name]" begin + # Square tiles, block sizes 1 to larger than n; T is checked through Q; Float16 also far from 1 (B37). + @testset "$T, ib=$ib, scale=$sc" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), ib in test_values(:ib, (1, 3, 8, 40)), + sc in (T === Float16 ? (1, 1e-4, 2e2) : (1,)) + T === Float16 && backend_name != "CPU" && continue # B40, pinned below + for n in test_values(:n, (1, 5, 24, 33)) + A1, A2 = T(sc) .* (triu(randn(T, n, n)) + T(2) * I), T(sc) .* triu(randn(T, n, n)) + a1, a2, Td = ArrayType(copy(A1)), ArrayType(copy(A2)), ArrayType(zeros(T, ib, n)) + NextLA.ttqrt!(n, n, ib, a1, a2, Td, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + synchronize(a1) + res, orth = _ttqrt_ratios(a1, a2, Td, [A1; A2], n, n, ib) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + end + + # Float16 on a GPU: the trailing update falls back to scalar indexing (B40). + backend_name == "CPU" || @testset "Float16" begin + @test_broken (NextLA.ttqrt!(5, 5, 2, ArrayType(triu(randn(Float16, 5, 5)) + 2I), ArrayType(triu(randn(Float16, 5, 5))), + ArrayType(zeros(Float16, 2, 5)), ArrayType(zeros(Float16, 5)), ArrayType(zeros(Float16, 10))); true) + end + + # Tiles of the size tiled QR uses (nb = 256, ib = 32) and its multiples; Float16 on a GPU is skipped (B40). + @testset "tiles n=$n, ib=$ib, $T" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (n, ib) in test_cases((:n, :ib), ((256, 32), (512, 32), (1024, 32))) + T === Float16 && backend_name != "CPU" && continue + A1, A2 = triu(randn(T, n, n)) + T(2) * I, triu(randn(T, n, n)) + a1, a2, Td = ArrayType(copy(A1)), ArrayType(copy(A2)), ArrayType(zeros(T, ib, n)) + NextLA.ttqrt!(n, n, ib, a1, a2, Td, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + synchronize(a1) + res, orth = _ttqrt_ratios(a1, a2, Td, [A1; A2], n, n, ib; wide = Float64) + @test res <= LAPACK_TEST_THRESHOLD + @test orth <= LAPACK_TEST_THRESHOLD + end + + # A2 with fewer rows than columns is factored only partly (B39). + @testset "m < n, ib=$ib" for ib in (3, 8) + T = supports_float64(ArrayType) ? Float64 : Float32 + m, n = 3, 7 + A1, A2 = triu(randn(T, n, n)) + 2I, triu(randn(T, m, n)) + a1, a2, Td = ArrayType(copy(A1)), ArrayType(copy(A2)), ArrayType(zeros(T, ib, n)) + ok = try + NextLA.ttqrt!(m, n, ib, a1, a2, Td, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + maximum(_ttqrt_ratios(a1, a2, Td, [A1; A2], n, m, ib)) <= LAPACK_TEST_THRESHOLD + catch + false + end + @test_broken ok + end + + # Only A2's upper triangle is read, as the docstring says: junk below it changes nothing and is left (C21). + @testset "junk below A2's diagonal, $T, n=$n, m=$m, ib=$ib" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)), + (n, m, ib) in test_cases((:n, nothing, :ib), ((24, 24, 8), (7, 9, 3), (256, 256, 32), (512, 512, 32))) + T === Float16 && backend_name != "CPU" && continue # B40 + n > 24 && !(T <: Union{Float32, Float64}) && continue # big tiles in the real types, as the tile tests + A1, A2, J = triu(randn(T, n, n)) + T(2) * I, triu(randn(T, m, n)), tril(randn(T, m, n), -1) + (x1, x2, Tx), (y1, y2, Ty) = map((A2, A2 + J)) do B + a1, a2, Td = ArrayType(copy(A1)), ArrayType(copy(B)), ArrayType(zeros(T, ib, n)) + NextLA.ttqrt!(m, n, ib, a1, a2, Td, ArrayType(zeros(T, n)), ArrayType(zeros(T, ib * n))) + synchronize(a1) + Array(a1), Array(a2), Array(Td) + end + @test y1 == x1 && triu(y2) == triu(x2) && Ty == Tx + @test tril(y2, -1) == J + end + + @testset "the short form equals the long form" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A1, A2 = triu(randn(T, 24, 24)) + 2I, triu(randn(T, 24, 24)) + a, b = ArrayType(copy(A1)), ArrayType(copy(A1)) + a2, b2 = ArrayType(copy(A2)), ArrayType(copy(A2)) + Ta, Tb = ArrayType(zeros(T, 8, 24)), ArrayType(zeros(T, 8, 24)) + NextLA.ttqrt!(a, a2, Ta) + NextLA.ttqrt!(24, 24, 8, b, b2, Tb, ArrayType(zeros(T, 24)), ArrayType(zeros(T, 192))) + @test Array(a) == Array(b) && Array(a2) == Array(b2) && Array(Ta) == Array(Tb) + end + + @testset "m, n or ib = 0 leave A; negative sizes are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + A1, A2 = ArrayType(triu(ones(T, 4, 4))), ArrayType(triu(ones(T, 4, 4))) + for (m, n, ib) in ((0, 4, 2), (4, 0, 2), (4, 4, 0)) + NextLA.ttqrt!(m, n, ib, A1, A2, ArrayType(zeros(T, 2, 4)), ArrayType(zeros(T, 4)), ArrayType(zeros(T, 8))) + end + @test Array(A1) == triu(ones(T, 4, 4)) && Array(A2) == triu(ones(T, 4, 4)) + Z = ArrayType(zeros(T, 8, 8)) + for (m, n, ib) in ((-1, 8, 4), (8, -1, 4), (8, 8, -1)) + @test_throws ArgumentError NextLA.ttqrt!(m, n, ib, Z, Z, ArrayType(zeros(T, 4, 8)), ArrayType(zeros(T, 8)), ArrayType(zeros(T, 32))) + end + end + end +end + +# R, the reflectors (upper triangle of A2) and T within 4n eps of LAPACK's tpqrt with l = n, relative. +cpu_wanted() && @testset "TTQRT against LAPACK, $T, n=$n, ib=$ib" for T in test_types(TEST_TYPES), (n, ib) in test_cases((:n, :ib), ((7, 3), (24, 8), (33, 8)); valid = (n, ib) -> ib <= n || "LAPACK's tpqrt needs ib ≤ n") + A1, A2 = triu(randn(T, n, n)) + T(2) * I, triu(randn(T, n, n)) + a1, a2, Tn = copy(A1), copy(A2), zeros(T, ib, n) + NextLA.ttqrt!(n, n, ib, a1, a2, Tn, zeros(T, n), zeros(T, ib * n)) + L1, L2, Tl = copy(A1), copy(A2), zeros(T, ib, n) + lapack_tpqrt!(T, n, n, n, ib, L1, n, L2, n, Tl, ib, zeros(T, ib * n)) + d = max(maximum(abs.(big.(triu(a1)) .- big.(triu(L1)))) / maximum(abs, L1), maximum(abs.(triu(big.(a2)) .- triu(big.(L2)))) / maximum(abs, L2), + maximum(abs.(triu(big.(Tn)) .- triu(big.(Tl)))) / maximum(abs, Tl)) + @test Float64(d) / eps(real(T)) <= 4n +end diff --git a/test/dense/lapack/qr/unmqr.jl b/test/dense/lapack/qr/unmqr.jl new file mode 100644 index 00000000..1f794f59 --- /dev/null +++ b/test/dense/lapack/qr/unmqr.jl @@ -0,0 +1,165 @@ +# unmqr! (src/dense/lapack/qr/unmqr.jl): C := op(Q) C or C op(Q), Q from geqrt!, block by block. + +test_params(m = "rows of C", n = "columns of C", ib = "inner block size") # the number options it takes (--params) + +# A geqrt! factor of an nq×k panel with block size ib, and its Q formed from the blocks in BigFloat (or Float64 for big tiles). +function _unmqr_panel(T, nq, k, ib; wide = big) + F, Tm = randn(T, nq, k), zeros(T, ib, k) + NextLA.geqrt!(nq, k, ib, F, Tm, zeros(T, k), zeros(T, ib * k)) + W, Tb = wide.(F), wide.(Tm) + Q = Matrix{eltype(W)}(I, nq, nq) + for i in reverse(collect(1:ib:k)) + sb = min(ib, k - i + 1) + V = zeros(eltype(W), nq, sb) + for j in 1:sb + V[i+j-1, j] = 1 + V[i+j:nq, j] = W[i+j:nq, i+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, i:i+sb-1]) * (V' * Q)) + end + return F, Tm, Q +end + +# dqrt03-style ratio ‖C - op(Q) C0‖₁ / (max(m, n) ‖C0‖₁ eps). +function _unmqr_ratio(C, side, trans, Q, C0; wide = big) + Qt = trans == 'N' ? Q : Q' + exact = side == 'L' ? Qt * wide.(C0) : wide.(C0) * Qt + return Float64(opnorm(wide.(Array(C)) - exact, 1) / (max(size(C0)...) * opnorm(wide.(C0), 1) * wide(eps(real(eltype(C0)))))) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "UNMQR [$backend_name]" begin + # Both sides and trans, square and rectangular C, k = 1, 5 and the whole order, ib = 1 to 32. + @testset "$T, side=$side, trans=$trans" for T in backend_types(ArrayType, TEST_TYPES), + side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + for (m, n) in test_cases((:m, :n), ((1, 1), (5, 1), (1, 5), (33, 20), (20, 33), (64, 64))), ib in test_values(:ib, (1, 3, 8, 32)) + nq = side == 'L' ? m : n + for k in unique((1, min(5, nq), nq)) + F, Tm, Q = _unmqr_panel(T, nq, k, ib) + C0 = randn(T, m, n) + Cd = ArrayType(copy(C0)) + NextLA.unmqr!(side, trans, m, n, k, ib, ArrayType(F), nq, ArrayType(Tm), Cd, ArrayType(zeros(T, side == 'L' ? n : m, ib))) + synchronize(Cd) + @test _unmqr_ratio(Cd, side, trans, Q, C0) <= LAPACK_TEST_THRESHOLD + end + end + end + + # Float16: the CPU is checked; on a GPU larfb! falls back to scalar indexing (B36). + @testset "Float16, side=$side, trans=$trans" for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + F, Tm, Q = _unmqr_panel(Float16, 20, 7, 3) + C0 = side == 'L' ? randn(Float16, 20, 9) : randn(Float16, 9, 20) + Cd = ArrayType(copy(C0)) + apply_q!() = NextLA.unmqr!(side, trans, size(C0)..., 7, 3, ArrayType(F), 20, ArrayType(Tm), Cd, ArrayType(zeros(Float16, 9, 3))) + if backend_name == "CPU" + apply_q!() + @test _unmqr_ratio(Cd, side, trans, Q, C0) <= LAPACK_TEST_THRESHOLD + else + @test_broken (apply_q!(); true) + end + end + + # Tiles of the size tiled QR uses (nb = 256, ib = 32) and its multiples, Q in Float64; Float16 on a GPU is skipped (B36). + @testset "tile m=$m, n=$n, ib=$ib, $T, side=$side" for T in backend_types(ArrayType, (Float16, Float32, Float64)), + (m, n, ib) in test_cases((:m, :n, :ib), ((256, 256, 32), (512, 512, 32), (1024, 1024, 32))), side in test_flags(:side, ('L', 'R')) + T === Float16 && backend_name != "CPU" && continue + nq = side == 'L' ? m : n + F, Tm, Q = _unmqr_panel(T, nq, nq, ib; wide = Float64) + for trans in test_flags(:trans, ('N', 'C')) + C0 = randn(T, m, n) + Cd = ArrayType(copy(C0)) + NextLA.unmqr!(side, trans, m, n, nq, ib, ArrayType(F), nq, ArrayType(Tm), Cd, ArrayType(zeros(T, side == 'L' ? n : m, ib))) + synchronize(Cd) + @test _unmqr_ratio(Cd, side, trans, Q, C0; wide = Float64) <= LAPACK_TEST_THRESHOLD + end + end + + @testset "real trans = 'T' is 'C', $T" for T in backend_types(ArrayType, (Float32, Float64)) + F, Tm, _ = _unmqr_panel(T, 10, 4, 2) + C0 = randn(T, 10, 6) + a, b = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.unmqr!('L', 'T', 10, 6, 4, 2, ArrayType(F), 10, ArrayType(Tm), a, ArrayType(zeros(T, 6, 2))) + NextLA.unmqr!('L', 'C', 10, 6, 4, 2, ArrayType(F), 10, ArrayType(Tm), b, ArrayType(zeros(T, 6, 2))) + @test Array(a) == Array(b) + end + + # k larger than the order of Q is clamped to it, as the tile routines rely on. + @testset "k is clamped to the order of Q" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + F, Tm, _ = _unmqr_panel(T, 10, 4, 2) + C0 = randn(T, 10, 6) + a, b = ArrayType(copy(C0)), ArrayType(copy(C0)) + NextLA.unmqr!('L', 'N', 10, 6, 40, 2, ArrayType(F), 10, ArrayType(Tm), a, ArrayType(zeros(T, 6, 2))) + NextLA.unmqr!('L', 'N', 10, 6, 4, 2, ArrayType(F), 10, ArrayType(Tm), b, ArrayType(zeros(T, 6, 2))) + @test Array(a) == Array(b) + end + + # C a view inside a larger matrix: only the view changes. + @testset "C a view, $T" for T in backend_types(ArrayType, TEST_TYPES) + F, Tm, Q = _unmqr_panel(T, 10, 4, 2) + Big0 = randn(T, 14, 9) + Bd = ArrayType(copy(Big0)) + NextLA.unmqr!('L', 'C', 10, 6, 4, 2, ArrayType(F), 10, ArrayType(Tm), view(Bd, 3:12, 2:7), ArrayType(zeros(T, 6, 2))) + B = Array(Bd) + @test _unmqr_ratio(B[3:12, 2:7], 'L', 'C', Q, Big0[3:12, 2:7]) <= LAPACK_TEST_THRESHOLD + outside = trues(14, 9); outside[3:12, 2:7] .= false + @test B[outside] == Big0[outside] + end + + @testset "the short form equals the long form and checks C" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + F, Tm, _ = _unmqr_panel(T, 10, 4, 2) + C0 = randn(T, 10, 6) + a, b = ArrayType(copy(C0)), ArrayType(copy(C0)) + @test NextLA.unmqr!('L', 'C', ArrayType(F), ArrayType(Tm), a) === a # the short form returns C + NextLA.unmqr!('L', 'C', 10, 6, 4, 2, ArrayType(F), 10, ArrayType(Tm), b, ArrayType(zeros(T, 6, 2))) + @test Array(a) == Array(b) + @test_throws ArgumentError NextLA.unmqr!('L', 'C', ArrayType(F), ArrayType(Tm), ArrayType(randn(T, 9, 6))) + end + + @testset "k = 0 leaves C; bad arguments are refused" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + F, Tm, _ = _unmqr_panel(T, 10, 4, 2) + C0 = randn(T, 10, 6) + Cd, w = ArrayType(copy(C0)), ArrayType(zeros(T, 6, 2)) + NextLA.unmqr!('L', 'N', 10, 6, 0, 2, ArrayType(F), 10, ArrayType(Tm), Cd, w) + @test Array(Cd) == C0 + Fd, Td = ArrayType(F), ArrayType(Tm) + @test_throws ArgumentError NextLA.unmqr!('X', 'N', 10, 6, 4, 2, Fd, 10, Td, Cd, w) + @test_throws ArgumentError NextLA.unmqr!('L', 'X', 10, 6, 4, 2, Fd, 10, Td, Cd, w) + @test_throws ArgumentError NextLA.unmqr!('L', 'N', -1, 6, 4, 2, Fd, 10, Td, Cd, w) + @test_throws ArgumentError NextLA.unmqr!('L', 'N', 10, 6, -1, 2, Fd, 10, Td, Cd, w) + @test_throws ArgumentError NextLA.unmqr!('L', 'N', 10, 6, 4, 2, Fd, 5, Td, Cd, w) + end + + @testset "lowercase flags give the same result" begin + T = supports_float64(ArrayType) ? Float64 : Float32 + F, Tm, _ = _unmqr_panel(T, 10, 4, 2) + F, Tm = ArrayType(F), ArrayType(Tm) + for side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C', 'T')) + C0 = side == 'L' ? randn(T, 10, 6) : randn(T, 6, 10) + a, b, c, d = (ArrayType(copy(C0)) for _ in 1:4) + NextLA.unmqr!(side, trans, size(C0)..., 4, 2, F, 10, Tm, a, ArrayType(zeros(T, 6, 2))) + NextLA.unmqr!(lowercase(side), lowercase(trans), size(C0)..., 4, 2, F, 10, Tm, b, ArrayType(zeros(T, 6, 2))) + NextLA.unmqr!(side, trans, F, Tm, c) + NextLA.unmqr!(lowercase(side), lowercase(trans), F, Tm, d) + @test Array(b) == Array(a) && Array(d) == Array(c) + end + end + end +end + +# The same C as LAPACK's gemqrt, within 2 max(m, n) eps relative (ib <= k, which LAPACK requires). +cpu_wanted() && @testset "UNMQR against LAPACK, $T, side=$side, trans=$trans" for T in test_types(TEST_TYPES), side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'C')) + for (m, n, k, ib) in test_cases((:m, :n, nothing, :ib), ((33, 20, 5, 3), (64, 64, 64, 8), (20, 33, 20, 8)); + valid = (m, n, k, ib) -> ib <= min(k, side == 'L' ? m : n) || "LAPACK's gemqrt needs ib ≤ k = $(min(k, side == 'L' ? m : n))") + nq = side == 'L' ? m : n + k = min(k, nq) + F, Tm, _ = _unmqr_panel(T, nq, k, ib) + C0 = randn(T, m, n) + Cn, Cl = copy(C0), copy(C0) + NextLA.unmqr!(side, trans, m, n, k, ib, F, nq, Tm, Cn, zeros(T, side == 'L' ? n : m, ib)) + LAPACK.gemqrt!(side, (T <: Real && trans == 'C') ? 'T' : trans, F, Tm, Cl) + @test maximum(abs.(big.(Cn) .- big.(Cl))) / (maximum(abs, Cl) * eps(real(T))) <= 2 * max(m, n) + end +end diff --git a/test/dense/lapack/rotations/lartg.jl b/test/dense/lapack/rotations/lartg.jl new file mode 100644 index 00000000..8158ffd9 --- /dev/null +++ b/test/dense/lapack/rotations/lartg.jl @@ -0,0 +1,60 @@ +# lartg (src/dense/lapack/rotations/lartg.jl): the plane rotation [c s; -s̄ c] [f; g] = [r; 0]. + +# Largest error, in eps units, of c² + |s|² = 1, c f + s g = r and -s̄ f + c g = 0 (relative to ‖(f, g)‖). +function _lartg_err(f, g, c, s, r) + e = big(eps(real(typeof(f)))) + fb, gb, cb, sb, rb = big(f), big(g), big(c), big(s), big(r) + n = max(sqrt(abs2(fb) + abs2(gb)), big(floatmin(real(typeof(f))))) + return Float64(max(abs(cb^2 + abs2(sb) - 1), abs(cb * fb + sb * gb - rb) / n, abs(cb * gb - conj(sb) * fb) / n) / e) +end + +# Pairs (f, g) for every branch: unscaled, f or g zero, both tiny, both huge, mixed scales, subnormal f. +function _lartg_cases(T) + RT = real(T) + x() = RT((rand() + 0.5) * rand((-1, 1))) + v() = T <: Complex ? T(x(), x()) : T(x()) + tiny, huge = 4floatmin(RT), floatmax(RT) / 8 + pairs = [(v(), v()) for _ in 1:20] + append!(pairs, [(v(), zero(T)), (v() * tiny, v() * tiny), (v() * huge, v() * huge), (v() * tiny, v() * huge), + (v() * huge, v() * tiny), (T(nextfloat(zero(RT))), v())]) + T <: Real && append!(pairs, [(zero(T), v()), (zero(T), v() * tiny), (zero(T), v() * huge)]) # complex f = 0: B32 + return first.(pairs), last.(pairs) +end + +for (backend_name, ArrayType, synchronize) in available_backends() + @testset "LARTG [$backend_name]" begin + # The identities hold within 10 eps in every branch, element by element of a broadcast. + @testset "$T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + F, G = _lartg_cases(T) + out = Array(NextLA.lartg.(ArrayType(F), ArrayType(G))) + @test all(o -> o[1] isa real(T) && o[2] isa T && o[3] isa T, out) + @test maximum(_lartg_err(F[i], G[i], out[i]...) for i in eachindex(F)) <= 10 + end + + # g = 0 gives c = 1, s = 0, r = f exactly; complex f = 0 gives c = 0 and r = |g|. + @testset "exact cases, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + F = T[0, 1.5, -2]; G = zeros(T, 3) + @test Array(NextLA.lartg.(ArrayType(F), ArrayType(G))) == [(one(real(T)), zero(T), f) for f in F] + g = T <: Complex ? T(3, 4) : T(-5) + c, s, r = Array(NextLA.lartg.(ArrayType([zero(T)]), ArrayType([g])))[1] + @test c == 0 && r == 5 && abs(s) ≈ 1 + end + + @testset "NaN propagates, $T" for T in backend_types(ArrayType, (Float16, TEST_TYPES...)) + @test isnan(Array(NextLA.lartg.(ArrayType([T(NaN)]), ArrayType([one(T)])))[1][3]) + end + end +end + +# Each of c, s, r within 8 eps of LAPACK's ?lartg, relative, in every branch. +cpu_wanted() && @testset "LARTG against LAPACK, $T" for T in test_types(TEST_TYPES) + F, G = _lartg_cases(T) + rel(a, b) = abs(big(a) - big(b)) / max(abs(big(b)), big(floatmin(real(T)))) + worst = maximum(maximum(rel.(NextLA.lartg(F[i], G[i]), lapack_lartg(F[i], G[i]))) for i in eachindex(F)) + @test Float64(worst) / eps(real(T)) <= 8 +end + +cpu_wanted() && @testset "LARTG argument types" begin + @test NextLA.lartg(1.0f0, 2.0) isa NTuple{3, Float64} # promoted + @test_throws MethodError NextLA.lartg(1, 2) # integers are refused +end diff --git a/test/gemm/gemmEx.jl b/test/gemm/gemmEx.jl deleted file mode 100644 index 13ec88fa..00000000 --- a/test/gemm/gemmEx.jl +++ /dev/null @@ -1,243 +0,0 @@ -# gemmEx! across backends. -# -# gemmEx! is the mixed-storage entry point: A, B and C may each have their own -# element type, and the accumulation happens in compute_type. On CUDA and -# AMDGPU that is a vendor GEMMEx call. On the CPU there is no such primitive, so -# a triple BLAS accepts goes to BLAS.gemm! and everything else is accumulated in -# compute_type and rounded once on store -- the same operation, not the same -# speed. oneAPI and Metal have no gemmEx!: it throws there for every signature. -# -# The reference is always computed in double precision and compared against, -# rather than in the storage type, so a wrong accumulation order shows up -# instead of being hidden by the rounding it causes. - -for (backend_name, ArrayType, synchronize) in available_backends() - if !(backend_name in ("CPU", "CUDA", "AMDGPU")) - @testset "GEMMEX [$backend_name] refuses" begin - A = ArrayType(rand(Float32, 4, 4)) - C = ArrayType(zeros(Float32, 4, 4)) - @test_throws ArgumentError NextLA.gemmEx!('N', 'N', 1.0f0, A, A, 0.0f0, C) - end - continue - end - # Local to the loop, not top level: these are this file's reference - # arithmetic, not names the library gains, and the review pages read an - # unindented definition in a test file as a contribution. - _ex_op(M, t::Char) = t == 'N' ? M : (t == 'C' ? adjoint(M) : transpose(M)) - _ex_refr(transA, transB, alpha, A, B, beta, C) = - alpha .* (_ex_op(Float64.(A), transA) * _ex_op(Float64.(B), transB)) .+ - beta .* Float64.(C) - - @testset "GEMMEX [$backend_name]" begin - - # Every backend supports the same-type BLAS-shaped case. - @testset "same type $T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "trans $ta$tb, n=$n k=$k m=$m" for - (ta, tb) in (('N', 'N'), ('T', 'N'), ('N', 'T'), ('T', 'T')), - (n, k, m) in ((16, 16, 16), (32, 16, 8), (17, 9, 5)) - - A = ta == 'N' ? rand(T, n, k) : rand(T, k, n) - B = tb == 'N' ? rand(T, k, m) : rand(T, m, k) - C0 = rand(T, n, m) - alpha, beta = T(2), T(3) - expected = _ex_refr(ta, tb, 2.0, A, B, 3.0, C0) - - Ad, Bd = ArrayType(copy(A)), ArrayType(copy(B)) - Cd = ArrayType(copy(C0)) - NextLA.gemmEx!(ta, tb, alpha, Ad, Bd, beta, Cd) - synchronize(Cd) - @test Array(Cd) ≈ expected rtol=rtol - end - - @testset "alpha=0 scales C only" begin - n = 8 - A, B, C0 = rand(T, n, n), rand(T, n, n), rand(T, n, n) - Cd = ArrayType(copy(C0)) - NextLA.gemmEx!('N', 'N', zero(T), ArrayType(A), ArrayType(B), T(2), Cd) - synchronize(Cd) - @test Array(Cd) ≈ 2 .* C0 rtol=rtol - end - - @testset "beta=0 overwrites C" begin - n = 8 - A, B = rand(T, n, n), rand(T, n, n) - Cd = ArrayType(fill(T(99), n, n)) - NextLA.gemmEx!('N', 'N', one(T), ArrayType(A), ArrayType(B), zero(T), Cd) - synchronize(Cd) - @test Array(Cd) ≈ Float64.(A) * Float64.(B) rtol=rtol - end - end - - # 'C' is the adjoint and must not be collapsed into 'T'. TLR passes - # adjoint_blas_char(T), which is 'C' exactly where the two differ. - @testset "adjoint is not transpose" begin - n = 12 - A, B = rand(ComplexF32, n, n), rand(ComplexF32, n, n) - Cc = ArrayType(zeros(ComplexF32, n, n)) - Ct = ArrayType(zeros(ComplexF32, n, n)) - NextLA.gemmEx!('C', 'N', 1.0f0, ArrayType(A), ArrayType(B), 0.0f0, Cc) - NextLA.gemmEx!('T', 'N', 1.0f0, ArrayType(A), ArrayType(B), 0.0f0, Ct) - synchronize(Cc); synchronize(Ct) - @test Array(Cc) ≈ adjoint(ComplexF64.(A)) * ComplexF64.(B) rtol=1e-5 - @test Array(Ct) ≈ transpose(ComplexF64.(A)) * ComplexF64.(B) rtol=1e-5 - @test !(Array(Cc) ≈ Array(Ct)) - end - - @testset "Float16 storage" begin - n = 16 - A, B = rand(Float16, n, n), rand(Float16, n, n) - ref = Float64.(A) * Float64.(B) - - for TC in (Float16, Float32) - Cd = ArrayType(zeros(TC, n, n)) - # The storage decides the compute type: Float16 for an - # all-Float16 triple, Float32 once C is Float32. The scalars - # take no part. - NextLA.gemmEx!('N', 'N', 1.0f0, ArrayType(A), ArrayType(B), 0.0f0, Cd) - synchronize(Cd) - # Float16 storage carries ~3 decimal digits, so the - # tolerance is the storage's, not the accumulation's. - @test Array(Cd) ≈ ref rtol=(TC === Float16 ? 1e-2 : 1e-3) - end - end - - @testset "compute_type is honoured" begin - n = 16 - A, B = rand(Float16, n, n), rand(Float16, n, n) - ref = Float64.(A) * Float64.(B) - Cd = ArrayType(zeros(Float32, n, n)) - NextLA.gemmEx!('N', 'N', 1.0, ArrayType(A), ArrayType(B), 0.0, Cd; - compute_type=Float32) - synchronize(Cd) - @test Array(Cd) ≈ ref rtol=1e-3 - end - - # A compute type wider than the storage is legitimate, and the CPU - # honours it -- the accumulation happens in Float64 and is rounded once - # on store. cuBLAS rejects the same request outright, which is why - # _gemm_dispatch! names Float32; this asserts the CPU capability the - # fallback relies on. - if backend_name == "CPU" - @testset "Float64 compute over Float16 storage" begin - n = 16 - A, B = rand(Float16, n, n), rand(Float16, n, n) - C = zeros(Float16, n, n) - NextLA.gemmEx!('N', 'N', -1.0, A, B, 1.0, C; compute_type=Float64) - @test C ≈ -(Float64.(A) * Float64.(B)) rtol=5e-3 - end - - # BLAS guarantees a zero scalar means the corresponding operand is - # never read. That matters here because Float16 overflows to Inf - # readily, and 0 * Inf is NaN -- so a caller that scales a product - # out of the result would otherwise still be poisoned by it. - @testset "a zero scalar does not read its operand" begin - n = 4 - Binf = ones(Float16, n, n) - - # wide path: alpha = 0 must ignore an Inf in A - Ainf = fill(Float16(Inf), n, n) - C = fill(Float16(2), n, n) - NextLA.gemmEx!('N', 'N', 0.0, Ainf, Binf, 3.0, C; compute_type=Float32) - @test all(C .== 6) - - # wide path: beta = 0 must ignore a NaN already in C - Cnan = fill(Float16(NaN), n, n) - NextLA.gemmEx!('N', 'N', 1.0, ones(Float16, n, n), Binf, 0.0, Cnan; - compute_type=Float32) - @test all(Cnan .== n) - - # both zero: C is zeroed, operands untouched - Cz = fill(Float16(7), n, n) - NextLA.gemmEx!('N', 'N', 0.0, Ainf, Binf, 0.0, Cz; compute_type=Float32) - @test all(iszero, Cz) - - # BLAS-type operands too: alpha = 0 must not reach BLAS, whose kernels may read A - Ad = fill(Inf, n, n) - Cd = fill(2.0, n, n) - NextLA.gemmEx!('N', 'N', 0.0, Ad, ones(n, n), 3.0, Cd) - @test all(Cd .== 6) - end - - @testset "argument errors" begin - n = 8 - A, B = rand(Float32, n, n), rand(Float32, n, n) - @test_throws DimensionMismatch NextLA.gemmEx!( - 'N', 'N', 1.0f0, A, B, 0.0f0, zeros(Float32, n + 1, n)) - @test_throws ArgumentError NextLA.gemmEx!( - 'N', 'N', 1.0f0, A, B, 0.0f0, zeros(Float32, n, n); - compute_type=Int8) - end - - # Only single-matrix gemmEx! widens on the CPU. The batched and - # precision entry points take what BLAS takes, and say so. - @testset "batched and precision refuse Float16" begin - n = 4 - A, B = rand(Float16, n, n), rand(Float16, n, n) - mode = NextLA.GEMMCompute{Float32}() - @test !NextLA.gemm_signature_supported( - KernelAbstractions.CPU(), Float16, Float16, Float32, mode) - @test_throws ArgumentError NextLA.precision_gemm!( - 'N', 'N', 1.0f0, A, B, 0.0f0, zeros(Float32, n, n), mode) - @test_throws ArgumentError NextLA.gemmEx_batched!( - 'N', 'N', 1.0, rand(Float16, n, n, 2), rand(Float16, n, n, 2), - 0.0, zeros(Float32, n, n, 2)) - @test_throws ArgumentError NextLA.gemm_batched!( - 'N', 'N', 1.0f0, rand(Float16, n, n, 2), rand(Float16, n, n, 2), - 0.0f0, zeros(Float16, n, n, 2)) - end - - # Pointer batches stay GPU-only: there is deliberately no CPU - # _build_batch_ptrs, and this records that as intended. - @testset "pointer batches remain unsupported" begin - n = 4 - A, B = rand(Float32, n, n), rand(Float32, n, n) - C = zeros(Float32, n, n) - @test !NextLA.supports_pointer_batched(KernelAbstractions.CPU()) - @test_throws ArgumentError NextLA.gemm_batched_ptrs!( - 'N', 'N', 1.0f0, nothing, A, nothing, B, 0.0f0, nothing, C, 1) - end - end - end -end - -# gemm! in the BLAS argument order, against LinearAlgebra.BLAS over all three -# transposes, with alpha and beta away from 1 and 0 so both scalings run. -# Complex only where the backend's GEMM takes it. -@testset "gemm! flag form [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - types = backend_name in ("CPU", "CUDA", "AMDGPU") ? - (Float32, Float64, ComplexF32, ComplexF64) : (Float32, Float64) - @testset "$T $ta$tb" for T in types, ta in ('N', 'T', 'C'), tb in ('N', 'T', 'C') - m, k, n = 7, 5, 6 - A0 = ta == 'N' ? rand(T, m, k) : rand(T, k, m) - B0 = tb == 'N' ? rand(T, k, n) : rand(T, n, k) - C0 = rand(T, m, n) - alpha, beta = T(1.5), T(-0.5) - ref = copy(C0) - LinearAlgebra.BLAS.gemm!(ta, tb, alpha, A0, B0, beta, ref) - C = ArrayType(copy(C0)) - out = gemm!(ta, tb, alpha, ArrayType(A0), ArrayType(B0), beta, C) - synchronize(C) - @test out === C - @test Array(C) ≈ ref rtol = (real(T) === Float32 ? 1e-5 : 1e-12) - end - @testset "rejects a bad flag" begin - A = ArrayType(rand(Float32, 2, 2)) - @test_throws ArgumentError gemm!('X', 'N', 1f0, A, A, 0f0, similar(A)) - end -end - -# The compute type comes from the storage types: an untyped alpha or beta (a -# Float64 literal on Float32 data) must not raise it. On CUDA it used to, and -# cuBLAS refused the Float64 compute it asked for. -@testset "compute type follows the data [$backend_name]" for (backend_name, ArrayType, synchronize) in available_backends() - backend_name in ("CPU", "CUDA", "AMDGPU") || continue - A0, B0, C0 = rand(Float32, 6, 4), rand(Float32, 4, 5), rand(Float32, 6, 5) - A, B, C = ArrayType(A0), ArrayType(B0), ArrayType(copy(C0)) - @test NextLA.default_compute_type(0.5, A, B, 2.0, C) == Float32 - @test NextLA.default_compute_type(1.0, A0, B0, 0.0, zeros(Float64, 6, 5)) == Float64 - NextLA.gemmEx!('N', 'N', 0.5, A, B, 2.0, C) - synchronize(C) - @test Array(C) ≈ 0.5f0 .* (A0 * B0) .+ 2f0 .* C0 rtol = 1e-5 -end diff --git a/test/gemm/gemm_grouped.jl b/test/gemm/gemm_grouped.jl deleted file mode 100644 index 92b105ca..00000000 --- a/test/gemm/gemm_grouped.jl +++ /dev/null @@ -1,74 +0,0 @@ -using Test - -@testset "grouped GEMM" begin - @test NextLA.supports_grouped_gemm(KernelAbstractions.CPU()) - A_cpu = Float32[1 2; 3 4] - B_cpu = Float32[2 0 1; 1 3 4] - C_cpu = fill(0.5f0, 2, 3) - cpu_task = NextLA.GroupedGemmTask( - 'N', 'N', 2.0f0, A_cpu, B_cpu, 0.5f0, C_cpu) - cpu_expected = 2f0 .* (A_cpu * B_cpu) .+ 0.5f0 .* fill(0.5f0, 2, 3) - NextLA.precision_gemm_grouped!([cpu_task], NextLA.GEMMCompute{Float32}()) - @test C_cpu ≈ cpu_expected - - prepared_cpu = NextLA.prepare_precision_gemm_grouped( - [cpu_task], NextLA.GEMMCompute{Float32}()) - @test prepared_cpu isa NextLA.CPUPreparedGroupedGemm - fill!(C_cpu, 1f0) - NextLA.precision_gemm_grouped_prepared!(prepared_cpu, 3f0, -0.25f0) - @test C_cpu ≈ 3f0 .* (A_cpu * B_cpu) .- 0.25f0 - NextLA.destroy_prepared_grouped_gemm!(prepared_cpu) - - for (name, AT, sync) in backends - name == "CUDA" || continue - A1 = _to_backend(AT, Float32[1 2; 3 4]) - B1 = _to_backend(AT, Float32[2 0 1; 1 3 4]) - C1 = _to_backend(AT, fill(0.5f0, 2, 3)) - C3 = _to_backend(AT, fill(0.25f0, 2, 3)) - A2 = _to_backend(AT, Float32[1 2 3]) - B2 = _to_backend(AT, reshape(Float32[2, 4, 1], 3, 1)) - C2 = _to_backend(AT, reshape(Float32[3], 1, 1)) - expected1 = 2f0 .* (Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4]) .+ 0.5f0 .* fill(0.5f0, 2, 3) - expected3 = Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4] - expected2 = 3f0 .* (Float32[1 2 3] * Float32[2; 4; 1]) .+ 0.25f0 .* reshape(Float32[3], 1, 1) - tasks = [ - NextLA.GroupedGemmTask('N', 'N', 2f0, A1, B1, 0.5f0, C1), - NextLA.GroupedGemmTask('N', 'N', 3f0, A2, B2, 0.25f0, C2), - # Same shape as the first task but a different alpha/beta pair: - # this must be a second cuBLAS group. - NextLA.GroupedGemmTask('N', 'N', 1f0, A1, B1, 0f0, C3), - ] - NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float32}()) - sync(C1) - @test Array(C1) ≈ expected1 - @test Array(C2) ≈ expected2 - @test Array(C3) ≈ expected3 - - Ah = _to_backend(AT, Float16[1 2; 3 4]) - Bh = _to_backend(AT, Float16[2 0 1; 1 3 4]) - Ch = _to_backend(AT, fill(Float16(0.5), 2, 3)) - mixed = [NextLA.GroupedGemmTask('N', 'N', 2f0, Ah, Bh, 0.5f0, Ch)] - NextLA.precision_gemm_grouped!(mixed, NextLA.GEMMCompute{Float32}()) - sync(Ch) - @test Float32.(Array(Ch)) ≈ 2f0 .* (Float32.(Float16[1 2; 3 4]) * - Float32.(Float16[2 0 1; 1 3 4])) .+ 0.25f0 - - # Offset by one Float32 element: grouped cuBLAS kernels may fault on - # this pointer, so the adapter must route it through ordinary GEMMEx. - Astore = _to_backend(AT, Float32[0 0; 1 2; 3 4]) - Aunsafe = view(Astore, 2:3, :) - Cunsafe = _to_backend(AT, zeros(Float32, 2, 3)) - unsafe = [NextLA.GroupedGemmTask('N', 'N', 1f0, Aunsafe, B1, 0f0, Cunsafe)] - NextLA.precision_gemm_grouped!(unsafe, NextLA.GEMMCompute{Float32}()) - sync(Cunsafe) - @test Array(Cunsafe) ≈ Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4] - prepared_unsafe = NextLA.prepare_precision_gemm_grouped( - unsafe, NextLA.GEMMCompute{Float32}()) - @test prepared_unsafe isa NextLA.PreparedGroupedGemmBundle - fill!(Cunsafe, 0f0) - NextLA.precision_gemm_grouped_prepared!(prepared_unsafe) - sync(Cunsafe) - @test Array(Cunsafe) ≈ Float32[1 2; 3 4] * Float32[2 0 1; 1 3 4] - NextLA.destroy_prepared_grouped_gemm!(prepared_unsafe) - end -end diff --git a/test/gemm/matmul.jl b/test/gemm/matmul.jl deleted file mode 100644 index c5ef6e70..00000000 --- a/test/gemm/matmul.jl +++ /dev/null @@ -1,129 +0,0 @@ -# GEMM_ADD! and GEMM_SUB! had no test of their own. Both were broken on the CPU -# backend: the matmul! kernel assigned I and J once and used them again after a -# @synchronize, and on CPU that splits the body into separate ndrange loops -# where a plain local no longer exists — so `I` resolved to LinearAlgebra.I and -# the call died with `isless(::UniformScaling{Bool}, ::Int64)`. Anything that -# recursed through unified_rectrxm! inherited it. -# -# Note the argument orders differ: -# GEMM_ADD!(A, B, C) -> C .+= A * B -# GEMM_SUB!(A, B, C) -> A .-= B * C - -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "MATMUL [$backend_name]" begin - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "GEMM_ADD! n=$n, r=$r, m=$m" for (n, r, m) in [ - (16, 16, 16), (32, 32, 32), (64, 32, 16), (33, 17, 9), - ] - A = rand(T, n, r) - B = rand(T, r, m) - C = rand(T, n, m) - expected = C + A * B - - Ad, Bd, Cd = ArrayType(copy(A)), ArrayType(copy(B)), ArrayType(copy(C)) - NextLA.GEMM_ADD!(Ad, Bd, Cd) - synchronize(Cd) - @test Array(Cd) ≈ expected rtol=rtol - end - - @testset "GEMM_SUB! n=$n, r=$r, m=$m" for (n, r, m) in [ - (16, 16, 16), (32, 32, 32), (64, 32, 16), - ] - B = rand(T, r, m) - C = rand(T, m, n) - A = rand(T, r, n) - expected = A - B * C - - Ad, Bd, Cd = ArrayType(copy(A)), ArrayType(copy(B)), ArrayType(copy(C)) - NextLA.GEMM_SUB!(Ad, Bd, Cd) - synchronize(Ad) - @test Array(Ad) ≈ expected rtol=rtol - end - end - end -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 -# recursion needs all three. -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "MATMUL scaled/transposed [$backend_name]" begin - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - n, r, m = 32, 24, 16 - - @testset "GEMM_ADD! scale=$sc" for sc in (1, 2.5, -0.5) - A, B, C = rand(T, n, r), rand(T, r, m), rand(T, n, m) - expected = C + T(sc) * A * B - Ad, Bd, Cd = ArrayType(copy(A)), ArrayType(copy(B)), ArrayType(copy(C)) - NextLA.GEMM_ADD!(Ad, Bd, Cd, sc) - synchronize(Cd) - @test Array(Cd) ≈ expected rtol=rtol - end - - @testset "GEMM_SUB! scale=$sc" for sc in (1, 0.5) - A, B, C = rand(T, n, m), rand(T, n, r), rand(T, r, m) - expected = A - T(sc) * B * C - Ad, Bd, Cd = ArrayType(copy(A)), ArrayType(copy(B)), ArrayType(copy(C)) - NextLA.GEMM_SUB!(Ad, Bd, Cd, sc) - synchronize(Ad) - @test Array(Ad) ≈ expected rtol=rtol - end - - @testset "transposed operands" begin - A, B, C = rand(T, n, r), rand(T, r, m), rand(T, n, m) - expected = C + A * B - # pass Aᵀ wrapped, so the wrapper must route it through transA - Atd = ArrayType(permutedims(copy(A))) - Bd, Cd = ArrayType(copy(B)), ArrayType(copy(C)) - NextLA.GEMM_ADD!(transpose(Atd), Bd, Cd) - synchronize(Cd) - @test Array(Cd) ≈ expected rtol=rtol - end - end - - # Each term is 200 * 200 = 40000 and the signs alternate, so the sum is 0 - # but a running Float16 sum would pass floatmax(Float16) = 65504 on the way. - @testset "Float16 destination accumulates in Float32" begin - A = ArrayType(fill(Float16(200), 32, 32)) - B = ArrayType(Float16[isodd(k) ? 200 : -200 for k in 1:32, j in 1:32]) - C = ArrayType(zeros(Float16, 32, 32)) - NextLA.GEMM_ADD!(A, B, C) - synchronize(C) - @test all(iszero, Array(C)) - end - - # 32 * 200 * 200 is beyond floatmax(Float16): it is Inf, not clamped. - @testset "a Float16 result past floatmax is Inf" begin - A = ArrayType(fill(Float16(200), 32, 32)) - B = ArrayType(fill(Float16(200), 32, 32)) - C = ArrayType(zeros(Float16, 32, 32)) - NextLA.GEMM_ADD!(A, B, C) - synchronize(C) - @test all(isinf, Array(C)) - end - - @testset "adjoint operands" begin - T = ComplexF64 - A, B, C = rand(T, 8, 6), rand(T, 8, 5), rand(T, 6, 5) - Ad, Bd, Cd = ArrayType(copy(A)), ArrayType(copy(B)), ArrayType(copy(C)) - NextLA.GEMM_ADD!(adjoint(Ad), Bd, Cd) - synchronize(Cd) - @test Array(Cd) ≈ C + A' * B rtol=test_rtol(Float64) - end - - @testset "shapes that do not fit throw" begin - @test_throws DimensionMismatch NextLA.GEMM_ADD!(ArrayType(rand(Float32, 8, 3)), - ArrayType(rand(Float32, 5, 8)), - ArrayType(zeros(Float32, 8, 8))) - @test_throws DimensionMismatch NextLA.GEMM_ADD!(ArrayType(rand(Float32, 8, 5)), - ArrayType(rand(Float32, 5, 8)), - ArrayType(zeros(Float32, 4, 4))) - @test_throws DimensionMismatch NextLA.GEMM_SUB!(ArrayType(zeros(Float32, 4, 4)), - ArrayType(rand(Float32, 8, 5)), - ArrayType(rand(Float32, 5, 8))) - end - end -end diff --git a/test/gemm/recgemm.jl b/test/gemm/recgemm.jl deleted file mode 100644 index 69942b95..00000000 --- a/test/gemm/recgemm.jl +++ /dev/null @@ -1,107 +0,0 @@ -# recgemm! over dense destinations, on the CPU backend. - -@testset "RECGEMM [CPU]" begin - # Complex belongs here: the rest of the library is four types wide, and - # recgemm! used to throw InexactError on both complex types because the - # dispatcher steered them into a Float32 accumulation. - @testset "$T" for T in (Float32, Float64, ComplexF32, ComplexF64) - rtol = test_rtol(T) - - @testset "dense C matches A*B, n=$n" for n in [4, 8, 16, 32] - A = rand(T, n, n) - B = rand(T, n, n) - C = rand(T, n, n) - alpha, beta = T(2), T(3) - expected = alpha * A * B + beta * C - - Cout = copy(C) - NextLA.recgemm!(alpha, A, B, beta, Cout) - @test Cout ≈ expected rtol=rtol - end - - @testset "beta=0 overwrites C" begin - n = 8 - A = rand(T, n, n) - B = rand(T, n, n) - C = fill(T(99), n, n) - NextLA.recgemm!(one(T), A, B, zero(T), C) - @test C ≈ A * B rtol=rtol - end - - @testset "alpha=0 scales C only" begin - n = 8 - A = rand(T, n, n) - B = rand(T, n, n) - C = rand(T, n, n) - C0 = copy(C) - NextLA.recgemm!(zero(T), A, B, T(2), C) - @test C ≈ 2 .* C0 rtol=rtol - end - end - - # Float16 takes the other arm of _gemm_dispatch!, through gemmEx!. Its - # absence here is why a missing CPU gemmEx! went unnoticed: the two types - # above both route to gemm!, so nothing in this file reached the arm that - # threw. The reference is in double precision, and the tolerance is - # Float16 storage's rather than the accumulation's. - @testset "Float16 through gemmEx!" begin - @testset "destination $TC" for TC in (Float16, Float32) - n = 16 - A = rand(Float16, n, n) - B = rand(Float16, n, n) - C = zeros(TC, n, n) - NextLA.recgemm!(1.0, A, B, 0.0, C) - @test C ≈ Float64.(A) * Float64.(B) rtol=(TC === Float16 ? 5e-3 : 1e-3) - end - - # the untyped literals recgemm!'s own callers use promote the compute - # type to Float64 over Float16 storage; that combination has to work - @testset "accumulate and subtract" begin - n = 16 - A = rand(Float16, n, n) - B = rand(Float16, n, n) - C0 = rand(Float16, n, n) - C = copy(C0) - NextLA.recgemm!(-1.0, A, B, 1.0, C) - @test C ≈ Float64.(C0) .- Float64.(A) * Float64.(B) rtol=5e-3 - end - end -end - -# A destination wider than both operands: the operands are widened exactly and -# the product is formed in C's type, so the result carries C's precision. -# Computing in the operands' type gave Float32 accuracy on the CPU (relative -# error ~2.5e-7), and cuBLAS refused it with CUBLAS_STATUS_NOT_SUPPORTED. -@testset "RECGEMM C wider than the operands [$backend_name]" for (backend_name, ArrayType, synchronize) in - filter(b -> b[1] in ("CPU", "CUDA", "AMDGPU"), available_backends()) - @testset "$TA, $TB -> $TC" for (TA, TB, TC) in ((Float32, Float32, Float64), - (Float16, Float16, Float64), - (Float16, Float32, Float64), - (ComplexF32, ComplexF32, ComplexF64)) - n = 32 - A, B, C0 = rand(TA, n, n), rand(TB, n, n), rand(TC, n, n) - C = ArrayType(copy(C0)) - NextLA.recgemm!(2, ArrayType(A), ArrayType(B), 3, C) - synchronize(C) - @test Array(C) ≈ 2 .* (TC.(A) * TC.(B)) .+ 3 .* C0 rtol=1e-12 - end -end - -# A destination narrower than the operands. The CPU accumulates at the operands' -# width and rounds once on store; a device rounds the operands to C's type -# first, because cuBLAS refuses Float64 compute into a Float32 C and Float32 -# compute into a Float16 C (CUBLAS_STATUS_NOT_SUPPORTED). -@testset "RECGEMM C narrower than the operands [$backend_name]" for (backend_name, ArrayType, synchronize) in - filter(b -> b[1] in ("CPU", "CUDA", "AMDGPU"), available_backends()) - @testset "$TA, $TB -> $TC" for (TA, TB, TC, rtol) in ((Float64, Float64, Float32, 1e-5), - (Float64, Float32, Float32, 1e-5), - (Float32, Float32, Float16, 1e-2), - (Float32, Float16, Float16, 1e-2)) - n = 32 - A, B, C0 = rand(TA, n, n), rand(TB, n, n), rand(TC, n, n) - C = ArrayType(copy(C0)) - NextLA.recgemm!(2, ArrayType(A), ArrayType(B), 3, C) - synchronize(C) - @test Float64.(Array(C)) ≈ 2 .* (Float64.(A) * Float64.(B)) .+ 3 .* Float64.(C0) rtol=rtol - end -end diff --git a/test/geqr2.jl b/test/geqr2.jl deleted file mode 100644 index 16d9b2a9..00000000 --- a/test/geqr2.jl +++ /dev/null @@ -1,59 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "GEQR2 [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "Unblocked QR m=$m, n=$n" for (m, n) in [ - (0, 0), (1, 1), (10, 8), (20, 15), (32, 32), (50, 30), - ] - k = min(m, n) - A_init = rand(T, m, n) - A_orig = copy(A_init) - A = ArrayType(copy(A_init)) - tau = ArrayType(zeros(T, k)) - work = ArrayType(zeros(T, max(1, n))) - NextLA.geqr2!(m, n, A, tau, work) - synchronize(A) - - if m == 0 || n == 0 - @test size(A) == size(A_orig) - else - A_cpu = Array(A) - tau_cpu = Array(tau) - R = triu(A_cpu[1:k, 1:n]) - Q = Matrix{T}(I, m, m) - LAPACK.ormqr!('L', 'N', A_cpu, tau_cpu, Q) - res = opnorm(A_orig - Q[:, 1:k] * R, 1) / - (opnorm(A_orig, 1) * n * eps(real(T))) - @test res < 10 - orth = opnorm(Q' * Q - I, 1) / (m * eps(real(T))) - @test orth < 10 - end - end - - @testset "Helper matches kernel" begin - m, n = 20, 15 - k = min(m, n) - A_init = rand(T, m, n) - A1 = ArrayType(copy(A_init)) - tau1 = ArrayType(zeros(T, k)) - work = ArrayType(zeros(T, n)) - NextLA.geqr2!(m, n, A1, tau1, work) - synchronize(A1) - - A2 = ArrayType(copy(A_init)) - tau2 = ArrayType(zeros(T, k)) - NextLA.geqr2!(A2, tau2) - synchronize(A2) - - @test Array(A1) ≈ Array(A2) rtol=rtol - @test Array(tau1) ≈ Array(tau2) rtol=rtol - end - end - end -end - -@testset "GEQR2 Error handling" begin - @test_throws ArgumentError NextLA.geqr2!(-1, 5, zeros(5, 5), zeros(5), zeros(5)) - @test_throws ArgumentError NextLA.geqr2!(5, -1, zeros(5, 5), zeros(5), zeros(5)) -end diff --git a/test/geqrt.jl b/test/geqrt.jl deleted file mode 100644 index fbacaa57..00000000 --- a/test/geqrt.jl +++ /dev/null @@ -1,105 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "GEQRT [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "Blocked QR m=$m, n=$n, ib=$ib" for (m, n, ib) in [ - (20, 15, 4), - (32, 32, 8), - (64, 32, 16), - (32, 64, 8), - ] - k = min(m, n) - A_init = rand(T, m, n) - A_orig = copy(A_init) - A = ArrayType(copy(A_init)) - Tm = ArrayType(zeros(T, ib, k)) - tau = ArrayType(zeros(T, k)) - work = ArrayType(zeros(T, ib * n)) - NextLA.geqrt!(m, n, ib, A, Tm, tau, work) - synchronize(A) - - A_cpu = Array(A) - tau_cpu = Array(tau) - R = triu(A_cpu[1:k, 1:n]) - Q = Matrix{T}(I, m, m) - LAPACK.ormqr!('L', 'N', A_cpu, tau_cpu, Q) - res = opnorm(A_orig - Q[:, 1:k] * R, 1) / - (opnorm(A_orig, 1) * n * eps(real(T))) - @test res < 10 - orth = opnorm(Q' * Q - I, 1) / (m * eps(real(T))) - @test orth < 10 - end - - @testset "Helper matches kernel" begin - m, n, ib = 32, 24, 8 - k = min(m, n) - A_init = rand(T, m, n) - A1 = ArrayType(copy(A_init)) - Tm1 = ArrayType(zeros(T, ib, k)) - NextLA.geqrt!(A1, Tm1) - synchronize(A1) - - A2 = ArrayType(copy(A_init)) - Tm2 = ArrayType(zeros(T, ib, k)) - tau = ArrayType(zeros(T, k)) - work = ArrayType(zeros(T, ib * n)) - NextLA.geqrt!(m, n, ib, A2, Tm2, tau, work) - synchronize(A2) - - @test Array(A1) ≈ Array(A2) rtol=rtol - @test Array(Tm1) ≈ Array(Tm2) rtol=rtol - end - - @testset "ib=1 matches unblocked" begin - m, n = 16, 12 - A_init = rand(T, m, n) - A_blocked = ArrayType(copy(A_init)) - Tm = ArrayType(zeros(T, 1, min(m, n))) - tau_b = ArrayType(zeros(T, min(m, n))) - work_b = ArrayType(zeros(T, n)) - NextLA.geqrt!(m, n, 1, A_blocked, Tm, tau_b, work_b) - synchronize(A_blocked) - - A_unblocked = ArrayType(copy(A_init)) - tau_u = ArrayType(zeros(T, min(m, n))) - work_u = ArrayType(zeros(T, n)) - NextLA.geqr2!(m, n, A_unblocked, tau_u, work_u) - synchronize(A_unblocked) - - @test Array(A_blocked) ≈ Array(A_unblocked) rtol=rtol - end - end - end -end - -@testset "GEQRT Error handling" begin - @test_throws ArgumentError NextLA.geqrt!(-1, 5, 2, zeros(5, 5), zeros(2, 5), zeros(5), zeros(10)) - @test_throws ArgumentError NextLA.geqrt!(5, -1, 2, zeros(5, 5), zeros(2, 5), zeros(5), zeros(10)) - @test_throws ArgumentError NextLA.geqrt!(5, 5, -1, zeros(5, 5), zeros(2, 5), zeros(5), zeros(10)) - @test_throws ArgumentError NextLA.geqrt!(5, 5, 0, zeros(5, 5), zeros(2, 5), zeros(5), zeros(10)) -end - -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "GEQRT Deterministic [$backend_name]" begin - m, n, ib = 20, 15, 4 - k = min(m, n) - A_init = rand(ComplexF64, m, n) - A1 = ArrayType(copy(A_init)) - Tm1 = ArrayType(zeros(ComplexF64, ib, k)) - tau1 = ArrayType(zeros(ComplexF64, k)) - work1 = ArrayType(zeros(ComplexF64, ib * n)) - NextLA.geqrt!(m, n, ib, A1, Tm1, tau1, work1) - synchronize(A1) - - A2 = ArrayType(copy(A_init)) - Tm2 = ArrayType(zeros(ComplexF64, ib, k)) - tau2 = ArrayType(zeros(ComplexF64, k)) - work2 = ArrayType(zeros(ComplexF64, ib * n)) - NextLA.geqrt!(m, n, ib, A2, Tm2, tau2, work2) - synchronize(A2) - - @test Array(A1) ≈ Array(A2) - @test Array(Tm1) ≈ Array(Tm2) - end -end diff --git a/test/gerc.jl b/test/gerc.jl deleted file mode 100644 index 9ec1dccd..00000000 --- a/test/gerc.jl +++ /dev/null @@ -1,38 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "GERC [$backend_name]" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - - @testset "m=$m, n=$n" for (m, n) in [ - (0, 0), (1, 1), (2, 3), (5, 4), (10, 8), (50, 40), - ] - α = T(0.7, 0.3) - x = ArrayType(rand(T, m)) - y = ArrayType(rand(T, n)) - A = ArrayType(rand(T, m, n)) - A_init = Array(A) - - NextLA.gerc!(α, x, y, A) - synchronize(A) - - if m == 0 || n == 0 - @test Array(A) == A_init - else - @test Array(A) ≈ A_init .+ α .* Array(x) * Array(y)' rtol=rtol - end - end - - @testset "α=0 leaves A unchanged" begin - A = ArrayType(rand(T, 5, 4)) - A0 = Array(A) - NextLA.gerc!(zero(T), ArrayType(rand(T, 5)), ArrayType(rand(T, 4)), A) - synchronize(A) - @test Array(A) == A0 - end - end - end -end - -@testset "GERC Error handling" begin - @test_throws ArgumentError NextLA.gerc!(1.0+0im, ComplexF64[1], ComplexF64[1,2], zeros(ComplexF64, 2, 2)) -end diff --git a/test/gpu_backends.jl b/test/gpu_backends.jl deleted file mode 100644 index 53d3b397..00000000 --- a/test/gpu_backends.jl +++ /dev/null @@ -1,93 +0,0 @@ -using KernelAbstractions - -""" - supports_float64(ArrayType) - -Whether `ArrayType`'s device can hold `Float64`, decided by trying it. - -Double precision is a property of the part and its driver, not of the vendor -library: Intel's data-center GPUs support it, consumer integrated graphics -generally do not, and `oneArray(::Matrix{Float64})` throws rather than falling -back. So this asks the device instead of assuming anything about the backend. -""" -function supports_float64(ArrayType) - try - # invokelatest for the same reason as the functional() call below: the - # backend package is loaded dynamically, so its constructors are too - # new for this world age and a direct call raises MethodError. - Base.invokelatest(ArrayType, zeros(Float64, 1, 1)) - return true - catch e - get(ENV, "NEXTLA_GPU_DEBUG", "0") == "1" && - @warn "$ArrayType: no Float64 support — $(sprint(showerror, e))" - return false - end -end - -""" - available_gpu_backends() - -Returns a vector of (name, ArrayType, synchronize_fn) for GPU backends that are -loadable and functional. Uses try/catch to skip backends that are not installed. - -Synchronize_fn is a function that takes a GPU array and synchronizes its backend: - sync(arr) = KernelAbstractions.synchronize(KernelAbstractions.get_backend(arr)) -""" -function available_gpu_backends() - backends = Tuple{String, Type, Function}[] - backend_defs = [ - ("CUDA", :CUDA, :CuArray, :functional), - ("AMDGPU", :AMDGPU, :ROCArray, :functional), - ("oneAPI", :oneAPI, :oneArray, :functional), - ("Metal", :Metal, :MtlArray, :functional), - ] - debug = get(ENV, "NEXTLA_GPU_DEBUG", "0") == "1" - for (name, pkg_sym, array_sym, func_sym) in backend_defs - try - # Load package - fails if not installed; require returns the module - pkg = Base.require(Main, pkg_sym) - # Check if backend is functional (GPU available) - # invokelatest avoids "method too new" world-age errors when loading packages dynamically - if Base.invokelatest(getproperty(pkg, func_sym)) - AT = getproperty(pkg, array_sym) - # This suite is written in double precision throughout, and - # NextLA does not currently run on a device without it. Leave - # such backends out rather than erroring on every case; see - # KNOWN_ISSUES.md for what supporting them would involve. - if !supports_float64(AT) - debug && @warn "$name: no Float64 on this device, backend skipped" - continue - end - sync_fn = function(arr) - KernelAbstractions.synchronize(KernelAbstractions.get_backend(arr)) - end - push!(backends, (name, AT, sync_fn)) - elseif debug - @warn "$name: functional() returned false (no GPU or driver issue)" - end - catch e - debug && @warn "$name: $(sprint(showerror, e))" - continue - end - end - return backends -end - -""" - available_backends() - -Returns a vector of (name, ArrayType, synchronize_fn) for all available backends, -including CPU first, then any functional GPU backends. Ensures tests always run -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)) - # Add GPU backends - for (name, AT, sync) in available_gpu_backends() - push!(backends, (name, AT, sync)) - end - return backends -end - diff --git a/test/larf.jl b/test/larf.jl deleted file mode 100644 index e9bc2f3a..00000000 --- a/test/larf.jl +++ /dev/null @@ -1,53 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LARF [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "side=$side, m=$m, n=$n" for side in ['L', 'R'], - (m, n) in [(1, 1), (5, 4), (10, 8), (20, 15)] - v_len = side == 'L' ? m : n - C_init = randn(T, m, n) - C_orig = copy(C_init) - v = ArrayType(randn(T, v_len)) - tau = randn(T) - work = ArrayType(zeros(T, side == 'L' ? n : m)) - C = ArrayType(copy(C_init)) - - NextLA.larf!(side, m, n, v, 1, tau, C, work) - synchronize(C) - - v_cpu = Array(v) - H = I - tau * (v_cpu * v_cpu') - C_ref = side == 'L' ? H * C_orig : C_orig * H - @test Array(C) ≈ C_ref rtol=rtol - end - - @testset "Helper matches kernel" begin - m, n = 10, 8 - C_init = randn(T, m, n) - v = ArrayType(randn(T, m)) - tau = randn(T) - C1 = ArrayType(copy(C_init)) - work = ArrayType(zeros(T, n)) - NextLA.larf!('L', m, n, v, 1, tau, C1, work) - synchronize(C1) - - C2 = ArrayType(copy(C_init)) - NextLA.larf!('L', v, 1, tau, C2) - synchronize(C2) - - @test Array(C1) ≈ Array(C2) rtol=rtol - end - - @testset "τ=0 leaves C unchanged" begin - C_init = randn(T, 6, 5) - C = ArrayType(copy(C_init)) - v = ArrayType(randn(T, 6)) - work = ArrayType(zeros(T, 5)) - NextLA.larf!('L', 6, 5, v, 1, zero(T), C, work) - synchronize(C) - @test Array(C) == C_init - end - end - end -end diff --git a/test/larfb.jl b/test/larfb.jl deleted file mode 100644 index 12055fa9..00000000 --- a/test/larfb.jl +++ /dev/null @@ -1,110 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LARFB [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "side=$side, trans=$trans, m=$m, n=$n" for - side in ['L', 'R'], - trans in ['N', 'C'], - (m, n) in [(5, 4), (10, 8), (20, 15)] - - k = min(side == 'L' ? m : n, 4) - panel_rows = side == 'L' ? m : n - - panel = randn(T, panel_rows, k) - tau_vec = zeros(T, k) - qr_work = zeros(T, k) - NextLA.geqr2!(panel_rows, k, panel, tau_vec, qr_work) - - V_init = copy(panel) - for j in 1:k - for i in 1:j-1 - V_init[i, j] = zero(T) - end - V_init[j, j] = one(T) - end - T_mat_init = zeros(T, k, k) - NextLA.larft!('F', 'C', panel_rows, k, V_init, tau_vec, T_mat_init) - - V = ArrayType(copy(V_init)) - T_mat = ArrayType(copy(T_mat_init)) - C_init = randn(T, m, n) - C_orig = copy(C_init) - C = ArrayType(copy(C_init)) - - NextLA.larfb!(side, trans, 'F', 'C', V, T_mat, C) - synchronize(C) - - I_mat = Matrix{T}(I, panel_rows, panel_rows) - H = I_mat - V_init * T_mat_init * V_init' - Ht = trans == 'N' ? H : H' - C_ref = side == 'L' ? Ht * C_orig : C_orig * Ht - @test Array(C) ≈ C_ref rtol=rtol * max(1, m, n) - end - - @testset "Roundtrip H then Hᴴ" begin - m, n, k = 12, 10, 3 - panel = randn(T, m, k) - tau_vec = zeros(T, k) - qr_work = zeros(T, k) - NextLA.geqr2!(m, k, panel, tau_vec, qr_work) - V_init = copy(panel) - for j in 1:k - for i in 1:j-1; V_init[i, j] = zero(T); end - V_init[j, j] = one(T) - end - T_mat_init = zeros(T, k, k) - NextLA.larft!('F', 'C', m, k, V_init, tau_vec, T_mat_init) - - V = ArrayType(copy(V_init)) - T_mat = ArrayType(copy(T_mat_init)) - C_init = randn(T, m, n) - C_orig = copy(C_init) - C = ArrayType(copy(C_init)) - - NextLA.larfb!('L', 'N', 'F', 'C', V, T_mat, C) - synchronize(C) - NextLA.larfb!('L', 'C', 'F', 'C', V, T_mat, C) - synchronize(C) - - @test Array(C) ≈ C_orig rtol=rtol * m - end - - @testset "Helper matches kernel" begin - m, n, k = 10, 8, 3 - panel = randn(T, m, k) - tau_vec = zeros(T, k) - qr_work = zeros(T, k) - NextLA.geqr2!(m, k, panel, tau_vec, qr_work) - V_init = copy(panel) - for j in 1:k - for i in 1:j-1; V_init[i, j] = zero(T); end - V_init[j, j] = one(T) - end - T_mat_init = zeros(T, k, k) - NextLA.larft!('F', 'C', m, k, V_init, tau_vec, T_mat_init) - - V = ArrayType(copy(V_init)) - T_mat = ArrayType(copy(T_mat_init)) - C_init = randn(T, m, n) - C1 = ArrayType(copy(C_init)) - work = ArrayType(zeros(T, n, k)) - NextLA.larfb!('L', 'N', 'F', 'C', m, n, k, V, m, T_mat, C1, work) - synchronize(C1) - - C2 = ArrayType(copy(C_init)) - NextLA.larfb!('L', 'N', 'F', 'C', V, T_mat, C2) - synchronize(C2) - - @test Array(C1) ≈ Array(C2) rtol=rtol - end - end - end -end - -@testset "LARFB Edge cases" begin - @test_nowarn NextLA.larfb!('L', 'N', 'F', 'C', 0, 0, 0, - zeros(0, 0), 1, zeros(0, 0), zeros(0, 0), zeros(0, 0)) - @test_nowarn NextLA.larfb!('L', 'N', 'F', 'C', 5, 5, 0, - zeros(5, 0), 5, zeros(0, 0), randn(5, 5), zeros(5, 0)) -end diff --git a/test/larfg.jl b/test/larfg.jl deleted file mode 100644 index bd475df8..00000000 --- a/test/larfg.jl +++ /dev/null @@ -1,79 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LARFG [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "n=$n" for n in [1, 2, 5, 10, 50] - alpha = randn(T) - x = randn(T, n - 1) - x_test = ArrayType(copy(x)) - - alpha_out, tau = NextLA.larfg!(n, alpha, x_test, 1, zero(T)) - synchronize(x_test) - - orig_norm = sqrt(abs(alpha)^2 + norm(x)^2) - @test abs(alpha_out) ≈ orig_norm rtol=rtol - - if n > 1 - x_cpu = Array(x_test) - v = vcat(one(T), x_cpu) - H = Matrix{T}(I, n, n) - tau * (v * v') - result = H' * vcat(alpha, x) - @test abs(result[1]) ≈ abs(alpha_out) rtol=rtol - @test norm(result[2:end]) < rtol * orig_norm + eps(real(T)) - end - - @test isfinite(alpha_out) - @test isfinite(tau) - end - - @testset "Convenience interface" begin - alpha = randn(T) - x = ArrayType(randn(T, 4)) - alpha2, tau2 = NextLA.larfg!(alpha, x, 1, zero(T)) - synchronize(x) - @test isfinite(alpha2) - @test isfinite(tau2) - end - end - end -end - -@testset "LARFG Edge cases" begin - for T in TEST_TYPES - a, t = NextLA.larfg!(1, T(3), T[], 1, zero(T)) - @test t == zero(T) - @test a == T(3) - a, t = NextLA.larfg!(0, T(1), T[], 1, zero(T)) - @test t == zero(T) - if T <: Real - a, t = NextLA.larfg!(3, T(5), zeros(T, 2), 1, zero(T)) - @test t == zero(T) - end - end -end - -for T in (ComplexF32, ComplexF64, Float32, Float64) - for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LARFG LAPACK $T [$backend_name]" begin - rtol = test_rtol(T) - for n in [2, 5, 10] - alpha = randn(T) - x = randn(T, n - 1) - x_nla = ArrayType(copy(x)) - a_nla, tau_nla = NextLA.larfg!(n, alpha, x_nla, 1, zero(T)) - synchronize(x_nla) - - lapack_vec = vcat([alpha], x) - tau_ref, a_ref = lapack_larfg!(lapack_vec) - x_ref = lapack_vec[2:end] - - @test abs(a_nla) ≈ abs(a_ref) rtol=rtol - @test abs(tau_nla) ≈ abs(tau_ref) rtol=rtol - if n > 1 - @test norm(abs.(Array(x_nla)) .- abs.(x_ref)) < rtol * max(1.0, norm(x_ref)) - end - end - end - end - end diff --git a/test/larft.jl b/test/larft.jl deleted file mode 100644 index f0a9045b..00000000 --- a/test/larft.jl +++ /dev/null @@ -1,86 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LARFT [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "direct=$direct, storev=$storev, n=$n, k=$k" for - direct in ['F'], - storev in ['C', 'R'], - (n, k) in [(1, 1), (5, 3), (10, 4), (20, 8)] - - if storev == 'C' - V_init = randn(T, n, k) - for j in 1:k - for i in 1:j-1 - V_init[i, j] = zero(T) - end - V_init[j, j] = one(T) - end - else - V_init = randn(T, k, n) - for i in 1:k - for j in 1:i-1 - V_init[i, j] = zero(T) - end - V_init[i, i] = one(T) - end - end - tau = ArrayType(randn(T, k)) - V = ArrayType(copy(V_init)) - T_mat = ArrayType(zeros(T, k, k)) - - NextLA.larft!(direct, storev, n, k, V, tau, T_mat) - synchronize(T_mat) - - T_cpu = Array(T_mat) - @test T_cpu ≈ UpperTriangular(T_cpu) - tau_cpu = Array(tau) - for i in 1:k - @test T_cpu[i, i] ≈ tau_cpu[i] - end - - V_cpu = Array(V) - if storev == 'C' - H_compact = Matrix{T}(I, n, n) - V_cpu * T_cpu * V_cpu' - else - H_compact = Matrix{T}(I, n, n) - V_cpu' * T_cpu * V_cpu - end - H_true = Matrix{T}(I, n, n) - for j in 1:k - if storev == 'C' - vj = V_cpu[:, j] - Hj = I - tau_cpu[j] * (vj * vj') - else - vj = V_cpu[j, :] - Hj = I - tau_cpu[j] * (conj(vj) * transpose(vj)) - end - H_true = direct == 'F' ? H_true * Hj : Hj * H_true - end - err = norm(H_compact - H_true) / max(1.0, norm(H_true)) - @test err < rtol * n - end - - @testset "Helper matches kernel" begin - n, k = 10, 4 - V_init = randn(T, n, k) - tau = ArrayType(randn(T, k)) - V = ArrayType(copy(V_init)) - T1 = ArrayType(zeros(T, k, k)) - NextLA.larft!('F', 'C', n, k, V, tau, T1) - synchronize(T1) - - V2 = ArrayType(copy(V_init)) - T2 = ArrayType(zeros(T, k, k)) - NextLA.larft!('F', 'C', V2, tau, T2) - synchronize(T2) - - @test Array(T1) ≈ Array(T2) rtol=rtol - end - end - end -end - -@testset "LARFT Edge cases" begin - T_mat = ones(2, 2) - @test_nowarn NextLA.larft!('F', 'C', 0, 2, zeros(0, 2), zeros(2), T_mat) -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/lu.jl b/test/lu.jl deleted file mode 100644 index b1b21bfc..00000000 --- a/test/lu.jl +++ /dev/null @@ -1,141 +0,0 @@ -@testset "lu! with varing pivot" begin - for T in [Float32, Float64, ComplexF32, ComplexF64] - for pivot in [NoPivot(), RowNonZero(), CompletePivoting()] - for m in [10, 100, 1000] - for n in [m, div(m,10)*9, div(m,10)*11] - # Use smaller matrices for Float32 to avoid numerical issues - - # Better conditioning for rectangular matrices - params = parameter_creation("GE", 3, 100, 100) - A = matrix_generation(T, m, n; - mode=params.mode, - cndnum=params.cndnum, - anorm=params.anorm, - kl=params.kl, - ku=params.ku) - - B = deepcopy(A) - DLA_A = NextLAMatrix{T}(A) - F = LinearAlgebra.lu!(DLA_A, pivot) - m, n = size(F.factors) - L = tril(F.factors[1:m, 1:min(m,n)]) - for i in 1:min(m,n); L[i,i] = 1 end - U = triu(F.factors[1:min(m,n), 1:n]) - p = LinearAlgebra.ipiv2perm(F.ipiv,m) - q = LinearAlgebra.ipiv2perm(F.jpiv, n) - - # Calculate relative error - reconstructed = L * U - original = B[p, q] - @test L * U ≈ B[p, q] - @test norm(reconstructed) ≈ norm(original) - @test norm(reconstructed - original) / norm(original) ≈ 0.0 atol=1e-6 - end - end - end - end -end - -@testset "lu generic_lufact!" begin - for T in [Float32, Float64, ComplexF32, ComplexF64] - for pivot in [NoPivot(), RowNonZero(), RowMaximum(), CompletePivoting()] - for m in [10, 100, 1000] - for n in [m, div(m,10)*9, div(m,10)*11] - params = parameter_creation("GE", 3, 100, 100) - A = matrix_generation(T, m, n; - mode=params.mode, - cndnum=params.cndnum, - anorm=params.anorm, - kl=params.kl, - ku=params.ku) - B = deepcopy(A) - DLA_A = NextLAMatrix{T}(A) - F =LinearAlgebra.generic_lufact!(DLA_A, pivot) - m, n = size(F.factors) - L = tril(F.factors[1:m, 1:min(m,n)]) - for i in 1:min(m,n); L[i,i] = 1 end - U = triu(F.factors[1:min(m,n), 1:n]) - p = LinearAlgebra.ipiv2perm(F.ipiv,m) - q = LinearAlgebra.ipiv2perm(F.jpiv, n) - @test L * U ≈ B[p, q] - @test norm(L * U) ≈ norm(B[p, q]) - end - end - end - end -end - -@testset "lu! default RowMaximum()" begin - for T in [Float32, Float64, ComplexF32, ComplexF64] - for m in [10, 100, 1000] - for n in [m, div(m,10)*9, div(m,10)*11] - params = parameter_creation("GE", 3, 100, 100) - A = matrix_generation(T, m, n; - mode=params.mode, - cndnum=params.cndnum, - anorm=params.anorm, - kl=params.kl, - ku=params.ku) - B = deepcopy(A) - DLA_A = NextLAMatrix{T}(A) - F =LinearAlgebra.lu!(DLA_A) - m, n = size(F.factors) - L = tril(F.factors[1:m, 1:min(m,n)]) - for i in 1:min(m,n); L[i,i] = 1 end - U = triu(F.factors[1:min(m,n), 1:n]) - p = LinearAlgebra.ipiv2perm(F.ipiv,m) - @test L * U ≈ B[p, :] - @test norm(L * U) ≈ norm(B[p, :]) - end - end - end -end - -# getrf2! reports through its return value, on every path. -# -# Each early exit used to `return` bare, so the caller's -# `A, ipiv, info = getrf2!(...)` raised MethodError: no method matching -# iterate(::Nothing) -- a 0-by-0 input was enough. The two singular paths also -# wrote `info[] = 1` to an Int, which is a MethodError of its own, and the two -# recursive calls dropped the info they computed, so a singular block never -# reached the caller. -@testset "getrf2! returns (A, ipiv, info) on every path" begin - for T in (Float64, ComplexF64) - # quick return: the path that crashed the caller - A = zeros(T, 0, 0) - Af, ipiv, info = NextLA.getrf2!(A, Int[], 0) - @test Af === A - @test info == 0 - - # m == 1 with a zero pivot: singular, reported through info - A = zeros(T, 1, 1) - _, _, info = NextLA.getrf2!(A, Vector{Int}(undef, 1), 0) - @test info == 1 - - # n == 1, all zero: the other single-column exit - A = zeros(T, 4, 1) - _, _, info = NextLA.getrf2!(A, Vector{Int}(undef, 1), 0) - @test info == 1 - - # a singular block inside the recursion: info is the failing column, - # offset by the split, not lost - A = T[1 0; 0 0] - _, _, info = NextLA.getrf2!(A, Vector{Int}(undef, 2), 0) - @test info == 2 - - # and a non-singular matrix still factors, with info == 0 - A0 = T[4 1; 1 3] - A = copy(A0) - Af, ipiv, info = NextLA.getrf2!(A, Vector{Int}(undef, 2), 0) - @test info == 0 - L = UnitLowerTriangular(Af) - U = UpperTriangular(Af) - @test L * U ≈ A0[LinearAlgebra.ipiv2perm(ipiv, 2), :] - - # the caller reports it as LAPACK does rather than crashing - F = LinearAlgebra.lu!(NextLAMatrix{T}(T[1 0; 0 0]), RowMaximum(); check=false) - @test F.info == 2 - @test_throws LinearAlgebra.SingularException LinearAlgebra.lu!( - NextLAMatrix{T}(T[1 0; 0 0]), RowMaximum()) - end -end diff --git a/test/lu/lu_factor.jl b/test/lu/lu_factor.jl deleted file mode 100644 index 455526e2..00000000 --- a/test/lu/lu_factor.jl +++ /dev/null @@ -1,93 +0,0 @@ -# Both routines pack L and U into A and return the row permutation as a vector -# p, with A₀[p, :] == L*U, and LAPACK's info: 0, or the first zero pivot. -# -# lu_base! runs on every backend. tile_lu_factor! is GPU-only: it is correct on -# CUDA and returns wrong numbers on the CPU backend, so it refuses there. See -# KNOWN_ISSUES.md. - -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "LU_BASE [$backend_name]" begin - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "n=$n" for n in [4, 8, 16, 32] - # diagonally dominant: well conditioned, and the pivoting has - # something to do without being pathological - A0 = rand(T, n, n) + T(n) * I - Ad = ArrayType(copy(A0)) - - Af, p, info = NextLA.lu_base!(Ad) - synchronize(Af) - - A = Array(Af) - L = UnitLowerTriangular(A) - U = UpperTriangular(A) - @test info == 0 - @test p isa Vector{Int} && sort(p) == 1:n - @test norm(A0[p, :] - L * U) / norm(A0) < rtol - end - end - end -end - -@testset "TILE_LU_FACTOR [GPU]" begin - gpus = available_gpu_backends() - if isempty(gpus) - @test_skip "no GPU backend available" - end - - for (backend_name, ArrayType, synchronize) in gpus - @testset "[$backend_name] $T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "N=$N tile=$tile" for (N, tile) in [ - (16, 4), (16, 8), (32, 8), (64, 16), - ] - A0 = rand(T, N, N) + T(N) * I - Ad = ArrayType(copy(A0)) - - Af, p, info = NextLA.tile_lu_factor!(Ad, tile) - synchronize(Af) - - A = Array(Af) - L = UnitLowerTriangular(A) - U = UpperTriangular(A) - @test info == 0 - @test p isa Vector{Int} && sort(p) == 1:N - @test norm(A0[p, :] - L * U) / norm(A0) < rtol - end - end - end - - # The CPU path is wrong rather than merely unsupported, so it refuses - # instead of returning plausible numbers. Guard the guard. - @testset "refuses the CPU backend" begin - A = rand(Float64, 16, 16) + 16I - @test_throws ArgumentError NextLA.tile_lu_factor!(A, 4) - end - - @testset "a work-group past 32 x 32 is refused on a GPU" begin - for (name, AT, _) in available_gpu_backends() - @test_throws ArgumentError NextLA.lu_base!(AT(rand(Float64, 33, 33) + 33I)) - @test_throws ArgumentError NextLA.tile_lu_factor!(AT(rand(Float64, 66, 66) + 66I), 33) - break - end - end - - @testset "a zero pivot is reported through info" begin - for (name, AT, _) in available_gpu_backends() - @test NextLA.lu_base!(AT(zeros(Float64, 4, 4)))[3] == 1 - @test NextLA.tile_lu_factor!(AT(zeros(Float64, 8, 8)), 4)[3] == 1 - break - end - @test NextLA.lu_base!(zeros(Float64, 4, 4))[3] == 1 - end - - @testset "tile size must divide the matrix" begin - for (name, AT, _) in available_gpu_backends() - A = AT(rand(Float64, 16, 16) + 16I) - @test_throws ArgumentError NextLA.tile_lu_factor!(A, 5) - break - end - end -end diff --git a/test/lu/reclu.jl b/test/lu/reclu.jl deleted file mode 100644 index 0ddb1ba5..00000000 --- a/test/lu/reclu.jl +++ /dev/null @@ -1,112 +0,0 @@ -# Recursive LU, splitting into a 2x2 block scheme and driving the updates -# through unified_rectrxm! and recgemm!. -# -# Diagonally dominant input for the sweeps. The recursion is unpivoted, leaves -# included, so a general random matrix can fail for mathematical reasons rather -# than a defect. The leaf used to be a pivoted lu! whose pivots were dropped; a -# matrix that has an unpivoted LU without being diagonally dominant is kept -# below so that regression is named. -# -# CPU only for the mixed-precision method: the containers index scalar-wise on -# the host, the limitation recorded for src/mxp/. Float32-only containers, since -# a Float16 block carries a scale factor getindex never applies. - -@testset "RECLU [CPU]" begin - @testset "$T" for T in (Float32, Float64) - rtol = T === Float32 ? 1e-4 : 1e-10 - - @testset "lu_recursive! n=$n block=$bs" for - n in [32, 64, 128], - bs in [16, 32] - - A0 = rand(T, n, n) + T(2n) * I - A = copy(A0) - NextLA.lu_recursive!(A, bs) - @test norm(UnitLowerTriangular(A) * UpperTriangular(A) - A0) / norm(A0) < rtol - end - - # The rectangular sibling. Square shapes are here so the two can be - # compared directly; the rest are the shapes lu_recursive! cannot take. - @testset "lu_recursive_nopiv! $(m)x$(n) block=$bs" for - (m, n) in [(64, 64), (128, 64), (64, 128), (100, 60), (48, 200)], - bs in [16, 32] - - k = min(m, n) - A0 = rand(T, m, n) - A0[1:k, 1:k] += T(2 * max(m, n)) * I # needs no pivoting - A = copy(A0) - NextLA.lu_recursive_nopiv!(A, bs) - - # L is unit lower trapezoidal, U upper trapezoidal, both packed in A. - L = m >= n ? [UnitLowerTriangular(A[1:k, 1:k]); A[(k + 1):m, 1:k]] : - Matrix(UnitLowerTriangular(A[1:k, 1:k])) - U = m >= n ? Matrix(UpperTriangular(A[1:k, 1:k])) : - [UpperTriangular(A[1:k, 1:k]) A[1:k, (k + 1):n]] - @test norm(L * U - A0) / norm(A0) < rtol - end - - # A wide matrix is where the branch's own split (n ÷ 2) walked off the - # top of the matrix. Kept as its own case so the regression is named. - @testset "wide matrix does not overrun its rows" begin - A = rand(T, 48, 200) - A[1:48, 1:48] += T(400) * I - @test NextLA.lu_recursive_nopiv!(copy(A), 32) isa AbstractMatrix - end - - @testset "rejects a block_size below one" begin - @test_throws ArgumentError NextLA.lu_recursive_nopiv!(rand(T, 8, 8), 0) - @test_throws ArgumentError NextLA.lu_recursive!(rand(T, 8, 8), 0) - end - - @testset "lu_recursive! rejects a non-square matrix" begin - @test_throws DimensionMismatch NextLA.lu_recursive!(rand(T, 8, 6), 4) - end - - # Leading minors all nonzero, so the unpivoted LU exists, but the first - # column's largest entry is off the diagonal: a pivoted leaf swaps rows. - @testset "the leaf does not pivot, block=$bs" for bs in (1, 2, 4) - A0 = T[1 2 3 4; 4 1 2 3; 3 4 1 2; 2 3 4 1] - A = copy(A0) - @test NextLA.lu_recursive!(A, bs) === A - @test norm(UnitLowerTriangular(A) * UpperTriangular(A) - A0) / norm(A0) < rtol - B = copy(A0) - NextLA.lu_recursive_nopiv!(B, bs) - @test norm(UnitLowerTriangular(B) * UpperTriangular(B) - A0) / norm(A0) < rtol - end - - @testset "a zero pivot throws ZeroPivotException" begin - @test_throws ZeroPivotException NextLA.lu_recursive!(T[0 1; 1 0], 2) - end - end -end - -# The leaf on the GPU backends that serve it: cuSOLVER through lu! on CUDA, and -# rocSOLVER through ext/amdgpu/lu.jl on AMDGPU, where lu! never reaches it. The -# recursion hands the leaf views, which the AMDGPU method factors in a copy. -@testset "RECLU leaf on the GPU [$backend_name]" for (backend_name, ArrayType, synchronize) in - filter(b -> b[1] in ("CUDA", "AMDGPU"), available_backends()) - @testset "$T n=$n block=$bs" for T in (Float32, Float64), n in [64, 128], bs in [16, 32] - rtol = T === Float32 ? 1e-4 : 1e-10 - A0 = rand(T, n, n) + T(2n) * I - A = ArrayType(A0) - NextLA.lu_recursive!(A, bs) - synchronize(A) - F = Array(A) - @test norm(UnitLowerTriangular(F) * UpperTriangular(F) - A0) / norm(A0) < rtol - end - - # getrf! used to return quietly here and let Inf/NaN spread; the leaf raises. - @testset "a zero pivot raises" begin - A = ArrayType(zeros(Float32, 16, 16)) - @test_throws ZeroPivotException NextLA.lu_recursive!(A, 32) - end - - @testset "the leaf does not pivot" begin - A0 = [1.0 2 3 4; 4 1 2 3; 3 4 1 2; 2 3 4 1] - A = ArrayType(copy(A0)) - NextLA.lu_recursive!(A, 4) - synchronize(A) - F = Array(A) - @test norm(UnitLowerTriangular(F) * UpperTriangular(F) - A0) / norm(A0) < 1e-12 - end -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..ddf61016 --- /dev/null +++ b/test/mxp/blas/gemm/recgemm_mixedprec.jl @@ -0,0 +1,360 @@ +# recgemm! into a FullMixedPrec destination (src/mxp/blas/gemm/recgemm_mixedprec.jl), against Float64 BLAS. + +test_params(n = "order of C", k = "inner dimension") # the number options it takes (--params) + +const MXP_GEMM_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[Float16, Float32, Float64], + DataType[Float16, Float16, Float32, Float64]) + +# Per element (Higham 2002, eq. 3.13, plus one rounding on store): |R - ref| <= u(E)(|ref| + mag) + (k+1)u(W)mag + eta(E), +# with mag = |alpha||A||B| + |beta||C0|, E each element's storage type and W = E but at least Float32. +# Inputs rounded before the product add at most 2u(Float16)·mag: operands S wider than a Float16 block are rounded to +# Float16, and with tf32 a Float32 element's Float32 x Float32 product may use TF32 (inputs to a 10-bit fraction). +_recgemm_ok(R, ref, mag, E, k; S=Float16, tf32=false) = (R = Array(R); all(abs(Float64(R[i]) - ref[i]) <= mxp_u(E[i]) * (abs(ref[i]) + mag[i]) + + (k + 1) * mxp_u(promote_type(E[i], Float32)) * mag[i] + 2mxp_eta(E[i]) + _recgemm_rounded(E[i], S, tf32) * mag[i] + for i in eachindex(ref))) # 2η: C0 is rounded when stored and again on store +_recgemm_rounded(E, S, tf32) = ((E == Float16 && sizeof(S) > 2) || (tf32 && E == Float32)) ? 2mxp_u(Float16) : 0.0 +# TF32 runs only on CUDA, and only when the container's top-level blocks are narrow (src/mxp/core/blocks.jl). +_rg_tf32(name, C) = name == "CUDA" && MixedPrecision._top_narrow(C) + +# Relative error of each block in `blocks` (row and column ranges). +_recgemm_block_errs(R, ref, blocks) = [mxp_relerr(R[I, J], ref[I, J]) for (I, J) in blocks] + +@testset "RECGEMM mixed precision [$name]" for (name, AT, _) in MXP_BACKENDS + @testset "$S input, precisions=$P, n=$n, k=$k" for P in test_precisions(MXP_GEMM_PRECISIONS), + S in backend_types(AT, (Float16, Float32, Float64)), n in test_values(:n, (1, 2, 5, 13, 16)), k in test_values(:k, (1, 7, 16)) + supports_float64(AT) || Float64 ∉ P || continue + A, B, C0 = mxp_rand(S, n, k), mxp_rand(S, k, n), mxp_rand(S, n, n) + alpha, beta = S(1.5), S(0.5) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + E = mxp_eltype_map(C) + ref = 1.5 * Float64.(A) * Float64.(B) + 0.5 * Float64.(C0) + mag = 1.5 * abs.(Float64.(A)) * abs.(Float64.(B)) + 0.5 * abs.(Float64.(C0)) + @test recgemm!(alpha, mxp_on(AT, A), mxp_on(AT, B), beta, C) === C + @test _recgemm_ok(reconstruct_matrix(C), ref, mag, E, k; S, tf32=_rg_tf32(name, C)) + end + + # Operands of other types than the container, against the operands as given. + @testset "operands $TA × $TB" for (TA, TB) in ((Float32, Float64), (Float16, Float32)) + supports_float64(AT) || Float64 ∉ (TA, TB) || continue + n, k = 16, 8 + TC = supports_float64(AT) ? Float64 : Float32 + A, B, C0 = TA.(mxp_rand(Float64, n, k)), TB.(mxp_rand(Float64, k, n)), mxp_rand(TC, n, n) + P = DataType[Float16, Float32] + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + E = mxp_eltype_map(C) + ref = Float64.(A) * Float64.(B) + C0 + mag = abs.(Float64.(A)) * abs.(Float64.(B)) + abs.(Float64.(C0)) + recgemm!(one(TC), mxp_on(AT, A), mxp_on(AT, B), one(TC), C) + @test _recgemm_ok(reconstruct_matrix(C), ref, mag, E, k; S=promote_type(TA, TB), tf32=_rg_tf32(name, C)) + end + + # Against beta times C as stored, so a Float16 subnormal is not rounded twice in the reference. + @testset "k = 0 leaves beta * C, $S operands" for S in backend_types(AT, (Float16, Float32, Float64)) + n = 16 + TC = supports_float64(AT) ? Float64 : Float32 + C = FullMixedPrec(mxp_on(AT, mxp_rand(TC, n, n)); precisions=DataType[Float16, Float32]) + E, R0 = mxp_eltype_map(C), Float64.(Array(reconstruct_matrix(C))) + recgemm!(one(S), mxp_on(AT, zeros(S, n, 0)), mxp_on(AT, zeros(S, 0, n)), S(0.5), C) + @test mxp_storage_ok(Array(reconstruct_matrix(C)), 0.5 .* R0, E) + end + + @testset "beta = 0 overwrites C, $S operands" for S in backend_types(AT, (Float16, Float32, Float64)) + n = 8 + P = DataType[Float32, supports_float64(AT) ? Float64 : Float32] + A, B = mxp_rand(S, n, n), mxp_rand(S, n, n) + C = FullMixedPrec(mxp_on(AT, mxp_rand(P[end], n, n)); precisions=P) + E = mxp_eltype_map(C) + ref, mag = Float64.(A) * Float64.(B), abs.(Float64.(A)) * abs.(Float64.(B)) + recgemm!(one(S), mxp_on(AT, A), mxp_on(AT, B), zero(S), C) + @test _recgemm_ok(reconstruct_matrix(C), ref, mag, E, n) + end + + # A21 and A12 with different scales and an update as large as them; each block is checked on its own. + @testset "scaled blocks take alpha divided by their own scale, $S operands, precisions=$P" for S in backend_types(AT, (Float16,)), + P in (DataType[Float16, supports_float64(AT) ? Float64 : Float32], DataType[Float16, Float16, Float32]) + n = length(P) == 2 ? 8 : 16 + TC = supports_float64(AT) ? Float64 : Float32 + C0 = mxp_rand(TC, n, n) + C0[5:8, 1:4] .*= 1.0e5; C0[5, 1] = -1.0e5 # A21 of C (n = 8) or of C.A11 (n = 16), scale 1e5 / floatmax(Float16) + C0[1:4, 5:8] .*= 3.0e5; C0[1, 5] = 3.0e5 # its A12, scale 3e5 / floatmax(Float16) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + D = length(P) == 2 ? C : C.A11 + @test D.A21_scale > 1 && D.A12_scale > D.A21_scale + A, B = mxp_rand(S, n, n), mxp_rand(S, n, n) + ref = -2.0e4 * Float64.(A) * Float64.(B) + C0 + q = [(1:4, 1:4), (5:8, 1:4), (1:4, 5:8), (5:8, 5:8)] + blocks = length(P) == 2 ? q : [q; (9:16, 1:8); (1:8, 9:16); (9:16, 9:16)] + tol = mxp_tol(Float16, n + 1) + recgemm!(S(-2.0e4), mxp_on(AT, A), mxp_on(AT, B), one(S), C) + @test all(<=(tol), _recgemm_block_errs(Array(reconstruct_matrix(C)), ref, blocks)) + end + + # The leaf's own scale (src :92): its stored values are read directly, as reconstruct_matrix of a scaled Float32 leaf is Inf. + supports_float64(AT) && @testset "a scaled leaf takes alpha divided by its scale, $S operands" for S in backend_types(AT, (Float16,)) + C0 = 1.0e39 .* (1 .+ rand(4, 4)) .* rand((-1, 1), 4, 4) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float32]) + @test C.Base_scale > 1 + A, B = mxp_rand(S, 4, 2), mxp_rand(S, 2, 4) + ref = 1.0e37 * Float64.(A) * Float64.(B) + 0.5 * C0 + recgemm!(1.0e37, mxp_on(AT, A), mxp_on(AT, B), 0.5, C) + @test mxp_relerr(Float64.(Array(C.Base)) .* C.Base_scale, ref) <= mxp_tol(Float32, 3) + end + + # A Float16 x Float16 result in (65504, 65520) rounds to floatmax in place; the redo in Float32 raises the scale. + @testset "a result just past floatmax(Float16) raises the scale" begin + A = Float16.(repeat([255.875 5.75], 4, 1)) # every entry of A * A' is 65505.08 + C = FullMixedPrec(mxp_on(AT, zeros(Float32, 4, 4)); precisions=DataType[Float16, Float32]) + recgemm!(1f0, mxp_on(AT, A), mxp_on(AT, copy(A')), 0f0, C) + @test C.A21_scale > 1 + @test Float64(Array(C.A21)[1, 1]) * C.A21_scale ≈ 255.875^2 + 5.75^2 rtol=2mxp_u(Float16) + end + + @testset "an update that overflows a Float16 block raises its scale, $S operands" for S in backend_types(AT, (Float16, Float32, Float64)) + TC = supports_float64(AT) ? Float64 : Float32 + C = FullMixedPrec(mxp_on(AT, zeros(TC, 4, 4)); precisions=DataType[Float16, Float32]) + A, B = fill(S(-1000), 4, 4), fill(S(1000), 4, 4) + ref = Float64.(A) * Float64.(B) + recgemm!(one(S), mxp_on(AT, A), mxp_on(AT, B), zero(S), C) + @test C.A12_scale > 1 && C.A21_scale > 1 + R = reconstruct_matrix(C) + @test all(isfinite, Array(R)) + @test mxp_relerr(R, ref) <= mxp_tol(Float16, 4) + end + + # A signed update raises a scale that is already above 1 (scale times growth). + @testset "a signed update raises a scale above 1, $S operands" for S in backend_types(AT, (Float16, Float32, Float64)) + TC = supports_float64(AT) ? Float64 : Float32 + C0 = mxp_rand(TC, 8, 8) + C0[5:8, 1:4] .*= 1.0e5; C0[5, 1] = -1.0e5 + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, TC]) + s0 = C.A21_scale + @test s0 > 1 + A, B = S.(1.0e3 .* mxp_rand(Float64, 8, 8)), S.(1.0e3 .* mxp_rand(Float64, 8, 8)) + ref = -Float64.(A) * Float64.(B) + C0 + recgemm!(-one(S), mxp_on(AT, A), mxp_on(AT, B), one(S), C) + @test C.A21_scale > s0 + @test mxp_relerr(Array(reconstruct_matrix(C))[5:8, 1:4], ref[5:8, 1:4]) <= mxp_tol(Float16, 9) + end + + # An Inf or NaN in A[6, 1] makes only row 6 non-finite; then beta = 0 over that C gives a finite result. + @testset "a $v in A, then beta = 0 over it, $S operands, precisions=$P" for v in (Inf, NaN), S in backend_types(AT, (Float16,)), + P in (DataType[Float16, Float32], DataType[Float32]) + TC = supports_float64(AT) ? Float64 : Float32 + A, B, C0 = mxp_rand(S, 8, 3), mxp_rand(S, 3, 8), mxp_rand(TC, 8, 8) + A[6, 1] = v + A2, B2 = mxp_rand(S, 8, 3), mxp_rand(S, 3, 8) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + E = mxp_eltype_map(C) + rows = [1:5; 7:8] + ref, mag = Float64.(A) * Float64.(B) + C0, abs.(Float64.(A)) * abs.(Float64.(B)) + abs.(C0) + ref2, mag2 = Float64.(A2) * Float64.(B2), abs.(Float64.(A2)) * abs.(Float64.(B2)) + recgemm!(one(S), mxp_on(AT, A), mxp_on(AT, B), one(S), C) + R = Array(reconstruct_matrix(C)) + @test all(!isfinite, R[6, :]) + @test _recgemm_ok(R[rows, :], ref[rows, :], mag[rows, :], E[rows, :], 3; S, tf32=_rg_tf32(name, C)) + recgemm!(1, mxp_on(AT, A2), mxp_on(AT, B2), 0, C) + @test _recgemm_ok(reconstruct_matrix(C), ref2, mag2, E, 3; S, tf32=_rg_tf32(name, C)) + end + + # alpha = 0: A and B are not read, so an Inf in a Float16 operand leaves beta * C (R / 2 is exact). + @testset "alpha = 0 with an Inf in a Float16 operand" begin + TC = supports_float64(AT) ? Float64 : Float32 + A, B, C0 = mxp_rand(Float16, 8, 4), mxp_rand(Float16, 4, 8), mxp_rand(TC, 8, 8) + A[rand(1:8), rand(1:4)] = Inf + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, Float32]) + E = mxp_eltype_map(C) + if name == "CUDA" # CUDA: B16, cublasGemmEx reads A and B + @test_broken (try recgemm!(zero(TC), mxp_on(AT, A), mxp_on(AT, B), TC(2), C) + mxp_storage_ok(Array(reconstruct_matrix(C)) ./ 2, C0, E) catch; false end) + else + recgemm!(zero(TC), mxp_on(AT, A), mxp_on(AT, B), TC(2), C) + @test mxp_storage_ok(Array(reconstruct_matrix(C)) ./ 2, C0, E) + end + end + + # B9: the update path only raises a block's scale, so products below Float16's range are lost in A21. + @testset "small products into a Float16 block" begin + TC = supports_float64(AT) ? Float64 : Float32 + C = FullMixedPrec(mxp_on(AT, zeros(TC, 8, 8)); precisions=DataType[Float16, Float32]) + A, B = TC(1.0e-4) .* mxp_rand(TC, 8, 8), TC(1.0e-4) .* mxp_rand(TC, 8, 8) + recgemm!(one(TC), mxp_on(AT, A), mxp_on(AT, B), zero(TC), C) + ref = Float64.(A) * Float64.(B) + @test_broken mxp_relerr(Array(reconstruct_matrix(C))[5:8, 1:4], ref[5:8, 1:4]) <= mxp_tol(Float16, 9) + end + + # B10: a leaf never raises its scale, so an update past floatmax(Float32) is Inf. + supports_float64(AT) && @testset "an update past floatmax(Float32) in a Float32 leaf" begin + C = FullMixedPrec(mxp_on(AT, fill(1.0e38, 4, 4)); precisions=DataType[Float32]) + recgemm!(3.0, mxp_on(AT, fill(1.0e19, 4, 1)), mxp_on(AT, fill(1.0e19, 1, 4)), 1.0, C) + @test_broken all(isfinite, Array(C.Base)) + end + + # B49 family: alpha and beta are rounded to Float32 before the GEMM, so a value past floatmax(Float32) is Inf. + @testset "alpha or beta past floatmax(Float32) into a Float32 leaf" begin + TC = supports_float64(AT) ? Float64 : Float32 + A = fill(1.0f-18, 4, 2) + C = FullMixedPrec(mxp_on(AT, ones(TC, 4, 4)); precisions=DataType[Float32]) + @test_broken (try recgemm!(1.0e40, mxp_on(AT, A), mxp_on(AT, copy(A')), 1.0, C); all(isfinite, Array(reconstruct_matrix(C))) catch; false end) + C = FullMixedPrec(mxp_on(AT, fill(TC(1.0e-30), 4, 4)); precisions=DataType[Float32]) + @test_broken (try recgemm!(1.0, mxp_on(AT, ones(Float32, 4, 2)), mxp_on(AT, ones(Float32, 2, 4)), 1.0e40, C) + all(isfinite, Array(reconstruct_matrix(C))) catch; false end) + end + + # A Rational alpha divided by a Float32 scale is a Float32, so Float64 blocks get Float32 accuracy. + supports_float64(AT) && @testset "alpha = $alpha into Float64 blocks, precisions=$P" for alpha in (1 // 3,), + P in (DataType[Float32, Float64],) + n, k = 8, 4 + A, B = mxp_rand(Float64, n, k), mxp_rand(Float64, k, n) + C = FullMixedPrec(mxp_on(AT, mxp_rand(Float64, n, n)); precisions=P) + F = mxp_eltype_map(C) .== Float64 + recgemm!(alpha, mxp_on(AT, A), mxp_on(AT, B), 0, C) + R, ref = Float64.(Array(reconstruct_matrix(C))), Float64.(big.(A) * big.(B) * alpha) + @test_broken norm(R[F] - ref[F]) / norm(ref[F]) <= mxp_tol(Float64, k + 1) + end + + # B46: complex operands into the real container throw an InexactError (a kernel exception on a GPU), not an ArgumentError. + @testset "$T operands are refused" for T in backend_types(AT, (ComplexF32,)) + TC = supports_float64(AT) ? Float64 : Float32 + C = FullMixedPrec(mxp_on(AT, mxp_rand(TC, 8, 8)); precisions=DataType[Float16, Float32]) + @test_broken (try recgemm!(one(TC), mxp_on(AT, mxp_rand(T, 8, 4)), mxp_on(AT, mxp_rand(T, 4, 8)), zero(TC), C) + Array(reconstruct_matrix(C)); false catch e; e isa ArgumentError end) + end + + # Same bits on the CPU (disjoint quadrants); on a GPU each task has its own stream, and cuBLAS is bitwise reproducible only on one. + @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) + if AT === Array + @test Array(reconstruct_matrix(seq)) == Array(reconstruct_matrix(par)) + else + @test mxp_relerr(reconstruct_matrix(par), Float64.(Array(reconstruct_matrix(seq)))) <= mxp_tol(Float16, n + 1) + end + end + + # The transpose of a container is refused as C, before C is touched; for Cᵀ the transposed operands go into C. + @testset "a transposed C is refused" begin + T = supports_float64(AT) ? Float64 : Float32 + C0 = mxp_rand(T, 8, 8) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, T]) + @test_throws ArgumentError("recgemm!: C must be the container itself, not its transpose; for Cᵀ use recgemm!(alpha, copy(transpose(B)), copy(transpose(A)), beta, C)") recgemm!(one(T), mxp_on(AT, mxp_rand(T, 8, 4)), mxp_on(AT, mxp_rand(T, 4, 8)), one(T), transpose(C)) + @test Array(reconstruct_matrix(C)) == Array(reconstruct_matrix(FullMixedPrec(mxp_on(AT, C0); precisions=DataType[Float16, T]))) + end + + # A transposed operand; on a GPU a view of a transposed device matrix fails (scalar indexing or the generic gemmEx!). + @testset "a transposed operand, $S" for S in backend_types(AT, (Float16,)) + n, k = 16, 8 + TC = supports_float64(AT) ? Float64 : Float32 + A, B, C0 = mxp_rand(S, n, k), mxp_rand(S, k, n), mxp_rand(TC, n, n) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, Float32]) + E = mxp_eltype_map(C) + ref, mag = Float64.(A) * Float64.(B) + C0, abs.(Float64.(A)) * abs.(Float64.(B)) + abs.(C0) + if AT !== Array + @test_broken (try recgemm!(one(S), transpose(mxp_on(AT, copy(transpose(A)))), mxp_on(AT, B), one(S), C) + _recgemm_ok(reconstruct_matrix(C), ref, mag, E, k) catch; false end) + continue + end + recgemm!(one(S), transpose(copy(transpose(A))), B, one(S), C) + @test _recgemm_ok(reconstruct_matrix(C), ref, mag, E, k) + end + + # Adjoint and strided-view operands (CPU; on a GPU they fail as the transposed operand does, and B15 below). + AT === Array && @testset "$what operand, $S" for what in ("an adjoint", "a strided-view"), S in backend_types(AT, (Float16,)) + n, k = 16, 8 + D, A, B, C0 = mxp_rand(S, 2n, 2k), mxp_rand(S, n, k), mxp_rand(S, k, n), mxp_rand(Float64, n, n) + X, Y = what == "an adjoint" ? (A, copy(B')') : (view(D, 1:2:2n-1, 1:2:2k-1), B) + C = FullMixedPrec(copy(C0); precisions=DataType[Float16, Float32]) + E = mxp_eltype_map(C) + recgemm!(one(S), X, Y, one(S), C) + @test _recgemm_ok(reconstruct_matrix(C), Float64.(X) * Float64.(Y) + C0, abs.(Float64.(X)) * abs.(Float64.(Y)) + abs.(C0), E, k) + end + + # B15: a Float16 view with rows not next to each other; CUDA's gemmEx! passes only stride(A, 2) as the leading dimension. + @testset "a strided-row Float16 view as A" begin + n, k = 16, 8 + TC = supports_float64(AT) ? Float64 : Float32 + D, B, C0 = mxp_rand(Float16, 2n, k), mxp_rand(Float16, k, n), mxp_rand(TC, n, n) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=DataType[Float16, Float32]) + E = mxp_eltype_map(C) + ref = Float64.(D[1:2:2n-1, :]) * Float64.(B) + C0 + mag = abs.(Float64.(D[1:2:2n-1, :])) * abs.(Float64.(B)) + abs.(C0) + if name == "AMDGPU" # B15 on AMDGPU (from reading); CUDA copies such views + @test_broken (try recgemm!(one(TC), view(mxp_on(AT, D), 1:2:2n-1, :), mxp_on(AT, B), one(TC), C) + _recgemm_ok(reconstruct_matrix(C), ref, mag, E, k) catch; false end) + else + recgemm!(one(TC), view(mxp_on(AT, D), 1:2:2n-1, :), mxp_on(AT, B), one(TC), C) + @test _recgemm_ok(reconstruct_matrix(C), ref, mag, E, k) + end + end + + # The operands must be on C's backend. + AT !== Array && @testset "operands on another backend are refused" begin + T = supports_float64(AT) ? Float64 : Float32 + P = DataType[Float16, T] + S0 = mxp_rand(T, 8, 8) + A, B = mxp_on(AT, mxp_rand(T, 8, 4)), mxp_on(AT, mxp_rand(T, 4, 8)) + C = FullMixedPrec(mxp_on(AT, copy(S0)); precisions=P) + R0 = Array(reconstruct_matrix(C)) # every refusal comes before C is changed + @test_throws "must be on one backend" recgemm!(one(T), mxp_rand(T, 8, 4), mxp_rand(T, 4, 8), one(T), C) + @test_throws "must be on one backend" recgemm!(one(T), A, mxp_rand(T, 4, 8), one(T), C) # B alone on the host + @test Array(reconstruct_matrix(C)) == R0 + @test_throws "must be on one backend" recgemm!(one(T), A, B, one(T), FullMixedPrec(copy(S0); precisions=P)) + end + + # A structured operand (copied to dense first) gives the result of its dense copy. + @testset "structured $(first(mk)) operand" for mk in ("Diagonal" => (X, d) -> Diagonal(d), "Symmetric" => (X, d) -> Symmetric(X)) + T = supports_float64(AT) ? Float64 : Float32 + P = DataType[Float16, T] + S0, M, d = mxp_rand(T, 8, 8), mxp_rand(T, 8, 8), vec(mxp_rand(T, 8, 1)) + W, Wd, D = last(mk)(M, d), last(mk)(mxp_on(AT, M), mxp_on(AT, d)), mxp_on(AT, mxp_rand(T, 8, 8)) + for (A, B, Ad, Bd) in ((Wd, D, mxp_on(AT, Matrix(W)), D), (D, Wd, D, mxp_on(AT, Matrix(W)))) + C1 = FullMixedPrec(mxp_on(AT, copy(S0)); precisions=P); C2 = FullMixedPrec(mxp_on(AT, copy(S0)); precisions=P) + recgemm!(T(1.5), A, B, T(-0.5), C1); recgemm!(T(1.5), Ad, Bd, T(-0.5), C2) + @test Array(reconstruct_matrix(C1)) == Array(reconstruct_matrix(C2)) + end + end + + @testset "mismatched shapes throw DimensionMismatch" begin + T = supports_float64(AT) ? Float64 : Float32 + C = FullMixedPrec(mxp_on(AT, rand(T, 8, 8)); precisions=DataType[T]) + @test_throws DimensionMismatch recgemm!(one(T), mxp_on(AT, rand(T, 7, 4)), mxp_on(AT, rand(T, 4, 8)), one(T), C) + @test_throws DimensionMismatch recgemm!(one(T), mxp_on(AT, rand(T, 8, 4)), mxp_on(AT, rand(T, 4, 7)), one(T), C) + @test_throws DimensionMismatch recgemm!(one(T), mxp_on(AT, rand(T, 8, 4)), mxp_on(AT, rand(T, 5, 8)), one(T), C) + @test_throws "got A 8×4 and B 5×8" recgemm!(one(T), mxp_on(AT, rand(T, 8, 4)), mxp_on(AT, rand(T, 5, 8)), one(T), C) + end +end + +# Parallel against sequential in a child Julia with 4 threads (CPU only), signed values and two precision lists. +cpu_wanted() && @testset "RECGEMM mixed precision, parallel with 4 threads [CPU]" begin + code = """ + using NextLA, NextLA.MixedPrecision, Random + Random.seed!($(rand(UInt32))) # from this test's seeded RNG, so --seed replays it + signed(n) = rand(Float32, n, n) .* rand((-1, 1), n, n) # as mxp_rand, which the child does not load + same = all(Iterators.product(1:10, (DataType[Float16, Float16, Float32], DataType[Float16, Float32, Float64]))) do (_, P) + n = 64 + A, B, C0 = signed(n), signed(n), signed(n) + seq = FullMixedPrec(copy(C0); precisions=P) + par = FullMixedPrec(copy(C0); precisions=P) + recgemm!(1f0, A, B, 1f0, seq; parallel=false) + recgemm!(1f0, A, B, 1f0, par; parallel=true) + reconstruct_matrix(seq) == reconstruct_matrix(par) + end + print(Threads.nthreads(), " ", same) + """ + @test with_threads(code; threads=test_threads()) == "$(test_threads()) true" +end + +# Big sizes and multiples (k = n): three recursion levels and, above RECGEMM_PARALLEL_THRESHOLD (512), the parallel default. +@testset "RECGEMM mixed precision, n = k = $n [$name]" for (name, AT, _) in MXP_BACKENDS, n in test_values(:n, (520, 1040, 2080)) + P = supports_float64(AT) ? DataType[Float16, Float32, Float64] : DataType[Float16, Float16, Float32] + A, B, C0 = mxp_rand(Float32, n, n), mxp_rand(Float32, n, n), mxp_rand(Float32, n, n) + C = FullMixedPrec(mxp_on(AT, copy(C0)); precisions=P) + recgemm!(1f0, mxp_on(AT, A), mxp_on(AT, B), 1f0, C) + Ad, Bd = Float64.(A), Float64.(B) + @test _recgemm_ok(reconstruct_matrix(C), Ad * Bd + C0, abs.(Ad) * abs.(Bd) + abs.(C0), mxp_eltype_map(C), n; # per element: the top off-diagonal slivers are small + S=Float32, tf32=_rg_tf32(name, C)) +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..6409ff7b --- /dev/null +++ b/test/mxp/blas/syrk/recsyrk_mixedprec.jl @@ -0,0 +1,328 @@ +# recsyrk! over a SymmMixedPrec container (src/mxp/blas/syrk/recsyrk_mixedprec.jl), against Float64 BLAS. + +test_params(n = "order of C", k = "columns of A") # the number options it takes (--params) + +const MXP_SYRK_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[Float64, Float64], DataType[Float16, Float32, Float64], + DataType[Float16, Float16, Float32, Float64]) + +_mxp_syrk_err(C, ref, uplo) = mxp_relerr(mxp_tri(uplo, Float64.(Array(reconstruct_matrix(C)))), mxp_tri(uplo, ref)) + +# Whether each element of C sits in a leaf block. +_mxp_leaf_mask!(M, C, o) = C.Base !== nothing ? (M[o .+ (1:size(C, 1)), o .+ (1:size(C, 1))] .= true; M) : + (_mxp_leaf_mask!(M, C.A11, o); _mxp_leaf_mask!(M, C.A22, o + size(C.A11, 1))) + +# Per element (Higham 2002, §3.5): rounding in each block's storage type plus a k-term product in its compute type. +function _mxp_syrk_ok(C, alpha, A, beta, C0) + E, leaf = mxp_eltype_map(C), _mxp_leaf_mask!(falses(size(C)), C, 0) + Ad, C0d, a, b = Float64.(A), Float64.(C0), Float64(alpha), Float64(beta) + G = abs(a) .* (abs.(Ad) * transpose(abs.(Ad))) + ref = a .* (Ad * transpose(Ad)) .+ b .* C0d + # Float16 blocks, and Float64 leaves updated by Float16 or Float32 A, sum in Float32 + narrow = eltype(A) in (Float16, Float32) + uc = map((T, l) -> mxp_u(T == Float16 || (T == Float64 && l && narrow) ? Float32 : T), E, leaf) + bound = MXP_LAMBDA .* (mxp_u.(E) .* (G .+ abs(b) .* abs.(C0d)) .+ (size(A, 2) + 1) .* uc .* G) + return all(abs.(Float64.(Array(reconstruct_matrix(C))) .- ref) .<= bound) +end + +# Whether the other triangle of every leaf is still zero (a host container). +_mxp_syrk_leaves(C) = C.Base !== nothing ? [C.Base] : [_mxp_syrk_leaves(C.A11); _mxp_syrk_leaves(C.A22)] +_mxp_syrk_other_zero(C) = all(L -> all(iszero, C.uplo == 'L' ? triu(L, 1) : tril(L, -1)), _mxp_syrk_leaves(C)) + +# The main cases, on the CPU (AT = Array) and on each GPU, read through a host copy of the container. +function _mxp_syrk_main(AT, ns) + @testset "$S input, precisions=$P, uplo=$uplo, n=$n, k=$k, alpha=$alpha, beta=$beta" for P in test_precisions(MXP_SYRK_PRECISIONS), + S in backend_types(AT, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, ns), + k in test_values(:k, (1, 16)), (alpha, beta) in ((1.5, 0.5), (-0.7, -2.0)) + supports_float64(AT) || Float64 ∉ P || continue + n == 300 && P != DataType[Float32] && continue # only a single leaf recurses inside the leaf at 300 + A, C0 = mxp_rand(S, n, k), mxp_spd(S, n) + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + @test recsyrk!(S(alpha), mxp_on(AT, A), S(beta), C) === C + H = mxp_host(C) + @test _mxp_syrk_ok(H, S(alpha), A, S(beta), C0) + @test _mxp_syrk_other_zero(H) + end +end + +# Cases run on the CPU and on each GPU backend, read through a host copy of the container. +function _mxp_syrk_more(AT, name) + TC = supports_float64(AT) ? Float64 : Float32 + + # Big sizes and multiples with k = n; at 300 a single leaf recurses inside the leaf. + @testset "n = k = $n, precisions=$P, uplo=$uplo" for (n, P) in test_cases((:n, nothing), ((300, DataType[Float32]), + (600, DataType[Float16, Float16, Float32]), (1200, DataType[Float16, Float16, Float32]), (2400, DataType[Float16, Float16, Float32]), + (600, DataType[Float16, Float32, Float64]), (1200, DataType[Float16, Float32, Float64]), (2400, DataType[Float16, Float32, Float64]))), + uplo in test_flags(:uplo, ('L', 'U')) + supports_float64(AT) || Float64 ∉ P || continue + A, C0 = mxp_rand(Float32, n, n), mxp_spd(Float32, n) + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + recsyrk!(1.5f0, mxp_on(AT, A), 0.5f0, 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), n + 1) + end + + @testset "beta = 0 overwrites the stored triangle, k = 0 leaves beta C, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + n, k = 45, 8 + P = DataType[Float16, Float32, supports_float64(AT) ? Float64 : Float32] + T = P[end] + A, C0 = mxp_rand(T, n, k), mxp_spd(T, n) + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + recsyrk!(one(T), mxp_on(AT, A), zero(T), C) + @test _mxp_syrk_err(mxp_host(C), Float64.(A) * transpose(Float64.(A)), uplo) <= mxp_tol(Float16, k + 1) + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + recsyrk!(one(T), mxp_on(AT, zeros(T, n, 0)), T(0.5), C) + @test _mxp_syrk_err(mxp_host(C), 0.5 .* Float64.(C0), uplo) <= mxp_tol(Float16, 1) + end + + # Float32 sums into a Float64 leaf: beta = 0 does not read the leaf, as BLAS syrk (a NaN there stays out). + supports_float64(AT) && @testset "beta = 0 does not read a Float64 leaf, $TA A, uplo=$uplo" for TA in backend_types(AT, (Float16, Float32)), + uplo in test_flags(:uplo, ('L', 'U')) + n, k = 45, 8 + C = SymmMixedPrec(mxp_on(AT, mxp_spd(Float64, n)), uplo; precisions=DataType[Float16, Float32, Float64]) + foreach(L -> copyto!(L, (uplo == 'L' ? tril : triu)(fill(NaN, size(L)))), _mxp_syrk_leaves(C)) + A = TA.(mxp_rand(Float64, n, k)) + recsyrk!(1.0, mxp_on(AT, A), 0.0, C) + @test _mxp_syrk_err(mxp_host(C), Float64.(A) * transpose(Float64.(A)), uplo) <= mxp_tol(Float16, k + 1) + end + + # Float16 and Float32 A into Float16 blocks at two levels. + @testset "A $TA into Float16 blocks, uplo=$uplo" for TA in backend_types(AT, (Float16, Float32)), uplo in test_flags(:uplo, ('L', 'U')) + n, k = 45, 8 + A, C0 = TA.(mxp_rand(Float64, n, k)), mxp_spd(TC, n) + P = DataType[Float16, Float16, Float32] + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + recsyrk!(one(TC), mxp_on(AT, A), one(TC), C) + ref = Float64.(A) * transpose(Float64.(A)) + C0 + @test _mxp_syrk_err(mxp_host(C), ref, uplo) <= mxp_tol(mxp_narrowest(vcat(P, TA)), k + 1) + end + + # An update of a Float32 leaf keeps only the stored triangle: Float16 A takes the GEMM copy, Float32 A syrk!. + @testset "a leaf's other triangle stays zero after an update with $TA A, uplo=$uplo" for TA in backend_types(AT, (Float16, Float32)), + uplo in test_flags(:uplo, ('L', 'U')) + C = SymmMixedPrec(mxp_on(AT, mxp_spd(TC, 8)), uplo; precisions=DataType[Float32]) + A = mxp_on(AT, TA.(mxp_rand(Float64, 8, 3))) + recsyrk!(one(TC), A, one(TC), C) + L = Array(C.Base) + @test all(iszero, uplo == 'L' ? triu(L, 1) : tril(L, -1)) + end + + # alpha = -1e5 makes the update as large as the 1e5 block, so a missing alpha / scale shows. + @testset "a scaled block takes alpha divided by its scale, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + n = 8 + C0 = ones(TC, n, n) + C0[5:8, 1:4] .= 1.0e5 + C0[1:4, 5:8] .= 1.0e5 + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=DataType[Float16, TC]) + @test C.OffDiag_scale != 1 + A = mxp_rand(TC, n, 4) + recsyrk!(TC(-1e5), mxp_on(AT, A), one(TC), C) + @test _mxp_syrk_err(mxp_host(C), -1e5 * Float64.(A) * transpose(Float64.(A)) + Float64.(C0), uplo) <= mxp_tol(Float16, 5) + end + + # Off-diagonal blocks at levels 1 (2e5, scale 3.05) and 2 (1e5, scale 1.53), each with its own alpha / scale. + @testset "two scaled levels take alpha divided by their own scales, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + C0 = ones(TC, 16, 16) + C0[9:16, 1:8] .= 2.0e5 + C0[1:8, 9:16] .= 2.0e5 + C0[13:16, 9:12] .= 1.0e5 + C0[9:12, 13:16] .= 1.0e5 + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=DataType[Float16, Float16, TC]) + @test C.OffDiag_scale != 1 + @test C.A22.OffDiag_scale != 1 + A = mxp_rand(TC, 16, 4) + recsyrk!(TC(-1e5), mxp_on(AT, A), one(TC), C) + @test _mxp_syrk_err(mxp_host(C), -1e5 * Float64.(A) * transpose(Float64.(A)) + Float64.(C0), uplo) <= mxp_tol(Float16, 5) + end + + # A wider A takes the Float32 copy; an update past floatmax(Float16) raises the block's scale. + @testset "an update that overflows a Float16 block raises its scale, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + C = SymmMixedPrec(mxp_on(AT, zeros(TC, 4, 4)), uplo; precisions=DataType[Float16, Float32]) + A = fill(TC(1000), 4, 2) + recsyrk!(one(TC), mxp_on(AT, A), zero(TC), C) + @test C.OffDiag_scale > 1 + @test _mxp_syrk_err(mxp_host(C), Float64.(A) * transpose(Float64.(A)), uplo) <= mxp_tol(Float16, 2) + end + + # Float16 A takes the in-place update; an overflow there is undone and redone through the Float32 copy. + @testset "Float16 A overflowing a Float16 block raises its scale, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + C = SymmMixedPrec(mxp_on(AT, zeros(TC, 4, 4)), uplo; precisions=DataType[Float16, Float32]) + A = fill(Float16(1000), 4, 2) + recsyrk!(one(TC), mxp_on(AT, A), zero(TC), C) + @test C.OffDiag_scale > 1 + @test _mxp_syrk_err(mxp_host(C), Float64.(A) * transpose(Float64.(A)), uplo) <= mxp_tol(Float16, 2) + end + + # A leaf holding 1e39 has a scale (5.88); reconstruct_matrix overflows Float32 here, so the leaf is read directly. + supports_float64(AT) && @testset "a scaled Float32 leaf takes alpha divided by its scale, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + C0 = fill(1e39, 4, 4) + 1e39 * I + C = SymmMixedPrec(mxp_on(AT, C0), uplo; precisions=DataType[Float32]) + @test C.Base_scale != 1 + A = mxp_rand(Float64, 4, 3) + recsyrk!(-1e37, mxp_on(AT, A), 1.0, C) + H = mxp_host(C) + @test mxp_relerr(mxp_tri(uplo, Float64.(H.Base) .* H.Base_scale), mxp_tri(uplo, -1e37 * A * transpose(A) + C0)) <= mxp_tol(Float32, 4) + C = SymmMixedPrec(mxp_on(AT, C0), uplo; precisions=DataType[Float32]) + recsyrk!(1e38, mxp_on(AT, ones(4, 1)), 1.0, C) + @test_broken all(isfinite, Array(C.Base)) # B10: the leaf's scale is not raised, so the update overflows to Inf + end + + # BLAS does not read A when alpha = 0; CUBLAS gemmEx! and syrk! do, so 0 * Inf gives NaN there (B16, B23). + @testset "alpha = 0 with Inf in A gives beta C, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + n, k = 45, 8 + C0 = mxp_spd(TC, n) + C = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=DataType[Float16, Float32, TC]) + recsyrk!(zero(TC), mxp_on(AT, fill(TC(Inf), n, k)), TC(2), C) + if name == "CUDA" + @test_broken _mxp_syrk_err(mxp_host(C), 2 .* Float64.(C0), uplo) <= mxp_tol(Float16, 1) + else + @test _mxp_syrk_err(mxp_host(C), 2 .* Float64.(C0), uplo) <= mxp_tol(Float16, 1) + end + end + + @testset "alpha = 0 and beta = 1 leave C bit for bit, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + C = SymmMixedPrec(mxp_on(AT, mxp_spd(TC, 45)), uplo; precisions=DataType[Float16, Float32, TC]) + R0 = reconstruct_matrix(mxp_host(C)) + recsyrk!(zero(TC), mxp_on(AT, mxp_rand(TC, 45, 8)), one(TC), C) + @test reconstruct_matrix(mxp_host(C)) == R0 + end + + # C[i, j] sums A[i, l] * A[j, l], so a NaN in row 40 of A reaches exactly row and column 40. + @testset "a NaN in row 40 of A reaches only row and column 40, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + n = 45 + A = mxp_rand(Float32, n, 8) + A[40, 2] = NaN + C = SymmMixedPrec(mxp_on(AT, mxp_spd(Float32, n)), uplo; precisions=DataType[Float16, Float32]) + recsyrk!(1f0, mxp_on(AT, A), 1f0, C) + @test isnan.(reconstruct_matrix(mxp_host(C))) == [i == 40 || j == 40 for i in 1:n, j in 1:n] + end + + # The parallel path on device arrays: the two tasks share A and write disjoint blocks. + @testset "parallel and sequential give the same result on $name, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + n = 64 + A, C0 = mxp_rand(Float32, n, 8), mxp_spd(Float32, n) + P = DataType[Float16, Float16, Float32] + seq = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + par = SymmMixedPrec(mxp_on(AT, copy(C0)), uplo; precisions=P) + MixedPrecision._recsyrk_mixed!(1, mxp_on(AT, A), 1, seq; parallel=false) + MixedPrecision._recsyrk_mixed!(1, mxp_on(AT, A), 1, par; parallel=true) + @test reconstruct_matrix(mxp_host(seq)) == reconstruct_matrix(mxp_host(par)) + end + + # A Float16 block holding 1e42 has scale 1.5e37; the update needs one past floatmax(Float32). + supports_float64(AT) && @testset "an update too large for a Float32 scale throws" begin + C = SymmMixedPrec(mxp_on(AT, fill(1e42, 4, 4) + 1e42 * I), 'L'; precisions=DataType[Float16, Float64]) + @test_throws ArgumentError recsyrk!(1e44, mxp_on(AT, ones(4, 1)), 1.0, C) + end + + # Pinned limits of the off-diagonal block scales. + @testset "off-diagonal scale limits" begin + # 1e40 passes floatmax(Float32) in the Float32 working copy and is stored as Inf with scale 1. + C = SymmMixedPrec(mxp_on(AT, zeros(TC, 4, 4)), 'L'; precisions=DataType[Float16, TC]) + recsyrk!(one(TC), mxp_on(AT, fill(TC(1e20), 4, 1)), zero(TC), C) + @test_broken isapprox(Float64.(Array(C.OffDiag)) .* C.OffDiag_scale, fill(1e40, 2, 2); rtol=2 * mxp_u(Float16)) + # B9: a 2e-10 update is below the Float16 range and becomes 0, as scales are only raised. + C = SymmMixedPrec(mxp_on(AT, zeros(TC, 16, 16)), 'L'; precisions=DataType[Float16, TC]) + recsyrk!(one(TC), mxp_on(AT, fill(TC(1e-5), 16, 2)), zero(TC), C) + @test_broken isapprox(Float64.(Array(C.OffDiag)) .* C.OffDiag_scale, fill(2 * Float64(TC(1e-5))^2, 8, 8); rtol=2 * mxp_u(Float16)) + # beta = 0 into a block with scale 1.5e25 (from 1e30) keeps the stale scale, so the new 1s become 0. + C = SymmMixedPrec(mxp_on(AT, fill(TC(1e30), 4, 4)), 'L'; precisions=DataType[Float16, TC]) + recsyrk!(one(TC), mxp_on(AT, ones(TC, 4, 1)), zero(TC), C) + @test_broken all(x -> abs(x - 1) <= 2 * mxp_u(Float16), Float64.(Array(reconstruct_matrix(mxp_host(C))))[3:4, 1:2]) + end + + # alpha / C.Base_scale divides by a Float32, so a non-float alpha reaches a Float64 leaf rounded to Float32. + supports_float64(AT) && @testset "a non-float alpha keeps Float64 accuracy: $alpha" for alpha in (1 // 3,) + A = mxp_rand(Float64, 8, 3) + C = SymmMixedPrec(mxp_on(AT, zeros(8, 8)), 'L'; precisions=DataType[Float64]) + recsyrk!(alpha, mxp_on(AT, A), 0, C) + @test_broken _mxp_syrk_err(mxp_host(C), Float64(alpha) * A * transpose(A), 'L') <= mxp_tol(Float64, 4) + end +end + +cpu_wanted() && @testset "RECSYRK mixed precision [CPU]" begin + _mxp_syrk_main(Array, (13, 32, 45, 64, 300)) + + @testset "n=$n, k=$k, alpha=$alpha, beta=$beta, uplo=$uplo" for n in (1, 2), k in (1, 16), uplo in test_flags(:uplo, ('L', 'U')), + (alpha, beta) in ((1.5, 0.5), (-0.7, -2.0)) + A, C0 = mxp_rand(Float32, n, k), mxp_spd(Float32, n) + C = SymmMixedPrec(copy(C0), uplo; precisions=DataType[Float16, Float32, Float64]) + recsyrk!(Float32(alpha), A, Float32(beta), C) + @test _mxp_syrk_ok(C, Float32(alpha), A, Float32(beta), C0) + 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 + + # Complex input is later work (B46); a complex A should be refused with an ArgumentError, not an InexactError. + # CPU only: on a GPU the conversion throws inside a kernel. + @testset "complex A is refused" begin + C = SymmMixedPrec(mxp_spd(Float64, 8), 'L'; precisions=DataType[Float16, Float64]) + @test_broken try recsyrk!(1.0, mxp_rand(ComplexF64, 8, 3), 1.0, C); false catch e; e isa ArgumentError end + end + + # A contiguous view of a larger matrix as A. + @testset "a contiguous view as A" begin + B, C0 = mxp_rand(Float64, 32, 12), mxp_spd(Float64, 32) + C = SymmMixedPrec(copy(C0), 'L'; precisions=DataType[Float16, Float32]) + recsyrk!(1.0, view(B, :, 3:10), 1.0, C) + @test _mxp_syrk_err(C, B[:, 3:10] * B[:, 3:10]' + C0, 'L') <= mxp_tol(Float16, 9) + end + + # B11: a transposed A works when it is converted to the leaf type ([F16, F32]); of the leaf's type, BLAS refuses it. + @testset "a transposed A, precisions=$P" for P in (DataType[Float16, Float32], DataType[Float16, Float64]) + At, C0 = mxp_rand(Float64, 8, 32), mxp_spd(Float64, 32) + C = SymmMixedPrec(copy(C0), 'L'; precisions=P) + ok = try + recsyrk!(1.0, transpose(At), 1.0, C) + _mxp_syrk_err(C, transpose(At) * At + C0, 'L') <= mxp_tol(Float16, 9) + catch + false + end + if P[end] == Float64 + @test_broken ok + else + @test ok + end + end + + _mxp_syrk_more(Array, "CPU") +end + +# Parallel against sequential in a child Julia with 4 threads (CPU only). +cpu_wanted() && @testset "RECSYRK mixed precision, parallel with 4 threads [CPU]" begin + code = """ + using NextLA, NextLA.MixedPrecision, LinearAlgebra, Random + Random.seed!($(rand(UInt32))) # from this test's seeded RNG, so --seed replays it + same = all(1:20) do i + uplo = isodd(i) ? 'L' : 'U' + n = 64 + A, R = 2 .* rand(n, 8) .- 1, rand(n, n) + S = R * R' + n * I + P = i <= 10 ? DataType[Float16, Float16, Float32] : DataType[Float16, Float32, Float64] + seq = SymmMixedPrec(copy(S), uplo; precisions=P) + par = SymmMixedPrec(copy(S), uplo; precisions=P) + MixedPrecision._recsyrk_mixed!(1.0, A, 1.0, seq; parallel=false) + MixedPrecision._recsyrk_mixed!(1.0, A, 1.0, par; parallel=true) + reconstruct_matrix(seq) == reconstruct_matrix(par) + end + # The public decision: n = 8193 puts 8192 rows in the first half, past RECSYRK_PARALLEL_THRESHOLD. + n = 8193 + A = 2 .* rand(Float32, n, 1) .- 1 + par = SymmMixedPrec(Matrix{Float32}(I, n, n), 'L'; precisions=DataType[Float16, Float32]) + seq = SymmMixedPrec(Matrix{Float32}(I, n, n), 'L'; precisions=DataType[Float16, Float32]) + recsyrk!(1f0, A, 1f0, par) + MixedPrecision._recsyrk_mixed!(1f0, A, 1f0, seq; parallel=false) + big = par.OffDiag == seq.OffDiag && par.A11.Base == seq.A11.Base && par.A22.Base == seq.A22.Base + print(Threads.nthreads(), " ", same, " ", big) + """ + @test with_threads(code; threads=test_threads()) == "$(test_threads()) true true" +end + +# On a GPU: the update runs on the device and is checked on the CPU through a host copy. +@testset "RECSYRK mixed precision [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + _mxp_syrk_main(AT, (13, 45, 64, 300)) + _mxp_syrk_more(AT, name) +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..913b9f23 --- /dev/null +++ b/test/mxp/blas/trsm/rectrxm_mixed.jl @@ -0,0 +1,527 @@ +# unified_rectrxm! with a mixed-precision A (src/mxp/blas/trsm/rectrxm_mixed.jl): solve and multiply. + +test_params(n = "order of the triangle A") # the number options it takes (--params) + +# A triangle with diagonal in [1, 2) and off-diagonal entries below 1/n: well conditioned, unit diagonal or not. +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 + +_mxp_flip(c) = c == 'L' ? 'U' : 'L' + +# The triangle uplo of A with another triangle of other values, so a FullMixedPrec of it has A12 ≠ transpose(A21). +function _mxp_trxm_full(A, uplo) + Other = mxp_tri(_mxp_flip(uplo), 4 .* mxp_rand(eltype(A), size(A)...)) + Other[LinearAlgebra.diagind(Other)] .= 0 + return A + Other +end + +function _mxp_trxm_container(kind, T, n, uplo, P, AT=Array) + A = _mxp_trxm_matrix(T, n, uplo) + kind === TriMixedPrec && return TriMixedPrec(mxp_on(AT, A), uplo; precisions=P) + kind === SymmMixedPrec && return SymmMixedPrec(mxp_on(AT, A + transpose(A) - Diagonal(A)), uplo; precisions=P) + return FullMixedPrec(mxp_on(AT, _mxp_trxm_full(A, uplo)); precisions=P) +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 + +cpu_wanted() && @testset "RECTRXM mixed [CPU]" begin + @testset "$S input, $(nameof(kind)) uplo=$uplo side=$side func=$func trans=$trans diag=$diag precisions=$P" for + kind in (TriMixedPrec, SymmMixedPrec, FullMixedPrec), uplo in test_flags(:uplo, ('L', 'U')), side in test_flags(:side, ('L', 'R')), + func in ('S', 'M'), trans in test_flags(:trans, ('N', 'T')), diag in test_flags(:diag, ('N', 'U')), + P in test_precisions((DataType[Float32, Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64])), + S in test_types((Float16, Float32, Float64)) + n, m = 37, 5 + Amp = _mxp_trxm_container(kind, S, n, uplo, P) + B = side == 'L' ? mxp_rand(S, n, m) : mxp_rand(S, m, n) + X = copy(B) + @test unified_rectrxm!(side, uplo, trans, diag, S(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(vcat(P, S)), n) + end + + # All-Float64 containers are held to Float64 accuracy (the lists above all have a narrower block). + @testset "Float64 accuracy, $(nameof(kind)) side=$side func=$func trans=$trans precisions=$P" for + P in (DataType[Float64], DataType[Float64, Float64]), kind in (TriMixedPrec, FullMixedPrec), + side in test_flags(:side, ('L', 'R')), func in ('S', 'M'), trans in test_flags(:trans, ('N', 'T', 'C')) + n = 37 + Amp = _mxp_trxm_container(kind, Float64, n, 'L', P) + B = side == 'L' ? mxp_rand(Float64, n, 5) : mxp_rand(Float64, 5, n) + X = copy(B) + unified_rectrxm!(side, 'L', trans, 'N', 2.0, func, Amp, X) + @test _mxp_trxm_err(side, 'L', trans, 'N', func, 2.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(Float64, n) + end + + # n = 300 with [Float32] and n = 600 with [Float16, Float32] give a leaf past the threshold 256; 1200 is the next multiple. + @testset "$S input, n=$n, precisions=$P" for n in test_values(:n, (1, 2, 16, 64, 300, 600, 1200)), + P in test_precisions((DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float16, Float32, Float64])), + S in test_types((Float16, Float32, Float64)) + for side in test_flags(:side, ('L', 'R')), func in ('S', 'M') + Amp = _mxp_trxm_container(TriMixedPrec, S, n, 'L', P) + B = side == 'L' ? mxp_rand(S, n, 3) : mxp_rand(S, 3, n) + X = copy(B) + unified_rectrxm!(side, 'L', 'N', 'N', one(S), func, Amp, X) + @test _mxp_trxm_err(side, 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= + mxp_tol(mxp_narrowest(vcat(P, S)), n) + end + end + + # B with no columns (side 'L') or no rows (side 'R'). + @testset "an empty $S B, side=$side func=$func" for S in test_types((Float32,)), + side in test_flags(:side, ('L', 'R')), func in ('S', 'M') + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 37, 'L', DataType[Float16, Float32]) + X = side == 'L' ? zeros(S, 37, 0) : zeros(S, 0, 37) + @test unified_rectrxm!(side, 'L', 'N', 'N', one(S), func, Amp, X) === X + end + + # B of another type than the container: wider, narrower, and a transposed narrow block. + @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 test_flags(:trans, ('N', 'T')) + n = 37 + Amp = _mxp_trxm_container(TriMixedPrec, P[end], n, 'L', P) + for side in test_flags(:side, ('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 + + # A Float16 B keeps its type: leaves run in Float32 and round to B's type. + @testset "B Float16, func=$func" for func in ('S', 'M') + n = 37 + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32]) + B = Float16.(mxp_rand(Float64, n, 4)) + X = copy(B) + unified_rectrxm!('L', 'L', 'N', 'N', one(Float16), func, Amp, X) + @test eltype(X) === Float16 + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(Float16, n) + end + + # B a strided view of a larger matrix: the view is solved and nothing else changes. + @testset "B a strided view" begin + n = 37 + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32]) + Bbig = mxp_rand(Float32, 2n, 8) + B0 = copy(Bbig) + Bv = view(Bbig, 1:2:2n-1, 2:2:8) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', Amp, Bv) + @test _mxp_trxm_err('L', 'L', 'N', 'N', 'S', 1.0, _mxp_stored(Amp, 'L'), Bv, B0[1:2:2n-1, 2:2:8]) <= + mxp_tol(Float16, n) + @test Bbig[2:2:2n, :] == B0[2:2:2n, :] && Bbig[:, 1:2:7] == B0[:, 1:2:7] + end + + # B the transpose of a matrix. + @testset "B the $w of a $S matrix, func=$func" for S in test_types((Float32,)), w in (transpose,), func in ('S',) + n = 37 + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32]) + B0 = mxp_rand(S, 3, n) + X = w(copy(B0)) + @test unified_rectrxm!('L', 'L', 'N', 'N', one(S), func, Amp, X) === X + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, w(B0)) <= mxp_tol(Float16, n) + end + + # B46: a complex B through a real split container reaches quantize, which has no complex method. + @testset "a $S B through a real container, func=$func" for S in test_types((ComplexF32,)), func in ('S',) + n = 37 + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32]) + B = mxp_rand(S, n, 3) + @test_broken (try X = unified_rectrxm!('L', 'L', 'N', 'N', one(S), func, Amp, copy(B)) + maximum(f -> _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), f(X), f(B)), + (real, imag)) <= mxp_tol(Float16, n) + catch; false end) + end + + @testset "a zero B, func=$func" for func in ('S', 'M') + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 37, 'L', DataType[Float16, Float32]) + X = zeros(Float32, 37, 3) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, func, Amp, X) + @test iszero(X) + end + + # A diagonal A: the off-diagonal blocks are zero, so the result is exact. + @testset "a diagonal A, func=$func" for func in ('S', 'M') + d = 1f0 .+ rand(Float32, 37) + Amp = TriMixedPrec(Matrix(Diagonal(d)), 'L'; precisions=DataType[Float16, Float32]) + B = mxp_rand(Float32, 37, 3) + X = copy(B) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, func, Amp, X) + @test X == (func == 'S' ? Diagonal(d) \ B : Diagonal(d) * B) + end + + @testset "a NaN in B stays in its column" begin + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 37, 'L', DataType[Float16, Float32]) + X = mxp_rand(Float32, 37, 2) + X[2, 1] = NaN32 + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', Amp, X) + @test isnan(X[2, 1]) && all(isfinite, X[:, 2]) + end + + # A zero on the diagonal gives a non-finite result, not an error (BLAS ?trsm does no singularity test). + @testset "a singular A" begin + A = _mxp_trxm_matrix(Float32, 37, 'L') + A[3, 3] = 0 + Amp = TriMixedPrec(A, 'L'; precisions=DataType[Float16, Float32]) + X = mxp_rand(Float32, 37, 3) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', Amp, X) + @test !all(isfinite, X) + end + + # O(1) off-diagonal entries and a diagonal in [-0.5, 1.5]: ill-conditioned, the solve stays backward stable. + @testset "an ill-conditioned triangle, uplo=$uplo, n=$n" for uplo in test_flags(:uplo, ('L', 'U')), + n in test_values(:n, (64,); valid = n -> n <= 64 || "a random O(1) triangle's solution overflows Float32 past n = 64") + A = mxp_tri(uplo, mxp_rand(Float32, n, n)) + 0.5f0I + Amp = TriMixedPrec(A, uplo; precisions=DataType[Float16, Float32]) + B = mxp_rand(Float32, n, 3) + X = copy(B) + unified_rectrxm!('L', uplo, 'N', 'N', 1f0, 'S', Amp, X) + @test _mxp_trxm_err('L', uplo, 'N', 'N', 'S', 1.0, _mxp_stored(Amp, uplo), X, B) <= mxp_tol(Float16, n) + end + + @testset "scaled off-diagonal blocks, func=$func" for func in ('S', 'M') + n, m = 16, 4 + A = mxp_tri('L', mxp_rand(Float32, n, n)) .* 1f5 + 1f6I + 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 = mxp_tri('L', mxp_rand(Float64, 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 + + # diag 'U' with a scaled leaf: the stored unit diagonal stands for the scale, not 1 (src :148-151), so the result is wrong. + @testset "diag U with a scaled leaf, $(nameof(kind)) side=$side func=$func" for kind in (TriMixedPrec, FullMixedPrec), + side in test_flags(:side, ('L',)), func in ('S',) + n, P = kind === TriMixedPrec ? (8, DataType[Float32]) : (37, DataType[Float16, Float32]) + A = _mxp_trxm_matrix(Float64, n, 'L') + A[LinearAlgebra.diagind(A)] .= 1e39 + Amp = kind === TriMixedPrec ? TriMixedPrec(A, 'L'; precisions=P) : FullMixedPrec(_mxp_trxm_full(A, 'L'); precisions=P) + B = side == 'L' ? mxp_rand(Float64, n, 3) : mxp_rand(Float64, 3, n) + X = copy(B) + unified_rectrxm!(side, 'L', 'N', 'U', 1.0, func, Amp, X) + @test_broken _mxp_trxm_err(side, 'L', 'N', 'U', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(mxp_narrowest(P), 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 Float64 B of ~1e42 overflows the Float32 partial product through a narrow off-diagonal block (Float32-range limit). + @testset "a large Float64 B through a narrow off-diagonal block, precisions=$P, B×$c, func=$func" for + P in (DataType[Float16, Float64],), c in (1e42,), func in ('S', 'M') + Amp = TriMixedPrec(tril(rand(8, 8)) + 8I, 'L'; precisions=P) + B = c .* mxp_rand(Float64, 8, 2) + @test_broken (try X = unified_rectrxm!('L', 'L', 'N', 'N', 1.0, func, Amp, copy(B)) + all(isfinite, X) && _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(P[1], 8) + catch; false end) + 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 + + # An off-diagonal product keeps B values past floatmax(Float16) through a scaled copy; O(1) off-diagonal entries so the update shows. + @testset "an off-diagonal product keeps B values past floatmax(Float16), func=$func" for func in ('S', 'M') + n = 16 + A = mxp_tri('L', mxp_rand(Float32, n, n)) + A[LinearAlgebra.diagind(A)] .= 2 .+ rand(Float32, n) + Amp = TriMixedPrec(A, 'L'; precisions=DataType[Float16, Float32]) + B = 1.0f6 .* mxp_rand(Float32, n, 3) + X = copy(B) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, func, Amp, X) + @test all(isfinite, X) + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(Amp, 'L'), X, B) <= mxp_tol(Float16, 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 + + # The transpose of a container is refused (pass trans = 'T'), and a B that does not match A too, before B is touched. + @testset "a transposed container and a mismatched B are refused" begin + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 16, 'L', DataType[Float16, Float32]) + B = mxp_rand(Float32, 16, 3) + msg = ArgumentError("unified_rectrxm!: pass the container itself, not its transpose, with trans flipped and uplo = A.uplo") + @test_throws msg unified_rectrxm!('L', 'U', 'N', 'N', 1f0, 'S', transpose(Amp), copy(B)) + @test_throws msg unified_rectrxm!('L', 'U', 'N', 1f0, 'S', transpose(Amp), copy(B)) + X = mxp_rand(Float32, 17, 3); X0 = copy(X) + @test_throws DimensionMismatch unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'S', Amp, X) + @test X == X0 + @test_throws DimensionMismatch unified_rectrxm!('R', 'L', 'N', 'N', 1f0, 'M', Amp, mxp_rand(Float32, 3, 15)) + 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) + X = unified_rectrxm!('L', 'L', 'T', 'N', 1f0, 'S', Amp, copy(B)) + @test unified_rectrxm!('l', 'l', 't', 'n', 1f0, 's', Amp, copy(B)) == X # BLAS takes either case + end +end + +# On a GPU: solve and multiply run on the device and are checked on the CPU through a host copy. +@testset "RECTRXM mixed [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + n = 37 + + @testset "$S input, FullMixedPrec uplo=$uplo side=$side func=$func trans=$trans diag=$diag precisions=$P" for + uplo in test_flags(:uplo, ('L', 'U')), side in test_flags(:side, ('L', 'R')), func in ('S', 'M'), + trans in test_flags(:trans, ('N', 'T')), diag in test_flags(:diag, ('N', 'U')), + P in test_precisions((DataType[Float32, Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64])), + S in backend_types(AT, (Float16, Float32, Float64)) + supports_float64(AT) || Float64 ∉ P || continue + Amp = _mxp_trxm_container(FullMixedPrec, S, n, uplo, P, AT) + B = side == 'L' ? mxp_rand(S, n, 4) : mxp_rand(S, 4, n) + X = AT(copy(B)) + tol = mxp_tol(mxp_narrowest(vcat(P, S)), n) + unified_rectrxm!(side, uplo, trans, diag, S(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) <= tol + end + + @testset "$S input, $(nameof(kind)) uplo=$uplo side=$side func=$func trans=$trans diag=$diag precisions=$P" for + kind in (TriMixedPrec, SymmMixedPrec), uplo in test_flags(:uplo, ('L', 'U')), side in test_flags(:side, ('L', 'R')), func in ('S', 'M'), + trans in test_flags(:trans, ('N', 'T')), diag in test_flags(:diag, ('N', 'U')), + P in test_precisions((DataType[Float32, Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64])), + S in backend_types(AT, (Float16, Float32, Float64)) + supports_float64(AT) || Float64 ∉ P || continue + Amp = _mxp_trxm_container(kind, S, n, uplo, P, AT) + B = side == 'L' ? mxp_rand(S, n, 4) : mxp_rand(S, 4, n) + X = AT(copy(B)) + tol = mxp_tol(mxp_narrowest(vcat(P, S)), n) + Ad = _mxp_stored(mxp_host(Amp), uplo) + unified_rectrxm!(side, uplo, trans, diag, S(2), func, Amp, X) + @test X isa AT + @test _mxp_trxm_err(side, uplo, trans, diag, func, 2.0, Ad, X, B) <= tol + end + + # trans = 'C', unit diagonal, Float16 blocks at two levels, each container, on the device. + @testset "$(nameof(kind)) uplo=$uplo side=$side trans=C diag=U, Float16 blocks" for + kind in (TriMixedPrec, SymmMixedPrec, FullMixedPrec), uplo in test_flags(:uplo, ('L', 'U')), side in test_flags(:side, ('L', 'R')) + P = DataType[Float16, Float16, Float32, supports_float64(AT) ? Float64 : Float32] + T = P[end] + A = _mxp_trxm_matrix(T, n, uplo) + A = kind === TriMixedPrec ? A : A + transpose(A) - Diagonal(A) + Amp = kind === FullMixedPrec ? FullMixedPrec(AT(A); precisions=P) : kind(AT(A), uplo; precisions=P) + B = side == 'L' ? mxp_rand(T, n, 4) : mxp_rand(T, 4, n) + X = AT(copy(B)) + tol = mxp_tol(Float16, n) + unified_rectrxm!(side, uplo, 'C', 'U', T(2), 'S', Amp, X) + @test X isa AT + @test _mxp_trxm_err(side, uplo, 'C', 'U', 'S', 2.0, _mxp_stored(mxp_host(Amp), uplo), X, B) <= tol + end + + @testset "B a strided view of a device matrix, B $TB" for TB in backend_types(AT, (Float32, Float64)) + P = DataType[Float16, Float32, supports_float64(AT) ? Float64 : Float32] + Amp = TriMixedPrec(AT(_mxp_trxm_matrix(P[end], n, 'L')), 'L'; precisions=P) + Bbig = mxp_rand(TB, 2n, 8) + D = AT(copy(Bbig)) + Ad = _mxp_stored(mxp_host(Amp), 'L') + unified_rectrxm!('L', 'L', 'N', 'N', one(TB), 'S', Amp, view(D, 1:2:2n-1, 2:2:8)) + R = Array(D) + @test _mxp_trxm_err('L', 'L', 'N', 'N', 'S', 1.0, Ad, R[1:2:2n-1, 2:2:8], Bbig[1:2:2n-1, 2:2:8]) <= mxp_tol(Float16, n) + # B15: a Float16 block's product goes into a Float32 view through gemmEx! (CUDA copies such views; AMDGPU from reading). + @test R[2:2:2n, :] == Bbig[2:2:2n, :] && R[:, 1:2:7] == Bbig[:, 1:2:7] broken=(TB === Float32 && name == "AMDGPU") + end + + # B the transpose of a device matrix: the off-diagonal update indexes its views scalar by scalar. + @testset "B the $w of a device $S matrix, func=$func" for S in backend_types(AT, (Float32,)), w in (transpose,), func in ('S',) + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32], AT) + B0 = mxp_rand(S, 3, n) + X = w(AT(copy(B0))) + @test_broken (try unified_rectrxm!('L', 'L', 'N', 'N', one(S), func, Amp, X) + _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(mxp_host(Amp), 'L'), w(Array(parent(X))), w(B0)) <= + mxp_tol(Float16, n) + catch; false end) + end + + # B46: a complex B through a real split container reaches quantize, which has no complex method. + @testset "a $S B through a real container, func=$func" for S in backend_types(AT, (ComplexF32,)), func in ('S',) + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', DataType[Float16, Float32], AT) + B = mxp_rand(S, n, 3) + @test_broken (try X = Array(unified_rectrxm!('L', 'L', 'N', 'N', one(S), func, Amp, AT(copy(B)))) + maximum(f -> _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, _mxp_stored(mxp_host(Amp), 'L'), f(X), f(B)), + (real, imag)) <= mxp_tol(Float16, n) + catch; false end) + end + + # All-Float64 containers are held to Float64 accuracy. + supports_float64(AT) && @testset "Float64 accuracy, $(nameof(kind)) side=$side func=$func trans=$trans precisions=$P" for + P in (DataType[Float64], DataType[Float64, Float64]), kind in (TriMixedPrec, FullMixedPrec), + side in test_flags(:side, ('L', 'R')), func in ('S', 'M'), trans in test_flags(:trans, ('N', 'T')) + Amp = _mxp_trxm_container(kind, Float64, n, 'L', P, AT) + B = side == 'L' ? mxp_rand(Float64, n, 5) : mxp_rand(Float64, 5, n) + X = AT(copy(B)) + unified_rectrxm!(side, 'L', trans, 'N', 2.0, func, Amp, X) + @test X isa AT + @test _mxp_trxm_err(side, 'L', trans, 'N', func, 2.0, _mxp_stored(mxp_host(Amp), 'L'), X, B) <= mxp_tol(Float64, n) + end + + # n = 300 with [Float32] and n = 600 with [Float16, Float32] give a leaf past the threshold 256; 1200 is the next multiple. + @testset "$S input, n=$n1, precisions=$P" for n1 in test_values(:n, (300, 600, 1200)), + P in test_precisions((DataType[Float32], DataType[Float16, Float32])), S in backend_types(AT, (Float16, Float32, Float64)) + supports_float64(AT) || Float64 ∉ P || continue + for side in test_flags(:side, ('L', 'R')), func in ('S', 'M') + Amp = _mxp_trxm_container(TriMixedPrec, S, n1, 'L', P, AT) + B = side == 'L' ? mxp_rand(S, n1, 3) : mxp_rand(S, 3, n1) + X = AT(copy(B)) + tol = mxp_tol(mxp_narrowest(vcat(P, S)), n1) + Ad = _mxp_stored(mxp_host(Amp), 'L') + unified_rectrxm!(side, 'L', 'N', 'N', one(S), func, Amp, X) + @test _mxp_trxm_err(side, 'L', 'N', 'N', func, 1.0, Ad, X, B) <= tol + end + end + + @testset "n=$n1" for n1 in (1, 2) + T = supports_float64(AT) ? Float64 : Float32 + P = DataType[Float16, Float32] + Amp = TriMixedPrec(AT(_mxp_trxm_matrix(T, n1, 'L')), 'L'; precisions=P) + B = mxp_rand(T, n1, 3) + X = AT(copy(B)) + Ad = _mxp_stored(mxp_host(Amp), 'L') + unified_rectrxm!('L', 'L', 'N', 'N', one(T), 'S', Amp, X) + @test _mxp_trxm_err('L', 'L', 'N', 'N', 'S', 1.0, Ad, X, B) <= mxp_tol(Float16, n1) + end + + # B with no columns (side 'L') or no rows (side 'R'). + @testset "an empty $S B, side=$side func=$func" for S in backend_types(AT, (Float32,)), + side in test_flags(:side, ('L', 'R')), func in ('S', 'M') + P = DataType[Float16, Float32] + Amp = _mxp_trxm_container(TriMixedPrec, Float32, n, 'L', P, AT) + X = AT(side == 'L' ? zeros(S, n, 0) : zeros(S, 0, n)) + @test unified_rectrxm!(side, 'L', 'N', 'N', one(S), func, Amp, X) === X + end + + # Off-diagonal blocks past floatmax(Float16), scaled at two levels, with signed values in Float32. + @testset "scaled off-diagonal blocks, uplo=$uplo side=$side func=$func trans=$trans diag=$diag" for + uplo in test_flags(:uplo, ('L', 'U')), side in test_flags(:side, ('L', 'R')), trans in test_flags(:trans, ('N', 'T')), + (func, diag) in test_flags((nothing, :diag), (('S', 'N'), ('M', 'N'), ('M', 'U'))) + ns, P = 32, DataType[Float16, Float16, Float32] + Amp = TriMixedPrec(AT(mxp_tri(uplo, mxp_rand(Float32, ns, ns)) .* 1f5 + 1f6I), uplo; precisions=P) + @test Amp.OffDiag_scale != 1 && Amp.A11.OffDiag_scale != 1 && Amp.A22.OffDiag_scale != 1 + B = side == 'L' ? mxp_rand(Float32, ns, 3) : mxp_rand(Float32, 3, ns) + X = AT(copy(B)) + Ad = _mxp_stored(mxp_host(Amp), uplo) + unified_rectrxm!(side, uplo, trans, diag, 2f0, func, Amp, X) + @test _mxp_trxm_err(side, uplo, trans, diag, func, 2.0, Ad, X, B) <= mxp_tol(Float16, ns) + 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 + P = DataType[Float16, Float32] + Amp = _mxp_trxm_container(TriMixedPrec, Float32, 8, 'L', P, AT) + B = mxp_rand(Float32, 8, 2) + B[2, 1] = Inf32 + X = AT(B) + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, 'M', Amp, X) + R = Array(X) + @test !isfinite(R[2, 1]) && all(isfinite, R[:, 2]) + end + + # An off-diagonal product keeps B values past floatmax(Float16) through a scaled copy. + @testset "an off-diagonal product keeps B values past floatmax(Float16), func=$func" for func in ('S', 'M') + ns, P = 16, DataType[Float16, Float32] + A = mxp_tri('L', mxp_rand(Float32, ns, ns)) + A[LinearAlgebra.diagind(A)] .= 2 .+ rand(Float32, ns) + Amp = TriMixedPrec(AT(A), 'L'; precisions=P) + B = 1.0f6 .* mxp_rand(Float32, ns, 3) + X = AT(copy(B)) + Ad = _mxp_stored(mxp_host(Amp), 'L') + unified_rectrxm!('L', 'L', 'N', 'N', 1f0, func, Amp, X) + @test all(isfinite, Array(X)) + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, Ad, X, B) <= mxp_tol(Float16, ns) + end + + # A leaf past floatmax(Float32) needs Float64 data. + @testset "a scaled leaf, func=$func" for func in ('S', 'M') + supports_float64(AT) || continue + ns = 16 + Amp = TriMixedPrec(AT(mxp_tri('L', mxp_rand(Float64, ns, ns)) .* 1.0e39 + 2.0e39I), 'L'; precisions=DataType[Float32]) + @test Amp.Base_scale != 1 + B = mxp_rand(Float64, ns, 4) + X = AT(copy(B)) + unified_rectrxm!('L', 'L', 'N', 'N', 1.0, func, Amp, X) + Ad = tril(Float64.(Array(Amp.Base)) .* Amp.Base_scale) + @test _mxp_trxm_err('L', 'L', 'N', 'N', func, 1.0, Ad, X, B) <= mxp_tol(Float32, ns) + end + + # diag 'U' with a scaled leaf: the stored unit diagonal stands for the scale, not 1 (src :148-151); needs Float64 data. + @testset "diag U with a scaled leaf, $(nameof(kind)) side=$side func=$func" for kind in (TriMixedPrec, FullMixedPrec), + side in test_flags(:side, ('L',)), func in ('S',) + supports_float64(AT) || continue + ns, P = kind === TriMixedPrec ? (8, DataType[Float32]) : (37, DataType[Float16, Float32]) + A = _mxp_trxm_matrix(Float64, ns, 'L') + A[LinearAlgebra.diagind(A)] .= 1e39 + Amp = kind === TriMixedPrec ? TriMixedPrec(AT(A), 'L'; precisions=P) : FullMixedPrec(AT(_mxp_trxm_full(A, 'L')); precisions=P) + B = side == 'L' ? mxp_rand(Float64, ns, 3) : mxp_rand(Float64, 3, ns) + X = AT(copy(B)) + unified_rectrxm!(side, 'L', 'N', 'U', 1.0, func, Amp, X) + @test_broken _mxp_trxm_err(side, 'L', 'N', 'U', func, 1.0, _mxp_stored(mxp_host(Amp), 'L'), X, B) <= mxp_tol(mxp_narrowest(P), ns) + end + + # On a device a Float32 block wider than a Float16 B is rounded to Float16 first (dense recgemm.jl:70-72), so values past 65504 overflow. + @testset "a Float32 block past floatmax(Float16) with a Float16 B, side=$side" for side in test_flags(:side, ('L', 'R')) + ns = 32 + A = mxp_tri('L', 1f5 .* mxp_rand(Float32, ns, ns)) + A[LinearAlgebra.diagind(A)] .= 1 + Amp = TriMixedPrec(AT(A), 'L'; precisions=DataType[Float32, Float32]) + B = Float16.(1f-3 .* (side == 'L' ? mxp_rand(Float32, ns, 2) : mxp_rand(Float32, 2, ns))) + X = AT(copy(B)) + @test_broken (try unified_rectrxm!(side, 'L', 'N', 'N', Float16(1), 'M', Amp, X) + all(isfinite, Array(X)) && + _mxp_trxm_err(side, 'L', 'N', 'N', 'M', 1.0, _mxp_stored(mxp_host(Amp), 'L'), X, B) <= mxp_tol(Float16, ns) + catch; false end) + end +end diff --git a/test/mxp/cholesky/recpotrf_mixedprec.jl b/test/mxp/cholesky/recpotrf_mixedprec.jl deleted file mode 100644 index 154473a6..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 NextLA.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]) - NextLA.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]) - NextLA.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 NextLA.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]) - NextLA.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.0e5 * ones(4, 4) + 1.0e6I, 'L'; precisions = DataType[Float16]) - @test mp.Base_scale != 1 - @test_throws ArgumentError NextLA.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..0169afae --- /dev/null +++ b/test/mxp/core/adaptive.jl @@ -0,0 +1,241 @@ +# adaptive_precisions (src/mxp/core/adaptive.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A") # the number options it takes (--params) + +cpu_wanted() && @testset "adaptive_precisions [CPU]" begin + n = 16 + A = mxp_trimat(Float64, n, 'L') + U = DataType[Float16, Float32, Float64] # the candidate types of most cases + + @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 + + # One level (n = 8, n_min = 4): the level takes the coarsest type with u(T) <= epsilon / (sqrt(2) E). + @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)) + @test U[findfirst(S -> mxp_u(S) <= ϵ / (sqrt(2) * E), U)] === T + @test adaptive_precisions(B, U, 4, ϵ) == DataType[T, Float64] + end + + # At the boundary ('F': norm 2, E = 1/2 on level 1) the level-1 target equals epsilon; 'L' reads norm sqrt(3). + @testset "the rule at its boundary, $T data" for T in test_types((Float16, Float32, Float64)) + B = zeros(T, 16, 16) + B[1, 1] = B[5, 1] = B[1, 5] = B[13, 9] = 1 + leaf = T === Float64 ? Float64 : Float32 + @test adaptive_precisions(B, U, 4, mxp_u(Float16); uplo='F') == DataType[Float16, Float16, leaf] + @test adaptive_precisions(B, U, 4, prevfloat(mxp_u(Float16)); uplo='F') == DataType[Float16, Float32, leaf] + @test adaptive_precisions(B, U, 4, mxp_u(Float16); uplo='L') == DataType[Float16, Float32, leaf] + @test adaptive_precisions(B, U, 4, mxp_u(Float16); uplo='f') == DataType[Float16, Float16, leaf] # uplo in either case + @test adaptive_precisions(B, U, 4, mxp_u(Float16); uplo='l') == DataType[Float16, Float32, leaf] + end + + # Zero off-diagonal blocks need no digits, so every level gets the coarsest type. + @testset "zero off-diagonal blocks get the coarsest type" begin + @test adaptive_precisions(Matrix(1.0I, 16, 16), U, 4, 1e-12) == DataType[Float16, Float16, Float64] + end + + # Equal block norms on two levels give different types through the depth factor 2^((k+1)/2). + @testset "two levels with equal block norms get different types" begin + B = Matrix(1.0I, 16, 16) + B[9:16, 1:8] .= 0.01 # level 0: one 8×8 block + B[5:8, 1:4] .= 0.02; B[13:16, 9:12] .= 0.02 # level 1: two 4×4 blocks of the same norm + E = norm(B[9:16, 1:8]) / norm(tril(B)) + ϵ = 6e-4 * sqrt(2) * E + @test adaptive_precisions(B, U, 4, ϵ) == DataType[Float16, Float32, Float64] + end + + # The levels match the containers' split: n = 13 splits once (8 + 5). + @testset "the levels match the containers' split, n=13" begin + A13 = tril(mxp_rand(Float64, 13, 13)) + 13I + p = adaptive_precisions(A13, U, 4, 1e-2) + @test length(p) == 2 + M = TriMixedPrec(A13, 'L'; precisions=p) + @test size(M.A11, 1) == 8 && M.A11.Base !== nothing && M.A22.Base !== nothing + end + + # The rule's error bound for a container: graded with a dominant diagonal (d > 0), or off-diagonal blocks carrying the norm (d = 0). + @testset "a container from the result meets the error the rule implies, n=$n, n_min=$n_min, d=$d, epsilon=$ϵ, uplo=$uplo" for + (n, n_min) in test_cases((:n, nothing), ((256, 16), (300, 4))), (d, ϵ) in ((0.0, 1e-4), (0.0, 1e-6), (0.2, 1e-6)), + uplo in test_flags(:uplo, ('L', 'U', 'F')) + G = [exp(-d * abs(i - j)) for i in 1:n, j in 1:n] .* mxp_rand(Float64, n, n) + S = d == 0 ? (uplo == 'F' ? G : G + G' + 2I) : G + G' + n * I + p = adaptive_precisions(S, U, n_min, ϵ; uplo) + L = length(p) - 1 + n == 300 && n_min == 4 && @test L == 3 # 300 splits unevenly over three levels + if uplo == 'F' + R = reconstruct_matrix(FullMixedPrec(S; precisions=p)) + @test norm(R - S) / norm(S) <= ϵ * sqrt(L) + mxp_u(p[end]) + else + T = mxp_tri(uplo, S) + R = reconstruct_matrix(TriMixedPrec(S, uplo; precisions=p)) + @test norm(R - T) / norm(T) <= ϵ * sqrt(L / 2) + mxp_u(p[end]) + end + 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 + + # At epsilon 1e-12 every level needs Float64; no level is finer than the leaves. + @testset "no level is finer than the leaves" begin + @test adaptive_precisions(A, U, 4, 1e-12) == DataType[Float64, Float64, Float64] + @test adaptive_precisions(Float32.(A), U, 4, 1e-12) == DataType[Float32, Float32, Float32] + @test adaptive_precisions(Float16.(A), U, 4, 1e-12) == DataType[Float32, Float32, Float32] + @test adaptive_precisions(A, DataType[Float16, Float32], 4, 1e-12) == DataType[Float32, Float32, 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 + + # The rule is relative: scaling A by a power of 2 leaves every level, up to the edges of each type's range. + @testset "scaling by 2^$e leaves the result, $T data" for T in test_types((Float16, Float32, Float64)), + e in (T === Float16 ? (-20, 10) : T === Float32 ? (100, -140) : (500, -500, -1060)) + X = T.(mxp_rand(Float64, 16, 16) + 16I) + @test adaptive_precisions(ldexp.(X, e), U, 4, 1e-4; uplo='F') == adaptive_precisions(X, U, 4, 1e-4; uplo='F') + end + + @testset "small and wrapped inputs" begin + @test adaptive_precisions(ones(1, 1)) == DataType[Float64] + @test adaptive_precisions([1.0 0; 0.5 1], U, 1, 1e-2) == DataType[Float16, Float64] # 2 splits 1 + 1 + Big = zeros(2n, 2n) + Big[1:2:2n, 1:2:2n] .= A + @test adaptive_precisions(view(Big, 1:2:2n, 1:2:2n)) == adaptive_precisions(A) + @test adaptive_precisions(A'; uplo='U') == adaptive_precisions(A) + end + + @testset "U may be given in any order" begin + @test adaptive_precisions(A, DataType[Float64, Float32]) == 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 + + # A NaN in the other triangle's off-diagonal block and in a leaf's other half is not read. + @testset "the other triangle is not read, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + X = uplo == 'L' ? A : copy(transpose(A)) + G = copy(X) + if uplo == 'L' + G[1, n] = NaN; G[1, 2] = NaN + else + G[n, 1] = NaN; G[2, 1] = NaN + end + @test adaptive_precisions(G; uplo) == adaptive_precisions(X; uplo) + end + + # B9: the rule is scale-free, but blocks are not scaled up, so small values lose digits in storage. + @testset "small values miss the error the rule implies (B9)" begin + X = ldexp.(mxp_rand(Float64, 64, 64), -24) + p = adaptive_precisions(X, U, 16, 1e-2; uplo='F') + @test_broken norm(reconstruct_matrix(FullMixedPrec(X; precisions=p)) - X) / norm(X) <= 1e-2 * sqrt(length(p) - 1) + mxp_u(p[end]) + 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 + + # One NaN or Inf in the part that is read, or a read triangle of zeros, is refused. + @testset "a non-finite entry or a zero triangle is refused" begin + X = copy(A); X[10, 2] = Inf + @test_throws "A must be finite" adaptive_precisions(X) + X = copy(A); X[3, 3] = NaN + @test_throws "A must be finite" adaptive_precisions(X) + X = Float16.(A); X[10, 2] = Inf16 + @test_throws "A must be finite" adaptive_precisions(X) + Z = zeros(n, n); Z[1, n] = 1 + @test_throws "A must not be zero" adaptive_precisions(Z; uplo='L') + end + + # B46: a complex matrix is accepted, though no container takes complex data. + @testset "complex input is refused, $T" for T in test_types((ComplexF32,)) + @test_broken (try adaptive_precisions(T.(A)); false catch e; e isa ArgumentError end) + 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) + U = DataType[Float16, Float32, Float64] + + # Each uplo and each element type on the device, signed, with the default arguments too. + @testset "a device matrix, $T, uplo=$uplo, n=$n" for T in backend_types(AT, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U', 'F')), + n in test_values(:n, (13,)) + G = mxp_rand(Float64, n, n) + S = G + G' + n * I + X = T.(uplo == 'U' ? triu(S) : S) + if !supports_float64(AT) && T === Float16 + # B44: Float16 block norms are summed in Float64 on the device; NEXTLA_TEST_NO_FLOAT64 cannot reproduce it. + if get(ENV, "NEXTLA_TEST_NO_FLOAT64", "0") == "1" + _test_note("Float16 device rows skipped under NEXTLA_TEST_NO_FLOAT64: B44 shows only on a device without Float64") + else + @test_broken adaptive_precisions(AT(X), U, 4, 1e-4; uplo) == adaptive_precisions(X, U, 4, 1e-4; uplo) + end + continue + end + @test adaptive_precisions(AT(X), U, 4, 1e-4; uplo) == adaptive_precisions(X, U, 4, 1e-4; uplo) + T === Float32 && uplo == 'L' && @test adaptive_precisions(AT(X); uplo) == adaptive_precisions(X; uplo) # the defaults, once + end + + # Several levels and a scaled block, compared with the CPU; refusals on the device. + @testset "several levels, a scaled block and refusals on the device" begin + X = mxp_rand(Float32, 64, 64) + 64f0 * I + X[40:48, 3:10] .*= 1f20 + for uplo in test_flags(:uplo, ('L', 'U', 'F')) + @test adaptive_precisions(AT(X), U, 4, 1e-4; uplo) == adaptive_precisions(X, U, 4, 1e-4; uplo) + end + Y = copy(X); Y[10, 2] = NaN32 + @test_throws "A must be finite" adaptive_precisions(AT(Y)) + Y = copy(X); Y[10, 2] = Inf32 + @test_throws "A must be finite" adaptive_precisions(AT(Y)) + Y = copy(X); Y[3, 3] = NaN32 # in a leaf + @test_throws "A must be finite" adaptive_precisions(AT(Y)) + Z = zeros(Float32, 16, 16); Z[1, 16] = 1 + @test_throws "A must not be zero" adaptive_precisions(AT(Z); uplo='L') + Big = zeros(Float32, 128, 128) + Big[1:2:128, 1:2:128] .= X + @test adaptive_precisions(view(AT(Big), 1:2:128, 1:2:128)) == adaptive_precisions(X) + end + + # The rule is relative on the device too. + @testset "scaling by 2^$e leaves the result, $T data" for T in backend_types(AT, (Float16, Float32, Float64)), + e in (T === Float16 ? (-20, 10) : T === Float32 ? (100, -140) : (500, -500)) + T === Float16 && !supports_float64(AT) && continue # B44, pinned above + X = ldexp.(T.(mxp_rand(Float64, 16, 16) + 16I), e) + @test adaptive_precisions(AT(X), U, 4, 1e-4; uplo='F') == adaptive_precisions(X, U, 4, 1e-4; uplo='F') + end + + # B46: a complex matrix is accepted, though no container takes complex data. + @testset "complex input is refused, $T" for T in backend_types(AT, (ComplexF32,)) + @test_broken (try adaptive_precisions(AT(T.(mxp_rand(Float64, 8, 8) + 8I))); false catch e; e isa ArgumentError end) + end +end diff --git a/test/mxp/core/blocks.jl b/test/mxp/core/blocks.jl new file mode 100644 index 00000000..04455b2b --- /dev/null +++ b/test/mxp/core/blocks.jl @@ -0,0 +1,247 @@ +# The block helpers (src/mxp/core/blocks.jl): argument checks and storing blocks with their scale. Helpers: test/setup/mxp.jl. + +# A leaf built from the stored triangle (_quantize_triangle_block) equals tril!/triu! then _quantize_mixedprec_block, +# scaled or not, from a matrix or a view, with junk in the other half; Inf in the stored half throws. +function _mxp_tri_block_check(AT) + @testset "leaf from the stored triangle, $S into $T, n=$n, lo=$lo, view=$v, scaled=$sc" for S in backend_types(AT, (Float16, Float32, Float64)), + T in backend_types(AT, (Float16, Float32, Float64)), n in (33, 1024), lo in (true, false), v in (false, true), sc in (false, true) + x = 4 * Float64(floatmax(T)) + sc && !(x < floatmax(S)) && continue # a scale only where S holds a value past T's range + R = S.(mxp_rand(Float64, n + 1, n) .* (sc ? x : 1)) + lo ? (R[1:n, :] .= ifelse.((1:n) .< (1:n)', S(NaN), R[1:n, :])) : (R[1:n, :] .= ifelse.((1:n) .> (1:n)', S(NaN), R[1:n, :])) + D = mxp_on(AT, R) + X = v ? view(D, 1:n, :) : mxp_on(AT, R[1:n, :]) + q, s = MixedPrecision._quantize_triangle_block(X, lo, T) + q0, s0 = MixedPrecision._quantize_mixedprec_block((lo ? tril : triu)(R[1:n, :]), T) + @test Array(q) == q0 && s == s0 && (s != 1) == sc + AT === Array || @test q isa AT + R[lo ? n : 1, lo ? 1 : n] = S(Inf) + @test_throws "must be finite" MixedPrecision._quantize_triangle_block(mxp_on(AT, R[1:n, :]), lo, T) + end +end + +cpu_wanted() && @testset "block helpers [CPU]" begin + _mxp_tri_block_check(Array) + + @testset "leaves narrower than Float32 are refused, $S input" for S in test_types((Float64,)) + @test_throws "leaf precision" FullMixedPrec(rand(S, 4, 4); precisions=DataType[Float16]) + @test_throws "leaf precision" SymmMixedPrec(rand(S, 4, 4), 'L'; precisions=DataType[Float16, Float16]) + @test_throws "leaf precision" TriMixedPrec(rand(S, 4, 4), 'L'; precisions=DataType[Float16, Float16]) + @test_throws "leaf precision" TiledTriMixedPrec(rand(S, 4, 4), 'L'; precisions=DataType[Float16, Float16], threshold=2) + @test FullMixedPrec(rand(S, 4, 4); precisions=DataType[Float16, Float32]) isa FullMixedPrec + end + + # The shared argument checks, on every constructor. + @testset "arguments are checked, $(nameof(C)), $S input" for C in (FullMixedPrec, SymmMixedPrec, TriMixedPrec, TiledTriMixedPrec), + S in test_types((Float64,)) + 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 "input matrix must not be empty" make(zeros(S, 0, 0), DataType[Float64]) + @test_throws DimensionMismatch make(rand(S, 4, 8), DataType[Float64]) + @test_throws "precisions must not be empty" make(rand(S, 4, 4), DataType[]) + @test_throws "precisions must be Float8_E5M2" make(rand(S, 4, 4), DataType[Int]) + @test_throws "precisions must be Float8_E5M2" make(rand(S, 4, 4), DataType[Float16, ComplexF64]) + @test_throws "must be finite" make(S[1 0; NaN 1], DataType[Float64]) + @test_throws "must be finite" make(S[1 0; Inf 1], DataType[Float64]) + # Float64 input too large for a block with a Float32 scale (here the Float32 leaf refuses it). + @test_throws "too large for Float32 storage" make(fill(1.0e300, 4, 4), DataType[Float16, Float32]) + end + + # The precisions are used in the order given (as adaptive_precisions returns them); a narrow leaf is refused. + @testset "precisions keep their order" begin + M = FullMixedPrec(mxp_rand(Float64, 8, 8); precisions=DataType[Float32, Float16, Float64]) + @test eltype(M.A21) === Float32 && eltype(M.A11.A21) === Float16 && eltype(M.A11.A11.Base) === Float64 + @test_throws "the leaf precision" FullMixedPrec(mxp_rand(Float64, 8, 8); precisions=DataType[Float64, Float16]) + end + + # An all-zero matrix is stored and read back exactly, every scale 1. + @testset "a zero matrix, $(nameof(C)), $S input" for C in (FullMixedPrec, SymmMixedPrec, TriMixedPrec, TiledTriMixedPrec), + S in test_types((Float64,)) + P = DataType[Float16, Float64] + Z = zeros(S, 5, 5) + M = C === FullMixedPrec ? C(Z; precisions=P) : + C === TiledTriMixedPrec ? C(Z, 'L'; precisions=P, threshold=2) : C(Z, 'L'; precisions=P) + scales = C === FullMixedPrec ? [M.A21_scale, M.A12_scale, M.A11.Base_scale, M.A22.Base_scale] : + C === TiledTriMixedPrec ? [M.diag_scales; vec(M.off_scales)] : [M.OffDiag_scale, M.A11.Base_scale, M.A22.Base_scale] + @test all(iszero, reconstruct_matrix(M)) && all(==(1), scales) + end + + # A block of tiny values is not scaled up, so Float16 loses its digits (source issue B9). + @testset "a tiny Float16 block keeps its digits, FullMixedPrec, Float64 input" begin + A = ones(4, 4) + A[3:4, 1:2] .= 1e-7 + R = reconstruct_matrix(FullMixedPrec(A; precisions=DataType[Float16, Float64])) + @test_broken all(abs.(R[3:4, 1:2] .- A[3, 1]) .<= 2mxp_u(Float16) * A[3, 1]) + end + + # The largest value a Float16 off-diagonal block holds is floatmax(Float32) * floatmax(Float16) ≈ 2.23e43. + @testset "the scaling limit of a Float16 block, FullMixedPrec" begin + make(A) = FullMixedPrec(A; precisions=DataType[Float16, Float64]) + A = ones(4, 4) + A[3:4, 1:2] .= 2.0e43 + M = make(A) + B, s = M.A21, M.A21_scale + @test 1 < s <= floatmax(Float32) && all(isfinite, B) && maximum(abs, B) <= floatmax(Float16) + @test reconstruct_matrix(M)[3:4, 1:2] ≈ fill(2.0e43, 2, 2) rtol=2mxp_u(Float16) + A[3:4, 1:2] .= 2.3e43 + @test_throws "too large for Float16 storage" make(A) + end + + # The exact limit is stored with scale floatmax(Float32); the next float needs a larger scale and throws. + @testset "the exact scaling limit of a Float16 block" begin + L = Float64(floatmax(Float32)) * floatmax(Float16) + q, s = MixedPrecision._quantize_mixedprec_block(fill(L, 2, 2), Float16) + @test s == floatmax(Float32) && maximum(abs, q) == floatmax(Float16) + @test_throws "too large for Float16 storage" MixedPrecision._quantize_mixedprec_block(fill(nextfloat(L), 2, 2), Float16) + end + + # Integer input is converted to floats; a typemin(Int) block (|typemin| past typemax) is stored scaled. + @testset "Int input, FullMixedPrec" begin + B = ones(Int, 4, 4) + B[3:4, 1:2] .= typemin(Int) + M = FullMixedPrec(B; precisions=DataType[Float16, Float64]) + @test reconstruct_matrix(M)[3:4, 1:2] ≈ fill(Float64(typemin(Int)), 2, 2) rtol=2mxp_u(Float16) + end + + # From a block already scaled by 4: the new scale carries the old one. + @testset "a solve that outgrows a scaled Float16 block" begin + blk = fill(Float16(100), 2, 2) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1000), blk, 4f0, Float32) + @test s > 4 + @test Float32.(blk) .* s ≈ fill(4f5, 2, 2) rtol=2mxp_u(Float16) + end + + # A Float64 base: the solve works on a Float64 copy, past floatmax(Float32). + @testset "a solve with a Float64 base outgrows a $T block" for (T, x) in ((Float16, 1e40), (Float32, 1e39)) + blk = fill(T(1), 2, 2) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= x), blk, 1f0, Float64) + @test s > 1 + @test Float64.(blk) .* s ≈ fill(x, 2, 2) rtol=2mxp_u(T) + 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 "past what Float32 storage" MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1e80), blk, 1f0, Float64) + @test blk == fill(1f0, 2, 2) + 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, 4f0) + @test s > 4 + @test Float32.(blk) .* s ≈ fill(4f6, 2, 2) rtol=2mxp_u(Float16) + end + + # The in-place Float16 update (Float16 operands) gives the bits and the scale of the Float32-copy update. + @testset "in-place Float16 update equals the Float32 copy" begin + X, Y, B0 = Float16.(mxp_rand(Float32, 8, 5)), Float16.(mxp_rand(Float32, 5, 8)), Float16.(mxp_rand(Float32, 8, 8)) + upd = P -> NextLA._gemm_dispatch!(0.7f0, X, Y, 0.5f0, P) + b1, b2 = copy(B0), copy(B0) + @test MixedPrecision._update_offdiag!(upd, b1, 1f0, X, Y) == MixedPrecision._update_mixedprec_offdiag_block!(upd, b2, 1f0) + @test b1 == b2 + end + + # The update runs in Float32, so a result past floatmax(Float32) gives Inf even with a Float64 leaf (review G2, as B10/B49). + @testset "an off-diagonal update past floatmax(Float32), $P" for P in (DataType[Float16, Float64],) + M = FullMixedPrec(ones(8, 8); precisions=P) + recgemm!(1e38, ones(8, 8), ones(8, 8), 1.0, M) + @test_broken reconstruct_matrix(M)[1, 8] ≈ 8e38 + 1 rtol=2mxp_u(P[1]) + end + + # A result with NaN or Inf is stored as it is and the scale stays (constructors refuse non-finite input). + @testset "a non-finite result is stored as it is, $T block, $x" for T in test_types((Float16, Float32)), x in (NaN32, -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 + + # B46: complex input is not supported yet; this becomes @test when it is. + @testset "a complex matrix round-trips, FullMixedPrec, ComplexF64" begin + A = rand(ComplexF64, 4, 4) + @test_broken (try reconstruct_matrix(FullMixedPrec(A; precisions=DataType[Float16, Float64])) ≈ A catch; false end) + end +end + +# On each GPU backend: the same helpers on device blocks. +@testset "block helpers [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + _mxp_tri_block_check(AT) + + @testset "a solve that outgrows a scaled Float16 block" begin + blk = AT(fill(Float16(100), 2, 2)) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1000), blk, 4f0, Float32) + @test blk isa AT + @test s > 4 + @test Float32.(Array(blk)) .* s ≈ fill(4f5, 2, 2) rtol=2mxp_u(Float16) + end + + supports_float64(AT) && @testset "a solve with a Float64 base outgrows a $T block" for (T, x) in ((Float16, 1e40), (Float32, 1e39)) + blk = AT(fill(T(1), 2, 2)) + s = MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= x), blk, 1f0, Float64) + @test blk isa AT + @test s > 1 + @test Float64.(Array(blk)) .* s ≈ fill(x, 2, 2) rtol=2mxp_u(T) + 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 + + # With a Float64 base: refused, and the block is left as it was. + supports_float64(AT) && @testset "a solve past what the scale can carry throws" begin + blk = AT(fill(1f0, 2, 2)) + @test_throws "past what Float32 storage" MixedPrecision._solve_mixedprec_offdiag_block!(W -> (W .*= 1e80), blk, 1f0, Float64) + @test Array(blk) == fill(1f0, 2, 2) + end + + @testset "an update past floatmax of a Float16 block raises its scale, from scale $s0" for s0 in (4f0,) + blk = AT(fill(Float16(1), 2, 2)) + s = MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .= 1f6), blk, s0) + @test blk isa AT && s > s0 + @test Float64.(Array(blk)) .* s ≈ fill(1e6 * s0, 2, 2) rtol=2mxp_u(Float16) + end + + # As on the CPU: a result past floatmax(Float32) gives Inf (review G2, as B10/B49). + supports_float64(AT) && @testset "an off-diagonal update past floatmax(Float32), $P" for P in (DataType[Float16, Float64],) + M = FullMixedPrec(AT(ones(8, 8)); precisions=P) + recgemm!(1e38, AT(ones(8, 8)), AT(ones(8, 8)), 1.0, M) + @test_broken Array(reconstruct_matrix(M))[1, 8] ≈ 8e38 + 1 rtol=2mxp_u(P[1]) + end + + @testset "an update of a Float32 block runs in place" begin + blk = AT(fill(1f0, 2, 2)) + @test MixedPrecision._update_mixedprec_offdiag_block!(P -> (P .+= 1), blk, 1f0) == 1f0 + @test blk isa AT && Array(blk) == fill(2f0, 2, 2) + end + + @testset "a non-finite result is stored as it is, $T block, $x" for T in test_types((Float16, Float32)), x in (NaN32, -Inf32) + TB = supports_float64(AT) ? Float64 : Float32 + blk = AT(fill(T(1), 2, 2)) + @test MixedPrecision._update_mixedprec_offdiag_block!(P -> fill!(view(P, 1:1, 1:1), x), blk, 1f0) == 1f0 + @test isequal(Array(blk)[1, 1], T(x)) && Array(blk)[2, 2] == 1 + blk = AT(fill(T(1), 2, 2)) + @test MixedPrecision._solve_mixedprec_offdiag_block!(W -> fill!(view(W, 1:1, 1:1), x), blk, 2f0, TB) == 2f0 + @test isequal(Array(blk)[1, 1], T(x)) && Array(blk)[2, 2] == 1 + end +end + +# Values too large for any scale are refused on the device too, for each container (needs Float64). +@testset "too-large values are refused [$name], FullMixedPrec" for (name, AT, _) in filter(b -> b[1] != "CPU" && supports_float64(b[2]), MXP_BACKENDS) + @test_throws "too large for Float32 storage" FullMixedPrec(AT(fill(1.0e300, 4, 4)); precisions=DataType[Float16, Float32]) +end diff --git a/test/mxp/core/fullmixedprec.jl b/test/mxp/core/fullmixedprec.jl new file mode 100644 index 00000000..bf1e7184 --- /dev/null +++ b/test/mxp/core/fullmixedprec.jl @@ -0,0 +1,151 @@ +# FullMixedPrec (src/mxp/core/fullmixedprec.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A") # the number options it takes (--params) + +_full_valid(n) = n >= 1 || "FullMixedPrec needs n >= 1" + +# Distinct signed values past floatmax(Float16): one scale at the top level, another inside A11. +function _full_two_levels(T) + A = ones(T, 8, 8) + A[5:8, 1:4] .= T.(1e5 .* reshape(range(-1, 1; length=16), 4, 4)) + A[1:4, 5:8] .= T.(2e5 .* reshape(range(1, -0.5; length=16), 4, 4)) + A[3:4, 1:2] .= T.(3e5 .* [1 -0.7; 0.3 -0.55]) + A[1:2, 3:4] .= T.(3e5 .* [-1 0.6; 0.25 0.8]) + return A +end + +# A scaled block reads back as the stored value times its scale, rounded once to the leaf type. +_full_unscaled(B, s, T) = T.(Float64.(B) .* Float64(s)) + +cpu_wanted() && @testset "FullMixedPrec [CPU]" begin + @testset "$T, n=$n" for T in test_types((Float32, Float64)), n in test_values(:n, (1, 2, 5, 8, 13); valid=_full_valid) + 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 + + # Float64 input also with a Float32 leaf, narrower than the input. + @testset "precisions=$P" for P in test_precisions((DataType[Float32, T], DataType[Float16, Float32, T], + DataType[Float16, Float16, Float32, T], + (T === Float64 ? (DataType[Float16, Float32],) : ())...)) + M = FullMixedPrec(A; precisions=P) + R = reconstruct_matrix(M) + E = mxp_expected_type_map(n, P) + @test eltype(R) === P[end] + @test mxp_eltype_map(M) == E + @test mxp_storage_ok(R, A, E) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + @test M[1, 1] isa P[end] + end + end + + # Float16 input: stored exactly (every block type holds it). + @testset "$T input, n=$n, precisions=$P" for T in test_types((Float16,)), n in test_values(:n, (1, 2, 5, 13); valid=_full_valid), + P in test_precisions((DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64])) + A = T.(mxp_rand(Float32, n, n)) + M = FullMixedPrec(A; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === P[end] + @test mxp_eltype_map(M) == mxp_expected_type_map(n, P) + @test R == P[end].(A) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + end + + # A view as input gives the same container as its copy. + @testset "a view as input, n=$n, precisions=$P" for n in test_values(:n, (13,); valid=_full_valid), + P in test_precisions((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_expected_type_map(n, P)) + end + + # Scaled off-diagonal blocks of two levels, each read back exactly through its own scale, element by element. + @testset "scaled off-diagonal blocks of two levels, $T leaf" for T in test_types((Float32,)) + A = _full_two_levels(T) + M = FullMixedPrec(A; precisions=DataType[Float16, Float16, T]) + @test M.A21_scale != 1 && M.A12_scale != 1 && M.A11.A21_scale != 1 + @test M.A21_scale != M.A12_scale && M.A21_scale != M.A11.A21_scale + R = reconstruct_matrix(M) + @test R[5:8, 1:4] == _full_unscaled(M.A21, M.A21_scale, T) + @test R[1:4, 5:8] == _full_unscaled(M.A12, M.A12_scale, T) + @test R[3:4, 1:2] == _full_unscaled(M.A11.A21, M.A11.A21_scale, T) + @test R[1:2, 3:4] == _full_unscaled(M.A11.A12, M.A11.A12_scale, T) + @test all(abs.(R .- A) .<= 2mxp_u(Float16) .* abs.(A)) + @test all(M[i, j] == R[i, j] for i in 1:8, j in 1:8) + end + + # A leaf past floatmax(T_Base) is kept scaled; it reads back as 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)) + @test isinf(M[1, 1]) # getindex applies the leaf's scale too + 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: built, stored and read back on the device. +@testset "FullMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + f64 = supports_float64(AT) + + # Every input type and precision list, equal to the CPU result; Float64 cases need Float64 on the device. + @testset "$T input, n=$n, precisions=$P" for T in test_types((Float16, Float32, Float64)), n in test_values(:n, (5, 13); valid=_full_valid), + P in test_precisions((DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float16, Float32], + DataType[Float16, Float32, Float64])) + f64 || (T !== Float64 && Float64 ∉ P) || continue + A = mxp_rand(T, n, n) + M = FullMixedPrec(AT(A); precisions=P) + R = reconstruct_matrix(M) + @test R isa AT + @test eltype(R) === P[end] + @test length(P) == 1 || n == 1 || (M.A21 isa AT && M.A12 isa AT) # n = 1 is a single leaf + @test mxp_eltype_map(mxp_host(M)) == mxp_expected_type_map(n, P) + @test mxp_storage_ok(Array(R), A, mxp_expected_type_map(n, P)) + @test Array(R) == reconstruct_matrix(FullMixedPrec(A; precisions=P)) + end + + # Scaled off-diagonal blocks of two levels built on the device equal the CPU container, scales too. + @testset "scaled off-diagonal blocks of two levels, $T leaf" for T in backend_types(AT, (Float32,)) + A = _full_two_levels(T) + P = DataType[Float16, Float16, T] + M, Mc = FullMixedPrec(AT(A); precisions=P), FullMixedPrec(A; precisions=P) + @test M.A21_scale == Mc.A21_scale != 1 && M.A12_scale == Mc.A12_scale && M.A11.A21_scale == Mc.A11.A21_scale + @test Array(reconstruct_matrix(M)) == reconstruct_matrix(Mc) + end + + @testset "a view of a device array as input" begin + B = mxp_rand(Float32, 16, 16) + P = DataType[Float16, Float32] + R = reconstruct_matrix(FullMixedPrec(view(AT(B), 2:14, 3:15); precisions=P)) + @test R isa AT + @test Array(R) == reconstruct_matrix(FullMixedPrec(B[2:14, 3:15]; precisions=P)) + end + + f64 && @testset "NaN and Inf are refused on the device" begin + @test_throws ArgumentError FullMixedPrec(AT([1.0 NaN; 0.0 1.0]); precisions=DataType[Float64]) + @test_throws ArgumentError FullMixedPrec(AT([1.0 Inf; 0.0 1.0]); precisions=DataType[Float64]) + end +end + +# The blocks are copies of the input: overwriting the input leaves the container as it was. +@testset "FullMixedPrec copies the input [$name]" for (name, AT, _) in MXP_BACKENDS + Ad = mxp_on(AT, mxp_rand(Float32, 13, 13)) + M = FullMixedPrec(Ad; precisions=DataType[Float16, Float32]) + R = Array(reconstruct_matrix(M)) + fill!(Ad, 0) + @test Array(reconstruct_matrix(M)) == R +end + diff --git a/test/mxp/core/quantize.jl b/test/mxp/core/quantize.jl new file mode 100644 index 00000000..6073f872 --- /dev/null +++ b/test/mxp/core/quantize.jl @@ -0,0 +1,186 @@ +# quantize and dequantize (src/mxp/core/quantize.jl). Helpers: test/setup/mxp.jl. + +cpu_wanted() && @testset "quantize and dequantize [CPU]" begin + @testset "$S to $T" for S in test_types((Float16, Float32, Float64)), T in test_types((Float16, Float32)) + A = mxp_rand(S, 32, 32) .* S(1000) + A0 = copy(A) + q, s = quantize(A, T) + @test eltype(q) === T && s === 1f0 + back = dequantize(q, s, S) + @test mxp_storage_ok(back, A, fill(T, size(A))) + fill!(q, 0) # the result is a new array: writing to it leaves A as it was + @test A == A0 + end + + @testset "a Float64 target keeps Float64 input" begin + A = mxp_rand(Float64, 4, 4) + q, s = quantize(A, Float64) + @test q == A && q !== A && s === 1f0 + end + + @testset "the default type is Float16" begin + @test eltype(first(quantize(rand(Float32, 4, 4)))) === Float16 + end + + # Values past floatmax(T), mixed signs, are stored with the smallest Float32 scale that fits and come back within u(T). + @testset "values past floatmax(T) come back scaled, $S to $T" for (S, T, c) in + ((Float32, Float16, 1e7), (Float64, Float16, 1e7), (Float64, Float32, 1e39)) + A = mxp_rand(S, 32, 32) .* S(c) + q, s = quantize(A, T) + @test eltype(q) === T && s > 1 && all(isfinite, q) + @test Float64(prevfloat(s)) * floatmax(T) < maximum(abs, Float64.(A)) # the next smaller scale would not fit + @test mxp_storage_ok(dequantize(q, s, S), A, fill(T, size(A))) + end + + # A scaled block with tiny, zero and middle values: a tiny value is subnormal in T after the division, so its error is up to s·η(T). + @testset "a scaled block with tiny, zero and middle values, $S" for S in test_types((Float64,)) + A = mxp_rand(S, 8, 8) .* S(1e7) + A[1, 1] = S(1e-3); A[2, 2] = 0; A[3, 3] = S(-2e-2) + q, s = quantize(A, Float16) + @test s > 1 + D = dequantize(q, s, S) + @test D[2, 2] == 0 + @test all(abs.(Float64.(D) .- Float64.(A)) .<= mxp_u(Float16) .* abs.(Float64.(A)) .+ Float64(s) * mxp_eta(Float16)) + end + + # Scaling starts just past floatmax(Float16) = 65504. + @testset "the scaling threshold of Float16, $x" for x in (65504.0, 65520.0) + q, s = quantize(fill(x, 2, 2), Float16) + @test (s == 1) == (x <= 65504) + @test all(isfinite, q) && maximum(abs, q) <= floatmax(Float16) + @test mxp_storage_ok(dequantize(q, s, Float64), fill(x, 2, 2), fill(Float16, 2, 2)) + end + + # B9: a block of tiny values is not scaled up (s = 1, as documented), so Float16 loses its digits. + @testset "a tiny block keeps scale 1 (B9)" begin + @test quantize(fill(3e-6, 2, 2), Float16)[2] === 1f0 + 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, or one past what the scale can carry, throws" begin + @test_throws ArgumentError quantize([1.0 NaN]) + @test_throws ArgumentError quantize([1.0 Inf]) + @test_throws ArgumentError quantize([1.0 -Inf]) + @test_throws ArgumentError quantize(Float32[1 NaN]) + @test_throws ArgumentError quantize(Float16[1 Inf]) + @test_throws ArgumentError quantize(fill(1.0e300, 2, 2), Float16) + end + + # A view and a transpose as input (unified_rectrxm! quantizes views of B). + @testset "a view and a transpose as input, $S" for S in test_types((Float64,)) + A = mxp_rand(S, 8, 8) .* S(1e6) + q, s = quantize(view(A, 2:5, 3:7)) + @test size(q) == (4, 5) && s > 1 + @test mxp_storage_ok(dequantize(q, s, S), A[2:5, 3:7], fill(Float16, 4, 5)) + q, s = quantize(transpose(A)) + @test mxp_storage_ok(dequantize(q, s, S), Matrix(transpose(A)), fill(Float16, 8, 8)) + end + + @testset "dequantize into a type that cannot hold the values gives Inf" begin + q, s = quantize(fill(1e5, 2, 2)) + @test all(==(Inf), dequantize(q, s, Float16)) + 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 + + @testset "complex input is refused" begin + @test_throws MethodError quantize(rand(ComplexF32, 2, 2)) + @test_throws MethodError quantize(rand(ComplexF64, 2, 2), Float32) + @test_throws MethodError dequantize(Float16[1 2], 1f0, ComplexF64) + end +end + +# On each GPU backend: the result stays on the device and has the CPU's bits. +@testset "quantize and dequantize [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + n = 13 + + @testset "quantize and dequantize stay on the device, $S to $T" for S in backend_types(AT, (Float16, Float32, Float64)), + T in test_types((Float16, Float32)) + A = mxp_rand(S, n, n) + q, s = quantize(AT(A), T) + @test q isa AT && eltype(q) === T + qc, sc = quantize(A, T) + @test s === sc && Array(q) == qc # the same bits as the CPU + back = dequantize(q, s, S) + @test back isa AT + @test mxp_storage_ok(Array(back), A, fill(T, n, n)) + end + + @testset "values past floatmax(T) come back scaled on the device, $S to $T" for (S, T, c) in + filter(x -> x[1] in backend_types(AT, (x[1],)), ((Float32, Float16, 1e7), (Float64, Float16, 1e7), (Float64, Float32, 1e39))) + A = mxp_rand(S, n, n) .* S(c) + q, s = quantize(AT(A), T) + @test q isa AT && eltype(q) === T && s > 1 + qc, sc = quantize(A, T) + @test s === sc && Array(q) == qc + @test mxp_storage_ok(Array(dequantize(q, s, S)), A, fill(T, n, n)) + end + + @testset "a view of a device matrix, $S" for S in backend_types(AT, (Float32,)) + A = mxp_rand(S, n, n) .* S(1e6) + q, s = quantize(view(AT(A), 2:6, 3:9)) + @test q isa AT && s > 1 + @test mxp_storage_ok(Array(dequantize(q, s, S)), A[2:6, 3:9], fill(Float16, 5, 7)) + end + + @testset "NaN and Inf throw, and a zero and an empty matrix, $S" for S in backend_types(AT, (Float32,)) + @test_throws ArgumentError quantize(AT(S[1 NaN])) + @test_throws ArgumentError quantize(AT(S[1 Inf])) + @test_throws ArgumentError quantize(AT(S[1 -Inf])) + z, sz = quantize(AT(zeros(S, 4, 4))) + @test z isa AT && sz === 1f0 && all(iszero, Array(z)) + qe, se = quantize(AT(zeros(S, 0, 3))) + @test qe isa AT && size(qe) == (0, 3) && se === 1f0 + end + + # A scaled block with tiny, zero and middle values on the device: the same bits as the CPU, within u(T)|a| + s·η(T). + @testset "a scaled block with tiny, zero and middle values on the device, $S" for S in backend_types(AT, (Float32,)) + A = mxp_rand(S, 8, 8) .* S(1e7) + A[1, 1] = S(1e-3); A[2, 2] = 0; A[3, 3] = S(-2e-2) + q, s = quantize(AT(A), Float16) + qc, sc = quantize(A, Float16) + @test s === sc > 1 && Array(q) == qc + D = Array(dequantize(q, s, S)) + @test D[2, 2] == 0 + @test all(abs.(Float64.(D) .- Float64.(A)) .<= mxp_u(Float16) .* abs.(Float64.(A)) .+ Float64(s) * mxp_eta(Float16)) + end + + @testset "the scaling threshold of Float16 on the device, $x" for x in (65504f0, 65520f0) + q, s = quantize(AT(fill(x, 2, 2)), Float16) + qc, sc = quantize(fill(x, 2, 2), Float16) + @test (s == 1) == (x <= 65504) + @test Array(q) == qc && s === sc + end + + @testset "the result is a new device array" begin + A = mxp_rand(Float32, n, n) + Ad = AT(A) + q, _ = quantize(Ad, Float32) + fill!(q, 0) + @test Array(Ad) == A + end + + # A transpose of a device matrix works; an array wrapped twice falls back to scalar indexing, which GPUs refuse. + @testset "wrapped device matrices" begin + A = mxp_rand(Float32, n, n) .* 1f5 + q, s = quantize(transpose(AT(A))) + @test q isa AT && Array(q) == first(quantize(Matrix(transpose(A)))) + @test_throws ErrorException quantize(view(transpose(AT(A)), 2:6, :)) + @test_throws ErrorException quantize(transpose(view(AT(A), 2:6, :))) + end + + @testset "complex input is refused on the device" begin + @test_throws MethodError quantize(AT(rand(ComplexF32, 2, 2))) + end +end diff --git a/test/mxp/core/symmmixedprec.jl b/test/mxp/core/symmmixedprec.jl new file mode 100644 index 00000000..6728f7f8 --- /dev/null +++ b/test/mxp/core/symmmixedprec.jl @@ -0,0 +1,129 @@ +# SymmMixedPrec (src/mxp/core/symmmixedprec.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A") # the number options it takes (--params) + +# A symmetric test matrix with entries of both signs. +_symm_rand(T, n) = (X = mxp_rand(T, n, n); X + X') + +# A symmetric matrix with distinct signed values past floatmax(Float16): one scale at the top level, another inside A11. +function _symm_two_levels(T) + A = ones(T, 8, 8) + A[5:8, 1:4] .= T.(1e5 .* reshape(range(-1, 1; length=16), 4, 4)) + A[3:4, 1:2] .= T.(3e5 .* [1 -0.7; 0.3 -0.55]) + A[1:4, 5:8] .= transpose(A[5:8, 1:4]) + A[1:2, 3:4] .= transpose(A[3:4, 1:2]) + return A +end + +# The lower off-diagonal block as read back: the stored block (transposed for 'U') times its scale, rounded once to T. +_symm_unscaled(B, s, T, uplo) = T.(Float64.(uplo == 'L' ? B : transpose(B)) .* Float64(s)) + +cpu_wanted() && @testset "SymmMixedPrec [CPU]" begin + @testset "$T, uplo=$uplo, n=$n, precisions=$P" for T in test_types((Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), + n in test_values(:n, (1, 2, 7, 8, 13)), P in test_precisions((DataType[Float32, T], DataType[Float16, Float32, T], + DataType[Float16, Float16, Float32, T]); valid = P -> P[end] === T || "this check keeps the input type, so the list must end with $T") + A = _symm_rand(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_eltype_map(M) == mxp_expected_type_map(n, P) + @test mxp_storage_ok(R, A, mxp_expected_type_map(n, P)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + end + + @testset "one precision: a single leaf, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A = _symm_rand(Float64, 8) + M = SymmMixedPrec(A, uplo; precisions=DataType[Float64]) + @test M.Base !== nothing && M.OffDiag === nothing + @test reconstruct_matrix(M) == A + @test transpose(M) === M + end + + # A leaf past floatmax(T_Base) is kept scaled; it reads back as Inf. + @testset "a leaf past floatmax of its type is stored with a scale" begin + uplo = '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)) + @test isinf(M[1, 1]) # getindex applies the leaf's scale too + end + + # Two levels with different scales, each read back exactly. + @testset "off-diagonal blocks of two levels with different scales, $T leaf, uplo=$uplo" for T in test_types((Float32,)), + uplo in test_flags(:uplo, ('L', 'U')) + A = _symm_two_levels(T) + M = SymmMixedPrec(A, uplo; precisions=DataType[Float16, Float16, T]) + @test M.OffDiag_scale != 1 && M.A11.OffDiag_scale != 1 && M.OffDiag_scale != M.A11.OffDiag_scale + R = reconstruct_matrix(M) + @test R[5:8, 1:4] == _symm_unscaled(M.OffDiag, M.OffDiag_scale, T, uplo) + @test R[3:4, 1:2] == _symm_unscaled(M.A11.OffDiag, M.A11.OffDiag_scale, T, uplo) + @test R == transpose(R) + @test all(abs.(R .- A) .<= 2mxp_u(Float16) .* abs.(A)) + @test all(M[i, j] == R[i, j] for i in 1:8, j in 1:8) + end + + # Float16 input: stored exactly (Float16 and Float32 hold it). + @testset "Float16 input, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + P = DataType[Float16, Float32] + A = Float16.(_symm_rand(Float32, 13)) + M = SymmMixedPrec(A, uplo; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === Float32 + @test mxp_eltype_map(M) == mxp_expected_type_map(13, P) + @test mxp_storage_ok(R, A, mxp_expected_type_map(13, P)) + @test R == Float32.(A) + end + + @testset "arguments are checked" begin + @test_throws ArgumentError SymmMixedPrec(rand(4, 4), 'X'; precisions=DataType[Float64]) + end + + @testset "uplo in either case, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A = rand(8, 8); A = A + A' + a, b = SymmMixedPrec(A, uplo; precisions=DataType[Float32, Float64]), SymmMixedPrec(A, lowercase(uplo); precisions=DataType[Float32, Float64]) + @test b.uplo == uplo && reconstruct_matrix(b) == reconstruct_matrix(a) + end + + @testset "out-of-bounds indexing throws" begin + @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) + f64 = supports_float64(AT) + + # Every input type and precision list, equal to the CPU result; Float64 cases need Float64 on the device. + @testset "$T input, n=$n, precisions=$P, uplo=$uplo" for T in test_types((Float16, Float32, Float64)), n in test_values(:n, (1, 2, 5, 13)), + P in test_precisions((DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64])), uplo in test_flags(:uplo, ('L', 'U')) + f64 || (T !== Float64 && Float64 ∉ P) || continue + n <= 2 && T !== Float32 && continue # the smallest sizes in one type + A = _symm_rand(T, n) + M = SymmMixedPrec(AT(A), uplo; precisions=P) + R = reconstruct_matrix(M) + @test R isa AT && eltype(R) === P[end] + @test length(P) == 1 || n == 1 || M.OffDiag isa AT # n = 1 is a single leaf + length(P) == 1 && @test M.Base isa AT + @test mxp_eltype_map(mxp_host(M)) == mxp_expected_type_map(n, P) + @test Array(R) == reconstruct_matrix(SymmMixedPrec(A, uplo; precisions=P)) + end + + # Scaled off-diagonal blocks of two levels built on the device equal the CPU container, scales too. + @testset "scaled off-diagonal blocks on the device, $T leaf, uplo=$uplo" for T in backend_types(AT, (Float32,)), + uplo in test_flags(:uplo, ('L', 'U')) + A = _symm_two_levels(T) + P = DataType[Float16, Float16, T] + M, Mc = SymmMixedPrec(AT(A), uplo; precisions=P), SymmMixedPrec(A, uplo; precisions=P) + @test M.OffDiag_scale == Mc.OffDiag_scale != 1 && M.A11.OffDiag_scale == Mc.A11.OffDiag_scale != 1 + @test Array(reconstruct_matrix(M)) == reconstruct_matrix(Mc) + end + + @testset "NaN and Inf are refused on the device" begin + @test_throws ArgumentError SymmMixedPrec(AT(Float32[1 NaN; NaN 1]), 'L'; precisions=DataType[Float32]) + @test_throws ArgumentError SymmMixedPrec(AT(Float32[1 Inf; Inf 1]), 'L'; precisions=DataType[Float32]) + end +end diff --git a/test/mxp/core/tiledtrimixedprec.jl b/test/mxp/core/tiledtrimixedprec.jl new file mode 100644 index 00000000..ca40b591 --- /dev/null +++ b/test/mxp/core/tiledtrimixedprec.jl @@ -0,0 +1,198 @@ +# TiledTriMixedPrec (src/mxp/core/tiledtrimixedprec.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A", tile = "largest tile (the threshold)") # the number options it takes (--params) + +# A given --precisions list: a tiled container takes one or two types (off-diagonal, then diagonal). +_tiled_precisions(P) = length(P) <= 2 || "TiledTriMixedPrec takes one or two precisions" +_tiled_valid(n, t) = (n >= 1 && t >= 1) || "n and tile must be at least 1" + +# Tile sizes written out for the default layouts, checked against mxp_tile_sizes. +const _TILED_SIZES = Dict((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], (1, 4) => [1], (2, 1) => [1, 1]) + +# Every stored off-diagonal tile reads back as its stored value times its scale, rounded once to the diagonal type. +function _tiled_exact(M, R) + o, T = M.offsets, eltype(R) + return all(R[o[r]:o[r+1]-1, o[c]:o[c+1]-1] == T.(Float64.(M.off[r, c]) .* Float64(M.off_scales[r, c])) + for r in axes(M.off, 1), c in axes(M.off, 2) if M.off[r, c] !== nothing) +end + +cpu_wanted() && @testset "TiledTriMixedPrec [CPU]" begin + # The tile sizes are TriMixedPrec's split (n/2 or the largest power of 2 below n) down to threshold rows. + @testset "$T input, uplo=$uplo, n=$n, threshold=$t, precisions=$P" for T in test_types((Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), + (n, t) in test_cases((:n, :tile), ((8, 4), (8, 2), (7, 3), (13, 4), (5, 1), (6, 6), (1, 4), (2, 1)); valid = _tiled_valid), + P in test_precisions((DataType[Float32, Float64], DataType[Float16, Float64], DataType[Float16, Float32], + DataType[Float64]); valid = _tiled_precisions) + A = mxp_tri(uplo, mxp_rand(T, n, n)) + M = TiledTriMixedPrec(A, uplo; precisions=P, threshold=t) + @test size(M) == (n, n) && size(M, 1) == n + @test size.(M.diag, 1) == mxp_tile_sizes(n, t) + haskey(_TILED_SIZES, (n, t)) && @test mxp_tile_sizes(n, t) == _TILED_SIZES[(n, t)] + @test count(!isnothing, M.off) == length(M.diag) * (length(M.diag) - 1) ÷ 2 # the other triangle is not stored + R = reconstruct_matrix(M) + @test eltype(R) === P[end] + @test mxp_eltype_map(M) == mxp_expected_tile_map(n, t, P) + @test mxp_storage_ok(R, A, mxp_expected_tile_map(n, t, P)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + end + + # Two off-diagonal tiles with different scales (signed values), and one with scale 1: each read through its own. + @testset "tiles with different scales read back unscaled, $T, uplo=$uplo" for T in test_types((Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')) + A = ones(T, 6, 6) + A[3:4, 1:2] .= T.(1e5 .* [1 -0.7; 0.3 -0.55]) + A[5:6, 1:2] .= T(3e5) + A = uplo == 'L' ? tril(A) : triu(copy(transpose(A))) + M = TiledTriMixedPrec(A, uplo; precisions=DataType[Float16, T], threshold=2) + s = uplo == 'L' ? (M.off_scales[2, 1], M.off_scales[3, 1], M.off_scales[3, 2]) : (M.off_scales[1, 2], M.off_scales[1, 3], M.off_scales[2, 3]) + @test s[1] != 1 && s[2] != 1 && s[1] != s[2] && s[3] == 1 + r(i, j) = uplo == 'L' ? M[i, j] : M[j, i] + @test r(3, 1) ≈ 1.0e5 rtol=2mxp_u(Float16) + @test r(4, 2) ≈ -0.55e5 rtol=2mxp_u(Float16) + @test r(5, 1) ≈ 3.0e5 rtol=2mxp_u(Float16) + @test r(5, 3) == 1 + R = reconstruct_matrix(M) + @test _tiled_exact(M, R) + @test all(M[i, j] == R[i, j] for i in 1:6, j in 1:6) + end + + # A diagonal tile past floatmax of its type is kept scaled: Inf in the stored triangle, zero in the other. + @testset "a diagonal tile past floatmax of its type is stored with a scale, uplo=$uplo" for uplo in test_flags(:uplo, ('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)) + @test isinf(M[1, 1]) && isinf(M[6, 6]) # getindex applies each diagonal tile's scale too + end + + # Only the uplo triangle of a full input is read: a NaN in the other triangle is never read. + @testset "only the uplo triangle of a full input is read, uplo=$uplo" for uplo in test_flags(:uplo, ('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) + G0 = copy(G) + M = TiledTriMixedPrec(G, uplo; precisions=DataType[Float32, Float64], threshold=4) + @test isequal(G, G0) # the input is left as it was + @test mxp_storage_ok(reconstruct_matrix(M), mxp_tri(uplo, A), mxp_expected_tile_map(8, 4, DataType[Float32, Float64])) + # NaN or Inf in a stored off-diagonal tile (the uplo triangle) is refused. + for bad in (NaN, Inf) + H = mxp_tri(uplo, mxp_rand(Float64, 8, 8)) + uplo == 'L' ? (H[8, 1] = bad) : (H[1, 8] = bad) + @test_throws ArgumentError TiledTriMixedPrec(H, uplo; precisions=DataType[Float32, Float64], threshold=4) + end + end + + # The tiles are copies of A (also diagonal tiles of A's own type): overwriting A leaves the container as it was. + @testset "every tile is a copy of A, uplo=$uplo, precisions=$P" for uplo in test_flags(:uplo, ('L', 'U')), + P in test_precisions((DataType[Float32, Float64],); valid = _tiled_precisions) + A = mxp_tri(uplo, mxp_rand(Float64, 13, 13)) + M = TiledTriMixedPrec(A, uplo; precisions=P, threshold=4) + R = reconstruct_matrix(M) + A .= 0 + @test reconstruct_matrix(M) == R + 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 test_flags(:uplo, ('L', 'U')), + P in test_precisions((DataType[Float32, Float64], DataType[Float16, Float64]); valid = _tiled_precisions) + 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_eltype_map(M) == mxp_expected_tile_map(13, 4, P) + @test mxp_storage_ok(R, mxp_tri(uplo, copy(V)), mxp_expected_tile_map(13, 4, P)) + 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 "uplo in either case, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A = rand(8, 8) + a = TiledTriMixedPrec(A, uplo; precisions=DataType[Float32, Float64], threshold=2) + b = TiledTriMixedPrec(A, lowercase(uplo); precisions=DataType[Float32, Float64], threshold=2) + @test b.uplo == uplo && reconstruct_matrix(b) == reconstruct_matrix(a) + 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) + f64 = supports_float64(AT) + + # Every input type and precision list, equal to the CPU result; Float64 cases need Float64 on the device. + @testset "$T input, n=$n, threshold=$t, precisions=$P, uplo=$uplo" for T in backend_types(AT, (Float16, Float32, Float64)), + P in test_precisions((DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float64]); valid = _tiled_precisions), + (n, t) in test_cases((:n, :tile), ((8, 2), (13, 4), (6, 6), (5, 1), (1, 4), (2, 1)); valid = _tiled_valid), uplo in test_flags(:uplo, ('L', 'U')) + f64 || Float64 ∉ P || continue + A = mxp_tri(uplo, mxp_rand(T, n, n)) + M = TiledTriMixedPrec(AT(A), uplo; precisions=P, threshold=t) + R = reconstruct_matrix(M) + @test R isa AT && eltype(R) === P[end] + @test mxp_eltype_map(M) == mxp_expected_tile_map(n, t, P) + @test Array(R) == reconstruct_matrix(TiledTriMixedPrec(A, uplo; precisions=P, threshold=t)) + end + + # Two off-diagonal tiles with different scales built on the device equal the CPU container. + @testset "tiles with different scales on the device, $T, uplo=$uplo" for T in backend_types(AT, (Float32, Float64)), + uplo in test_flags(:uplo, ('L', 'U')) + A = ones(T, 6, 6) + A[3:4, 1:2] .= T(1e5) + A[5:6, 1:2] .= T(3e5) + A = uplo == 'L' ? tril(A) : triu(copy(transpose(A))) + P = DataType[Float16, T] + M, Mc = TiledTriMixedPrec(AT(A), uplo; precisions=P, threshold=2), TiledTriMixedPrec(A, uplo; precisions=P, threshold=2) + @test M.off_scales == Mc.off_scales && count(!=(1), M.off_scales) == 2 + @test Array(reconstruct_matrix(M)) == reconstruct_matrix(Mc) + end + + # A view of a device array as input equals the CPU container of the copied view. + @testset "a view of a device array as input, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + B = mxp_rand(Float32, 16, 16) + P = DataType[Float16, Float32] + R = reconstruct_matrix(TiledTriMixedPrec(view(AT(B), 2:14, 3:15), uplo; precisions=P, threshold=4)) + @test R isa AT + @test Array(R) == reconstruct_matrix(TiledTriMixedPrec(B[2:14, 3:15], uplo; precisions=P, threshold=4)) + end + + # NaN in the unread triangle (in an off-diagonal tile and inside a diagonal tile) is ignored; NaN or Inf in the stored one is refused. + @testset "unread and stored triangle on the device, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + P = DataType[Float16, Float32] + G = mxp_tri(uplo, mxp_rand(Float32, 8, 8)) + uplo == 'L' ? (G[1, 8] = NaN32; G[1, 2] = NaN32) : (G[8, 1] = NaN32; G[2, 1] = NaN32) + @test Array(reconstruct_matrix(TiledTriMixedPrec(AT(G), uplo; precisions=P, threshold=4))) == + reconstruct_matrix(TiledTriMixedPrec(G, uplo; precisions=P, threshold=4)) + for bad in (NaN32, Inf32) + H = mxp_tri(uplo, mxp_rand(Float32, 8, 8)) + uplo == 'L' ? (H[8, 1] = bad) : (H[1, 8] = bad) + @test_throws ArgumentError TiledTriMixedPrec(AT(H), uplo; precisions=P, threshold=4) + end + end +end + +# A scaled diagonal tile built on the device equals the CPU container, scales too (values past floatmax(Float32) need Float64). +@testset "TiledTriMixedPrec scaled diagonal tile [$name], uplo=$uplo" for (name, AT, _) in filter(b -> b[1] != "CPU" && supports_float64(b[2]), MXP_BACKENDS), uplo in test_flags(:uplo, ('L', 'U')) + A = mxp_tri(uplo, fill(1.0e39, 8, 8)) + 1.0e40I + Md, Mc = TiledTriMixedPrec(AT(A), uplo; precisions=DataType[Float32, Float32], threshold=4), TiledTriMixedPrec(A, uplo; precisions=DataType[Float32, Float32], threshold=4) + @test Array(reconstruct_matrix(Md)) == reconstruct_matrix(Mc) && Md.diag_scales == Mc.diag_scales +end + +# The tiles are copies of the device input: overwriting the input leaves the container as it was. +@testset "TiledTriMixedPrec copies the device input [$name], uplo=$uplo" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS), uplo in test_flags(:uplo, ('L', 'U')) + Ad = AT(mxp_tri(uplo, mxp_rand(Float32, 13, 13))) + M = TiledTriMixedPrec(Ad, uplo; precisions=DataType[Float16, Float32], threshold=4) + R = Array(reconstruct_matrix(M)) + fill!(Ad, 0) + @test Array(reconstruct_matrix(M)) == R +end diff --git a/test/mxp/core/transposedmixedprec.jl b/test/mxp/core/transposedmixedprec.jl new file mode 100644 index 00000000..ae1917a4 --- /dev/null +++ b/test/mxp/core/transposedmixedprec.jl @@ -0,0 +1,107 @@ +# The lazy transpose and adjoint (src/mxp/core/transposedmixedprec.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A") # the number options it takes (--params) + +const _TMP = MixedPrecision.TransposedMixedPrec + +# Full, Tri and TiledTri with each uplo --uplo keeps. +const _TMP_KINDS = ((FullMixedPrec, nothing), ((TriMixedPrec, u) for u in test_flags(:uplo, ('L', 'U')))..., + ((TiledTriMixedPrec, u) for u in test_flags(:uplo, ('L', 'U')))...) +const _TMP_PRECISIONS = (DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64]) + +# scaled = true multiplies the data by 3e5, so the Float16 blocks are stored scaled, with both signs. +function _tmp_data(S, n, scaled) + A = mxp_rand(S, n, n) + scaled && (A .*= S(3.0e5)) + return A +end + +function _tmp_container(kind, uplo, A, P) + kind === FullMixedPrec && return FullMixedPrec(A; precisions=P) + kind === TriMixedPrec && return TriMixedPrec(A, uplo; precisions=P) + return TiledTriMixedPrec(A, uplo; precisions=P, threshold=4) +end + +_tmp_scaled(M::FullMixedPrec) = M.A21_scale != 1 +_tmp_scaled(M::TriMixedPrec) = M.OffDiag_scale != 1 +_tmp_scaled(M::TiledTriMixedPrec) = any(!=(1), M.off_scales) + +# The cases a container cannot take or that have nothing to scale; a note when a run option caused it. +function _tmp_skip(kind, n, P, S, scaled) + if kind === TiledTriMixedPrec && length(P) > 2 + _test_option(:precisions) === nothing || + _test_note("TiledTriMixedPrec skipped for precisions=$(join(P, ",")): it takes one or two types") + return true + end + scaled || return false + S === Float16 && _test_option(:types) !== nothing && + _test_note("scaled cases skipped for Float16 input: 3e5 overflows Float16") + Float16 ∉ P && _test_option(:precisions) !== nothing && + _test_note("scaled cases skipped for precisions=$(join(P, ",")): no Float16 block to scale") + n == 1 && _test_option(:n) !== nothing && + _test_note("scaled cases skipped for n=1: a single leaf has no block to scale") + S === Float64 && _test_option(:types) !== nothing && + _test_note("scaled cases skipped for Float64 input: they run once, with Float32 input") + return n == 1 || S !== Float32 || Float16 ∉ P # scaled blocks once per container kind and list, Float32 input +end + +cpu_wanted() && @testset "TransposedMixedPrec [CPU]" begin + # Each element is the container's at the swapped index, exactly; adjoint is transpose for these real containers. + @testset "$S input, $(nameof(kind))$(uplo === nothing ? "" : " uplo=$uplo"), n=$n, precisions=$P$(scaled ? ", scaled" : "")" for + (kind, uplo) in _TMP_KINDS, n in test_values(:n, (1, 13)), P in test_precisions(_TMP_PRECISIONS), + S in test_types((Float16, Float32, Float64)), scaled in (false, true) + _tmp_skip(kind, n, P, S, scaled) && continue + M = _tmp_container(kind, uplo, _tmp_data(S, n, scaled), P) + scaled && @test _tmp_scaled(M) + Mᵀ = transpose(M) + @test adjoint(M) isa _TMP && parent(adjoint(M)) === M + @test Mᵀ isa _TMP + @test parent(Mᵀ) === M + @test transpose(Mᵀ) === M + @test adjoint(Mᵀ) === M + @test eltype(Mᵀ) === eltype(M) + @test all(Mᵀ[i, j] == M[j, i] for i in 1:n, j in 1:n) + @test reconstruct_matrix(Mᵀ) == [M[j, i] for i in 1:n, j in 1:n] + end + + @testset "out-of-bounds indexing throws" begin + @test_throws BoundsError transpose(FullMixedPrec(rand(4, 4); precisions=DataType[Float32, Float64]))[5, 1] + end + + # transpose of a SymmMixedPrec is itself; the wrapper the recursive TRSM builds reads the container's values. + @testset "$S input, SymmMixedPrec uplo=$uplo, n=$n, precisions=$P" for uplo in test_flags(:uplo, ('L', 'U')), n in test_values(:n, (13,)), + P in test_precisions((DataType[Float16, Float32, Float64],)), S in test_types((Float32,)) + A = mxp_rand(S, n, n) + M = SymmMixedPrec(A + transpose(A), uplo; precisions=P) + @test transpose(M) === M + @test adjoint(M) === M + W = _TMP(M) + @test parent(W) === M + @test transpose(W) === M + @test adjoint(W) === M + @test all(W[i, j] == M[j, i] for i in 1:n, j in 1:n) + @test reconstruct_matrix(W) == [M[j, i] for i in 1:n, j in 1:n] + end +end + +# On each GPU backend: wrapping copies nothing, and reconstruct_matrix transposes on the device (no element is read). +@testset "TransposedMixedPrec [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + @testset "$S input, $(nameof(kind))$(uplo === nothing ? "" : " uplo=$uplo"), n=$n, precisions=$P$(scaled ? ", scaled" : "")" for + (kind, uplo) in _TMP_KINDS, n in test_values(:n, (13,)), P in test_precisions(_TMP_PRECISIONS), S in backend_types(AT, (Float16, Float32, Float64)), + scaled in (false, true) + supports_float64(AT) || Float64 ∉ P || continue + _tmp_skip(kind, n, P, S, scaled) && continue + M = _tmp_container(kind, uplo, AT(_tmp_data(S, n, scaled)), P) + scaled && @test _tmp_scaled(M) + Mᵀ = transpose(M) + @test adjoint(M) isa _TMP && parent(adjoint(M)) === M + @test Mᵀ isa _TMP + @test parent(Mᵀ) === M + @test transpose(Mᵀ) === M + @test adjoint(Mᵀ) === M + @test eltype(Mᵀ) === eltype(M) + R = reconstruct_matrix(Mᵀ) + @test R isa AT + @test Array(R) == transpose(Array(reconstruct_matrix(M))) + end +end diff --git a/test/mxp/core/trimixedprec.jl b/test/mxp/core/trimixedprec.jl new file mode 100644 index 00000000..a8653a1c --- /dev/null +++ b/test/mxp/core/trimixedprec.jl @@ -0,0 +1,229 @@ +# TriMixedPrec (src/mxp/core/trimixedprec.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A") # the number options it takes (--params) + +# A triangle with distinct signed values past floatmax(Float16): one scale at the top level, another inside A11. +function _tri_two_levels(T, uplo) + L = tril(ones(T, 8, 8)) + L[5:8, 1:4] .= T.(1e5 .* reshape(range(-1, 1; length=16), 4, 4)) + L[3:4, 1:2] .= T.(3e5 .* [1 -0.7; 0.3 -0.55]) + return uplo == 'L' ? L : copy(transpose(L)) +end + +# The off-diagonal block of the stored triangle with rows/columns r1, r2 ('L': A[r2, r1]; 'U': A[r1, r2]). +_tri_block(R, uplo, r1, r2) = uplo == 'L' ? R[r2, r1] : R[r1, r2] + +# A scaled block reads back as the stored value times its scale, rounded once to T. +_tri_unscaled(B, s, T) = T.(Float64.(B) .* Float64(s)) + +cpu_wanted() && @testset "TriMixedPrec [CPU]" begin + @testset "$T, uplo=$uplo, n=$n, precisions=$P" for T in test_types((Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), + n in test_values(:n, (1, 2, 7, 8, 13)), P in test_precisions((DataType[Float32, T], DataType[Float16, Float32, T], + DataType[Float16, Float16, Float32, T]); valid = P -> P[end] === T || "this check keeps the input type, so the list must end with $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_eltype_map(M) == mxp_expected_type_map(n, P) + @test mxp_storage_ok(R, A, mxp_expected_type_map(n, P)) + @test all(M[i, j] == R[i, j] for i in 1:n, j in 1:n) + end + + @testset "one precision: a single leaf, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A = mxp_tri(uplo, mxp_rand(Float64, 8, 8)) + M = TriMixedPrec(A, uplo; precisions=DataType[Float64]) + @test M.Base !== nothing && M.OffDiag === nothing + @test reconstruct_matrix(M) == A + end + + # A leaf past floatmax of T_Base is kept scaled: Inf in the stored triangle, zero in the other. + @testset "a leaf past floatmax of its type is stored with a scale" begin + uplo = 'L' + 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)) + @test isinf(M[1, 1]) # getindex applies the leaf's scale too + end + + # A NaN in the unread triangle, the other off-diagonal block and inside a leaf is never read. + @testset "the other triangle is not read, uplo=$uplo" for uplo in test_flags(:uplo, ('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_expected_type_map(8, DataType[Float32, Float64])) + end + + # [Float64, Float64]: every block has the input's type, so a block that aliased A would show. + @testset "every block is a copy of A, uplo=$uplo, precisions=$P" for uplo in test_flags(:uplo, ('L', 'U')), + P in test_precisions((DataType[Float64], DataType[Float32, Float64], DataType[Float64, 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 + + # The input is left as it is: the other triangle is dropped from copies only. + @testset "only the uplo triangle of a full input is kept, uplo=$uplo, precisions=$P" for uplo in test_flags(:uplo, ('L', 'U')), + P in test_precisions((DataType[Float64], DataType[Float32, Float64])) + A = mxp_rand(Float64, 8, 8) + A0 = copy(A) + M = TriMixedPrec(A, uplo; precisions=P) + @test A == A0 + @test mxp_storage_ok(reconstruct_matrix(M), mxp_tri(uplo, A), mxp_expected_type_map(8, P)) + end + + @testset "converts from SymmMixedPrec without copying, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + n = 13 + X = mxp_rand(Float64, n, n) + S = SymmMixedPrec(X + X', 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 test_flags(:uplo, ('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 mxp_storage_ok(reconstruct_matrix(M), mxp_tri(uplo, A), mxp_expected_type_map(4, DataType[Float16, Float64])) + 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 + + # Two levels with different scales, each read back exactly; the other side stays zero. + @testset "off-diagonal blocks of two levels with different scales, $T leaf, uplo=$uplo" for T in test_types((Float32,)), + uplo in test_flags(:uplo, ('L', 'U')) + A = _tri_two_levels(T, uplo) + P = DataType[Float16, Float16, T] + M = TriMixedPrec(A, uplo; precisions=P) + @test M.OffDiag_scale != 1 && M.A11.OffDiag_scale != 1 && M.OffDiag_scale != M.A11.OffDiag_scale + R = reconstruct_matrix(M) + @test _tri_block(R, uplo, 1:4, 5:8) == _tri_unscaled(M.OffDiag, M.OffDiag_scale, T) + @test _tri_block(R, uplo, 1:2, 3:4) == _tri_unscaled(M.A11.OffDiag, M.A11.OffDiag_scale, T) + @test iszero(_tri_block(R, uplo, 5:8, 1:4)) && iszero(_tri_block(R, uplo, 3:4, 1:2)) + @test mxp_storage_ok(R, A, mxp_expected_type_map(8, P)) + @test all(M[i, j] == R[i, j] for i in 1:8, j in 1:8) + end + + # Float16 input: stored exactly (Float16 and Float32 hold it). + @testset "Float16 input, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + P = DataType[Float16, Float32] + A = Float16.(mxp_tri(uplo, mxp_rand(Float32, 13, 13))) + M = TriMixedPrec(A, uplo; precisions=P) + R = reconstruct_matrix(M) + @test eltype(R) === Float32 + @test mxp_eltype_map(M) == mxp_expected_type_map(13, P) + @test mxp_storage_ok(R, A, mxp_expected_type_map(13, P)) + @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 test_flags(:uplo, ('L', 'U')), + P in test_precisions((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_eltype_map(M) == mxp_expected_type_map(13, P) + @test mxp_storage_ok(R, mxp_tri(uplo, copy(V)), mxp_expected_type_map(13, P)) + end + + @testset "arguments are checked" begin + @test_throws ArgumentError TriMixedPrec(rand(4, 4), 'X'; precisions=DataType[Float64]) + end + + @testset "uplo in either case, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + A = rand(8, 8); A = A + A' + a, b = TriMixedPrec(A, uplo; precisions=DataType[Float32, Float64]), TriMixedPrec(A, lowercase(uplo); precisions=DataType[Float32, Float64]) + @test b.uplo == uplo && reconstruct_matrix(b) == reconstruct_matrix(a) + end + + @testset "out-of-bounds indexing throws" begin + @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) + f64 = supports_float64(AT) + + # Every input type and precision list, equal to the CPU result; Float64 cases need Float64 on the device. + @testset "$T input, n=$n, precisions=$P, uplo=$uplo" for T in test_types((Float16, Float32, Float64)), n in test_values(:n, (5, 13)), + P in test_precisions((DataType[Float32], DataType[Float16, Float32], DataType[Float16, Float32, Float64])), uplo in test_flags(:uplo, ('L', 'U')) + f64 || (T !== Float64 && Float64 ∉ P) || continue + A = mxp_tri(uplo, mxp_rand(T, n, n)) + M = TriMixedPrec(AT(A), uplo; precisions=P) + R = reconstruct_matrix(M) + @test R isa AT && eltype(R) === P[end] + @test length(P) == 1 || n == 1 || M.OffDiag isa AT # n = 1 is a single leaf + length(P) == 1 && @test M.Base isa AT + @test mxp_eltype_map(mxp_host(M)) == mxp_expected_type_map(n, P) + @test Array(R) == reconstruct_matrix(TriMixedPrec(A, uplo; precisions=P)) + end + + # Converting a device SymmMixedPrec shares its device blocks and equals the CPU conversion. + @testset "converts from SymmMixedPrec on the device, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + X = mxp_rand(Float32, 13, 13) + S = SymmMixedPrec(AT(X + X'), uplo; precisions=DataType[Float16, Float16, Float32]) + M = TriMixedPrec(S) + @test M.OffDiag === S.OffDiag && M.OffDiag isa AT + @test M.A11.OffDiag === S.A11.OffDiag && M.A11.OffDiag isa AT + @test Array(reconstruct_matrix(M)) == reconstruct_matrix(TriMixedPrec(mxp_host(S))) + end + + # A view of a device array as input equals the CPU container of the copied view. + @testset "a view of a device array as input, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + B = mxp_rand(Float32, 16, 16) + P = DataType[Float16, Float32] + R = reconstruct_matrix(TriMixedPrec(view(AT(B), 2:14, 3:15), uplo; precisions=P)) + @test R isa AT + @test Array(R) == reconstruct_matrix(TriMixedPrec(B[2:14, 3:15], uplo; precisions=P)) + end + + # Two levels of scaled blocks built on the device equal the CPU container, scales too. + @testset "scaled off-diagonal blocks on the device, $T leaf, uplo=$uplo" for T in backend_types(AT, (Float32,)), + uplo in test_flags(:uplo, ('L', 'U')) + A = _tri_two_levels(T, uplo) + P = DataType[Float16, Float16, T] + M, Mc = TriMixedPrec(AT(A), uplo; precisions=P), TriMixedPrec(A, uplo; precisions=P) + @test M.OffDiag_scale == Mc.OffDiag_scale != 1 && M.A11.OffDiag_scale == Mc.A11.OffDiag_scale != 1 + @test Array(reconstruct_matrix(M)) == reconstruct_matrix(Mc) + end +end + +# On the device NaN in the unread triangle, also inside a leaf, is ignored (equal to the CPU container); one in the stored triangle is refused. +@testset "TriMixedPrec unread triangle on the device [$name], uplo=$uplo" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS), uplo in test_flags(:uplo, ('L', 'U')) + P = DataType[Float16, Float32] + G = mxp_tri(uplo, mxp_rand(Float32, 8, 8)) + uplo == 'L' ? (G[1, 8] = NaN32; G[1, 2] = NaN32) : (G[8, 1] = NaN32; G[2, 1] = NaN32) + @test Array(reconstruct_matrix(TriMixedPrec(AT(G), uplo; precisions=P))) == reconstruct_matrix(TriMixedPrec(G, uplo; precisions=P)) + for bad in (NaN32, Inf32) + H = mxp_tri(uplo, mxp_rand(Float32, 8, 8)) + uplo == 'L' ? (H[8, 1] = bad) : (H[1, 8] = bad) + @test_throws ArgumentError TriMixedPrec(AT(H), uplo; precisions=P) + end +end + +# The blocks are copies of the device input: overwriting the input leaves the container as it was. +@testset "TriMixedPrec copies the device input [$name], uplo=$uplo" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS), uplo in test_flags(:uplo, ('L', 'U')) + A = mxp_rand(Float32, 13, 13) + Ad = AT(A) + M = TriMixedPrec(Ad, uplo; precisions=DataType[Float16, Float32]) + @test Array(Ad) == A # the input is left as it is + R = Array(reconstruct_matrix(M)) + fill!(Ad, 0) + @test Array(reconstruct_matrix(M)) == R +end diff --git a/test/mxp/gemm/recgemm_mixedprec.jl b/test/mxp/gemm/recgemm_mixedprec.jl deleted file mode 100644 index 048bf7aa..00000000 --- a/test/mxp/gemm/recgemm_mixedprec.jl +++ /dev/null @@ -1,114 +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 NextLA.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]) - NextLA.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 needs square A and B, k=$k" for k in [3, 20] - n = 8 - C_mp = FullMixedPrec(rand(Float64, n, n); precisions=DataType[Float32, Float64]) - @test_throws DimensionMismatch NextLA.recgemm!(1.0, rand(n, k), rand(k, n), 1.0, C_mp) - end - - @testset "an uneven split below the top needs its leaves, n=$n" for n in [5, 13] - # n = 5 splits 4 + 1: C11's second product A12 * B21 has k = 1. That is fine while - # C11 is a leaf and a DimensionMismatch once C11 is split again. - A, B, C_dense = rand(n, n), rand(n, n), rand(n, n) - leafy = FullMixedPrec(copy(C_dense); precisions=DataType[Float32, Float64]) - NextLA.recgemm!(1.0, A, B, 1.0, leafy) - @test reconstruct_matrix(leafy) ≈ A * B + C_dense rtol=1e-5 - deep = FullMixedPrec(copy(C_dense); precisions=DataType[Float32, Float32, Float64]) - @test_throws DimensionMismatch NextLA.recgemm!(1.0, A, B, 1.0, deep) - 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 - NextLA.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 - NextLA.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]) - NextLA.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]) - NextLA.recgemm!(one(T), A, B, one(T), C_seq; parallel=false) - NextLA.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 NextLA.recgemm!(1.0, rand(7, 4), rand(4, 8), 1.0, C_mp) - @test_throws DimensionMismatch NextLA.recgemm!(1.0, rand(8, 4), rand(4, 7), 1.0, C_mp) - @test_throws DimensionMismatch NextLA.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) - NextLA.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..90092cc9 --- /dev/null +++ b/test/mxp/lapack/cholesky/recpotrf_mixedprec.jl @@ -0,0 +1,235 @@ +# potrf_recursive! over a SymmMixedPrec container (src/mxp/lapack/cholesky/recpotrf_mixedprec.jl). Helpers: test/setup/mxp.jl. + +test_params(n = "order of A", block = "block size of the leaf Cholesky") # the number options it takes (--params) + +const MXP_POTRF_PRECISIONS = (DataType[Float32], DataType[Float32, Float32], DataType[Float16, Float32], + DataType[Float16, Float32, Float64], + DataType[Float16, Float16, Float32, Float64]) + +# The dense factor of a factored container: its uplo triangle, zeros in the other. +_mxp_factor(A) = reconstruct_matrix(TriMixedPrec(A)) + +# A signed SPD matrix: R*R' + n*I with R of random signs. +_mxp_potrf_spd(T, n) = (R = mxp_rand(T, n, n); S = R * R' + T(n) * I; (S + S') / 2) + +# A precision list with Float32 for Float64 on a device without Float64. +_mxp_potrf_list(AT, P) = supports_float64(AT) ? P : DataType[T === Float64 ? Float32 : T for T in P] + +# Relative error of the factored off-diagonal block of the host container H against a Float64 solve +# with its stored first leaf; B0 is the block (times its scale) before the call. +function _mxp_offdiag_err(H, B0) + L11 = Float64.(H.A11.Base) + L21 = Float64.(H.OffDiag) * H.OffDiag_scale + ref = H.uplo == 'L' ? B0 / LowerTriangular(L11)' : UpperTriangular(L11)' \ B0 + return norm(L21 - ref) / norm(ref) +end + +# Cases run on the CPU and on each GPU backend, read through a host copy of the container. +function _mxp_potrf_more(name, AT) + supports_float64(AT) && @testset "a leaf stored with a scale factor throws" begin + A = SymmMixedPrec(mxp_on(AT, 1.0e39 * ones(4, 4) + 1.0e40I), 'L'; precisions=DataType[Float32]) + @test A.Base_scale != 1 + @test_throws ArgumentError potrf_recursive!(A) + end + + # Metal refuses potrf! and oneAPI has none, so the leaves cannot be factored there. + if !has_device_potrf(name) + @testset "no device potrf! for the leaves throws ArgumentError" begin + @test_throws ArgumentError potrf_recursive!(SymmMixedPrec(AT(Matrix(1.0f0I, 8, 8)), 'L'; precisions=DataType[Float32])) + end + return + end + + # Signed SPD input; on a device without Float64 the lists take Float32 for it. + @testset "$S input, precisions=$P, uplo=$uplo, n=$n, block_size=$bs" for P in map(P -> _mxp_potrf_list(AT, P), test_precisions(MXP_POTRF_PRECISIONS)), + S in backend_types(AT, (Float16, Float32, Float64)), uplo in test_flags(:uplo, ('L', 'U')), + n in test_values(:n, AT === Array ? (13, 32, 40, 64) : (13, 64)), bs in test_values(:block, (8,)) + A0 = _mxp_potrf_spd(S, n) + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=P) + @test potrf_recursive!(A, bs) === A + F = _mxp_factor(mxp_host(A)) + @test uplo == 'L' ? istril(F) : istriu(F) + @test mxp_chol_backward_error(F, Float64.(A0), uplo) <= mxp_tol(mxp_narrowest(P), n) + if AT !== Array + # The blocks stay on the device, and the factor rebuilt there equals the host's. + @test (A.Base === nothing ? A.OffDiag : A.Base) isa AT + @test Array(_mxp_factor(A)) == F + end + end + + # Big sizes and multiples with the default block size (POTRF_BLOCK_SIZE). + @testset "n=$n, default block size, uplo=$uplo" for n in test_values(:n, (800, 1600, 3200)), uplo in test_flags(:uplo, ('L', 'U')) + d = rand((-1, 1), n) + A0 = mxp_spd(Float32, n) .* (d * d') # off-diagonal blocks carry the norm, so a missing update shows + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=DataType[Float16, Float16, Float32]) + potrf_recursive!(A) + @test mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(A0), uplo) <= mxp_tol(Float16, n) + end + + @testset "n=$n, uplo=$uplo" for n in (1, 2), uplo in test_flags(:uplo, ('L', 'U')) + A0 = mxp_spd(Float32, n) + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=DataType[Float16, Float32]) + potrf_recursive!(A, 8) + @test mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(A0), uplo) <= mxp_tol(Float16, n) + end + + # Condition numbers 1e3 and 1e4 with Float16 off-diagonal blocks: the backward error still meets the bound. + @testset "condition number $c, $S input, uplo=$uplo" for c in (1e3, 1e4), S in backend_types(AT, (Float32,)), + uplo in test_flags(:uplo, ('L', 'U')) + n = 64 + A0 = spd(S, n; cond=c) + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=DataType[Float16, Float32]) + potrf_recursive!(A, 8) + @test mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(A0), uplo) <= mxp_tol(Float16, n) + end + + # The factor is read through TriMixedPrec(A); reconstruct_matrix mirrors it into both triangles. + @testset "the factor is read through TriMixedPrec, $S input, uplo=$uplo" for S in backend_types(AT, (Float32,)), + uplo in test_flags(:uplo, ('L', 'U')) + A = SymmMixedPrec(mxp_on(AT, mxp_spd(S, 16)), uplo; precisions=_mxp_potrf_list(AT, DataType[Float32, Float64])) + potrf_recursive!(A) + H = mxp_host(A) + F, R = _mxp_factor(H), reconstruct_matrix(H) + @test mxp_tri(uplo, R) == F + @test R == transpose(R) + end + + # An off-diagonal block stored with a scale: the solve runs on the stored values and the scale carries through. + @testset "a scaled off-diagonal block, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + S = 1.0f6 * mxp_spd(Float32, 16) + A = SymmMixedPrec(mxp_on(AT, copy(S)), uplo; precisions=DataType[Float16, Float32]) + @test A.OffDiag_scale != 1 + potrf_recursive!(A, 4) + @test mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(S), uplo) <= mxp_tol(Float16, 16) + end + + # Graded input: the solved block passes floatmax(Float16) and is stored with its scale raised. + @testset "a solve past floatmax(Float16) raises the scale, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + D = Diagonal(Float32[fill(1.0f-3, 4); fill(1.0f6, 4)]) + S = D * mxp_spd(Float32, 8) * D + A = SymmMixedPrec(mxp_on(AT, copy(S)), uplo; precisions=DataType[Float16, Float32]) + @test A.OffDiag_scale == 1 + potrf_recursive!(A, 2) + F = _mxp_factor(mxp_host(A)) + @test A.OffDiag_scale > 1 + @test all(isfinite, F) + @test mxp_chol_backward_error(F, Float64.(S), uplo) <= mxp_tol(Float16, 8) + end + + # Per block with Float16 off-diagonal blocks: solved in Float32 and rounded once; the first leaf factored in Float32. + @testset "per-block accuracy, uplo=$uplo, n=$n" for uplo in test_flags(:uplo, ('L', 'U')), + n in test_values(:n, (16, 64); valid = n -> n >= 2 || "needs an off-diagonal block") + A0 = _mxp_potrf_spd(Float32, n) + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=DataType[Float16, Float32]) + n1 = A.A11.n + B0 = Float64.(Array(A.OffDiag)) * A.OffDiag_scale + potrf_recursive!(A, 8) + H = mxp_host(A) + @test _mxp_offdiag_err(H, B0) <= mxp_u(Float16) + mxp_tol(Float32, n1) + @test mxp_chol_backward_error(H.A11.Base, Float64.(A0[1:n1, 1:n1]), uplo) <= mxp_tol(Float32, n1) + end + + # Too ill-conditioned for its Float16 blocks: PosDefException or a factor within the bound, never NaN. + @testset "condition number $c fails cleanly, uplo=$uplo" for c in (1e5, 1e8), uplo in test_flags(:uplo, ('L', 'U')) + S = spd(Float32, 64; cond=c) + A = SymmMixedPrec(mxp_on(AT, copy(S)), uplo; precisions=DataType[Float16, Float32]) + @test (try + potrf_recursive!(A, 8) + mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(S), uplo) <= mxp_tol(Float16, 64) + catch e + e isa PosDefException + end) + end + + # A matrix that is not positive definite throws PosDefException, from a small leaf or the dense recursion. + @testset "a matrix that is not positive definite throws, uplo=$uplo, block_size=$bs" for uplo in test_flags(:uplo, ('L', 'U')), + bs in (2, 4096) + P = _mxp_potrf_list(AT, DataType[Float32, Float64]) + A = SymmMixedPrec(mxp_on(AT, -Matrix{P[end]}(I, 8, 8)), uplo; precisions=P) + @test_throws PosDefException potrf_recursive!(A, bs) + end + + # A leaf of A22 that is not positive definite throws; its info counts in the whole matrix. + @testset "not positive definite further down throws, uplo=$uplo, block_size=$bs" for uplo in test_flags(:uplo, ('L', 'U')), + bs in (2, 4096) + S = Matrix(1.0f0I, 16, 16) + S[16, 16] = -1 + P = _mxp_potrf_list(AT, DataType[Float16, Float32, Float64]) + @test_throws PosDefException potrf_recursive!(SymmMixedPrec(mxp_on(AT, S), uplo; precisions=P), bs) + e = try potrf_recursive!(SymmMixedPrec(mxp_on(AT, S), uplo; precisions=P), bs) catch err; err end + @test e.info == 16 + end + + # A Schur complement that is not positive definite ([I 2I; 2I I]) throws at its first row, info 9. + @testset "a Schur complement that is not positive definite throws, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + P = _mxp_potrf_list(AT, DataType[Float32, Float64]) + S = kron(P[end][1 2; 2 1], Matrix{P[end]}(I, 8, 8)) + @test_throws PosDefException potrf_recursive!(SymmMixedPrec(mxp_on(AT, S), uplo; precisions=P), 2) + e = try potrf_recursive!(SymmMixedPrec(mxp_on(AT, S), uplo; precisions=P), 2) catch err; err end + @test e.info == 9 + end + + # A scaled leaf below the top level throws, after A11 is factored and A22 updated. + supports_float64(AT) && @testset "a leaf of A22 stored with a scale factor throws, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + D = Diagonal([fill(1.0, 4); fill(1.0e20, 4)]) + A = SymmMixedPrec(mxp_on(AT, D * mxp_spd(Float64, 8) * D), uplo; precisions=DataType[Float32, Float32]) + @test A.A22.Base_scale != 1 + @test_throws ArgumentError potrf_recursive!(A, 2) + end + + # Source issue B9: tiny values in Float16 blocks are never scaled up, so the factor is wrong with no exception. + @testset "tiny values in Float16 blocks, uplo=$uplo" for uplo in test_flags(:uplo, ('L',)) + S = 1.0f-8 * mxp_spd(Float32, 16) + A = SymmMixedPrec(mxp_on(AT, copy(S)), uplo; precisions=DataType[Float16, Float32]) + @test_broken (try + potrf_recursive!(A, 4) + mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(S), uplo) <= mxp_tol(Float16, 16) + catch + false + end) + end + + # Source issue (B49 pattern): the update alpha -(scale^2) rounds to -Inf in Float32, so a PD matrix throws. + @testset "an off-diagonal scale past sqrt(floatmax(Float32)), uplo=$uplo" for uplo in test_flags(:uplo, ('L',)) + R = randn(16, 16) + C = R * R' + 16I + d = 1 ./ sqrt.(diag(C)) + D = [fill(1.0e6, 8); fill(1.5e19, 8)] + A0 = Float32.(D .* (d .* C .* d') .* D') + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=DataType[Float16, Float32]) + @test Float64(A.OffDiag_scale)^2 > floatmax(Float32) + @test_broken (try + potrf_recursive!(A, 4) + mxp_chol_backward_error(_mxp_factor(mxp_host(A)), Float64.(A0), uplo) <= mxp_tol(Float16, 16) + catch + false + end) + end + + # Source issue B9, uniform scaling: the scale is only raised, so the stored Float16 L21 underflows. + @testset "a uniformly scaled matrix, uplo=$uplo" for uplo in test_flags(:uplo, ('L',)) + A0 = Float32.(1.0e20 * mxp_spd(Float64, 16)) + A = SymmMixedPrec(mxp_on(AT, copy(A0)), uplo; precisions=DataType[Float16, Float32]) + B0 = Float64.(Array(A.OffDiag)) * A.OffDiag_scale + @test_broken (try + potrf_recursive!(A, 4) + _mxp_offdiag_err(mxp_host(A), B0) <= mxp_u(Float16) + mxp_tol(Float32, 8) + catch + false + end) + end +end + +cpu_wanted() && @testset "POTRF_RECURSIVE mixed precision [CPU]" begin + @testset "block_size 0 and an all-zero matrix throw, uplo=$uplo" for uplo in test_flags(:uplo, ('L', 'U')) + @test_throws ArgumentError potrf_recursive!(SymmMixedPrec(mxp_spd(Float64, 8), uplo; precisions=DataType[Float32, Float64]), 0) + @test_throws PosDefException potrf_recursive!(SymmMixedPrec(zeros(8, 8), uplo; precisions=DataType[Float32, Float64])) + end + + _mxp_potrf_more("CPU", Array) +end + +# On a GPU: the factorization runs on the device and is checked on the CPU through a host copy. +@testset "POTRF_RECURSIVE mixed precision [$name]" for (name, AT, _) in filter(b -> b[1] != "CPU", MXP_BACKENDS) + _mxp_potrf_more(name, AT) +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..9037b4c9 --- /dev/null +++ b/test/mxp/lapack/lu/reclu_mixedprec.jl @@ -0,0 +1,234 @@ +# lu_recursive! over a FullMixedPrec matrix (src/mxp/lapack/lu/reclu_mixedprec.jl), by backward error. Helpers: test/setup/mxp.jl. + +test_params(n = "order of A", block = "block size of the leaf LU") # the number options it takes (--params) + +# [Float32] alone is one leaf, run once below (the dense method's test covers it). +const MXP_LU_PRECISIONS = (DataType[Float32, Float32], DataType[Float16, Float32], + DataType[Float16, Float32, Float64], + DataType[Float16, Float16, Float32, Float64]) + +# Signed inputs that need no pivoting: diagonally dominant, and SPD with random row and column signs. +lu_diagdom(T, n) = mxp_rand(T, n, n) + T(2n) * I +lu_spd(T, n) = (d = rand((-1, 1), n); mxp_spd(T, n) .* (d * d')) + +# 8x8, A21 up to 6e4 over pivots near 0.5: solving it against U11 goes past floatmax(Float16). +function lu_raised() + A0 = [0.5f0 * I + 0.01f0 * mxp_rand(Float32, 4, 4) mxp_rand(Float32, 4, 4) + 6.0f4 * mxp_rand(Float32, 4, 4) 1.0f6 * I + mxp_rand(Float32, 4, 4)] + A0[5, 1] = 6.0f4 + return A0 +end + +# Residual of A0 X = B solved with the factors in M, L (unit diagonal) then U, as the docs do. +function lu_solve_residual(M, A0, B, AT) + X = mxp_on(AT, copy(B)) + unified_rectrxm!('L', 'L', 'N', 'U', one(eltype(B)), 'S', M, X) + unified_rectrxm!('L', 'U', 'N', 'N', one(eltype(B)), 'S', M, X) + A, Xd, Bd = Float64.(A0), Float64.(Array(X)), Float64.(B) + return norm(A * Xd - Bd) / (norm(A) * norm(Xd) + norm(Bd)) +end + +@testset "RECLU mixed precision [$name]" for (name, AT, _) in MXP_BACKENDS + # SPD too (on diagdom input a missing trailing update passes the Float16 bound); Float32 stands in for Float64 on a device without it. + @testset "$kind $S input, precisions=$P, n=$n, block_size=$bs" for P in map(P -> supports_float64(AT) ? P : replace(P, Float64 => Float32), + test_precisions(MXP_LU_PRECISIONS)), + S in backend_types(AT, (Float16, Float32, Float64)), kind in ("diagdom", "spd"), + n in test_values(:n, (13, 32, 50, 100)), bs in test_values(:block, (8,)) + A0 = kind == "spd" ? lu_spd(S, n) : lu_diagdom(S, 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 "one leaf, $S input, precisions=$P, n=$n, block_size=$bs" for P in filter(P -> length(P) == 1, test_precisions((DataType[Float32],))), + S in backend_types(AT, (Float32,)), n in test_values(:n, (50,)), bs in test_values(:block, (8,)) + supports_float64(AT) || Float64 ∉ P || continue + A0 = lu_diagdom(S, 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(Float32, n) + end + + @testset "$S input, n=$n" for S in backend_types(AT, (Float32,)), n in (1, 2) + A0 = lu_diagdom(S, n) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float32]) + lu_recursive!(A, 8) + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, n) + end + + # cond(A) above 1/u(Float16) still gives a small backward error; no Float16 input (rounding A to Float16 shifts eigenvalues by more than the smallest). + @testset "SPD with cond $c, $S input, precisions=$P, n=$n" for c in (1e4, 1e6), P in test_precisions(filter(P -> Float16 in P, MXP_LU_PRECISIONS)), + S in backend_types(AT, (Float32,)), n in test_values(:n, (64,); valid = n -> n >= 2 || "a condition number needs n >= 2") + supports_float64(AT) || Float64 ∉ P || continue + A0 = S.(spd(Float64, n; cond=c)) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=P) + lu_recursive!(A, 8) + F = reconstruct_matrix(A) + @test mxp_lu_backward_error(F, Float64.(A0)) <= mxp_tol(mxp_narrowest(P), n) + # Unpivoted LU of an SPD matrix has no growth; at cond 1e6 Float16 storage leaves the stored matrix not SPD, so only 1e4. + c == 1e4 && @test maximum(abs, triu(Array(F))) <= 2 * maximum(abs, A0) + end + + # A21's solve against U11 goes past floatmax(Float16): its scale is raised from 1, and the factors still solve A X = B. + @testset "an off-diagonal block solved past floatmax(Float16)" begin + A0 = lu_raised() + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float32]) + @test A.A21_scale == 1 + lu_recursive!(A, 8) + @test A.A21_scale > 1 + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, 8) + @test lu_solve_residual(A, A0, mxp_rand(Float32, 8, 3), AT) <= mxp_tol(Float16, 8) + end + + # A21 and A12 scaled differently: the trailing update's alpha is the product of the two scales. + @testset "both off-diagonal blocks scaled" begin + A0 = lu_spd(Float32, 64) .* 1f5 + A0[1:32, 33:64] .*= 3; A0[33:64, 1:32] ./= 3 # same L21 * U12, different scales + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float16, Float32]) + @test A.A21_scale > 1 && A.A12_scale > 1 && A.A21_scale != A.A12_scale + lu_recursive!(A, 8) + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, 64) + end + + @testset "solve A X = B with the factors, precisions=$P, n=$n" for + P in test_precisions((DataType[Float16, Float32], DataType[Float16, Float32, Float64], DataType[Float32, Float64])), n in test_values(:n, (50,)) + supports_float64(AT) || Float64 ∉ P || continue + A0 = lu_diagdom(P[end], n) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=P) + lu_recursive!(A, 8) + @test lu_solve_residual(A, A0, mxp_rand(P[end], n, 3), AT) <= mxp_tol(mxp_narrowest(P), n) + end + + # At 1e-6 the Float16 off-diagonal entries are subnormal but kept; at 1e-9 they flush to zero (B9: scales are only raised). + @testset "diagdom scaled by $c, $S input" for S in backend_types(AT, (Float32,)), c in (1e-6, 1e-9) + A0 = S(c) .* lu_diagdom(S, 32) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, Float32]) + lu_recursive!(A, 8) + err = mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) + if c == 1e-6 + @test err <= mxp_tol(Float16, 32) + else + @test_broken err <= mxp_tol(Float16, 32) # B9 + end + 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 + + # Big sizes and multiples (800, 1600, 3200); above 512 rows the default is parallel, from n = 1600 inside A11 and A22 too. + @testset "n=$n, default arguments, precisions=$P" for (n, P) in test_cases((:n, nothing), ((520, DataType[Float16, Float32]), + (800, DataType[Float16, Float16, Float32]), (1600, DataType[Float16, Float16, Float32]), (3200, DataType[Float16, Float16, Float32]))) + A0 = lu_spd(Float32, n) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=P) + lu_recursive!(A) + @test mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, n) + end + + # Inside the LU's TF32 scope the parallel trailing recgemm! (Float32 blocks in A22) keeps TF32 in its tasks. + name == "CUDA" && @testset "TF32 in parallel tasks: parallel = sequential" begin + A0 = lu_spd(Float32, 2400) + P = DataType[Float16, Float32, Float32] + a, b = FullMixedPrec(AT(A0); precisions=P), FullMixedPrec(AT(A0); precisions=P) + lu_recursive!(a; parallel=true) + lu_recursive!(b; parallel=false) + @test Array(reconstruct_matrix(a)) == Array(reconstruct_matrix(b)) + end + + # The same bits either way: the two off-diagonal solves write disjoint blocks. + @testset "parallel=false and parallel=true give the same factors" begin + P = DataType[Float16, Float32, supports_float64(AT) ? Float64 : Float32] + A0 = mxp_diagdom(P[end], 64) + a = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=P) + b = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=P) + 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, $TL leaf" for TL in backend_types(AT, (Float32, Float64)) + n = 8 + A0 = TL.(mxp_rand(Float64, n, n) .* 2.0e24 + 1.0e27I) + A = FullMixedPrec(mxp_on(AT, copy(A0)); precisions=DataType[Float16, TL]) + @test isinf(A.A21_scale * A.A12_scale) + if TL === Float32 # B49: the product of the two scales, about 1e44, overflows a Float32 leaf's GEMM alpha. + @test_broken (try lu_recursive!(A, 4); mxp_lu_backward_error(reconstruct_matrix(A), Float64.(A0)) <= mxp_tol(Float16, n) catch e; e isa ArgumentError || rethrow(); false end) + continue + end + lu_recursive!(A, 4) + R = reconstruct_matrix(A) + @test all(isfinite, Array(R)) + @test mxp_lu_backward_error(R, Float64.(A0)) <= mxp_tol(Float16, n) + end + + supports_float64(AT) && @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 + + # The LU of transpose(A) is not A's factors stored another way: refused, A unchanged. + @testset "transpose(A) throws ArgumentError, $f" for f in (transpose, adjoint) + T = supports_float64(AT) ? Float64 : Float32 + A = FullMixedPrec(mxp_on(AT, mxp_diagdom(T, 16)); precisions=DataType[Float16, T]) + R0 = Array(reconstruct_matrix(A)) + @test_throws ArgumentError lu_recursive!(f(A)) + @test_throws ArgumentError lu_recursive!(f(A), 8; parallel=true) + @test Array(reconstruct_matrix(A)) == R0 + end + + # A zero pivot in A11 or A22 throws ZeroPivotException, as lu!(A, NoPivot()) does. + @testset "a zero pivot throws ZeroPivotException, in $place" for place in ("A11", "A22") + P = DataType[Float16, Float32, supports_float64(AT) ? Float64 : Float32] + Z = Matrix(one(P[end])I, 16, 16) + P[end](0.01) .* mxp_rand(P[end], 16, 16) + if place == "A11" + Z[1, 1] = 0 + else + Z[9, 9] = 0 + Z[9, 1:8] .= 0 + Z[1:8, 9] .= 0 + end + A = FullMixedPrec(mxp_on(AT, Z); precisions=P) + @test_throws LinearAlgebra.ZeroPivotException lu_recursive!(A, 4) + e = try lu_recursive!(FullMixedPrec(mxp_on(AT, Z); precisions=P), 4) catch err; err end + @test e isa LinearAlgebra.ZeroPivotException && e.info == (place == "A11" ? 1 : 9) + end +end + +cpu_wanted() && @testset "RECLU mixed precision, other entry points [CPU]" begin + # TF32 is opened only when the top-level off-diagonal blocks are narrower than Float32. + @testset "the TF32 scope follows the top-level blocks" begin + A = mxp_diagdom(Float64, 16) + @test MixedPrecision._top_narrow(FullMixedPrec(A; precisions=DataType[Float16, Float32])) + @test !MixedPrecision._top_narrow(FullMixedPrec(A; precisions=DataType[Float32, Float32])) + @test !MixedPrecision._top_narrow(FullMixedPrec(A; precisions=DataType[Float32, Float16, Float32])) + @test !MixedPrecision._top_narrow(FullMixedPrec(A; precisions=DataType[Float32])) + end + + @testset "the dense method still takes a dense matrix" begin + @test lu_recursive!(mxp_rand(Float64, 4, 4) + 8I, 2) isa Matrix{Float64} + end +end + +# Parallel against sequential in a child Julia with 4 threads, on the CPU and CUDA; at n = 1100 A11 (1024 rows) splits in parallel too. +@testset "RECLU mixed precision, parallel with 4 threads [$name]" for (name, AT, _) in filter(b -> b[1] in ("CPU", "CUDA"), MXP_BACKENDS) + T = supports_float64(AT) ? Float64 : Float32 + code = """ + using NextLA, NextLA.MixedPrecision, LinearAlgebra, Random$(name == "CUDA" ? ", CUDA" : "") + Random.seed!($(rand(UInt32))) # from this test's seeded RNG, so --seed replays it + function same(n, bs) + A0 = rand($T, n, n) + $T(2n) * I + P = DataType[Float16, Float16, Float32, $T] + a = FullMixedPrec($(name == "CUDA" ? "CuArray(A0)" : "copy(A0)"); precisions=P) + b = FullMixedPrec($(name == "CUDA" ? "CuArray(A0)" : "copy(A0)"); precisions=P) + lu_recursive!(a, bs; parallel=true) + lu_recursive!(b, bs; parallel=false) + Array(reconstruct_matrix(a)) == Array(reconstruct_matrix(b)) + end + print(Threads.nthreads(), " ", all(_ -> same(64, 8), 1:20) && same(1100, 64)) + """ + @test with_threads(code; threads=test_threads()) == "$(test_threads()) true" +end diff --git a/test/mxp/lu/reclu_mixedprec.jl b/test/mxp/lu/reclu_mixedprec.jl deleted file mode 100644 index d517b854..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 throws" begin - # n = 50 splits 32 + 18: the trailing update multiplies an 18×32 block by a 32×18 - # one into A22, which recgemm! accepts only while A22 is a leaf. - A0 = rand(Float64, 50, 50) + 100I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float32, Float32, Float64]) - @test_throws DimensionMismatch lu_recursive!(mp, 8) - end - - @testset "lu_recursive_mixed! is the same function" begin - @test lu_recursive_mixed! === lu_recursive! - A0 = rand(Float64, 16, 16) + 32I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float32, Float64]) - lu_recursive_mixed!(mp, 4) - @test _mxp_lu_err(reconstruct_matrix(mp), A0) < 1e-5 - 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 Float16 scales do not overflow the trailing update" begin - n = 8 - A0 = rand(n, n) .* 2.0e7 + 1.0e10I - mp = FullMixedPrec(copy(A0); precisions = DataType[Float16, Float64], scale_type = Float16) - @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.0e5, 4, 4) + 1.0e6I; precisions = DataType[Float16]) - @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_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_block!(W -> (W .*= 2), same, 1f0, Float32) == 1f0 - @test same == fill(2f0, 2, 2) -end diff --git a/test/mxp/mxp.jl b/test/mxp/mxp.jl deleted file mode 100644 index 8c52841a..00000000 --- a/test/mxp/mxp.jl +++ /dev/null @@ -1,319 +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 "scale_type sets the type of every scale" begin - M = FullMixedPrec(rand(8, 8); precisions=DataType[Float32, Float64], scale_type=Float64) - @test M.A21_scale isa Float64 - @test M.A11.Base_scale isa Float64 - 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(rand(4, 4); precisions=DataType[Float64], - scale_type=BigFloat) - @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], scale_type=Float16) - 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 "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 - - @testset "adaptive_precision_LT is the same function" begin - @test adaptive_precision_LT === adaptive_precisions - end - end - - @testset "values beyond floatmax(T_Base) cannot be read back as T_Base" begin - A = fill(1.0e5, 4, 4) - M = FullMixedPrec(A; precisions=DataType[Float16]) - @test M.Base_scale != 1 - @test_broken all(isapprox.(Float64.(reconstruct_matrix(M)), A; rtol=1e-2)) - @test_broken isapprox(Float64(M[1, 1]), A[1, 1]; rtol=1e-2) - 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 diff --git a/test/mxp/syrk/recsyrk_mixedprec.jl b/test/mxp/syrk/recsyrk_mixedprec.jl deleted file mode 100644 index ead161e5..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 NextLA.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]) - NextLA.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) - NextLA.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 NextLA.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) - NextLA.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 ef38708a..00000000 --- a/test/mxp/trsm/rectrxm_mixed.jl +++ /dev/null @@ -1,204 +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 MixedPrecision.unified_rec_mixed(func, side, uplo, 'N', 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) - MixedPrecision.unified_rec_mixed(func, 'L', 'L', 'U', 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) - MixedPrecision.unified_rec_mixed(func, side, 'U', 'N', transpose(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 - MixedPrecision.unified_rec_mixed('S', 'L', uplo, 'N', transpose(Amp), Bm) - ref = _mxp_reference('S', 'L', uplo == 'L' ? 'U' : 'L', 'T', 'N', A, B) - else - MixedPrecision.unified_rec_mixed('S', 'L', uplo, 'N', 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, Float16]) - ref = _mxp_reference(func, 'L', 'L', 'N', 'N', reconstruct_matrix(Amp), B) - Bm = copy(B) - MixedPrecision.unified_rec_mixed(func, 'L', 'L', 'N', 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) - MixedPrecision.unified_rec_mixed(func, 'L', 'L', 'N', 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.0e5 + 2.0e5I - Amp = TriMixedPrec(A, 'L'; precisions = DataType[Float16]) - @test Amp.Base_scale != 1 - B = rand(Float32, n, m) - Bm = copy(B) - MixedPrecision.unified_rec_mixed(func, 'L', 'L', 'N', 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.0e5I, 4, 4), 'L'; precisions = DataType[Float16]) - @test Amp.Base_scale != 1 - B = fill(1f34, 4, 2) - MixedPrecision.unified_rec_mixed('M', 'L', 'L', 'N', 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) - MixedPrecision.unified_rec_mixed('S', 'L', 'L', 'N', 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) - MixedPrecision.unified_rec_mixed('S', 'L', 'L', Amp, B1) - MixedPrecision.unified_rec_mixed('S', 'L', 'L', 'N', Amp, B2) - @test B1 == B2 - 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.unified_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 and scale type" begin - q2, s2 = MixedPrecision.quantize(rand(Float64, 4, 4), Float32, Float64) - @test eltype(q2) === Float32 - @test s2 isa Float64 - end - - @testset "an empty matrix" begin - qe, se = MixedPrecision.quantize(zeros(Float64, 0, 3), Float16, Float64) - @test size(qe) == (0, 3) && eltype(qe) === Float16 - @test se === 1.0 - 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/pamm.jl b/test/pamm.jl deleted file mode 100644 index e63b2e83..00000000 --- a/test/pamm.jl +++ /dev/null @@ -1,180 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "PAMM [$backend_name]" begin - @testset "W op — left, column, forward" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, k, l = 40, 30, 20, 10 - - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, m, k))) - W = ArrayType(zeros(T, k, n)) - - NextLA.pamm!('W', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W) - synchronize(W) - - @test all(isfinite.(Array(W))) - @test !isapprox(Array(W), zeros(T, k, n), rtol=rtol) - end - end - - @testset "A op — left, column, forward" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, k, l = 40, 30, 20, 10 - - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - A2_orig = copy(A2) - V = ArrayType(copy(rand(T, m, k))) - W = ArrayType(copy(rand(T, k, n))) - - NextLA.pamm!('A', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W) - synchronize(A2) - - @test all(isfinite.(Array(A2))) - @test !isapprox(Array(A2), Array(A2_orig), rtol=rtol) - end - end - - @testset "W op — right, column, forward" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - m, n, k, l = 30, 40, 20, 10 - - A1 = ArrayType(copy(rand(T, m, k))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, n, k))) - W = ArrayType(copy(rand(T, m, k))) - - NextLA.pamm!('W', 'R', 'C', 'F', m, n, k, l, A1, A2, V, W) - synchronize(W) - - @test all(isfinite.(Array(W))) - end - end - - @testset "W op — left, column, backward" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - m, n, k, l = 40, 30, 20, 10 - - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, m, k))) - W = ArrayType(copy(rand(T, k, n))) - - NextLA.pamm!('W', 'L', 'C', 'B', m, n, k, l, A1, A2, V, W) - synchronize(W) - - @test all(isfinite.(Array(W))) - end - end - - @testset "W op — left, row, forward" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - m, n, k, l = 40, 30, 20, 10 - - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, k, m))) - W = ArrayType(copy(rand(T, k, n))) - - NextLA.pamm!('W', 'L', 'R', 'F', m, n, k, l, A1, A2, V, W) - synchronize(W) - - @test all(isfinite.(Array(W))) - end - end - - @testset "Quick return for zero dims" begin - T = ComplexF64 - A1 = ArrayType(copy(rand(T, 5, 5))) - A2 = ArrayType(copy(rand(T, 10, 5))) - V = ArrayType(copy(rand(T, 10, 5))) - W = ArrayType(copy(rand(T, 5, 5))) - W_orig = copy(W) - - NextLA.pamm!('W', 'L', 'C', 'F', 0, 5, 5, 3, A1, A2, V, W) - synchronize(W) - @test Array(W) == Array(W_orig) - - W_orig2 = copy(W) - NextLA.pamm!('W', 'L', 'C', 'F', 10, 0, 5, 3, A1, A2, V, W) - synchronize(W) - @test Array(W) == Array(W_orig2) - - W_orig3 = copy(W) - NextLA.pamm!('W', 'L', 'C', 'F', 10, 5, 0, 3, A1, A2, V, W) - synchronize(W) - @test Array(W) == Array(W_orig3) - end - - @testset "W then A consistency" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, k, l = 40, 30, 20, 10 - - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, m, k))) - W = ArrayType(zeros(T, k, n)) - - NextLA.pamm!('W', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W) - synchronize(W) - @test all(isfinite.(Array(W))) - - A2_before = copy(A2) - NextLA.pamm!('A', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W) - synchronize(A2) - @test all(isfinite.(Array(A2))) - @test !isapprox(Array(A2), Array(A2_before), rtol=rtol) - end - end - - @testset "Different sizes" begin - T = ComplexF64 - for (m, n, k, l) in [(10, 8, 5, 3), (25, 20, 12, 8), (50, 40, 25, 15)] - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, m, k))) - W = ArrayType(zeros(T, k, n)) - - NextLA.pamm!('W', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W) - synchronize(W) - @test all(isfinite.(Array(W))) - @test size(W) == (k, n) - end - end - - @testset "Deterministic" begin - Random.seed!(42) - T = ComplexF64 - m, n, k, l = 20, 15, 10, 5 - A1 = ArrayType(copy(rand(T, k, n))) - A2 = ArrayType(copy(rand(T, m, n))) - V = ArrayType(copy(rand(T, m, k))) - W1 = ArrayType(zeros(T, k, n)) - NextLA.pamm!('W', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W1) - synchronize(W1) - - W2 = ArrayType(zeros(T, k, n)) - NextLA.pamm!('W', 'L', 'C', 'F', m, n, k, l, A1, A2, V, W2) - synchronize(W2) - @test Array(W1) == Array(W2) - end - end -end - -@testset "PAMM Error handling" begin - T = ComplexF64 - A1 = zeros(T, 5, 5) - A2 = zeros(T, 10, 5) - V = zeros(T, 10, 5) - W = zeros(T, 5, 5) - - @test_throws ArgumentError NextLA.pamm!('X', 'L', 'C', 'F', 10, 5, 5, 3, A1, A2, V, W) - @test_throws ArgumentError NextLA.pamm!('W', 'X', 'C', 'F', 10, 5, 5, 3, A1, A2, V, W) - @test_throws ArgumentError NextLA.pamm!('W', 'L', 'X', 'F', 10, 5, 5, 3, A1, A2, V, W) - @test_throws ArgumentError NextLA.pamm!('W', 'L', 'C', 'X', 10, 5, 5, 3, A1, A2, V, W) - @test_throws ArgumentError NextLA.pamm!('W', 'L', 'C', 'F', -1, 5, 5, 3, A1, A2, V, W) - @test_throws ArgumentError NextLA.pamm!('W', 'L', 'C', 'F', 10, -1, 5, 3, A1, A2, V, W) -end diff --git a/test/parfb.jl b/test/parfb.jl deleted file mode 100644 index 2b30a4f8..00000000 --- a/test/parfb.jl +++ /dev/null @@ -1,66 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "PARFB [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "side=$side, trans=$trans, direct=$direct, storev=$storev" for - side in ['L', 'R'], - trans in ['N', 'C'], - direct in ['F', 'B'], - storev in ['C', 'R'] - - if side == 'L' && direct == 'F' && storev == 'R' - continue - end - - m2, n2, k, l = 20, 24, 8, 4 - - if side == 'L' - m1, n1 = k, n2 - else - m1, n1 = m2, k - end - - A1 = rand(T, m1, n1) - A2 = rand(T, m2, n2) - - if storev == 'C' - V = side == 'L' ? rand(T, m2, k) : rand(T, n2, k) - else - V = side == 'L' ? rand(T, k, m2) : rand(T, k, n2) - end - - Tee = rand(T, k, k) - work_n = side == 'L' ? rand(T, k, n2) : rand(T, m2, k) - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - V_n = ArrayType(copy(V)) - Tee_n = ArrayType(copy(Tee)) - work_n_gpu = ArrayType(copy(work_n)) - NextLA.parfb!(side, trans, direct, storev, m1, n1, m2, n2, k, l, - A1_n, A2_n, V_n, Tee_n, work_n_gpu) - synchronize(A1_n) - - A1_l = copy(A1) - A2_l = copy(A2) - lapack_tprfb!(T, side, trans, direct, storev, l, - copy(V), copy(Tee), A1_l, A2_l) - - @test Array(A1_n) ≈ A1_l rtol=rtol - @test Array(A2_n) ≈ A2_l rtol=rtol - end - end - end -end - -@testset "PARFB Error handling" begin - @test_throws ArgumentError NextLA.parfb!('X', 'N', 'F', 'C', 4, 4, 4, 4, 2, 0, - zeros(2, 4), zeros(4, 4), zeros(4, 2), zeros(2, 2), zeros(2, 4)) - @test_throws ArgumentError NextLA.parfb!('L', 'X', 'F', 'C', 4, 4, 4, 4, 2, 0, - zeros(2, 4), zeros(4, 4), zeros(4, 2), zeros(2, 2), zeros(2, 4)) - @test_throws ArgumentError NextLA.parfb!('L', 'N', 'X', 'C', 4, 4, 4, 4, 2, 0, - zeros(2, 4), zeros(4, 4), zeros(4, 2), zeros(2, 2), zeros(2, 4)) - @test_throws ArgumentError NextLA.parfb!('L', 'N', 'F', 'X', 4, 4, 4, 4, 2, 0, - zeros(2, 4), zeros(4, 4), zeros(4, 2), zeros(2, 2), zeros(2, 4)) -end diff --git a/test/pemv.jl b/test/pemv.jl deleted file mode 100644 index 836fb7e3..00000000 --- a/test/pemv.jl +++ /dev/null @@ -1,285 +0,0 @@ -"""Build the pentagonal matrix that pemv! actually reads. - -Columnwise storage + [Conj]Trans: - The bottom-left l×l block A[m-l+1:m, 1:l] is treated as upper triangular. - Zero the strictly-lower triangle of that block. - -Rowwise storage + NoTrans: - The top-right l×l block A[1:l, n-l+1:n] is treated as lower triangular. - Zero the strictly-upper triangle of that block. -""" -function make_pentagonal(A, m, n, l, storev) - Ap = copy(A) - if l <= 1 # l==1 is treated as l==0 (no triangle) - return Ap - end - if storev == 'C' - for j in 1:l, i in (m - l + j + 1):m - Ap[i, j] = zero(eltype(A)) - end - else # 'R' - for j in 1:l - col = n - l + j - for i in 1:(j - 1) - Ap[i, col] = zero(eltype(A)) - end - end - end - return Ap -end - -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "PEMV [$backend_name]" begin - @testset "Column storage, conjugate transpose" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, l = 40, 30, 10 - alpha = T(2.5 + 1.5im) - beta = T(1.2 - 0.8im) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - Y_orig_cpu = Array(copy(Y)) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, l, alpha, A, X, beta, Y, work) - synchronize(Y) - - Ap = make_pentagonal(Array(A), m, n, l, 'C') - Y_ref = alpha * Ap' * Array(X) + beta * Y_orig_cpu - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "Column storage, transpose (real)" begin - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - m, n, l = 40, 30, 10 - alpha = T(2.0) - beta = T(0.5) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - Y_orig_cpu = Array(copy(Y)) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('T', 'C', m, n, l, alpha, A, X, beta, Y, work) - synchronize(Y) - - Ap = make_pentagonal(Array(A), m, n, l, 'C') - Y_ref = alpha * transpose(Ap) * Array(X) + beta * Y_orig_cpu - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "Row storage, no transpose" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, l = 30, 40, 10 - alpha = T(1.8 + 2.2im) - beta = T(0.5 + 1.0im) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, n))) - Y = ArrayType(copy(rand(T, m))) - Y_orig_cpu = Array(copy(Y)) - work = ArrayType(zeros(T, m)) - - NextLA.pemv!('N', 'R', m, n, l, alpha, A, X, beta, Y, work) - synchronize(Y) - - Ap = make_pentagonal(Array(A), m, n, l, 'R') - Y_ref = alpha * Ap * Array(X) + beta * Y_orig_cpu - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "Wrapper (auto-workspace)" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n = 40, 30 - alpha = T(2.0 + 1.0im) - beta = T(1.5 - 0.5im) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - Y_orig_cpu = Array(copy(Y)) - - NextLA.pemv!('C', 'C', alpha, A, X, beta, Y) - synchronize(Y) - - l_def = min(m, n) - Ap = make_pentagonal(Array(A), m, n, l_def, 'C') - Y_ref = alpha * Ap' * Array(X) + beta * Y_orig_cpu - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "Zero alpha" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, l = 20, 15, 5 - alpha = zero(T) - beta = T(2.0 + 1.5im) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - Y_orig_cpu = Array(copy(Y)) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, l, alpha, A, X, beta, Y, work) - synchronize(Y) - - @test Array(Y) ≈ beta * Y_orig_cpu rtol=rtol - end - end - - @testset "Zero beta" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n, l = 20, 15, 5 - alpha = T(2.0 + 1.5im) - beta = zero(T) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, l, alpha, A, X, beta, Y, work) - synchronize(Y) - - Ap = make_pentagonal(Array(A), m, n, l, 'C') - Y_ref = alpha * Ap' * Array(X) - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "Different sizes" begin - T = ComplexF64 - rtol = test_rtol(T) - for (m, n, l) in [(10, 8, 5), (25, 20, 12), (50, 40, 25)] - alpha = rand(T) - beta = rand(T) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - Y_orig_cpu = Array(copy(Y)) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, l, alpha, A, X, beta, Y, work) - synchronize(Y) - - Ap = make_pentagonal(Array(A), m, n, l, 'C') - Y_ref = alpha * Ap' * Array(X) + beta * Y_orig_cpu - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "l == 0 (pure gemv)" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n = 20, 15 - alpha = T(1.5 + 0.5im) - beta = T(0.8 - 0.3im) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y = ArrayType(copy(rand(T, n))) - Y_orig_cpu = Array(copy(Y)) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, 0, alpha, A, X, beta, Y, work) - synchronize(Y) - - Y_ref = alpha * Array(A)' * Array(X) + beta * Y_orig_cpu - @test Array(Y) ≈ Y_ref rtol=rtol - end - end - - @testset "Quick return for zero dims" begin - T = ComplexF64 - alpha = T(1.0) - beta = T(1.0) - A = ArrayType(copy(rand(T, 1, 5))) - X = ArrayType(copy(rand(T, 5))) - Y = ArrayType(copy(rand(T, 1))) - work = ArrayType(zeros(T, 5)) - Y_orig = Array(copy(Y)) - - NextLA.pemv!('C', 'C', 0, 5, 0, alpha, A, X, beta, Y, work) - synchronize(Y) - - A2 = ArrayType(copy(rand(T, 5, 1))) - X2 = ArrayType(zeros(T, 0)) - Y2 = ArrayType(copy(rand(T, 5))) - work2 = ArrayType(zeros(T, 5)) - NextLA.pemv!('C', 'C', 5, 0, 0, alpha, A2, X2, beta, Y2, work2) - end - - @testset "BLAS consistency (l == 0)" begin - @testset "$T" for T in (ComplexF32, ComplexF64) - rtol = test_rtol(T) - m, n = 20, 15 - alpha = T(2.0 + 1.0im) - beta = T(1.5 - 0.8im) - - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y1 = ArrayType(copy(rand(T, n))) - Y2_cpu = copy(Array(Y1)) - work = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, 0, alpha, A, X, beta, Y1, work) - synchronize(Y1) - BLAS.gemv!('C', alpha, Array(A), Array(X), beta, Y2_cpu) - - @test Array(Y1) ≈ Y2_cpu rtol=rtol - end - end - - @testset "Deterministic" begin - Random.seed!(123) - T = ComplexF64 - m, n, l = 20, 15, 8 - alpha = T(1.5 + 0.5im) - beta = T(0.8 - 0.3im) - A = ArrayType(copy(rand(T, m, n))) - X = ArrayType(copy(rand(T, m))) - Y1 = ArrayType(copy(rand(T, n))) - Y2 = ArrayType(copy(Y1)) - work1 = ArrayType(zeros(T, n)) - work2 = ArrayType(zeros(T, n)) - - NextLA.pemv!('C', 'C', m, n, l, alpha, A, X, beta, Y1, work1) - NextLA.pemv!('C', 'C', m, n, l, alpha, A, X, beta, Y2, work2) - synchronize(Y1) - synchronize(Y2) - @test Array(Y1) == Array(Y2) - end - end -end - -@testset "PEMV Error handling" begin - T = ComplexF64 - m, n, l = 10, 8, 5 - alpha = one(T) - beta = one(T) - A = zeros(T, m, n) - X = zeros(T, n) - Y = zeros(T, m) - work = zeros(T, m) - - @test_throws ArgumentError NextLA.pemv!('X', 'C', m, n, l, alpha, A, X, beta, Y, work) - @test_throws ArgumentError NextLA.pemv!('C', 'X', m, n, l, alpha, A, X, beta, Y, work) - @test_throws ArgumentError NextLA.pemv!('N', 'C', m, n, l, alpha, A, X, beta, Y, work) - @test_throws ArgumentError NextLA.pemv!('C', 'R', m, n, l, alpha, A, X, beta, Y, work) - @test_throws ArgumentError NextLA.pemv!('C', 'C', -1, n, l, alpha, A, X, beta, Y, work) - @test_throws ArgumentError NextLA.pemv!('C', 'C', m, -1, l, alpha, A, X, beta, Y, work) - @test_throws ArgumentError NextLA.pemv!('C', 'C', m, n, min(m,n)+1, alpha, A, X, beta, Y, work) -end diff --git a/test/rotations/lartg.jl b/test/rotations/lartg.jl deleted file mode 100644 index 2dfe0be4..00000000 --- a/test/rotations/lartg.jl +++ /dev/null @@ -1,53 +0,0 @@ -@testset "LARTG" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - for _ in 1:50 - f = randn(T) - g = randn(T) - c, s, r = NextLA.lartg(f, g) - r_calc = c * f + s * g - z_calc = -conj(s) * f + c * g - @test r ≈ r_calc rtol=rtol - @test abs(z_calc) <= rtol * max(one(real(T)), abs(r)) + eps(real(T)) - @test abs2(r) ≈ (abs2(f) + abs2(g)) rtol=rtol - @test isfinite(r) - end - - # different branch coverage - zeroT = zero(T) - oneRT = one(real(T)) - - c, s, r = NextLA.lartg(zeroT, zeroT) - @test c == oneRT - @test s == zeroT - @test r == zeroT - - f = randn(T) - c, s, r = NextLA.lartg(f, zeroT) - @test c == oneRT - @test s == zeroT - @test r == f - - g = randn(T) - c, s, r = NextLA.lartg(zeroT, g) - @test c == zero(real(T)) - @test abs(r) ≈ abs(g) rtol=rtol - @test abs(s) ≈ oneRT rtol=rtol - end -end - -for T in (ComplexF32, ComplexF64, Float32, Float64) - @testset "LARTG LAPACK $T" begin - rtol = test_rtol(T) - for _ in 1:50 - f = randn(T) - g = randn(T) - c_nla, s_nla, r_nla = NextLA.lartg(f, g) - c_ref, s_ref, r_ref = lapack_lartg(f, g) - - @test c_nla ≈ c_ref rtol=rtol - @test s_nla ≈ s_ref rtol=rtol - @test r_nla ≈ r_ref rtol=rtol - end - end -end diff --git a/test/runtests.jl b/test/runtests.jl index b6b43508..751f2c52 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,95 +1,311 @@ +# Runs each test file in its own process with ParallelTestRunner.jl (usage: test/README.md). + using NextLA -using Test -using LinearAlgebra -using LinearAlgebra.LAPACK +using ParallelTestRunner using Random -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] - -# ── 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 +const TESTDIR = @__DIR__ + +# --backends=: the backends every test runs on. --seed=: see SEED below. +# The other options choose the cases inside the tests (TEST_OPTIONS below; test/setup/options.jl). +const NUMBER_OPTIONS = ["m", "n", "k", "ib", "block", "tile", "batch"] +args = parse_args(ARGS; custom=["backends", "seed", "types", "uplo", "side", "trans", "diag", "precisions", + NUMBER_OPTIONS..., "threads", "failfast", "no-float64", "gpu-debug", "params"]) +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, ','))) +# Backend names accepted by --backends; a misspelt name stops the run once. +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 + +# The run's random seed (new each run, or --seed=); each test seeds Random from it and its name. +const SEED = let flag = args.custom["seed"] + if flag === nothing + rand(Random.RandomDevice(), UInt32) + elseif something(flag) === nothing + error("--seed needs a value, e.g. --seed=1234") + else + parse(UInt64, String(something(flag))) + end +end +println("Random seed of this run: ", SEED, " (to repeat: --seed=", SEED, ")") + +# --types, --uplo, --side, --trans, --diag, --precisions, the number options and --threads; a value +# that is not accepted stops the run with the accepted ones. +const TYPE_NAMES = Dict(string(T) => T for T in (Float16, Float32, Float64, ComplexF32, ComplexF64)) +function _option_list(name) + flag = args.custom[name] + flag === nothing && return nothing + v = something(flag) + (v === nothing || isempty(strip(v))) && error("--$name needs a value, e.g. ", Dict( + "types" => "--types=Float32,ComplexF64", "precisions" => "--precisions=Float16,Float32,Float64", + "uplo" => "--uplo=L", "side" => "--side=R", "trans" => "--trans=N,T", "diag" => "--diag=U", + "threads" => "--threads=8")[name]) + return String.(strip.(split(String(v), ','))) +end +function _option_types(name, accepted) + l = _option_list(name) + l === nothing && return nothing + bad = filter(x -> !(haskey(TYPE_NAMES, x) && TYPE_NAMES[x] in accepted), l) + isempty(bad) || error("--$name: unknown ", join(bad, ", "), "; accepted: ", join(sort(string.(collect(accepted))), ", ")) + return Tuple(TYPE_NAMES[x] for x in l) +end +function _option_chars(name, accepted) + l = _option_list(name) + l === nothing && return nothing + bad = filter(x -> !(length(x) == 1 && uppercase(x[1]) in accepted), l) + isempty(bad) || error("--$name: unknown ", join(bad, ", "), "; accepted: ", join(accepted, ", ")) + return Tuple(unique(uppercase(x[1]) for x in l)) +end +function _option_ints(name, least; one = false) + flag = args.custom[name] + flag === nothing && return nothing + v = something(flag) + l = v === nothing ? String[] : String.(strip.(split(String(v), ','))) + n = tryparse.(Int, l) + (isempty(l) || any(isnothing, n) || any(<(least), n) || (one && length(n) != 1)) && + error("--$name needs ", one ? "a whole number" : "whole numbers", " of at least $least, e.g. --$name=", + one ? least * 4 : join((least + 16, least + 100), ",")) + return one ? only(n) : Tuple(unique(n)) +end +const LEAST = Dict("m" => 0, "n" => 0, "k" => 0, "ib" => 1, "block" => 1, "tile" => 1, "batch" => 0) +const TEST_OPTIONS = (; types = _option_types("types", values(TYPE_NAMES)), + precisions = _option_types("precisions", (Float16, Float32, Float64)), + uplo = _option_chars("uplo", ('L', 'U')), side = _option_chars("side", ('L', 'R')), + trans = _option_chars("trans", ('N', 'T', 'C')), diag = _option_chars("diag", ('N', 'U')), + (Symbol(o) => _option_ints(o, LEAST[o]) for o in NUMBER_OPTIONS)..., + threads = _option_ints("threads", 2; one = true)) +let given = [string(k, "=", v isa Tuple ? join(v, ",") : v) for (k, v) in pairs(TEST_OPTIONS) if v !== nothing] + isempty(given) || println("Test options: ", join(given, "; ")) +end + +# --failfast: each test file stops at its first failing check (Julia's Test, JULIA_TEST_FAILFAST). +# --no-float64: every GPU backend behaves as one without Float64 (NEXTLA_TEST_NO_FLOAT64=1, the Metal check). +# --gpu-debug: print why a GPU backend was skipped (NEXTLA_GPU_DEBUG=1). +for (flag, var, val) in (("failfast", "JULIA_TEST_FAILFAST", "true"), ("no-float64", "NEXTLA_TEST_NO_FLOAT64", "1"), + ("gpu-debug", "NEXTLA_GPU_DEBUG", "1")) + f = args.custom[flag] + f === nothing && continue + something(f) === nothing || error("--$flag takes no value") + ENV[var] = val # the test processes inherit the environment of this one +end + +# Code evaluated at the top level of each test's module, before the test. +const init_code = quote + using NextLA, Test, LinearAlgebra, Random + const TEST_BACKENDS_WANTED = $BACKENDS + const TEST_OPTIONS = $TEST_OPTIONS +end + +# One test per file under test/dense and test/mxp, preceded by the setup file of its part. +const SETUP = Dict( + "dense" => [joinpath(TESTDIR, "setup", "dense.jl")], + "mxp" => [joinpath(TESTDIR, "setup", "gpu_backends.jl"), joinpath(TESTDIR, "setup", "mxp.jl")], +) +# Stop when a folder under test/ is not one of the parts above, so it cannot be skipped silently. +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 + +testsuite = Dict{String, Expr}() +const TEST_FILES = Dict{String, String}() +for (part, setup) in SETUP, (name, body) in find_tests(joinpath(TESTDIR, part)) + TEST_FILES["$part/$name"] = joinpath(TESTDIR, part, name * ".jl") + testsuite["$part/$name"] = quote + $((:(include($f)) for f in setup)...) + Random.seed!(hash($("$part/$name"), $(UInt(SEED)))) + seed_backends!(hash($("$part/$name"), $(UInt(SEED)))) # device RNGs (setup/gpu_backends.jl) + $body + report_test_options() # chosen values the test has no case for (setup/options.jl) + end +end + +# The number options a test declares with test_params(...) at the top of its file, and the values +# its loops have (test_values/test_cases), the types (test_types/backend_types) and the flags (test_flags), +# read from the file's syntax without running it. +function _literal(ex, names = Dict{Symbol, Any}()) + ex isa Union{Number, Char, String} && return ex + ex isa QuoteNode && return ex.value + ex isa Symbol && ex in (:nothing, :true, :false) && return eval(ex) + ex isa Symbol && haskey(TYPE_NAMES, string(ex)) && return TYPE_NAMES[string(ex)] + ex isa Symbol && haskey(names, ex) && return names[ex] + Meta.isexpr(ex, :tuple) && return map(x -> _literal(x, names), Tuple(ex.args)) + if Meta.isexpr(ex, :if) && length(ex.args) == 3 # `c ? a : b`: the values of both + a, b = _literal(ex.args[2], names), _literal(ex.args[3], names) + a isa Tuple && b isa Tuple && return Tuple(unique((a..., b...))) + end + return missing +end +# Names assigned a literal list in the file (`const _LU_SHAPES = (...)`, `sizes = c ? (...) : (...)`). +function _assigned_lists(ex, names = Dict{Symbol, Any}()) + ex isa Expr || return names + a = Meta.isexpr(ex, :const) ? ex.args[1] : ex + if Meta.isexpr(a, :(=)) && a.args[1] isa Symbol + v = _literal(a.args[2], names) + v isa Tuple && (names[a.args[1]] = v) + end + foreach(x -> _assigned_lists(x, names), ex.args) + return names +end +function test_declaration(file) + params = Pair{Symbol, String}[] + seen = Dict{Symbol, Set{Any}}() + add!(name, v) = v === missing || v === nothing || push!(get!(Set{Any}, seen, name), v) + lists = Dict{Symbol, Any}() + _literal(x) = Main._literal(x, lists) + function walk(ex) + ex isa Expr || return + if Meta.isexpr(ex, :call) && !isempty(ex.args) + f, a = ex.args[1], ex.args[2:end] + pos = filter(x -> !Meta.isexpr(x, :parameters) && !Meta.isexpr(x, :kw), a) + if f === :test_params + for x in a, kv in (Meta.isexpr(x, :parameters) ? x.args : (x,)) + Meta.isexpr(kv, :kw) && push!(params, kv.args[1] => string(kv.args[2])) + end + elseif f === :test_values && length(pos) >= 2 + name, vals = _literal(pos[1]), _literal(pos[2]) + vals isa Tuple && foreach(v -> add!(name, v), vals) + elseif f === :test_cases && length(pos) >= 2 + names, vals = _literal(pos[1]), _literal(pos[2]) + if names isa Tuple && vals isa Tuple + for c in vals, (i, n) in enumerate(names) + n === nothing || !(c isa Tuple) || add!(n, c[i]) + end + end + elseif f in (:test_flags,) && length(pos) >= 2 + name, vals = _literal(pos[1]), _literal(pos[2]) + if name isa Symbol && vals isa Tuple + foreach(v -> add!(name, v isa Bool ? (v ? 'U' : 'N') : v), vals) + elseif name isa Tuple && vals isa Tuple + for c in vals, (i, n) in enumerate(name) + n === nothing || !(c isa Tuple) || add!(n, c[i] isa Bool ? (c[i] ? 'U' : 'N') : c[i]) + end + end + elseif f in (:test_types, :backend_types) && !isempty(pos) + vals = _literal(pos[end]) + vals isa Tuple && foreach(T -> T isa DataType && add!(:types, T), vals) + Meta.isexpr(pos[end], :tuple) && any(x -> Meta.isexpr(x, :...) && x.args[1] === :TEST_TYPES, pos[end].args) && + foreach(T -> add!(:types, T), (Float32, Float64, ComplexF32, ComplexF64)) + pos[end] === :TEST_TYPES && foreach(T -> add!(:types, T), (Float32, Float64, ComplexF32, ComplexF64)) + end + end + foreach(walk, ex.args) + end + code = Meta.parseall(read(file, String); filename = file) + _assigned_lists(code, lists) + walk(code) + return params, seen +end + +const SELECTED = let s = copy(testsuite) + filter_tests!(s, args) + sort(collect(keys(s))) +end + +# --params: print the options each selected test takes, with the values its loops have, and stop. +if args.custom["params"] !== nothing + something(args.custom["params"]) === nothing || error("--params takes no value; name the tests after it") + show_vals(vs) = join(sort(collect(vs); by = v -> v isa DataType ? string(v) : v), ", ") + for t in SELECTED + params, seen = test_declaration(TEST_FILES[t]) + println(t) + for (p, meaning) in params + println(" --", rpad(p, 7), rpad(meaning, 44), haskey(seen, p) ? show_vals(seen[p]) : "") end + group = [p for (p, _) in params if p in (:m, :n, :k)] + length(group) > 1 && println(" (give ", join(("--$p" for p in group), ", ", " and "), " together)") + for f in (:types, :uplo, :side, :trans, :diag) + haskey(seen, f) && println(" --", rpad(f, 7), rpad("", 44), show_vals(seen[f])) + end + println() 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)) + exit(0) +end + +# The number options: one test at a time, only the options it declares, its sizes all together. +let given = [o for o in NUMBER_OPTIONS if TEST_OPTIONS[Symbol(o)] !== nothing] + if !isempty(given) + # A name selects every test that starts with it; with number options the test named exactly runs alone. + exact = filter(t -> t in args.positionals, SELECTED) + if length(exact) == 1 + foreach(t -> t == only(exact) || delete!(testsuite, t), collect(keys(testsuite))) + empty!(SELECTED); push!(SELECTED, only(exact)) end + length(SELECTED) == 1 || error("--", join(given, ", --"), " can be given for one test only; ", + isempty(SELECTED) ? "no test is selected" : "selected $(length(SELECTED)): " * join(first(SELECTED, 5), ", ") * + (length(SELECTED) > 5 ? ", ..." : ""), " (see the options of a test with --params )") + t = only(SELECTED) + params, _ = test_declaration(TEST_FILES[t]) + declared = string.(first.(params)) + bad = setdiff(given, declared) + isempty(bad) || error("$t has no --", join(bad, ", --"), "; it takes ", + isempty(declared) ? "no number options" : "--" * join(declared, ", --")) + group = intersect(["m", "n", "k"], declared) + (isempty(intersect(group, given)) || issubset(group, given)) || + error("$t needs --", join(group, ", --"), " together; given --", join(intersect(group, given), ", --")) end - return A -end - -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") +end + +# Cap the number of test processes by the GPU's free memory when CUDA is used. +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 no memory report (some integrated GPUs) + CUDA.device!(() -> Int(CUDA.free_memory()), dev) + end + 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 + +# The backends the tests will run on, printed once (a GPU that fails to load would otherwise go unnoticed). +const BACKENDS_TESTED = let m = Module(:BackendsTested) + Core.eval(m, :(const TEST_BACKENDS_WANTED = $BACKENDS)) + Base.include(m, joinpath(TESTDIR, "setup", "gpu_backends.jl")) + first.(Base.invokelatest(() -> m.available_backends())) +end +println("Backends tested: ", join(BACKENDS_TESTED, ", ")) + +# Keep test times and last failures separately for each --backends choice (and each set of options). +const HISTORY_KEY = let parts = String[] + isempty(WANTED) || push!(parts, join(sort(WANTED), ",")) + for (k, v) in pairs(TEST_OPTIONS) + v === nothing || push!(parts, string(k, "=", v isa Tuple ? join(v, ",") : v)) + end + isempty(parts) ? nothing : join(parts, ";") +end + +runtests(NextLA, args; testsuite, init_code, max_default_jobs = MAX_DEFAULT_JOBS, history_key = HISTORY_KEY) diff --git a/test/setup/accuracy.jl b/test/setup/accuracy.jl new file mode 100644 index 00000000..1ed0e82c --- /dev/null +++ b/test/setup/accuracy.jl @@ -0,0 +1,178 @@ +# Accuracy ratios of the reference BLAS and LAPACK tests, computed on the host in BigFloat. + +# Pass threshold of the reference BLAS level-3 element ratio (dblat3.f, DMMCH). +const BLAS_TEST_THRESHOLD = 16 + +# Pass threshold of LAPACK's test ratios (TESTING/dtest.in). +const LAPACK_TEST_THRESHOLD = 30 + +_test_op(X, t::Char) = t == 'N' ? X : t == 'T' ? transpose(X) : adjoint(X) + +# One element's ratio before dividing by eps; the error alone where the gauge is zero, as DMMCH does. +_elem_ratio(e, g) = iszero(g) ? e : e / g + +""" + gemm_ratio(C, transA, transB, α, A, B, β, C0; eps) -> Float64 + +The largest per-element ratio of the reference BLAS test for `C = α op(A) op(B) + +β C0`: `|C - exact| / (eps (|α| |op(A)| |op(B)| + |β| |C0|))`. `C`, `A`, `B` and +`C0` may be device arrays. `eps` is that of the wider of the compute type and the +storage of `C` (see `gemm_eps`). +""" +function gemm_ratio(C, transA, transB, α, A, B, β, C0; eps) + opA, opB = _test_op(big.(Array(A)), transA), _test_op(big.(Array(B)), transB) + exact = big(α) .* (opA * opB) .+ big(β) .* big.(Array(C0)) + gauge = abs(big(α)) .* (abs.(opA) * abs.(opB)) .+ abs(big(β)) .* abs.(big.(Array(C0))) + return Float64(maximum(_elem_ratio.(abs.(big.(Array(C)) .- exact), gauge); init=big(0))) / eps +end + +""" + gemm_eps(compute_type, TC) + +The eps a product's error is measured in: that of the wider of the accumulation +type and the storage type of the result, as the result is rounded to the latter +once at the end. +""" +gemm_eps(compute_type, TC) = Float64(max(eps(real(compute_type)), eps(real(TC)))) + +""" + trsm_ratio(X, side, uplo, trans, diag, α, A, B; eps) -> Float64 + +The largest per-element ratio of the reference BLAS test for a triangular solve +`op(A) X = α B` (`side = 'L'`) or `X op(A) = α B` (`'R'`): the computed `X` is put +back, `|op(A) X - α B| / (eps (|op(A)| |X| + |α| |B|))`, as dblat3 checks DTRSM. +`A` is read as its `uplo` triangle, with ones on the diagonal for `diag = 'U'`. +""" +function trsm_ratio(X, side, uplo, trans, diag, α, A, B; eps) + Ab = big.(Array(A)) + Tr = uplo == 'L' ? tril(Ab) : triu(Ab) + diag == 'U' && (Tr[LinearAlgebra.diagind(Tr)] .= 1) + opT, Xb, αB = _test_op(Tr, trans), big.(Array(X)), big(α) .* big.(Array(B)) + R = side == 'L' ? opT * Xb .- αB : Xb * opT .- αB + G = side == 'L' ? abs.(opT) * abs.(Xb) .+ abs.(αB) : abs.(Xb) * abs.(opT) .+ abs.(αB) + return Float64(maximum(_elem_ratio.(abs.(R), G); init=big(0))) / eps +end + +""" + trmm_ratio(X, side, uplo, trans, diag, α, A, B; eps) -> Float64 + +The reference BLAS ratio for a triangular multiply `X = α op(A) B` (`side = 'L'`) +or `α B op(A)` (`'R'`): `gemm_ratio` with `A` read as its `uplo` triangle (ones on +the diagonal for `diag = 'U'`) and `β = 0`. +""" +function trmm_ratio(X, side, uplo, trans, diag, α, A, B; eps) + Ab = Array(A) + Tr = uplo == 'L' ? tril(Ab) : triu(Ab) + diag == 'U' && (Tr[LinearAlgebra.diagind(Tr)] .= one(eltype(Tr))) + Z = zeros(eltype(B), size(X)) + return side == 'L' ? gemm_ratio(X, trans, 'N', α, Tr, Array(B), 0, Z; eps) : + gemm_ratio(X, 'N', trans, α, Array(B), Tr, 0, Z; eps) +end + +""" + trxm_ratio(X, func, side, uplo, trans, diag, α, A, B; eps) + +`trsm_ratio` for a solve (`func = 'S'`), `trmm_ratio` for a multiply (`'M'`). +""" +trxm_ratio(X, func, args...; eps) = func == 'S' ? trsm_ratio(X, args...; eps) : trmm_ratio(X, args...; eps) + +""" + trxm_residual_ratio(X, func, side, uplo, trans, diag, α, A, B) -> Float64 + +LAPACK's normwise checks of a triangular solve and multiply (TESTING/LIN/dtrt02.f, +dtrt03.f), for sizes where the per-element ratio in BigFloat is too slow: for a +solve `‖op(A) X - α B‖₁ / (‖op(A)‖₁ ‖X‖₁ eps)`, for a multiply +`‖X - α op(A) B‖₁ / (‖op(A)‖₁ ‖α B‖₁ eps)`, with the right-hand side on the side +of `side`; computed in Float64 (ComplexF64) with the eps of the data's type, and +compared with `LAPACK_TEST_THRESHOLD`. +""" +function trxm_residual_ratio(X, func, side, uplo, trans, diag, α, A, B) + W = real(eltype(B)) === Float64 || real(eltype(B)) === Float32 || real(eltype(B)) === Float16 ? + (eltype(B) <: Complex ? ComplexF64 : Float64) : eltype(B) + Ab = W.(Array(A)) + Tr = uplo == 'L' ? tril(Ab) : triu(Ab) + diag == 'U' && (Tr[LinearAlgebra.diagind(Tr)] .= one(W)) + opT, Xw, Bw = _test_op(Tr, trans), W.(Array(X)), W(α) .* W.(Array(B)) + e = Float64(eps(real(eltype(B)))) + if func == 'S' + R = side == 'L' ? opT * Xw .- Bw : Xw * opT .- Bw + return opnorm(R, 1) / (opnorm(opT, 1) * opnorm(Xw, 1) * e) + else + R = side == 'L' ? Xw .- opT * Bw : Xw .- Bw * opT + return opnorm(R, 1) / (opnorm(opT, 1) * opnorm(Bw, 1) * e) + end +end + +""" + lu_ratio(L, U, PAQ; eps) -> Float64 + +LAPACK's check of an LU factorization (TESTING/LIN/dget01.f): +`‖L U - P A Q‖₁ / (n ‖A‖₁ eps)`, `n` the number of columns, computed in Float64 +(ComplexF64); compared with `LAPACK_TEST_THRESHOLD`. +""" +function lu_ratio(L, U, PAQ; eps) + W = eltype(PAQ) <: Complex ? ComplexF64 : Float64 + return opnorm(W.(Array(L)) * W.(Array(U)) .- W.(Array(PAQ)), 1) / + (max(size(PAQ, 2), 1) * opnorm(W.(Array(PAQ)), 1) * eps) +end + +""" + syrk_ratio(C, uplo, trans, α, A, β, C0; eps) -> Float64 + +The largest per-element ratio of the reference BLAS test of DSYRK (dblat3, DCHK4 +through DMMCH) over the `uplo` triangle of `C = α op(A) op(A)ᵀ + β C0`, with +`op(A) = A` for `trans = 'N'` and `Aᵀ` otherwise (SYRK does not conjugate): +`|C - exact| / (eps (|α| |op(A)| |op(A)|ᵀ + |β| |C0|))`, exact in BigFloat. +""" +function syrk_ratio(C, uplo, trans, α, A, β, C0; eps) + Ab = big.(Array(A)) + opA = trans == 'N' ? Ab : transpose(Ab) + exact = big(α) .* (opA * transpose(opA)) .+ big(β) .* big.(Array(C0)) + gauge = abs(big(α)) .* (abs.(opA) * transpose(abs.(opA))) .+ abs(big(β)) .* abs.(big.(Array(C0))) + keep = uplo == 'L' ? tril : triu + return Float64(maximum(keep(_elem_ratio.(abs.(big.(Array(C)) .- exact), gauge)); init=big(0))) / eps +end + +""" + other_triangle(uplo, X) + +The strict triangle of `X` that a SYRK of triangle `uplo` must leave as it was: +above the diagonal for `'L'`, below it for `'U'` (dblat3 checks it with LDERES). +""" +other_triangle(uplo, X) = uplo == 'L' ? triu(Array(X), 1) : tril(Array(X), -1) + +""" + chol_ratio(F, uplo, A; eps) -> Float64 + +LAPACK's check of a Cholesky factorization (dpot01): `‖LLᴴ - A‖₁ / (n ‖A‖₁ eps)` with +`L` the lower triangle of `F` (`uplo = 'L'`), or `‖UᴴU - A‖₁ / (n ‖A‖₁ eps)` with `U` the +upper one, in Float64 (ComplexF64). +""" +function chol_ratio(F, uplo, A; eps) + W = eltype(A) <: Complex ? ComplexF64 : Float64 + Fd, Ad = W.(Array(F)), W.(Array(A)) + P = uplo == 'L' ? LowerTriangular(Fd) * LowerTriangular(Fd)' : UpperTriangular(Fd)' * UpperTriangular(Fd) + return opnorm(P .- Ad, 1) / (max(size(Ad, 1), 1) * opnorm(Ad, 1) * eps) +end + +""" + tpqr_q(V2, Tm, n, m, ib) -> Matrix{BigFloat or Complex{BigFloat}} + +The orthogonal factor, of order n + m, of a triangle-on-top factorization (tsqrt!, ttqrt!, +LAPACK tpqrt): block b of columns ii:ii+sb-1 is I - V T_b Vᴴ with V = [unit rows ii:ii+sb-1; +V2's columns ii:ii+sb-1], applied in order; computed exactly. +""" +function tpqr_q(V2, Tm, n, m, ib) + Vb, Tb = big.(Array(V2)), big.(Array(Tm)) + Q = Matrix{eltype(Vb)}(I, n + m, n + m) + for ii in reverse(collect(1:ib:n)) + sb = min(ib, n - ii + 1) + V = zeros(eltype(Vb), n + m, sb) + for j in 1:sb + V[ii+j-1, j] = 1 + V[n+1:n+m, j] = Vb[:, ii+j-1] + end + Q -= V * (UpperTriangular(Tb[1:sb, ii:ii+sb-1]) * (V' * Q)) + end + return Q +end diff --git a/test/backend_test_helpers.jl b/test/setup/backend_test_helpers.jl similarity index 73% rename from test/backend_test_helpers.jl rename to test/setup/backend_test_helpers.jl index 60edaaac..18fde19a 100644 --- a/test/backend_test_helpers.jl +++ b/test/setup/backend_test_helpers.jl @@ -1,5 +1,4 @@ -# Batched GEMM tests cover both plain arrays and pointer-batched -# Vector-of-matrix inputs, so backend conversion needs to recurse into batches. +# Move an input to a backend, recursing into Vector-of-matrix batches. _to_backend(::Type{Array}, x) = x _to_backend(::Type{Array}, x::AbstractVector) = [_to_backend(Array, xi) for xi in x] @@ -21,14 +20,12 @@ function _device_pointer_batch(name::String, batch::AbstractVector) throw(ArgumentError("pointer batches are not supported for backend `$name`")) end -# method source files give us a cheap dispatch-path assertion in tests. -# Separators are normalised to "/" so the expected paths below match on -# Windows, where functionloc returns backslashes. +# Source file of the method a call dispatches to, with "/" separators, for dispatch-path checks. _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 +34,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 +43,17 @@ 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" + # oneAPI has no single-matrix potrf! wrapper, so it reaches the generic method's guard (KNOWN_ISSUES.md). + 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 +62,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/setup/dense.jl b/test/setup/dense.jl new file mode 100644 index 00000000..6709db2e --- /dev/null +++ b/test/setup/dense.jl @@ -0,0 +1,12 @@ +# Helpers shared by the dense tests (test/dense/**), included at the start of each dense test. + +using LinearAlgebra.LAPACK + +include(joinpath(@__DIR__, "gpu_backends.jl")) # backends and test options (shared with mxp) +include(joinpath(@__DIR__, "lapack_helpers.jl")) # test types, tolerances, LAPACK references +include(joinpath(@__DIR__, "backend_test_helpers.jl")) # moving inputs to a backend, dispatch checks +include(joinpath(@__DIR__, "matrices.jl")) # shared test matrices (randsvd, spd, ...) +include(joinpath(@__DIR__, "accuracy.jl")) # BLAS/LAPACK-style accuracy ratios + +# The backends the dense tests run on (several files loop over this global). +backends = available_backends() diff --git a/test/setup/gpu_backends.jl b/test/setup/gpu_backends.jl new file mode 100644 index 00000000..5b14f598 --- /dev/null +++ b/test/setup/gpu_backends.jl @@ -0,0 +1,171 @@ +using KernelAbstractions + +Base.include(@__MODULE__, joinpath(@__DIR__, "options.jl")) # --types, --n, --uplo, ... (test_types, test_values, ...) + +""" + supports_float64(ArrayType) + +Whether `ArrayType`'s device can hold `Float64`, decided by trying it. + +Double precision is a property of the part and its driver, not of the vendor +library: Intel's data-center GPUs support it, consumer integrated graphics +generally do not, and `oneArray(::Matrix{Float64})` throws rather than falling +back. So this asks the device instead of assuming anything about the backend. +""" +function supports_float64(ArrayType) + # NEXTLA_TEST_NO_FLOAT64=1: every GPU backend behaves as one without Float64 (to check the Metal path). + ArrayType !== Array && get(ENV, "NEXTLA_TEST_NO_FLOAT64", "0") == "1" && return false + try + # invokelatest: the backend package is loaded dynamically, so a direct call hits a world-age error. + Base.invokelatest(ArrayType, zeros(Float64, 1, 1)) + return true + catch e + get(ENV, "NEXTLA_GPU_DEBUG", "0") == "1" && + @warn "$ArrayType: no Float64 support — $(sprint(showerror, e))" + return false + end +end + +""" + backend_types(ArrayType, types) + +The types of `types` a backend can hold: all of them, or without Float64 and ComplexF64 on a device +without Float64 (Metal); then only those chosen with `--types` (test_types). +""" +backend_types(ArrayType, types) = + test_types(supports_float64(ArrayType) ? Tuple(types) : Tuple(T for T in types if real(T) !== Float64)) + +""" + has_device_potrf(name) + +Whether the backend `name` has a single-matrix `potrf!`: the CPU, CUDA and AMDGPU do; Metal's +throws ArgumentError (ext/metal/potrf.jl) and oneAPI has only the batched one (ext/oneapi/potrf.jl). +""" +has_device_potrf(name) = name in ("CPU", "CUDA", "AMDGPU") + +# Backends asked for with --backends, as lowercase names; empty means every available backend. +_wanted_backends() = + isdefined(@__MODULE__, :TEST_BACKENDS_WANTED) && !isempty(strip(TEST_BACKENDS_WANTED)) ? + lowercase.(strip.(split(TEST_BACKENDS_WANTED, ','))) : String[] + +""" + cpu_wanted() + +Whether the CPU is one of the backends asked for: no --backends, or --backends +naming CPU. A testset written for the CPU alone runs only then +(`cpu_wanted() && @testset ...`), so that --backends=CUDA runs nothing on the CPU, +as test/README.md says. +""" +cpu_wanted() = (w = _wanted_backends(); isempty(w) || "cpu" in w) + +""" + with_threads(code; threads = test_threads()) -> String + +Runs the Julia `code` in a child Julia with `threads` threads, in the same +environment as this test (Base.julia_cmd() and --project=Base.active_project(), as +ParallelTestRunner starts its workers), and returns what it prints. The suite runs +each test with one thread, so this is how a test runs a threaded path with several +threads at once, as Julia's own test/threads.jl does. +""" +function with_threads(code::AbstractString; threads::Integer=test_threads()) + cmd = `$(Base.julia_cmd()) --startup-file=no --threads=$threads --project=$(Base.active_project()) -e $code` + return readchomp(addenv(cmd, "JULIA_NUM_THREADS" => string(threads))) +end + +""" + seed_backends!(seed) + +Seeds the random number generators of the GPU backends that are loaded, as +test/runtests.jl seeds Random on the host before each test, so that --seed=N also +replays numbers drawn on a device. CUDA: randn!/rand! of a CuArray use cuRAND's own +generators, which otherwise seed themselves from the system; cuRAND.seed! seeds all +three (CUDA.jl, lib/curand/src/cuda_integration.jl). The other backends are not +seeded here yet: no test or routine draws on them. +""" +function seed_backends!(seed::Integer) + id = Base.identify_package("CUDA") + (id === nothing || !haskey(Base.loaded_modules, id)) && return nothing + CUDA = Base.loaded_modules[id] + Base.invokelatest(CUDA.functional) || return nothing + s = UInt64(seed) + if isdefined(CUDA, :cuRAND) && isdefined(CUDA.cuRAND, :seed!) + Base.invokelatest(CUDA.cuRAND.seed!, s) + else # CUDA.jl before cuRAND moved to its own package + Base.invokelatest(CUDA.seed!, s) + end + return nothing +end + +""" + available_gpu_backends() + +Returns a vector of (name, ArrayType, synchronize_fn) for GPU backends that are +loadable and functional. Uses try/catch to skip backends that are not installed. + +Synchronize_fn is a function that takes a GPU array and synchronizes its backend: + sync(arr) = KernelAbstractions.synchronize(KernelAbstractions.get_backend(arr)) +""" +function available_gpu_backends() + backends = Tuple{String, Type, Function}[] + backend_defs = [ + ("CUDA", :CUDA, :CuArray, :functional), + ("AMDGPU", :AMDGPU, :ROCArray, :functional), + ("oneAPI", :oneAPI, :oneArray, :functional), + ("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 loaded, so --backends=CPU loads no 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) + # Check the backend is functional (invokelatest avoids world-age errors). + if Base.invokelatest(getproperty(pkg, func_sym)) + AT = getproperty(pkg, array_sym) + # A backend without Float64 (Metal) is kept; its tests take their types from backend_types. + # Under NEXTLA_TEST_NO_FLOAT64=1 a CUDA array refuses Float64 data, as a Metal array does. + if name == "CUDA" && get(ENV, "NEXTLA_TEST_NO_FLOAT64", "0") == "1" + Core.eval(pkg, :((::Type{CuArray})(x::AbstractArray{<:Union{Float64, ComplexF64}}) = + throw(ArgumentError("no Float64 on this device (NEXTLA_TEST_NO_FLOAT64=1)")))) + end + sync_fn = function(arr) + KernelAbstractions.synchronize(KernelAbstractions.get_backend(arr)) + end + push!(backends, (name, AT, sync_fn)) + elseif debug + @warn "$name: functional() returned false (no GPU or driver issue)" + end + catch e + debug && @warn "$name: $(sprint(showerror, e))" + continue + end + end + return backends +end + +""" + available_backends() + +Returns a vector of (name, ArrayType, synchronize_fn) for all available backends, +including CPU first, then any functional GPU backends. Ensures tests always run +on at least CPU when no GPU is available. +""" +function available_backends() + backends = Tuple{String, Type, Function}[] + 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/lapack_helpers.jl b/test/setup/lapack_helpers.jl similarity index 80% rename from test/lapack_helpers.jl rename to test/setup/lapack_helpers.jl index be246038..237cfa2b 100644 --- a/test/lapack_helpers.jl +++ b/test/setup/lapack_helpers.jl @@ -10,11 +10,26 @@ using LinearAlgebra.BLAS: @blasfunc const TEST_TYPES = (Float32, Float64, ComplexF32, ComplexF64) -# Tolerance helper: single‑precision types get looser tolerance -test_rtol(::Type{T}) where {T} = (T <: Union{Float32, ComplexF32}) ? 1e-5 : 1e-12 +# One relative tolerance per type of TEST_TYPES (reviewed files use test/setup/accuracy.jl). +function test_rtol(::Type{T}) where {T} + T <: Union{Float32, ComplexF32} && return 1e-5 + T <: Union{Float64, ComplexF64} && return 1e-12 + throw(ArgumentError("test_rtol has no tolerance for $T, only for $(join(TEST_TYPES, ", ")); give the check its own")) +end -# ── xLARFG — elementary reflector generation ───────────────────────────────── -# Reference for larfg! comparison tests. +# xLARFT: triangular factor of a block reflector, reference for larft!. +for (elty, func) in ((Float64, :dlarft_), (Float32, :slarft_), (ComplexF64, :zlarft_), (ComplexF32, :clarft_)) + @eval function lapack_larft(direct::Char, storev::Char, n::Int, k::Int, V::Matrix{$elty}, tau::Vector{$elty}) + T = zeros($elty, k, k) + ccall((@blasfunc($func), libblastrampoline), Cvoid, + (Ref{UInt8}, Ref{UInt8}, Ref{BlasInt}, Ref{BlasInt}, Ptr{$elty}, Ref{BlasInt}, Ptr{$elty}, + Ptr{$elty}, Ref{BlasInt}, Clong, Clong), + direct, storev, n, k, V, max(1, stride(V, 2)), tau, T, max(1, k), 1, 1) + return T + end +end + +# xLARFG: elementary reflector, reference for larfg!. for (elty, func) in ((Float64, :dlarfg_), (Float32, :slarfg_), (ComplexF64, :zlarfg_), @@ -33,8 +48,7 @@ for (elty, func) in ((Float64, :dlarfg_), end end -# ── xLARTG — Givens rotation generation ───────────────────────────────────── -# Reference for lartg comparison tests. +# xLARTG: Givens rotation, reference for lartg. for (elty, func, rty) in ((Float64, :dlartg_, Float64), (Float32, :slartg_, Float32), (ComplexF64, :zlartg_, Float64), @@ -54,8 +68,7 @@ for (elty, func, rty) in ((Float64, :dlartg_, Float64), end end -# ── xTPQRT — triangular‑pentagonal QR factorization ───────────────────────── -# Reference for tsqrt! (l=0) and ttqrt! (l=n). +# xTPQRT: triangular-pentagonal QR, reference for tsqrt! (l = 0) and ttqrt! (l = n). for (elty, func) in ((Float64, :dtpqrt_), (Float32, :stpqrt_), (ComplexF64, :ztpqrt_), @@ -77,8 +90,7 @@ for (elty, func) in ((Float64, :dtpqrt_), end end -# ── xTPMQRT — apply Q from xTPQRT factorization ───────────────────────────── -# Reference for tsmqr! (l=0) and ttmqr! (l>0). +# xTPMQRT: apply Q from xTPQRT, reference for tsmqr! (l = 0) and ttmqr! (l > 0). for (elty, func) in ((Float64, :dtpmqrt_), (Float32, :stpmqrt_), (ComplexF64, :ztpmqrt_), @@ -118,8 +130,7 @@ for (elty, func) in ((Float64, :dtpmqrt_), end end -# ── xTPRFB — apply block reflector ────────────────────────────────────────── -# Reference for parfb!. +# xTPRFB: apply a block reflector, reference for parfb!. for (elty, func) in ((Float64, :dtprfb_), (Float32, :stprfb_), (ComplexF64, :ztprfb_), @@ -133,7 +144,7 @@ for (elty, func) in ((Float64, :dtprfb_), ldt, k = size(Tee) ldv = max(1, stride(V, 2)) lda = max(1, stride(A, 2)) - ldb = max(1, m) + ldb = max(1, stride(B, 2)) if side == 'L' work = Matrix{$elty}(undef, k, n) diff --git a/test/setup/matrices.jl b/test/setup/matrices.jl new file mode 100644 index 00000000..5f4b6b70 --- /dev/null +++ b/test/setup/matrices.jl @@ -0,0 +1,67 @@ +# Host test matrices of a chosen kind and condition number (dense and mxp tests, benchmark). + +""" + diagdom(T, n; rng) -> Matrix{T} + +`rand + 2n I`: strictly diagonally dominant by rows and by columns, so LU +needs no pivoting (Higham 2002, §9.5). +""" +diagdom(T, n; rng=Random.default_rng()) = rand(rng, T, n, n) + T(2n) * I + +""" + spd(T, n; cond = nothing, rng) -> Matrix{T} + +A symmetric positive definite matrix. Without `cond`: `R Rᵀ + n I` with `R = +rand`, well conditioned. With `cond`: `Q Λ Qᵀ`, `Q` from the QR factorization +of a Gaussian matrix and eigenvalues from 1 down to `1/cond` in geometric steps, so +its condition number is `cond`. +""" +function spd(T, n; cond=nothing, rng=Random.default_rng()) + if cond === nothing + R = rand(rng, T, n, n) + S = R * R' + T(n) * I + else + Q = Matrix(qr(randn(rng, T, n, n)).Q) + S = Q * Diagonal(T.(exp10.(range(0, -log10(cond); length=n)))) * Q' + end + return (S + S') / 2 +end + +""" + randsvd(T, m, n; cond, mode = :geometric, anorm = 1, rng) -> Matrix{T} + +`U[:, 1:k] Σ V[:, 1:k]ᴴ`, `k = min(m, n)`, with `U` and `V` from the QR factorization +of Gaussian matrices and singular values set by `mode`: `:geometric`, from `anorm` +down to `anorm/cond` in geometric steps; `:one_large`, all 1 but the first, `cond`; +`:one_small`, all 1 but the last, `1/cond`. These are the modes of Higham's randsvd +(Higham 2002, §28.3) and of LAPACK's test-matrix generator dlatms. +""" +function randsvd(T, m, n; cond, mode=:geometric, anorm=one(real(T)), rng=Random.default_rng()) + (m == 0 || n == 0) && return zeros(T, m, n) + k = min(m, n) + σ = zeros(real(T), k) + if mode === :geometric + k == 1 ? (σ[1] = anorm) : (σ .= [anorm * (1 / cond)^((i - 1) / (k - 1)) for i in 1:k]) + elseif mode === :one_large + σ .= 1; σ[1] = cond + elseif mode === :one_small + σ .= 1; σ[end] = 1 / cond + else + throw(ArgumentError("randsvd: mode must be :geometric, :one_large or :one_small, got $mode")) + end + U, _ = qr(randn(rng, T, m, m)) + V, _ = qr(randn(rng, T, n, n)) + return U[:, 1:k] * Diagonal(σ) * V[:, 1:k]' +end + +""" + graded(T, n; range = 1e6, rng) -> Matrix{T} + +`D A D` with `A = rand` and `D` diagonal from 1 down to `1/sqrt(range)` in +geometric steps, so the entries span about `range`: a badly scaled matrix, the case +two-sided diagonal scaling is for (Higham and Pranesh, SIAM J. Sci. Comput. 2019). +""" +function graded(T, n; range=1e6, rng=Random.default_rng()) + d = T.(exp10.(Base.range(0, -log10(range) / 2; length=n))) + return Diagonal(d) * rand(rng, T, n, n) * Diagonal(d) +end diff --git a/test/setup/mxp.jl b/test/setup/mxp.jl new file mode 100644 index 00000000..414e019c --- /dev/null +++ b/test/setup/mxp.jl @@ -0,0 +1,186 @@ +# Helpers shared by the mixed-precision tests (test/mxp/**); error bounds in records/mxp-error-bounds.md. + +using NextLA.MixedPrecision +include(joinpath(@__DIR__, "matrices.jl")) # spd, diagdom, randsvd, graded + +# Backends: every available one, or those given with --backends. +const MXP_BACKENDS = available_backends() +@info "Mixed-precision test backends" backends=first.(MXP_BACKENDS) + +const MXP_LAMBDA = 8 + +mxp_u(::Type{T}) where {T} = Float64(eps(T)) / 2 +# Largest absolute error of storing a value below the normal range of T (Higham 2002, §2.1). +mxp_eta(::Type{T}) where {T} = mxp_u(T) * Float64(floatmin(T)) + +""" + 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_expected_type_map(n, P) -> Matrix{DataType} + +Expected storage type of each element of an n×n Full/Symm/TriMixedPrec with +precisions `P`, from `n` and `P` alone (the FullMixedPrec docstring rule), not from +the container. +""" +function mxp_expected_type_map(n::Integer, P) + E = Matrix{DataType}(undef, n, n) + _mxp_expected!(E, P) + return E +end + +function _mxp_expected!(E, P) + n = size(E, 1) + (length(P) == 1 || n == 1) && return fill!(E, P[end]) + mid = ispow2(n) ? n ÷ 2 : prevpow(2, n) + _mxp_expected!(view(E, 1:mid, 1:mid), P[2:end]) + _mxp_expected!(view(E, mid+1:n, mid+1:n), P[2:end]) + fill!(view(E, mid+1:n, 1:mid), P[1]) + fill!(view(E, 1:mid, mid+1:n), P[1]) + return E +end + +""" + mxp_tile_sizes(n, threshold) -> Vector{Int} + +The diagonal tile sizes of a TiledTriMixedPrec: TriMixedPrec's split, stopped at `threshold` rows. +""" +mxp_tile_sizes(n, t) = n <= t ? [n] : (mid = ispow2(n) ? n ÷ 2 : prevpow(2, n); [mxp_tile_sizes(mid, t); mxp_tile_sizes(n - mid, t)]) + +""" + mxp_expected_tile_map(n, threshold, P) -> Matrix{DataType} + +Expected storage type of each element of a TiledTriMixedPrec, from n, threshold and P alone: +`P[end]` on the diagonal tiles, `P[1]` elsewhere. +""" +function mxp_expected_tile_map(n, t, P) + E = fill(P[1], n, n) + o = cumsum([1; mxp_tile_sizes(n, t)]) + for k in 1:length(o)-1 + E[o[k]:o[k+1]-1, o[k]:o[k+1]-1] .= P[end] + end + return E +end + +""" + mxp_storage_ok(R, A, E) + +Whether each element of `R` is within one rounding of `A` in its storage type +`E[i, j]`: u relative, plus mxp_eta below the normal range. +""" +function mxp_storage_ok(R, A, E) + return all(abs(Float64(R[i]) - Float64(A[i])) <= mxp_u(E[i]) * abs(Float64(A[i])) + mxp_eta(E[i]) + for i in eachindex(A)) +end + +# Matrices (entries uniform in [0, 1) in magnitude, with random signs). + +mxp_rand(T, m, n) = rand(T, m, n) .* rand((-1, 1), m, n) +mxp_spd(T, n) = spd(T, n) +mxp_diagdom(T, n) = diagdom(T, n) +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 in Float64 on the host: solve, LU, Cholesky. + +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: a host copy of a device container. + +""" + mxp_host(M) + +A copy of the container `M` with every block on the host. +""" +_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/options.jl b/test/setup/options.jl new file mode 100644 index 00000000..049a2852 --- /dev/null +++ b/test/setup/options.jl @@ -0,0 +1,180 @@ +# The run's test options (test/README.md "Choosing cases inside the tests"); test/runtests.jl +# defines TEST_OPTIONS in every test's module. Without an option each helper returns the loop's own values. +# Number options (--m, --n, --k, --ib, --block, --tile, --batch) replace a loop's values; +# --types, --uplo, --side, --trans, --diag keep the chosen values a loop has; --precisions replaces +# a loop's precision lists with the one given. + +_test_option(name::Symbol) = + isdefined(@__MODULE__, :TEST_OPTIONS) ? get(TEST_OPTIONS, name, nothing) : nothing + +const _TEST_OPTIONS_USED = Dict{Symbol, Set{Any}}() # chosen values that some loop ran +const _TEST_OPTIONS_SKIPPED = Dict{Symbol, Set{Any}}() # chosen values of a case skipped with a note +const _TEST_NOTES = Set{String}() + +# Prints `msg` once per test. +_test_note(msg::AbstractString) = msg in _TEST_NOTES || (push!(_TEST_NOTES, msg); println("Note: ", msg); nothing) + +_test_used!(name::Symbol, values) = (union!(get!(Set{Any}, _TEST_OPTIONS_USED, name), values); nothing) +const _TEST_OPTIONS_SEEN = Set{Symbol}() # options some loop of the test looked at +_test_seen!(name::Symbol) = (push!(_TEST_OPTIONS_SEEN, name); nothing) + +""" + test_params(; name = "meaning", ...) + +Declares the number options a test takes, at the top of its file (read by `--params` and checked +by test/runtests.jl before the run). Does nothing when the test runs. +""" +test_params(; kw...) = nothing + +""" + test_types(types) + +The element types of `types` chosen with `--types` (all of them without the option). +""" +function test_types(types) + w = _test_option(:types) + w === nothing && return Tuple(types) + _test_seen!(:types) + kept = Tuple(T for T in types if T in w) + _test_used!(:types, kept) + return kept +end + +# --diag=U/N also selects loops written as `unit in (false, true)`. +_flag_value(v) = v isa Bool ? (v ? 'U' : 'N') : v + +""" + test_flags(name, values) + test_flags(names, cases) + +The values of the flag `name` (`:uplo`, `:side`, `:trans` or `:diag`) chosen with `--uplo=L`, +`--side=R`, `--trans=N,T` or `--diag=U` (all of `values` without the option). With a tuple of +names, the tuples of `cases` whose named entries are all chosen; `nothing` marks an entry that +is not a flag, e.g. `test_flags((:side, :uplo, nothing), ((side, uplo, f), ...))`. +""" +function test_flags(name::Symbol, values) + w = _test_option(name) + w === nothing && return Tuple(values) + _test_seen!(name) + kept = Tuple(v for v in values if _flag_value(v) in w) + _test_used!(name, map(_flag_value, kept)) + return kept +end +function test_flags(names::Tuple, cases) + kept = Tuple(c for c in cases if all(i -> (w = names[i] === nothing ? nothing : _test_option(names[i]); + w === nothing || _flag_value(c[i]) in w), eachindex(names))) + for (i, n) in enumerate(names) + n === nothing || _test_option(n) === nothing || (_test_seen!(n); _test_used!(n, map(c -> _flag_value(c[i]), kept))) + end + return kept +end + +""" + test_precisions(lists; valid = P -> true) + +The mixed-precision lists a loop runs: `lists`, or the one list given with `--precisions`, sorted +from least to most precise as the containers sort it. A list whose most precise type is not Float32 +or Float64 (the containers' rule), or that `valid(P)` refuses (returning the reason as a string), is +skipped with a note. +""" +function test_precisions(lists; valid = _ -> true) + w = _test_option(:precisions) + w === nothing && return Tuple(lists) + _test_seen!(:precisions) + P = sort(DataType[w...]; by = sizeof) + if sizeof(P[end]) < 4 + _test_note("skipped precisions=$(join(P, ",")): the most precise type must be Float32 or Float64") + return () + end + _test_valid((:precisions,), (P,), valid) || return () + _test_used!(:precisions, (Tuple(w),)) + return (P,) +end + +# Prints a skipped case once, with the reason `valid` gave. +_test_show(v) = v isa AbstractVector ? join(v, ",") : string(v) +function _test_valid(names, c, valid) + r = valid(c...) + r === true && return true + for (n, v) in zip(names, c) + n === nothing || push!(get!(Set{Any}, _TEST_OPTIONS_SKIPPED, n), n === :precisions ? Tuple(v) : v) + end + _test_note("skipped " * join((string(n, "=", _test_show(v)) for (n, v) in zip(names, c) if n !== nothing), ", ") * + ": " * string(r)) + return false +end + +""" + test_values(name, values; valid = v -> true) + +The values of a loop over the number `name` (`:m`, `:n`, `:k`, `:ib`, `:block`, `:tile`, `:batch`): +`values`, or those given with `--name=...`. Given values the test cannot take are skipped with a +note: `valid(v)` returns `true` or the reason as a string. +""" +function test_values(name::Symbol, values; valid = _ -> true) + w = _test_option(name) + w === nothing && return Tuple(values) + kept = Tuple(v for v in w if _test_valid((name,), (v,), valid)) + _test_used!(name, kept) + return kept +end + +""" + test_cases(names, cases; valid = (c...) -> true) + +The tuples a loop runs, e.g. `(m, n, ib) in test_cases((:m, :n, :ib), ((20, 7, 3), ...))`: `cases`, +or, when some of `names` are given as options, every combination of the given values with the +values of `cases` in the other entries (taken together, as `cases` pairs them). `nothing` marks an +entry that is not an option. Combinations the test cannot take are skipped with a note: +`valid(c...)` returns `true` or the reason as a string. +""" +function test_cases(names::Tuple, cases; valid = (_...) -> true) + given = map(n -> n !== nothing && _test_option(n) !== nothing, names) + any(given) || return Tuple(cases) + idx_given = Tuple(i for i in eachindex(names) if given[i]) + idx_rest = Tuple(i for i in eachindex(names) if !given[i]) + rest = unique(Tuple(c[i] for i in idx_rest) for c in cases) + out = Any[] + for g in Iterators.product((_test_option(names[i]) for i in idx_given)...), r in rest + c = Vector{Any}(undef, length(names)) + for (j, i) in enumerate(idx_given); c[i] = g[j]; end + for (j, i) in enumerate(idx_rest); c[i] = r[j]; end + t = Tuple(c) + _test_valid(names, t, valid) && push!(out, t) + end + for i in idx_given + _test_used!(names[i], (c[i] for c in out)) + end + return Tuple(out) +end + +const _NUMBER_OPTION_NAMES = (:m, :n, :k, :ib, :block, :tile, :batch) + +""" + report_test_options() + +After a test: prints the chosen values that no loop of the test ran, for the options the test has +loops for (test/runtests.jl calls it). +""" +function report_test_options() + isdefined(@__MODULE__, :TEST_OPTIONS) || return nothing + for (name, w) in pairs(TEST_OPTIONS) + (w === nothing || name === :threads || !(name in _TEST_OPTIONS_SEEN || name in _NUMBER_OPTION_NAMES)) && continue + used = get(_TEST_OPTIONS_USED, name, Set{Any}()) + skipped = get(_TEST_OPTIONS_SKIPPED, name, Set{Any}()) + if name === :precisions + isempty(used) && isempty(skipped) && _test_note("--precisions was not used by this test") + continue + end + unused = [v for v in w if !(v in used) && !(v in skipped)] + isempty(unused) || _test_note("--$name=$(join(unused, ",")) was not used by this test (it has no such case)") + end + return nothing +end + +""" + test_threads() + +The number of threads of the checks that run parallel routines in a child Julia (`--threads`, default 4). +""" +test_threads() = something(_test_option(:threads), 4) diff --git a/test/syrk/recsyrk.jl b/test/syrk/recsyrk.jl deleted file mode 100644 index 854ffda0..00000000 --- a/test/syrk/recsyrk.jl +++ /dev/null @@ -1,126 +0,0 @@ -# Recursive blocked SYRK over dense matrices. -# -# recsyrk! writes the lower triangle only, and the recursion's off-diagonal -# GEMM fills C21 while the diagonal blocks recurse -- so the comparison is -# against tril(alpha*A*A' + beta*C). -# -# The Float16 path of _syrk_dispatch! routes to gemmEx!, which now has a CPU -# method: the accumulation happens in the compute type and is rounded back to -# Float16 on store, so the tolerance below is the storage's, not the sum's. - -@testset "RECSYRK [CPU]" begin - # syrk is A*transpose(A), not A*adjoint(A), so complex is a real case here - # and BLAS.syrk! has methods for it. - @testset "$T" for T in (Float32, Float64, ComplexF32, ComplexF64) - # ComplexF32 is single precision too -- `T === Float32` missed that and - # held the complex single case to a double-precision tolerance. - rtol = T <: Union{Float32, ComplexF32} ? 1e-4 : 1e-10 - - @testset "dense n=$n k=$k threshold=$th" for - n in [32, 64, 128], - k in [16, 64], - th in [16, 64, 256] - - A0 = rand(T, n, k) - C0 = rand(T, n, n) - alpha = T(1.5) - beta = T(0.5) - - C = copy(C0) - NextLA.recsyrk!(alpha, A0, beta, C, th) - - expected = alpha * (A0 * transpose(A0)) + beta * C0 - @test norm(tril(C) - tril(expected)) / norm(tril(expected)) < rtol - end - end - - # threshold >= n takes the base case directly, without ever recursing - @testset "base case only" begin - n = 32 - A0 = rand(Float64, n, 8); C0 = rand(Float64, n, n) - C = copy(C0) - NextLA.recsyrk!(1.0, A0, 0.0, C, 4096) - @test norm(tril(C) - tril(A0 * transpose(A0))) / norm(A0 * transpose(A0)) < 1e-10 - end - - # This used to assert an ArgumentError: gemmEx! had no CPU method, so a - # Float16 container could not be updated on the host at all. It now - # computes, and the reference is taken in double precision so that a wrong - # accumulation order cannot hide inside Float16 rounding. - @testset "Float16" begin - n = 32 - A0 = rand(Float16, n, 8) - C0 = rand(Float16, n, n) - C = copy(C0) - NextLA.recsyrk!(Float16(1), A0, Float16(0), C, 4096) - expected = Float64.(A0) * transpose(Float64.(A0)) - @test norm(tril(Float64.(C)) - tril(expected)) / norm(tril(expected)) < 5e-3 - end -end - -# A and C of different types are computed in C's type: A widened exactly into a -# wider C, rounded once into a narrower one, and C itself never rounded. The -# Float32 fallback this replaced rounded a Float64 C to Float32 (single-precision -# accuracy) and threw InexactError on mismatched complex types. -@testset "RECSYRK A and C of different types [$backend_name]" for (backend_name, ArrayType, synchronize) in - filter(b -> b[1] in ("CPU", "CUDA", "AMDGPU"), available_backends()) - @testset "$TA -> $TC" for (TA, TC, rtol) in ((Float32, Float64, 1e-12), - (Float16, Float64, 1e-12), - (Float64, Float32, 1e-5), - (ComplexF32, ComplexF64, 1e-12), - (ComplexF64, ComplexF32, 1e-5)) - n, k = 96, 40 - A, C0 = rand(TA, n, k), rand(TC, n, n) - C = ArrayType(copy(C0)) - NextLA.recsyrk!(TC(2), ArrayType(A), TC(3), C, 32) - synchronize(C) - expected = 2 .* (TC.(A) * transpose(TC.(A))) .+ 3 .* C0 - @test norm(tril(Array(C)) - tril(expected)) / norm(tril(expected)) < rtol - end -end - -@testset "RECSYRK uplo [CPU]" begin - @testset "uplo='U', $T n=$n threshold=$th" for T in (Float32, Float64), n in (32, 50, 64), th in (16, 256) - A0, C0 = rand(T, n, 12), rand(T, n, n) - C = copy(C0) - NextLA.recsyrk!(T(1.5), A0, T(0.5), C, th; uplo='U') - expected = T(1.5) * (A0 * transpose(A0)) + T(0.5) * C0 - @test norm(triu(C) - triu(expected)) / norm(triu(expected)) < (T === Float32 ? 1e-4 : 1e-10) - @test tril(C, -1) == tril(C0, -1) - end - @testset "uplo='L' leaves the upper triangle" begin - A0, C0 = rand(40, 8), rand(40, 40) - C = copy(C0) - NextLA.recsyrk!(1.0, A0, 1.0, C, 16) - @test triu(C, 1) == triu(C0, 1) - end - @testset "an unknown uplo throws" begin - @test_throws ArgumentError NextLA.recsyrk!(1.0, rand(8, 2), 1.0, rand(8, 8); uplo='X') - end - # The half-precision leaf is a GEMM; it must still leave the other triangle alone. - @testset "Float16 leaves the other triangle, uplo=$uplo" for uplo in ('L', 'U') - A0, C0 = rand(Float16, 32, 8), rand(Float16, 32, 32) - C = copy(C0) - NextLA.recsyrk!(1, A0, 1, C, 16; uplo=uplo) - if uplo == 'L' - @test triu(C, 1) == triu(C0, 1) - else - @test tril(C, -1) == tril(C0, -1) - end - end -end - -# Float16 storage on the GPU: gemmEx! with Float32 accumulation on CUDA and -# AMDGPU, gemm! on oneAPI, which has no gemmEx! (ext/oneapi/syrk.jl). -@testset "RECSYRK Float16 on the GPU [$backend_name]" for (backend_name, ArrayType, synchronize) in - filter(b -> b[1] in ("CUDA", "AMDGPU", "oneAPI"), available_backends()) - @testset "C $TC" for TC in (Float16, Float32) - n, k = 64, 16 - A0, C0 = rand(Float16, n, k), rand(TC, n, n) - C = ArrayType(copy(C0)) - NextLA.recsyrk!(1, ArrayType(A0), 1, C, 16) - synchronize(C) - expected = Float64.(A0) * transpose(Float64.(A0)) .+ Float64.(C0) - @test norm(tril(Float64.(Array(C))) - tril(expected)) / norm(tril(expected)) < 5e-3 - end -end diff --git a/test/syrk/syrk.jl b/test/syrk/syrk.jl deleted file mode 100644 index 925dc056..00000000 --- a/test/syrk/syrk.jl +++ /dev/null @@ -1,148 +0,0 @@ -# syrk! and syrk_batched!. -# -# Source: origin/pr/19, by Alessandro . Adapted from that -# branch's own `backends` / `_to_backend` locals to this repo's -# available_backends(), and extended with the untouched-triangle and -# dispatch-path assertions below. -# -# The point of SYRK over GEMM is that it writes one triangle. Checking only the -# written half, as the branch test did, cannot tell a correct SYRK from a GEMM -# that happens to agree there -- so the other triangle is asserted unchanged. - -function _syrk_expected(trans::Char, alpha, A, beta, C) - prod = trans == 'N' ? A * transpose(A) : transpose(A) * A - return alpha * prod + beta * C -end - -function _triangle_matches(uplo::Char, got::AbstractMatrix, expected::AbstractMatrix) - n = size(got, 1) - if uplo == 'U' - for j in 1:n, i in 1:j - @inbounds isapprox(got[i, j], expected[i, j]) || return false - end - else - for j in 1:n, i in j:n - @inbounds isapprox(got[i, j], expected[i, j]) || return false - end - end - return true -end - -# the half syrk! must not write: strictly outside the `uplo` triangle -function _other_triangle_untouched(uplo::Char, got::AbstractMatrix, before::AbstractMatrix) - n = size(got, 1) - if uplo == 'U' - for j in 1:n, i in (j + 1):n - @inbounds got[i, j] == before[i, j] || return false - end - else - for j in 1:n, i in 1:(j - 1) - @inbounds got[i, j] == before[i, j] || return false - end - end - return true -end - -@testset "SYRK" begin - A_single = Float32[1 2 3; 4 5 6] - C_single = Float32[2 1; 3 4] - - A_batch = [Float32[1 2 0; 3 4 1], Float32[2 1 3; 0 1 2]] - C_batch = [Float32[1 0; 0 1], Float32[2 1; 1 2]] - A_batch3 = cat(A_batch..., dims = 3) - C_batch3 = cat(C_batch..., dims = 3) - - alpha = Float32(1.5) - beta = Float32(0.25) - - for (name, AT, sync) in backends - # Metal's non-MPS path falls through to mul!, which writes the whole - # square; and it has no SYRK at all. Recorded in KNOWN_ISSUES.md. - metal = name == "Metal" - - @testset "[$name] uplo=$uplo trans=$trans" for uplo in ('L', 'U'), trans in ('N', 'T') - A = trans == 'N' ? A_single : permutedims(A_single) - C = C_single - expected = _syrk_expected(trans, alpha, A, beta, C) - - Ad = _to_backend(AT, copy(A)) - Cd = _to_backend(AT, copy(C)) - NextLA.syrk!(uplo, trans, alpha, Ad, beta, Cd) - sync(Cd) - - got = Array(Cd) - @test _triangle_matches(uplo, got, expected) - if metal - @test_broken _other_triangle_untouched(uplo, got, C) - else - @test _other_triangle_untouched(uplo, got, C) - end - end - - @testset "[$name] strided views" begin - Ap = Float32[9 8 7 6; 1 2 3 4; 5 6 7 8; 2 3 4 5] - Cp = Float32[5 4 3; 2 1 0; 7 6 5] - expected = _syrk_expected('N', alpha, Ap[2:3, 2:4], beta, Cp[2:3, 2:3]) - - Ad = _to_backend(AT, copy(Ap)) - Cd = _to_backend(AT, copy(Cp)) - NextLA.syrk!('L', 'N', alpha, @view(Ad[2:3, 2:4]), beta, @view(Cd[2:3, 2:3])) - sync(Cd) - @test _triangle_matches('L', Array(Cd)[2:3, 2:3], expected) - end - - # A missing ext file would silently fall back to CPU BLAS on a device - # array and still pass every numeric check above. - @testset "[$name] dispatches to its own backend" begin - Ad = _to_backend(AT, copy(A_single)) - Cd = _to_backend(AT, copy(C_single)) - @test endswith(_method_file(NextLA.syrk!, 'L', 'N', alpha, Ad, beta, Cd), - _expected_syrk_file(name)) - end - - @testset "[$name] batched" begin - expected = [_syrk_expected('N', alpha, A_batch[i], beta, C_batch[i]) - for i in eachindex(A_batch)] - expected3 = cat(expected..., dims = 3) - - # AMDGPU is the only backend with a native batched SYRK in both - # layouts; everywhere else warns before falling back. - warns_pointer = name != "AMDGPU" - warns_strided = !(name in ("AMDGPU", "oneAPI")) - - Ad = _to_backend(AT, deepcopy(A_batch)) - Cd = _to_backend(AT, deepcopy(C_batch)) - if warns_pointer - @test_logs (:warn,) match_mode = :any NextLA.syrk_batched!( - 'L', 'N', alpha, Ad, beta, Cd) - else - NextLA.syrk_batched!('L', 'N', alpha, Ad, beta, Cd) - end - sync(first(Cd)) - for i in eachindex(expected) - @test _triangle_matches('L', Array(Cd[i]), expected[i]) - end - - Ad3 = _to_backend(AT, copy(A_batch3)) - Cd3 = _to_backend(AT, copy(C_batch3)) - if warns_strided - @test_logs (:warn,) match_mode = :any NextLA.syrk_batched!( - 'L', 'N', alpha, Ad3, beta, Cd3) - else - NextLA.syrk_batched!('L', 'N', alpha, Ad3, beta, Cd3) - end - sync(Cd3) - for i in axes(expected3, 3) - @test _triangle_matches('L', Array(@view(Cd3[:, :, i])), @view(expected3[:, :, i])) - end - end - - @testset "[$name] rejects bad arguments" begin - Ad = _to_backend(AT, copy(A_single)) - Cd = _to_backend(AT, copy(C_single)) - @test_throws ArgumentError NextLA.syrk!('X', 'N', alpha, Ad, beta, Cd) - Cbad = _to_backend(AT, rand(Float32, 3, 2)) - @test_throws DimensionMismatch NextLA.syrk!('L', 'N', alpha, Ad, beta, Cbad) - end - end -end diff --git a/test/syrk/syrk_kernel.jl b/test/syrk/syrk_kernel.jl deleted file mode 100644 index 6c4575aa..00000000 --- a/test/syrk/syrk_kernel.jl +++ /dev/null @@ -1,58 +0,0 @@ -# SYRK_KERNEL!, the KernelAbstractions symmetric rank-k update. -# -# Vicki's own test/syrk/syrk.jl is not usable here: it hardcodes CuArray, pulls in -# an include("benchmark.jl") that is not on the branch, and runs to n=1024 with -# printing per case. This one covers the same ground over available_backends(). -# -# CPU coverage is the point of the exercise. The kernel as it stood on the -# branch could not run there at all -- I and J were assigned before a -# @synchronize and read after it, and N and M were computed inside the body. A -# CUDA-only green run would have hidden every one of those. See KNOWN_ISSUES.md. - -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "SYRK_KERNEL [$backend_name]" begin - @testset "$T" for T in (Float32, Float64) - rtol = test_rtol(T) - - @testset "uplo=$uplo trans=$trans n=$n k=$k" for - uplo in ('L', 'U'), - trans in ('N', 'T'), - n in [16, 32, 64, 50], - k in [1, 8, 40] - - A0 = trans == 'N' ? rand(T, n, k) : rand(T, k, n) - C0 = rand(T, n, n) - alpha = T(1.5) - beta = T(0.5) - - Ad = ArrayType(copy(A0)) - Cd = ArrayType(copy(C0)) - NextLA.SYRK_KERNEL!(uplo, trans, alpha, Ad, beta, Cd) - synchronize(Cd) - - got = Array(Cd) - prod = trans == 'N' ? A0 * transpose(A0) : transpose(A0) * A0 - expected = alpha * prod + beta * C0 - - keep = uplo == 'L' ? tril : triu - @test norm(keep(got) - keep(expected)) / max(norm(keep(expected)), eps(T)) < rtol - - # the other triangle must be byte-identical: that is what makes - # this a SYRK rather than a GEMM - drop = uplo == 'L' ? triu : tril - @test drop(got, uplo == 'L' ? 1 : -1) == drop(C0, uplo == 'L' ? 1 : -1) - end - end - - @testset "rejects bad arguments" begin - A = ArrayType(rand(Float32, 8, 4)) - C = ArrayType(rand(Float32, 8, 8)) - @test_throws ArgumentError NextLA.SYRK_KERNEL!('X', 'N', 1f0, A, 0f0, C) - @test_throws ArgumentError NextLA.SYRK_KERNEL!('L', 'X', 1f0, A, 0f0, C) - @test_throws DimensionMismatch NextLA.SYRK_KERNEL!('L', 'N', 1f0, A, 0f0, - ArrayType(rand(Float32, 8, 4))) - @test_throws DimensionMismatch NextLA.SYRK_KERNEL!('L', 'N', 1f0, A, 0f0, - ArrayType(rand(Float32, 4, 4))) - end - end -end diff --git a/test/trsm.jl b/test/trsm.jl deleted file mode 100644 index 9be89e1f..00000000 --- a/test/trsm.jl +++ /dev/null @@ -1,67 +0,0 @@ -@testset "TRSM GPU kernels" begin - backends = available_gpu_backends() - if isempty(backends) - @test_skip "No GPU backends available" - end - for (backend_name, ArrayType, synchronize) in backends - @testset "[$backend_name]" begin - tol = 1e-5 - - @testset "LeftLowerTRSM! n=$n, m=$m" for n in [16, 32, 128, 256], - m in [1, 8, 64] - A = Matrix(LowerTriangular(rand(Float32, n, n) .+ 1)) .+ Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, m) .+ 1 - Ac, Bc = copy(A), copy(B) - A_gpu = ArrayType(A) - B_gpu = ArrayType(B) - - LeftLowerTRSM!(A_gpu, B_gpu) - synchronize(B_gpu) - LinearAlgebra.BLAS.trsm!('L', 'L', 'N', 'N', 1f0, Ac, Bc) - @test norm(Array(B_gpu) - Bc) / norm(Bc) < tol - end - - @testset "LeftUpperTRSM! n=$n, m=$m" for n in [16, 32, 128, 256], - m in [1, 8, 64] - A = Matrix(UpperTriangular(rand(Float32, n, n) .+ 1)) .+ Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, n, m) .+ 1 - Ac, Bc = copy(A), copy(B) - A_gpu = ArrayType(A) - B_gpu = ArrayType(B) - - LeftUpperTRSM!(A_gpu, B_gpu) - synchronize(B_gpu) - LinearAlgebra.BLAS.trsm!('L', 'U', 'N', 'N', 1f0, Ac, Bc) - @test norm(Array(B_gpu) - Bc) / norm(Bc) < tol - end - - @testset "RightLowerTRSM! n=$n, m=$m" for n in [16, 32, 128, 256], - m in [1, 8, 64] - A = Matrix(LowerTriangular(rand(Float32, n, n) .+ 1)) .+ Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, m, n) .+ 1 - Ac, Bc = copy(A), copy(B) - A_gpu = ArrayType(A) - B_gpu = ArrayType(B) - - RightLowerTRSM!(A_gpu, B_gpu) - synchronize(B_gpu) - LinearAlgebra.BLAS.trsm!('R', 'L', 'N', 'N', 1f0, Ac, Bc) - @test norm(Array(B_gpu) - Bc) / norm(Bc) < tol - end - - @testset "RightUpperTRSM! n=$n, m=$m" for n in [16, 32, 128, 256], - m in [1, 8, 64] - A = Matrix(UpperTriangular(rand(Float32, n, n) .+ 1)) .+ Diagonal(10f0 * ones(Float32, n)) - B = rand(Float32, m, n) .+ 1 - Ac, Bc = copy(A), copy(B) - A_gpu = ArrayType(A) - B_gpu = ArrayType(B) - - RightUpperTRSM!(A_gpu, B_gpu) - synchronize(B_gpu) - LinearAlgebra.BLAS.trsm!('R', 'U', 'N', 'N', 1f0, Ac, Bc) - @test norm(Array(B_gpu) - Bc) / norm(Bc) < tol - end - end - end -end diff --git a/test/trsm/trsm_batched.jl b/test/trsm/trsm_batched.jl deleted file mode 100644 index 53d68686..00000000 --- a/test/trsm/trsm_batched.jl +++ /dev/null @@ -1,63 +0,0 @@ -using LinearAlgebra -using Random -using Test - -function _trsm_batched_inputs(::Type{T}, n::Int, nrhs::Int, batch::Int) where {T} - rng = MersenneTwister(41) - A = Array{T}(undef, n, n, batch) - B = rand(rng, T, n, nrhs, batch) - for bid in 1:batch - tile = Matrix(UpperTriangular(rand(rng, T, n, n))) - tile .+= Diagonal(fill(T(4), n)) - A[:, :, bid] = tile - end - return A, B -end - -function _trsm_batched_reference!(A, B) - for bid in axes(B, 3) - BLAS.trsm!('L', 'U', 'N', 'N', one(eltype(B)), - view(A, :, :, bid), view(B, :, :, bid)) - end - return B -end - -@testset "batched TRSM wrappers" begin - A, B = _trsm_batched_inputs(Float32, 16, 4, 3) - expected = _trsm_batched_reference!(copy(A), copy(B)) - - for (name, AT, sync) in backends - @testset "$name strided batch" begin - Adev = _to_backend(AT, copy(A)) - Bdev = _to_backend(AT, copy(B)) - @test occursin(_expected_trsm_batched_file(name), - _method_file(NextLA.trsm_batched!, - 'L', 'U', 'N', 'N', Adev, Bdev)) - if name == "Metal" - @test_throws ArgumentError NextLA.trsm_batched!('L', - 'U', 'N', 'N', Adev, Bdev) - else - NextLA.trsm_batched!('L', 'U', 'N', 'N', Adev, Bdev) - sync(Bdev) - @test Array(Bdev) ≈ expected rtol=2f-5 - end - end - - @testset "$name pointer batch" begin - Abatch = [copy(view(A, :, :, bid)) for bid in axes(A, 3)] - Bbatch = [copy(view(B, :, :, bid)) for bid in axes(B, 3)] - Adev = _to_backend(AT, Abatch) - Bdev = _to_backend(AT, Bbatch) - if name == "Metal" - @test_throws ArgumentError NextLA.trsm_batched!('L', - 'U', 'N', 'N', Adev, Bdev) - else - NextLA.trsm_batched!('L', 'U', 'N', 'N', Adev, Bdev) - sync(first(Bdev)) - for bid in eachindex(Bdev) - @test Array(Bdev[bid]) ≈ view(expected, :, :, bid) rtol=2f-5 - end - end - end - end -end diff --git a/test/trsm/unified_rectrxm.jl b/test/trsm/unified_rectrxm.jl deleted file mode 100644 index 366ba8d3..00000000 --- a/test/trsm/unified_rectrxm.jl +++ /dev/null @@ -1,404 +0,0 @@ -@testset "unified_rectrxm! GPU" begin - backends = available_gpu_backends() - if isempty(backends) - @test_skip "No GPU backends available" - end - for (backend_name, ArrayType, synchronize) in backends - @testset "[$backend_name]" begin - tol = 1e-14 - - @testset "func=$func side=$side uplo=$uplo trans=$trans n=$n m=$m" for - n in [16, 32, 128, 256], - m in [1, 8, 64], - side in ['L', 'R'], - uplo in ['L', 'U'], - trans in ['N', 'T', 'C'], - func in ['S', 'M'] - - alpha = 1.0 - - A = if uplo == 'L' - Matrix(LowerTriangular(rand(n, n) .+ 1)) - else - Matrix(UpperTriangular(rand(n, n) .+ 1)) - end - A += Diagonal(10 * ones(n)) - - B = side == 'L' ? rand(n, m) .+ 1 : rand(m, n) .+ 1 - - Ac, Bc = copy(A), copy(B) - A_gpu = ArrayType(A) - B_gpu = ArrayType(B) - - unified_rectrxm!(side, uplo, trans, alpha, func, A_gpu, B_gpu) - synchronize(B_gpu) - - if func == 'S' - LinearAlgebra.BLAS.trsm!(side, uplo, trans, 'N', alpha, Ac, Bc) - else - LinearAlgebra.BLAS.trmm!(side, uplo, trans, 'N', alpha, Ac, Bc) - end - - rel_err = norm(Array(B_gpu) - Bc) / norm(Bc) - @test rel_err < tol - end - end - end -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, -# oneAPI and Metal use — would be exercised by nothing at all. -@testset "unified_rectrxm! CPU (recursive KA path)" begin - tol = 1e-12 - - @testset "func=$func side=$side uplo=$uplo trans=$trans n=$n m=$m" for - n in [16, 32, 128, 256], - m in [1, 8, 64], - side in ['L', 'R'], - uplo in ['L', 'U'], - trans in ['N', 'T', 'C'], - func in ['S', 'M'] - - alpha = 1.0 - - A = if uplo == 'L' - Matrix(LowerTriangular(rand(n, n) .+ 1)) - else - Matrix(UpperTriangular(rand(n, n) .+ 1)) - end - A += Diagonal(10 * ones(n)) - - B = side == 'L' ? rand(n, m) .+ 1 : rand(m, n) .+ 1 - - Ac, Bc = copy(A), copy(B) - A_cpu, B_cpu = copy(A), copy(B) - - unified_rectrxm!(side, uplo, trans, alpha, func, A_cpu, B_cpu) - - if func == 'S' - LinearAlgebra.BLAS.trsm!(side, uplo, trans, 'N', alpha, Ac, Bc) - else - LinearAlgebra.BLAS.trmm!(side, uplo, trans, 'N', alpha, Ac, Bc) - end - - @test norm(B_cpu - Bc) / norm(Bc) < tol - end -end - -# A silently non-dispatching extension looks exactly like a passing suite -- -# that is how the oneAPI extension went unnoticed. Assert where each call lands. -@testset "unified_rectrxm! dispatch" begin - _slashes(p) = replace(p, "\\" => "/") - n = 8 - A = Matrix(LowerTriangular(rand(n, n) .+ 1)) + Diagonal(10 * ones(n)) - B = rand(n, 2) .+ 1 - # 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") - @test endswith(_slashes(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', 1.0, 'S', A, B)), - "src/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") - for (name, AT, _) in available_gpu_backends() - haskey(fast, name) || continue - Ag, Bg = AT(A), AT(B) - @test endswith(_slashes(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', 1.0, 'S', Ag, Bg)), - fast[name]) - end -end - -# diag='U' treats the stored diagonal as all ones without reading it, the BLAS -# convention. The seven-argument form delegates here with 'N', so the sweeps -# above already cover that half. -# -# The CPU kernels and the vendor extensions (CUDA, AMDGPU) implement this -# independently -- the kernels skip the diagonal read, the vendor library is -# told 'U' -- so the last testset checks they agree. Each passing alone would not catch the extension quietly -# ignoring the flag. -@testset "unified_rectrxm! unit diagonal" begin - tol = 1e-12 - - @testset "func=$func side=$side uplo=$uplo trans=$trans diag=$dg" for - func in ['S', 'M'], - side in ['L', 'R'], - uplo in ['L', 'U'], - trans in ['N', 'T'], - dg in ['N', 'U'] - - n, m = 32, 8 - A = uplo == 'L' ? Matrix(LowerTriangular(rand(n, n) .+ 1)) : - Matrix(UpperTriangular(rand(n, n) .+ 1)) - A += Diagonal(10 * ones(n)) - B = side == 'L' ? rand(n, m) .+ 1 : rand(m, n) .+ 1 - - ref = copy(B) - if func == 'S' - LinearAlgebra.BLAS.trsm!(side, uplo, trans, dg, 1.0, A, ref) - else - LinearAlgebra.BLAS.trmm!(side, uplo, trans, dg, 1.0, A, ref) - end - - B_cpu = copy(B) - unified_rectrxm!(side, uplo, trans, dg, 1.0, func, copy(A), B_cpu) - @test norm(B_cpu - ref) / norm(ref) < tol - - for (name, AT, sync) in available_gpu_backends() - name in ("CUDA", "AMDGPU") || continue - Ag, Bg = AT(copy(A)), AT(copy(B)) - unified_rectrxm!(side, uplo, trans, dg, 1.0, func, Ag, Bg) - sync(Bg) - @test norm(Array(Bg) - ref) / norm(ref) < tol - # the point of the testset: both paths, same answer - @test Array(Bg) ≈ B_cpu rtol=1e-10 - end - end - - # A Float16 base case accumulates in Float32 and rounds once on store. The - # test is not a tolerance: it is that the answer equals the one obtained by - # doing the whole solve in Float32 and rounding at the end, which is what - # the promotion claims to deliver. A kernel accumulating in Float16 misses - # it by more than an order of magnitude at n = 128. - @testset "Float16 accumulates wider than it stores" begin - for n in (16, 64, 128), (side, uplo, func) in - [('L', 'L', 'S'), ('L', 'U', 'S'), ('R', 'L', 'M')] - A0 = Matrix(LowerTriangular(rand(Float64, n, n) .+ 1.0)) - uplo == 'U' && (A0 = Matrix(UpperTriangular(rand(Float64, n, n) .+ 1.0))) - B0 = rand(Float64, n, n) - A16, B16 = Float16.(A0), Float16.(B0) - - got = copy(B16) - unified_rectrxm!(side, uplo, 'N', 'N', Float16(1), func, copy(A16), got) - - # The same operation carried out in Float32 and rounded once at the - # end. They agree exactly only where the call is a single base case: - # above the threshold the recursion's GEMM updates round to Float16 - # at every step, so the promotion buys accuracy within a block and - # not across the recursion. That is the branch's bargain too -- - # dispatch_trsm! wrapped the base-case call and nothing above it. - want32 = Float32.(B16) - unified_rectrxm!(side, uplo, 'N', 'N', Float32(1), func, - Float32.(A16), want32) - if n <= (func == 'S' ? 256 : 16) - @test got == Float16.(want32) - end - - # and it is genuinely better than accumulating in Float16: compare - # both against the exact solve of the rounded inputs - exact = func == 'S' ? - (side == 'L' ? Float64.(A16) \ Float64.(B16) : - Float64.(B16) / Float64.(A16)) : - (side == 'L' ? Float64.(A16) * Float64.(B16) : - Float64.(B16) * Float64.(A16)) - @test norm(Float64.(got) - exact) / norm(exact) < 1e-3 - end - end - - @testset "rejects a bad diag" begin - A = Matrix(LowerTriangular(rand(8, 8) .+ 1)) + Diagonal(10 * ones(8)) - B = rand(8, 2) - @test_throws ArgumentError unified_rectrxm!('L', 'L', 'N', 'X', 1.0, 'S', A, B) - end -end - -# trsm!/trmm! are the BLAS-order entry points over unified_rectrxm!. They are -# checked on every backend against LinearAlgebra.BLAS, over the whole flag -# space and all four BLAS element types, with alpha != 1 so the scaling is -# exercised. -# On CUDA and AMDGPU the answer must also come from the vendor fast path: a -# wrapper that quietly fell back to the portable kernels would still pass the -# numerical checks. -@testset "trsm! / trmm!" begin - _slashes(p) = replace(p, "\\" => "/") - @test :trsm! in names(NextLA) && :trmm! in names(NextLA) - @test :unified_rectrxm! in names(NextLA) - @test NextLA.trsm! !== LinearAlgebra.BLAS.trsm! - @test NextLA.trmm! !== LinearAlgebra.BLAS.trmm! - - fast = Dict("CUDA" => "ext/cuda/rectrxm.jl", "AMDGPU" => "ext/amdgpu/rectrxm.jl") - targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] - for (name, AT, sync) in targets - @testset "[$name] $fn T=$T side=$side uplo=$uplo trans=$trans diag=$dg" for - T in (Float32, Float64, ComplexF32, ComplexF64), - fn in (trsm!, trmm!), - side in ('L', 'R'), - uplo in ('L', 'U'), - trans in ('N', 'T', 'C'), - dg in ('N', 'U') - - n, m = 48, 5 - # small off-diagonal part: well conditioned with or without the - # stored diagonal, so Float32 can be held to a tight tolerance - L = T(0.1) .* rand(T, n, n) - A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + - Diagonal(fill(T(2), n)) - B = side == 'L' ? rand(T, n, m) .+ 1 : rand(T, m, n) .+ 1 - alpha = T(1.5) - - ref = copy(B) - blas = fn === trsm! ? LinearAlgebra.BLAS.trsm! : LinearAlgebra.BLAS.trmm! - blas(side, uplo, trans, dg, alpha, A, ref) - - Ag, Bg = AT(A), AT(B) - out = fn(side, uplo, trans, dg, alpha, Ag, Bg) - sync(Bg) - @test out === Bg # in place, like BLAS - tol = real(T) === Float32 ? 1e-5 : 1e-12 - @test norm(Array(Bg) - ref) / norm(ref) < tol - end - - if haskey(fast, name) - @testset "[$name] reaches the vendor library" begin - for T in (Float32, Float64, ComplexF32, ComplexF64) - Ag = AT(Matrix(LowerTriangular(rand(T, 8, 8))) + Diagonal(fill(T(2), 8))) - Bg = AT(rand(T, 8, 3)) - # the wrapper is generic; what it calls is the extension method - @test endswith(_slashes(_method_file(unified_rectrxm!, 'L', 'L', 'N', 'N', - T(1), 'S', Ag, Bg)), fast[name]) - end - end - end - end -end - -# A transposed Float16 operand reaches the base case as a view of a Transpose -# once the recursion splits it (TRMM above n = 16, TRSM above 256), or at once -# when the caller passes a view. The base case widens it to Float32; done -# directly, that broadcast has no GPU method and falls back to scalar indexing. -# Checked on every backend, both sides of both thresholds, whole arrays and -# offset views, against the Float64 answer for the rounded inputs. -@testset "Float16 with transposes and views" begin - targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] - for (name, AT, sync) in targets - @testset "[$name] $fn n=$n side=$side uplo=$uplo trans=$trans view=$useview" for - fn in (trsm!, trmm!), - n in (17, 300), - side in ('L', 'R'), - uplo in ('L', 'U'), - trans in ('N', 'T', 'C'), - useview in (false, true) - - m = 5 - L = rand(n, n) ./ n - A = Float16.((uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + - Diagonal(fill(2.0, n))) - B = Float16.(side == 'L' ? rand(n, m) .+ 1 : rand(m, n) .+ 1) - - ref = Float64.(B) - blas = fn === trsm! ? LinearAlgebra.BLAS.trsm! : LinearAlgebra.BLAS.trmm! - blas(side, uplo, trans, 'N', 1.0, Float64.(A), ref) - - if useview - # offset blocks of larger arrays, so neither operand is a whole array - Abig = AT(zeros(Float16, n + 3, n + 2)) - Bbig = AT(zeros(Float16, size(B, 1) + 2, size(B, 2) + 2)) - Ag = view(Abig, 3:n+2, 2:n+1) - Bg = view(Bbig, 2:size(B, 1)+1, 2:size(B, 2)+1) - copyto!(Ag, AT(A)); copyto!(Bg, AT(B)) - else - Ag, Bg = AT(A), AT(B) - end - fn(side, uplo, trans, 'N', Float16(1), Ag, Bg) - sync(Bg) - @test norm(Float64.(Array(Bg)) - ref) / norm(ref) < 1e-2 - end - end -end - -# Complex. trsm!/trmm! above cover ComplexF32/ComplexF64 at n = 48 through each -# backend's own route; this goes past the TRSM threshold (n = 300) so the -# recursion's GEMM updates run in complex arithmetic, on whole arrays and on -# offset views, and on a GPU it also forces the portable method with invoke -- -# the path AMD views and every backend without a vendor BLAS take. 'C' is the -# case that differs from 'T' only for complex. -@testset "complex: recursion, views and the portable path" begin - GEN = Tuple{Char,Char,Char,Char,Number,Char,AbstractMatrix,AbstractMatrix} - targets = [("CPU", Array, _ -> nothing, (false,)); - [(nm, AT, sy, (false, true)) for (nm, AT, sy) in available_gpu_backends()]] - for (name, AT, sync, portables) in targets - @testset "[$name] portable=$portable $T $fn side=$side uplo=$uplo trans=$trans view=$useview" for - portable in portables, - T in (ComplexF32, ComplexF64), - fn in (trsm!, trmm!), - side in ('L', 'R'), - uplo in ('L', 'U'), - trans in ('N', 'T', 'C'), - useview in (false, true) - - n, m = 300, 5 - L = rand(T, n, n) ./ n - A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + - Diagonal(fill(T(2), n)) - B = side == 'L' ? rand(T, n, m) : rand(T, m, n) - alpha = T(1.5 - 0.5im) - - ref = copy(B) - blas = fn === trsm! ? LinearAlgebra.BLAS.trsm! : LinearAlgebra.BLAS.trmm! - blas(side, uplo, trans, 'N', alpha, A, ref) - - if useview - Abig = AT(zeros(T, n + 3, n + 2)) - Bbig = AT(zeros(T, size(B, 1) + 2, size(B, 2) + 2)) - Ag = view(Abig, 3:n+2, 2:n+1) - Bg = view(Bbig, 2:size(B, 1)+1, 2:size(B, 2)+1) - copyto!(Ag, AT(A)); copyto!(Bg, AT(B)) - else - Ag, Bg = AT(A), AT(B) - end - if portable - invoke(unified_rectrxm!, GEN, side, uplo, trans, 'N', alpha, - fn === trsm! ? 'S' : 'M', Ag, Bg) - else - fn(side, uplo, trans, 'N', alpha, Ag, Bg) - end - sync(Bg) - tol = real(T) === Float32 ? 1e-4 : 1e-10 - @test norm(Array(Bg) - ref) / norm(ref) < tol - end - end -end - -# trmm! with a separate output: C gets alpha * op(A) * B (or B * op(A)) and B is -# left alone; C = B is the in-place form. Checked on every backend against -# LinearAlgebra.BLAS.trmm! over side, uplo and transa, real and complex. -@testset "trmm! with a separate output" begin - targets = [("CPU", Array, _ -> nothing); available_gpu_backends()] - for (name, AT, sync) in targets - @testset "[$name] $T side=$side uplo=$uplo trans=$trans" for - T in (Float32, Float64, ComplexF32, ComplexF64), - side in ('L', 'R'), - uplo in ('L', 'U'), - trans in ('N', 'T', 'C') - - n, m = 24, 5 - L = T(0.1) .* rand(T, n, n) - A = (uplo == 'L' ? Matrix(LowerTriangular(L)) : Matrix(UpperTriangular(L))) + - Diagonal(fill(T(2), n)) - B = side == 'L' ? rand(T, n, m) : rand(T, m, n) - alpha = T(1.5) - ref = copy(B) - LinearAlgebra.BLAS.trmm!(side, uplo, trans, 'N', alpha, A, ref) - - Ag, Bg = AT(A), AT(B) - Cg = AT(zeros(T, size(B))) - out = trmm!(side, uplo, trans, 'N', alpha, Ag, Bg, Cg) - sync(Cg) - tol = real(T) === Float32 ? 1e-5 : 1e-12 - @test out === Cg - @test norm(Array(Cg) - ref) / norm(ref) < tol - @test Array(Bg) == B # B untouched - - Bi = AT(B) # C = B: the in-place form - trmm!(side, uplo, trans, 'N', alpha, Ag, Bi, Bi) - sync(Bi) - @test norm(Array(Bi) - ref) / norm(ref) < tol - end - end - @testset "rejects a C of the wrong size" begin - A = Matrix(LowerTriangular(rand(4, 4))) + 2I - @test_throws DimensionMismatch trmm!('L', 'L', 'N', 'N', 1.0, A, rand(4, 2), zeros(3, 2)) - end -end diff --git a/test/tsmqr.jl b/test/tsmqr.jl deleted file mode 100644 index aff26936..00000000 --- a/test/tsmqr.jl +++ /dev/null @@ -1,94 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "TSMQR [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "side=$side, trans=$trans" for side in ['L', 'R'], - trans in ['N', 'C'] - if side == 'L' - m1, n1, m2, k, ib = 32, 24, 20, 16, 8 - n2 = n1 - else - m1, n1, n2, k, ib = 24, 32, 20, 16, 8 - m2 = m1 - end - - A1 = rand(T, m1, n1) - A2 = rand(T, m2, n2) - V = side == 'L' ? rand(T, m2, k) : rand(T, n2, k) - Tm = triu(rand(T, ib, k)) - work = ArrayType(zeros(T, side == 'L' ? ib * n1 : ib * m1)) - - A1_orig = copy(A1) - A2_orig = copy(A2) - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - V_n = ArrayType(copy(V)) - Tm_n = ArrayType(copy(Tm)) - NextLA.tsmqr!(side, trans, m1, n1, m2, n2, k, ib, - A1_n, A2_n, V_n, Tm_n, work) - synchronize(A1_n) - - A1_l = copy(A1) - A2_l = copy(A2) - lapack_tpmqrt!(T, side, trans, 0, V, Tm, A1_l, A2_l) - - @test Array(A1_n) ≈ A1_l rtol=rtol - @test Array(A2_n) ≈ A2_l rtol=rtol - @test !isapprox(Array(A1_n), A1_orig; rtol=rtol) || !isapprox(Array(A2_n), A2_orig; rtol=rtol) - end - - @testset "Helper matches kernel (side=$side)" for side in ['L', 'R'] - if side == 'L' - m1, n1, m2, k, ib = 32, 24, 20, 16, 8 - n2 = n1 - else - m1, n1, n2, k, ib = 24, 32, 20, 16, 8 - m2 = m1 - end - - A1 = rand(T, m1, n1) - A2 = rand(T, m2, n2) - V = side == 'L' ? rand(T, m2, k) : rand(T, n2, k) - Tm = triu(rand(T, ib, k)) - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - V_n = ArrayType(copy(V)) - Tm_n = ArrayType(copy(Tm)) - NextLA.tsmqr!(side, 'N', A1_h, A2_h, V_n, Tm_n) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - work = ArrayType(zeros(T, side == 'L' ? ib * n1 : ib * m1)) - NextLA.tsmqr!(side, 'N', m1, n1, m2, n2, k, ib, - A1_k, A2_k, V_n, Tm_n, work) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol - @test A2_h ≈ A2_k rtol=rtol - end - end - - @testset "k=0 is a no-op" begin - A1 = ArrayType(copy(rand(ComplexF64, 8, 8))) - A2 = ArrayType(copy(rand(ComplexF64, 8, 8))) - A1_orig = copy(A1) - A2_orig = copy(A2) - NextLA.tsmqr!('L', 'N', 8, 8, 8, 8, 0, 0, - A1, A2, ArrayType(zeros(ComplexF64, 8, 0)), ArrayType(zeros(ComplexF64, 0, 0)), ArrayType(zeros(ComplexF64, 0))) - synchronize(A1) - @test A1 ≈ A1_orig - @test A2 ≈ A2_orig - end - end -end - -@testset "TSMQR Error handling" begin - @test_throws ArgumentError NextLA.tsmqr!('X', 'N', 8, 8, 8, 8, 4, 2, - zeros(8, 8), zeros(8, 8), zeros(8, 4), zeros(2, 4), zeros(16)) - @test_throws ArgumentError NextLA.tsmqr!('L', 'X', 8, 8, 8, 8, 4, 2, - zeros(8, 8), zeros(8, 8), zeros(8, 4), zeros(2, 4), zeros(16)) -end diff --git a/test/tsqrt.jl b/test/tsqrt.jl deleted file mode 100644 index 8382d765..00000000 --- a/test/tsqrt.jl +++ /dev/null @@ -1,190 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "TSQRT [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "m=$m, n=$n, ib=$ib" for (m, n, ib) in [ - (32, 24, 8), - (48, 32, 16), - (64, 48, 16), - (20, 20, 10), - ] - A1 = triu(rand(T, n, n)) - A2 = rand(T, m, n) - - for i in 1:n - A1[i, i] += 2 * one(T) - end - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm_n = ArrayType(zeros(T, ib, n)) - tau_n = ArrayType(zeros(T, n)) - work_n = ArrayType(zeros(T, ib * n)) - NextLA.tsqrt!(m, n, ib, A1_n, A2_n, Tm_n, tau_n, work_n) - synchronize(A1_n) - - A1_l = copy(A1) - A2_l = copy(A2) - Tm_l = zeros(T, ib, n) - work_l = zeros(T, ib * n) - lapack_tpqrt!(T, m, n, 0, ib, A1_l, n, A2_l, m, Tm_l, ib, work_l) - - @test Array(A1_n) ≈ A1_l rtol=rtol - @test Array(A2_n) ≈ A2_l rtol=rtol - - A1_cpu = Array(A1_n) - for i in 1:n, j in 1:i-1 - @test abs(A1_cpu[i, j]) < rtol * 100 - end - - # R diagonal magnitudes vs LAPACK tpqrt (same check as qr() baseline but independent reference) - for j in 1:n - if abs(A1_l[j, j]) > rtol * 10 - @test abs(abs(A1_cpu[j, j]) - abs(A1_l[j, j])) < - rtol * max(abs(A1_cpu[j, j]), abs(A1_l[j, j])) * 100 - end - end - end - - @testset "Helper matches kernel" begin - m, n, ib = 32, 24, 8 - A1 = triu(rand(T, n, n)) - A2 = rand(T, m, n) - for i in 1:n; A1[i, i] += one(T); end - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - Tm_h = ArrayType(zeros(T, ib, n)) - NextLA.tsqrt!(A1_h, A2_h, Tm_h) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - Tm_k = ArrayType(zeros(T, ib, n)) - tau = ArrayType(zeros(T, n)) - work = ArrayType(zeros(T, ib * n)) - NextLA.tsqrt!(m, n, ib, A1_k, A2_k, Tm_k, tau, work) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol - @test A2_h ≈ A2_k rtol=rtol - end - end - - @testset "Rectangular A1 (m1 ≠ n)" begin - ET = Float64 - rtol_r = test_rtol(ET) - - @testset "Tall A1: m1=$m1, m2=$m2, n=$n, ib=$ib" for (m1, m2, n, ib) in [ - (32, 48, 16, 4), - (64, 32, 32, 8), - ] - k = min(m1, n) - A1 = triu(rand(ET, m1, n)) - A2 = rand(ET, m2, n) - for i in 1:k; A1[i, i] += 2 * one(ET); end - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm_n = ArrayType(zeros(ET, ib, k)) - tau_n = ArrayType(zeros(ET, k)) - work_n = ArrayType(zeros(ET, ib * n)) - NextLA.tsqrt!(m2, n, ib, A1_n, A2_n, Tm_n, tau_n, work_n) - synchronize(A1_n) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - for i in 1:k, j in 1:i-1 - @test abs(A1_cpu[i, j]) < rtol_r * 100 - end - end - - @testset "Wide A1: m1=$m1, m2=$m2, n=$n, ib=$ib" for (m1, m2, n, ib) in [ - (16, 32, 32, 4), - (24, 48, 48, 8), - ] - k = min(m1, n) - A1 = triu(rand(ET, m1, n)) - A2 = rand(ET, m2, n) - for i in 1:k; A1[i, i] += 2 * one(ET); end - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm_n = ArrayType(zeros(ET, ib, k)) - tau_n = ArrayType(zeros(ET, k)) - work_n = ArrayType(zeros(ET, ib * n)) - NextLA.tsqrt!(m2, n, ib, A1_n, A2_n, Tm_n, tau_n, work_n) - synchronize(A1_n) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - for i in 1:k, j in 1:i-1 - @test abs(A1_cpu[i, j]) < rtol_r * 100 - end - end - - @testset "Helper with rectangular A1" begin - m1, n, m2 = 32, 16, 48 - ib = 4 - k = min(m1, n) - A1 = triu(rand(ET, m1, n)) - A2 = rand(ET, m2, n) - for i in 1:k; A1[i, i] += one(ET); end - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - Tm_h = ArrayType(zeros(ET, ib, k)) - NextLA.tsqrt!(A1_h, A2_h, Tm_h) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - Tm_k = ArrayType(zeros(ET, ib, k)) - tau_k = ArrayType(zeros(ET, k)) - work_k = ArrayType(zeros(ET, ib * n)) - NextLA.tsqrt!(m2, n, ib, A1_k, A2_k, Tm_k, tau_k, work_k) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol_r - @test A2_h ≈ A2_k rtol=rtol_r - end - end - - @testset "Block size sweep" begin - T = Float64 - m, n = 48, 32 - for ib in [4, 8, 16, 32] - A1 = triu(rand(T, n, n)) - A2 = rand(T, m, n) - for i in 1:n; A1[i, i] += one(T); end - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm = ArrayType(zeros(T, ib, n)) - tau = ArrayType(zeros(T, n)) - work = ArrayType(zeros(T, ib * n)) - NextLA.tsqrt!(m, n, ib, A1_n, A2_n, Tm, tau, work) - synchronize(A1_n) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - for i in 1:n, j in 1:i-1 - @test abs(A1_cpu[i, j]) < 1e-12 * 100 - end - end - end - end -end - -@testset "TSQRT Error handling" begin - @test_throws ArgumentError NextLA.tsqrt!(-1, 8, 4, zeros(8, 8), zeros(8, 8), zeros(4, 8), zeros(8), zeros(32)) - @test_throws ArgumentError NextLA.tsqrt!(8, -1, 4, zeros(8, 8), zeros(8, 8), zeros(4, 8), zeros(8), zeros(32)) - @test_throws ArgumentError NextLA.tsqrt!(8, 8, -1, zeros(8, 8), zeros(8, 8), zeros(4, 8), zeros(8), zeros(32)) -end diff --git a/test/ttmqr.jl b/test/ttmqr.jl deleted file mode 100644 index 40d86307..00000000 --- a/test/ttmqr.jl +++ /dev/null @@ -1,167 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "TTMQR [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "side=$side, trans=$trans" for side in ['L', 'R'], - trans in ['N', 'C'] - n = 24 - k = 16 - ib = 8 - - A1 = randn(T, n, n) - A2 = randn(T, n, n) - V = triu(randn(T, n, k)) - Tm = triu(rand(T, ib, k)) - - A1_orig = copy(A1) - A2_orig = copy(A2) - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - V_n = ArrayType(copy(V)) - Tm_n = ArrayType(copy(Tm)) - work = ArrayType(zeros(T, side == 'L' ? ib * n : n * ib)) - NextLA.ttmqr!(side, trans, n, n, n, n, k, ib, - A1_n, A2_n, V_n, Tm_n, work) - synchronize(A1_n) - - A1_l = copy(A1) - A2_l = copy(A2) - lapack_tpmqrt!(T, side, trans, 0, V, Tm, A1_l, A2_l) - - @test Array(A1_n) ≈ A1_l rtol=rtol - @test Array(A2_n) ≈ A2_l rtol=rtol - @test !isapprox(Array(A1_n), A1_orig; rtol=rtol) || !isapprox(Array(A2_n), A2_orig; rtol=rtol) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - end - - @testset "Helper matches kernel (side=$side)" for side in ['L', 'R'] - n = 24 - k = 16 - ib = 8 - - A1 = randn(T, n, n) - A2 = randn(T, n, n) - V = triu(randn(T, n, k)) - Tm = triu(rand(T, ib, k)) - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - V_n = ArrayType(copy(V)) - Tm_n = ArrayType(copy(Tm)) - NextLA.ttmqr!(side, 'N', A1_h, A2_h, V_n, Tm_n) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - work = ArrayType(zeros(T, side == 'L' ? ib * n : n * ib)) - NextLA.ttmqr!(side, 'N', n, n, n, n, k, ib, - A1_k, A2_k, V_n, Tm_n, work) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol - @test A2_h ≈ A2_k rtol=rtol - end - - @testset "trans='T' accepted for real types" begin - if !(T <: Complex) - n = 16 - k = 8 - ib = 4 - A1 = ArrayType(copy(randn(T, n, n))) - A2 = ArrayType(copy(randn(T, n, n))) - V = ArrayType(copy(triu(randn(T, n, k)))) - Tm = ArrayType(copy(triu(rand(T, ib, k)))) - work = ArrayType(zeros(T, ib * n)) - @test_nowarn NextLA.ttmqr!('L', 'T', n, n, n, n, k, ib, - A1, A2, V, Tm, work) - end - end - end - - @testset "Rectangular tiles (m ≠ n)" begin - ET = Float64 - rtol_r = test_rtol(ET) - - @testset "Wide A1: side=$side" for side in ['L', 'R'] - m_tile, n_tile = 16, 32 - k = min(m_tile, n_tile) - ib = 4 - - A1 = randn(ET, m_tile, n_tile) - A2 = randn(ET, m_tile, n_tile) - v_rows = side == 'L' ? m_tile : n_tile - V = triu(randn(ET, v_rows, k)) - Tm = triu(rand(ET, ib, k)) - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - V_n = ArrayType(copy(V)) - Tm_n = ArrayType(copy(Tm)) - if side == 'L' - work = ArrayType(zeros(ET, ib * n_tile)) - else - work = ArrayType(zeros(ET, m_tile * ib)) - end - @test_nowarn NextLA.ttmqr!(side, 'N', m_tile, n_tile, m_tile, n_tile, - k, ib, A1_n, A2_n, V_n, Tm_n, work) - end - - @testset "Helper rectangular: side=$side" for side in ['L', 'R'] - m_tile, n_tile = 16, 32 - k = min(m_tile, n_tile) - ib = 4 - - A1 = randn(ET, m_tile, n_tile) - A2 = randn(ET, m_tile, n_tile) - v_rows = side == 'L' ? m_tile : n_tile - V_cpu = triu(randn(ET, v_rows, k)) - Tm_cpu = zeros(ET, ib, n_tile) - Tm_cpu[:, 1:k] .= triu(rand(ET, ib, k)) - V_n = ArrayType(copy(V_cpu)) - Tm_wide = ArrayType(copy(Tm_cpu)) - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - @test_nowarn NextLA.ttmqr!(side, 'N', A1_h, A2_h, V_n, Tm_wide) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - kmax = side == 'L' ? m_tile : n_tile - k_eff = min(n_tile, kmax, size(V_n, 2)) - work = ArrayType(zeros(ET, side == 'L' ? ib * n_tile : m_tile * ib)) - NextLA.ttmqr!(side, 'N', m_tile, n_tile, m_tile, n_tile, - k_eff, ib, A1_k, A2_k, V_n, Tm_wide, work) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol_r - @test A2_h ≈ A2_k rtol=rtol_r - end - end - - @testset "k=0 is a no-op" begin - A1 = ArrayType(copy(rand(ComplexF64, 8, 8))) - A2 = ArrayType(copy(rand(ComplexF64, 8, 8))) - A1_orig = copy(A1) - A2_orig = copy(A2) - NextLA.ttmqr!('L', 'N', 8, 8, 8, 8, 0, 0, - A1, A2, ArrayType(zeros(ComplexF64, 8, 0)), ArrayType(zeros(ComplexF64, 0, 0)), ArrayType(zeros(ComplexF64, 0))) - synchronize(A1) - @test A1 ≈ A1_orig - @test A2 ≈ A2_orig - end - end -end - -@testset "TTMQR Error handling" begin - @test_throws ArgumentError NextLA.ttmqr!('X', 'N', 8, 8, 8, 8, 4, 2, - zeros(8, 8), zeros(8, 8), zeros(8, 4), zeros(2, 4), zeros(16)) - @test_throws ArgumentError NextLA.ttmqr!('L', 'X', 8, 8, 8, 8, 4, 2, - zeros(8, 8), zeros(8, 8), zeros(8, 4), zeros(2, 4), zeros(16)) -end diff --git a/test/ttqrt.jl b/test/ttqrt.jl deleted file mode 100644 index 5a0c7b7d..00000000 --- a/test/ttqrt.jl +++ /dev/null @@ -1,176 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "TTQRT [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - - @testset "n=$n, ib=$ib" for (n, ib) in [ - (16, 4), - (24, 8), - (32, 8), - (48, 16), - ] - A1 = triu(randn(T, n, n)) - A2 = triu(randn(T, n, n)) - - for i in 1:n - A1[i, i] += 2 * one(T) - A2[i, i] += 2 * one(T) - end - - A1_orig = copy(A1) - A2_orig = copy(A2) - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm_n = ArrayType(zeros(T, ib, n)) - tau_n = ArrayType(zeros(T, n)) - work_n = ArrayType(zeros(T, ib * n)) - NextLA.ttqrt!(n, n, ib, A1_n, A2_n, Tm_n, tau_n, work_n) - synchronize(A1_n) - - A1_l = copy(A1) - A2_l = copy(A2) - Tm_l = zeros(T, ib, n) - work_l = zeros(T, ib * n) - lapack_tpqrt!(T, n, n, n, ib, A1_l, n, A2_l, n, Tm_l, ib, work_l) - - @test Array(A1_n) ≈ A1_l rtol=rtol - @test Array(A2_n) ≈ A2_l rtol=rtol - @test !isapprox(Array(A1_n), A1_orig; rtol=rtol) || !isapprox(Array(A2_n), A2_orig; rtol=rtol) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - Tm_cpu = Array(Tm_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - @test all(isfinite.(Tm_cpu)) - end - - @testset "Helper matches kernel" begin - n, ib = 24, 8 - A1 = triu(randn(T, n, n)) - A2 = triu(randn(T, n, n)) - for i in 1:n; A1[i, i] += one(T); A2[i, i] += one(T); end - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - Tm_h = ArrayType(zeros(T, ib, n)) - NextLA.ttqrt!(A1_h, A2_h, Tm_h) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - Tm_k = ArrayType(zeros(T, ib, n)) - tau = ArrayType(zeros(T, n)) - work = ArrayType(zeros(T, ib * n)) - NextLA.ttqrt!(n, n, ib, A1_k, A2_k, Tm_k, tau, work) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol - @test A2_h ≈ A2_k rtol=rtol - end - end - - @testset "Rectangular tiles (m ≠ n)" begin - ET = Float64 - rtol_r = test_rtol(ET) - - @testset "Tall: m=$m, n=$n, ib=$ib" for (m, n, ib) in [ - (32, 16, 4), - (48, 24, 8), - (64, 32, 16), - ] - k = min(m, n) - A1 = triu(randn(ET, m, n)) - A2 = triu(randn(ET, m, n)) - for i in 1:k - A1[i, i] += 2 * one(ET) - A2[i, i] += 2 * one(ET) - end - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm_n = ArrayType(zeros(ET, ib, k)) - tau_n = ArrayType(zeros(ET, k)) - work_n = ArrayType(zeros(ET, ib * n)) - NextLA.ttqrt!(m, n, ib, A1_n, A2_n, Tm_n, tau_n, work_n) - synchronize(A1_n) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - Tm_cpu = Array(Tm_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - @test all(isfinite.(Tm_cpu)) - for i in 1:k, j in 1:i-1 - @test abs(A1_cpu[i, j]) < rtol_r * 100 - end - end - - @testset "Wide: m=$m, n=$n, ib=$ib" for (m, n, ib) in [ - (16, 32, 4), - (24, 48, 8), - ] - k = min(m, n) - A1 = triu(randn(ET, m, n)) - A2 = triu(randn(ET, m, n)) - for i in 1:k - A1[i, i] += 2 * one(ET) - A2[i, i] += 2 * one(ET) - end - - A1_n = ArrayType(copy(A1)) - A2_n = ArrayType(copy(A2)) - Tm_n = ArrayType(zeros(ET, ib, k)) - tau_n = ArrayType(zeros(ET, k)) - work_n = ArrayType(zeros(ET, ib * n)) - NextLA.ttqrt!(m, n, ib, A1_n, A2_n, Tm_n, tau_n, work_n) - synchronize(A1_n) - - A1_cpu = Array(A1_n) - A2_cpu = Array(A2_n) - Tm_cpu = Array(Tm_n) - @test all(isfinite.(A1_cpu)) - @test all(isfinite.(A2_cpu)) - @test all(isfinite.(Tm_cpu)) - for i in 1:k, j in 1:i-1 - @test abs(A1_cpu[i, j]) < rtol_r * 100 - end - end - - @testset "Helper rectangular: m=$m, n=$n" for (m, n) in [ - (32, 16), - (16, 32), - ] - k = min(m, n) - ib = min(8, k) - A1 = triu(randn(ET, m, n)) - A2 = triu(randn(ET, m, n)) - for i in 1:k; A1[i, i] += one(ET); A2[i, i] += one(ET); end - - A1_h = ArrayType(copy(A1)) - A2_h = ArrayType(copy(A2)) - Tm_h = ArrayType(zeros(ET, ib, k)) - NextLA.ttqrt!(A1_h, A2_h, Tm_h) - synchronize(A1_h) - - A1_k = ArrayType(copy(A1)) - A2_k = ArrayType(copy(A2)) - Tm_k = ArrayType(zeros(ET, ib, k)) - tau = ArrayType(zeros(ET, k)) - work = ArrayType(zeros(ET, ib * n)) - NextLA.ttqrt!(m, n, ib, A1_k, A2_k, Tm_k, tau, work) - synchronize(A1_k) - - @test A1_h ≈ A1_k rtol=rtol_r - @test A2_h ≈ A2_k rtol=rtol_r - end - end - end -end - -@testset "TTQRT Error handling" begin - @test_throws ArgumentError NextLA.ttqrt!(-1, 8, 4, zeros(8, 8), zeros(8, 8), zeros(4, 8), zeros(8), zeros(32)) - @test_throws ArgumentError NextLA.ttqrt!(8, -1, 4, zeros(8, 8), zeros(8, 8), zeros(4, 8), zeros(8), zeros(32)) - @test_throws ArgumentError NextLA.ttqrt!(8, 8, -1, zeros(8, 8), zeros(8, 8), zeros(4, 8), zeros(8), zeros(32)) -end diff --git a/test/unmqr.jl b/test/unmqr.jl deleted file mode 100644 index 7ba82cdd..00000000 --- a/test/unmqr.jl +++ /dev/null @@ -1,134 +0,0 @@ -for (backend_name, ArrayType, synchronize) in available_backends() - @testset "UNMQR [$backend_name]" begin - @testset "$T" for T in TEST_TYPES - rtol = test_rtol(T) - m, n, k, ib = 64, 48, 32, 8 - - # Build a valid QR factorization first - A_qr = ArrayType(copy(rand(T, m, k))) - Tm = ArrayType(zeros(T, ib, k)) - tau = ArrayType(zeros(T, k)) - work_qr = ArrayType(zeros(T, ib * k)) - NextLA.geqrt!(m, k, ib, A_qr, Tm, tau, work_qr) - synchronize(A_qr) - - @testset "Left, No-Transpose" begin - C = ArrayType(copy(rand(T, m, n))) - C_orig = copy(C) - - work = ArrayType(zeros(T, n, ib)) - NextLA.unmqr!('L', 'N', m, n, k, ib, A_qr, m, Tm, C, work) - synchronize(C) - - @test norm(C) ≈ norm(C_orig) rtol=rtol - - C_h = copy(C_orig) - NextLA.unmqr!('L', 'N', A_qr, Tm, C_h) - synchronize(C_h) - @test C_h ≈ C rtol=rtol - end - - @testset "Left, Conjugate-Transpose" begin - C = ArrayType(copy(rand(T, m, n))) - C_orig = copy(C) - - work = ArrayType(zeros(T, n, ib)) - NextLA.unmqr!('L', 'C', m, n, k, ib, A_qr, m, Tm, C, work) - synchronize(C) - - @test norm(C) ≈ norm(C_orig) rtol=rtol - - C_h = copy(C_orig) - NextLA.unmqr!('L', 'C', A_qr, Tm, C_h) - synchronize(C_h) - @test C_h ≈ C rtol=rtol - end - - @testset "Right, No-Transpose" begin - C = ArrayType(copy(rand(T, n, m))) - C_orig = copy(C) - - work = ArrayType(zeros(T, n, ib)) - NextLA.unmqr!('R', 'N', n, m, k, ib, A_qr, m, Tm, C, work) - synchronize(C) - - @test norm(C) ≈ norm(C_orig) rtol=rtol - end - - @testset "Right, Conjugate-Transpose" begin - C = ArrayType(copy(rand(T, n, m))) - C_orig = copy(C) - - work = ArrayType(zeros(T, n, ib)) - NextLA.unmqr!('R', 'C', n, m, k, ib, A_qr, m, Tm, C, work) - synchronize(C) - - @test norm(C) ≈ norm(C_orig) rtol=rtol - end - - @testset "Q * Qᴴ = I (orthogonality)" begin - C = ArrayType(collect(Matrix{T}(I, m, m))) - work = ArrayType(zeros(T, m, ib)) - - NextLA.unmqr!('L', 'N', m, m, k, ib, A_qr, m, Tm, C, work) - NextLA.unmqr!('L', 'C', m, m, k, ib, A_qr, m, Tm, C, work) - synchronize(C) - - @test Array(C) ≈ Matrix{T}(I, m, m) rtol=rtol - end - end - - @testset "Rectangular tile: k clamped to nq" begin - for T in (Float64, ComplexF64) - m_tile, n_tile = 16, 32 # wide tile: only 16 reflectors possible - ib = 4 - k_actual = m_tile - A_qr = ArrayType(copy(rand(T, m_tile, k_actual))) - Tm = ArrayType(zeros(T, ib, k_actual)) - tau = ArrayType(zeros(T, k_actual)) - work_qr = ArrayType(zeros(T, ib * k_actual)) - NextLA.geqrt!(m_tile, k_actual, ib, A_qr, Tm, tau, work_qr) - - C = ArrayType(copy(rand(T, m_tile, 24))) - C_orig = copy(C) - work = ArrayType(zeros(T, 24, ib)) - @test_nowarn NextLA.unmqr!('L', 'N', m_tile, 24, n_tile, ib, - A_qr, m_tile, Tm, C, work) - synchronize(C) - @test norm(C) ≈ norm(C_orig) rtol=test_rtol(T) - - Tm_wide = ArrayType(zeros(T, ib, n_tile)) - Tm_wide[:, 1:k_actual] .= Tm - C2 = copy(C_orig) - @test_nowarn NextLA.unmqr!('L', 'N', A_qr, Tm_wide, C2) - synchronize(C2) - @test norm(C2) ≈ norm(C_orig) rtol=test_rtol(T) - end - end - end -end - -@testset "UNMQR Error handling" begin - m, n, k, ib = 32, 24, 16, 4 - A = zeros(ComplexF64, m, k) - Tm = zeros(ComplexF64, ib, k) - C = zeros(ComplexF64, m, n) - work = zeros(ComplexF64, n, ib) - - @test_throws ArgumentError NextLA.unmqr!('X', 'N', m, n, k, ib, A, m, Tm, C, work) - @test_throws ArgumentError NextLA.unmqr!('L', 'X', m, n, k, ib, A, m, Tm, C, work) - @test_throws ArgumentError NextLA.unmqr!('L', 'N', -1, n, k, ib, A, m, Tm, C, work) - C_test = zeros(ComplexF64, m, n) - @test_nowarn NextLA.unmqr!('L', 'N', m, n, m+1, ib, A, m, Tm, C_test, work) -end - -@testset "UNMQR k=0 is a no-op" begin - C = rand(ComplexF64, 32, 24) - C_orig = copy(C) - A = zeros(ComplexF64, 32, 1) - Tm = zeros(ComplexF64, 4, 1) - work = zeros(ComplexF64, 24, 4) - - NextLA.unmqr!('L', 'N', 32, 24, 0, 4, A, 32, Tm, C, work) - @test C ≈ C_orig -end