diff --git a/.dev/Manifest.toml b/.dev/Manifest.toml deleted file mode 100644 index 84d95f7..0000000 --- a/.dev/Manifest.toml +++ /dev/null @@ -1,253 +0,0 @@ -# This file is machine-generated - editing it directly is not advised - -julia_version = "1.12.6" -manifest_format = "2.0" -project_hash = "ba6d5fe1adc09573ca293b48992a40c015edc97b" - -[[deps.ArgParse]] -deps = ["Logging", "TextWrap"] -git-tree-sha1 = "22cf435ac22956a7b45b0168abbc871176e7eecc" -uuid = "c7e460c6-2fb9-53a9-8c5b-16f535851c63" -version = "1.2.0" - -[[deps.ArgTools]] -uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" -version = "1.1.2" - -[[deps.Artifacts]] -uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" -version = "1.11.0" - -[[deps.Base64]] -uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" -version = "1.11.0" - -[[deps.CSTParser]] -deps = ["Tokenize"] -git-tree-sha1 = "fff070691d78b302dc7174a1d8eb1a94cc514987" -uuid = "00ebfdb7-1f24-5e51-bd34-a7502290713f" -version = "3.5.0" - -[[deps.CommonMark]] -deps = ["Crayons", "PrecompileTools"] -git-tree-sha1 = "5fdf00d1979fd4883b44b754fc3423175c9504b4" -uuid = "a80b9123-70ca-4bc0-993e-6e3bcb318db6" -version = "0.8.16" - -[[deps.Compat]] -deps = ["TOML", "UUIDs"] -git-tree-sha1 = "9d8a54ce4b17aa5bdce0ea5c34bc5e7c340d16ad" -uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" -version = "4.18.1" - - [deps.Compat.extensions] - CompatLinearAlgebraExt = "LinearAlgebra" - - [deps.Compat.weakdeps] - Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" - LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" - -[[deps.CompilerSupportLibraries_jll]] -deps = ["Artifacts", "Libdl"] -uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" -version = "1.3.0+1" - -[[deps.Crayons]] -git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15" -uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" -version = "4.1.1" - -[[deps.DataStructures]] -deps = ["Compat", "InteractiveUtils", "OrderedCollections"] -git-tree-sha1 = "4e1fe97fdaed23e9dc21d4d664bea76b65fc50a0" -uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" -version = "0.18.22" - -[[deps.Dates]] -deps = ["Printf"] -uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" -version = "1.11.0" - -[[deps.Downloads]] -deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] -uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" -version = "1.7.0" - -[[deps.FileWatching]] -uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" -version = "1.11.0" - -[[deps.Glob]] -git-tree-sha1 = "246c628cec062230b7d183aab88841fa94fcabe9" -uuid = "c27321d9-0574-5035-807b-f59d2c89b15c" -version = "1.5.0" - -[[deps.InteractiveUtils]] -deps = ["Markdown"] -uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" -version = "1.11.0" - -[[deps.JuliaFormatter]] -deps = ["CSTParser", "CommonMark", "DataStructures", "Glob", "PrecompileTools", "TOML", "Tokenize"] -git-tree-sha1 = "59cf7ad64f1b0708a4fa4369879d33bad3239b56" -uuid = "98e50ef6-434e-11e9-1051-2b60c6c9e899" -version = "1.0.62" - -[[deps.JuliaSyntaxHighlighting]] -deps = ["StyledStrings"] -uuid = "ac6e5ff7-fb65-4e79-a425-ec3bc9c03011" -version = "1.12.0" - -[[deps.LibCURL]] -deps = ["LibCURL_jll", "MozillaCACerts_jll"] -uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" -version = "0.6.4" - -[[deps.LibCURL_jll]] -deps = ["Artifacts", "LibSSH2_jll", "Libdl", "OpenSSL_jll", "Zlib_jll", "nghttp2_jll"] -uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" -version = "8.15.0+0" - -[[deps.LibGit2]] -deps = ["LibGit2_jll", "NetworkOptions", "Printf", "SHA"] -uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" -version = "1.11.0" - -[[deps.LibGit2_jll]] -deps = ["Artifacts", "LibSSH2_jll", "Libdl", "OpenSSL_jll"] -uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" -version = "1.9.0+0" - -[[deps.LibSSH2_jll]] -deps = ["Artifacts", "Libdl", "OpenSSL_jll"] -uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" -version = "1.11.3+1" - -[[deps.Libdl]] -uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" -version = "1.11.0" - -[[deps.Logging]] -uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" -version = "1.11.0" - -[[deps.Markdown]] -deps = ["Base64", "JuliaSyntaxHighlighting", "StyledStrings"] -uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" -version = "1.11.0" - -[[deps.MozillaCACerts_jll]] -uuid = "14a3606d-f60d-562e-9121-12d972cd8159" -version = "2025.11.4" - -[[deps.NetworkOptions]] -uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" -version = "1.3.0" - -[[deps.OpenSSL_jll]] -deps = ["Artifacts", "Libdl"] -uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" -version = "3.5.4+0" - -[[deps.OrderedCollections]] -git-tree-sha1 = "94ba93778373a53bfd5a0caaf7d809c445292ff4" -uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" -version = "1.8.2" - -[[deps.Pkg]] -deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "Random", "SHA", "TOML", "Tar", "UUIDs", "p7zip_jll"] -uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" -version = "1.12.1" -weakdeps = ["REPL"] - - [deps.Pkg.extensions] - REPLExt = "REPL" - -[[deps.PkgDevTools]] -deps = ["OrderedCollections", "Pkg", "REPL"] -git-tree-sha1 = "82e067d0d1cb1213eec2a0520daed024ed7b5fc9" -uuid = "2afb0842-1d6c-4499-8b39-71b06199676f" -version = "0.1.1" - -[[deps.PrecompileTools]] -deps = ["Preferences"] -git-tree-sha1 = "edbeefc7a4889f528644251bdb5fc9ab5348bc2c" -uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" -version = "1.3.4" - -[[deps.Preferences]] -deps = ["TOML"] -git-tree-sha1 = "8b770b60760d4451834fe79dd483e318eee709c4" -uuid = "21216c6a-2e73-6563-6e65-726566657250" -version = "1.5.2" - -[[deps.Printf]] -deps = ["Unicode"] -uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" -version = "1.11.0" - -[[deps.REPL]] -deps = ["InteractiveUtils", "JuliaSyntaxHighlighting", "Markdown", "Sockets", "StyledStrings", "Unicode"] -uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" -version = "1.11.0" - -[[deps.Random]] -deps = ["SHA"] -uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" -version = "1.11.0" - -[[deps.SHA]] -uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" -version = "0.7.0" - -[[deps.Sockets]] -uuid = "6462fe0b-24de-5631-8697-dd941f90decc" -version = "1.11.0" - -[[deps.StyledStrings]] -uuid = "f489334b-da3d-4c2e-b8f0-e476e12c162b" -version = "1.11.0" - -[[deps.TOML]] -deps = ["Dates"] -uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" -version = "1.0.3" - -[[deps.Tar]] -deps = ["ArgTools", "SHA"] -uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" -version = "1.10.0" - -[[deps.TextWrap]] -git-tree-sha1 = "43044b737fa70bc12f6105061d3da38f881a3e3c" -uuid = "b718987f-49a8-5099-9789-dcd902bef87d" -version = "1.0.2" - -[[deps.Tokenize]] -git-tree-sha1 = "468b4685af4abe0e9fd4d7bf495a6554a6276e75" -uuid = "0796e94c-ce3b-5d07-9a54-7f471281c624" -version = "0.5.29" - -[[deps.UUIDs]] -deps = ["Random", "SHA"] -uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" -version = "1.11.0" - -[[deps.Unicode]] -uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" -version = "1.11.0" - -[[deps.Zlib_jll]] -deps = ["Libdl"] -uuid = "83775a58-1f1d-513f-b197-d71354ab007a" -version = "1.3.1+2" - -[[deps.nghttp2_jll]] -deps = ["Artifacts", "Libdl"] -uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" -version = "1.64.0+1" - -[[deps.p7zip_jll]] -deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] -uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" -version = "17.7.0+0" diff --git a/.github/workflows/UpDeps.yml b/.github/workflows/UpDeps.yml deleted file mode 100644 index dba17bc..0000000 --- a/.github/workflows/UpDeps.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: UpDeps - -on: - push: - branches: - - main - tags: '*' - pull_request: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - update_deps: - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@v6 - - - uses: julia-actions/setup-julia@v3 - with: - version: '1.12' - - - name: Install PkgDevTools - run: julia -e 'using Pkg; Pkg.add("PkgDevTools")' - - - name: Apply UpDeps - run: | - julia -e 'using PkgDevTools; PkgDevTools.update_deps("."; auto_all=true)' - - - name: Check Manifest diff - run: | - git diff --color=always --exit-code diff --git a/CHANGELOG.md b/CHANGELOG.md index 666558d..0bd0846 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ All notable changes to this project will be documented in this file. - **Benefit**: All code paths now validated by JET; zero runtime overhead from dispatch selection #### GPU Acceleration -- Added `StructureFunctionsGPUExt` extension for portable GPU kernels +- Added `StructureFunctionsKernelAbstractionsExt` extension for portable GPU kernels - Supports NVIDIA (CUDA), AMD (ROCm), CPU (for testing) via KernelAbstractions - `GPUBackend` passes to kernels seamlessly; full parity with CPU implementations validated diff --git a/Project.toml b/Project.toml index 7de9eb9..5436103 100644 --- a/Project.toml +++ b/Project.toml @@ -7,6 +7,7 @@ authors = ["Jordan Benjamin"] projects = ["test", "gpu"] [deps] +ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" @@ -20,19 +21,22 @@ Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" -SharedArrays = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [extensions] StructureFunctionsCUDAExt = ["KernelAbstractions", "CUDA"] StructureFunctionsCairoMakieExt = ["CairoMakie"] -StructureFunctionsGPUExt = ["KernelAbstractions"] +StructureFunctionsKernelAbstractionsExt = ["KernelAbstractions"] StructureFunctionsOhMyThreadsExt = ["OhMyThreads"] -StructureFunctionsDistributedExt = ["Distributed", "SharedArrays"] +StructureFunctionsDistributedExt = ["Distributed"] StructureFunctionsMPIExt = ["MPI"] +[sources] +ComputationalBackends = { url = "https://github.com/jbphyswx/ComputationalBackends.jl" } + [compat] CUDA = "5, 6" CairoMakie = "0.15" +ComputationalBackends = "0.1" Distances = "0.10" Distributed = "1.11" KernelAbstractions = "0.9" @@ -41,6 +45,5 @@ MPI = "0.20" OhMyThreads = "0.8" PrecompileTools = "1.3.3" ProgressMeter = "1.9" -SharedArrays = "1.11" StaticArrays = "1.9" julia = "1.12" diff --git a/README.md b/README.md index c008e23..daf7245 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ using Base.Threads if nthreads() > 1 result_threaded = SFC.calculate_structure_function( sf_type, x, u, bins; - backend=SFC.ThreadedBackend() + backend=CB.ThreadedBackend() ) end ``` @@ -84,7 +84,7 @@ sums = zeros(Float64, n_bins) counts = zeros(Float64, n_bins) # Compute in-place (accumulates into provided buffers) -SFC.calculate_structure_function!(sums, counts, sf_type, x, u, bins; backend=SFC.ThreadedBackend()) +SFC.calculate_structure_function!(sums, counts, sf_type, x, u, bins; backend=CB.ThreadedBackend()) # Obtain structure function values via division sf_values = sums ./ counts @@ -143,7 +143,7 @@ Single-threaded CPU execution. Use when: ```julia result = SFC.calculate_structure_function(sf_type, x, u, bins) # Defaults to Serial result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.SerialBackend()) + backend=CB.SerialBackend()) ``` **Performance**: O(N²) pairwise distance/SF evaluations. @@ -157,7 +157,7 @@ Multi-threaded execution using [OhMyThreads.jl](https://github.com/JuliaFolds2/O using Base.Threads result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.ThreadedBackend()) + backend=CB.ThreadedBackend()) ``` - **Prerequisites**: `Threads.nthreads() > 1`, OhMyThreads.jl loaded (extension auto-loads) @@ -176,7 +176,7 @@ using Distributed: addprocs addprocs(4) # Or specify SSH workers, etc. result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.DistributedBackend()) + backend=CB.DistributedBackend()) ``` - **Prerequisites**: Workers launched via `addprocs()` or similar @@ -193,16 +193,16 @@ using KernelAbstractions as KA # NVIDIA GPU (after loading CUDA.jl) using CUDA result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.GPUBackend(CUDA.CUDABackend())) + backend=CB.GPUBackend(CUDA.CUDABackend())) # AMD GPU (after loading AMDGPU.jl) using AMDGPU result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.GPUBackend(AMDGPU.ROCBackend())) + backend=CB.GPUBackend(AMDGPU.ROCBackend())) # CPU backend for testing (no GPU required) result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.GPUBackend(KA.CPU())) + backend=CB.GPUBackend(KA.CPU())) ``` - **Ideal for**: Large datasets (few×10³+ points) where GPU memory is sufficient @@ -214,7 +214,7 @@ Automatic selection based on environment: ```julia result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.AutoBackend()) + backend=CB.AutoBackend()) # Selection order: # 1. Distributed (if nworkers() > 1) @@ -369,7 +369,7 @@ distance_bins = LogBinEdges(log_bins_raw) # Returns a NamedTuple keyed by invariant: results.S2, results.L2, results.T2, # results.S3, results.L3, results.L1T2 (+ results.helmholtz for point-field input). # Each entry is a StructureFunction (pass output_type=StructureFunctionSumsAndCounts for raw). -results = SFC.calculate_structure_functions_single_pass(x, u, distance_bins; backend=SFC.SerialBackend()) +results = SFC.calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.SerialBackend()) ``` ## Theory & References @@ -513,7 +513,7 @@ StructureFunctionsOhMyThreadsExt = "OhMyThreads" ### DistributedExt (DistributedBackend) -Requires `Distributed.jl` (stdlib) + `SharedArrays.jl` (stdlib): +Requires `Distributed.jl` (stdlib): ```julia using Distributed: addprocs @@ -530,7 +530,7 @@ Requires `KernelAbstractions.jl` + GPU package (CUDA.jl, AMDGPU.jl, etc.): KernelAbstractions = "63c18a36-062a-441e-b365-b594b6ce51b1" [extensions] -StructureFunctionsGPUExt = "KernelAbstractions" +StructureFunctionsKernelAbstractionsExt = "KernelAbstractions" ``` ## Migration from v0.2 diff --git a/RELEASE_NOTES_v0.3.0.md b/RELEASE_NOTES_v0.3.0.md index 6fc01f0..b0e9830 100644 --- a/RELEASE_NOTES_v0.3.0.md +++ b/RELEASE_NOTES_v0.3.0.md @@ -19,7 +19,7 @@ StructureFunctions.jl v0.3.0 is a major release featuring a complete backend sys #### 2. **GPU Acceleration** - New `GPUBackend` supports NVIDIA (CUDA), AMD (ROCm), Apple Silicon (Metal) -- Implemented via `StructureFunctionsGPUExt` and KernelAbstractions.jl +- Implemented via `StructureFunctionsKernelAbstractionsExt` and KernelAbstractions.jl - **Performance**: 10–100x faster for 1B+ point calculations #### 3. **Bug Fixes** diff --git a/benchmark/Project.toml b/benchmark/Project.toml index 2d461cc..05b1840 100644 --- a/benchmark/Project.toml +++ b/benchmark/Project.toml @@ -1,9 +1,16 @@ [deps] BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" +ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" StructureFunctions = "e93fee26-4d5e-49c1-899d-490508cfd19b" + +[sources] +ComputationalBackends = {url = "https://github.com/jbphyswx/ComputationalBackends.jl"} +StructureFunctions = { path = ".." } diff --git a/benchmark/accuracy.jl b/benchmark/accuracy.jl new file mode 100644 index 0000000..3f88f7d --- /dev/null +++ b/benchmark/accuracy.jl @@ -0,0 +1,81 @@ +#!/usr/bin/env julia +# Stage 0 accuracy harness: measured relative error of Float32 accumulation orderings against a +# Float64 reference, on the real per-pair values of the 1D pair loop. +# +# This is the measurement behind the accumulator-eltype decision: the accumulator stays Float32 +# (widening halves the GPU shared-memory histogram and with it occupancy — the measured bottleneck), +# and accuracy comes from the accumulation STRUCTURE. Blocked/pairwise summation reduces roundoff +# growth from O(n) to O(log n) at no bandwidth cost; this prints how much that buys at each N. +# +# Usage: julia --project=benchmark benchmark/accuracy.jl + +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, + StructureFunctionTypes as SFT +using Printf, Random + +const SFTYPE = SFT.L2SFType() + +# Per-pair L2SF values of the pairs of one bin, exactly as the kernel computes them (Float32 path), +# plus the Float64-computed reference values of the same pairs. +function bin_values(N) + Random.seed!(7) + x64 = rand(Float64, 2, N); u64 = randn(Float64, 2, N) + x32 = Float32.(x64); u32 = Float32.(u64) + v32 = Float32[]; v64 = Float64[] + for i in 1:(N - 1), j in (i + 1):N + dx64 = (x64[1, j] - x64[1, i], x64[2, j] - x64[2, i]) + r64 = sqrt(dx64[1]^2 + dx64[2]^2) + du64 = (u64[1, j] - u64[1, i], u64[2, j] - u64[2, i]) + push!(v64, ((du64[1] * dx64[1] + du64[2] * dx64[2]) / r64)^2) + + dx32 = (x32[1, j] - x32[1, i], x32[2, j] - x32[2, i]) + r32 = sqrt(dx32[1]^2 + dx32[2]^2) + du32 = (u32[1, j] - u32[1, i], u32[2, j] - u32[2, i]) + push!(v32, ((du32[1] * dx32[1] + du32[2] * dx32[2]) / r32)^2) + end + return v32, v64 +end + +naive_sum(v::Vector{T}) where {T} = (s = zero(T); for x in v; s += x; end; s) + +# Panel-blocked naive sum: partials of `blk` values summed naively, then partials summed naively. +# This is the ordering a j-panel kernel produces for free. +function blocked_sum(v::Vector{T}, blk::Int) where {T} + s = zero(T) + i = 1 + while i <= length(v) + hi = min(i + blk - 1, length(v)) + p = zero(T) + for k in i:hi + p += v[k] + end + s += p + i = hi + 1 + end + return s +end + +function main() + @printf("%s\nFloat32 accumulation error vs Float64 reference (same pairs, kernel-order values)\n%s\n", + "="^100, "="^100) + @printf("%8s %12s | %14s %14s %14s %14s\n", + "N", "pairs", "naive f32", "blk=512 f32", "blk=2048 f32", "pairwise f32") + for N in (1_000, 3_000, 10_000) + v32, v64 = bin_values(N) + ref = sum(v64) # Float64 pairwise (Base) = reference + rel(x) = abs(Float64(x) - ref) / abs(ref) + @printf("%8d %12d | %14.3e %14.3e %14.3e %14.3e\n", + N, length(v32), + rel(naive_sum(v32)), + rel(blocked_sum(v32, 512)), + rel(blocked_sum(v32, 2048)), + rel(sum(v32))) # Base pairwise on Float32 + end + println(""" +naive f32 = today's kernel ordering (straight left-to-right +=) +blk f32 = j-panel partial sums (the Stage-3 blocked kernel's free ordering) +pairwise f32 = Base's pairwise reduction (log-depth; the achievable floor without widening) +The per-value input error floor for Float32 data is ~1e-7 regardless of summation order.""") +end + +main() diff --git a/benchmark/alloc_regression.jl b/benchmark/alloc_regression.jl new file mode 100644 index 0000000..657bdd0 --- /dev/null +++ b/benchmark/alloc_regression.jl @@ -0,0 +1,87 @@ +using Test: Test +using BenchmarkTools: BenchmarkTools +using StructureFunctions: StructureFunctions as SF +using StaticArrays: StaticArrays as SA +using Random: Random +using JSON: JSON + +const BASELINE_FILE = joinpath(@__DIR__, "benchmark_results", "alloc_baseline.json") + +"""Set `SF_UPDATE_ALLOC_BASELINE=1` to overwrite the committed baseline with this run.""" +const UPDATE_BASELINE = get(ENV, "SF_UPDATE_ALLOC_BASELINE", "0") == "1" + +function load_baseline() + isfile(BASELINE_FILE) || return Dict{String, Any}() + try + return JSON.parsefile(BASELINE_FILE) + catch + @warn "Unparseable baseline at $BASELINE_FILE; treating every case as new." + return Dict{String, Any}() + end +end + +function save_baseline(results) + mkpath(dirname(BASELINE_FILE)) + open(BASELINE_FILE, "w") do f + JSON.print(f, results, 4) + end +end + +function run_sf_benchmark(x, u, bins, sf_type) + return BenchmarkTools.@benchmark SF.calculate_structure_function( + $sf_type, + $x, + $u, + $bins; + verbose = false, + show_progress = false, + ) seconds = 0.2 samples = 50 +end + +Test.@testset "Allocation regression" begin + Random.seed!(42) + N = 100 + + x2, u2 = randn(2, N), randn(2, N) + x3, u3 = randn(3, N), randn(3, N) + bins = [0.0, 0.5, 1.0, 1.5, 2.0] + + baseline = load_baseline() + current = Dict{String, Any}() + + test_matrix = [ + ("sf_2d_array_2nd_long", x2, u2, SF.LongitudinalSecondOrderStructureFunction), + ("sf_3d_array_2nd_long", x3, u3, SF.LongitudinalSecondOrderStructureFunction), + ("sf_2d_array_2nd_trans", x2, u2, SF.TransverseSecondOrderStructureFunction), + ("sf_2d_array_3rd_diag", x2, u2, SF.DiagonalConsistentThirdOrderStructureFunction), + ] + + for (name, x_in, u_in, sft) in test_matrix + Test.@testset "$name" begin + b = run_sf_benchmark(x_in, u_in, bins, sft) + allocs = b.allocs + current[name] = Dict("allocs" => allocs, "time_μs" => minimum(b.times) / 1e3) + if haskey(baseline, name) + Test.@test allocs <= baseline[name]["allocs"] + else + @info "$name: new case, recording $allocs allocs" + Test.@test allocs < 100_000 + end + end + end + + Test.@testset "n̂ allocates nothing" begin + r_hat = SA.SVector(1.0, 0.0) + b = BenchmarkTools.@benchmark SF.HelperFunctions.n̂($r_hat) + current["nhat_helper"] = Dict("allocs" => b.allocs, "time_μs" => minimum(b.times) / 1e3) + Test.@test b.allocs == 0 + end + + # Overwriting unconditionally would bake a regression in as the new baseline. + if UPDATE_BASELINE + save_baseline(merge(baseline, current)) + @info "Baseline updated: $BASELINE_FILE" + else + @info "Baseline unchanged; set SF_UPDATE_ALLOC_BASELINE=1 to record this run." + end +end diff --git a/benchmark/benchmark_worker.jl b/benchmark/benchmark_worker.jl index fd6ff9b..0397085 100644 --- a/benchmark/benchmark_worker.jl +++ b/benchmark/benchmark_worker.jl @@ -12,6 +12,7 @@ Usage (internal, called automatically by benchmark_scaling.jl): julia --project=benchmark -t 8 benchmark/benchmark_worker.jl 5000 """ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions, Calculations as SFC using OhMyThreads: OhMyThreads # Trigger extension using JSON: JSON @@ -31,11 +32,11 @@ bins = scaling_bins(FT) sft = SCALING_SFT # Warmup (avoid counting compile time) -SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = SFC.ThreadedBackend(), verbose = false, show_progress = false) +SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = CB.ThreadedBackend(), verbose = false, show_progress = false) # Timed run t_start = time() -SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = SFC.ThreadedBackend(), verbose = false, show_progress = false) +SFC.calculate_structure_function(sft, x_arr, u_arr, bins; backend = CB.ThreadedBackend(), verbose = false, show_progress = false) elapsed = time() - t_start result = Dict( diff --git a/benchmark/cpu_regimes.jl b/benchmark/cpu_regimes.jl index bbf8c1e..7046740 100644 --- a/benchmark/cpu_regimes.jl +++ b/benchmark/cpu_regimes.jl @@ -14,6 +14,7 @@ # # Backends: SerialBackend, ThreadedBackend (OhMyThreads ext). +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT using OhMyThreads: OhMyThreads # load threaded extension @@ -77,9 +78,9 @@ for T in (Float64, Float32) # Regime 1: point-field 1D single SF (O(N^2) headline path); threaded = OMT (works) let x = rand(T, 3, NPF), u = rand(T, 3, NPF), bins = _bins(T) pairs = NPF*(NPF-1)÷2 - fS() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=SFC.SerialBackend(), + fS() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=CB.SerialBackend(), verbose=false, show_progress=false, output_type=SF.StructureFunctionSumsAndCounts) - fT() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=SFC.ThreadedBackend(), + fT() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=CB.ThreadedBackend(), verbose=false, show_progress=false, output_type=SF.StructureFunctionSumsAndCounts) report("point-field 1D", pairs, fS, fT) end @@ -87,9 +88,9 @@ for T in (Float64, Float32) # Regime 2: batched shared-positions 1D ("same surface") let x = rand(T, 3, N), u = rand(T, 3, N, B), bins = _bins(T) pairs = N*(N-1)÷2 * B - fS() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=SFC.SerialBackend(), + fS() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=CB.SerialBackend(), verbose=false, show_progress=false, output_type=SF.StructureFunctionSumsAndCounts) - fT() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=SFC.ThreadedBackend(), + fT() = SFC.calculate_structure_function(SFTYPE, x, u, bins; backend=CB.ThreadedBackend(), verbose=false, show_progress=false, output_type=SF.StructureFunctionSumsAndCounts) report("batch shared-pos 1D", pairs, fS, fT; do_threaded = DO_THREADED_BATCH) end @@ -97,9 +98,9 @@ for T in (Float64, Float32) # Regime 3: batched 2D joint let x = rand(T, 3, N), u = rand(T, 3, N, B), bins = _bins(T), vb = _vbins(T) pairs = N*(N-1)÷2 * B - fS() = SFC.calculate_structure_function(SFTYPE, x, u, bins, vb; backend=SFC.SerialBackend(), + fS() = SFC.calculate_structure_function(SFTYPE, x, u, bins, vb; backend=CB.SerialBackend(), verbose=false, show_progress=false, output_type=SF.StructureFunctionSumsAndCounts) - fT() = SFC.calculate_structure_function(SFTYPE, x, u, bins, vb; backend=SFC.ThreadedBackend(), + fT() = SFC.calculate_structure_function(SFTYPE, x, u, bins, vb; backend=CB.ThreadedBackend(), verbose=false, show_progress=false, output_type=SF.StructureFunctionSumsAndCounts) report("batch 2D joint", pairs, fS, fT; do_threaded = DO_THREADED_BATCH) end diff --git a/benchmark/profile/profile_runner.jl b/benchmark/profile/profile_runner.jl index 008cf9b..0f7339f 100644 --- a/benchmark/profile/profile_runner.jl +++ b/benchmark/profile/profile_runner.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions using OhMyThreads using Profile @@ -33,16 +34,16 @@ function main() flush(stdout); flush(stderr) # warm up serial - calculate_structure_functions_single_pass(x[:, 1:200], u[:, 1:200], distance_bins; backend=SerialBackend()) + calculate_structure_functions_single_pass(x[:, 1:200], u[:, 1:200], distance_bins; backend=CB.SerialBackend()) # warm up threaded - calculate_structure_functions_single_pass(x[:, 1:200], u[:, 1:200], distance_bins; backend=ThreadedBackend()) + calculate_structure_functions_single_pass(x[:, 1:200], u[:, 1:200], distance_bins; backend=CB.ThreadedBackend()) # 3. CPU Profiling (Serial) println("Profiling CPU execution (Serial)...") flush(stdout); flush(stderr) Profile.clear() - Profile.@profile calculate_structure_functions_single_pass(x, u, distance_bins; backend=SerialBackend()) + Profile.@profile calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.SerialBackend()) cpu_serial_txt = joinpath(profile_dir, "cpu_serial.txt") cpu_serial_jls = joinpath(profile_dir, "cpu_serial.jls") @@ -60,7 +61,7 @@ function main() flush(stdout); flush(stderr) Profile.clear() - Profile.@profile calculate_structure_functions_single_pass(x, u, distance_bins; backend=ThreadedBackend()) + Profile.@profile calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.ThreadedBackend()) cpu_threaded_txt = joinpath(profile_dir, "cpu_threaded.txt") cpu_threaded_jls = joinpath(profile_dir, "cpu_threaded.jls") @@ -130,7 +131,7 @@ function main() println("Profiling memory allocations (Serial)...") flush(stdout); flush(stderr) Profile.Allocs.clear() - Profile.Allocs.@profile sample_rate=0.1 calculate_structure_functions_single_pass(x, u, distance_bins; backend=SerialBackend()) + Profile.Allocs.@profile sample_rate=0.1 calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.SerialBackend()) allocs_serial_profile = Profile.Allocs.fetch() allocs_serial_txt = joinpath(profile_dir, "allocs_serial.txt") @@ -146,7 +147,7 @@ function main() println("Profiling memory allocations (Threaded)...") flush(stdout); flush(stderr) Profile.Allocs.clear() - Profile.Allocs.@profile sample_rate=0.1 calculate_structure_functions_single_pass(x, u, distance_bins; backend=ThreadedBackend()) + Profile.Allocs.@profile sample_rate=0.1 calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.ThreadedBackend()) allocs_threaded_profile = Profile.Allocs.fetch() allocs_threaded_txt = joinpath(profile_dir, "allocs_threaded.txt") diff --git a/benchmark/regimes.jl b/benchmark/regimes.jl new file mode 100644 index 0000000..3f4d3fc --- /dev/null +++ b/benchmark/regimes.jl @@ -0,0 +1,182 @@ +#!/usr/bin/env julia +# Stage 0 measurement harness: one row per (entry x shape x D x eltype x bin type x N x B x backend). +# +# Every later performance claim is a before/after row from this table. Output is both an aligned +# human table and a CSV under benchmark/benchmark_results/ so runs can be diffed. +# +# The plan's full cross-product is ~2.5e4 cells and N=1e5 alone is 5e9 pairs, so the matrix is +# expressed as SWEEPS: each sweep varies one axis against a fixed base point. Scale with env knobs. +# +# Usage: +# julia -t 32 --project=benchmark benchmark/regimes.jl +# SF_BENCH_SCALE=full julia -t 32 --project=benchmark benchmark/regimes.jl +# SF_BENCH_ONLY=dist_bins julia --project=benchmark benchmark/regimes.jl + +using ComputationalBackends: ComputationalBackends as CB +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, + StructureFunctionTypes as SFT, LinearBinEdges, LogBinEdges, InfPaddedBinEdges +using OhMyThreads: OhMyThreads # threaded extension +using KernelAbstractions: KernelAbstractions as KA # GPU(KA.CPU) parity backend +using Printf, Random, Dates + +const SCALE = get(ENV, "SF_BENCH_SCALE", "fast") +const ONLY = get(ENV, "SF_BENCH_ONLY", "") +const REPS = parse(Int, get(ENV, "SF_BENCH_REPS", "3")) +const OUTDIR = joinpath(@__DIR__, "benchmark_results") + +# --------------------------------------------------------------------------------------------- +# Timing. min-of-k after a warmup; allocations from a separate warmed call so the timing loop is +# not perturbed by @allocated. +# --------------------------------------------------------------------------------------------- +function measure(f, n_pairs::Real) + f() # warm (compile) + GC.gc() + best = Inf + for _ in 1:REPS + best = min(best, @elapsed f()) + end + bytes = @allocated f() + return (; seconds = best, bytes = bytes, + ns_per_pair = best * 1e9 / max(n_pairs, 1), pairs = n_pairs) +end + +# --------------------------------------------------------------------------------------------- +# Roofline. Measured triad bandwidth is the ceiling for the streaming half of the pair loop; the +# FLOP ceiling is measured with a dependency-free FMA chain. Reported so "speed of light" is a +# number and not a mood. +# --------------------------------------------------------------------------------------------- +function measured_triad_gbs(n = 1 << 24) + a = rand(Float64, n); b = rand(Float64, n); c = similar(a) + triad!() = (@inbounds @simd for i in eachindex(c); c[i] = a[i] + 3.0 * b[i]; end) + triad!() + t = Inf + for _ in 1:3 + t = min(t, @elapsed triad!()) + end + return 3 * n * sizeof(Float64) / t / 1e9 # 2 reads + 1 write +end + +# No FLOP ceiling is reported. The pair loop is bound by the digitize dependency chain and the +# histogram scatter, not by arithmetic throughput (benchmark/profile/open_issues.md §3 measured +# `@fastmath` at exactly 0% twice, because the scatter blocks vectorization). A peak-FLOP number +# would be a real measurement of an irrelevant ceiling, so it is deliberately absent. + +# --------------------------------------------------------------------------------------------- +# Inputs +# --------------------------------------------------------------------------------------------- +_bin(::Val{:linear}, ::Type{T}, nb) where {T} = LinearBinEdges(range(T(0), T(2); length = nb + 1)) +_bin(::Val{:log}, ::Type{T}, nb) where {T} = LogBinEdges(collect(T, 10 .^ range(T(-2), T(0.4); length = nb + 1))) +_bin(::Val{:infpad}, ::Type{T}, nb) where {T} = InfPaddedBinEdges(LinearBinEdges(range(T(0), T(2); length = nb + 1))) +_bin(::Val{:vector}, ::Type{T}, nb) where {T} = collect(T, range(T(0), T(2); length = nb + 1)) +_valbins(::Type{T}, nv) where {T} = LinearBinEdges(range(T(-3), T(3); length = nv + 1)) + +# UInt32 counts saturate at N = 92682 (see `_assert_counts_representable`); widen past that so the +# harness measures the kernel instead of tripping the guard. +_count_eltype(N) = N > 92_682 ? UInt64 : UInt32 + +const BACKENDS = Dict( + :serial => CB.SerialBackend(), + :threaded => CB.ThreadedBackend(), + :gpu_kacpu => CB.GPUBackend(KA.CPU()), +) + +const SFTYPE = SFT.L2SFType() + +# Each entry returns (closure, n_pairs). `B` is the auxiliary/batch extent (1 = point field). +function build_case(entry::Symbol, D::Int, ::Type{T}, binkind::Symbol, N::Int, B::Int, backend) where {T} + Random.seed!(1234) + nb, nv = 32, 16 + db = _bin(Val(binkind), T, nb) + vb = _valbins(T, nv) + ce = _count_eltype(N) + x = B == 1 ? rand(T, D, N) : rand(T, D, N) # shared positions when batched + u = B == 1 ? rand(T, D, N) : rand(T, D, N, B) + n_pairs = (N * (N - 1) ÷ 2) * B + kw = (; verbose = false, show_progress = false) + + f = if entry === :sf1d + () -> SFC.calculate_structure_function(SFTYPE, x, u, db, ce; backend = backend, + output_type = SF.StructureFunctionSumsAndCounts, kw...) + elseif entry === :joint2d + () -> SFC.calculate_structure_function(SFTYPE, x, u, db, vb; backend = backend, + count_eltype = ce, kw...) + elseif entry === :sp1d + () -> SFC.calculate_structure_functions_single_pass(x, u, db; backend = backend, + output_type = SF.StructureFunctionSumsAndCounts, count_eltype = ce) + elseif entry === :sp2d + () -> SFC.calculate_structure_functions_single_pass_2d(x, u, db, vb; backend = backend, + count_eltype = ce) + elseif entry === :tensor + () -> SFC.calculate_structure_function_tensor(Val(2), x, u, db; backend = backend, count_eltype = ce) + else + error("unknown entry $entry") + end + return f, n_pairs +end + +# --------------------------------------------------------------------------------------------- +# Sweeps: each varies ONE axis against the base point. +# --------------------------------------------------------------------------------------------- +const BASE = (; entry = :sf1d, D = 2, T = Float64, bin = :log, N = 2000, B = 1, backend = :serial) + +function sweeps() + small = SCALE == "fast" + Ns = small ? [500, 1000, 2000] : [1000, 3000, 10_000, 30_000] + return [ + # The default bin type is LogBinEdges, so its digitize cost is on the default path. + (:dist_bins, [merge(BASE, (; bin = b)) for b in (:linear, :log, :infpad, :vector)]), + (:eltype, [merge(BASE, (; T = t)) for t in (Float64, Float32)]), + (:dimension, [merge(BASE, (; D = d)) for d in (2, 3)]), + (:entry, [merge(BASE, (; entry = e)) for e in (:sf1d, :sp1d, :joint2d, :sp2d, :tensor)]), + (:scaling_N, [merge(BASE, (; N = n)) for n in Ns]), + (:batch_B, [merge(BASE, (; N = 400, B = b)) for b in (1, 8, 64)]), + (:backend, [merge(BASE, (; backend = k)) for k in (:serial, :threaded, :gpu_kacpu)]), + ] +end + +# --------------------------------------------------------------------------------------------- +# Run +# --------------------------------------------------------------------------------------------- +function main() + mkpath(OUTDIR) + stamp = Dates.format(Dates.now(), "yyyymmdd-HHMMSS") + csv = joinpath(OUTDIR, "regimes-$stamp.csv") + + gbs = measured_triad_gbs() + @printf("%s\nStage 0 regimes | julia %s | nthreads=%d | scale=%s reps=%d\n", + "="^118, VERSION, Threads.nthreads(), SCALE, REPS) + @printf("roofline (measured): triad %.1f GB/s single-core stream bandwidth\n%s\n", gbs, "="^118) + flush(stdout) + + open(csv, "w") do io + println(io, "sweep,entry,D,eltype,bins,N,B,backend,pairs,seconds,ns_per_pair,bytes,status") + for (name, cases) in sweeps() + (!isempty(ONLY) && String(name) != ONLY) && continue + @printf("\n--- sweep: %s ---\n", name) + @printf("%-8s %-8s %-2s %-8s %-7s %7s %4s %-10s %12s %10s %9s\n", + "entry", "", "D", "eltype", "bins", "N", "B", "backend", "pairs", "ns/pair", "MiB") + flush(stdout) + for c in cases + be = BACKENDS[c.backend] + label = @sprintf("%-8s %-8s %-2d %-8s %-7s %7d %4d %-10s", + c.entry, "", c.D, c.T, c.bin, c.N, c.B, c.backend) + try + f, np = build_case(c.entry, c.D, c.T, c.bin, c.N, c.B, be) + m = measure(f, np) + @printf("%s %12d %10.2f %9.2f\n", label, m.pairs, m.ns_per_pair, m.bytes / 2^20) + println(io, join((name, c.entry, c.D, c.T, c.bin, c.N, c.B, c.backend, + m.pairs, m.seconds, m.ns_per_pair, m.bytes, "ok"), ",")) + catch e + msg = first(split(sprint(showerror, e), '\n')) + @printf("%s %12s %10s %9s SKIP: %s\n", label, "-", "-", "-", first(msg, 60)) + println(io, join((name, c.entry, c.D, c.T, c.bin, c.N, c.B, c.backend, + 0, 0, 0, 0, "skip: " * replace(msg, "," => ";")), ",")) + end + flush(stdout); flush(io) + end + end + end + @printf("\n%s\nwrote %s\nDONE\n", "="^118, csv) +end + +main() diff --git a/docs/generate_assets/generate_assets.jl b/docs/generate_assets/generate_assets.jl index 296ba5b..5391572 100644 --- a/docs/generate_assets/generate_assets.jl +++ b/docs/generate_assets/generate_assets.jl @@ -5,6 +5,7 @@ Run from the repo root: julia --project=docs/generate_assets docs/generate_assets/generate_assets.jl """ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC using OhMyThreads: OhMyThreads # loads StructureFunctionsOhMyThreadsExt → enables ThreadedBackend using KernelAbstractions: KernelAbstractions as KA @@ -77,7 +78,7 @@ function generate_kolmogorov_figure() op = SF.SecondOrderStructureFunctionType() result = SF.calculate_structure_function(op, x, u, bins; - backend=SF.SerialBackend(), show_progress=false, verbose=false) + backend=CB.SerialBackend(), show_progress=false, verbose=false) sf2 = result.values rdist = bin_midpoints(result.distance) @@ -130,9 +131,9 @@ function generate_long_vs_trans_figure() op_T = SF.TransverseSecondOrderStructureFunctionType() res_L = SF.calculate_structure_function(op_L, x, u, bins; - backend=SF.SerialBackend(), show_progress=false, verbose=false) + backend=CB.SerialBackend(), show_progress=false, verbose=false) res_T = SF.calculate_structure_function(op_T, x, u, bins; - backend=SF.SerialBackend(), show_progress=false, verbose=false) + backend=CB.SerialBackend(), show_progress=false, verbose=false) sf_L = res_L.values sf_T = res_T.values @@ -173,10 +174,10 @@ function generate_parity_figure() op = SF.SecondOrderStructureFunctionType() res_serial = SF.calculate_structure_function(op, x, u, bins; - backend=SF.SerialBackend(), show_progress=false, verbose=false) + backend=CB.SerialBackend(), show_progress=false, verbose=false) res_thread = SF.calculate_structure_function(op, x, u, bins; - backend=SF.ThreadedBackend(), show_progress=false, verbose=false) + backend=CB.ThreadedBackend(), show_progress=false, verbose=false) sf_s = res_serial.values sf_t = res_thread.values @@ -273,7 +274,7 @@ function generate_single_pass_figure() # One O(N²) pass → NamedTuple of the six isotropic invariants; point-field input also # yields a `:helmholtz` entry (rotational/divergent decomposition). - res = SF.calculate_structure_functions_single_pass(x, u, bins; backend=SF.SerialBackend()) + res = SF.calculate_structure_functions_single_pass(x, u, bins; backend=CB.SerialBackend()) fig = CM.Figure(size=(900, 560), fontsize=14) CM.Label(fig[0, 1], @@ -338,14 +339,14 @@ function generate_2d_binning_figure() x, u = mk(N=2500) # Velocity-increment scale σ from L2(r); set per-order value ranges around it. l2 = SF.calculate_structure_function(SF.LongitudinalSecondOrderStructureFunctionType(), - x, u, dist_bins; backend=SF.SerialBackend(), show_progress=false, verbose=false) + x, u, dist_bins; backend=CB.SerialBackend(), show_progress=false, verbose=false) σ2 = maximum(filter(isfinite, l2.values)); σ = sqrt(σ2) seq(hi) = collect(range(0.0, hi; length=nval + 1)) # ≥0 (2nd order) sym(hi) = collect(range(-hi, hi; length=nval + 1)) # ± (3rd order) # One pass → all six joint histograms (per-invariant value bins, common bin count). value_bins = (seq(24σ2), seq(12σ2), seq(12σ2), sym(15σ^3), sym(15σ^3), sym(15σ^3)) res = SF.calculate_structure_functions_single_pass_2d(x, u, dist_bins, value_bins; - backend=SF.SerialBackend()) + backend=CB.SerialBackend()) for (col, (key, signed, lab)) in enumerate(invs) vmid = bin_midpoints(value_bins[col]) diff --git a/docs/generate_assets/generate_gpu_figures.jl b/docs/generate_assets/generate_gpu_figures.jl index 464f747..030f9bc 100644 --- a/docs/generate_assets/generate_gpu_figures.jl +++ b/docs/generate_assets/generate_gpu_figures.jl @@ -74,7 +74,7 @@ function _warn_gpu_jit_outliers!(f32, f64) n = r["N"] t32 = r["gpu_elapsed_s"] t64 = get(f64_by_n, n, nothing) - t64 === nothing && continue + isnothing(t64) && continue if t32 > 5 * t64 && t32 > 0.01 @warn "GPU Float32 at N=$n looks like JIT/outlier" gpu_f32_s=t32 gpu_f64_s=t64 hint="Re-run collect_benchmark_assets.jl (session warmup + median timing)." end diff --git a/docs/src/architecture.md b/docs/src/architecture.md index 799f45f..f8cb507 100644 --- a/docs/src/architecture.md +++ b/docs/src/architecture.md @@ -193,7 +193,7 @@ src/ ext/ ├── StructureFunctionsOhMyThreadsExt.jl # OhMyThreads integration ├── StructureFunctionsDistributedExt.jl # Distributed.jl integration -├── StructureFunctionsGPUExt.jl # KernelAbstractions integration +├── StructureFunctionsKernelAbstractionsExt.jl # KernelAbstractions integration ├── StructureFunctionsCairoMakieExt.jl # Plotting helpers └── gpu/ # GPU kernel organization ``` @@ -290,8 +290,8 @@ To add support for a new backend (e.g., `CUDABackend`): | `src/HelperFunctions.jl` | Binning, distance metrics, utils | | `src/Backends.jl` | Backend type definitions | | `ext/StructureFunctionsOhMyThreadsExt.jl` | OhMyThreads integration | -| `ext/StructureFunctionsDistributedExt.jl` | Distributed/SharedArrays integration | -| `ext/StructureFunctionsGPUExt.jl` | KernelAbstractions + GPU kernels | +| `ext/StructureFunctionsDistributedExt.jl` | Distributed.jl integration | +| `ext/StructureFunctionsKernelAbstractionsExt.jl` | KernelAbstractions + GPU kernels | | `ext/StructureFunctionsCairoMakieExt.jl` | Plotting helpers | | `src/__init__.jl` | Exports public types/functions | diff --git a/docs/src/backends.md b/docs/src/backends.md index d754fef..a8e4e2b 100644 --- a/docs/src/backends.md +++ b/docs/src/backends.md @@ -56,7 +56,7 @@ bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] result = SFC.calculate_structure_function( SFT.S2SFType(), x, u, bins; - backend=SFC.SerialBackend(), + backend=CB.SerialBackend(), show_progress=true ) @@ -81,7 +81,7 @@ counts = zeros(Float64, n_bins) SFC.calculate_structure_function!( sums, counts, SFT.S2SFType(), x, u, bins; - backend=SFC.SerialBackend() + backend=CB.SerialBackend() ) ``` @@ -130,7 +130,7 @@ bins = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)] result = SFC.calculate_structure_function( SFT.L2SFType(), x, u, bins; - backend=SFC.ThreadedBackend(), + backend=CB.ThreadedBackend(), show_progress=true ) ``` @@ -154,7 +154,7 @@ counts = zeros(Float64, n_bins) SFC.calculate_structure_function!( sums, counts, SFT.L2SFType(), x, u, bins; - backend=SFC.ThreadedBackend() + backend=CB.ThreadedBackend() ) ``` @@ -248,7 +248,7 @@ srun julia -p $((${SLURM_NNODES} * ${SLURM_CPUS_PER_TASK})) compute_sf.jl ### Definition GPU-accelerated computation using KernelAbstractions.jl. Production kernels live in -`StructureFunctionsGPUExt` (tiled pair histograms, UInt32 counts). See **[gpu.md](gpu.md)** +`StructureFunctionsKernelAbstractionsExt` (tiled pair histograms, UInt32 counts). See **[gpu.md](gpu.md)** for workspace reuse, slice batches, testing tiers, and benchmark regeneration. ### When to Use @@ -467,7 +467,7 @@ raw_bins = collect(exp.(range(log(0.01), log(10.0), length=51))) distance_bins = LogBinEdges(raw_bins) # Bypasses binary search bottleneck completely -results = SFC.calculate_structure_functions_single_pass(x, u, distance_bins; backend=SFC.ThreadedBackend()) +results = SFC.calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.ThreadedBackend()) ``` ### Profiling diff --git a/docs/src/examples.md b/docs/src/examples.md index 88e279b..ebffbed 100644 --- a/docs/src/examples.md +++ b/docs/src/examples.md @@ -32,7 +32,7 @@ x = rand(2, 4096) .* 1.0e4 # (D, N) coordinates u = randn(2, 4096) # (D, N) velocities bins = LogBinEdges(collect(exp10.(range(log10(50.0), log10(5.0e3); length = 41)))) -res = SFC.calculate_structure_functions_single_pass(x, u, bins; backend = SFC.AutoBackend()) +res = SFC.calculate_structure_functions_single_pass(x, u, bins; backend = CB.AutoBackend()) res.S2 # StructureFunction (averaged) for S2; also res.L2, res.T2, res.S3, res.L3, res.L1T2 res.helmholtz # HelmholtzDecomposition2D (rotational/divergent), point-field input only @@ -52,7 +52,7 @@ using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, Lo dist = LogBinEdges(collect(exp10.(range(log10(50.0), log10(5.0e3); length = 41)))) vbins = LinearBinEdges(collect(range(-5.0, 5.0; length = 51))) -sf2d = SFC.calculate_structure_function(SFT.L2SFType(), x, u, dist, vbins; backend = SFC.AutoBackend()) +sf2d = SFC.calculate_structure_function(SFT.L2SFType(), x, u, dist, vbins; backend = CB.AutoBackend()) sf2d.sums, sf2d.counts # (n_dist, n_val) joint histogram ``` @@ -65,7 +65,7 @@ once per pair and the batch axis is vectorized — far faster than looping `t`: sums = zeros(SFC.SINGLE_PASS_N, length(dist) - 1, length(vbins) - 1, T) counts = zeros(Int, size(sums)) SFC.calculate_structure_functions_single_pass_2d_batch!(sums, counts, x, u_batch, dist, vbins; - backend = SFC.AutoBackend()) + backend = CB.AutoBackend()) ``` See [Backends](backends.md) for choosing serial / threaded / distributed / GPU, and diff --git a/docs/src/extensions.md b/docs/src/extensions.md index ae4921f..1dfbcff 100644 --- a/docs/src/extensions.md +++ b/docs/src/extensions.md @@ -17,12 +17,11 @@ result = calculate_structure_function(sf, x, u, bins; backend = ThreadedBackend( ### Distributed -Loading `Distributed` and `SharedArrays` activates distributed CPU methods used by `DistributedBackend()`. +Loading `Distributed` activates the distributed CPU methods used by `DistributedBackend()`. ```julia using StructureFunctions using Distributed -using SharedArrays addprocs(4) result = calculate_structure_function(sf, x, u, bins; backend = DistributedBackend()) @@ -71,12 +70,11 @@ CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" -SharedArrays = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [extensions] StructureFunctionsCairoMakieExt = ["CairoMakie"] -StructureFunctionsDistributedExt = ["Distributed", "SharedArrays"] -StructureFunctionsGPUExt = ["KernelAbstractions"] +StructureFunctionsDistributedExt = ["Distributed"] +StructureFunctionsKernelAbstractionsExt = ["KernelAbstractions"] StructureFunctionsOhMyThreadsExt = ["OhMyThreads"] ``` diff --git a/docs/src/gpu.md b/docs/src/gpu.md index 1e629c7..0016b19 100644 --- a/docs/src/gpu.md +++ b/docs/src/gpu.md @@ -1,7 +1,7 @@ # GPU acceleration guide StructureFunctions.jl provides GPU structure-function kernels via -[`StructureFunctionsGPUExt`](@ref) (loaded when `KernelAbstractions.jl` is available). +[`StructureFunctionsKernelAbstractionsExt`](@ref) (loaded when `KernelAbstractions.jl` is available). This guide covers production APIs: single snapshots, workspace reuse, and time-slice batches. For backend selection across serial / threaded / distributed / GPU, see [backends.md](backends.md). diff --git a/docs/src/index.md b/docs/src/index.md index fd589d8..9a9ec72 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -34,7 +34,7 @@ u = randn(2, 2048) # (D, N) velocity components bins = LogBinEdges(collect(exp10.(range(log10(50.0), log10(5.0e3); length = 41)))) # Second-order longitudinal SF, averaged S₂(r): -sf = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = SFC.AutoBackend()) +sf = SFC.calculate_structure_function(SFT.L2SFType(), x, u, bins; backend = CB.AutoBackend()) sf.distance, sf.values # All six invariants (+ Helmholtz) in one pass: @@ -60,5 +60,5 @@ Pkg.add(url = "https://github.com/jbphyswx/StructureFunctions.jl.git") ``` Optional backends/visualization load via package extensions when you bring their trigger packages -(`OhMyThreads`, `Distributed` + `SharedArrays`, `KernelAbstractions` + `CUDA`, `MPI`, `CairoMakie`); +(`OhMyThreads`, `Distributed`, `KernelAbstractions` + `CUDA`, `MPI`, `CairoMakie`); see [Extensions](extensions.md). diff --git a/docs/src/theory.md b/docs/src/theory.md index 45a32da..e4023f4 100644 --- a/docs/src/theory.md +++ b/docs/src/theory.md @@ -7,6 +7,7 @@ This document explains the mathematical foundation of structure functions and ho - [Longitudinal vs Transverse](#longitudinal-vs-transverse) - [Order](#order) - [Dimensional Variants](#dimensional-variants) +- [Curved Geometry: Structure Functions on a Sphere](#curved-geometry-structure-functions-on-a-sphere) - [Kolmogorov Theory](#kolmogorov-theory) - [References](#references) @@ -107,6 +108,92 @@ For full 3D velocity fields $(u_x, u_y, u_z)$: - **Projected SF**: Projects onto specific directions (e.g., vertical, meridional) - Flexibility for analyzing anisotropic flows +## Curved Geometry: Structure Functions on a Sphere + +Everything above assumes flat space: $\hat{r} = \vec{r}/|\vec{r}|$ is a single vector, and $\Delta\vec{u}$ +is a plain difference of two velocity vectors. On a sphere neither holds. The two points have +*different* tangent planes, so "the separation direction" is two different vectors, and subtracting +velocities that live in different tangent spaces is not defined. + +### The transported frame + +The separation is the great-circle arc. With $\hat{p}, \hat{q}$ the unit position vectors, +$c = \hat{p}\cdot\hat{q}$, $\vec{w} = \hat{p}\times\hat{q}$, $s = |\vec{w}| = \sin\sigma$: + +$$\sigma = 2\,\mathrm{atan2}\!\left(|\hat{q}-\hat{p}|,\ |\hat{q}+\hat{p}|\right), \qquad r = R\sigma$$ + +$$\hat{t}_A = \frac{\hat{q} - c\,\hat{p}}{s}, \qquad + \hat{t}_B = \frac{c\,\hat{q} - \hat{p}}{s}, \qquad + \hat{m} = \frac{\vec{w}}{s}$$ + +$\hat{t}_A$ and $\hat{t}_B$ are the geodesic tangents at each endpoint, and $\hat{m}$ is the +great-circle normal. Two facts make this cheap: $|\hat{q}-c\hat{p}|^2 = |c\hat{q}-\hat{p}|^2 = s^2$, +so one reciprocal square root normalises both; and $\hat{m}$ is **the same vector at both endpoints**, +so the transverse direction needs no transport at all. + +The increments are then + +$$\delta u_L = \vec{u}_B\cdot\hat{t}_B - \vec{u}_A\cdot\hat{t}_A, \qquad + \delta u_T = (\vec{u}_B - \vec{u}_A)\cdot\hat{m}$$ + +Projecting each velocity onto its *own* geodesic frame before differencing **is** parallel transport, +not an approximation: a geodesic parallel-transports its own tangent, and transport on $S^2$ is an +orientation-preserving isometry, so the frame carried from $A$ arrives at $B$ rotated by exactly the +difference of forward azimuths. + +### Why a flat frame is wrong, and by how much + +Using one flat direction for both endpoints ignores the **meridian convergence** — the angle $\psi$ +between the two local frames: + +$$\psi \approx \frac{r}{R}\tan\varphi$$ + +| separation | latitude | $\psi$ | +|---|---|---| +| 100 km | 45° | 0.9° | +| 1000 km | 45° | 9° | +| 1000 km | 70° | 25° | + +$D_{LT}$ vanishes identically under reflection symmetry, so this leaks $O(\psi)\,(D_{TT}-D_{LL})/2$ +into a quantity whose true value is zero, and the third-order cascade diagnostics $D_{LLL}$, $D_{LTT}$ +inherit $O(\psi)$. It is the same pathology as spurious B-modes from flat-sky projection in weak +lensing. A direct measurement of the effect: for a solid-body rotation — which has *no* strain, so +$D_{LL}$ must vanish at every separation — the transported frame gives $\Sigma D_{LL}/\Sigma S_2 +\approx 5\times10^{-32}$, while a flat lon/lat frame puts **36% of the total signal** into $D_{LL}$. + +**Guidance:** below ~10 km a flat tangent plane is fine; beyond ~100 km, or anywhere poleward of +about 60°, use a spherical metric. + +### Conventions and limits + +- **Radial component.** For a thin shell ($D = 3$, $u = (\text{east},\text{north},\text{up})$) the + radial component is differenced as a scalar and never transported: the geodesic frame is tangent to + the shell, hence orthogonal to $\hat{p}$ at both endpoints, so radial motion cannot leak into + $\delta u_L$ or $\delta u_T$. Ambient-transporting the full 3-vector would leak radial into + tangential at $O(r/R)$ — a *first*-order error. +- **Coordinates.** A point on a shell is located by two numbers. `x` is `(2, N)` lon/lat while `u` may + be `(2, N)` or `(3, N)`; the shell radius belongs to the metric, not to each point. +- **Angle units follow the metric.** `Distances.Haversine` is degrees, `Distances.SphericalAngle` is + radians. Mixing them rescales every separation by ~57. +- **Handedness.** $\hat{n} = \hat{z}\times\hat{r}$, so $(\hat{r},\hat{n},\hat{z})$ is right-handed. +- **Degenerate pairs are excluded.** Coincident points have no direction, and antipodal points are + joined by infinitely many great circles, so parallel transport is genuinely non-unique. Both are + masked out rather than producing a NaN. +- **Precision.** Sub-metre separations on Earth need `Float64` input: at 45°, one `Float32` ulp of + latitude is already ~4 m on the ground. +- **Isotropy relations are planar.** `KHM.jl`'s `transverse_incompressibility_residual` + ($D_{TT} = \mathrm{d}(rD_{LL})/\mathrm{d}r$, Lindborg 1999 eq. 53) is a *planar* isotropic relation + and holds on the sphere only to $O((r/R)^2)$. + +### What the literature does + +Published velocity-SF work is almost entirely regional ($\lesssim 500$ km), where $\psi$ is +negligible, and works in a local tangent plane: Balwada, LaCasce & Speer (2016) define +$\vec{r} = \Delta x\,\hat{i} + \Delta y\,\hat{j}$; `FluidSF` uses a great-circle distance for the +*scalar separation only* and then rotates with a flat grid-space angle. The transported-frame +convention adopted here is the one established in CMB polarization and weak-lensing shear +$\xi_\pm$, which face the identical problem. + ## Kolmogorov Theory ### The Inertial Range @@ -159,6 +246,23 @@ where $\delta_n > 0$ represents intermittency. These corrections are significant 6. **Skamarock, W. C., et al. (2019).** "A Description of the Advanced Research WRF Version 4." NCAR Technical Note. - Structure functions used in validation of weather model turbulence. +### Curved Geometry + +8. **Kamionkowski, M., Kosowsky, A., & Stebbins, A. (1997).** "Statistics of cosmic microwave background polarization." *Physical Review D*, 55, 7368. + - Establishes the transported-frame convention for two-point vector statistics on a sphere; flat-sky projection is documented to produce spurious B-modes, the same failure mode as spurious $D_{LT}$. + +9. **Absil, P.-A., Mahony, R., & Sepulchre, R. (2008).** *Optimization Algorithms on Matrix Manifolds.* Princeton University Press, Ex. 8.1.1. + - Closed-form parallel transport on $S^2$. + +10. **Aluie, H. (2019).** "Convolutions on the sphere: commutation with differential operators." *GEM — International Journal on Geomathematics*, 10, 9. [doi:10.1007/s13137-019-0123-9](https://doi.org/10.1007/s13137-019-0123-9) + - Prop. 2: normal/tangent character is preserved, which is why the radial component is differenced rather than transported. + +11. **Lindborg, E. (1999).** "Can the atmospheric kinetic energy spectrum be explained by two-dimensional turbulence?" *Journal of Fluid Mechanics*, 388, 259–288. [doi:10.1017/S0022112099004851](https://doi.org/10.1017/S0022112099004851) + - §5 longitudinal–transverse–vertical convention; eq. 53 the planar isotropy relation. + +12. **Balwada, D., LaCasce, J. H., & Speer, K. G. (2016).** "Scale-dependent distribution of kinetic energy from surface drifters in the Gulf of Mexico." *Geophysical Research Letters*, 43. [doi:10.1002/2016GL069405](https://doi.org/10.1002/2016GL069405) + - Representative of the local-tangent-plane convention used in regional studies. + ### Multifractal & Intermittency 7. **She, Z. S., & Leveque, E. (1994).** "Universal dimensionality of intermittent structures in fully developed turbulence." *Physical Review Letters*, 72, 336. diff --git a/examples/distributed_parallel.jl b/examples/distributed_parallel.jl index 7eafd6a..a291688 100644 --- a/examples/distributed_parallel.jl +++ b/examples/distributed_parallel.jl @@ -7,6 +7,7 @@ Run from package root: julia --project=examples examples/distributed_parallel.jl 4 """ +using ComputationalBackends: ComputationalBackends as CB using Distributed: Distributed using StructureFunctions: StructureFunctions as SF @@ -28,7 +29,7 @@ result = @time SF.calculate_structure_function( x, u, bins; - backend = SF.DistributedBackend(), + backend = CB.DistributedBackend(), show_progress = false, verbose = false, ) diff --git a/examples/simple_2d.jl b/examples/simple_2d.jl index 88f39d6..f5fef55 100644 --- a/examples/simple_2d.jl +++ b/examples/simple_2d.jl @@ -7,6 +7,7 @@ Run from package root: julia --project=examples examples/simple_2d.jl """ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF using Statistics: Statistics using CairoMakie: CairoMakie as CM @@ -36,7 +37,7 @@ println(" Mean velocity: $(round.(Statistics.mean(u; dims = 1); digits = 2)) m/ println(" Velocity std: $(round.(Statistics.std(u; dims = 1); digits = 2)) m/s") operator = SF.FullVectorStructureFunctionType{Float64}(order = 2) -backend = SF.SerialBackend() +backend = CB.SerialBackend() r_min = 10.0 r_max = grid_size * spacing / 2 diff --git a/examples/single_pass.jl b/examples/single_pass.jl index d3ffd93..b6eb57c 100644 --- a/examples/single_pass.jl +++ b/examples/single_pass.jl @@ -8,6 +8,7 @@ Run from the package root: julia --project=examples examples/single_pass.jl """ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC using Random: Random using CairoMakie: CairoMakie as CM @@ -27,7 +28,7 @@ println("Single pass over N=$N points, $(length(edges) - 1) distance bins...") # Averaged invariants (default output_type = StructureFunction). One pass returns a NamedTuple # keyed by invariant; point-field input also yields a `:helmholtz` entry. -res = SFC.calculate_structure_functions_single_pass(x, u, bins; backend = SFC.AutoBackend()) +res = SFC.calculate_structure_functions_single_pass(x, u, bins; backend = CB.AutoBackend()) println("Invariants returned: ", keys(res)) @assert haskey(res, :helmholtz) "point-field input should include the Helmholtz decomposition" diff --git a/examples/threaded_calculation.jl b/examples/threaded_calculation.jl index 9805ae9..acd67fb 100644 --- a/examples/threaded_calculation.jl +++ b/examples/threaded_calculation.jl @@ -7,6 +7,7 @@ Run from package root: JULIA_NUM_THREADS=4 julia --project=examples examples/threaded_calculation.jl """ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF using Base.Threads: Threads @@ -24,7 +25,7 @@ serial_time = @elapsed begin x, u, bins; - backend = SF.SerialBackend(), + backend = CB.SerialBackend(), show_progress = false, verbose = false, ) @@ -38,7 +39,7 @@ if Threads.nthreads() > 1 x, u, bins; - backend = SF.ThreadedBackend(), + backend = CB.ThreadedBackend(), show_progress = false, verbose = false, ) @@ -49,5 +50,5 @@ if Threads.nthreads() > 1 println("Speedup: $(round(serial_time / threaded_time; digits = 2))x") println("Pairs counted: $(sum(threaded_result.counts))") else - println("Run with JULIA_NUM_THREADS>1 to use SF.ThreadedBackend().") + println("Run with JULIA_NUM_THREADS>1 to use CB.ThreadedBackend().") end diff --git a/ext/StructureFunctionsCUDAExt.jl b/ext/StructureFunctionsCUDAExt.jl index fb92d03..4555242 100644 --- a/ext/StructureFunctionsCUDAExt.jl +++ b/ext/StructureFunctionsCUDAExt.jl @@ -4,7 +4,7 @@ CUDA-specialized fast structure-function kernels. Loaded automatically when **both** `KernelAbstractions` and `CUDA` are present. Provides the settled-optimal GPU kernels (N-body broadcast + privatized / dynamic-shared histograms) for NVIDIA GPUs, overriding the portable -KernelAbstractions tiled kernels in `StructureFunctionsGPUExt` (which remain the +KernelAbstractions tiled kernels in `StructureFunctionsKernelAbstractionsExt` (which remain the CPU/AMD reference). See `gpu/OPTIMAL_KERNEL_DESIGN.md`. These kernels use CUDA-only intrinsics not exposed by KernelAbstractions: @@ -15,7 +15,7 @@ specialized path while the CPU backend stays on the KA kernels. The pure, device-callable building blocks (`_sf_moments`, `_sf_dot`, `_gpu_digitize_value_plan`, digitizer functors, value plans) live in -`StructureFunctionsGPUExt`; this extension reuses them via `GE` so there is a +`StructureFunctionsKernelAbstractionsExt`; this extension reuses them via `GE` so there is a single source of truth for the per-pair math and binning. """ module StructureFunctionsCUDAExt @@ -24,15 +24,16 @@ using CUDA: CUDA, CuStaticSharedArray, CuDynamicSharedArray, @cuda, threadIdx, blockIdx, blockDim, sync_threads using KernelAbstractions: KernelAbstractions as KA using StaticArrays: StaticArrays as SA -using StructureFunctions: StructureFunctions as SF, Calculations as SFC +using StructureFunctions: StructureFunctions as SF, Calculations as SFC, + HelperFunctions as SFH # The GPU (KernelAbstractions) extension owns the shared device-callable building # blocks and the digitizer / value-plan types. It is triggered by # KernelAbstractions alone, so it is loaded whenever this extension's triggers # (KernelAbstractions + CUDA) are satisfied. -const GE = let m = Base.get_extension(SF, :StructureFunctionsGPUExt) - m === nothing && - error("StructureFunctionsCUDAExt: StructureFunctionsGPUExt must be loaded first " * +const GE = let m = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) + isnothing(m) && + error("StructureFunctionsCUDAExt: StructureFunctionsKernelAbstractionsExt must be loaded first " * "(load KernelAbstractions before / with CUDA).") m end @@ -47,19 +48,31 @@ include(joinpath(@__DIR__, "cuda", "kernels_1d.jl")) function SFC.gpu_fast_launch_2d_batch!( ::CUDA.CUDABackend, out, cnt, x, u, sf_type, dist_dig, val_plan, - N, n_dist, n_val, B, D, nmom, fixed_x, + N, n_dist, n_val, B, D, nmom, fixed_x, geom, ) return _cuda_launch_2d!(out, cnt, x, u, sf_type, dist_dig, val_plan, Int(N), Int(n_dist), Int(n_val), Int(B), - Int(D), Int(nmom), fixed_x) + Int(D), Int(nmom), fixed_x, geom) end function SFC.gpu_fast_launch_1d_batch!( ::CUDA.CUDABackend, out, cnt, x, u, sf_type, dist_dig, - N, NB, B, D, nmom, fixed_x, + N, NB, B, D, nmom, fixed_x, geom, ) return _cuda_launch_1d!(out, cnt, x, u, sf_type, dist_dig, - Int(N), Int(NB), Int(B), Int(D), Int(nmom), fixed_x) + Int(N), Int(NB), Int(B), Int(D), Int(nmom), fixed_x, geom) +end + +# Real device numbers instead of the universal floor. Reached only through the CUDABackend hook, so +# a device exists by construction and a query failure is a genuine driver fault, not a fallback. +function SFC.gpu_device_caps(::CUDA.CUDABackend) + dev = CUDA.device() + return SFC.GPUDeviceCaps( + Int(CUDA.attribute(dev, CUDA.DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN)), + Int(CUDA.attribute(dev, CUDA.DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR)), + Int(CUDA.attribute(dev, CUDA.DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)), + Int(CUDA.warpsize(dev)), + ) end end # module diff --git a/ext/StructureFunctionsDistributedExt.jl b/ext/StructureFunctionsDistributedExt.jl index dec2327..270fc47 100644 --- a/ext/StructureFunctionsDistributedExt.jl +++ b/ext/StructureFunctionsDistributedExt.jl @@ -6,35 +6,16 @@ module StructureFunctionsDistributedExt using Distributed: Distributed using ProgressMeter: ProgressMeter as PM using Distances: Distances as DI -using StaticArrays: StaticArrays as SA -using LinearAlgebra: LinearAlgebra as LA -using SharedArrays: SharedArrays +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, - HelperFunctions as SFH, StructureFunctionTypes as SFT, - StructureFunctionObjects as SFO, + StructureFunctionTypes as SFT, StructureFunctionObjects as SFO, AbstractBinEdges, LinearBinEdges, LogBinEdges SFC.distributed_workers_available(::Val{:distributed}) = Distributed.nworkers() > 1 -# Balanced outer-index order for the triangular pair loop (work for index i is ~ N - i). -# `@distributed` splits its iterable into CONTIGUOUS per-worker blocks, so iterating 1:N -# directly gives worker 1 all the expensive low-i pairs (~2x imbalance). Interleaving -# high/low indices ([1, N, 2, N-1, ...]) makes every contiguous block carry ~equal work. -function _balanced_triangle_perm(N::Integer) - perm = Vector{Int}(undef, N) - lo, hi, k = 1, N, 1 - @inbounds while lo <= hi - perm[k] = lo; k += 1; lo += 1 - if lo <= hi - perm[k] = hi; k += 1; hi -= 1 - end - end - return perm -end - # --- Non-Mutating 1D Dispatch (returns the raw accumulator; public boundary finalizes) --- function SFC._dispatch_execution_backend( - db::SFC.DistributedBackend, + db::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, @@ -47,22 +28,21 @@ function SFC._dispatch_execution_backend( x_vecs, u_vecs, distance_bins; - inner = db.inner, + inner = CB.local_backend(db), kwargs..., ) end function SFC._dispatch_execution_backend( - db::SFC.DistributedBackend, + db::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_arr::AbstractMatrix, u_arr::AbstractMatrix, distance_bins::AbstractVector; kwargs..., ) - N_dims = size(x_arr, 1) - x_vecs = ntuple(k -> view(x_arr, k, :), N_dims) - u_vecs = ntuple(k -> view(u_arr, k, :), N_dims) + x_vecs = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_vecs = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return SFC._dispatch_execution_backend( db, structure_function_type, @@ -82,7 +62,7 @@ function _parallel_calculate_structure_function_core( verbose = true, show_progress = true, count_eltype::Type{CT} = UInt32, - inner::SFC.AbstractExecutionBackend = SFC.SerialBackend(), + inner::CB.AbstractLocalBackend = CB.SerialBackend(), kwargs..., ) where {CT} if verbose @@ -129,7 +109,7 @@ end end function SFC._dispatch_execution_backend( - db::SFC.DistributedBackend, + db::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x::AbstractArray, u::AbstractArray, @@ -141,7 +121,7 @@ function SFC._dispatch_execution_backend( backend = nothing, kwargs..., ) where {CT} - verbose && @info("calculating batched structure function (distributed over batch axis, inner=$(nameof(typeof(db.inner))))") + verbose && @info("calculating batched structure function (distributed over batch axis, inner=$(nameof(typeof(CB.local_backend(db)))))") D, N = size(u, 1), size(u, 2) bdims = size(u)[3:end] B = prod(bdims) @@ -149,19 +129,20 @@ function SFC._dispatch_execution_backend( u_flat = reshape(u, D, N, B) x_flat = fixed_x ? x : reshape(x, D, N, B) nb = SFC.n_histogram_bins(distance_bins) - inner = db.inner + inner = CB.local_backend(db) chunks = _dist_batch_chunks(B, Distributed.nworkers()) - # each worker computes its contiguous b-chunk locally via the inner backend, requesting the - # raw accumulator so partials can be concatenated; the public boundary finalizes. - parts = Distributed.pmap(chunks) do bc - usub = u_flat[:, :, bc] - xsub = fixed_x ? x_flat : x_flat[:, :, bc] + # Each worker computes its contiguous b-chunk locally via the inner backend, requesting the raw + # accumulator so partials can be concatenated; the public boundary finalizes. The b-slice is the + # pmap ITEM, not a closure capture: `pmap` re-serializes the closure on every `remotecall`, so + # capturing `u_flat` would ship the whole batch to every worker instead of its own 1/nw share. + items = [(fixed_x ? x_flat : x_flat[:, :, bc], u_flat[:, :, bc]) for bc in chunks] + parts = Distributed.pmap(items) do xu r = SFC.calculate_structure_function( - structure_function_type, xsub, usub, distance_bins; + structure_function_type, xu[1], xu[2], distance_bins, count_eltype; backend = inner, output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, - distance_metric = distance_metric, count_eltype = count_eltype, + distance_metric = distance_metric, ) (r.sums, r.counts) end @@ -182,7 +163,7 @@ end # --- Auto-Binning 1D Dispatch --- function SFC._dispatch_execution_backend( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, @@ -221,7 +202,7 @@ function SFC._dispatch_execution_backend( end return SFC._dispatch_execution_backend( - SFC.DistributedBackend(), + CB.DistributedBackend(), structure_function_type, x_vecs, u_vecs, @@ -235,7 +216,7 @@ end # --- Non-Mutating 2D Dispatch --- function SFC._dispatch_execution_backend( - ::SFC.DistributedBackend, + db::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, @@ -252,33 +233,23 @@ function SFC._dispatch_execution_backend( @info("calculating 2D joint structure function (distributed reduction)") end - # Round-robin the balanced triangle permutation across workers (an interleaved subset of a - # balance-ordered list stays load-balanced); each worker accumulates its i's into a local 2D - # buffer, then we sum the partials into a preallocated typed buffer. (Same rationale as the 1D - # core: avoids `@distributed (+)`'s `Any`-typed reduction / the return-type assertion.) + # Each worker accumulates its stride-`nw` share of the outer indices into a local 2D buffer, + # then we sum the partials into a preallocated typed buffer. (Same rationale as the 1D core: + # avoids `@distributed (+)`'s `Any`-typed reduction / the return-type assertion.) N = length(x_vecs[1]) nw = max(1, Distributed.nworkers()) - perm = _balanced_triangle_perm(N) - chunks = [perm[w:nw:length(perm)] for w in 1:nw] + chunks = SFC._balanced_index_chunks(N, nw) - D = length(x_vecs) - vD = Val(D) nd = SFC.n_histogram_bins(distance_bins) nv = SFC.n_histogram_bins(value_bins) OT = promote_type(float(eltype(x_vecs[1])), float(eltype(u_vecs[1]))) - dist_be = SFC.BinEdges(distance_bins) - val_be = SFC.BinEdges(value_bins) + inner = CB.local_backend(db) partials = Distributed.pmap(chunks) do ichunk - ls = zeros(OT, nd, nv) - lc = zeros(CT, nd, nv) - for i in ichunk - SFC.calculate_structure_function_2d_i!( - ls, lc, vD, structure_function_type, i, x_vecs, u_vecs, dist_be, val_be; - distance_metric = distance_metric, - ) - end - (ls, lc) + SFC._partial_2d_sums_counts( + inner, structure_function_type, x_vecs, u_vecs, distance_bins, value_bins, ichunk; + distance_metric = distance_metric, count_eltype = CT, + ) end sums = zeros(OT, nd, nv) @@ -291,7 +262,7 @@ function SFC._dispatch_execution_backend( end function SFC._dispatch_execution_backend( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_arr::AbstractMatrix, u_arr::AbstractMatrix, @@ -299,11 +270,10 @@ function SFC._dispatch_execution_backend( value_bins::AbstractVector; kwargs..., ) - N_dims = size(x_arr, 1) - x_vecs = ntuple(k -> view(x_arr, k, :), N_dims) - u_vecs = ntuple(k -> view(u_arr, k, :), N_dims) + x_vecs = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_vecs = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return SFC._dispatch_execution_backend( - SFC.DistributedBackend(), + CB.DistributedBackend(), structure_function_type, x_vecs, u_vecs, @@ -315,7 +285,7 @@ end # --- Single Pass Dispatch --- function SFC._dispatch_single_pass( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}; @@ -324,54 +294,31 @@ function SFC._dispatch_single_pass( kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} OT = promote_type(float(FT1), float(FT2)) - n_bins = length(distance_bins) - 1 + n_bins = SFC.n_histogram_bins(distance_bins) n_points = size(x, 2) - D = size(x, 1) - vD = Val(D) - - combined_reduced = Distributed.@distributed (+) for i in _balanced_triangle_perm(n_points) - local_combined = zeros(Float64, 2 * SFC.SINGLE_PASS_N, n_bins) - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i+1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) - - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i - - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_T2 = SFH.transverse_norm2(du, rh) - - local_combined[1, bin_idx] += du_L2 + du_T2 - local_combined[2, bin_idx] += du_L2 - local_combined[3, bin_idx] += du_T2 - local_combined[4, bin_idx] += du_L * (du_L2 + du_T2) - local_combined[5, bin_idx] += du_L * du_L2 - local_combined[6, bin_idx] += du_L * du_T2 - - for t in (SFC.SINGLE_PASS_N + 1):(2 * SFC.SINGLE_PASS_N) - local_combined[t, bin_idx] += 1.0 - end - end - end - local_combined + + # One accumulator per worker chunk, not per outer index: the old `@distributed (+)` body + # allocated a (12, n_bins) matrix for every `i` and reduced O(N) full matrices. Chunks also let + # each worker take the SIMD kernel, and the accumulator is typed from the inputs. + chunks = SFC._balanced_index_chunks(n_points, max(1, Distributed.nworkers())) + partials = Distributed.pmap(chunks) do ch + SFC._partial_single_pass_1d( + x, u, distance_bins, ch; + distance_metric = distance_metric, count_eltype = CT, + ) end - - sums = OT.(combined_reduced[1:SFC.SINGLE_PASS_N, :]) - counts = CT.(combined_reduced[(SFC.SINGLE_PASS_N + 1):(2 * SFC.SINGLE_PASS_N), :]) + sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins) + counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins) + for (s, c) in partials + sums .+= s + counts .+= c + end return (sums = sums, counts = counts) # raw 6-row; public wrapper adds Helmholtz once end function SFC._dispatch_single_pass_2d( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}, @@ -381,66 +328,32 @@ function SFC._dispatch_single_pass_2d( kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} OT = promote_type(float(FT1), float(FT2)) - n_bins = length(distance_bins) - 1 - vb0 = SFC._sp2d_value_bin_at(value_bins, 1) - n_val = length(vb0) - 1 + n_bins = SFC.n_histogram_bins(distance_bins) + n_val = length(SFC._sp2d_value_bin_at(value_bins, 1)) - 1 n_points = size(x, 2) - D = size(x, 1) - vD = Val(D) - - combined_reduced = Distributed.@distributed (+) for i in _balanced_triangle_perm(n_points) - local_combined = zeros(Float64, 2 * SFC.SINGLE_PASS_N, n_bins, n_val) - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) - - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i - - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_T = SFH.mδu_t(du, rh) - - du_L2 = du_L * du_L - du_T2 = SFH.transverse_norm2(du, rh) - - vals = ( - du_L2 + du_T2, - du_L2, - du_T2, - du_L * (du_L2 + du_T2), - du_L * du_L2, - du_L * du_T2, - ) - - for t in 1:SFC.SINGLE_PASS_N - vb = SFC._sp2d_value_bin_at(value_bins, t) - vbin = SFH.digitize(vals[t], vb) - n_val_t = length(vb) - 1 - if 1 <= vbin <= n_val_t && vbin <= n_val - local_combined[t, bin_idx, vbin] += vals[t] - local_combined[t + SFC.SINGLE_PASS_N, bin_idx, vbin] += 1.0 - end - end - end - end - local_combined + + # One accumulator per worker chunk, not per outer index: the old `@distributed (+)` body + # allocated a (12, n_bins, n_val) matrix for every `i` and reduced O(N) of them. + chunks = SFC._balanced_index_chunks(n_points, max(1, Distributed.nworkers())) + partials = Distributed.pmap(chunks) do ch + SFC._partial_single_pass_2d( + x, u, distance_bins, value_bins, ch; + distance_metric = distance_metric, count_eltype = CT, + ) end - sums = OT.(combined_reduced[1:SFC.SINGLE_PASS_N, :, :]) - counts = CT.(combined_reduced[(SFC.SINGLE_PASS_N + 1):(2 * SFC.SINGLE_PASS_N), :, :]) + sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins, n_val) + counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins, n_val) + for (s, c) in partials + sums .+= s + counts .+= c + end return sums, counts end # --- Mutating 1D Dispatch --- function SFC._dispatch_execution_backend!( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, sums::AbstractVector{OT}, counts::AbstractVector{CT}, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, @@ -450,7 +363,7 @@ function SFC._dispatch_execution_backend!( kwargs..., ) where {OT, CT} result = SFC._dispatch_execution_backend( - SFC.DistributedBackend(), + CB.DistributedBackend(), structure_function_type, x_vecs, u_vecs, @@ -463,7 +376,7 @@ function SFC._dispatch_execution_backend!( end function SFC._dispatch_execution_backend!( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, sums::AbstractVector{OT}, counts::AbstractVector{CT}, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, @@ -472,11 +385,10 @@ function SFC._dispatch_execution_backend!( distance_bins::AbstractVector; kwargs..., ) where {OT, CT, FT1 <: Number, FT2 <: Number} - N_dims = size(x_arr, 1) - x_tuple = ntuple(k -> view(x_arr, k, :), N_dims) - u_tuple = ntuple(k -> view(u_arr, k, :), N_dims) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return SFC._dispatch_execution_backend!( - SFC.DistributedBackend(), + CB.DistributedBackend(), sums, counts, structure_function_type, @@ -489,7 +401,7 @@ end # --- Mutating 2D Dispatch --- function SFC._dispatch_execution_backend!( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, sums_2d::AbstractMatrix{OT}, counts_2d::AbstractMatrix{CT}, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, @@ -500,7 +412,7 @@ function SFC._dispatch_execution_backend!( kwargs..., ) where {OT, CT} result = SFC._dispatch_execution_backend( - SFC.DistributedBackend(), + CB.DistributedBackend(), structure_function_type, x_vecs, u_vecs, @@ -514,7 +426,7 @@ function SFC._dispatch_execution_backend!( end function SFC._dispatch_execution_backend!( - ::SFC.DistributedBackend, + ::CB.AbstractDistributedBackend, sums_2d::AbstractMatrix{OT}, counts_2d::AbstractMatrix{CT}, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, @@ -524,11 +436,10 @@ function SFC._dispatch_execution_backend!( value_bins::AbstractVector; kwargs..., ) where {OT, CT, FT1 <: Number, FT2 <: Number} - N_dims = size(x_arr, 1) - x_tuple = ntuple(k -> view(x_arr, k, :), N_dims) - u_tuple = ntuple(k -> view(u_arr, k, :), N_dims) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return SFC._dispatch_execution_backend!( - SFC.DistributedBackend(), + CB.DistributedBackend(), sums_2d, counts_2d, structure_function_type, diff --git a/ext/StructureFunctionsGPUExt.jl b/ext/StructureFunctionsKernelAbstractionsExt.jl similarity index 82% rename from ext/StructureFunctionsGPUExt.jl rename to ext/StructureFunctionsKernelAbstractionsExt.jl index 68f35eb..f662321 100644 --- a/ext/StructureFunctionsGPUExt.jl +++ b/ext/StructureFunctionsKernelAbstractionsExt.jl @@ -40,11 +40,12 @@ fast paths; plain `Vector` inputs use the general kernel with no layout inferenc these macros currently fail to resolve correctly when called as `KA.@index`, etc. `@Const` is only valid on **kernel** parameter lists, not on host `@inline` helpers. """ -module StructureFunctionsGPUExt +module StructureFunctionsKernelAbstractionsExt using KernelAbstractions: KernelAbstractions as KA, @index, @atomic, @Const, @localmem, @private, @uniform, @synchronize using StaticArrays: StaticArrays as SA using Distances: Distances as DI +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, HelperFunctions as SFH, StructureFunctionTypes as SFT, AbstractBinEdges, LinearBinEdges, LogBinEdges, InfPaddedBinEdges, BinEdges, physical_edges_vector @@ -86,12 +87,13 @@ end # Device-side digitize (matches HelperFunctions.digitize / BinEdges.jl) # --------------------------------------------------------------------------- +# `T` is the EDGE type and the query is untyped, exactly as CPU `searchsortedfirst(::LinearBinEdges{T}, x)` +# declares it: the reconstructed edge is built in the edge type, the comparison promotes. @inline function _gpu_digitize_linear( - x::T, + x, first_edge::T, last_edge::T, inv_step::T, - offset::T, step_val::T, n_edges::Int, ) where {T} @@ -110,37 +112,34 @@ end """Log-spaced bins: `log(x)` then O(1) FMA on the log grid (matches CPU `LogBinEdges`).""" @inline function _gpu_digitize_log_spaced( - x::T, + x, first_edge::T, last_edge::T, inv_step::T, - offset::T, step_val::T, n_edges::Int, ) where {T} - x <= zero(T) && return 0 + x <= zero(x) && return 0 return _gpu_digitize_linear( - log(x), first_edge, last_edge, inv_step, offset, step_val, n_edges, + log(x), first_edge, last_edge, inv_step, step_val, n_edges, ) end @inline function _gpu_digitize_log_spaced_col( - x::T, + x, first_edge, last_edge, inv_step, - offset, step_val, col::Int, n_edges::Int, -) where {T} - x <= zero(T) && return 0 +) + x <= zero(x) && return 0 return _gpu_digitize_linear( log(x), @inbounds(first_edge[col]), @inbounds(last_edge[col]), @inbounds(inv_step[col]), - @inbounds(offset[col]), @inbounds(step_val[col]), n_edges, ) @@ -149,10 +148,10 @@ end """FMA scalar fields from [`LogBinEdges`](@ref) `log_linear` for GPU digitize.""" @inline function _dist_log_linear_fields(lbe::LogBinEdges) lb = lbe.log_linear - return lb.first_edge, lb.last_edge, lb.inv_step, lb.offset, lb.step_val + return lb.first_edge, lb.last_edge, lb.inv_step, lb.step_val end -@inline function _gpu_digitize_general(x::T, edges, n_edges::Int) where {T} +@inline function _gpu_digitize_general(x, edges, n_edges::Int) low = 1 high = n_edges while low <= high @@ -167,11 +166,11 @@ end end @inline function _gpu_digitize_general_col( - x::T, + x, edges, col::Int, n_edges::Int, -) where {T} +) low = 1 high = n_edges while low <= high @@ -189,14 +188,13 @@ end """ Device digitize for [`InfPaddedBinEdges`](@ref) with [`LinearBinEdges`](@ref) interior. -Matches CPU `digitize(x, InfPadded)` (underflow bin 1, interior FMA+offset, overflow past inner last). +Matches CPU `digitize(x, InfPadded)` (underflow bin 1, interior FMA, overflow past inner last). """ @inline function _gpu_digitize_inf_padded_linear( - x::T, + x, first_edge::T, last_edge::T, inv_step::T, - offset::T, step_val::T, n_inner_edges::Int, inner_last::T, @@ -208,7 +206,7 @@ Matches CPU `digitize(x, InfPadded)` (underflow bin 1, interior FMA+offset, over return n_inner_edges + 1 end inner_bin = _gpu_digitize_linear( - x, first_edge, last_edge, inv_step, offset, step_val, n_inner_edges, + x, first_edge, last_edge, inv_step, step_val, n_inner_edges, ) return inner_bin + 1 end @@ -280,14 +278,28 @@ include(joinpath(@__DIR__, "gpu", "sf_tiled.jl")) include(joinpath(@__DIR__, "gpu", "workspace.jl")) include(joinpath(@__DIR__, "gpu", "launch.jl")) +# The kernels compute Euclidean geometry inline, so every GPU entry types its `distance_metric` +# keyword as `DI.Euclidean`: asking for another metric is a TypeError naming the keyword, and the +# constraint lives in the signature rather than in a trait table and a runtime branch. + +"""`true` when `a` is an array living on `backend`. Only a missing `KA.get_backend` method (i.e. `a` +is not a recognized device array) counts as "not on this backend" — every other failure is a real +fault and propagates rather than silently degrading to a host round-trip.""" function _array_on_backend(a, backend::KA.Backend) - return try - KA.get_backend(a) == backend - catch - false + a_backend = try + KA.get_backend(a) + catch e + e isa MethodError || rethrow() + return false end + return a_backend == backend end +"""Host-dense view of `a` for `copyto!` into a device array. A host `Array` is passed through — the +DMA accepts it directly, so materializing a copy first would double the host traffic.""" +@inline _as_host_dense(a::Array) = a +@inline _as_host_dense(a) = Array(a) + """ _stage_sf_device_inputs(backend, x_mat, u_mat, N_dims, N_points) @@ -325,16 +337,16 @@ function _stage_sf_device_inputs( size(ud) == (N_dims, N_points) && eltype(xd) == FT && eltype(ud) == FT - copyto!(xd, Array(x_mat)) - copyto!(ud, Array(u_mat)) + copyto!(xd, _as_host_dense(x_mat)) + copyto!(ud, _as_host_dense(u_mat)) return xd, ud end end x_dev = KA.allocate(backend, FT, N_dims, N_points) u_dev = KA.allocate(backend, FT, N_dims, N_points) - copyto!(x_dev, Array(x_mat)) - copyto!(u_dev, Array(u_mat)) + copyto!(x_dev, _as_host_dense(x_mat)) + copyto!(u_dev, _as_host_dense(u_mat)) if workspace !== nothing workspace.x_dev_cache = x_dev workspace.u_dev_cache = u_dev @@ -397,7 +409,7 @@ Accepts host `Matrix` or device arrays on `backend`. Inputs are staged as `(N_dims, N_points)` with no padding (same layout as CPU). Keyword arguments intended for CPU backends (e.g. `verbose`, `show_progress`) are -accepted and ignored so `calculate_structure_function(...; backend=GPUBackend(...))` +accepted and ignored so `calculate_structure_function(...; backend=CB.GPUBackend(...))` can use the same call surface as threaded/serial paths. """ function _tiled_launch_params(N_points::Int) @@ -420,6 +432,7 @@ function _launch_sf_tiled_kernel!( N_dims::Int, N_bins::Int, NB::Int, + geom, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) dim2 = N_dims == 2 @@ -429,8 +442,8 @@ function _launch_sf_tiled_kernel!( kernel!( out_dev, cnt_dev, x_dev, u_dev, sf_type, N_points, N_dims, N_bins, NB, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -448,6 +461,7 @@ function _launch_sf_tiled_kernel!( N_dims::Int, N_bins::Int, NB::Int, + geom, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) dim2 = N_dims == 2 @@ -458,8 +472,8 @@ function _launch_sf_tiled_kernel!( kernel!( out_dev, cnt_dev, x_dev, u_dev, sf_type, N_points, N_dims, N_bins, NB, - lb.first_edge, lb.last_edge, lb.inv_step, lb.offset, lb.step_val, - n_tiles, n_tile_blocks, ws; + lb.first_edge, lb.last_edge, lb.inv_step, lb.step_val, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -476,12 +490,13 @@ function _launch_sf_tiled_kernel!( N_points::Int, N_dims::Int, N_bins::Int, - NB::Int; + NB::Int, + geom; general_edges_dev = nothing, ) where {FT} n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) dim2 = N_dims == 2 - if general_edges_dev === nothing + if isnothing(general_edges_dev) bins_dev = KA.allocate(backend, FT, N_bins) copyto!(bins_dev, edges) else @@ -493,7 +508,7 @@ function _launch_sf_tiled_kernel!( kernel!( out_dev, cnt_dev, x_dev, u_dev, sf_type, N_points, N_dims, N_bins, NB, edges[1], bins_dev, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -510,7 +525,8 @@ function _launch_sf_kernel!( bins::LogBinEdges, N_points::Int, N_dims::Int, - N_bins::Int; + N_bins::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) NB = N_bins - 1 @@ -518,7 +534,7 @@ function _launch_sf_kernel!( error("GPUExt: tiled kernels support at most $SF_GPU_MAX_BINS bins (got NB=$NB)") return _launch_sf_tiled_kernel!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, bins, - N_points, N_dims, N_bins, NB, + N_points, N_dims, N_bins, NB, geom, ) end @@ -533,7 +549,8 @@ function _launch_sf_kernel!( bins::LinearBinEdges, N_points::Int, N_dims::Int, - N_bins::Int; + N_bins::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) NB = N_bins - 1 @@ -541,7 +558,7 @@ function _launch_sf_kernel!( error("GPUExt: tiled kernels support at most $SF_GPU_MAX_BINS bins (got NB=$NB)") return _launch_sf_tiled_kernel!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, bins, - N_points, N_dims, N_bins, NB, + N_points, N_dims, N_bins, NB, geom, ) end @@ -556,7 +573,8 @@ function _launch_sf_kernel!( bins::Vector{FT}, N_points::Int, N_dims::Int, - N_bins::Int; + N_bins::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} NB = N_bins - 1 @@ -565,7 +583,7 @@ function _launch_sf_kernel!( _, _, gen_e = _workspace_dist_edge_bufs(workspace) return _launch_sf_tiled_kernel!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, bins, - N_points, N_dims, N_bins, NB; + N_points, N_dims, N_bins, NB, geom; general_edges_dev = gen_e, ) end @@ -589,11 +607,13 @@ function _launch_gpu_structure_function_core!( workspace::Union{GPUSFWorkspace, Nothing} = nothing, workgroup_size::Int = 64, synchronize::Bool = true, + distance_metric::DI.PreMetric = DI.Euclidean(), ) _launch_sf_kernel!( backend, workgroup_size, out_dev, cnt_dev, x_dev, u_dev, - sf_type, dist_bins, N_points, N_dims, N_bins; + sf_type, dist_bins, N_points, N_dims, N_bins, + SFH.pair_geometry_for(distance_metric, N_dims == 3 ? Val(3) : Val(2)); workspace = workspace, ) synchronize && KA.synchronize(backend) @@ -616,6 +636,7 @@ function _launch_gpu_structure_function!( workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, synchronize::Bool = true, + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., ) where {FT} N_dims, N_points = size(x_mat) @@ -629,9 +650,9 @@ function _launch_gpu_structure_function!( NB > SF_GPU_MAX_BINS && error("GPUExt: at most $SF_GPU_MAX_BINS distance bins on GPU (got NB=$NB)") - x_dev, u_dev = _stage_sf_device_inputs(backend, x_mat, u_mat, N_dims, N_points) + x_dev, u_dev = _stage_sf_device_inputs(backend, x_mat, u_mat, N_dims, N_points; workspace = workspace) - if workspace === nothing + if isnothing(workspace) out_dev = KA.zeros(backend, FT, NB) cnt_dev = KA.zeros(backend, UInt32, NB) ws = nothing @@ -647,6 +668,7 @@ function _launch_gpu_structure_function!( sf_type, backend, x_dev, u_dev, dist_bins, N_points, N_dims, N_bins; out_dev = out_dev, cnt_dev = cnt_dev, workspace = ws, workgroup_size = workgroup_size, synchronize = synchronize, + distance_metric = distance_metric, ) edges_host = _gpu_host_edge_vector(distance_bins) return out_dev, cnt_dev, edges_host @@ -663,7 +685,7 @@ function _accumulate_gpu_sf_host!( NB = length(output_sums) length(output_counts) == NB || throw(ArgumentError("GPUExt: output_counts length ($(length(output_counts))) must match output_sums ($NB)")) - if workspace !== nothing && OT === workspace.FT + if !isnothing(workspace) && OT === workspace.FT copyto!(workspace.host_sums_scratch, out_dev) output_sums .+= workspace.host_sums_scratch elseif OT === eltype(out_dev) && _array_on_backend(out_dev, KA.CPU()) @@ -813,12 +835,23 @@ function _gpu_calculate_structure_function_core( workgroup_size::Int = 64, count_eltype::Type{CT} = UInt32, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + synchronize::Bool = true, + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT, CT} + # This entry downloads before returning, so it must synchronize. + synchronize || throw( + ArgumentError( + "gpu_calculate_structure_function returns host arrays and must synchronize; " * + "use the in-place gpu_calculate_structure_function! for synchronize=false.", + ), + ) out_dev, cnt_dev, edges_host = _launch_gpu_structure_function!( sf_type, backend, x_mat, u_mat, distance_bins; workgroup_size = workgroup_size, workspace = workspace, + distance_metric = distance_metric, ) output, counts = _download_gpu_sf_results(out_dev, cnt_dev, FT, CT) @@ -834,10 +867,13 @@ end """True when six-invariant-type 2D single-pass can use HTP-EJ tiled128 (`n_dist ≤ 64`, typed dist bins).""" @inline _gpu_single_pass_2d_tiled_eligible(n_dist::Int) = n_dist <= SF_GPU_MAX_BINS -"""Route to HTP-EJ when tiled-eligible; raw `Vector` distance edges use naive pair loops.""" +""" +Route to HTP-EJ whenever the distance axis is tiled-eligible. Every distance-bin form (linear, log, +arbitrary edges via device binary search) and every value plan has a tiled variant, so the +global-atomic pair loops are reached only when `n_dist` exceeds the tiled bin cap. +""" @inline _gpu_single_pass_2d_use_tiled(dist_bins, ::GPUValueDigitizePlan, n_dist::Int) = - _gpu_single_pass_2d_tiled_eligible(n_dist) && !(dist_bins isa Vector) -@inline _gpu_single_pass_2d_use_tiled(dist_bins, ::GPUValueVectorCols, n_dist::Int) = false + _gpu_single_pass_2d_tiled_eligible(n_dist) function _launch_single_pass_tiled_kernel!( backend::KA.Backend, @@ -848,7 +884,8 @@ function _launch_single_pass_tiled_kernel!( lbe::LinearBinEdges, N_points::Int, n_edges::Int, - NB::Int; + NB::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -857,8 +894,8 @@ function _launch_single_pass_tiled_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_edges, NB, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -873,7 +910,8 @@ function _launch_single_pass_tiled_kernel!( lbe::LogBinEdges, N_points::Int, n_edges::Int, - NB::Int; + NB::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -881,9 +919,9 @@ function _launch_single_pass_tiled_kernel!( kernel! = _sf6_single_pass_kernel_tiled128_log_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, - lb.first_edge, lb.last_edge, lb.inv_step, lb.offset, lb.step_val, + lb.first_edge, lb.last_edge, lb.inv_step, lb.step_val, N_points, n_edges, NB, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -898,12 +936,13 @@ function _launch_single_pass_tiled_kernel!( edges::Vector{FT}, N_points::Int, n_edges::Int, - NB::Int; + NB::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) _, _, gen_e = _workspace_dist_edge_bufs(workspace) - if gen_e === nothing + if isnothing(gen_e) bins_dev = KA.allocate(backend, FT, n_edges) copyto!(bins_dev, edges) else @@ -913,7 +952,7 @@ function _launch_single_pass_tiled_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, edges[1], bins_dev, N_points, n_edges, NB, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -923,6 +962,9 @@ end # Single-Pass GPU Kernels (global-atomic path when NB > SF_GPU_MAX_BINS) # --------------------------------------------------------------------------- +@inline _gpu_ld_col(m, k::Int, ::Val{W}, ::Type{FT}) where {W, FT} = + SA.SVector{W, FT}(ntuple(d -> @inbounds(m[d, k]), Val(W))) + @inline function _gpu_single_pass_pair_invariants( x_mat, u_mat, @@ -930,18 +972,16 @@ end j::Int, ::Val{2}, ::Type{FT}, + geom, ) where {FT} - dx1 = x_mat[1, j] - x_mat[1, i] - dx2 = x_mat[2, j] - x_mat[2, i] - du1 = u_mat[1, j] - u_mat[1, i] - du2 = u_mat[2, j] - u_mat[2, i] - dist = sqrt(dx1^2 + dx2^2) - rx = dx1 / dist - ry = dx2 / dist - du_L = du1 * rx + du2 * ry + X1 = _gpu_ld_col(x_mat, i, SFH.coordinate_width(geom), FT) + X2 = _gpu_ld_col(x_mat, j, SFH.coordinate_width(geom), FT) + U1 = _gpu_ld_col(u_mat, i, Val(2), FT) + U2 = _gpu_ld_col(u_mat, j, Val(2), FT) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du1^2 + du2^2 - du_L2 - return dist, du_L, du_L2, du_T2 + return ok, dist, du_L, du_L2, du_n2 - du_L2 end @inline function _gpu_single_pass_pair_invariants( @@ -951,21 +991,16 @@ end j::Int, ::Val{3}, ::Type{FT}, + geom, ) where {FT} - dx1 = x_mat[1, j] - x_mat[1, i] - dx2 = x_mat[2, j] - x_mat[2, i] - dx3 = x_mat[3, j] - x_mat[3, i] - du1 = u_mat[1, j] - u_mat[1, i] - du2 = u_mat[2, j] - u_mat[2, i] - du3 = u_mat[3, j] - u_mat[3, i] - dist = sqrt(dx1^2 + dx2^2 + dx3^2) - rx = dx1 / dist - ry = dx2 / dist - rz = dx3 / dist - du_L = du1 * rx + du2 * ry + du3 * rz + X1 = _gpu_ld_col(x_mat, i, SFH.coordinate_width(geom), FT) + X2 = _gpu_ld_col(x_mat, j, SFH.coordinate_width(geom), FT) + U1 = _gpu_ld_col(u_mat, i, Val(3), FT) + U2 = _gpu_ld_col(u_mat, j, Val(3), FT) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du1^2 + du2^2 + du3^2 - du_L2 - return dist, du_L, du_L2, du_T2 + return ok, dist, du_L, du_L2, du_n2 - du_L2 end @inline function _gpu_accumulate_single_pass_global!( @@ -1000,22 +1035,22 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel_linear!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, + geom, ) where {D, FT} I = @index(Global, NTuple) i = I[1] j = I[2] if i < j - dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( - x_mat, u_mat, i, j, Val(D), FT, + ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, + dist, first_edge, last_edge, inv_step, step_val, N_bins, ) - if 1 <= bin < N_bins + if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_L2, du_T2) end end @@ -1032,20 +1067,20 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel_log!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, + geom, ) where {D, FT} I = @index(Global, NTuple) i = I[1] j = I[2] if i < j - dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( - x_mat, u_mat, i, j, Val(D), FT, + ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + x_mat, u_mat, i, j, Val(D), FT, geom, ) - bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) + bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) - if 1 <= bin < N_bins + if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_L2, du_T2) end end @@ -1060,6 +1095,7 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel!( N_points::Int, ::Val{D}, N_bins::Int, + geom, ) where {D} I = @index(Global, NTuple) i = I[1] @@ -1067,17 +1103,40 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_kernel!( if i < j FT = eltype(x_mat) - dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( - x_mat, u_mat, i, j, Val(D), FT, + ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_general(dist, distance_bins, N_bins) - if 1 <= bin < N_bins + if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_global!(output_sums, output_counts, bin, du_L, du_L2, du_T2) end end end +""" +Offer a non-batch single-pass 1D launch to the batch dispatcher as `B=1`, which reaches the CUDA +N-body kernel; `false` means the hook declined and the caller stays on the tiled128 path. + +Measured on A100 (N=20000): 1.90× Float32, 1.32× Float64. The batch machinery is not a win at +`B=1` in general — 1D-individual measures 0.64× because its fixed-x path pays strip staging and two +merge kernels for a strip of one — so this is applied per regime, not globally. See +`gpu/SPEED_OF_LIGHT.md`. +""" +@inline function _sp1d_try_fast_batch!( + backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_bins, + N_points::Int, N_dims::Int, NB::Int, geom, +) + return SFC.gpu_fast_launch_1d_batch!( + backend, + reshape(out_sums_dev, SF_GPU_SINGLE_PASS_N, NB, 1), + reshape(out_cnts_dev, SF_GPU_SINGLE_PASS_N, NB, 1), + x_dev, reshape(u_dev, N_dims, N_points, 1), + nothing, _sf_batch_dist_digitizer(backend, dist_bins), + N_points, NB, 1, N_dims, SF_GPU_SINGLE_PASS_N, true, geom, + ) +end + function _launch_single_pass_kernel!( backend::KA.Backend, workgroup_size::Int, @@ -1088,21 +1147,24 @@ function _launch_single_pass_kernel!( lbe::LinearBinEdges, N_points::Int, N_dims::Int, - n_edges::Int; + n_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) NB = n_edges - 1 + _sp1d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, + lbe, N_points, N_dims, NB, geom) && return nothing if N_dims == 2 && _gpu_single_pass_tiled_eligible(NB) return _launch_single_pass_tiled_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - lbe, N_points, n_edges, NB; workspace = workspace, + lbe, N_points, n_edges, NB, geom; workspace = workspace, ) end kernel! = _sf_single_pass_kernel_linear!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, Val(N_dims), n_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1118,14 +1180,17 @@ function _launch_single_pass_kernel!( lbe::LogBinEdges, N_points::Int, N_dims::Int, - n_edges::Int; + n_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) NB = n_edges - 1 + _sp1d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, + lbe, N_points, N_dims, NB, geom) && return nothing if N_dims == 2 && _gpu_single_pass_tiled_eligible(NB) return _launch_single_pass_tiled_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - lbe, N_points, n_edges, NB; workspace = workspace, + lbe, N_points, n_edges, NB, geom; workspace = workspace, ) end lb = lbe.log_linear @@ -1133,7 +1198,7 @@ function _launch_single_pass_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, Val(N_dims), n_edges, - lb.first_edge, lb.last_edge, lb.inv_step, lb.offset, lb.step_val; + lb.first_edge, lb.last_edge, lb.inv_step, lb.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1149,18 +1214,21 @@ function _launch_single_pass_kernel!( edges::Vector{FT}, N_points::Int, N_dims::Int, - n_edges::Int; + n_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} NB = n_edges - 1 + _sp1d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, + edges, N_points, N_dims, NB, geom) && return nothing if N_dims == 2 && _gpu_single_pass_tiled_eligible(NB) return _launch_single_pass_tiled_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - edges, N_points, n_edges, NB; workspace = workspace, + edges, N_points, n_edges, NB, geom; workspace = workspace, ) end _, _, gen_e = _workspace_dist_edge_bufs(workspace) - if gen_e === nothing + if isnothing(gen_e) bins_dev = KA.allocate(backend, FT, n_edges) copyto!(bins_dev, edges) else @@ -1169,7 +1237,7 @@ function _launch_single_pass_kernel!( kernel! = _sf_single_pass_kernel!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, - bins_dev, N_points, Val(N_dims), n_edges; + bins_dev, N_points, Val(N_dims), n_edges, geom; ndrange = (N_points, N_points), ) return nothing @@ -1192,8 +1260,8 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel_linear!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, + geom, ) where {FT} I = @index(Global, NTuple) i, j = I[1], I[2] @@ -1202,14 +1270,13 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel_linear!( X2 = SA.SVector{2}(x_mat[1, j], x_mat[2, j]) U1 = SA.SVector{2}(u_mat[1, i], u_mat[2, i]) U2 = SA.SVector{2}(u_mat[1, j], u_mat[2, j]) - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) dbin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_dist_bins, + dist, first_edge, last_edge, inv_step, step_val, N_dist_bins, ) - if 1 <= dbin < N_dist_bins - r̂ = dX / dist - val = sf_type(U2 - U1, r̂) + if ok && 1 <= dbin < N_dist_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) vbin = _gpu_digitize_general(val, value_edges, N_val_edges) if 1 <= vbin < N_val_edges @atomic output_sums[dbin, vbin] += val @@ -1232,8 +1299,8 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel_log!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, + geom, ) where {FT} I = @index(Global, NTuple) i, j = I[1], I[2] @@ -1242,12 +1309,10 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel_log!( X2 = SA.SVector{2}(x_mat[1, j], x_mat[2, j]) U1 = SA.SVector{2}(u_mat[1, i], u_mat[2, i]) U2 = SA.SVector{2}(u_mat[1, j], u_mat[2, j]) - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - dbin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, offset, step_val, N_dist_bins) - if 1 <= dbin < N_dist_bins - dU = U2 - U1 - r̂ = dX / dist + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + dbin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_dist_bins) + if ok && 1 <= dbin < N_dist_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) val = sf_type(dU, r̂) vbin = _gpu_digitize_general(val, value_edges, N_val_edges) if 1 <= vbin < N_val_edges @@ -1269,6 +1334,7 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel!( N_points::Int, N_dist_bins::Int, N_val_edges::Int, + geom, ) I = @index(Global, NTuple) i, j = I[1], I[2] @@ -1277,12 +1343,10 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel!( X2 = SA.SVector{2}(x_mat[1, j], x_mat[2, j]) U1 = SA.SVector{2}(u_mat[1, i], u_mat[2, i]) U2 = SA.SVector{2}(u_mat[1, j], u_mat[2, j]) - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) dbin = _gpu_digitize_general(dist, distance_edges, N_dist_bins) - if 1 <= dbin < N_dist_bins - dU = U2 - U1 - r̂ = dX / dist + if ok && 1 <= dbin < N_dist_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) val = sf_type(dU, r̂) vbin = _gpu_digitize_general(val, value_edges, N_val_edges) if 1 <= vbin < N_val_edges @@ -1293,6 +1357,29 @@ KA.@kernel unsafe_indices=true function _sf_joint_2d_kernel!( end end +""" +Offer a non-batch joint 2D launch to the batch dispatcher as `B=1` (`NMOM=1`, so `sf_type` is +carried through and does the per-pair math); `false` means the hook declined and the caller +continues unchanged. `(n_dist, n_val)` reshapes to `(1, n_dist, n_val, 1)` at no cost — column-major +layout is identical. Measured on A100 (N=20000): 1.48× Float32, 1.18× Float64. +See `gpu/SPEED_OF_LIGHT.md`. +""" +@inline function _joint2d_try_fast_batch!( + backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, dist_bins, vp, + N_points::Int, n_dist::Int, n_val::Int, geom, +) + isnothing(vp) && return false + D = size(x_dev, 1) + return SFC.gpu_fast_launch_2d_batch!( + backend, + reshape(out_sums_dev, 1, n_dist, n_val, 1), + reshape(out_cnts_dev, 1, n_dist, n_val, 1), + x_dev, reshape(u_dev, D, N_points, 1), + sf_type, _sf_batch_dist_digitizer(backend, dist_bins), vp, + N_points, n_dist, n_val, 1, D, 1, true, geom, + ) +end + function _launch_joint_2d_kernel!( backend::KA.Backend, workgroup_size::Int, @@ -1305,17 +1392,20 @@ function _launch_joint_2d_kernel!( dist_bins::LinearBinEdges, N_points::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; val_plan::Union{GPUValueDigitizePlan, Nothing} = nothing, workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_dist = n_dist_edges - 1 n_val = n_val_edges - 1 - vp = val_plan === nothing && workspace !== nothing ? workspace.val_plan : val_plan + vp = isnothing(val_plan) && !isnothing(workspace) ? workspace.val_plan : val_plan + _joint2d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, + dist_bins, vp, N_points, n_dist, n_val, geom) && return nothing if _gpu_joint_2d_tiled_eligible(n_dist, n_val) return _launch_joint_2d_tiled_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, - sf_type, dist_bins, vp, N_points, n_dist_edges, n_val_edges, n_dist, n_val; + sf_type, dist_bins, vp, N_points, n_dist_edges, n_val_edges, n_dist, n_val, geom; workspace = workspace, ) end @@ -1338,17 +1428,20 @@ function _launch_joint_2d_kernel!( dist_bins::LogBinEdges, N_points::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; val_plan::Union{GPUValueDigitizePlan, Nothing} = nothing, workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_dist = n_dist_edges - 1 n_val = n_val_edges - 1 - vp = val_plan === nothing && workspace !== nothing ? workspace.val_plan : val_plan + vp = isnothing(val_plan) && !isnothing(workspace) ? workspace.val_plan : val_plan + _joint2d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, + dist_bins, vp, N_points, n_dist, n_val, geom) && return nothing if _gpu_joint_2d_tiled_eligible(n_dist, n_val) return _launch_joint_2d_tiled_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, - sf_type, dist_bins, vp, N_points, n_dist_edges, n_val_edges, n_dist, n_val; + sf_type, dist_bins, vp, N_points, n_dist_edges, n_val_edges, n_dist, n_val, geom; workspace = workspace, ) end @@ -1371,17 +1464,20 @@ function _launch_joint_2d_kernel!( dist_bins::Vector{FT}, N_points::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; val_plan::Union{GPUValueDigitizePlan, Nothing} = nothing, workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} n_dist = n_dist_edges - 1 n_val = n_val_edges - 1 - vp = val_plan === nothing && workspace !== nothing ? workspace.val_plan : val_plan + vp = isnothing(val_plan) && !isnothing(workspace) ? workspace.val_plan : val_plan + _joint2d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, + dist_bins, vp, N_points, n_dist, n_val, geom) && return nothing if _gpu_joint_2d_tiled_eligible(n_dist, n_val) return _launch_joint_2d_tiled_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, - sf_type, dist_bins, vp, N_points, n_dist_edges, n_val_edges, n_dist, n_val; + sf_type, dist_bins, vp, N_points, n_dist_edges, n_val_edges, n_dist, n_val, geom; workspace = workspace, ) end @@ -1411,7 +1507,7 @@ function _launch_joint_2d_global_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, sf_type, N_points, n_dist_edges, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1437,7 +1533,7 @@ function _launch_joint_2d_global_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, sf_type, N_points, n_dist_edges, n_val_edges, - lb.first_edge, lb.last_edge, lb.inv_step, lb.offset, lb.step_val; + lb.first_edge, lb.last_edge, lb.inv_step, lb.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1459,7 +1555,7 @@ function _launch_joint_2d_global_kernel!( workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} _, _, gen_e = _workspace_dist_edge_bufs(workspace) - if gen_e === nothing + if isnothing(gen_e) dist_dev = KA.allocate(backend, FT, n_dist_edges) copyto!(dist_dev, edges) else @@ -1469,7 +1565,7 @@ function _launch_joint_2d_global_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_dev, value_edges_dev, sf_type, - N_points, n_dist_edges, n_val_edges; + N_points, n_dist_edges, n_val_edges, geom; ndrange = (N_points, N_points), ) return nothing @@ -1485,6 +1581,7 @@ function _launch_gpu_joint2d!( workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, synchronize::Bool = true, + distance_metric::DI.PreMetric = DI.Euclidean(), ) FT = promote_type(eltype(x_mat), eltype(u_mat), eltype(distance_bins), eltype(value_bins)) N_dims, N_points = size(x_mat) @@ -1501,15 +1598,15 @@ function _launch_gpu_joint2d!( n_val = n_val_edges - 1 NB = n_dist - x_dev, u_dev = _stage_sf_device_inputs(backend, x_mat, u_mat, N_dims, N_points) + x_dev, u_dev = _stage_sf_device_inputs(backend, x_mat, u_mat, N_dims, N_points; workspace = workspace) - val_plan = if workspace === nothing + val_plan = if isnothing(workspace) _joint2d_build_val_plan(backend, value_bins) else workspace.val_plan end - if workspace === nothing + if isnothing(workspace) value_host = _gpu_host_edge_vector(value_bins) value_edges_dev = KA.allocate(backend, FT, n_val_edges) copyto!(value_edges_dev, value_host) @@ -1528,7 +1625,8 @@ function _launch_gpu_joint2d!( _launch_joint_2d_kernel!( backend, workgroup_size, out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, - sf_type, dist_bins, N_points, n_dist_edges, n_val_edges; + sf_type, dist_bins, N_points, n_dist_edges, n_val_edges, + SFH.pair_geometry_for(distance_metric, Val(2)); val_plan = val_plan, workspace = ws, ) synchronize && KA.synchronize(backend) @@ -1578,11 +1676,14 @@ function _gpu_calculate_structure_function_2d_snapshot( count_eltype::Type{CT} = UInt32, workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, FT4 <: Number, CT} out_sums_dev, out_cnts_dev = _launch_gpu_joint2d!( sf_type, backend, x_mat, u_mat, distance_bins, value_bins; workgroup_size = workgroup_size, workspace = workspace, + distance_metric = distance_metric, ) sums = Array(out_sums_dev) counts = _download_gpu_counts(out_cnts_dev, CT) @@ -1637,19 +1738,19 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel_linear!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, + geom, ) where {D, FT} I = @index(Global, NTuple) i, j = I[1], I[2] if i < j - dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( - x_mat, u_mat, i, j, Val(D), FT, + ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, + dist, first_edge, last_edge, inv_step, step_val, N_bins, ) - if 1 <= bin < N_bins + if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_2d_pair!( output_sums, output_counts, value_edges, bin, du_L, zero(du_L), du_L2, du_T2, N_val_edges, @@ -1671,17 +1772,17 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel_log!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, + geom, ) where {D, FT} I = @index(Global, NTuple) i, j = I[1], I[2] if i < j - dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( - x_mat, u_mat, i, j, Val(D), FT, + ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + x_mat, u_mat, i, j, Val(D), FT, geom, ) - bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) - if 1 <= bin < N_bins + bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) + if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_2d_pair!( output_sums, output_counts, value_edges, bin, du_L, zero(du_L), du_L2, du_T2, N_val_edges, @@ -1701,16 +1802,17 @@ KA.@kernel unsafe_indices=true function _sf_single_pass_2d_kernel!( ::Val{D}, N_bins::Int, N_val_edges::Int, + geom, ) where {D} I = @index(Global, NTuple) i, j = I[1], I[2] if i < j FT = eltype(x_mat) - dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( - x_mat, u_mat, i, j, Val(D), FT, + ok, dist, du_L, du_L2, du_T2 = _gpu_single_pass_pair_invariants( + x_mat, u_mat, i, j, Val(D), FT, geom, ) bin = _gpu_digitize_general(dist, distance_bins, N_bins) - if 1 <= bin < N_bins + if ok && 1 <= bin < N_bins _gpu_accumulate_single_pass_2d_pair!( output_sums, output_counts, value_edges, bin, du_L, zero(du_L), du_L2, du_T2, N_val_edges, @@ -1724,7 +1826,7 @@ const _SinglePass2DValueBins = SFC.SinglePass2DValueBins include(joinpath(@__DIR__, "gpu", "batch_dispatch.jl")) function _gpu_run_single_pass_2d!( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, sums_3d::AbstractArray{OT, 3}, counts_3d::AbstractArray{CT, 3}, x::AbstractMatrix{FT1}, @@ -1735,12 +1837,14 @@ function _gpu_run_single_pass_2d!( workspace::Union{GPUSFWorkspace, Nothing} = nothing, synchronize::Bool = true, force_global_atomic::Bool = false, + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {OT, CT, FT1 <: Number, FT2 <: Number, FT3 <: Number} backend = gpu_backend.backend FT = _sp2d_value_eltype(value_bins, promote_type(float(FT1), float(FT2), float(FT3))) N_dims, N_points = size(x) N_dims in (2, 3) || error("GPUExt: single-pass 2D calculation requires N_dims ∈ (2, 3) (got N_dims=$N_dims)") + geom = SFH.pair_geometry_for(distance_metric, N_dims == 3 ? Val(3) : Val(2)) n_bins = _gpu_n_edges(distance_bins) - 1 n_val = size(sums_3d, 3) @@ -1756,8 +1860,12 @@ function _gpu_run_single_pass_2d!( x_dev, u_dev = _stage_sf_device_inputs(backend, x, u, N_dims, N_points; workspace = workspace) - if workspace === nothing - val_plan = force_global_atomic ? _gpu_build_value_vector_cols_plan(backend, value_bins) : N_dims == 3 ? + # The global-atomic kernel only has methods for `GPUValueVectorCols`, so the plan choice must + # use the same predicate the launcher does — see `_sp2d_prefers_global_atomics`. + go_global = force_global_atomic || + _sp2d_prefers_global_atomics(n_bins, n_val, FT, SFC.gpu_device_caps(backend)) + if isnothing(workspace) + val_plan = go_global ? _gpu_build_value_vector_cols_plan(backend, value_bins) : _gpu_build_value_digitize_plan(backend, value_bins) out_sums_dev = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, n_bins, n_val) @@ -1766,8 +1874,8 @@ function _gpu_run_single_pass_2d!( else _validate_gpu_workspace!(workspace, backend, :single_pass_2d, n_bins; n_val = n_val) SFC.reset_histogram!(workspace) - val_plan = force_global_atomic ? GPUValueVectorCols{FT}(workspace.value_edges_sp2d_dev) : N_dims == 3 ? - _gpu_build_value_vector_cols_plan(backend, value_bins) : + val_plan = go_global ? + GPUValueVectorCols{FT}(workspace.value_edges_sp2d_dev) : workspace.val_plan out_sums_dev = workspace.out_sums_dev out_cnts_dev = workspace.out_cnts_dev @@ -1777,7 +1885,7 @@ function _gpu_run_single_pass_2d!( _launch_single_pass_2d!( backend, workgroup_size, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, N_dims, n_dist_edges, n_val_edges; + dist_bins, val_plan, N_points, N_dims, n_dist_edges, n_val_edges, geom; workspace = ws, force_global_atomic = force_global_atomic, ) @@ -1799,14 +1907,15 @@ function _launch_single_pass_2d_kernel!( lbe::LinearBinEdges, N_points::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) kernel! = _sf_single_pass_2d_kernel_linear!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, N_points, Val(2), n_dist_edges, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1823,15 +1932,16 @@ function _launch_single_pass_2d_kernel!( lbe::LogBinEdges, N_points::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf_single_pass_2d_kernel_log!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, N_points, Val(2), n_dist_edges, n_val_edges, - d_f, d_l, d_inv, d_off, d_st; + d_f, d_l, d_inv, d_st, geom; ndrange = (N_points, N_points), ) return nothing @@ -1848,11 +1958,12 @@ function _launch_single_pass_2d_kernel!( edges::Vector{FT}, N_points::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} _, _, gen_e = _workspace_dist_edge_bufs(workspace) - if gen_e === nothing + if isnothing(gen_e) bins_dev = KA.allocate(backend, FT, n_dist_edges) copyto!(bins_dev, edges) else @@ -1861,28 +1972,30 @@ function _launch_single_pass_2d_kernel!( kernel! = _sf_single_pass_2d_kernel!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, - bins_dev, value_edges_dev, N_points, Val(2), n_dist_edges, n_val_edges; + bins_dev, value_edges_dev, N_points, Val(2), n_dist_edges, n_val_edges, geom; ndrange = (N_points, N_points), ) return nothing end """ - SFC._dispatch_single_pass(::GPUBackend, x, u, distance_bins; workgroup_size=64, kwargs...) + SFC._dispatch_single_pass(::CB.AbstractGPUBackend, x, u, distance_bins; workgroup_size=64, kwargs...) Calculates single-pass structure functions utilizing GPU-accelerated computing. Device histograms are `UInt32`; `count_eltype` (default `UInt32`) selects the host count matrix type returned by [`append_helmholtz_rotational_divergent_rows`](@ref). """ function SFC._dispatch_single_pass( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}; workgroup_size::Int = 64, count_eltype::Type{CT} = UInt32, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs... + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} backend = gpu_backend.backend FT = promote_type(float(FT1), float(FT2)) @@ -1896,7 +2009,7 @@ function SFC._dispatch_single_pass( x_dev, u_dev = _stage_sf_device_inputs(backend, x, u, N_dims, N_points; workspace = workspace) - if workspace === nothing + if isnothing(workspace) out_sums_dev = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, n_bins) out_cnts_dev = KA.zeros(backend, UInt32, SF_GPU_SINGLE_PASS_N, n_bins) ws = nothing @@ -1911,7 +2024,8 @@ function SFC._dispatch_single_pass( _launch_single_pass_kernel!( backend, workgroup_size, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, N_points, N_dims, n_edges; + dist_bins, N_points, N_dims, n_edges, + SFH.pair_geometry_for(distance_metric, N_dims == 3 ? Val(3) : Val(2)); workspace = ws, ) KA.synchronize(backend) @@ -1938,7 +2052,9 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d( workgroup_size::Int = 64, count_eltype::Type{CT} = UInt32, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + synchronize::Bool = true, + force_global_atomic::Bool = false, + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} OT = promote_type(float(FT1), float(FT2)) n_bins = length(distance_bins) - 1 @@ -1946,9 +2062,12 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d( SFC._validate_value_bins!(value_bins, n_val) sums = zeros(OT, SF_GPU_SINGLE_PASS_N, n_bins, n_val) counts = zeros(CT, SF_GPU_SINGLE_PASS_N, n_bins, n_val) + # Only forward knobs the core accepts; it has no `kwargs...` sink. return _gpu_run_single_pass_2d!( - SF.GPUBackend(backend), sums, counts, x, u, distance_bins, value_bins; - workgroup_size = workgroup_size, workspace = workspace, kwargs..., + CB.GPUBackend(backend), sums, counts, x, u, distance_bins, value_bins; + workgroup_size = workgroup_size, workspace = workspace, + synchronize = synchronize, force_global_atomic = force_global_atomic, + distance_metric = distance_metric, ) end @@ -1962,7 +2081,9 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d!( value_bins::_SinglePass2DValueBins; workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + synchronize::Bool = true, + force_global_atomic::Bool = false, + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {OT, CT, FT1 <: Number, FT2 <: Number, FT3 <: Number} fill!(sums_3d, zero(OT)) fill!(counts_3d, 0) @@ -1973,8 +2094,10 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d!( size(counts_3d) == size(sums_3d) || throw(DimensionMismatch("counts must match sums shape $(size(sums_3d))")) _gpu_run_single_pass_2d!( - SF.GPUBackend(backend), sums_3d, counts_3d, x, u, distance_bins, value_bins; - workgroup_size = workgroup_size, workspace = workspace, kwargs..., + CB.GPUBackend(backend), sums_3d, counts_3d, x, u, distance_bins, value_bins; + workgroup_size = workgroup_size, workspace = workspace, + synchronize = synchronize, force_global_atomic = force_global_atomic, + distance_metric = distance_metric, ) return sums_3d, counts_3d end @@ -1996,7 +2119,7 @@ function SFC.gpu_calculate_structure_function_batch!( distance_bins::AbstractVector{FT}; workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {OT, CT, FT} N_dims, N_points, T = size(x) # Any distance-bin type: the unified device path digitizes via @@ -2010,7 +2133,8 @@ function SFC.gpu_calculate_structure_function_batch!( error("GPUExt: slice batch requires N_dims=2 (got N_dims=$N_dims)") # Fused varying-x batch (B = T) through the unified N-body path (measured # ~1.9× the old per-slice varying kernel; single launch, no per-slice loop). - oh, ch = _gpu_1d_individual_device(backend, sf_type, x, u, distance_bins, NB, T, false, OT) + oh, ch = _gpu_1d_individual_device(backend, sf_type, x, u, distance_bins, NB, T, false, OT, + SFH.pair_geometry_for(distance_metric, Val(2))) copy!(sums, reshape(oh, NB, T)) copy!(counts, reshape(ch, NB, T)) return nothing @@ -2032,7 +2156,7 @@ function SFC.gpu_calculate_structure_function_2d_batch!( value_bins::AbstractVector{FT}; workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {OT, CT, FT} N_dims, N_points, T = size(x) n_dist = length(distance_bins) - 1 @@ -2045,7 +2169,7 @@ function SFC.gpu_calculate_structure_function_2d_batch!( # Fused varying-x batch (B = T) through the unified joint-2D path (one launch, # no per-slice loop; N-body + privatized histogram). oh, ch = _gpu_2d_unified_device(backend, x, u, sf_type, distance_bins, value_bins, - Val(1), n_dist, n_val, T, false, OT) + Val(1), n_dist, n_val, T, false, OT, SFH.pair_geometry_for(distance_metric, Val(2))) copy!(sums, reshape(oh, n_dist, n_val, T)) copy!(counts, reshape(ch, n_dist, n_val, T)) return nothing @@ -2066,7 +2190,7 @@ function SFC.gpu_calculate_structure_functions_single_pass_batch!( distance_bins::AbstractVector{FT}; workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {OT, CT, FT} N_dims, N_points, T = size(x) # Any distance-bin type: the unified device path digitizes via @@ -2080,7 +2204,7 @@ function SFC.gpu_calculate_structure_functions_single_pass_batch!( error("GPUExt: single-pass slice batch requires N_dims=2 (got N_dims=$N_dims)") # Fused varying-x batch (B = T) through the unified N-body single-pass path. oh, ch = _gpu_1d_unified_device(backend, x, u, nothing, distance_bins, - Val(SFC.SINGLE_PASS_N), n_bins, T, false, OT) + Val(SFC.SINGLE_PASS_N), n_bins, T, false, OT, SFH.pair_geometry_for(distance_metric, Val(2))) copy!(sums, reshape(oh, SFC.SINGLE_PASS_N, n_bins, T)) copy!(counts, reshape(ch, SFC.SINGLE_PASS_N, n_bins, T)) return nothing @@ -2102,7 +2226,7 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d_batch!( value_bins::_SinglePass2DValueBins; workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), ) where {OT, CT, FT} N_dims, N_points, T = size(x) # Any distance-bin type: the unified device path digitizes via @@ -2120,19 +2244,19 @@ function SFC.gpu_calculate_structure_functions_single_pass_2d_batch!( # (N-body + dynamic-shared privatized histogram; ~17× the old per-slice path # at 50×50, one launch instead of T). oh, ch = _gpu_sp2d_unified_device(backend, x, u, distance_bins, value_bins, - n_bins, n_val, T, false, OT) + n_bins, n_val, T, false, OT, SFH.pair_geometry_for(distance_metric, Val(2))) copy!(sums, reshape(oh, SFC.SINGLE_PASS_N, n_bins, n_val, T)) copy!(counts, reshape(ch, SFC.SINGLE_PASS_N, n_bins, n_val, T)) return nothing end """ - SFC._dispatch_single_pass!(::GPUBackend, sums, counts, x, u, distance_bins; ...) + SFC._dispatch_single_pass!(::CB.AbstractGPUBackend, sums, counts, x, u, distance_bins; ...) In-place six-invariant-type single-pass distance histograms on GPU (no Helmholtz row append). """ function SFC._dispatch_single_pass!( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, x::AbstractMatrix{FT1}, @@ -2140,6 +2264,7 @@ function SFC._dispatch_single_pass!( distance_bins::AbstractVector{FT3}; workgroup_size::Int = 64, workspace::Union{GPUSFWorkspace, Nothing} = nothing, + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., ) where {OT, CT, FT1 <: Number, FT2 <: Number, FT3 <: Number} backend = gpu_backend.backend @@ -2157,7 +2282,7 @@ function SFC._dispatch_single_pass!( x_dev, u_dev = _stage_sf_device_inputs(backend, x, u, N_dims, N_points; workspace = workspace) - if workspace === nothing + if isnothing(workspace) out_sums_dev = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, n_bins) out_cnts_dev = KA.zeros(backend, UInt32, SF_GPU_SINGLE_PASS_N, n_bins) ws = nothing @@ -2172,7 +2297,8 @@ function SFC._dispatch_single_pass!( _launch_single_pass_kernel!( backend, workgroup_size, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, N_points, N_dims, n_edges; + dist_bins, N_points, N_dims, n_edges, + SFH.pair_geometry_for(distance_metric, N_dims == 3 ? Val(3) : Val(2)); workspace = ws, ) KA.synchronize(backend) @@ -2212,7 +2338,7 @@ function SFC.gpu_calculate_structure_function_2d_batch( end function SFC._dispatch_single_pass( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, x::AbstractMatrix{FT1}, u::AbstractArray{FT2, N}, distance_bins::AbstractVector{FT3}; @@ -2226,7 +2352,7 @@ function SFC._dispatch_single_pass( end function SFC._dispatch_single_pass( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, x::AbstractArray{FT1, N}, u::AbstractArray{FT2, N}, distance_bins::AbstractVector{FT3}; @@ -2240,7 +2366,7 @@ function SFC._dispatch_single_pass( end function SFC._dispatch_single_pass!( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, sums::AbstractArray{OT}, counts::AbstractArray{CT}, x::AbstractArray{FT1, N}, @@ -2256,7 +2382,7 @@ function SFC._dispatch_single_pass!( end function SFC._dispatch_single_pass_2d( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, x::AbstractArray{FT1, N}, u::AbstractArray{FT2, N}, distance_bins::AbstractVector{FT3}, @@ -2271,7 +2397,7 @@ function SFC._dispatch_single_pass_2d( end function SFC._dispatch_single_pass_2d( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}, @@ -2284,7 +2410,7 @@ function SFC._dispatch_single_pass_2d( end function SFC._dispatch_single_pass_2d( - gpu_backend::SF.GPUBackend, + gpu_backend::CB.AbstractGPUBackend, x::AbstractMatrix{FT1}, u::AbstractArray{FT2, N}, distance_bins::AbstractVector{FT3}, diff --git a/ext/StructureFunctionsMPIExt.jl b/ext/StructureFunctionsMPIExt.jl index 9bfcd8d..df1bb15 100644 --- a/ext/StructureFunctionsMPIExt.jl +++ b/ext/StructureFunctionsMPIExt.jl @@ -5,83 +5,211 @@ Mirrors the parametric `DistributedBackend{Inner}`: each MPI rank computes a bal of the pairs with the `inner` backend (Serial/Threaded), then partial histograms are combined with `MPI.Allreduce!` so every rank holds the full result. Run under `mpiexec` with `MPI.Init()`. -Currently supports point-field (non-batched) 1D inputs. Batched / 2D MPI can reuse the same -share-then-Allreduce pattern and is left as a follow-up. +Covers point-field and batched inputs for all four entry families (1D, joint 2D, single-pass 1D, +single-pass 2D). Every rank must call with identical bins and input shapes: `Allreduce!` is +collective, so a rank that takes a different path deadlocks. """ module StructureFunctionsMPIExt using MPI: MPI using Distances: Distances as DI +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionObjects as SFO, StructureFunctionTypes as SFT, n_histogram_bins -@inline _comm(b::SFC.MPIBackend) = b.comm === nothing ? MPI.COMM_WORLD : b.comm +@inline _comm(b::CB.AbstractMPIBackend) = isnothing(b.comm) ? MPI.COMM_WORLD : b.comm -# Public entry (with shape). Point-field only for now. -function SFC._dispatch_execution_backend( - b::SFC.MPIBackend, - shape::SFC.AbstractFieldShape, - structure_function_type::SFT.AbstractPairwiseStructureFunctionType, - x, - u, - distance_bins::AbstractVector; - kwargs..., -) - SFC.has_auxiliary_axes(shape) && throw(ArgumentError( - "MPIBackend currently supports point-field (non-batched) inputs; got a batched shape.")) - return _mpi_point_1d(b, structure_function_type, x, u, distance_bins; kwargs...) +# Round-robin outer-index share: work for index i is ~ N - i, so a strided subset of the +# triangular loop carries ~equal work on every rank. +@inline function _rank_share(comm, ifull) + return (first(ifull) + MPI.Comm_rank(comm)):MPI.Comm_size(comm):last(ifull) +end + +@inline function _allreduce_pair!(comm, sums, counts) + MPI.Allreduce!(sums, +, comm) + MPI.Allreduce!(counts, +, comm) + return sums, counts +end + +# `Allreduce!` needs contiguous, mutable buffers; a partial kernel may hand back a view. +@inline _dense(a::Array) = a +@inline _dense(a::AbstractArray) = Array(a) + +# Batch-leading executor: run this rank's share through the inner backend's executor, then +# Allreduce so every rank holds the full histogram before it is permuted into the caller's buffer. +function _mpi_bl_exec(comm, inner_exec) + return function (make_accum, run_chunk!, ifull, B, accum_bytes, ws) + acc = inner_exec(make_accum, run_chunk!, _rank_share(comm, ifull), B, accum_bytes, ws) + return _allreduce_pair!(comm, _dense(acc[1]), _dense(acc[2])) + end end -# 2D joint is not yet implemented for MPI (the share-then-Allreduce pattern would extend to it). -# Give an honest error here so the 7-arg call does not fall through to the core "MPI unavailable" -# stub, which would wrongly tell the user to load MPI when MPI is already loaded. +@inline _inner_exec(b::CB.AbstractMPIBackend) = SFC._bl_executor(CB.local_backend(b)) + +# --- 1D --- +# `count_eltype` is POSITIONAL, matching the core 1D dispatch in `dispatch.jl`, which passes it as +# the 7th positional argument. Declaring it as a keyword makes this method fail to match, and the +# call then falls through to the `(::AbstractMPIBackend, args...)` stub that reports "MPI +# unavailable" — a signature mismatch disguised as a missing package. function SFC._dispatch_execution_backend( - ::SFC.MPIBackend, - ::SFC.AbstractFieldShape, - ::SFT.AbstractPairwiseStructureFunctionType, + b::CB.AbstractMPIBackend, + shape::SFC.AbstractFieldShape, + structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins::AbstractVector, - value_bins::AbstractVector; + count_eltype::Type{CT} = UInt32; + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose = false, + show_progress = false, kwargs..., -) - throw(ArgumentError( - "2D joint structure functions are not yet implemented for MPIBackend; use a different \ - backend, or compute the 2D histogram with SerialBackend/ThreadedBackend per rank.")) +) where {CT} + if SFC.has_auxiliary_axes(shape) + OT = promote_type(float(eltype(x)), float(eltype(u))) + nb = n_histogram_bins(distance_bins) + bdims = size(u)[3:end] + sums = zeros(OT, nb, bdims...) + counts = zeros(CT, nb, bdims...) + SFC._bl_run_1d!(sums, counts, structure_function_type, x, u, + SFC.BinEdges(distance_bins), distance_metric, _mpi_bl_exec(_comm(b), _inner_exec(b))) + return SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, sums, counts) + end + return _mpi_point_1d(b, structure_function_type, x, u, distance_bins; + distance_metric = distance_metric, count_eltype = CT, kwargs...) end # Returns the raw accumulator; the public boundary applies `_finalize`. function _mpi_point_1d( - b::SFC.MPIBackend, + b::CB.AbstractMPIBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, - verbose = false, - show_progress = false, kwargs..., ) where {CT} comm = _comm(b) - rank = MPI.Comm_rank(comm) - nranks = MPI.Comm_size(comm) - D, N = size(x, 1), size(x, 2) - x_vecs = ntuple(k -> view(x, k, :), D) - u_vecs = ntuple(k -> view(u, k, :), D) - - # round-robin outer-index share balances the triangular pair work across ranks - ilist = (rank + 1):nranks:N + N = size(x, 2) + x_vecs = ntuple(k -> view(x, k, :), size(x, 1)) + u_vecs = ntuple(k -> view(u, k, :), size(u, 1)) + part = SFC._partial_sums_counts( - b.inner, structure_function_type, x_vecs, u_vecs, distance_bins, ilist; + CB.local_backend(b), structure_function_type, x_vecs, u_vecs, distance_bins, + _rank_share(comm, 1:(N - 1)); distance_metric = distance_metric, count_eltype = count_eltype, ) - sums = Array(part.sums) # contiguous buffers for in-place Allreduce - counts = Array(part.counts) - MPI.Allreduce!(sums, +, comm) - MPI.Allreduce!(counts, +, comm) - + sums, counts = _allreduce_pair!(comm, _dense(part.sums), _dense(part.counts)) return SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, sums, counts) end +# --- Joint 2D (distance x value) --- +function SFC._dispatch_execution_backend( + b::CB.AbstractMPIBackend, + shape::SFC.AbstractFieldShape, + structure_function_type::SFT.AbstractPairwiseStructureFunctionType, + x, + u, + distance_bins::AbstractVector, + value_bins::AbstractVector; + distance_metric::DI.PreMetric = DI.Euclidean(), + count_eltype::Type{CT} = UInt32, + verbose = false, + show_progress = false, + kwargs..., +) where {CT} + comm = _comm(b) + OT = promote_type(float(eltype(x)), float(eltype(u))) + nd = n_histogram_bins(distance_bins) + nv = n_histogram_bins(value_bins) + + if SFC.has_auxiliary_axes(shape) + bdims = size(u)[3:end] + sums = zeros(OT, nd, nv, bdims...) + counts = zeros(CT, nd, nv, bdims...) + SFC._bl_run_joint2d!(sums, counts, structure_function_type, x, u, + SFC.BinEdges(distance_bins), SFC.BinEdges(value_bins), distance_metric, + _mpi_bl_exec(comm, _inner_exec(b))) + return SFO.StructureFunction2DSumsAndCounts( + structure_function_type, distance_bins, value_bins, sums, counts) + end + + N = size(x, 2) + x_vecs = ntuple(k -> view(x, k, :), size(x, 1)) + u_vecs = ntuple(k -> view(u, k, :), size(u, 1)) + s, c = SFC._partial_2d_sums_counts( + CB.local_backend(b), structure_function_type, x_vecs, u_vecs, distance_bins, value_bins, + _rank_share(comm, 1:(N - 1)); + distance_metric = distance_metric, count_eltype = CT, + ) + sums, counts = _allreduce_pair!(comm, s, c) + return SFO.StructureFunction2DSumsAndCounts( + structure_function_type, distance_bins, value_bins, sums, counts) +end + +# --- Single pass 1D --- +function SFC._dispatch_single_pass( + b::CB.AbstractMPIBackend, + shape::SFC.AbstractFieldShape, + x::AbstractArray{FT1}, + u::AbstractArray{FT2}, + distance_bins::AbstractVector; + distance_metric::DI.PreMetric = DI.Euclidean(), + count_eltype::Type{CT} = UInt32, + kwargs..., +) where {FT1 <: Number, FT2 <: Number, CT} + comm = _comm(b) + OT = promote_type(float(FT1), float(FT2)) + nb = n_histogram_bins(distance_bins) + + if SFC.has_auxiliary_axes(shape) + bdims = size(u)[3:end] + sums = zeros(OT, SFC.SINGLE_PASS_N, nb, bdims...) + counts = zeros(CT, SFC.SINGLE_PASS_N, nb, bdims...) + SFC._bl_run_sp1d!(sums, counts, x, u, SFC.BinEdges(distance_bins), distance_metric, + _mpi_bl_exec(comm, _inner_exec(b))) + return (sums = sums, counts = counts) + end + + s, c = SFC._partial_single_pass_1d( + x, u, distance_bins, _rank_share(comm, 1:(size(x, 2) - 1)); + distance_metric = distance_metric, count_eltype = CT, + ) + sums, counts = _allreduce_pair!(comm, s, c) + return (sums = sums, counts = counts) +end + +# --- Single pass 2D --- +function SFC._dispatch_single_pass_2d( + b::CB.AbstractMPIBackend, + shape::SFC.AbstractFieldShape, + x::AbstractArray{FT1}, + u::AbstractArray{FT2}, + distance_bins::AbstractVector, + value_bins::SFC.SinglePass2DValueBins; + distance_metric::DI.PreMetric = DI.Euclidean(), + count_eltype::Type{CT} = UInt32, + kwargs..., +) where {FT1 <: Number, FT2 <: Number, CT} + comm = _comm(b) + OT = promote_type(float(FT1), float(FT2)) + nb = n_histogram_bins(distance_bins) + nv = length(SFC._sp2d_value_bin_at(value_bins, 1)) - 1 + + if SFC.has_auxiliary_axes(shape) + bdims = size(u)[3:end] + sums = zeros(OT, SFC.SINGLE_PASS_N, nb, nv, bdims...) + counts = zeros(CT, SFC.SINGLE_PASS_N, nb, nv, bdims...) + SFC._bl_run_sp2d!(sums, counts, x, u, SFC.BinEdges(distance_bins), value_bins, + distance_metric, _mpi_bl_exec(comm, _inner_exec(b))) + return sums, counts + end + + s, c = SFC._partial_single_pass_2d( + x, u, distance_bins, value_bins, _rank_share(comm, 1:(size(x, 2) - 1)); + distance_metric = distance_metric, count_eltype = CT, + ) + return _allreduce_pair!(comm, s, c) +end + end # module diff --git a/ext/StructureFunctionsOhMyThreadsExt.jl b/ext/StructureFunctionsOhMyThreadsExt.jl index 01c04b6..daf3938 100644 --- a/ext/StructureFunctionsOhMyThreadsExt.jl +++ b/ext/StructureFunctionsOhMyThreadsExt.jl @@ -4,6 +4,7 @@ using Distances: Distances as DI using OhMyThreads: OhMyThreads as OMT using StaticArrays: StaticArrays as SA using LinearAlgebra: LinearAlgebra as LA +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, @@ -56,7 +57,7 @@ function SFC.threaded_calculate_structure_function!( result = OMT.tmapreduce(+, _triangle_outer_chunks(eachindex(x_vecs[1]), Threads.nthreads())) do chunk local_output = zeros(OT, n_bins) local_counts = zeros(CT, n_bins) - vN = Val(length(x_vecs)) + vN = Val(length(u_vecs)) for i in chunk SFC.calculate_structure_function_i!( local_output, @@ -81,8 +82,8 @@ function SFC.threaded_calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, - distance_bins::AbstractVector; - count_eltype::Type{CT} = UInt32, + distance_bins::AbstractVector, + count_eltype::Type{CT} = UInt32; kwargs..., ) where {CT} FT1 = eltype(x_vecs[1]) @@ -145,14 +146,15 @@ function SFC.threaded_calculate_structure_function!( end # Fallback: scalar per-i over chunks - x_tuple = ntuple(k -> view(x_arr, k, :), N) - u_tuple = ntuple(k -> view(u_arr, k, :), N) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) + vD = Val(size(u_arr, 1)) result = OMT.tmapreduce(+, _triangle_outer_chunks(axes(x_arr, 2), Threads.nthreads())) do chunk local_output = zeros(OT, N3) local_counts = zeros(CT, N3) for i in chunk SFC.calculate_structure_function_i!( - local_output, local_counts, Val(N), structure_function_type, i, + local_output, local_counts, vD, structure_function_type, i, x_tuple, u_tuple, distance_bins; distance_metric = distance_metric, ) end @@ -175,12 +177,14 @@ function _threaded_pf_simd!( Np = size(x_arr, 2) nb = n_histogram_bins(dist_be) FTx = eltype(xc[1]) + plan = SF.squared_digitize_plan(dist_be) # built once; read-only, shared across tasks result = OMT.tmapreduce(+, _triangle_outer_chunks(1:(Np - 1), Threads.nthreads())) do chunk local_output = zeros(OT, nb) local_counts = zeros(CT, nb) - distbuf = Vector{FTx}(undef, Np) + r2buf = Vector{FTx}(undef, Np) valbuf = Vector{OT}(undef, Np) - SFC._pf_simd_pairs!(local_output, local_counts, sf, xc, uc, dist_be, Val(D), distbuf, valbuf, chunk) + idxbuf = Vector{Int32}(undef, Np) + SFC._pf_simd_pairs!(local_output, local_counts, sf, xc, uc, plan, Val(D), r2buf, valbuf, idxbuf, chunk) SFO.StructureFunctionSumsAndCounts(sf, dist_be, local_output, local_counts) end output_sums .+= result.sums @@ -192,8 +196,8 @@ function SFC.threaded_calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_arr::AbstractMatrix{FT1}, u_arr::AbstractMatrix{FT2}, - distance_bins::AbstractVector; - count_eltype::Type{CT} = UInt32, + distance_bins::AbstractVector, + count_eltype::Type{CT} = UInt32; kwargs..., ) where {FT1 <: Number, FT2 <: Number, CT} OT = promote_type(float(FT1), float(FT2)) @@ -244,7 +248,7 @@ function SFC.threaded_calculate_structure_function!( N4 = n_histogram_bins(value_bins) # Fast path: Euclidean + D ∈ (2,3) threads the 2D SIMD compute/scatter kernel. - D = length(x_vecs) + D = length(u_vecs) if distance_metric isa DI.Euclidean && (D == 2 || D == 3) _threaded_2d_simd!(sums_2d, counts_2d, structure_function_type, x_vecs, u_vecs, distance_bins, value_bins, D == 2 ? Val(2) : Val(3)) @@ -255,7 +259,7 @@ function SFC.threaded_calculate_structure_function!( result = OMT.tmapreduce(+, _triangle_outer_chunks(eachindex(x_vecs[1]), Threads.nthreads())) do chunk local_sums = zeros(OT, N3, N4) local_counts = zeros(CT, N3, N4) - vN = Val(length(x_vecs)) + vN = Val(length(u_vecs)) for i in chunk SFC.calculate_structure_function_2d_i!( local_sums, local_counts, vN, structure_function_type, i, @@ -282,12 +286,14 @@ function _threaded_2d_simd!( n_dist = n_histogram_bins(dist_be) n_val = n_histogram_bins(val_be) FTx = eltype(xc[1]) + j2d_plan = SF.squared_digitize_plan(dist_be) # built once; read-only, shared across tasks result = OMT.tmapreduce(+, _triangle_outer_chunks(1:(Np - 1), Threads.nthreads())) do chunk local_sums = zeros(OT, n_dist, n_val) local_counts = zeros(CT, n_dist, n_val) - distbuf = Vector{FTx}(undef, Np) + keybuf = Vector{FTx}(undef, Np) valbuf = Vector{OT}(undef, Np) - SFC._pf_2d_simd_pairs!(local_sums, local_counts, sf, xc, uc, dist_be, val_be, Val(D), distbuf, valbuf, chunk) + idxbuf = Vector{Int32}(undef, Np) + SFC._pf_2d_simd_pairs!(local_sums, local_counts, sf, xc, uc, j2d_plan, val_be, Val(D), keybuf, valbuf, idxbuf, chunk) SFO.StructureFunction2DSumsAndCounts(sf, dist_be, val_be, local_sums, local_counts) end sums2d .+= result.sums @@ -345,9 +351,8 @@ function SFC.threaded_calculate_structure_function!( value_bins::AbstractVector; kwargs..., ) where {OT, FT1 <: Number, FT2 <: Number} - N_dims = size(x_arr, 1) - x_tuple = ntuple(k -> view(x_arr, k, :), N_dims) - u_tuple = ntuple(k -> view(u_arr, k, :), N_dims) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return SFC.threaded_calculate_structure_function!( sums_2d, counts_2d, @@ -420,19 +425,19 @@ end # https://juliafolds2.github.io/OhMyThreads.jl/stable/translation/ function SFC._dispatch_single_pass( - ::SF.ThreadedBackend, + ::CB.AbstractThreadedBackend, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}; distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, - kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} + dist_be = BinEdges(distance_bins) OT = promote_type(float(FT1), float(FT2)) n_bins = length(distance_bins) - 1 n_points = size(x, 2) - D = size(x, 1) - vD = Val(D) + D = size(u, 1) + vW, vD = SFC._pair_dims(distance_metric, D) # Fast path: Euclidean + D ∈ (2,3) threads the SIMD compute/scatter single-pass kernel. if distance_metric isa DI.Euclidean && (D == 2 || D == 3) @@ -446,46 +451,13 @@ function SFC._dispatch_single_pass( # The reducer `+` merges partial results via element-wise addition. # This produces O(nthreads) allocations total — not O(n_points). (sums, counts) = OMT.tmapreduce( - ((s1, c1), (s2, c2)) -> (s1 .+ s2, c1 .+ c2), + ((s1, c1), (s2, c2)) -> (s1 .+= s2; c1 .+= c2; (s1, c1)), _triangle_outer_chunks(1:n_points, Threads.nthreads()) ) do chunk local_sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins) local_counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins) - - for i in chunk - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) - - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i - - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_norm2 = LA.dot(du, du) - du_T2 = du_norm2 - du_L2 - - # Accumulate the six invariant bulk structure functions. - @inbounds local_sums[1, bin_idx] += du_norm2 # S2SF - @inbounds local_sums[2, bin_idx] += du_L2 # L2SF - @inbounds local_sums[3, bin_idx] += du_T2 # T2SF - @inbounds local_sums[4, bin_idx] += du_L * du_norm2 # S3SF - @inbounds local_sums[5, bin_idx] += du_L * du_L2 # L3SF - @inbounds local_sums[6, bin_idx] += du_L * du_T2 # L1T2SF - - @inbounds for t in 1:SFC.SINGLE_PASS_N - local_counts[t, bin_idx] += one(CT) - end - end - end - end + SFC._sp1d_pairs!(local_sums, local_counts, x, u, dist_be, vW, vD, + distance_metric, n_bins, chunk) (local_sums, local_counts) end @@ -493,19 +465,19 @@ function SFC._dispatch_single_pass( end function SFC._dispatch_single_pass!( - ::SF.ThreadedBackend, + ::CB.AbstractThreadedBackend, sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}; distance_metric::DI.PreMetric = DI.Euclidean(), - kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} + dist_be = BinEdges(distance_bins) n_bins = length(distance_bins) - 1 n_points = size(x, 2) - D = size(x, 1) - vD = Val(D) + D = size(u, 1) + vW, vD = SFC._pair_dims(distance_metric, D) # Fast path: Euclidean + D ∈ (2,3) threads the SIMD compute/scatter single-pass kernel. if distance_metric isa DI.Euclidean && (D == 2 || D == 3) @@ -514,45 +486,13 @@ function SFC._dispatch_single_pass!( end chunk_sums, chunk_counts = OMT.tmapreduce( - ((s1, c1), (s2, c2)) -> (s1 .+ s2, c1 .+ c2), + ((s1, c1), (s2, c2)) -> (s1 .+= s2; c1 .+= c2; (s1, c1)), _triangle_outer_chunks(1:n_points, Threads.nthreads()), ) do chunk local_sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins) local_counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins) - - for i in chunk - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) - - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i - - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_norm2 = LA.dot(du, du) - du_T2 = du_norm2 - du_L2 - - @inbounds local_sums[1, bin_idx] += du_norm2 - @inbounds local_sums[2, bin_idx] += du_L2 - @inbounds local_sums[3, bin_idx] += du_T2 - @inbounds local_sums[4, bin_idx] += du_L * du_norm2 - @inbounds local_sums[5, bin_idx] += du_L * du_L2 - @inbounds local_sums[6, bin_idx] += du_L * du_T2 - - @inbounds for t in 1:SFC.SINGLE_PASS_N - local_counts[t, bin_idx] += one(CT) - end - end - end - end + SFC._sp1d_pairs!(local_sums, local_counts, x, u, dist_be, vW, vD, + distance_metric, n_bins, chunk) (local_sums, local_counts) end @@ -571,16 +511,18 @@ function _threaded_sp_simd!( Np = size(x, 2) nb = n_histogram_bins(dist_be) FTx = eltype(xc[1]) + sp_plan = SF.squared_digitize_plan(dist_be) # built once; read-only, shared across tasks cs, cc = OMT.tmapreduce( - ((s1, c1), (s2, c2)) -> (s1 .+ s2, c1 .+ c2), + ((s1, c1), (s2, c2)) -> (s1 .+= s2; c1 .+= c2; (s1, c1)), _triangle_outer_chunks(1:(Np - 1), Threads.nthreads()), ) do chunk ls = zeros(OT, SFC.SINGLE_PASS_N, nb) lc = zeros(CT, SFC.SINGLE_PASS_N, nb) - distbuf = Vector{FTx}(undef, Np) + keybuf = Vector{FTx}(undef, Np) duLbuf = Vector{OT}(undef, Np) dn2buf = Vector{OT}(undef, Np) - SFC._pf_sp_simd_pairs!(ls, lc, xc, uc, dist_be, Val(D), distbuf, duLbuf, dn2buf, chunk) + idxbuf = Vector{Int32}(undef, Np) + SFC._pf_sp_simd_pairs!(ls, lc, xc, uc, sp_plan, Val(D), keybuf, duLbuf, dn2buf, idxbuf, chunk) (ls, lc) end sums .+= cs @@ -589,79 +531,26 @@ function _threaded_sp_simd!( end function SFC._dispatch_single_pass_2d( - ::SF.ThreadedBackend, + ::CB.AbstractThreadedBackend, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}, value_bins::SFC.SinglePass2DValueBins; distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, - kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} OT = promote_type(float(FT1), float(FT2)) - n_bins = length(distance_bins) - 1 - vb0 = SFC._sp2d_value_bin_at(value_bins, 1) - n_val = length(vb0) - 1 - n_points = size(x, 2) - D = size(x, 1) - vD = Val(D) - - (sums, counts) = OMT.tmapreduce( - ((s1, c1), (s2, c2)) -> (s1 .+ s2, c1 .+ c2), - _triangle_outer_chunks(1:n_points, Threads.nthreads()), - ) do chunk - local_sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins, n_val) - local_counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins, n_val) - - for i in chunk - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) - - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i - - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_norm2 = LA.dot(du, du) - du_T2 = du_norm2 - du_L2 - - vals = ( - du_norm2, - du_L2, - du_T2, - du_L * du_norm2, - du_L * du_L2, - du_L * du_T2, - ) - - for t in 1:SFC.SINGLE_PASS_N - vb = SFC._sp2d_value_bin_at(value_bins, t) - vbin = SFH.digitize(vals[t], vb) - n_val_t = length(vb) - 1 - if 1 <= vbin <= n_val_t && vbin <= n_val - @inbounds local_sums[t, bin_idx, vbin] += vals[t] - @inbounds local_counts[t, bin_idx, vbin] += 1 - end - end - end - end - end - (local_sums, local_counts) - end - + n_bins = SFC.n_histogram_bins(distance_bins) + n_val = length(SFC._sp2d_value_bin_at(value_bins, 1)) - 1 + sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins, n_val) + counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins, n_val) + _threaded_sp2d!(sums, counts, x, u, BinEdges(distance_bins), value_bins, + distance_metric, n_bins, n_val) return sums, counts end function SFC._dispatch_single_pass_2d!( - ::SF.ThreadedBackend, + ::CB.AbstractThreadedBackend, sums_3d::AbstractArray{OT, 3}, counts_3d::AbstractArray{CT, 3}, x::AbstractMatrix{FT1}, @@ -669,68 +558,31 @@ function SFC._dispatch_single_pass_2d!( distance_bins::AbstractVector{FT3}, value_bins::SFC.SinglePass2DValueBins; distance_metric::DI.PreMetric = DI.Euclidean(), - kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} - n_bins = length(distance_bins) - 1 - n_val = size(sums_3d, 3) - n_points = size(x, 2) - D = size(x, 1) - vD = Val(D) + _threaded_sp2d!(sums_3d, counts_3d, x, u, BinEdges(distance_bins), value_bins, + distance_metric, SFC.n_histogram_bins(distance_bins), size(sums_3d, 3)) + return sums_3d, counts_3d +end - chunk_sums, chunk_counts = OMT.tmapreduce( - ((s1, c1), (s2, c2)) -> (s1 .+ s2, c1 .+ c2), +# Round-robin outer-index chunks, thread-local accumulators reduced in place; each chunk runs the +# same single-pass 2D kernel the serial and distributed drivers use. The reduction is over the +# compact interleaved accumulator, so the unpack to (6, n_bins, n_val) runs once, not per chunk. +function _threaded_sp2d!( + sums_3d::AbstractArray{OT, 3}, counts_3d::AbstractArray{CT, 3}, + x::AbstractMatrix, u::AbstractMatrix, dist_be, value_bins, distance_metric, + n_bins::Int, n_val::Int, +) where {OT, CT} + n_points = size(x, 2) + h = OMT.tmapreduce( + (a, b) -> (a .+= b; a), _triangle_outer_chunks(1:n_points, Threads.nthreads()), ) do chunk - local_sums = zeros(OT, SFC.SINGLE_PASS_N, n_bins, n_val) - local_counts = zeros(CT, SFC.SINGLE_PASS_N, n_bins, n_val) - - for i in chunk - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) - - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i - - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_norm2 = LA.dot(du, du) - du_T2 = du_norm2 - du_L2 - - vals = ( - du_norm2, - du_L2, - du_T2, - du_L * du_norm2, - du_L * du_L2, - du_L * du_T2, - ) - - for t in 1:SFC.SINGLE_PASS_N - vb = SFC._sp2d_value_bin_at(value_bins, t) - vbin = SFH.digitize(vals[t], vb) - n_val_t = length(vb) - 1 - if 1 <= vbin <= n_val_t && vbin <= n_val - @inbounds local_sums[t, bin_idx, vbin] += vals[t] - @inbounds local_counts[t, bin_idx, vbin] += 1 - end - end - end - end - end - (local_sums, local_counts) + hloc = SFC._sp2d_histogram(OT, n_bins, n_val) + SFC._sp2d_fill!(hloc, x, u, dist_be, value_bins, distance_metric, n_bins, n_val, chunk) + hloc end - - sums_3d .+= chunk_sums - counts_3d .+= chunk_counts - return sums_3d, counts_3d + SFC._sp2d_unpack!(sums_3d, counts_3d, h, n_bins, n_val) + return nothing end # ============================================================================================ @@ -742,50 +594,85 @@ end # more specialized than the generic core serial-fallback stubs, so they win dispatch here. # ============================================================================================ -@inline _bl_accum_reduce(a, b) = (a[1] .+ b[1], a[2] .+ b[2]) +# Executor: partition the (i, b) index space. `i` is split round-robin (triangular load balance); +# `b` is split only as far as the accumulator budget demands, because each batch chunk recomputes +# the pair geometry. Tasks in different batch chunks own disjoint output slices, so a task writes +# only its own accumulator and the slices are summed into the result afterwards. +function _bl_threaded_exec(make_accum, run_chunk!, ifull, B, accum_bytes, ws) + nt = Threads.nthreads() + if nt <= 1 || length(ifull) <= 1 + acc = SFC._bl_zero_accum!(SFC._bl_accum_pool(ws, make_accum, [B])[1]) + run_chunk!(acc, ifull, 1:B) + return acc + end -# per-chunk work as a named function so the assigned `acc` is not a boxed closure capture -# (OhMyThreads rejects boxed captures; see its boxing docs). -@inline function _bl_run_one_chunk(make_accum, run_chunk!, isub) - acc = make_accum() - run_chunk!(acc, isub) - return acc -end + bchunks, n_ichunks = SFC._bl_partition(B, nt, accum_bytes) + ichunks = collect(OMT.chunks(ifull; n = n_ichunks, split = OMT.RoundRobin())) + tasks = [(bc, isub) for bc in bchunks for isub in ichunks] + pool = SFC._bl_accum_pool(ws, make_accum, [length(t[1]) for t in tasks]) + length(pool) == length(tasks) || throw(ArgumentError( + "CPUSFWorkspace holds $(length(pool)) accumulators; this call needs $(length(tasks))")) -# executor: round-robin chunks of the outer i-range; per-chunk thread-local accumulators reduced by +. -function _bl_threaded_exec(make_accum, run_chunk!, ifull) - nt = Threads.nthreads() - (nt <= 1 || length(ifull) <= 1) && return _bl_run_one_chunk(make_accum, run_chunk!, ifull) - return OMT.tmapreduce(_bl_accum_reduce, OMT.chunks(ifull; n = nt, split = OMT.RoundRobin())) do isub - _bl_run_one_chunk(make_accum, run_chunk!, isub) + OMT.tforeach(eachindex(tasks)) do k + brange, isub = tasks[k] + _bl_run_one_chunk(pool[k], run_chunk!, isub, brange) + end + + result = SFC._bl_result_accum(ws, make_accum, B) + for (k, (brange, _)) in enumerate(tasks) + selectdim(result[1], 1, brange) .+= pool[k][1] + selectdim(result[2], 1, brange) .+= pool[k][2] end + return result +end + +# Named function so the pooled accumulator is concretely typed inside the task (the pool is +# heterogeneous in batch width, so indexing it is a dynamic call — once per task, not per pair). +@inline function _bl_run_one_chunk(acc, run_chunk!, isub, brange) + SFC._bl_zero_accum!(acc) + run_chunk!(acc, isub, brange) + return acc end +SFC._bl_executor(::CB.AbstractThreadedBackend) = _bl_threaded_exec + function SFC.auxiliary_structure_function_threaded!( sums::AbstractArray, counts::AbstractArray, - sf_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs..., + sf_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true, ) - SFC._bl_run_1d!(sums, counts, sf_type, x, u, BinEdges(distance_bins), _bl_threaded_exec) + SFC._bl_run_1d!(sums, counts, sf_type, x, u, BinEdges(distance_bins), distance_metric, + _bl_threaded_exec, workspace) end function SFC.auxiliary_joint2d_threaded!( sums::AbstractArray, counts::AbstractArray, - sf_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins; kwargs..., + sf_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true, ) - SFC._bl_run_joint2d!(sums, counts, sf_type, x, u, BinEdges(distance_bins), BinEdges(value_bins), _bl_threaded_exec) + SFC._bl_run_joint2d!(sums, counts, sf_type, x, u, BinEdges(distance_bins), BinEdges(value_bins), + distance_metric, _bl_threaded_exec, workspace) end function SFC.threaded_calculate_structure_functions_single_pass!( - sums::AbstractArray, counts::AbstractArray, x, u, distance_bins; kwargs..., + sums::AbstractArray, counts::AbstractArray, x, u, distance_bins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true, ) - SFC._bl_run_sp1d!(sums, counts, x, u, BinEdges(distance_bins), _bl_threaded_exec) + SFC._bl_run_sp1d!(sums, counts, x, u, BinEdges(distance_bins), distance_metric, + _bl_threaded_exec, workspace) end function SFC.threaded_calculate_structure_functions_single_pass_2d!( sums::AbstractArray, counts::AbstractArray, x, u, distance_bins, - value_bins::SFC.SinglePass2DValueBins; kwargs..., + value_bins::SFC.SinglePass2DValueBins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true, ) - SFC._bl_run_sp2d!(sums, counts, x, u, BinEdges(distance_bins), value_bins, _bl_threaded_exec) + SFC._bl_run_sp2d!(sums, counts, x, u, BinEdges(distance_bins), value_bins, distance_metric, + _bl_threaded_exec, workspace) end # Batched (ndims(u) >= 3) non-mutating joint-2D. The AbstractMatrix method earlier is more @@ -813,7 +700,7 @@ end # Threaded partial over an explicit outer-index list (hybrid distributed+threaded: a worker # threads over its assigned i-list). Round-robin chunks for triangle balance; reduce by +. function SFC._partial_sums_counts( - ::SFC.ThreadedBackend, + ::CB.AbstractThreadedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, @@ -825,15 +712,23 @@ function SFC._partial_sums_counts( OT = promote_type(float(eltype(eltype(x_vecs))), float(eltype(eltype(u_vecs)))) nb = n_histogram_bins(distance_bins) be = BinEdges(distance_bins) - vN = Val(length(x_vecs)) + D = length(u_vecs) + vN = Val(D) + simd = distance_metric isa DI.Euclidean && (D == 2 || D == 3) result = OMT.tmapreduce(+, _triangle_outer_chunks(ilist, Threads.nthreads())) do chunk local_sums = zeros(OT, nb) local_counts = zeros(CT, nb) - for i in chunk - SFC.calculate_structure_function_i!( - local_sums, local_counts, vN, structure_function_type, i, x_vecs, u_vecs, be; - distance_metric = distance_metric, - ) + if simd + D == 2 ? + SFC._pf_simd_partial!(local_sums, local_counts, structure_function_type, x_vecs, u_vecs, be, Val(2), chunk) : + SFC._pf_simd_partial!(local_sums, local_counts, structure_function_type, x_vecs, u_vecs, be, Val(3), chunk) + else + for i in chunk + SFC.calculate_structure_function_i!( + local_sums, local_counts, vN, structure_function_type, i, x_vecs, u_vecs, be; + distance_metric = distance_metric, + ) + end end SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, local_sums, local_counts) end diff --git a/ext/cuda/kernels_1d.jl b/ext/cuda/kernels_1d.jl index 57911e5..5cc1a29 100644 --- a/ext/cuda/kernels_1d.jl +++ b/ext/cuda/kernels_1d.jl @@ -24,6 +24,7 @@ function _cuda_sf_1d_kernel!( N::Int, NB::Int, nt::Int, ntb::Int, ::Val{D}, ::Val{NMOM}, ::Val{FIXED_X}, ::Val{TILE}, + geom, ) where {D, NMOM, FIXED_X, TILE} FT = eltype(output) lid = Int(threadIdx().x) @@ -87,13 +88,12 @@ function _cuda_sf_1d_kernel!( Xj = _cuda_ld(sxj, Val(D), Val(TILE), jj) Uj = _cuda_ld(suj, Val(D), Val(TILE), jj) end - dX = Xj - Xi - dist = sqrt(GE._sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = ddig(dist) - if 1 <= bin <= NB - rhat = dX / dist - moments = GE._sf_moments(Val(NMOM), sf_type, Uj - Ui, rhat) - @inbounds for m in 1:NMOM + if ok && 1 <= bin <= NB + dU, rhat = SFH.pair_increments(geom, frame, dist, Xi, Xj, Ui, Uj) + moments = GE._sf_moments(Val(NMOM), sf_type, dU, rhat) + @inbounds for m in GE._sf_accum_moments(Val(NMOM)) CUDA.@atomic ssum[(m - 1) * NB + bin] += moments[m] end @inbounds CUDA.@atomic scnt[bin] += UInt32(1) @@ -105,10 +105,10 @@ function _cuda_sf_1d_kernel!( cell = lid while cell <= NMOM * NB - @inbounds s = ssum[cell] + m = (cell - 1) ÷ NB + 1 + bin = (cell - 1) % NB + 1 + s = GE._sf_flush_moment(Val(NMOM), ssum, NB, m, bin) if s != zero(FT) - m = (cell - 1) ÷ NB + 1 - bin = (cell - 1) % NB + 1 CUDA.@atomic output[m, bin, b] += s end cell += wg @@ -131,29 +131,29 @@ end exceeds the static-shared cap (caller uses the KA fallback). `out`/`cnt` are `(NMOM, NB, B)`; `x` is `(D,N,B)` varying or `(D,N)`/`(D,N,1)` fixed; `u` is `(D,N,B)`.""" function _cuda_launch_1d!(out, cnt, x, u, sf_type, ddig, - N::Int, NB::Int, B::Int, D::Int, NMOM::Int, fixed_x::Bool) + N::Int, NB::Int, B::Int, D::Int, NMOM::Int, fixed_x::Bool, geom) NB > CU_MAX_BINS && return false xv = fixed_x ? reshape(x, D, N, 1) : reshape(x, D, N, B) uv = reshape(u, D, N, B) - _cuda_launch_1d_specialized!(out, cnt, xv, uv, sf_type, ddig, N, NB, B, D, NMOM, fixed_x) + _cuda_launch_1d_specialized!(out, cnt, xv, uv, sf_type, ddig, N, NB, B, D, NMOM, fixed_x, geom) return true end -function _cuda_launch_1d_specialized!(out, cnt, x, u, sf_type, ddig, N, NB, B, D, NMOM, fixed_x) +function _cuda_launch_1d_specialized!(out, cnt, x, u, sf_type, ddig, N, NB, B, D, NMOM, fixed_x, geom) Dv = D == 3 ? Val(3) : Val(2) Mv = NMOM == 6 ? Val(6) : Val(1) Fv = fixed_x ? Val(true) : Val(false) - _cuda_launch_1d_valed!(out, cnt, x, u, sf_type, ddig, N, NB, B, Dv, Mv, Fv, Val(CU_TILE_1D)) + _cuda_launch_1d_valed!(out, cnt, x, u, sf_type, ddig, N, NB, B, Dv, Mv, Fv, Val(CU_TILE_1D), geom) return nothing end function _cuda_launch_1d_valed!(out, cnt, x, u, sf_type, ddig, N, NB, B, - ::Val{D}, ::Val{NMOM}, ::Val{FIXED_X}, ::Val{TILE}) where {D, NMOM, FIXED_X, TILE} + ::Val{D}, ::Val{NMOM}, ::Val{FIXED_X}, ::Val{TILE}, geom) where {D, NMOM, FIXED_X, TILE} nt = cld(N, TILE) ntb = nt * (nt + 1) ÷ 2 @cuda threads=TILE blocks=ntb*B _cuda_sf_1d_kernel!( out, cnt, x, u, sf_type, ddig, N, NB, nt, ntb, - Val(D), Val(NMOM), Val(FIXED_X), Val(TILE)) + Val(D), Val(NMOM), Val(FIXED_X), Val(TILE), geom) return nothing end diff --git a/ext/cuda/kernels_2d.jl b/ext/cuda/kernels_2d.jl index 9b16882..1193110 100644 --- a/ext/cuda/kernels_2d.jl +++ b/ext/cuda/kernels_2d.jl @@ -17,6 +17,19 @@ # D ∈ {2,3} — all via Val type params. Validated in proto_nbody2d / proto_settle. # ============================================================================= +""" + _cuda_val_stride(n_val) + +Row stride of the value axis in the privatized histogram, forced odd. + +Shared memory has 32 banks. With a power-of-two `n_val`, the flat index `(dbin-1)*n_val + vbin` puts +every value-axis row into the same couple of banks, so lanes differing only in `dbin` serialize on +bank conflicts even though they target different cells. An odd stride is coprime with 32 and spreads +them across banks, at the cost of one unused column per row. Measured 2.0–2.3× on the sibling +single-pass 2D kernel, which had identical indexing. +""" +@inline _cuda_val_stride(n_val::Int) = isodd(n_val) ? n_val : n_val + 1 + """Map linear tile id `k` (1-based) to upper-triangle `(ti,tj)`, `ti ≤ tj`.""" @inline function _cuda_tile_pair(k::Int, nt::Int) ti = 1 @@ -45,6 +58,7 @@ function _cuda_sf_2d_kernel!( N::Int, n_dist::Int, n_val::Int, nt::Int, ntb::Int, ::Val{D}, ::Val{NMOM}, ::Val{FIXED_X}, ::Val{TILE}, ::Val{HCELLS}, + geom, ) where {D, NMOM, FIXED_X, TILE, HCELLS} FT = eltype(output) lid = Int(threadIdx().x) @@ -57,6 +71,7 @@ function _cuda_sf_2d_kernel!( sxj = CuStaticSharedArray(FT, D * TILE) sui = CuStaticSharedArray(FT, D * TILE) suj = CuStaticSharedArray(FT, D * TILE) + vstride = _cuda_val_stride(n_val) sums = CuDynamicSharedArray(FT, NMOM * HCELLS) cnts = CuDynamicSharedArray(UInt32, NMOM * HCELLS, NMOM * HCELLS * sizeof(FT)) @@ -107,16 +122,15 @@ function _cuda_sf_2d_kernel!( Xj = _cuda_ld(sxj, Val(D), Val(TILE), jj) Uj = _cuda_ld(suj, Val(D), Val(TILE), jj) end - dX = Xj - Xi - dist = sqrt(GE._sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = ddig(dist) - if 1 <= dbin <= n_dist - rhat = dX / dist - moments = GE._sf_moments(Val(NMOM), sf_type, Uj - Ui, rhat) + if ok && 1 <= dbin <= n_dist + dU, rhat = SFH.pair_increments(geom, frame, dist, Xi, Xj, Ui, Uj) + moments = GE._sf_moments(Val(NMOM), sf_type, dU, rhat) @inbounds for m in 1:NMOM vb = GE._gpu_digitize_value_plan(moments[m], vplan, m, n_val + 1) if 1 <= vb <= n_val - cell = (m - 1) * HCELLS + (dbin - 1) * n_val + vb + cell = (m - 1) * HCELLS + (dbin - 1) * vstride + vb CUDA.@atomic sums[cell] += moments[m] CUDA.@atomic cnts[cell] += UInt32(1) end @@ -132,11 +146,12 @@ function _cuda_sf_2d_kernel!( while cell <= NMOM * HCELLS @inbounds s = sums[cell] @inbounds cc = cnts[cell] - if cc != UInt32(0) - m = (cell - 1) ÷ HCELLS + 1 - lc = (cell - 1) % HCELLS - dbin = lc ÷ n_val + 1 - vb = lc % n_val + 1 + m = (cell - 1) ÷ HCELLS + 1 + lc = (cell - 1) % HCELLS + dbin = lc ÷ vstride + 1 + vb = lc % vstride + 1 + # vb > n_val is a padding column, never written + if cc != UInt32(0) && vb <= n_val CUDA.@atomic output[m, dbin, vb, b] += s CUDA.@atomic counts[m, dbin, vb, b] += cc end @@ -145,19 +160,26 @@ function _cuda_sf_2d_kernel!( return nothing end -"""Largest TILE ∈ (1024,512,256) whose staging + dynamic histogram fit the device -opt-in shared max; 0 if even 256 won't fit (caller falls back to the KA path).""" +"""Largest TILE ∈ (1024,512,256) whose staging + the full `NMOM`-plane dynamic histogram fit the +device opt-in shared max; 0 if even 256 won't fit. + +Returning 0 hands the call to the naive global-atomic kernel, which is the measured winner whenever +the histogram does not fit on chip: contention spreads over many cells, and it beats every on-chip +variant there (128×128 Float64: 5.95 vs 0.75 bapps). Splitting the histogram into moment planes to +force it on chip was implemented and measured — it is ~2× *slower* than going global, so the +all-or-nothing test below is deliberate. See `gpu/SPEED_OF_LIGHT.md`.""" function _cuda_2d_pick_tile(::Type{FT}, D::Int, NMOM::Int, n_dist::Int, n_val::Int) where {FT} - optin = try - dev = CUDA.device() - Int(CUDA.attribute(dev, CUDA.DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN)) - catch - 48 * 1024 - end - dynb = NMOM * n_dist * n_val * (sizeof(FT) + sizeof(UInt32)) + # Queried, never assumed: this is only reached via the CUDABackend hook, so a device is present + # by construction and a failure here is a real driver fault. Defaulting to the 48 KB static cap + # instead would silently forfeit ~3.4× the shared budget on an A100 (163 KB opt-in). + optin = Int(CUDA.attribute(CUDA.device(), CUDA.DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN)) + dynb = NMOM * n_dist * _cuda_val_stride(n_val) * (sizeof(FT) + sizeof(UInt32)) for TILE in (1024, 512, 256) staging = 4 * D * TILE * sizeof(FT) - if staging + dynb <= optin + # Staging is `CuStaticSharedArray`, capped by the architecture independently of the opt-in; + # only `dynb` may draw on the larger budget. Testing the sum against `optin` alone lets ptxas + # reject the kernel at compile time (Float64, D=2, TILE=1024 needs 64 KiB of static shared). + if staging <= SFC.GPU_SMEM_STATIC_MAX && staging + dynb <= optin return TILE, dynb end end @@ -170,39 +192,39 @@ histogram doesn't fit any supported TILE (caller uses the KA fallback). `(D,N,1)` fixed; `u` is `(D,N,B)`.""" function _cuda_launch_2d!(out, cnt, x, u, sf_type, ddig, vplan, N::Int, n_dist::Int, n_val::Int, B::Int, - D::Int, NMOM::Int, fixed_x::Bool) + D::Int, NMOM::Int, fixed_x::Bool, geom) FT = eltype(out) TILE, dynb = _cuda_2d_pick_tile(FT, D, NMOM, n_dist, n_val) TILE == 0 && return false xv = fixed_x ? reshape(x, D, N, 1) : reshape(x, D, N, B) uv = reshape(u, D, N, B) - hcells = n_dist * n_val + hcells = n_dist * _cuda_val_stride(n_val) _cuda_launch_2d_specialized!(out, cnt, xv, uv, sf_type, ddig, vplan, - N, n_dist, n_val, B, D, NMOM, fixed_x, TILE, hcells, dynb) + N, n_dist, n_val, B, D, NMOM, fixed_x, TILE, hcells, dynb, geom) return true end # Resolve the runtime (D, NMOM, FIXED_X, TILE) into Val type params, then launch. function _cuda_launch_2d_specialized!(out, cnt, x, u, sf_type, ddig, vplan, - N, n_dist, n_val, B, D, NMOM, fixed_x, TILE, hcells, dynb) + N, n_dist, n_val, B, D, NMOM, fixed_x, TILE, hcells, dynb, geom) Dv = D == 3 ? Val(3) : Val(2) Mv = NMOM == 6 ? Val(6) : Val(1) Fv = fixed_x ? Val(true) : Val(false) Tv = TILE == 1024 ? Val(1024) : TILE == 512 ? Val(512) : Val(256) _cuda_launch_2d_valed!(out, cnt, x, u, sf_type, ddig, vplan, - N, n_dist, n_val, B, Dv, Mv, Fv, Tv, Val(hcells), dynb) + N, n_dist, n_val, B, Dv, Mv, Fv, Tv, Val(hcells), dynb, geom) return nothing end function _cuda_launch_2d_valed!(out, cnt, x, u, sf_type, ddig, vplan, N, n_dist, n_val, B, ::Val{D}, ::Val{NMOM}, ::Val{FIXED_X}, ::Val{TILE}, ::Val{HCELLS}, - dynb) where {D, NMOM, FIXED_X, TILE, HCELLS} + dynb, geom) where {D, NMOM, FIXED_X, TILE, HCELLS} nt = cld(N, TILE) ntb = nt * (nt + 1) ÷ 2 kern = @cuda launch=false _cuda_sf_2d_kernel!( out, cnt, x, u, sf_type, ddig, vplan, N, n_dist, n_val, nt, ntb, - Val(D), Val(NMOM), Val(FIXED_X), Val(TILE), Val(HCELLS)) + Val(D), Val(NMOM), Val(FIXED_X), Val(TILE), Val(HCELLS), geom) # Opt into the larger shared budget. This must be set whenever the TOTAL # (static staging + dynamic histogram) exceeds the 48 KB default cap — not # only when the dynamic part alone does — so set it unconditionally. The @@ -210,7 +232,7 @@ function _cuda_launch_2d_valed!(out, cnt, x, u, sf_type, ddig, vplan, # ≤ the device opt-in max. CUDA.attributes(kern.fun)[CUDA.FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES] = dynb kern(out, cnt, x, u, sf_type, ddig, vplan, N, n_dist, n_val, nt, ntb, - Val(D), Val(NMOM), Val(FIXED_X), Val(TILE), Val(HCELLS); + Val(D), Val(NMOM), Val(FIXED_X), Val(TILE), Val(HCELLS), geom; threads = TILE, blocks = ntb * B, shmem = dynb) return nothing end diff --git a/ext/gpu/batch_dispatch.jl b/ext/gpu/batch_dispatch.jl index 130db8a..0b73ee7 100644 --- a/ext/gpu/batch_dispatch.jl +++ b/ext/gpu/batch_dispatch.jl @@ -1,5 +1,5 @@ # GPU batch routing — fixed-x / varying-x fused launches. -# Included from StructureFunctionsGPUExt.jl after BatchLaunch.jl. +# Included from StructureFunctionsKernelAbstractionsExt.jl after BatchLaunch.jl. """Typed fast-path selector for the fixed-x tiled FMA kernels. @@ -50,7 +50,7 @@ fixed-x and varying-x, `D ∈ {2,3}`, any distance-bin type `(NMOM, NB, B)`. `u` is staged `(D,N,B)` with NO batch-major permute.""" function _gpu_1d_unified_device( backend, x, u, sf_type, distance_bins, - ::Val{NMOM}, NB::Int, B::Int, fixed_x::Bool, ::Type{OT}, + ::Val{NMOM}, NB::Int, B::Int, fixed_x::Bool, ::Type{OT}, geom, ) where {NMOM, OT} D = size(x, 1) N = size(x, 2) @@ -65,7 +65,7 @@ function _gpu_1d_unified_device( u_dev = KA.adapt(backend, reshape(u, D, N, B)) end _sf_launch_1d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, dig, - N, NB, B, D, Val(NMOM), fixed_x) + N, NB, B, D, Val(NMOM), fixed_x, geom) KA.synchronize(backend) return Array(out_dev), Array(cnt_dev) end @@ -78,17 +78,17 @@ kernel per regime (job 239164, histograms verified equal): bapps for the old kernel on varying-x; also handles general bins). Returns host `(sums, counts)` of shape `(NB, B)`.""" function _gpu_1d_individual_device(backend, sf_type, x, u, distance_bins, - NB::Int, B::Int, fixed_x::Bool, ::Type{OT}) where {OT} + NB::Int, B::Int, fixed_x::Bool, ::Type{OT}, geom) where {OT} lbe = fixed_x ? _fma_distance_bins(distance_bins) : nothing if lbe !== nothing N = size(x, 2) sums_dev = KA.adapt(backend, zeros(OT, NB, B)) counts_dev = KA.adapt(backend, zeros(UInt32, NB, B)) x_dev, u_dev = _stage_batch_device(backend, x, u; fixed_x = true) - _launch_batch_fixed_x_sf!(backend, sums_dev, counts_dev, x_dev, u_dev, sf_type, N, B, lbe) + _launch_batch_fixed_x_sf!(backend, sums_dev, counts_dev, x_dev, u_dev, sf_type, N, B, lbe, geom) return Array(sums_dev), Array(counts_dev) end - oh, ch = _gpu_1d_unified_device(backend, x, u, sf_type, distance_bins, Val(1), NB, B, fixed_x, OT) + oh, ch = _gpu_1d_unified_device(backend, x, u, sf_type, distance_bins, Val(1), NB, B, fixed_x, OT, geom) return reshape(oh, NB, B), reshape(ch, NB, B) end @@ -104,13 +104,16 @@ function _gpu_calculate_structure_function_batch( u::AbstractArray{FT}, distance_bins::AbstractVector{FT}; count_eltype::Type{CT} = UInt32, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT, CT} fixed_x = ndims(x) == 2 NB = length(distance_bins) - 1 B = SFC.batch_size(u) bdims = SFC.batch_dims(u) - out_host, cnt_host = _gpu_1d_individual_device(backend, sf_type, x, u, distance_bins, NB, B, fixed_x, FT) + out_host, cnt_host = _gpu_1d_individual_device(backend, sf_type, x, u, distance_bins, NB, B, fixed_x, FT, + SFH.pair_geometry_for(distance_metric, size(x, 1) == 3 ? Val(3) : Val(2))) sums = reshape(out_host, NB, bdims...) counts = reshape(cnt_host, NB, bdims...) return SF.StructureFunctionSumsAndCounts( @@ -126,13 +129,16 @@ function _gpu_calculate_structure_function_batch!( x::AbstractArray{FT}, u::AbstractArray{FT}, distance_bins::AbstractVector{FT}; - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT} fixed_x = ndims(x) == 2 NB = length(distance_bins) - 1 B = SFC.batch_size(u) out_host, cnt_host = _gpu_1d_individual_device( - backend, sf_type, x, u, distance_bins, NB, B, fixed_x, eltype(output_sums)) + backend, sf_type, x, u, distance_bins, NB, B, fixed_x, eltype(output_sums), + SFH.pair_geometry_for(distance_metric, size(x, 1) == 3 ? Val(3) : Val(2))) output_sums .+= reshape(out_host, size(output_sums)...) cflat = reshape(cnt_host, size(output_counts)...) if eltype(output_counts) === UInt32 @@ -163,7 +169,9 @@ function _gpu_dispatch_single_pass_batch( u::AbstractArray{FT2}, distance_bins::AbstractVector{FT3}; count_eltype::Type{CT} = UInt32, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT1, FT2, FT3, CT} FT = promote_type(float(FT1), float(FT2)) fixed_x = ndims(x) == 2 @@ -171,7 +179,8 @@ function _gpu_dispatch_single_pass_batch( B = SFC.batch_size(u) bdims = SFC.batch_dims(u) out_host, cnt_host = _gpu_1d_unified_device( - backend, x, u, nothing, distance_bins, Val(SFC.SINGLE_PASS_N), NB, B, fixed_x, FT) + backend, x, u, nothing, distance_bins, Val(SFC.SINGLE_PASS_N), NB, B, fixed_x, FT, + SFH.pair_geometry_for(distance_metric, size(x, 1) == 3 ? Val(3) : Val(2))) sums = reshape(out_host, SFC.SINGLE_PASS_N, NB, bdims...) counts_u32 = reshape(cnt_host, SFC.SINGLE_PASS_N, NB, bdims...) return (sums = sums, counts = CT === UInt32 ? counts_u32 : CT.(counts_u32)) @@ -184,13 +193,16 @@ function _gpu_dispatch_single_pass_batch!( x::AbstractArray{FT1}, u::AbstractArray{FT2}, distance_bins::AbstractVector{FT3}; - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {OT, CT, FT1, FT2, FT3} fixed_x = ndims(x) == 2 NB = length(distance_bins) - 1 B = SFC.batch_size(u) out_host, cnt_host = _gpu_1d_unified_device( - backend, x, u, nothing, distance_bins, Val(SFC.SINGLE_PASS_N), NB, B, fixed_x, OT) + backend, x, u, nothing, distance_bins, Val(SFC.SINGLE_PASS_N), NB, B, fixed_x, OT, + SFH.pair_geometry_for(distance_metric, size(x, 1) == 3 ? Val(3) : Val(2))) sums .+= reshape(out_host, size(sums)...) cflat = reshape(cnt_host, size(counts)...) if CT === UInt32 @@ -211,7 +223,7 @@ otherwise. Covers fixed-x and varying-x, `D ∈ {2,3}`, and any distance-bin typ unified kernels read `u[d, point, b]` directly).""" function _gpu_2d_unified_device( backend, x, u, sf_type, distance_bins, value_bins, ::Val{NMOM}, - n_dist::Int, n_val::Int, B::Int, fixed_x::Bool, ::Type{OT}, + n_dist::Int, n_val::Int, B::Int, fixed_x::Bool, ::Type{OT}, geom, ) where {NMOM, OT} D = size(x, 1) N = size(x, 2) @@ -227,16 +239,16 @@ function _gpu_2d_unified_device( u_dev = KA.adapt(backend, reshape(u, D, N, B)) end _sf_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, - N, n_dist, n_val, B, D, Val(NMOM), fixed_x) + N, n_dist, n_val, B, D, Val(NMOM), fixed_x, geom) KA.synchronize(backend) return Array(out_dev), Array(cnt_dev) end """Single-pass (NMOM=6) 2D batch device launch — thin wrapper over the unified `_gpu_2d_unified_device`.""" -_gpu_sp2d_unified_device(backend, x, u, distance_bins, value_bins, n_dist, n_val, B, fixed_x, ::Type{OT}) where {OT} = +_gpu_sp2d_unified_device(backend, x, u, distance_bins, value_bins, n_dist, n_val, B, fixed_x, ::Type{OT}, geom) where {OT} = _gpu_2d_unified_device(backend, x, u, nothing, distance_bins, value_bins, - Val(SFC.SINGLE_PASS_N), n_dist, n_val, B, fixed_x, OT) + Val(SFC.SINGLE_PASS_N), n_dist, n_val, B, fixed_x, OT, geom) function _gpu_dispatch_single_pass_2d_batch( backend::KA.Backend, @@ -245,7 +257,9 @@ function _gpu_dispatch_single_pass_2d_batch( distance_bins::AbstractVector{FT3}, value_bins::SFC.SinglePass2DValueBins; count_eltype::Type{CT} = UInt32, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT1, FT2, FT3, CT} FT = promote_type(float(FT1), float(FT2)) fixed_x = ndims(x) == 2 @@ -255,7 +269,8 @@ function _gpu_dispatch_single_pass_2d_batch( B = SFC.batch_size(u) bdims = SFC.batch_dims(u) out_host, cnt_host = _gpu_sp2d_unified_device( - backend, x, u, distance_bins, value_bins, n_dist, n_val, B, fixed_x, FT) + backend, x, u, distance_bins, value_bins, n_dist, n_val, B, fixed_x, FT, + SFH.pair_geometry_for(distance_metric, size(x, 1) == 3 ? Val(3) : Val(2))) sums = reshape(out_host, SFC.SINGLE_PASS_N, n_dist, n_val, bdims...) counts_u32 = reshape(cnt_host, SFC.SINGLE_PASS_N, n_dist, n_val, bdims...) return (sums = sums, counts = CT === UInt32 ? counts_u32 : CT.(counts_u32)) @@ -269,14 +284,17 @@ function _gpu_dispatch_single_pass_2d_batch!( u::AbstractArray{FT2}, distance_bins::AbstractVector{FT3}, value_bins::SFC.SinglePass2DValueBins; - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {OT, CT, FT1, FT2, FT3} fixed_x = ndims(x) == 2 n_dist = length(distance_bins) - 1 n_val = size(sums, 3) B = SFC.batch_size(u) out_host, cnt_host = _gpu_sp2d_unified_device( - backend, x, u, distance_bins, value_bins, n_dist, n_val, B, fixed_x, OT) + backend, x, u, distance_bins, value_bins, n_dist, n_val, B, fixed_x, OT, + SFH.pair_geometry_for(distance_metric, size(x, 1) == 3 ? Val(3) : Val(2))) sums .+= reshape(out_host, size(sums)...) if CT === UInt32 counts .+= reshape(cnt_host, size(counts)...) @@ -305,7 +323,9 @@ function _gpu_calculate_structure_function_2d_batch( distance_bins::AbstractVector{FT}, value_bins::AbstractVector{FT}; count_eltype::Type{CT} = UInt32, - kwargs..., + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT, CT} fixed_x = ndims(x) == 2 n_dist = length(distance_bins) - 1 @@ -329,7 +349,8 @@ function _gpu_calculate_structure_function_2d_batch( u_dev = KA.adapt(backend, reshape(u, D, N, B)) end _sf_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, - N, n_dist, n_val, B, D, Val(1), fixed_x) + N, n_dist, n_val, B, D, Val(1), fixed_x, + SFH.pair_geometry_for(distance_metric, D == 3 ? Val(3) : Val(2))) KA.synchronize(backend) sums = reshape(Array(out_dev)[1, :, :, :], n_dist, n_val, bdims...) diff --git a/ext/gpu/kernels_1d.jl b/ext/gpu/kernels_1d.jl index 6a935f5..8d087fa 100644 --- a/ext/gpu/kernels_1d.jl +++ b/ext/gpu/kernels_1d.jl @@ -1,5 +1,5 @@ # Six production tiled128 SF histogram kernels (2D/3D × linear/log/general). -# Included from StructureFunctionsGPUExt.jl — no macro codegen. +# Included from StructureFunctionsKernelAbstractionsExt.jl — no macro codegen. # # Block-local `shared_cnts` is `@localmem UInt32` (compile-time fixed width). # Global `counts` is also device UInt32 at launch; `count_eltype` applies on host only. @@ -22,11 +22,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_2d_linear_u32!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -104,15 +104,13 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_2d_linear_u32!( U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist_sq = dX[1]^2 + dX[2]^2 - dist = sqrt(dist_sq) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, + dist, first_edge, last_edge, inv_step, step_val, N_bins, ) - if 1 <= bin < N_bins - r̂ = dX / dist - val = sf_type(U2 - U1, r̂) + if ok && 1 <= bin < N_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) @atomic shared_sums[bin] += val @atomic shared_cnts[bin] += UInt32(1) end @@ -148,11 +146,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_3d_linear_u32!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (384,) shared_ui = @localmem FT (384,) @@ -234,15 +232,13 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_3d_linear_u32!( U1 = SA.SVector{3, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia], shared_ui[2 * SF_GPU_TILE + ia]) U2 = SA.SVector{3, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb], shared_ui[2 * SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist_sq = dX[1]^2 + dX[2]^2 + dX[3]^2 - dist = sqrt(dist_sq) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, + dist, first_edge, last_edge, inv_step, step_val, N_bins, ) - if 1 <= bin < N_bins - r̂ = SFH.r̂(X1, X2) - val = sf_type(U2 - U1, r̂) + if ok && 1 <= bin < N_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) @atomic shared_sums[bin] += val @atomic shared_cnts[bin] += UInt32(1) end @@ -278,11 +274,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_2d_log_u32!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -360,13 +356,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_2d_log_u32!( U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist_sq = dX[1]^2 + dX[2]^2 - dist = sqrt(dist_sq) - bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) - if 1 <= bin < N_bins - r̂ = dX / dist - val = sf_type(U2 - U1, r̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) + if ok && 1 <= bin < N_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) @atomic shared_sums[bin] += val @atomic shared_cnts[bin] += UInt32(1) end @@ -402,11 +396,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_3d_log_u32!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (384,) shared_ui = @localmem FT (384,) @@ -488,13 +482,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_3d_log_u32!( U1 = SA.SVector{3, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia], shared_ui[2 * SF_GPU_TILE + ia]) U2 = SA.SVector{3, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb], shared_ui[2 * SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist_sq = dX[1]^2 + dX[2]^2 + dX[3]^2 - dist = sqrt(dist_sq) - bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) - if 1 <= bin < N_bins - r̂ = SFH.r̂(X1, X2) - val = sf_type(U2 - U1, r̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) + if ok && 1 <= bin < N_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) @atomic shared_sums[bin] += val @atomic shared_cnts[bin] += UInt32(1) end @@ -532,6 +524,7 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_2d_general_u32!( n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -609,13 +602,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_2d_general_u32!( U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist_sq = dX[1]^2 + dX[2]^2 - dist = sqrt(dist_sq) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_general(dist, distance_bins, N_bins) - if 1 <= bin < N_bins - r̂ = dX / dist - val = sf_type(U2 - U1, r̂) + if ok && 1 <= bin < N_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) @atomic shared_sums[bin] += val @atomic shared_cnts[bin] += UInt32(1) end @@ -653,6 +644,7 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_3d_general_u32!( n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (384,) shared_ui = @localmem FT (384,) @@ -734,13 +726,11 @@ KA.@kernel unsafe_indices=true function _sf_kernel_tiled128_3d_general_u32!( U1 = SA.SVector{3, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia], shared_ui[2 * SF_GPU_TILE + ia]) U2 = SA.SVector{3, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb], shared_ui[2 * SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist_sq = dX[1]^2 + dX[2]^2 + dX[3]^2 - dist = sqrt(dist_sq) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_general(dist, distance_bins, N_bins) - if 1 <= bin < N_bins - r̂ = SFH.r̂(X1, X2) - val = sf_type(U2 - U1, r̂) + if ok && 1 <= bin < N_bins + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) @atomic shared_sums[bin] += val @atomic shared_cnts[bin] += UInt32(1) end diff --git a/ext/gpu/kernels_1d_single_pass.jl b/ext/gpu/kernels_1d_single_pass.jl index 9303df0..2638312 100644 --- a/ext/gpu/kernels_1d_single_pass.jl +++ b/ext/gpu/kernels_1d_single_pass.jl @@ -1,24 +1,25 @@ # Tiled128 six-invariant-type single-pass 1D distance histogram kernels (linear/log/general). -# Included from StructureFunctionsGPUExt.jl — block-local (6, NB) sums + one count row. +# Included from StructureFunctionsKernelAbstractionsExt.jl — block-local (6, NB) sums + one count row. -"""Accumulate six invariant native 1D SF types into flat `@localmem` sums `(6*NB,)`. -du_norm2 = du_L2 + du_T2 (= ||dU||²) must be pre-computed by the caller.""" +"""Accumulate the four independent invariants into flat `@localmem` sums `(6*NB,)`. +`du_norm2 = ||dU||²` must be pre-computed by the caller. + +Rows 3 (`T2`) and 6 (`L1T2`) are exact differences of the others (`T2 = S2 - L2`, +`L1T2 = S3 - L3`) and a bin is a sum, so they are left zero here and reconstructed once at flush by +[`_sf_flush_moment`](@ref) — 4 shared atomics per pair instead of 6.""" @inline function _gpu_accumulate_single_pass_1d_shared!( shared_sums, shared_cnts, bin::Int, du_L, du_L2, - du_T2, du_norm2, NB::Int, ) @atomic shared_sums[bin] += du_norm2 @atomic shared_sums[NB + bin] += du_L2 - @atomic shared_sums[2NB + bin] += du_T2 @atomic shared_sums[3NB + bin] += du_L * du_norm2 @atomic shared_sums[4NB + bin] += du_L * du_L2 - @atomic shared_sums[5NB + bin] += du_L * du_T2 @atomic shared_cnts[bin] += UInt32(1) return nothing end @@ -34,11 +35,11 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_linear_ first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -120,20 +121,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_linear_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, + dist, first_edge, last_edge, inv_step, step_val, N_bins, ) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - du_L = SA.dot(dU, r̂) + if ok && 1 <= bin < N_bins + du_L, du_norm2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_norm2 = SA.dot(dU, dU) - du_T2 = du_norm2 - du_L2 _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_T2, du_norm2, NB, + shared_sums, shared_cnts, bin, du_L, du_L2, du_norm2, NB, ) end p += workgroup_size @@ -146,10 +142,10 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_linear_ if bid <= n_tile_blocks k = lid while k <= SF_GPU_SINGLE_PASS_N * NB - s = shared_sums[k] + t = (k - 1) ÷ NB + 1 + b = (k - 1) % NB + 1 + s = _sf_flush_moment(Val(SF_GPU_SINGLE_PASS_N), shared_sums, NB, t, b) if s != zero(FT) - t = (k - 1) ÷ NB + 1 - b = (k - 1) % NB + 1 @atomic output_sums[t, b] += s end k += workgroup_size @@ -175,7 +171,6 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_log_u32 first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, N_points::Int, N_bins::Int, @@ -183,6 +178,7 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_log_u32 n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -264,18 +260,13 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_log_u32 U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - du_L = SA.dot(dU, r̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, first_edge, last_edge, inv_step, step_val, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_norm2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_norm2 = SA.dot(dU, dU) - du_T2 = du_norm2 - du_L2 _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_T2, du_norm2, NB, + shared_sums, shared_cnts, bin, du_L, du_L2, du_norm2, NB, ) end p += workgroup_size @@ -288,10 +279,10 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_log_u32 if bid <= n_tile_blocks k = lid while k <= SF_GPU_SINGLE_PASS_N * NB - s = shared_sums[k] + t = (k - 1) ÷ NB + 1 + b = (k - 1) % NB + 1 + s = _sf_flush_moment(Val(SF_GPU_SINGLE_PASS_N), shared_sums, NB, t, b) if s != zero(FT) - t = (k - 1) ÷ NB + 1 - b = (k - 1) % NB + 1 @atomic output_sums[t, b] += s end k += workgroup_size @@ -322,6 +313,7 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_general n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -403,18 +395,13 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_general U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_general(dist, bins, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - du_L = SA.dot(dU, r̂) + if ok && 1 <= bin < N_bins + du_L, du_norm2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_norm2 = SA.dot(dU, dU) - du_T2 = du_norm2 - du_L2 _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_T2, du_norm2, NB, + shared_sums, shared_cnts, bin, du_L, du_L2, du_norm2, NB, ) end p += workgroup_size @@ -427,10 +414,10 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_kernel_tiled128_general if bid <= n_tile_blocks k = lid while k <= SF_GPU_SINGLE_PASS_N * NB - s = shared_sums[k] + t = (k - 1) ÷ NB + 1 + b = (k - 1) % NB + 1 + s = _sf_flush_moment(Val(SF_GPU_SINGLE_PASS_N), shared_sums, NB, t, b) if s != zero(FT) - t = (k - 1) ÷ NB + 1 - b = (k - 1) % NB + 1 @atomic output_sums[t, b] += s end k += workgroup_size diff --git a/ext/gpu/kernels_2d.jl b/ext/gpu/kernels_2d.jl index d31879a..d3da243 100644 --- a/ext/gpu/kernels_2d.jl +++ b/ext/gpu/kernels_2d.jl @@ -1,5 +1,5 @@ # Tiled128 joint 2D SF histogram kernels (distance × value, typed digitize routes). -# Included from StructureFunctionsGPUExt.jl — block-local flat histogram in `@localmem`. +# Included from StructureFunctionsKernelAbstractionsExt.jl — block-local flat histogram in `@localmem`. # # Compile-time width `compile_cells` is chosen per [`GPUSFWorkspace`](@ref) (default exact # `n_dist × n_val`; optional override via `joint2d_compile_cells`). Max-width kernels @@ -55,12 +55,12 @@ function _joint2d_kernel_param_exprs(dist_route::Symbol, val_route::Symbol) if dist_route == :linear append!(params, [ :(first_edge::FT), :(last_edge::FT), :(inv_step::FT), - :(offset::FT), :(step_val::FT), + :(step_val::FT), ]) elseif dist_route == :log append!(params, [ :(dist_first::FT), :(dist_last::FT), :(dist_inv_step::FT), - :(dist_offset::FT), :(dist_step::FT), + :(dist_step::FT), ]) elseif dist_route == :general push!(params, :(edge_anchor::FT)) @@ -68,28 +68,28 @@ function _joint2d_kernel_param_exprs(dist_route::Symbol, val_route::Symbol) if val_route == :linear || val_route == :log_linear append!(params, [ :(val_first::FT), :(val_last::FT), :(val_inv_step::FT), - :(val_offset::FT), :(val_step::FT), + :(val_step::FT), ]) elseif val_route == :inflinear append!(params, [ :(val_first::FT), :(val_last::FT), :(val_inv_step::FT), - :(val_offset::FT), :(val_step::FT), + :(val_step::FT), :(n_inner_edges::Int), :(inner_last::FT), ]) end - append!(params, [:(n_tiles::Int), :(n_tile_blocks::Int), :(workgroup_size::Int)]) + append!(params, [:(n_tiles::Int), :(n_tile_blocks::Int), :(workgroup_size::Int), :(geom)]) return params end function _joint2d_dist_digitize_expr(dist_route::Symbol) dist_route == :linear && return :( dbin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_dist_edges, + dist, first_edge, last_edge, inv_step, step_val, N_dist_edges, ) ) dist_route == :log && return :( dbin = _gpu_digitize_log_spaced( - dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_dist_edges, + dist, dist_first, dist_last, dist_inv_step, dist_step, N_dist_edges, ) ) return :(dbin = _gpu_digitize_general(dist, distance_edges, N_dist_edges)) @@ -99,18 +99,18 @@ function _joint2d_val_digitize_expr(val_route::Symbol) val_route == :general && return :(vbin = _gpu_digitize_general(val, value_edges, N_val_edges)) val_route == :linear && return :( vbin = _gpu_digitize_linear( - val, val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + val, val_first, val_last, val_inv_step, val_step, N_val_edges, ) ) val_route == :inflinear && return :( vbin = _gpu_digitize_inf_padded_linear( - val, val_first, val_last, val_inv_step, val_offset, val_step, + val, val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) ) return :( vbin = _gpu_digitize_log_spaced( - val, val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + val, val_first, val_last, val_inv_step, val_step, N_val_edges, ) ) end @@ -195,12 +195,11 @@ function _joint2d_kernel_def(dist_route::Symbol, val_route::Symbol, compile_cell U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) $(dist_digitize) - if 1 <= dbin < N_dist_edges - r̂ = dX / dist - val = sf_type(U2 - U1, r̂) + if ok && 1 <= dbin < N_dist_edges + dU, r̂ = SFH.pair_increments(geom, frame, dist, X1, X2, U1, U2) + val = sf_type(dU, r̂) $(val_digitize) if 1 <= vbin < N_val_edges idx = (dbin - 1) * NV + vbin diff --git a/ext/gpu/kernels_2d_direct.jl b/ext/gpu/kernels_2d_direct.jl index 6900cff..467489a 100644 --- a/ext/gpu/kernels_2d_direct.jl +++ b/ext/gpu/kernels_2d_direct.jl @@ -5,12 +5,50 @@ # Direct (:direct): global atomics into block-private partition; merge on host. # # See gpu/SP2D_HTP_EJ.md for strategy, benchmarks, and future perf notes. -# Included from StructureFunctionsGPUExt.jl after TiledSinglePass2DValueKernels.jl. +# Included from StructureFunctionsKernelAbstractionsExt.jl after TiledSinglePass2DValueKernels.jl. + +"""Load point `k`'s D-vector from a tile buffer staged as `(d-1)*SF_GPU_TILE + k`.""" +@inline _sp2d_ld_tile(buf, ::Val{2}, k) = + @inbounds SA.SVector{2}(buf[k], buf[SF_GPU_TILE + k]) +@inline _sp2d_ld_tile(buf, ::Val{3}, k) = + @inbounds SA.SVector{3}(buf[k], buf[SF_GPU_TILE + k], buf[2 * SF_GPU_TILE + k]) @inline function _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) return (t - 1) * n_dist * n_val + (dbin - 1) * n_val + vbin end +""" + _sp2d_val_stride(n_val) + +Row stride of the shared histogram's value axis, forced odd. + +Shared memory has 32 banks. With a stride of `n_val = 16`, the flat index +`(dbin-1)*n_val + vbin` puts every row of the value axis in the same 2 banks, so lanes that differ +only in `dbin` serialize up to 16 ways on bank conflicts alone — before any same-address atomic +contention. An odd stride is coprime with 32 and spreads them over all banks. The cost is one unused +column per row. +""" +@inline _sp2d_val_stride(n_val) = isodd(n_val) ? n_val : n_val + 1 + +"""Cells in the bank-conflict-padded shared histogram.""" +@inline _sp2d_shared_cells(n_dist, n_val) = + SF_GPU_SINGLE_PASS_N * n_dist * _sp2d_val_stride(n_val) + +"""Flat index into the padded shared histogram.""" +@inline function _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) + s = _sp2d_val_stride(n_val) + return (t - 1) * n_dist * s + (dbin - 1) * s + vbin +end + +"""Invert [`_sp2d_shared_index`](@ref); `vbin > n_val` marks a padding hole to skip.""" +@inline function _sp2d_shared_decode(g, n_dist, n_val) + s = _sp2d_val_stride(n_val) + plane = n_dist * s + t = (g - 1) ÷ plane + 1 + r = (g - 1) % plane + return t, r ÷ s + 1, r % s + 1 +end + @inline function _sp2d_decode_flat_index(g, n_dist, n_val) t = (g - 1) ÷ (n_dist * n_val) + 1 rem = (g - 1) % (n_dist * n_val) @@ -57,11 +95,13 @@ end ) g = lid while g <= C - t, dbin, vbin = _sp2d_decode_flat_index(g, n_dist, n_val) - @inbounds begin - partition_sums[t, dbin, vbin, block_id] += shared_sums[g] - if shared_cnts[g] != UInt32(0) - partition_counts[t, dbin, vbin, block_id] += shared_cnts[g] + t, dbin, vbin = _sp2d_shared_decode(g, n_dist, n_val) + if vbin <= n_val + @inbounds begin + partition_sums[t, dbin, vbin, block_id] += shared_sums[g] + if shared_cnts[g] != UInt32(0) + partition_counts[t, dbin, vbin, block_id] += shared_cnts[g] + end end end g += workgroup_size @@ -83,11 +123,13 @@ end ) g = lid while g <= C - t, dbin, vbin = _sp2d_decode_flat_index(g, n_dist, n_val) - @inbounds begin - @atomic out_sums[t, dbin, vbin] += shared_sums[g] - if shared_cnts[g] != UInt32(0) - @atomic out_cnts[t, dbin, vbin] += shared_cnts[g] + t, dbin, vbin = _sp2d_shared_decode(g, n_dist, n_val) + if vbin <= n_val + @inbounds begin + @atomic out_sums[t, dbin, vbin] += shared_sums[g] + if shared_cnts[g] != UInt32(0) + @atomic out_cnts[t, dbin, vbin] += shared_cnts[g] + end end end g += workgroup_size @@ -99,8 +141,8 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_linear_val!( shared_sums, shared_cnts, n_dist, n_val, - dbin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin, du_L, du_L2, du_T2, N_val_edges, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -109,10 +151,10 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -122,8 +164,8 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_linear_val_cols!( shared_sums, shared_cnts, n_dist, n_val, - val_first, val_last, val_inv_step, val_offset, val_step, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -132,11 +174,11 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( - vals[t], val_first[t], val_last[t], val_inv_step[t], val_offset[t], val_step[t], + vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], N_val_edges, ) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -146,8 +188,8 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_inflinear_val!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, ) where {FT} vals = SA.SVector( @@ -157,11 +199,11 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, + vals[t], val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -171,8 +213,8 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_inflinear_val_cols!( shared_sums, shared_cnts, n_dist, n_val, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - dbin::Int, du_L, du_T, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, inner_last, + dbin::Int, du_L, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -181,11 +223,11 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first[t], val_last[t], val_inv_step[t], val_offset[t], val_step[t], + vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], n_inner_edges, inner_last[t], ) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -195,8 +237,8 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_log_val!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -205,10 +247,10 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -218,8 +260,8 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_log_val_cols!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first, val_last, val_inv_step, val_offset, val_step, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -228,10 +270,10 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced_col( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, t, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges, ) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -241,7 +283,7 @@ end @inline function _gpu_accumulate_sp2d_sharedhist_vector_val_cols!( shared_sums, shared_cnts, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, value_edges, ) vals = SA.SVector( @@ -252,7 +294,7 @@ end for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_general_col(vals[t], value_edges, t, N_val_edges) if 1 <= vbin < N_val_edges - g = _sp2d_flat_index(t, dbin, vbin, n_dist, n_val) + g = _sp2d_shared_index(t, dbin, vbin, n_dist, n_val) @atomic shared_sums[g] += vals[t] @atomic shared_cnts[g] += UInt32(1) end @@ -262,10 +304,14 @@ end # --- type-plane shared accumulation (one SF type per pass; plane = n_dist × n_val) --- +"""Flat index within one padded type plane; same bank argument as [`_sp2d_val_stride`](@ref).""" @inline function _sp2d_plane_flat_index(dbin::Int, vbin::Int, n_val::Int) - return (dbin - 1) * n_val + vbin + return (dbin - 1) * _sp2d_val_stride(n_val) + vbin end +"""Cells in one padded type plane.""" +@inline _sp2d_plane_cells(n_dist::Int, n_val::Int) = n_dist * _sp2d_val_stride(n_val) + """Flush type-plane shared histogram into block-private partition (`:direct` path only).""" @inline function _sp2d_flush_typeplane!( partition_sums, @@ -316,16 +362,19 @@ end ) t_lo = (type_pass - 1) * types_per_pass + 1 t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) + stride = _sp2d_val_stride(n_val) g = Int(lid) while g <= plane - dbin = (g - 1) ÷ n_val + 1 - vbin = (g - 1) % n_val + 1 - for t in t_lo:t_hi - slot = t - t_lo - @inbounds idx = slot * plane + g - @inbounds @atomic out_sums[t, dbin, vbin] += shared_sums[idx] - @inbounds if shared_cnts[idx] != UInt32(0) - @atomic out_cnts[t, dbin, vbin] += shared_cnts[idx] + dbin = (g - 1) ÷ stride + 1 + vbin = (g - 1) % stride + 1 + if vbin <= n_val + for t in t_lo:t_hi + slot = t - t_lo + @inbounds idx = slot * plane + g + @inbounds @atomic out_sums[t, dbin, vbin] += shared_sums[idx] + @inbounds if shared_cnts[idx] != UInt32(0) + @atomic out_cnts[t, dbin, vbin] += shared_cnts[idx] + end end end g += workgroup_size @@ -336,8 +385,8 @@ end @inline function _gpu_accumulate_sp2d_typeplane_linear_val!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -348,7 +397,7 @@ end t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi vbin = _gpu_digitize_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges slot = t - t_lo @@ -362,8 +411,8 @@ end @inline function _gpu_accumulate_sp2d_typeplane_linear_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - val_first, val_last, val_inv_step, val_offset, val_step, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -375,7 +424,7 @@ end for t in t_lo:t_hi vbin = _gpu_digitize_linear( vals[t], val_first[t], val_last[t], - val_inv_step[t], val_offset[t], val_step[t], + val_inv_step[t], val_step[t], N_val_edges, ) if 1 <= vbin < N_val_edges @@ -390,8 +439,8 @@ end @inline function _gpu_accumulate_sp2d_typeplane_inflinear_val!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, ) where {FT} vals = SA.SVector( @@ -403,7 +452,7 @@ end t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, + vals[t], val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) if 1 <= vbin < N_val_edges @@ -418,8 +467,8 @@ end @inline function _gpu_accumulate_sp2d_typeplane_inflinear_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - dbin::Int, du_L, du_T, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, inner_last, + dbin::Int, du_L, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -431,7 +480,7 @@ end for t in t_lo:t_hi vbin = _gpu_digitize_inf_padded_linear( vals[t], val_first[t], val_last[t], - val_inv_step[t], val_offset[t], val_step[t], + val_inv_step[t], val_step[t], n_inner_edges, inner_last[t], ) if 1 <= vbin < N_val_edges @@ -446,8 +495,8 @@ end @inline function _gpu_accumulate_sp2d_typeplane_log_val!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -458,7 +507,7 @@ end t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi vbin = _gpu_digitize_log_spaced( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges slot = t - t_lo @@ -472,8 +521,8 @@ end @inline function _gpu_accumulate_sp2d_typeplane_log_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first, val_last, val_inv_step, val_offset, val_step, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -484,7 +533,7 @@ end t_hi = min(SF_GPU_SINGLE_PASS_N, type_pass * types_per_pass) for t in t_lo:t_hi vbin = _gpu_digitize_log_spaced_col( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, + vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges, ) if 1 <= vbin < N_val_edges @@ -499,7 +548,7 @@ end @inline function _gpu_accumulate_sp2d_typeplane_vector_val_cols!( shared_sums, shared_cnts, n_val, plane::Int, type_pass::Int, types_per_pass::Int, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, value_edges, ) vals = SA.SVector( @@ -525,8 +574,8 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_linear_val!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -535,7 +584,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges @atomic partition_sums[t, dbin, vbin, block_id] += vals[t] @@ -547,8 +596,8 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_linear_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - val_first, val_last, val_inv_step, val_offset, val_step, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -557,7 +606,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( - vals[t], val_first[t], val_last[t], val_inv_step[t], val_offset[t], val_step[t], + vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], N_val_edges, ) if 1 <= vbin < N_val_edges @@ -570,8 +619,8 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_inflinear_val!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, ) where {FT} vals = SA.SVector( @@ -581,7 +630,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, + vals[t], val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) if 1 <= vbin < N_val_edges @@ -594,8 +643,8 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_inflinear_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - dbin::Int, du_L, du_T, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, inner_last, + dbin::Int, du_L, du_L2, du_T2, n_inner_edges::Int, N_val_edges::Int, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -604,7 +653,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first[t], val_last[t], val_inv_step[t], val_offset[t], val_step[t], + vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], n_inner_edges, inner_last[t], ) if 1 <= vbin < N_val_edges @@ -617,8 +666,8 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_log_val!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, ) where {FT} vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -627,7 +676,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges @atomic partition_sums[t, dbin, vbin, block_id] += vals[t] @@ -639,8 +688,8 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_log_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, - val_first, val_last, val_inv_step, val_offset, val_step, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, + val_first, val_last, val_inv_step, val_step, ) vals = SA.SVector( du_L2 + du_T2, du_L2, du_T2, @@ -649,7 +698,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_log_spaced_col( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, t, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges, ) if 1 <= vbin < N_val_edges @atomic partition_sums[t, dbin, vbin, block_id] += vals[t] @@ -661,7 +710,7 @@ end @inline function _gpu_accumulate_sp2d_partitioned_direct_vector_val_cols!( partition_sums, partition_counts, block_id::Integer, n_dist, n_val, - dbin::Int, du_L, du_T, du_L2, du_T2, N_val_edges::Int, + dbin::Int, du_L, du_L2, du_T2, N_val_edges::Int, value_edges, ) vals = SA.SVector( @@ -818,37 +867,41 @@ end # --- kernel codegen --- -"""Compile-time max shared histogram cells (48 KiB default smem, Float32 cell width).""" -const _SP2D_SHAREDHIST_COMPILE_CELLS = _sp2d_max_shared_cells(SF_GPU_SMEM_DEFAULT, Float32) - function _sp2d_partition_dist_spec(::Val{:linear}) params = [ - :(dist_first::FT), :(dist_last::FT), :(dist_inv_step::FT), - :(dist_offset::FT), :(dist_step::FT), + :(dist_first), :(dist_last), :(dist_inv_step), + :(dist_step), ] bin = :(_gpu_digitize_linear( - dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins, + dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins, )) return params, bin end function _sp2d_partition_dist_spec(::Val{:log_linear}) params = [ - :(dist_first::FT), :(dist_last::FT), :(dist_inv_step::FT), - :(dist_offset::FT), :(dist_step::FT), + :(dist_first), :(dist_last), :(dist_inv_step), + :(dist_step), ] bin = :(_gpu_digitize_log_spaced( - dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins, + dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins, )) return params, bin end +"""Arbitrary distance edges: binary search on device, so no bin spacing is assumed.""" +function _sp2d_partition_dist_spec(::Val{:general}) + params = [:(@Const(distance_edges))] + bin = :(_gpu_digitize_general(dist, distance_edges, N_bins)) + return params, bin +end + function _sp2d_partition_val_accum(::Val{:linear_shared}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_linear_val!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -856,8 +909,8 @@ function _sp2d_partition_val_accum(::Val{:linear_shared}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_linear_val!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -866,8 +919,8 @@ function _sp2d_partition_val_accum(::Val{:linear_cols}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_linear_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, - val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end end @@ -875,8 +928,8 @@ function _sp2d_partition_val_accum(::Val{:linear_cols}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_linear_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end end @@ -885,8 +938,8 @@ function _sp2d_partition_val_accum(::Val{:inflinear_shared}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_inflinear_val!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, n_inner_edges, inner_last, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end end @@ -894,8 +947,8 @@ function _sp2d_partition_val_accum(::Val{:inflinear_shared}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_inflinear_val!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, n_inner_edges, inner_last, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end end @@ -904,8 +957,8 @@ function _sp2d_partition_val_accum(::Val{:inflinear_cols}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_inflinear_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - bin, du_L, du_T, du_L2, du_T2, n_inner_edges, N_val_edges, + val_first, val_last, val_inv_step, val_step, inner_last, + bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, ) end end @@ -913,8 +966,8 @@ function _sp2d_partition_val_accum(::Val{:inflinear_cols}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_inflinear_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - bin, du_L, du_T, du_L2, du_T2, n_inner_edges, N_val_edges, + val_first, val_last, val_inv_step, val_step, inner_last, + bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, ) end end @@ -923,8 +976,8 @@ function _sp2d_partition_val_accum(::Val{:log_linear_shared}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_log_val!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -932,8 +985,8 @@ function _sp2d_partition_val_accum(::Val{:log_linear_shared}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_log_val!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -942,8 +995,8 @@ function _sp2d_partition_val_accum(::Val{:log_linear_cols}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_log_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -951,8 +1004,8 @@ function _sp2d_partition_val_accum(::Val{:log_linear_cols}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_log_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -961,7 +1014,7 @@ function _sp2d_partition_val_accum(::Val{:vector_cols}, ::Val{:shared}) return quote _gpu_accumulate_sp2d_sharedhist_vector_val_cols!( shared_sums, shared_cnts, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, value_edges, + bin, du_L, du_L2, du_T2, N_val_edges, value_edges, ) end end @@ -969,7 +1022,7 @@ function _sp2d_partition_val_accum(::Val{:vector_cols}, ::Val{:direct}) return quote _gpu_accumulate_sp2d_partitioned_direct_vector_val_cols!( partition_sums, partition_counts, block_id, NB, N_val_edges - 1, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, value_edges, + bin, du_L, du_L2, du_T2, N_val_edges, value_edges, ) end end @@ -979,8 +1032,8 @@ function _sp2d_partition_val_accum(::Val{:linear_shared}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_linear_val!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -988,8 +1041,8 @@ function _sp2d_partition_val_accum(::Val{:linear_cols}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_linear_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end end @@ -997,8 +1050,8 @@ function _sp2d_partition_val_accum(::Val{:inflinear_shared}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_inflinear_val!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, n_inner_edges, inner_last, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end end @@ -1006,8 +1059,8 @@ function _sp2d_partition_val_accum(::Val{:inflinear_cols}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_inflinear_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - bin, du_L, du_T, du_L2, du_T2, n_inner_edges, N_val_edges, + val_first, val_last, val_inv_step, val_step, inner_last, + bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, ) end end @@ -1015,8 +1068,8 @@ function _sp2d_partition_val_accum(::Val{:log_linear_shared}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_log_val!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -1024,8 +1077,8 @@ function _sp2d_partition_val_accum(::Val{:log_linear_cols}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_log_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end end @@ -1033,7 +1086,7 @@ function _sp2d_partition_val_accum(::Val{:vector_cols}, ::Val{:typeplane}) return quote _gpu_accumulate_sp2d_typeplane_vector_val_cols!( shared_sums, shared_cnts, N_val_edges - 1, plane, type_pass, types_per_pass, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, value_edges, + bin, du_L, du_L2, du_T2, N_val_edges, value_edges, ) end end @@ -1049,35 +1102,28 @@ function _sp2d_partition_kernel_prefix(::Val{:direct}) end function _sp2d_partition_val_params(::Val{:linear_shared}) - return [ - :(val_first::FT), :(val_last::FT), :(val_inv_step::FT), - :(val_offset::FT), :(val_step::FT), - ] + return [:(val_first), :(val_last), :(val_inv_step), :(val_step)] end function _sp2d_partition_val_params(::Val{:linear_cols}) - return [:(val_first), :(val_last), :(val_inv_step), :(val_offset), :(val_step)] + return [:(val_first), :(val_last), :(val_inv_step), :(val_step)] end function _sp2d_partition_val_params(::Val{:inflinear_shared}) return [ - :(val_first::FT), :(val_last::FT), :(val_inv_step::FT), - :(val_offset::FT), :(val_step::FT), - :(n_inner_edges::Int), :(inner_last::FT), + :(val_first), :(val_last), :(val_inv_step), :(val_step), + :(n_inner_edges::Int), :(inner_last), ] end function _sp2d_partition_val_params(::Val{:inflinear_cols}) return [ - :(val_first), :(val_last), :(val_inv_step), :(val_offset), :(val_step), + :(val_first), :(val_last), :(val_inv_step), :(val_step), :(inner_last), :(n_inner_edges::Int), ] end function _sp2d_partition_val_params(::Val{:log_linear_shared}) - return [ - :(val_first::FT), :(val_last::FT), :(val_inv_step::FT), - :(val_offset::FT), :(val_step::FT), - ] + return [:(val_first), :(val_last), :(val_inv_step), :(val_step)] end function _sp2d_partition_val_params(::Val{:log_linear_cols}) - return [:(val_first), :(val_last), :(val_inv_step), :(val_offset), :(val_step)] + return [:(val_first), :(val_last), :(val_inv_step), :(val_step)] end function _sp2d_partition_val_params(::Val{:vector_cols}) return [:(@Const(value_edges))] @@ -1089,16 +1135,17 @@ end """Emit one HTP-EJ tiled128 kernel for `accum_mode` (`:shared`, `:typeplane`, or `:direct`).""" function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbol) - hist_cells = _SP2D_SHAREDHIST_COMPILE_CELLS prefix = _sp2d_partition_kernel_prefix(Val(accum_mode)) fname = Symbol(prefix, dist, :_, val, :_u32!) dist_params, dist_bin = _sp2d_partition_dist_spec(dist) val_params = _sp2d_partition_val_params(Val(val)) accum = _sp2d_partition_val_accum(Val(val), Val(accum_mode)) uses_shared = accum_mode in (:shared, :typeplane) + # Width is a kernel type parameter, so one definition specializes per config instead of every + # config paying for the largest one the budget allows. shared_hist_decl = uses_shared ? quote - shared_sums = @localmem FT ($(hist_cells),) - shared_cnts = @localmem UInt32 ($(hist_cells),) + shared_sums = @localmem OT (HC,) + shared_cnts = @localmem UInt32 (HC,) end : quote end type_pass_decl = accum_mode == :typeplane ? quote shared_type_pass = @localmem Int (1,) @@ -1106,6 +1153,7 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo kernel_tail_params = [ :(n_tiles::Int), :(n_tile_blocks::Int), :(workgroup_size::Int), :(C::Int), :(plane::Int), :(types_per_pass::Int), :(n_type_passes::Int), + :(::Val{HC}), :(::Val{D}), :(geom), ] pair_loop = quote p = lid @@ -1113,28 +1161,27 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo if ti < tj ia = (p - 1) ÷ nj + 1 jb = (p - 1) - (ia - 1) * nj + 1 - X1 = SA.SVector{2, FT}(shared_xi[ia], shared_xi[SF_GPU_TILE + ia]) - X2 = SA.SVector{2, FT}(shared_xj[jb], shared_xj[SF_GPU_TILE + jb]) - U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) - U2 = SA.SVector{2, FT}(shared_uj[jb], shared_uj[SF_GPU_TILE + jb]) + X1 = _sp2d_ld_tile(shared_xi, Val(D), ia) + X2 = _sp2d_ld_tile(shared_xj, Val(D), jb) + U1 = _sp2d_ld_tile(shared_ui, Val(D), ia) + U2 = _sp2d_ld_tile(shared_uj, Val(D), jb) else ia, jb = _pair_from_linear(p, ni) - X1 = SA.SVector{2, FT}(shared_xi[ia], shared_xi[SF_GPU_TILE + ia]) - X2 = SA.SVector{2, FT}(shared_xi[jb], shared_xi[SF_GPU_TILE + jb]) - U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) - U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) + X1 = _sp2d_ld_tile(shared_xi, Val(D), ia) + X2 = _sp2d_ld_tile(shared_xi, Val(D), jb) + U1 = _sp2d_ld_tile(shared_ui, Val(D), ia) + U2 = _sp2d_ld_tile(shared_ui, Val(D), jb) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = $(dist_bin) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + if ok && 1 <= bin < N_bins + # |du_T|² from the norm rather than a transverse basis vector: the six invariants + # use only du_L, du_L², du_T², never the signed du_T, and building n̂ = (r̂₂, -r̂₁) + # is both wasted work and the kernel's only 2D-specific assumption. This is also + # exactly the CPU's formula, so the two agree to the last bit of the algorithm. + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 $(accum) end p += workgroup_size @@ -1163,7 +1210,7 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo let g_zero = lid while g_zero <= types_per_pass * plane @inbounds begin - shared_sums[g_zero] = zero(FT) + shared_sums[g_zero] = zero(OT) shared_cnts[g_zero] = zero(UInt32) end g_zero += workgroup_size @@ -1204,7 +1251,7 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo let g_zero = lid while g_zero <= C @inbounds begin - shared_sums[g_zero] = zero(FT) + shared_sums[g_zero] = zero(OT) shared_cnts[g_zero] = zero(UInt32) end g_zero += workgroup_size @@ -1247,20 +1294,20 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo end end hist_params = accum_mode == :direct ? - [:(partition_sums), :(partition_counts)] : - [:(out_sums), :(out_cnts)] + [:(partition_sums::AbstractArray{OT}), :(partition_counts)] : + [:(out_sums::AbstractArray{OT}), :(out_cnts)] return quote KA.@kernel unsafe_indices=true function $(fname)( - $(hist_params...), x_mat, u_mat, + $(hist_params...), x_mat::AbstractMatrix{FT}, u_mat::AbstractMatrix{FT}, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, $(dist_params...), $(val_params...), $(kernel_tail_params...), - ) where {FT} - shared_xi = @localmem FT (256,) - shared_ui = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_uj = @localmem FT (256,) + ) where {OT, FT, HC, D} + shared_xi = @localmem FT (D * SF_GPU_TILE,) + shared_ui = @localmem FT (D * SF_GPU_TILE,) + shared_xj = @localmem FT (D * SF_GPU_TILE,) + shared_uj = @localmem FT (D * SF_GPU_TILE,) $(shared_hist_decl) $(type_pass_decl) shared_block_id = @localmem Int (1,) @@ -1280,7 +1327,7 @@ function _sp2d_partition_kernel_def(accum_mode::Symbol, dist::Symbol, val::Symbo nj = min(SF_GPU_TILE, N_points - j0 + 1) _sp2d_tiled_load_tile!( shared_xi, shared_ui, shared_xj, shared_uj, x_mat, u_mat, - ti, tj, i0, j0, ni, nj, N_points, lid, workgroup_size, + ti, tj, i0, j0, ni, nj, N_points, lid, workgroup_size, Val(D), ) end @synchronize @@ -1310,6 +1357,7 @@ const _SP2D_PARTITION_DIST_VAL = [ (:linear, :inflinear_cols), (:linear, :log_linear_shared), (:linear, :log_linear_cols), + (:linear, :vector_cols), (:log_linear, :linear_shared), (:log_linear, :linear_cols), (:log_linear, :inflinear_shared), @@ -1317,6 +1365,13 @@ const _SP2D_PARTITION_DIST_VAL = [ (:log_linear, :log_linear_shared), (:log_linear, :log_linear_cols), (:log_linear, :vector_cols), + (:general, :linear_shared), + (:general, :linear_cols), + (:general, :inflinear_shared), + (:general, :inflinear_cols), + (:general, :log_linear_shared), + (:general, :log_linear_cols), + (:general, :vector_cols), ] for accum_mode in (:shared, :typeplane, :direct), (dist, val) in _SP2D_PARTITION_DIST_VAL diff --git a/ext/gpu/kernels_2d_single_pass.jl b/ext/gpu/kernels_2d_single_pass.jl index b902fcc..66c311a 100644 --- a/ext/gpu/kernels_2d_single_pass.jl +++ b/ext/gpu/kernels_2d_single_pass.jl @@ -8,7 +8,6 @@ value_edges, bin::Int, du_L, - du_T, du_L2, du_T2, N_val_edges::Int, @@ -36,14 +35,12 @@ end output_counts, bin::Int, du_L, - du_T, du_L2, du_T2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, - val_offset::FT, val_step::FT, ) where {FT} vals = SA.SVector( @@ -56,7 +53,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges, + vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges, ) if 1 <= vbin < N_val_edges @atomic output_sums[t, bin, vbin] += vals[t] @@ -72,11 +69,9 @@ end val_first, val_last, val_inv_step, - val_offset, val_step, bin::Int, du_L, - du_T, du_L2, du_T2, N_val_edges::Int, @@ -92,7 +87,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_linear( - vals[t], val_first[t], val_last[t], val_inv_step[t], val_offset[t], val_step[t], + vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], N_val_edges, ) if 1 <= vbin < N_val_edges @@ -108,14 +103,12 @@ end output_counts, bin::Int, du_L, - du_T, du_L2, du_T2, N_val_edges::Int, val_first::FT, val_last::FT, val_inv_step::FT, - val_offset::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, @@ -130,7 +123,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first, val_last, val_inv_step, val_offset, val_step, + vals[t], val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) if 1 <= vbin < N_val_edges @@ -147,12 +140,10 @@ end val_first, val_last, val_inv_step, - val_offset, val_step, inner_last, bin::Int, du_L, - du_T, du_L2, du_T2, n_inner_edges::Int, @@ -168,7 +159,7 @@ end ) for t in 1:SF_GPU_SINGLE_PASS_N vbin = _gpu_digitize_inf_padded_linear( - vals[t], val_first[t], val_last[t], val_inv_step[t], val_offset[t], val_step[t], + vals[t], val_first[t], val_last[t], val_inv_step[t], val_step[t], n_inner_edges, inner_last[t], ) if 1 <= vbin < N_val_edges @@ -185,11 +176,9 @@ end val_first::FT, val_last::FT, val_inv_step::FT, - val_offset::FT, val_step::FT, bin::Int, du_L, - du_T, du_L2, du_T2, N_val_edges::Int, @@ -203,7 +192,7 @@ end du_L * du_T2, ) for t in 1:SF_GPU_SINGLE_PASS_N - vbin = _gpu_digitize_log_spaced(vals[t], val_first, val_last, val_inv_step, val_offset, val_step, N_val_edges) + vbin = _gpu_digitize_log_spaced(vals[t], val_first, val_last, val_inv_step, val_step, N_val_edges) if 1 <= vbin < N_val_edges @atomic output_sums[t, bin, vbin] += vals[t] @atomic output_counts[t, bin, vbin] += one(eltype(output_counts)) @@ -218,11 +207,9 @@ end val_first, val_last, val_inv_step, - val_offset, val_step, bin::Int, du_L, - du_T, du_L2, du_T2, N_val_edges::Int, @@ -236,7 +223,7 @@ end du_L * du_T2, ) for t in 1:SF_GPU_SINGLE_PASS_N - vbin = _gpu_digitize_log_spaced_col(vals[t], val_first, val_last, val_inv_step, val_offset, val_step, t, N_val_edges) + vbin = _gpu_digitize_log_spaced_col(vals[t], val_first, val_last, val_inv_step, val_step, t, N_val_edges) if 1 <= vbin < N_val_edges @atomic output_sums[t, bin, vbin] += vals[t] @atomic output_counts[t, bin, vbin] += one(eltype(output_counts)) @@ -257,16 +244,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line dist_first::FT, dist_last::FT, dist_inv_step::FT, - dist_offset::FT, dist_step::FT, val_first::FT, val_last::FT, val_inv_step::FT, - val_offset::FT, val_step::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -334,23 +320,18 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) bin = _gpu_digitize_linear( - dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins, + dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins, ) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val!( output_sums, output_counts, bin, - du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end p += workgroup_size @@ -372,11 +353,11 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ dist_first::FT, dist_last::FT, dist_inv_step::FT, - dist_offset::FT, dist_step::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -444,20 +425,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global!( output_sums, output_counts, value_edges, bin, - du_L, du_T, du_L2, du_T2, N_val_edges, + du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -478,16 +454,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ dist_first::FT, dist_last::FT, dist_inv_step::FT, - dist_offset::FT, dist_step::FT, val_first::FT, val_last::FT, val_inv_step::FT, - val_offset::FT, val_step::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -555,21 +530,16 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val!( output_sums, output_counts, bin, - du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, + du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, ) end p += workgroup_size diff --git a/ext/gpu/kernels_2d_value_axis.jl b/ext/gpu/kernels_2d_value_axis.jl index e35f254..e7c9cc1 100644 --- a/ext/gpu/kernels_2d_value_axis.jl +++ b/ext/gpu/kernels_2d_value_axis.jl @@ -1,16 +1,21 @@ # Additional tiled128 single-pass 2D kernels for typed value-axis digitize plans. # Pair loop is inlined in each kernel (KA @index cannot live inside a user macro). -function _sp2d_tiled_load_tile!(shared_xi, shared_ui, shared_xj, shared_uj, x_mat, u_mat, ti, tj, i0, j0, ni, nj, N_points, lid, workgroup_size) +""" +Stage tile `ti` (and `tj` when off-diagonal) into shared memory, component-major as +`(d-1)*SF_GPU_TILE + k`. `D` defaults to 2 so the two-dimensional kernels here call it unchanged. +""" +function _sp2d_tiled_load_tile!( + shared_xi, shared_ui, shared_xj, shared_uj, x_mat, u_mat, + ti, tj, i0, j0, ni, nj, N_points, lid, workgroup_size, ::Val{D} = Val(2), +) where {D} if ni > 0 && nj > 0 k = lid while k <= ni gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_mat[1, gi] - shared_xi[SF_GPU_TILE + k] = x_mat[2, gi] - shared_ui[k] = u_mat[1, gi] - shared_ui[SF_GPU_TILE + k] = u_mat[2, gi] + @inbounds for d in 1:D + shared_xi[(d - 1) * SF_GPU_TILE + k] = x_mat[d, gi] + shared_ui[(d - 1) * SF_GPU_TILE + k] = u_mat[d, gi] end k += workgroup_size end @@ -18,11 +23,9 @@ function _sp2d_tiled_load_tile!(shared_xi, shared_ui, shared_xj, shared_uj, x_ma k = lid while k <= nj gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_mat[1, gj] - shared_xj[SF_GPU_TILE + k] = x_mat[2, gj] - shared_uj[k] = u_mat[1, gj] - shared_uj[SF_GPU_TILE + k] = u_mat[2, gj] + @inbounds for d in 1:D + shared_xj[(d - 1) * SF_GPU_TILE + k] = x_mat[d, gj] + shared_uj[(d - 1) * SF_GPU_TILE + k] = u_mat[d, gj] end k += workgroup_size end @@ -34,9 +37,10 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_linear_linear_val_cols_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first, val_last, val_inv_step, val_offset, val_step, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first, val_last, val_inv_step, val_step, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -79,20 +83,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val_cols!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -104,9 +103,10 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_linear_val_cols_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first, val_last, val_inv_step, val_offset, val_step, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first, val_last, val_inv_step, val_step, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -149,20 +149,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_linear_val_cols!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -174,10 +169,11 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_linear_inflinear_val_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -220,20 +216,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val!( - output_sums, output_counts, bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, n_inner_edges, inner_last, + output_sums, output_counts, bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end p += workgroup_size @@ -245,10 +236,11 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_inflinear_val_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_inner_edges::Int, inner_last::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -291,20 +283,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val!( - output_sums, output_counts, bin, du_L, du_T, du_L2, du_T2, N_val_edges, - val_first, val_last, val_inv_step, val_offset, val_step, n_inner_edges, inner_last, + output_sums, output_counts, bin, du_L, du_L2, du_T2, N_val_edges, + val_first, val_last, val_inv_step, val_step, n_inner_edges, inner_last, ) end p += workgroup_size @@ -316,10 +303,11 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_linear_inflinear_val_cols_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first, val_last, val_inv_step, val_step, inner_last, n_inner_edges::Int, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -362,20 +350,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val_cols!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - bin, du_L, du_T, du_L2, du_T2, n_inner_edges, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, inner_last, + bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, ) end p += workgroup_size @@ -387,10 +370,11 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_inflinear_val_cols_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first, val_last, val_inv_step, val_offset, val_step, inner_last, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first, val_last, val_inv_step, val_step, inner_last, n_inner_edges::Int, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -433,20 +417,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_inflinear_val_cols!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, inner_last, - bin, du_L, du_T, du_L2, du_T2, n_inner_edges, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, inner_last, + bin, du_L, du_L2, du_T2, n_inner_edges, N_val_edges, ) end p += workgroup_size @@ -458,9 +437,10 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_log_val_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -503,20 +483,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, bin, - du_L, du_T, du_L2, du_T2, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, bin, + du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -529,8 +504,9 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ output_sums, output_counts, x_mat, u_mat, @Const(value_edges), N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -573,20 +549,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global!( output_sums, output_counts, value_edges, bin, - du_L, du_T, du_L2, du_T2, N_val_edges, + du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -598,9 +569,10 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_linear_log_val_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first::FT, val_last::FT, val_inv_step::FT, val_offset::FT, val_step::FT, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first::FT, val_last::FT, val_inv_step::FT, val_step::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -643,20 +615,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, bin, - du_L, du_T, du_L2, du_T2, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, bin, + du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -668,9 +635,10 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_linear_log_val_cols_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first, val_last, val_inv_step, val_offset, val_step, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first, val_last, val_inv_step, val_step, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -713,20 +681,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_line U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_linear(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val_cols!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size @@ -738,9 +701,10 @@ end KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_log_val_cols_u32!( output_sums, output_counts, x_mat, u_mat, N_points::Int, N_bins::Int, NB::Int, N_val_edges::Int, - dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_offset::FT, dist_step::FT, - val_first, val_last, val_inv_step, val_offset, val_step, + dist_first::FT, dist_last::FT, dist_inv_step::FT, dist_step::FT, + val_first, val_last, val_inv_step, val_step, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ) where {FT} shared_xi = @localmem FT (256,) shared_ui = @localmem FT (256,) @@ -783,20 +747,15 @@ KA.@kernel unsafe_indices=true function _sf6_single_pass_2d_kernel_tiled128_log_ U1 = SA.SVector{2, FT}(shared_ui[ia], shared_ui[SF_GPU_TILE + ia]) U2 = SA.SVector{2, FT}(shared_ui[jb], shared_ui[SF_GPU_TILE + jb]) end - dX = X2 - X1 - dist = sqrt(dX[1]^2 + dX[2]^2) - bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_offset, dist_step, N_bins) - if 1 <= bin < N_bins - dU = U2 - U1 - r̂ = dX / dist - n̂ = SA.SVector{2, FT}(r̂[2], -r̂[1]) - du_L = SA.dot(dU, r̂) - du_T = SA.dot(dU, n̂) + ok, dist, frame = SFH.pair_frame(geom, X1, X2) + bin = _gpu_digitize_log_spaced(dist, dist_first, dist_last, dist_inv_step, dist_step, N_bins) + if ok && 1 <= bin < N_bins + du_L, du_n2 = SFH.pair_invariants(geom, frame, dist, U1, U2) du_L2 = du_L * du_L - du_T2 = du_T * du_T + du_T2 = du_n2 - du_L2 _gpu_accumulate_single_pass_2d_pair_global_log_val_cols!( - output_sums, output_counts, val_first, val_last, val_inv_step, val_offset, val_step, - bin, du_L, du_T, du_L2, du_T2, N_val_edges, + output_sums, output_counts, val_first, val_last, val_inv_step, val_step, + bin, du_L, du_L2, du_T2, N_val_edges, ) end p += workgroup_size diff --git a/ext/gpu/kernels_batch.jl b/ext/gpu/kernels_batch.jl index f33f329..6fd4d12 100644 --- a/ext/gpu/kernels_batch.jl +++ b/ext/gpu/kernels_batch.jl @@ -1,8 +1,18 @@ # Production batch tiled128 kernels — fixed-x u-smem strips + block-private merge. -# Included from StructureFunctionsGPUExt.jl after GPUBatchWorkspace.jl. +# Included from StructureFunctionsKernelAbstractionsExt.jl after GPUBatchWorkspace.jl. -"""u-smem strip width for small-strip reference (`_batch_fixed_x_usmem_priv!`).""" -const BATCH_USMEM_STRIP_W = 16 +""" +u-smem strip width for `_batch_fixed_x_usmem_priv!`, the widest strip whose static staging fits. + +The kernel stages `512 + 512W` elements of `FT`, so `W` is a shared-memory budget question, not a +constant: 16 for `Float32` (34 KB) but at most 11 for `Float64`, which is why a hardcoded 16 +requested 68 KB against the 48 KB static cap and failed to compile. Rounded down to a power of two +for a margin under the cap. +""" +@inline function _batch_usmem_strip_w(::Type{FT}) where {FT} + w = SFC.GPU_SMEM_STATIC_MAX ÷ (512 * sizeof(FT)) - 1 + return w >= 16 ? 16 : w >= 8 ? 8 : w >= 4 ? 4 : w >= 2 ? 2 : 1 +end """Warps per batch tile block (`SF_GPU_TILED_WS ÷ 32`).""" const BATCH_USMEM_WARPS = SF_GPU_TILED_WS ÷ 32 @@ -22,12 +32,6 @@ const BATCH_USMEM_WARPS = SF_GPU_TILED_WS ÷ 32 _batch_fixed_x_sf_kernel(backend::KA.Backend, ws::Int) = _batch_fixed_x_usmem_priv!(backend, ws) -""" -SP1D batch strip width — smaller than `BATCH_USMEM_STRIP_W` because on-chip hist is -`(6, NB, strip_w)` not `(NB, strip_w)`. -""" -const BATCH_SP1D_USMEM_STRIP_W = 8 - function _batch_tiled_launch_params(N_points::Int) n_tiles = cld(N_points, SF_GPU_TILE) n_tile_blocks = n_tiles * (n_tiles + 1) ÷ 2 @@ -113,17 +117,25 @@ end end @inline function _batch_dist_bin( - dist::T, fe::T, le::T, is_::T, off::T, sv::T, nb::Int, ::Val{false}, + dist::T, fe::T, le::T, is_::T, sv::T, nb::Int, ::Val{false}, ) where {T} - return _gpu_digitize_linear(dist, fe, le, is_, off, sv, nb) + return _gpu_digitize_linear(dist, fe, le, is_, sv, nb) end @inline function _batch_dist_bin( - dist::T, fe::T, le::T, is_::T, off::T, sv::T, nb::Int, ::Val{true}, + dist::T, fe::T, le::T, is_::T, sv::T, nb::Int, ::Val{true}, ) where {T} - return _gpu_digitize_log_spaced(dist, fe, le, is_, off, sv, nb) + return _gpu_digitize_log_spaced(dist, fe, le, is_, sv, nb) end -@inline function _pair_bin_rhat_from_smem!( +""" +Separation and pair frame for one staged pair, plus its bin. + +The bin comes from the same O(1) FMA digitizer whatever the geometry: `_fma_distance_bins` is a +statement about the *edges* being linear- or log-spaced, not about the space the separation was +measured in. Only the separation and frame are geometry-dependent, and those come from dispatch on +`geom`. +""" +@inline function _pair_bin_frame_from_smem!( shared_xi::AbstractVector{FT}, shared_xj::AbstractVector{FT}, ia::Int, @@ -132,25 +144,21 @@ end first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, N_bins::Int, + geom, ::Val{LOG} = Val(false), ) where {FT, OFF_DIAG, LOG} if OFF_DIAG - dx = shared_xj[jb] - shared_xi[ia] - dy = shared_xj[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] + Xi = SA.SVector{2, FT}(shared_xi[ia], shared_xi[SF_GPU_TILE + ia]) + Xj = SA.SVector{2, FT}(shared_xj[jb], shared_xj[SF_GPU_TILE + jb]) else - dx = shared_xi[jb] - shared_xi[ia] - dy = shared_xi[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] + Xi = SA.SVector{2, FT}(shared_xi[ia], shared_xi[SF_GPU_TILE + ia]) + Xj = SA.SVector{2, FT}(shared_xi[jb], shared_xi[SF_GPU_TILE + jb]) end - dist_sq = dx * dx + dy * dy - dist = sqrt(dist_sq) - bin = _batch_dist_bin(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG)) - if 1 <= bin < N_bins - return (true, bin, dx / dist, dy / dist) - end - return (false, bin, zero(FT), zero(FT)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) + bin = _batch_dist_bin(dist, first_edge, last_edge, inv_step, step_val, N_bins, Val(LOG)) + return (ok && 1 <= bin < N_bins, bin, Xi, Xj, dist, frame) end """Stage host batch inputs. Fixed-x: `u` → `(B, N, N_dims)` batch-major.""" @@ -294,346 +302,6 @@ KA.@kernel unsafe_indices=true function _batch_merge_usmem_cnts_grouped!( end end -KA.@kernel unsafe_indices=true function _batch_merge_usmem_cnts_by_col!( - output_cnts, - @Const(partial_cnts), - NB::Int, - bw::Int, - n_priv::Int, - nworkers::Int, -) - worker = @index(Global, Linear) - n_out = NB * bw - t = worker - while t <= n_out - rem0 = t - 1 - bin = rem0 % NB + 1 - col = rem0 ÷ NB + 1 - acc_c = UInt32(0) - @inbounds for blk in 1:n_priv - acc_c += partial_cnts[bin, col, blk] - end - @inbounds output_cnts[bin, col] = acc_c - t += nworkers - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp1d_sums!( - output, - @Const(partial_sums), - NB::Int, - bw::Int, - n_priv::Int, - nworkers::Int, -) - worker = @index(Global, Linear) - n_out = SF_GPU_SINGLE_PASS_N * NB * bw - t = worker - while t <= n_out - rem0 = t - 1 - bin = rem0 % NB + 1 - rem1 = rem0 ÷ NB - ty = rem1 % SF_GPU_SINGLE_PASS_N + 1 - col = rem1 ÷ SF_GPU_SINGLE_PASS_N + 1 - acc_s = zero(eltype(output)) - @inbounds for blk in 1:n_priv - acc_s += partial_sums[ty, bin, col, blk] - end - @inbounds output[ty, bin, col] = acc_s - t += nworkers - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp1d_sums_grouped!( - output, - @Const(partial_sums), - NB::Int, - bw::Int, - n_priv::Int, - workgroup_size::Int, -) - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - shared_acc = @localmem eltype(output) (256,) - n_out = SF_GPU_SINGLE_PASS_N * NB * bw - if gid <= n_out - rem0 = gid - 1 - bin = rem0 % NB + 1 - rem1 = rem0 ÷ NB - ty = rem1 % SF_GPU_SINGLE_PASS_N + 1 - col = rem1 ÷ SF_GPU_SINGLE_PASS_N + 1 - acc_s = zero(eltype(output)) - blk = lid - @inbounds while blk <= n_priv - acc_s += partial_sums[ty, bin, col, blk] - blk += workgroup_size - end - shared_acc[lid] = acc_s - @synchronize - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - if gid <= n_out && lid == 1 - rem0 = gid - 1 - bin = rem0 % NB + 1 - rem1 = rem0 ÷ NB - ty = rem1 % SF_GPU_SINGLE_PASS_N + 1 - col = rem1 ÷ SF_GPU_SINGLE_PASS_N + 1 - total = zero(eltype(output)) - @inbounds for t in 1:workgroup_size - total += shared_acc[t] - end - @inbounds output[ty, bin, col] = total - end - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp1d_cnts!( - output_cnts, - @Const(partial_cnts), - NB::Int, - n_priv::Int, - nworkers::Int, -) - worker = @index(Global, Linear) - n_out = SF_GPU_SINGLE_PASS_N * NB - t = worker - while t <= n_out - rem0 = t - 1 - bin = rem0 % NB + 1 - ty = rem0 ÷ NB + 1 - acc_c = UInt32(0) - @inbounds for blk in 1:n_priv - acc_c += partial_cnts[ty, bin, blk] - end - @inbounds output_cnts[ty, bin] = acc_c - t += nworkers - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp1d_cnts_grouped!( - output_cnts, - @Const(partial_cnts), - NB::Int, - n_priv::Int, - workgroup_size::Int, -) - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - shared_acc = @localmem UInt32 (256,) - n_out = SF_GPU_SINGLE_PASS_N * NB - if gid <= n_out - rem0 = gid - 1 - bin = rem0 % NB + 1 - ty = rem0 ÷ NB + 1 - acc_c = UInt32(0) - blk = lid - @inbounds while blk <= n_priv - acc_c += partial_cnts[ty, bin, blk] - blk += workgroup_size - end - shared_acc[lid] = acc_c - @synchronize - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - if gid <= n_out && lid == 1 - rem0 = gid - 1 - bin = rem0 % NB + 1 - ty = rem0 ÷ NB + 1 - total = UInt32(0) - @inbounds for t in 1:workgroup_size - total += shared_acc[t] - end - @inbounds output_cnts[ty, bin] = total - end - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp2d_cnts!( - output_cnts, - @Const(partial_cnts), - n_dist::Int, - n_val::Int, - bw::Int, - n_priv::Int, - nworkers::Int, -) - worker = @index(Global, Linear) - n_out = SF_GPU_SINGLE_PASS_N * n_dist * n_val * bw - t = worker - while t <= n_out - rem0 = t - 1 - vbin = rem0 % n_val + 1 - rem1 = rem0 ÷ n_val - dbin = rem1 % n_dist + 1 - rem2 = rem1 ÷ n_dist - ty = rem2 % SF_GPU_SINGLE_PASS_N + 1 - col = rem2 ÷ SF_GPU_SINGLE_PASS_N + 1 - acc_c = UInt32(0) - @inbounds for blk in 1:n_priv - acc_c += partial_cnts[ty, dbin, vbin, col, blk] - end - @inbounds output_cnts[ty, dbin, vbin, col] = acc_c - t += nworkers - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp2d_cnts_grouped!( - output_cnts, - @Const(partial_cnts), - n_dist::Int, - n_val::Int, - bw::Int, - n_priv::Int, - workgroup_size::Int, -) - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - shared_acc = @localmem UInt32 (256,) - n_out = SF_GPU_SINGLE_PASS_N * n_dist * n_val * bw - if gid <= n_out - rem0 = gid - 1 - vbin = rem0 % n_val + 1 - rem1 = rem0 ÷ n_val - dbin = rem1 % n_dist + 1 - rem2 = rem1 ÷ n_dist - ty = rem2 % SF_GPU_SINGLE_PASS_N + 1 - col = rem2 ÷ SF_GPU_SINGLE_PASS_N + 1 - acc_c = UInt32(0) - blk = lid - @inbounds while blk <= n_priv - acc_c += partial_cnts[ty, dbin, vbin, col, blk] - blk += workgroup_size - end - shared_acc[lid] = acc_c - @synchronize - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - if gid <= n_out && lid == 1 - rem0 = gid - 1 - vbin = rem0 % n_val + 1 - rem1 = rem0 ÷ n_val - dbin = rem1 % n_dist + 1 - rem2 = rem1 ÷ n_dist - ty = rem2 % SF_GPU_SINGLE_PASS_N + 1 - col = rem2 ÷ SF_GPU_SINGLE_PASS_N + 1 - total = UInt32(0) - @inbounds for t in 1:workgroup_size - total += shared_acc[t] - end - @inbounds output_cnts[ty, dbin, vbin, col] = total - end - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp2d_sums!( - output, - @Const(partial_sums), - n_dist::Int, - n_val::Int, - bw::Int, - n_priv::Int, - nworkers::Int, -) - worker = @index(Global, Linear) - n_out = SF_GPU_SINGLE_PASS_N * n_dist * n_val * bw - t = worker - while t <= n_out - rem0 = t - 1 - vbin = rem0 % n_val + 1 - rem1 = rem0 ÷ n_val - dbin = rem1 % n_dist + 1 - rem2 = rem1 ÷ n_dist - ty = rem2 % SF_GPU_SINGLE_PASS_N + 1 - col = rem2 ÷ SF_GPU_SINGLE_PASS_N + 1 - acc_s = zero(eltype(output)) - @inbounds for blk in 1:n_priv - acc_s += partial_sums[ty, dbin, vbin, col, blk] - end - @inbounds output[ty, dbin, vbin, col] = acc_s - t += nworkers - end -end - -KA.@kernel unsafe_indices=true function _batch_merge_sp2d_sums_grouped!( - output, - @Const(partial_sums), - n_dist::Int, - n_val::Int, - bw::Int, - n_priv::Int, - workgroup_size::Int, -) - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - shared_acc = @localmem eltype(output) (256,) - n_out = SF_GPU_SINGLE_PASS_N * n_dist * n_val * bw - if gid <= n_out - rem0 = gid - 1 - vbin = rem0 % n_val + 1 - rem1 = rem0 ÷ n_val - dbin = rem1 % n_dist + 1 - rem2 = rem1 ÷ n_dist - ty = rem2 % SF_GPU_SINGLE_PASS_N + 1 - col = rem2 ÷ SF_GPU_SINGLE_PASS_N + 1 - acc_s = zero(eltype(output)) - blk = lid - @inbounds while blk <= n_priv - acc_s += partial_sums[ty, dbin, vbin, col, blk] - blk += workgroup_size - end - shared_acc[lid] = acc_s - @synchronize - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - gid = (g - 1) ÷ workgroup_size + 1 - if gid <= n_out && lid == 1 - rem0 = gid - 1 - vbin = rem0 % n_val + 1 - rem1 = rem0 ÷ n_val - dbin = rem1 % n_dist + 1 - rem2 = rem1 ÷ n_dist - ty = rem2 % SF_GPU_SINGLE_PASS_N + 1 - col = rem2 ÷ SF_GPU_SINGLE_PASS_N + 1 - total = zero(eltype(output)) - @inbounds for t in 1:workgroup_size - total += shared_acc[t] - end - @inbounds output[ty, dbin, vbin, col] = total - end - end -end - -@inline function _batch_sp1d_accum_shared!( - shared_sums, - shared_cnts, - bin::Int, - col::Int, - du_L, - du_L2, - du_T2, - du_norm2, - NB::Int; - track_counts::Bool = true, -) - base = (col - 1) * SF_GPU_SINGLE_PASS_N * NB - @atomic shared_sums[base + bin] += du_norm2 - @atomic shared_sums[base + NB + bin] += du_L2 - @atomic shared_sums[base + 2NB + bin] += du_T2 - @atomic shared_sums[base + 3NB + bin] += du_L * du_norm2 - @atomic shared_sums[base + 4NB + bin] += du_L * du_L2 - @atomic shared_sums[base + 5NB + bin] += du_L * du_T2 - if track_counts && col == 1 - @atomic shared_cnts[bin] += UInt32(1) - end - return nothing -end # --------------------------------------------------------------------------- # Fixed-x individual SF — u-smem priv strip kernel @@ -657,17 +325,17 @@ KA.@kernel unsafe_indices=true function _batch_fixed_x_usmem_priv!( first_edge::FT, last_edge::FT, inv_step::FT, - offset::FT, step_val::FT, n_tiles::Int, n_tile_blocks::Int, workgroup_size::Int, + geom, ::Val{LOG} = Val(false), ) where {FT, LOG} shared_xi = @localmem FT (256,) shared_xj = @localmem FT (256,) - shared_ui = @localmem FT (256 * BATCH_USMEM_STRIP_W,) - shared_uj = @localmem FT (256 * BATCH_USMEM_STRIP_W,) + shared_ui = @localmem FT (256 * _batch_usmem_strip_w(FT),) + shared_uj = @localmem FT (256 * _batch_usmem_strip_w(FT),) g = @index(Global, Linear) lid = (g - 1) % workgroup_size + 1 @@ -744,16 +412,19 @@ KA.@kernel unsafe_indices=true function _batch_fixed_x_usmem_priv!( while p <= n_pairs ia = (p - 1) ÷ nj + 1 jb = (p - 1) - (ia - 1) * nj + 1 - pair_ok, bin, rx, ry = _pair_bin_rhat_from_smem!( + pair_ok, bin, Xi, Xj, dist, frame = _pair_bin_frame_from_smem!( shared_xi, shared_xj, ia, jb, Val(true), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), + first_edge, last_edge, inv_step, step_val, N_bins, geom, Val(LOG), ) if pair_ok priv_idx = _batch_usmem_priv_idx(block_id, lid) + # Loop-invariant across the field strip. + rhat = SFH.pair_direction(geom, frame, dist) @inbounds for col in 1:bw - du_x = shared_uj[_batch_usmem_idx(1, jb, col)] - shared_ui[_batch_usmem_idx(1, ia, col)] - du_y = shared_uj[_batch_usmem_idx(2, jb, col)] - shared_ui[_batch_usmem_idx(2, ia, col)] - val = _gpu_sf_value_2d(sf_type, du_x, du_y, rx, ry) + Ui = SA.SVector{2}(shared_ui[_batch_usmem_idx(1, ia, col)], shared_ui[_batch_usmem_idx(2, ia, col)]) + Uj = SA.SVector{2}(shared_uj[_batch_usmem_idx(1, jb, col)], shared_uj[_batch_usmem_idx(2, jb, col)]) + dU = SFH.pair_delta(geom, frame, Xi, Xj, Ui, Uj) + val = _gpu_sf_value_2d(sf_type, dU[1], dU[2], rhat[1], rhat[2]) @atomic partial_sums[bin, col, priv_idx] += val end if b_base == 1 @@ -767,16 +438,19 @@ KA.@kernel unsafe_indices=true function _batch_fixed_x_usmem_priv!( p = lid while p <= n_pairs ia, jb = _pair_from_linear(p, ni) - pair_ok, bin, rx, ry = _pair_bin_rhat_from_smem!( + pair_ok, bin, Xi, Xj, dist, frame = _pair_bin_frame_from_smem!( shared_xi, shared_xj, ia, jb, Val(false), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), + first_edge, last_edge, inv_step, step_val, N_bins, geom, Val(LOG), ) if pair_ok priv_idx = _batch_usmem_priv_idx(block_id, lid) + # Loop-invariant across the field strip. + rhat = SFH.pair_direction(geom, frame, dist) @inbounds for col in 1:bw - du_x = shared_ui[_batch_usmem_idx(1, jb, col)] - shared_ui[_batch_usmem_idx(1, ia, col)] - du_y = shared_ui[_batch_usmem_idx(2, jb, col)] - shared_ui[_batch_usmem_idx(2, ia, col)] - val = _gpu_sf_value_2d(sf_type, du_x, du_y, rx, ry) + Ui = SA.SVector{2}(shared_ui[_batch_usmem_idx(1, ia, col)], shared_ui[_batch_usmem_idx(2, ia, col)]) + Uj = SA.SVector{2}(shared_ui[_batch_usmem_idx(1, jb, col)], shared_ui[_batch_usmem_idx(2, jb, col)]) + dU = SFH.pair_delta(geom, frame, Xi, Xj, Ui, Uj) + val = _gpu_sf_value_2d(sf_type, dU[1], dU[2], rhat[1], rhat[2]) @atomic partial_sums[bin, col, priv_idx] += val end if b_base == 1 @@ -790,963 +464,3 @@ KA.@kernel unsafe_indices=true function _batch_fixed_x_usmem_priv!( end end -# --------------------------------------------------------------------------- -# Fixed-x individual SF — global-`u` strip kernel (WITHDRAWN — not used in launch) -# -# A100 Mar 2026: strip 128 / 63 sweeps measured ~48 s at NB=50–64 vs ~12 s for usmem -# strip 16 / 504 sweeps at NB=50. Fewer geometry replays were canceled by 8× more -# inner-loop atomics per pair and uncached global `u` loads. Do not wire without profiling. -# --------------------------------------------------------------------------- - -""" - _batch_fixed_x_global_u_priv!(partial_sums, partial_cnts, ...) -""" -KA.@kernel unsafe_indices=true function _batch_fixed_x_global_u_priv!( - partial_sums, - partial_cnts, - @Const(x_mat), - @Const(u_batch), - sf_type, - N_points::Int, - N_bins::Int, - NB::Int, - b_base::Int, - bw::Int, - first_edge::FT, - last_edge::FT, - inv_step::FT, - offset::FT, - step_val::FT, - n_tiles::Int, - n_tile_blocks::Int, - workgroup_size::Int, - ::Val{LOG} = Val(false), -) where {FT, LOG} - shared_xi = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_sums = @localmem FT (SF_GPU_MAX_BINS * 128,) - shared_cnts = @localmem UInt32 (SF_GPU_MAX_BINS,) - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - - slot = lid - while slot <= NB * bw - @inbounds shared_sums[slot] = zero(FT) - slot += workgroup_size - end - if b_base == 1 - slot = lid - while slot <= NB - @inbounds shared_cnts[slot] = UInt32(0) - slot += workgroup_size - end - end - - if bid <= n_tile_blocks - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - k = lid - while k <= ni - gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_mat[1, gi] - shared_xi[SF_GPU_TILE + k] = x_mat[2, gi] - end - k += workgroup_size - end - if ti < tj - k = lid - while k <= nj - gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_mat[1, gj] - shared_xj[SF_GPU_TILE + k] = x_mat[2, gj] - end - k += workgroup_size - end - end - end - end - @synchronize - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - if bid <= n_tile_blocks - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - if ti < tj - n_pairs = ni * nj - p = lid - while p <= n_pairs - ia = (p - 1) ÷ nj + 1 - jb = (p - 1) - (ia - 1) * nj + 1 - pair_ok, bin, rx, ry = _pair_bin_rhat_from_smem!( - shared_xi, shared_xj, ia, jb, Val(true), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), - ) - if pair_ok - gi = i0 + ia - 1 - gj = j0 + jb - 1 - @inbounds for col in 1:bw - b_idx = b_base + col - 1 - du_x = u_batch[b_idx, gj, 1] - u_batch[b_idx, gi, 1] - du_y = u_batch[b_idx, gj, 2] - u_batch[b_idx, gi, 2] - val = _gpu_sf_value_2d(sf_type, du_x, du_y, rx, ry) - hist_slot = bin + (col - 1) * NB - @atomic shared_sums[hist_slot] += val - end - if b_base == 1 - @atomic shared_cnts[bin] += UInt32(1) - end - end - p += workgroup_size - end - else - n_pairs = ni * (ni - 1) ÷ 2 - p = lid - while p <= n_pairs - ia, jb = _pair_from_linear(p, ni) - pair_ok, bin, rx, ry = _pair_bin_rhat_from_smem!( - shared_xi, shared_xj, ia, jb, Val(false), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), - ) - if pair_ok - gi = i0 + ia - 1 - gj = i0 + jb - 1 - @inbounds for col in 1:bw - b_idx = b_base + col - 1 - du_x = u_batch[b_idx, gj, 1] - u_batch[b_idx, gi, 1] - du_y = u_batch[b_idx, gj, 2] - u_batch[b_idx, gi, 2] - val = _gpu_sf_value_2d(sf_type, du_x, du_y, rx, ry) - hist_slot = bin + (col - 1) * NB - @atomic shared_sums[hist_slot] += val - end - if b_base == 1 - @atomic shared_cnts[bin] += UInt32(1) - end - end - p += workgroup_size - end - end - end - end - @synchronize - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - if bid <= n_tile_blocks - slot = lid - while slot <= NB * bw - bin = (slot - 1) % NB + 1 - col = (slot - 1) ÷ NB + 1 - @inbounds partial_sums[bin, col, block_id] = shared_sums[slot] - slot += workgroup_size - end - if b_base == 1 - slot = lid - while slot <= NB - @inbounds partial_cnts[slot, block_id] = shared_cnts[slot] - slot += workgroup_size - end - end - end -end - -# --------------------------------------------------------------------------- -# Fixed-x SP1D (six invariants) — u-smem priv strip kernel -# --------------------------------------------------------------------------- - -KA.@kernel unsafe_indices=true function _batch_fixed_x_sp1d_usmem_priv!( - partial_sums, - partial_cnts, - @Const(x_mat), - @Const(u_batch), - N_points::Int, - N_bins::Int, - NB::Int, - b_base::Int, - bw::Int, - first_edge::FT, - last_edge::FT, - inv_step::FT, - offset::FT, - step_val::FT, - n_tiles::Int, - n_tile_blocks::Int, - workgroup_size::Int, - ::Val{LOG} = Val(false), -) where {FT, LOG} - shared_xi = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_ui = @localmem FT (256 * BATCH_SP1D_USMEM_STRIP_W,) - shared_uj = @localmem FT (256 * BATCH_SP1D_USMEM_STRIP_W,) - shared_sums = @localmem FT (SF_GPU_SINGLE_PASS_N * SF_GPU_MAX_BINS * BATCH_SP1D_USMEM_STRIP_W,) - shared_cnts = @localmem UInt32 (SF_GPU_MAX_BINS,) - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - - slot = lid - while slot <= SF_GPU_SINGLE_PASS_N * NB * bw - @inbounds shared_sums[slot] = zero(FT) - slot += workgroup_size - end - if b_base == 1 - slot = lid - while slot <= NB - @inbounds shared_cnts[slot] = UInt32(0) - slot += workgroup_size - end - end - - if bid <= n_tile_blocks - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - k = lid - while k <= ni - gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_mat[1, gi] - shared_xi[SF_GPU_TILE + k] = x_mat[2, gi] - end - k += workgroup_size - end - if ti < tj - k = lid - while k <= nj - gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_mat[1, gj] - shared_xj[SF_GPU_TILE + k] = x_mat[2, gj] - end - k += workgroup_size - end - end - elem = lid - while elem <= 256 * bw - col = (elem - 1) ÷ 256 + 1 - rem = (elem - 1) % 256 - k = rem ÷ 2 + 1 - c = rem % 2 + 1 - gi = i0 + k - 1 - b_idx = b_base + col - 1 - if k <= ni - @inbounds shared_ui[elem] = u_batch[b_idx, gi, c] - else - @inbounds shared_ui[elem] = zero(FT) - end - elem += workgroup_size - end - if ti < tj - elem = lid - while elem <= 256 * bw - col = (elem - 1) ÷ 256 + 1 - rem = (elem - 1) % 256 - k = rem ÷ 2 + 1 - c = rem % 2 + 1 - gj = j0 + k - 1 - b_idx = b_base + col - 1 - if k <= nj - @inbounds shared_uj[elem] = u_batch[b_idx, gj, c] - else - @inbounds shared_uj[elem] = zero(FT) - end - elem += workgroup_size - end - end - end - end - @synchronize - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - if bid <= n_tile_blocks - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - if ti < tj - n_pairs = ni * nj - p = lid - while p <= n_pairs - ia = (p - 1) ÷ nj + 1 - jb = (p - 1) - (ia - 1) * nj + 1 - pair_ok, bin, rx, ry = _pair_bin_rhat_from_smem!( - shared_xi, shared_xj, ia, jb, Val(true), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), - ) - if pair_ok - @inbounds for col in 1:bw - du_x = shared_uj[_batch_usmem_idx(1, jb, col)] - shared_ui[_batch_usmem_idx(1, ia, col)] - du_y = shared_uj[_batch_usmem_idx(2, jb, col)] - shared_ui[_batch_usmem_idx(2, ia, col)] - du_L = rx * du_x + ry * du_y - du_L2 = du_L * du_L - du_norm2 = du_x * du_x + du_y * du_y - du_T2 = du_norm2 - du_L2 - _batch_sp1d_accum_shared!( - shared_sums, shared_cnts, bin, col, - du_L, du_L2, du_T2, du_norm2, NB, - ) - end - end - p += workgroup_size - end - else - n_pairs = ni * (ni - 1) ÷ 2 - p = lid - while p <= n_pairs - ia, jb = _pair_from_linear(p, ni) - pair_ok, bin, rx, ry = _pair_bin_rhat_from_smem!( - shared_xi, shared_xj, ia, jb, Val(false), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), - ) - if pair_ok - @inbounds for col in 1:bw - du_x = shared_ui[_batch_usmem_idx(1, jb, col)] - shared_ui[_batch_usmem_idx(1, ia, col)] - du_y = shared_ui[_batch_usmem_idx(2, jb, col)] - shared_ui[_batch_usmem_idx(2, ia, col)] - du_L = rx * du_x + ry * du_y - du_L2 = du_L * du_L - du_norm2 = du_x * du_x + du_y * du_y - du_T2 = du_norm2 - du_L2 - _batch_sp1d_accum_shared!( - shared_sums, shared_cnts, bin, col, - du_L, du_L2, du_T2, du_norm2, NB, - ) - end - end - p += workgroup_size - end - end - end - end - @synchronize - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - if bid <= n_tile_blocks - slot = lid - while slot <= SF_GPU_SINGLE_PASS_N * NB * bw - rem0 = slot - 1 - bin = rem0 % NB + 1 - rem1 = rem0 ÷ NB - ty = rem1 % SF_GPU_SINGLE_PASS_N + 1 - col = rem1 ÷ SF_GPU_SINGLE_PASS_N + 1 - @inbounds partial_sums[ty, bin, col, block_id] = shared_sums[slot] - slot += workgroup_size - end - if b_base == 1 - slot = lid - while slot <= SF_GPU_SINGLE_PASS_N * NB - rem0 = slot - 1 - bin = rem0 % NB + 1 - ty = rem0 ÷ NB + 1 - @inbounds partial_cnts[ty, bin, block_id] = shared_cnts[bin] - slot += workgroup_size - end - end - end -end - -# --------------------------------------------------------------------------- -# Fixed-x SP2D — shared x, u strip, partial block-private outputs -# --------------------------------------------------------------------------- - -KA.@kernel unsafe_indices=true function _batch_varying_x_sp2d_fixed_x!( - partial_sums, - partial_cnts, - @Const(x_mat), - @Const(u_batch), - N_points::Int, - N_bins::Int, - n_dist::Int, - n_val::Int, - b_base::Int, - bw::Int, - first_edge::FT, - last_edge::FT, - inv_step::FT, - offset::FT, - step_val::FT, - val_plan::GPUValueDigitizePlan, - n_tiles::Int, - n_tile_blocks::Int, - workgroup_size::Int, - ::Val{LOG} = Val(false), -) where {FT, LOG} - shared_xi = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_ui = @localmem FT (BATCH_USMEM_STRIP_W * SF_GPU_TILE * 2,) - shared_uj = @localmem FT (BATCH_USMEM_STRIP_W * SF_GPU_TILE * 2,) - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - - if bid <= n_tile_blocks - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - k = lid - while k <= ni - gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_mat[1, gi] - shared_xi[SF_GPU_TILE + k] = x_mat[2, gi] - end - k += workgroup_size - end - _stage_batch_ui_tile!(shared_ui, u_batch, b_base, bw, i0, ni, workgroup_size, lid) - if ti < tj - k = lid - while k <= nj - gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_mat[1, gj] - shared_xj[SF_GPU_TILE + k] = x_mat[2, gj] - end - k += workgroup_size - end - _stage_batch_ui_tile!(shared_uj, u_batch, b_base, bw, j0, nj, workgroup_size, lid) - end - end - end - @synchronize - - g = @index(Global, Linear) - lid = (g - 1) % workgroup_size + 1 - bid = (g - 1) ÷ workgroup_size + 1 - block_id = bid - if bid <= n_tile_blocks - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - n_pairs = ti < tj ? ni * nj : ni * (ni - 1) ÷ 2 - p = lid - while p <= n_pairs - if ti < tj - ia = (p - 1) ÷ nj + 1 - jb = (p - 1) - (ia - 1) * nj + 1 - pair_ok, dbin, rx, ry = _pair_bin_rhat_from_smem!( - shared_xi, shared_xj, ia, jb, Val(true), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), - ) - if pair_ok - @inbounds for col in 1:bw - du_x = shared_uj[_batch_usmem_idx(1, jb, col)] - shared_ui[_batch_usmem_idx(1, ia, col)] - du_y = shared_uj[_batch_usmem_idx(2, jb, col)] - shared_ui[_batch_usmem_idx(2, ia, col)] - du_L = rx * du_x + ry * du_y - du_L2 = du_L * du_L - du_norm2 = du_x * du_x + du_y * du_y - du_T2 = du_norm2 - du_L2 - v1 = du_norm2 - v2 = du_L2 - v3 = du_T2 - v4 = du_L * du_norm2 - v5 = du_L * du_L2 - v6 = du_L * du_T2 - @inbounds for t in 1:SF_GPU_SINGLE_PASS_N - val_t = t == 1 ? v1 : t == 2 ? v2 : t == 3 ? v3 : t == 4 ? v4 : t == 5 ? v5 : v6 - vbin = _gpu_digitize_value_plan(val_t, val_plan, t, n_val + 1) - if 1 <= vbin <= n_val - @atomic partial_sums[t, dbin, vbin, col, block_id] += val_t - @atomic partial_cnts[t, dbin, vbin, col, block_id] += UInt32(1) - end - end - end - end - else - ia, jb = _pair_from_linear(p, ni) - pair_ok, dbin, rx, ry = _pair_bin_rhat_from_smem!( - shared_xi, shared_xj, ia, jb, Val(false), - first_edge, last_edge, inv_step, offset, step_val, N_bins, Val(LOG), - ) - if pair_ok - @inbounds for col in 1:bw - du_x = shared_ui[_batch_usmem_idx(1, jb, col)] - shared_ui[_batch_usmem_idx(1, ia, col)] - du_y = shared_ui[_batch_usmem_idx(2, jb, col)] - shared_ui[_batch_usmem_idx(2, ia, col)] - du_L = rx * du_x + ry * du_y - du_L2 = du_L * du_L - du_norm2 = du_x * du_x + du_y * du_y - du_T2 = du_norm2 - du_L2 - v1 = du_norm2 - v2 = du_L2 - v3 = du_T2 - v4 = du_L * du_norm2 - v5 = du_L * du_L2 - v6 = du_L * du_T2 - @inbounds for t in 1:SF_GPU_SINGLE_PASS_N - val_t = t == 1 ? v1 : t == 2 ? v2 : t == 3 ? v3 : t == 4 ? v4 : t == 5 ? v5 : v6 - vbin = _gpu_digitize_value_plan(val_t, val_plan, t, n_val + 1) - if 1 <= vbin <= n_val - @atomic partial_sums[t, dbin, vbin, col, block_id] += val_t - @atomic partial_cnts[t, dbin, vbin, col, block_id] += UInt32(1) - end - end - end - end - end - p += workgroup_size - end - end - end -end - -# --------------------------------------------------------------------------- -# Varying geometry — one launch per (tile, b) -# --------------------------------------------------------------------------- - -"""Tiled varying-x individual SF: stages x and u per tile per batch element into shared memory, -accumulates into a block-local histogram, then flushes to global output. -Replaces the naive version which did all reads/writes from global memory.""" -KA.@kernel unsafe_indices=true function _batch_varying_x_sf!( - output, - counts, - @Const(x_batch), - @Const(u_batch), - sf_type, - N_points::Int, - N_bins::Int, - NB::Int, - first_edge::FT, - last_edge::FT, - inv_step::FT, - offset::FT, - step_val::FT, - n_tiles::Int, - n_tile_blocks::Int, - workgroup_size::Int, - B::Int, -) where {FT} - shared_xi = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_ui = @localmem FT (256,) - shared_uj = @localmem FT (256,) - shared_sums = @localmem FT (SF_GPU_MAX_BINS,) - shared_cnts = @localmem UInt32 (SF_GPU_MAX_BINS,) - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - - b_init = lid - while b_init <= NB - @inbounds shared_sums[b_init] = zero(FT) - @inbounds shared_cnts[b_init] = UInt32(0) - b_init += workgroup_size - end - - if bid <= n_tile_blocks && b <= B - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - k = lid - while k <= ni - gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_batch[1, gi, b] - shared_xi[SF_GPU_TILE + k] = x_batch[2, gi, b] - shared_ui[k] = u_batch[1, gi, b] - shared_ui[SF_GPU_TILE + k] = u_batch[2, gi, b] - end - k += workgroup_size - end - if ti < tj - k = lid - while k <= nj - gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_batch[1, gj, b] - shared_xj[SF_GPU_TILE + k] = x_batch[2, gj, b] - shared_uj[k] = u_batch[1, gj, b] - shared_uj[SF_GPU_TILE + k] = u_batch[2, gj, b] - end - k += workgroup_size - end - end - end - end - @synchronize - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - if bid <= n_tile_blocks && b <= B - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - n_pairs = ti < tj ? ni * nj : ni * (ni - 1) ÷ 2 - p = lid - while p <= n_pairs - if ti < tj - ia = (p - 1) ÷ nj + 1 - jb = (p - 1) - (ia - 1) * nj + 1 - dx = shared_xj[jb] - shared_xi[ia] - dy = shared_xj[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] - U1x = shared_ui[ia]; U1y = shared_ui[SF_GPU_TILE + ia] - U2x = shared_uj[jb]; U2y = shared_uj[SF_GPU_TILE + jb] - else - ia, jb = _pair_from_linear(p, ni) - dx = shared_xi[jb] - shared_xi[ia] - dy = shared_xi[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] - U1x = shared_ui[ia]; U1y = shared_ui[SF_GPU_TILE + ia] - U2x = shared_ui[jb]; U2y = shared_ui[SF_GPU_TILE + jb] - end - dist_sq = dx * dx + dy * dy - dist = sqrt(dist_sq) - bin = _gpu_digitize_linear(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) - if 1 <= bin < N_bins - rx = dx / dist; ry = dy / dist - val = _gpu_sf_value_2d(sf_type, U2x - U1x, U2y - U1y, rx, ry) - @atomic shared_sums[bin] += val - @atomic shared_cnts[bin] += UInt32(1) - end - p += workgroup_size - end - end - end - @synchronize - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - if bid <= n_tile_blocks && b <= B - flushed = lid - while flushed <= NB - s = shared_sums[flushed] - @atomic output[flushed, b] += s - c = shared_cnts[flushed] - if c != UInt32(0) - @atomic counts[flushed, b] += c - end - flushed += workgroup_size - end - end -end - -"""Tiled varying-x SP1D: stages x and u per tile per batch element into shared memory, -accumulates into a block-local (6, NB) histogram, then flushes to global output. -Replaces the naive version that issued 12 global atomics per valid pair.""" -KA.@kernel unsafe_indices=true function _batch_varying_x_sp1d!( - output_sums, - output_counts, - @Const(x_batch), - @Const(u_batch), - N_points::Int, - N_bins::Int, - NB::Int, - first_edge::FT, - last_edge::FT, - inv_step::FT, - offset::FT, - step_val::FT, - n_tiles::Int, - n_tile_blocks::Int, - workgroup_size::Int, - B::Int, -) where {FT} - shared_xi = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_ui = @localmem FT (256,) - shared_uj = @localmem FT (256,) - shared_sums = @localmem FT (SF_GPU_SINGLE_PASS_N * SF_GPU_MAX_BINS,) - shared_cnts = @localmem UInt32 (SF_GPU_MAX_BINS,) - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - - k_init = lid - while k_init <= SF_GPU_SINGLE_PASS_N * NB - @inbounds shared_sums[k_init] = zero(FT) - k_init += workgroup_size - end - b_init = lid - while b_init <= NB - @inbounds shared_cnts[b_init] = UInt32(0) - b_init += workgroup_size - end - - if bid <= n_tile_blocks && b <= B - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - k = lid - while k <= ni - gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_batch[1, gi, b] - shared_xi[SF_GPU_TILE + k] = x_batch[2, gi, b] - shared_ui[k] = u_batch[1, gi, b] - shared_ui[SF_GPU_TILE + k] = u_batch[2, gi, b] - end - k += workgroup_size - end - if ti < tj - k = lid - while k <= nj - gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_batch[1, gj, b] - shared_xj[SF_GPU_TILE + k] = x_batch[2, gj, b] - shared_uj[k] = u_batch[1, gj, b] - shared_uj[SF_GPU_TILE + k] = u_batch[2, gj, b] - end - k += workgroup_size - end - end - end - end - @synchronize - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - if bid <= n_tile_blocks && b <= B - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - n_pairs = ti < tj ? ni * nj : ni * (ni - 1) ÷ 2 - p = lid - while p <= n_pairs - if ti < tj - ia = (p - 1) ÷ nj + 1 - jb = (p - 1) - (ia - 1) * nj + 1 - dx = shared_xj[jb] - shared_xi[ia] - dy = shared_xj[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] - U1x = shared_ui[ia]; U1y = shared_ui[SF_GPU_TILE + ia] - U2x = shared_uj[jb]; U2y = shared_uj[SF_GPU_TILE + jb] - else - ia, jb = _pair_from_linear(p, ni) - dx = shared_xi[jb] - shared_xi[ia] - dy = shared_xi[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] - U1x = shared_ui[ia]; U1y = shared_ui[SF_GPU_TILE + ia] - U2x = shared_ui[jb]; U2y = shared_ui[SF_GPU_TILE + jb] - end - dist_sq = dx * dx + dy * dy - dist = sqrt(dist_sq) - bin = _gpu_digitize_linear(dist, first_edge, last_edge, inv_step, offset, step_val, N_bins) - if 1 <= bin < N_bins - rx = dx / dist; ry = dy / dist - du_x = U2x - U1x; du_y = U2y - U1y - du_L = rx * du_x + ry * du_y - du_L2 = du_L * du_L - du_norm2 = du_x * du_x + du_y * du_y - du_T2 = du_norm2 - du_L2 - _gpu_accumulate_single_pass_1d_shared!( - shared_sums, shared_cnts, bin, du_L, du_L2, du_T2, du_norm2, NB, - ) - end - p += workgroup_size - end - end - end - @synchronize - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - if bid <= n_tile_blocks && b <= B - k = lid - while k <= SF_GPU_SINGLE_PASS_N * NB - s = shared_sums[k] - if s != zero(FT) - t = (k - 1) ÷ NB + 1 - bin = (k - 1) % NB + 1 - @atomic output_sums[t, bin, b] += s - end - k += workgroup_size - end - cnt_slot = lid - while cnt_slot <= NB - c = shared_cnts[cnt_slot] - if c != UInt32(0) - for t in 1:SF_GPU_SINGLE_PASS_N - @atomic output_counts[t, cnt_slot, b] += c - end - end - cnt_slot += workgroup_size - end - end -end - -"""Tiled varying-x SP2D: stages tile x/u into shared memory to cut global loads per pair -from 8 down to 0 after the load phase. Output histogram is too large for shared memory -(n_dist×n_val×6 can exceed 48 KB), so global atomics are used for output.""" -KA.@kernel unsafe_indices=true function _batch_varying_x_sp2d!( - output_sums, - output_counts, - @Const(x_batch), - @Const(u_batch), - N_points::Int, - N_bins::Int, - n_dist::Int, - n_val::Int, - first_edge::FT, - last_edge::FT, - inv_step::FT, - offset::FT, - step_val::FT, - val_plan::GPUValueDigitizePlan, - n_tiles::Int, - n_tile_blocks::Int, - workgroup_size::Int, - B::Int, -) where {FT} - shared_xi = @localmem FT (256,) - shared_xj = @localmem FT (256,) - shared_ui = @localmem FT (256,) - shared_uj = @localmem FT (256,) - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - - if bid <= n_tile_blocks && b <= B - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - k = lid - while k <= ni - gi = i0 + k - 1 - @inbounds begin - shared_xi[k] = x_batch[1, gi, b] - shared_xi[SF_GPU_TILE + k] = x_batch[2, gi, b] - shared_ui[k] = u_batch[1, gi, b] - shared_ui[SF_GPU_TILE + k] = u_batch[2, gi, b] - end - k += workgroup_size - end - if ti < tj - k = lid - while k <= nj - gj = j0 + k - 1 - @inbounds begin - shared_xj[k] = x_batch[1, gj, b] - shared_xj[SF_GPU_TILE + k] = x_batch[2, gj, b] - shared_uj[k] = u_batch[1, gj, b] - shared_uj[SF_GPU_TILE + k] = u_batch[2, gj, b] - end - k += workgroup_size - end - end - end - end - @synchronize - - lid = @index(Local, Linear) - launch_block = @index(Group, Linear) - bid = (launch_block - 1) % n_tile_blocks + 1 - b = (launch_block - 1) ÷ n_tile_blocks + 1 - if bid <= n_tile_blocks && b <= B - ti, tj = _tile_from_linear(bid, n_tiles) - i0 = (ti - 1) * SF_GPU_TILE + 1 - j0 = (tj - 1) * SF_GPU_TILE + 1 - ni = min(SF_GPU_TILE, N_points - i0 + 1) - nj = min(SF_GPU_TILE, N_points - j0 + 1) - if ni > 0 && nj > 0 - n_pairs = ti < tj ? ni * nj : ni * (ni - 1) ÷ 2 - p = lid - while p <= n_pairs - @inbounds begin - if ti < tj - ia = (p - 1) ÷ nj + 1 - jb = (p - 1) - (ia - 1) * nj + 1 - dx = shared_xj[jb] - shared_xi[ia] - dy = shared_xj[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] - du_x = shared_uj[jb] - shared_ui[ia] - du_y = shared_uj[SF_GPU_TILE + jb] - shared_ui[SF_GPU_TILE + ia] - else - ia, jb = _pair_from_linear(p, ni) - dx = shared_xi[jb] - shared_xi[ia] - dy = shared_xi[SF_GPU_TILE + jb] - shared_xi[SF_GPU_TILE + ia] - du_x = shared_ui[jb] - shared_ui[ia] - du_y = shared_ui[SF_GPU_TILE + jb] - shared_ui[SF_GPU_TILE + ia] - end - dist = sqrt(dx * dx + dy * dy) - dbin = _gpu_digitize_linear( - dist, first_edge, last_edge, inv_step, offset, step_val, N_bins, - ) - if 1 <= dbin < N_bins - rx = dx / dist - ry = dy / dist - du_L = rx * du_x + ry * du_y - du_L2 = du_L * du_L - du_norm2 = du_x * du_x + du_y * du_y - du_T2 = du_norm2 - du_L2 - v1 = du_norm2 - v2 = du_L2 - v3 = du_T2 - v4 = du_L * du_norm2 - v5 = du_L * du_L2 - v6 = du_L * du_T2 - @inbounds for t in 1:SF_GPU_SINGLE_PASS_N - val_t = t == 1 ? v1 : t == 2 ? v2 : t == 3 ? v3 : t == 4 ? v4 : t == 5 ? v5 : v6 - vbin = _gpu_digitize_value_plan(val_t, val_plan, t, n_val + 1) - if 1 <= vbin <= n_val - @atomic output_sums[t, dbin, vbin, b] += val_t - @atomic output_counts[t, dbin, vbin, b] += UInt32(1) - end - end - end - end - p += workgroup_size - end - end - end -end diff --git a/ext/gpu/launch.jl b/ext/gpu/launch.jl index 05f3080..4c392e6 100644 --- a/ext/gpu/launch.jl +++ b/ext/gpu/launch.jl @@ -35,7 +35,8 @@ function _launch_joint_2d_tiled_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - n_val::Int; + n_val::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -49,9 +50,9 @@ function _launch_joint_2d_tiled_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LinearBinEdges && val_plan isa GPUValueInfLinearShared @@ -60,10 +61,10 @@ function _launch_joint_2d_tiled_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LinearBinEdges && val_plan isa GPUValueLogLinearShared @@ -72,9 +73,9 @@ function _launch_joint_2d_tiled_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LinearBinEdges && val_plan === nothing @@ -83,56 +84,56 @@ function _launch_joint_2d_tiled_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LogBinEdges && val_plan isa GPUValueLinearShared lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) _joint2d_invoke_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LogBinEdges && val_plan isa GPUValueInfLinearShared lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) _joint2d_invoke_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LogBinEdges && val_plan isa GPUValueLogLinearShared lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) _joint2d_invoke_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa LogBinEdges && val_plan === nothing lbe = dist_bins - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) _joint2d_invoke_kernel!( kernel!, out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - d_f, d_l, d_inv, d_off, d_st, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa Vector && val_plan isa GPUValueLinearShared @@ -149,8 +150,8 @@ function _launch_joint_2d_tiled_kernel!( dist_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, edges[1], - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa Vector && val_plan isa GPUValueInfLinearShared @@ -167,9 +168,9 @@ function _launch_joint_2d_tiled_kernel!( dist_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, edges[1], - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa Vector && val_plan isa GPUValueLogLinearShared @@ -186,8 +187,8 @@ function _launch_joint_2d_tiled_kernel!( dist_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, edges[1], - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) elseif dist_bins isa Vector && val_plan === nothing @@ -204,7 +205,7 @@ function _launch_joint_2d_tiled_kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_dev, value_edges_dev, sf_type, N_points, n_dist_edges, n_val_edges, n_val, NB2, - edges[1], n_tiles, n_tile_blocks, ws; + edges[1], n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) else @@ -245,13 +246,25 @@ function _sp2d_val_variant(::GPUValueVectorCols) return :vector_cols end -"""Trailing kernel args after tile launch params (`C, plane, types_per_pass, n_type_passes`).""" -@inline function _sp2d_strategy_kernel_tail_args(config::SP2DAccumulationStrategy) +""" +Trailing kernel args after tile launch params: `C, plane, types_per_pass, n_type_passes`, then the +compile-time shared-histogram width as a `Val`. Every launch site splats this, so the width reaches +all of them from one place. + +`C` and `plane` are the **padded** extents, because the kernel uses them to bound its zeroing and +flush loops over the shared layout — not the logical cell counts, which are what the histogram +actually contains. `D` follows as a `Val` so the kernel can size its tile staging and build its +coordinate vectors at compile time. +""" +@inline function _sp2d_strategy_kernel_tail_args(config::SP2DAccumulationStrategy, D::Int, geom) return ( - config.n_joint_cells, - config.plane_cells, + config.shared_cells, + config.plane_shared_cells, config.types_per_pass, config.n_type_passes, + Val(_sp2d_sharedhist_compile_cells(config)), + D == 3 ? Val(3) : Val(2), + geom, ) end @@ -267,10 +280,6 @@ function _sp2d_resolve_pair_kernel( if workspace !== nothing && workspace.sp2d_pair_kernel !== nothing return workspace.sp2d_pair_kernel end - dist_bins isa LinearBinEdges || dist_bins isa LogBinEdges || - throw(ArgumentError( - "HTP-EJ sp2d pair kernel requires LinearBinEdges or LogBinEdges distance bins (got $(typeof(dist_bins)))", - )) dist_sym = _sp2d_dist_variant(dist_bins) val_sym = _sp2d_val_variant(val_plan) kernel! = _sp2d_partition_kernel_fn(dist_sym, val_sym, config.accum_mode, backend, ws) @@ -292,7 +301,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -301,10 +311,10 @@ function _sp2d_pair_launch_kernel!( kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -322,7 +332,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -331,10 +342,10 @@ function _sp2d_pair_launch_kernel!( kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -352,7 +363,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -361,11 +373,11 @@ function _sp2d_pair_launch_kernel!( kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -383,7 +395,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -392,11 +405,11 @@ function _sp2d_pair_launch_kernel!( kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, vp.inner_last, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, vp.inner_last, vp.n_inner_edges, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -414,7 +427,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -423,10 +437,10 @@ function _sp2d_pair_launch_kernel!( kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -444,7 +458,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -453,10 +468,10 @@ function _sp2d_pair_launch_kernel!( kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -474,20 +489,21 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -505,20 +521,21 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -536,21 +553,22 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -568,21 +586,22 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, vp.inner_last, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, vp.inner_last, vp.n_inner_edges, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -600,20 +619,21 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -631,20 +651,21 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -662,20 +683,113 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; + workspace::Union{GPUSFWorkspace, Nothing} = nothing, +) + n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) + kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) + lbe, vp = dist_bins, val_plan + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) + kernel!( + partition_sums_dev, partition_counts_dev, x_dev, u_dev, + N_points, n_dist_edges, n_dist, n_val_edges, + d_f, d_l, d_inv, d_st, + vp.edges_dev, + n_tiles, n_tile_blocks, ws, + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; + ndrange = ndrange, + ) + return n_tile_blocks +end + +""" + _sp2d_val_launch_fields(val_plan) + +Launch-time values for a value plan, in the order [`_sp2d_partition_val_params`](@ref) declares them +for the matching route. Keep the two in step: a mismatch is an argument-count error at launch. +""" +@inline _sp2d_val_launch_fields(p::GPUValueLinearShared) = + (p.first, p.last, p.inv_step, p.step) +@inline _sp2d_val_launch_fields(p::GPUValueLinearCols) = + (p.first, p.last, p.inv_step, p.step) +@inline _sp2d_val_launch_fields(p::GPUValueLogLinearShared) = + (p.first, p.last, p.inv_step, p.step) +@inline _sp2d_val_launch_fields(p::GPUValueLogLinearCols) = + (p.first, p.last, p.inv_step, p.step) +@inline _sp2d_val_launch_fields(p::GPUValueInfLinearShared) = + (p.first, p.last, p.inv_step, p.step, p.n_inner_edges, p.inner_last) +@inline _sp2d_val_launch_fields(p::GPUValueInfLinearCols) = + (p.first, p.last, p.inv_step, p.step, p.inner_last, p.n_inner_edges) +@inline _sp2d_val_launch_fields(p::GPUValueVectorCols) = (p.edges_dev,) + +""" +Tiled launch for arbitrary distance edges. The edges are uploaded once (or reused from the +workspace) and binary-searched on device, so non-uniform bins get the shared-histogram path instead +of the global-atomic fallback. +""" +function _sp2d_pair_launch_kernel!( + backend::KA.Backend, + partition_sums_dev, + partition_counts_dev, + x_dev, + u_dev, + dist_bins::AbstractVector{FT}, + val_plan::GPUValueDigitizePlan, + N_points::Int, + n_dist_edges::Int, + n_val_edges::Int, + n_dist::Int, + config::SP2DAccumulationStrategy, + geom; + workspace::Union{GPUSFWorkspace, Nothing} = nothing, +) where {FT} + n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) + kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) + _, _, gen_e = _workspace_dist_edge_bufs(workspace) + bins_dev = gen_e === nothing ? begin + b = KA.allocate(backend, FT, n_dist_edges) + copyto!(b, dist_bins) + b + end : gen_e + kernel!( + partition_sums_dev, partition_counts_dev, x_dev, u_dev, + N_points, n_dist_edges, n_dist, n_val_edges, + bins_dev, + _sp2d_val_launch_fields(val_plan)..., + n_tiles, n_tile_blocks, ws, + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; + ndrange = ndrange, + ) + return n_tile_blocks +end + +function _sp2d_pair_launch_kernel!( + backend::KA.Backend, + partition_sums_dev, + partition_counts_dev, + x_dev, + u_dev, + dist_bins::LinearBinEdges, + val_plan::GPUValueVectorCols, + N_points::Int, + n_dist_edges::Int, + n_val_edges::Int, + n_dist::Int, + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) kernel! = _sp2d_resolve_pair_kernel(workspace, backend, dist_bins, val_plan, config, ws) lbe, vp = dist_bins, val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) kernel!( partition_sums_dev, partition_counts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, vp.edges_dev, n_tiles, n_tile_blocks, ws, - _sp2d_strategy_kernel_tail_args(config)...; + _sp2d_strategy_kernel_tail_args(config, size(x_dev, 1), geom)...; ndrange = ndrange, ) return n_tile_blocks @@ -693,7 +807,8 @@ function _sp2d_pair_launch_kernel!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) throw(ArgumentError( @@ -713,19 +828,20 @@ function _launch_single_pass_2d_strategy!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) if config.needs_partition_merge return _launch_sp2d_direct_partitioned!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config; + dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config, geom; workspace = workspace, ) end return _launch_sp2d_onchip!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config; + dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config, geom; workspace = workspace, ) end @@ -743,12 +859,13 @@ function _launch_sp2d_onchip!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) _sp2d_pair_launch_kernel!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config; + dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config, geom; workspace = workspace, ) return nothing @@ -767,14 +884,15 @@ function _launch_sp2d_direct_partitioned!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) config.needs_partition_merge || throw(ArgumentError("_launch_sp2d_direct_partitioned! requires needs_partition_merge")) partition_sums, partition_counts, n_tb = _sp2d_partition_pair_bufs_and_launch!( backend, out_sums_dev, x_dev, u_dev, dist_bins, val_plan, - N_points, n_dist_edges, n_val_edges, n_dist, config; + N_points, n_dist_edges, n_val_edges, n_dist, config, geom; workspace = workspace, ) _launch_merge_sp2d_partitions!( @@ -796,7 +914,8 @@ function _sp2d_partition_pair_bufs_and_launch!( n_dist_edges::Int, n_val_edges::Int, n_dist::Int, - config::SP2DAccumulationStrategy; + config::SP2DAccumulationStrategy, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) config.needs_partition_merge || @@ -815,7 +934,7 @@ function _sp2d_partition_pair_bufs_and_launch!( end n_tb = _sp2d_pair_launch_kernel!( backend, partition_sums, partition_counts, x_dev, u_dev, - dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config; + dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config, geom; workspace = workspace, ) return partition_sums, partition_counts, n_tb @@ -833,7 +952,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -843,9 +963,9 @@ function _launch_single_pass_2d_tiled!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -862,7 +982,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -872,9 +993,9 @@ function _launch_single_pass_2d_tiled!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -891,7 +1012,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -901,10 +1023,10 @@ function _launch_single_pass_2d_tiled!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -921,7 +1043,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -931,10 +1054,10 @@ function _launch_single_pass_2d_tiled!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, vp.inner_last, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, vp.inner_last, vp.n_inner_edges, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -951,20 +1074,21 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_linear_val_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -981,20 +1105,21 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_linear_val_cols_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1011,21 +1136,22 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_inflinear_val_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, vp.n_inner_edges, vp.inner_last, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1042,21 +1168,22 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_inflinear_val_cols_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, vp.inner_last, + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, vp.inner_last, vp.n_inner_edges, - n_tiles, n_tile_blocks, ws; + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1073,20 +1200,21 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_log_val_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1103,20 +1231,21 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_vector_val_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, vp.edges_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1133,7 +1262,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -1143,9 +1273,9 @@ function _launch_single_pass_2d_tiled!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1162,7 +1292,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) @@ -1172,9 +1303,9 @@ function _launch_single_pass_2d_tiled!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1191,20 +1322,21 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) n_tiles, n_tile_blocks, ws, ndrange = _tiled_launch_params(N_points) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf6_single_pass_2d_kernel_tiled128_log_log_val_cols_u32!(backend, ws) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, N_points, n_dist_edges, n_dist, n_val_edges, - d_f, d_l, d_inv, d_off, d_st, - vp.first, vp.last, vp.inv_step, vp.offset, vp.step, - n_tiles, n_tile_blocks, ws; + d_f, d_l, d_inv, d_st, + vp.first, vp.last, vp.inv_step, vp.step, + n_tiles, n_tile_blocks, ws, geom; ndrange = ndrange, ) return nothing @@ -1221,7 +1353,8 @@ function _launch_single_pass_2d_tiled!( N_points::Int, n_dist_edges::Int, n_val_edges::Int, - n_dist::Int; + n_dist::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) throw(ArgumentError( @@ -1241,18 +1374,27 @@ function _launch_single_pass_2d_kernel!( N_points::Int, N_dims::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) lbe = dist_bins vp = val_plan value_edges_dev = workspace === nothing ? nothing : workspace.value_edges_sp2d_dev - value_edges_dev === nothing && throw(ArgumentError("naive single-pass 2D linear+linear requires vector value workspace")) + if value_edges_dev === nothing + # This kernel digitizes the value axis by binary search, so it needs the explicit edge + # vector. The linear plan carries `first`/`last`, so reconstruct it rather than demanding a + # workspace: this path is the only route when `n_dist > SF_GPU_MAX_BINS`, and requiring a + # workspace there made every large-bin call fail outright. + VT = typeof(vp.first) + value_edges_dev = KA.allocate(backend, VT, n_val_edges) + copyto!(value_edges_dev, collect(range(vp.first, vp.last; length = n_val_edges))) + end kernel! = _sf_single_pass_2d_kernel_linear!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, value_edges_dev, N_points, Val(N_dims), n_dist_edges, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1270,7 +1412,8 @@ function _launch_single_pass_2d_kernel!( N_points::Int, N_dims::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) lbe = dist_bins @@ -1278,7 +1421,7 @@ function _launch_single_pass_2d_kernel!( kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, val_plan.edges_dev, N_points, Val(N_dims), n_dist_edges, n_val_edges, - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val; + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, geom; ndrange = (N_points, N_points), ) return nothing @@ -1296,18 +1439,19 @@ function _launch_single_pass_2d_kernel!( N_points::Int, N_dims::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) lbe = dist_bins vp = val_plan - d_f, d_l, d_inv, d_off, d_st = _dist_log_linear_fields(lbe) + d_f, d_l, d_inv, d_st = _dist_log_linear_fields(lbe) kernel! = _sf_single_pass_2d_kernel_log!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, vp.edges_dev, N_points, Val(N_dims), n_dist_edges, n_val_edges, - d_f, d_l, d_inv, d_off, d_st; + d_f, d_l, d_inv, d_st, geom; ndrange = (N_points, N_points), ) return nothing @@ -1325,7 +1469,8 @@ function _launch_single_pass_2d_kernel!( N_points::Int, N_dims::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) where {FT} _, _, gen_e = _workspace_dist_edge_bufs(workspace) @@ -1337,7 +1482,7 @@ function _launch_single_pass_2d_kernel!( kernel! = _sf_single_pass_2d_kernel!(backend, workgroup_size) kernel!( out_sums_dev, out_cnts_dev, x_dev, u_dev, - bins_dev, val_plan.edges_dev, N_points, Val(N_dims), n_dist_edges, n_val_edges; + bins_dev, val_plan.edges_dev, N_points, Val(N_dims), n_dist_edges, n_val_edges, geom; ndrange = (N_points, N_points), ) return nothing @@ -1355,13 +1500,14 @@ function _launch_single_pass_2d_kernel!( N_points::Int, N_dims::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, ) if N_dims == 2 && _gpu_single_pass_2d_use_tiled(dist_bins, val_plan, n_dist_edges - 1) return _launch_single_pass_2d_tiled!( backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist_edges - 1; + dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist_edges - 1, geom; workspace = workspace, ) end @@ -1370,6 +1516,25 @@ function _launch_single_pass_2d_kernel!( )) end +""" +Offer a non-batch single-pass 2D launch to the batch dispatcher as `B=1`, reaching the CUDA N-body ++ dynamic-shared kernel; `false` means the hook declined and the caller continues unchanged. +Measured on A100 (N=20000): 1.24× Float32, 2.58× Float64. See `gpu/SPEED_OF_LIGHT.md`. +""" +@inline function _sp2d_try_fast_batch!( + backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_bins, val_plan, + N_points::Int, N_dims::Int, n_dist::Int, n_val::Int, geom, +) + return SFC.gpu_fast_launch_2d_batch!( + backend, + reshape(out_sums_dev, SF_GPU_SINGLE_PASS_N, n_dist, n_val, 1), + reshape(out_cnts_dev, SF_GPU_SINGLE_PASS_N, n_dist, n_val, 1), + x_dev, reshape(u_dev, N_dims, N_points, 1), + nothing, _sf_batch_dist_digitizer(backend, dist_bins), val_plan, + N_points, n_dist, n_val, 1, N_dims, SF_GPU_SINGLE_PASS_N, true, geom, + ) +end + function _launch_single_pass_2d!( backend::KA.Backend, workgroup_size::Int, @@ -1382,7 +1547,8 @@ function _launch_single_pass_2d!( N_points::Int, N_dims::Int, n_dist_edges::Int, - n_val_edges::Int; + n_val_edges::Int, + geom; workspace::Union{GPUSFWorkspace, Nothing} = nothing, force_global_atomic::Bool = false, ) @@ -1390,32 +1556,46 @@ function _launch_single_pass_2d!( if force_global_atomic return _launch_single_pass_2d_kernel!( backend, workgroup_size, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, N_dims, n_dist_edges, n_val_edges; + dist_bins, val_plan, N_points, N_dims, n_dist_edges, n_val_edges, geom; workspace = workspace, ) end - if N_dims == 2 && !force_global_atomic && _gpu_single_pass_2d_use_tiled(dist_bins, val_plan, n_dist) + _sp2d_try_fast_batch!(backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, dist_bins, val_plan, + N_points, N_dims, n_dist, n_val_edges - 1, geom) && return nothing + # D ∈ {2,3}: the tiled kernel stages D components and builds D-vectors from `Val{D}`, and its + # invariants use |du_T|² = |du|² - du_L², which needs no transverse basis and so no gauge choice. + if (N_dims == 2 || N_dims == 3) && !force_global_atomic && + _gpu_single_pass_2d_use_tiled(dist_bins, val_plan, n_dist) config = workspace === nothing ? - _sp2d_accumulation_strategy(n_dist, n_val_edges - 1, eltype(out_sums_dev)) : + _sp2d_accumulation_strategy(n_dist, n_val_edges - 1, eltype(out_sums_dev), + SFC.gpu_device_caps(backend)) : workspace.sp2d_accumulation_strategy - return _launch_single_pass_2d_strategy!( - backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config; - workspace = workspace, - ) + # `:shared` and `:typeplane` keep the histogram on chip and always win. `:direct` does not — + # it abandons the on-chip histogram for block-private global partitions plus a merge pass, so + # its cost grows with cells × tile-blocks, while plain global atomics get *cheaper* as more + # cells spread the contention. Past `SP2D_GLOBAL_ATOMIC_HIST_BYTES` the naive kernel wins, so + # send `:direct` there; below it `:direct` is still ahead and stays. + if !_sp2d_prefers_global_atomics(n_dist, n_val_edges - 1, eltype(out_sums_dev), + SFC.gpu_device_caps(backend)) + return _launch_single_pass_2d_strategy!( + backend, out_sums_dev, out_cnts_dev, x_dev, u_dev, + dist_bins, val_plan, N_points, n_dist_edges, n_val_edges, n_dist, config, geom; + workspace = workspace, + ) + end end return _launch_single_pass_2d_kernel!( backend, workgroup_size, out_sums_dev, out_cnts_dev, x_dev, u_dev, - dist_bins, val_plan, N_points, N_dims, n_dist_edges, n_val_edges; + dist_bins, val_plan, N_points, N_dims, n_dist_edges, n_val_edges, geom; workspace = workspace, ) end # Production batch launch drivers — fixed-x and varying-x. -# Included from StructureFunctionsGPUExt.jl after BatchTiledKernels.jl. +# Included from StructureFunctionsKernelAbstractionsExt.jl after BatchTiledKernels.jl. # # Fixed-x launch invariant (do not regress): # - `ndrange = n_tile_blocks * workgroup_size` only — never multiply by `cld(B, strip_w)`. -# - Host strip loop over `BATCH_USMEM_STRIP_W` (16) via `_batch_fixed_x_usmem_priv!`. +# - Host strip loop over `_batch_usmem_strip_w(FT)` via `_batch_fixed_x_usmem_priv!`. # - `KA.CPU`: serial merge; other backends: grouped merge. Same kernel on both. # - Varying-x routes use `(tile, auxiliary)` grid scaling (`ndrange * B`), not host strips. @@ -1424,13 +1604,13 @@ bin type. Linear and log share the same 5-parameter FMA digitize — log runs it log space (`log(dist)` at bin time; see `_batch_dist_bin`), so both bin types take the same fast kernels via `Val{LOG}` specialization.""" @inline _batch_fma_dist_params(lbe::LinearBinEdges) = ( - lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, + lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, length(lbe.edges), Val(false), ) @inline function _batch_fma_dist_params(lbe::LogBinEdges) ll = lbe.log_linear return ( - ll.first_edge, ll.last_edge, ll.inv_step, ll.offset, ll.step_val, + ll.first_edge, ll.last_edge, ll.inv_step, ll.step_val, length(lbe.log_edges), Val(true), ) end @@ -1446,10 +1626,11 @@ function _launch_batch_fixed_x_sf!( sf_type, N::Int, B::Int, - lbe::_BatchFMADistBins{FT}; + lbe::_BatchFMADistBins{FT}, + geom; workspace::Union{GPUBatchWorkspace{FT}, Nothing} = nothing, ) where {FT} - fe, le, is_, off, sv, n_bins, logv = _batch_fma_dist_params(lbe) + fe, le, is_, sv, n_bins, logv = _batch_fma_dist_params(lbe) NB = n_bins - 1 NB > SF_GPU_MAX_BINS && error("batch tiled128 supports at most $SF_GPU_MAX_BINS bins (got NB=$NB)") @@ -1458,17 +1639,18 @@ function _launch_batch_fixed_x_sf!( kernel! = _batch_fixed_x_sf_kernel(backend, ws) merge_sums! = _batch_merge_usmem_sums!(backend, ws) merge_cnts! = _batch_merge_usmem_cnts!(backend, ws) - partial_sums = KA.zeros(backend, FT, NB, BATCH_USMEM_STRIP_W, n_priv) + strip_w = _batch_usmem_strip_w(FT) + partial_sums = KA.zeros(backend, FT, NB, strip_w, n_priv) partial_cnts = KA.zeros(backend, UInt32, NB, n_priv) b_base = 1 while b_base <= B - bw = min(BATCH_USMEM_STRIP_W, B - b_base + 1) + bw = min(strip_w, B - b_base + 1) fill!(partial_sums, zero(FT)) fill!(partial_cnts, zero(UInt32)) kernel!( partial_sums, partial_cnts, x_dev, u_dev, sf_type, - N, n_bins, NB, b_base, bw, fe, le, is_, off, sv, - n_tiles, n_tile_blocks, ws, logv; + N, n_bins, NB, b_base, bw, fe, le, is_, sv, + n_tiles, n_tile_blocks, ws, geom, logv; ndrange = ndrange, ) merge_sums!( @@ -1500,10 +1682,11 @@ function _launch_batch_fixed_x_sf!( sf_type, N::Int, B::Int, - lbe::_BatchFMADistBins{FT}; + lbe::_BatchFMADistBins{FT}, + geom; workspace::Union{GPUBatchWorkspace{FT}, Nothing} = nothing, ) where {FT} - fe, le, is_, off, sv, n_bins, logv = _batch_fma_dist_params(lbe) + fe, le, is_, sv, n_bins, logv = _batch_fma_dist_params(lbe) NB = n_bins - 1 NB > SF_GPU_MAX_BINS && error("batch tiled128 supports at most $SF_GPU_MAX_BINS bins (got NB=$NB)") @@ -1512,17 +1695,18 @@ function _launch_batch_fixed_x_sf!( kernel! = _batch_fixed_x_sf_kernel(backend, ws) merge_sums! = _batch_merge_usmem_sums_grouped!(backend, ws) merge_cnts! = _batch_merge_usmem_cnts_grouped!(backend, ws) - partial_sums = KA.zeros(backend, FT, NB, BATCH_USMEM_STRIP_W, n_priv) + strip_w = _batch_usmem_strip_w(FT) + partial_sums = KA.zeros(backend, FT, NB, strip_w, n_priv) partial_cnts = KA.zeros(backend, UInt32, NB, n_priv) b_base = 1 while b_base <= B - bw = min(BATCH_USMEM_STRIP_W, B - b_base + 1) + bw = min(strip_w, B - b_base + 1) fill!(partial_sums, zero(FT)) fill!(partial_cnts, zero(UInt32)) kernel!( partial_sums, partial_cnts, x_dev, u_dev, sf_type, - N, n_bins, NB, b_base, bw, fe, le, is_, off, sv, - n_tiles, n_tile_blocks, ws, logv; + N, n_bins, NB, b_base, bw, fe, le, is_, sv, + n_tiles, n_tile_blocks, ws, geom, logv; ndrange = ndrange, ) merge_sums!( @@ -1544,384 +1728,3 @@ function _launch_batch_fixed_x_sf!( KA.synchronize(backend) return nothing end - -function _launch_batch_fixed_x_sp1d!( - backend::KA.CPU, - sums_dev, - counts_dev, - x_dev, - u_dev, - N::Int, - B::Int, - lbe::LinearBinEdges{FT}; -) where {FT} - n_bins = length(lbe.edges) - NB = n_bins - 1 - NB > SF_GPU_MAX_BINS && - error("batch SP1D tiled128 supports at most $SF_GPU_MAX_BINS bins (got NB=$NB)") - n_tiles, n_tile_blocks, ws, ndrange = _batch_tiled_launch_params(N) - fe, le, is_, off, sv = lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val - kernel! = _batch_fixed_x_sp1d_usmem_priv!(backend, ws) - merge_sums! = _batch_merge_sp1d_sums!(backend, ws) - merge_cnts! = _batch_merge_sp1d_cnts!(backend, ws) - partial_sums = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, NB, BATCH_SP1D_USMEM_STRIP_W, n_tile_blocks) - partial_cnts = KA.zeros(backend, UInt32, SF_GPU_SINGLE_PASS_N, NB, n_tile_blocks) - b_base = 1 - while b_base <= B - bw = min(BATCH_SP1D_USMEM_STRIP_W, B - b_base + 1) - fill!(partial_sums, zero(FT)) - fill!(partial_cnts, zero(UInt32)) - kernel!( - partial_sums, partial_cnts, x_dev, u_dev, - N, n_bins, NB, b_base, bw, fe, le, is_, off, sv, - n_tiles, n_tile_blocks, ws; - ndrange = ndrange, - ) - merge_sums!( - @view(sums_dev[:, :, b_base:b_base + bw - 1]), partial_sums, - NB, bw, n_tile_blocks, SF_GPU_SINGLE_PASS_N * NB * bw; - ndrange = SF_GPU_SINGLE_PASS_N * NB * bw, - ) - if b_base == 1 - merge_cnts!( - @view(counts_dev[:, :, 1]), partial_cnts, NB, n_tile_blocks, SF_GPU_SINGLE_PASS_N * NB; - ndrange = SF_GPU_SINGLE_PASS_N * NB, - ) - end - b_base += bw - end - if B > 1 - @views counts_dev[:, :, 2:end] .= counts_dev[:, :, 1:1] - end - KA.synchronize(backend) - return nothing -end - -function _launch_batch_fixed_x_sp1d!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - N::Int, - B::Int, - lbe::LinearBinEdges{FT}; -) where {FT} - n_bins = length(lbe.edges) - NB = n_bins - 1 - NB > SF_GPU_MAX_BINS && - error("batch SP1D tiled128 supports at most $SF_GPU_MAX_BINS bins (got NB=$NB)") - n_tiles, n_tile_blocks, ws, ndrange = _batch_tiled_launch_params(N) - fe, le, is_, off, sv = lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val - kernel! = _batch_fixed_x_sp1d_usmem_priv!(backend, ws) - merge_sums! = _batch_merge_sp1d_sums_grouped!(backend, ws) - merge_cnts! = _batch_merge_sp1d_cnts_grouped!(backend, ws) - partial_sums = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, NB, BATCH_SP1D_USMEM_STRIP_W, n_tile_blocks) - partial_cnts = KA.zeros(backend, UInt32, SF_GPU_SINGLE_PASS_N, NB, n_tile_blocks) - b_base = 1 - while b_base <= B - bw = min(BATCH_SP1D_USMEM_STRIP_W, B - b_base + 1) - fill!(partial_sums, zero(FT)) - fill!(partial_cnts, zero(UInt32)) - kernel!( - partial_sums, partial_cnts, x_dev, u_dev, - N, n_bins, NB, b_base, bw, fe, le, is_, off, sv, - n_tiles, n_tile_blocks, ws; - ndrange = ndrange, - ) - merge_sums!( - @view(sums_dev[:, :, b_base:b_base + bw - 1]), partial_sums, - NB, bw, n_tile_blocks, ws; - ndrange = SF_GPU_SINGLE_PASS_N * NB * bw * ws, - ) - if b_base == 1 - merge_cnts!( - @view(counts_dev[:, :, 1]), partial_cnts, NB, n_tile_blocks, ws; - ndrange = SF_GPU_SINGLE_PASS_N * NB * ws, - ) - end - b_base += bw - end - if B > 1 - @views counts_dev[:, :, 2:end] .= counts_dev[:, :, 1:1] - end - KA.synchronize(backend) - return nothing -end - -function _launch_batch_varying_x_sf!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - sf_type, - N::Int, - B::Int, - lbe::LinearBinEdges{FT}, -) where {FT} - n_bins = length(lbe.edges) - NB = n_bins - 1 - n_tiles, n_tile_blocks, ws, ndrange = _batch_tiled_launch_params(N) - fe, le, is_, off, sv = lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val - kernel! = _batch_varying_x_sf!(backend, ws) - kernel!( - sums_dev, counts_dev, x_dev, u_dev, sf_type, - N, n_bins, NB, fe, le, is_, off, sv, - n_tiles, n_tile_blocks, ws, B; - ndrange = ndrange * B, - ) - KA.synchronize(backend) - return nothing -end - -function _launch_batch_varying_x_sp1d!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - N::Int, - B::Int, - lbe::LinearBinEdges{FT}, -) where {FT} - n_bins = length(lbe.edges) - NB = n_bins - 1 - n_tiles, n_tile_blocks, ws, ndrange = _batch_tiled_launch_params(N) - fe, le, is_, off, sv = lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val - kernel! = _batch_varying_x_sp1d!(backend, ws) - kernel!( - sums_dev, counts_dev, x_dev, u_dev, - N, n_bins, NB, fe, le, is_, off, sv, - n_tiles, n_tile_blocks, ws, B; - ndrange = ndrange * B, - ) - KA.synchronize(backend) - return nothing -end - -function _launch_batch_fixed_x_sp2d!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - N::Int, - B::Int, - dist_lbe::LinearBinEdges{FT}, - val_plan::GPUValueDigitizePlan, - n_dist::Int, - n_val::Int, -) where {FT} - n_bins = length(dist_lbe.edges) - n_tiles, n_tile_blocks, ws, ndrange = _batch_tiled_launch_params(N) - fe, le, is_, off, sv = dist_lbe.first_edge, dist_lbe.last_edge, dist_lbe.inv_step, - dist_lbe.offset, dist_lbe.step_val - kernel! = _batch_varying_x_sp2d_fixed_x!(backend, ws) - partial = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, n_dist, n_val, BATCH_USMEM_STRIP_W, n_tile_blocks) - partial_cnt = KA.zeros(backend, UInt32, SF_GPU_SINGLE_PASS_N, n_dist, n_val, BATCH_USMEM_STRIP_W, n_tile_blocks) - b_base = 1 - while b_base <= B - bw = min(BATCH_USMEM_STRIP_W, B - b_base + 1) - fill!(partial, zero(FT)) - fill!(partial_cnt, zero(UInt32)) - kernel!( - partial, partial_cnt, x_dev, u_dev, - N, n_bins, n_dist, n_val, b_base, bw, - fe, le, is_, off, sv, val_plan, - n_tiles, n_tile_blocks, ws; - ndrange = ndrange, - ) - _merge_batch_sp2d_partial!( - backend, sums_dev, counts_dev, partial, partial_cnt, - n_dist, n_val, b_base, bw, n_tile_blocks, ws, - ) - b_base += bw - end - KA.synchronize(backend) - return nothing -end - -@inline function _merge_batch_sp2d_partial!( - backend::KA.CPU, - sums_dev, - counts_dev, - partial, - partial_cnt, - n_dist::Int, - n_val::Int, - b_base::Int, - bw::Int, - n_tile_blocks::Int, - ws::Int, -) - merge_s! = _batch_merge_sp2d_sums!(backend, ws) - merge_c! = _batch_merge_sp2d_cnts!(backend, ws) - n_out = SF_GPU_SINGLE_PASS_N * n_dist * n_val * bw - merge_s!( - @view(sums_dev[:, :, :, b_base:(b_base + bw - 1)]), partial, - n_dist, n_val, bw, n_tile_blocks, n_out; - ndrange = n_out, - ) - merge_c!( - @view(counts_dev[:, :, :, b_base:(b_base + bw - 1)]), partial_cnt, - n_dist, n_val, bw, n_tile_blocks, n_out; - ndrange = n_out, - ) - return nothing -end - -@inline function _merge_batch_sp2d_partial!( - backend::KA.Backend, - sums_dev, - counts_dev, - partial, - partial_cnt, - n_dist::Int, - n_val::Int, - b_base::Int, - bw::Int, - n_tile_blocks::Int, - ws::Int, -) - merge_s! = _batch_merge_sp2d_sums_grouped!(backend, ws) - merge_c! = _batch_merge_sp2d_cnts_grouped!(backend, ws) - n_out = SF_GPU_SINGLE_PASS_N * n_dist * n_val * bw - merge_s!( - @view(sums_dev[:, :, :, b_base:(b_base + bw - 1)]), partial, - n_dist, n_val, bw, n_tile_blocks, ws; - ndrange = n_out * ws, - ) - merge_c!( - @view(counts_dev[:, :, :, b_base:(b_base + bw - 1)]), partial_cnt, - n_dist, n_val, bw, n_tile_blocks, ws; - ndrange = n_out * ws, - ) - return nothing -end - -function _launch_batch_varying_x_sp2d!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - N::Int, - B::Int, - dist_lbe::LinearBinEdges{FT}, - val_plan::GPUValueDigitizePlan, - n_dist::Int, - n_val::Int, -) where {FT} - n_bins = length(dist_lbe.edges) - n_tiles, n_tile_blocks, ws, ndrange = _batch_tiled_launch_params(N) - fe, le, is_, off, sv = dist_lbe.first_edge, dist_lbe.last_edge, dist_lbe.inv_step, - dist_lbe.offset, dist_lbe.step_val - kernel! = _batch_varying_x_sp2d!(backend, ws) - kernel!( - sums_dev, counts_dev, x_dev, u_dev, - N, n_bins, n_dist, n_val, fe, le, is_, off, sv, val_plan, - n_tiles, n_tile_blocks, ws, B; - ndrange = ndrange * B, - ) - KA.synchronize(backend) - return nothing -end - -function _launch_batch_varying_x_joint2d!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - sf_type, - N::Int, - B::Int, - distance_bins, - value_bins, - n_dist::Int, - n_val::Int; - workspace::Union{GPUSFWorkspace, Nothing} = nothing, - workgroup_size::Int = 64, -) - FT = eltype(sums_dev) - dist_bins = _gpu_normalize_bins(distance_bins) - n_dist_edges = _gpu_n_edges(distance_bins) - n_val_edges = _gpu_n_edges(value_bins) - val_plan = _joint2d_build_val_plan(backend, value_bins) - - value_host = _gpu_host_edge_vector(value_bins) - value_edges_dev = KA.allocate(backend, FT, n_val_edges) - copyto!(value_edges_dev, value_host) - - out_sums_dev = KA.allocate(backend, FT, n_dist, n_val) - out_cnts_dev = KA.allocate(backend, UInt32, n_dist, n_val) - - for b in 1:B - fill!(out_sums_dev, zero(FT)) - fill!(out_cnts_dev, zero(UInt32)) - _launch_joint_2d_kernel!( - backend, workgroup_size, - out_sums_dev, out_cnts_dev, - @view(x_dev[:, :, b]), @view(u_dev[:, :, b]), - value_edges_dev, - sf_type, dist_bins, N, n_dist_edges, n_val_edges; - val_plan = val_plan, - ) - copyto!(@view(sums_dev[:, :, b]), out_sums_dev) - copyto!(@view(counts_dev[:, :, b]), out_cnts_dev) - end - KA.synchronize(backend) - return nothing -end - -function _launch_batch_fixed_x_joint2d!( - backend::KA.Backend, - sums_dev, - counts_dev, - x_dev, - u_dev, - sf_type, - N::Int, - B::Int, - distance_bins, - value_bins, - n_dist::Int, - n_val::Int; - workspace::Union{GPUSFWorkspace, Nothing} = nothing, - workgroup_size::Int = 64, -) - FT = eltype(sums_dev) - dist_bins = _gpu_normalize_bins(distance_bins) - n_dist_edges = _gpu_n_edges(distance_bins) - n_val_edges = _gpu_n_edges(value_bins) - val_plan = _joint2d_build_val_plan(backend, value_bins) - - value_host = _gpu_host_edge_vector(value_bins) - value_edges_dev = KA.allocate(backend, FT, n_val_edges) - copyto!(value_edges_dev, value_host) - - out_sums_dev = KA.allocate(backend, FT, n_dist, n_val) - out_cnts_dev = KA.allocate(backend, UInt32, n_dist, n_val) - - # u_dev layout from _stage_batch_device: (B, N, N_dims) - # pre-transpose to (N_dims, N, B) once so each slice @view(u_t[:, :, b]) is (N_dims, N) - u_t = permutedims(u_dev, (3, 2, 1)) - - for b in 1:B - fill!(out_sums_dev, zero(FT)) - fill!(out_cnts_dev, zero(UInt32)) - _launch_joint_2d_kernel!( - backend, workgroup_size, - out_sums_dev, out_cnts_dev, - x_dev, @view(u_t[:, :, b]), - value_edges_dev, - sf_type, dist_bins, N, n_dist_edges, n_val_edges; - val_plan = val_plan, - ) - copyto!(@view(sums_dev[:, :, b]), out_sums_dev) - copyto!(@view(counts_dev[:, :, b]), out_cnts_dev) - end - KA.synchronize(backend) - return nothing -end diff --git a/ext/gpu/sf_core.jl b/ext/gpu/sf_core.jl index fccd8f5..cfbe76e 100644 --- a/ext/gpu/sf_core.jl +++ b/ext/gpu/sf_core.jl @@ -35,13 +35,12 @@ struct SFLinearDigitizer{T} first_edge::T last_edge::T inv_step::T - offset::T step_val::T n_edges::Int end @inline (d::SFLinearDigitizer{T})(r::T) where {T} = - _gpu_digitize_linear(r, d.first_edge, d.last_edge, d.inv_step, d.offset, d.step_val, d.n_edges) + _gpu_digitize_linear(r, d.first_edge, d.last_edge, d.inv_step, d.step_val, d.n_edges) """Log-grid distance digitizer: `log(r)` then a linear digitize on the log grid (matches `LogBinEdges`). Non-positive `r` falls below the first edge (→ 0).""" @@ -49,14 +48,13 @@ struct SFLogDigitizer{T} first_edge::T last_edge::T inv_step::T - offset::T step_val::T n_edges::Int end @inline (d::SFLogDigitizer{T})(r::T) where {T} = r <= zero(T) ? 0 : - _gpu_digitize_linear(log(r), d.first_edge, d.last_edge, d.inv_step, d.offset, d.step_val, d.n_edges) + _gpu_digitize_linear(log(r), d.first_edge, d.last_edge, d.inv_step, d.step_val, d.n_edges) """General (arbitrary edges) distance digitizer: binary search over a device edge vector. `edges` is adapted to the backend alongside the kernel arguments.""" @@ -65,6 +63,11 @@ struct SFGeneralDigitizer{E} n_edges::Int end +# Without this the struct reaches the kernel holding a host-side `CuArray` and the launch fails +# with `KernelError: passing non-bitstype argument`. +KA.Adapt.adapt_structure(to, d::SFGeneralDigitizer) = + SFGeneralDigitizer(KA.Adapt.adapt(to, d.edges), d.n_edges) + @inline (d::SFGeneralDigitizer)(r) = _gpu_digitize_general(r, d.edges, d.n_edges) # Number of bins (edges - 1) for a digitizer. @@ -74,11 +77,11 @@ end # Host-side constructors from the bin-edge wrapper types. @inline _sf_digitizer(lbe::LinearBinEdges) = - SFLinearDigitizer(lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.offset, lbe.step_val, length(lbe.edges)) + SFLinearDigitizer(lbe.first_edge, lbe.last_edge, lbe.inv_step, lbe.step_val, length(lbe.edges)) @inline function _sf_digitizer(lbe::LogBinEdges) ll = lbe.log_linear - return SFLogDigitizer(ll.first_edge, ll.last_edge, ll.inv_step, ll.offset, ll.step_val, length(lbe.log_edges)) + return SFLogDigitizer(ll.first_edge, ll.last_edge, ll.inv_step, ll.step_val, length(lbe.log_edges)) end # General edges: caller passes a device array of edges (already on backend). @@ -122,6 +125,24 @@ end @inline _sf_moments(::Val{6}, sf_type, dU, rhat) = _sf_moments6(dU, rhat) @inline _sf_moments(::Val{1}, sf_type, dU, rhat) = (sf_type(dU, rhat),) +""" +Moments needing a per-pair atomic. `T2 = S2 - L2` and `L1T2 = S3 - L3` hold for every pair, and a +histogram bin is a sum, so both are recovered exactly at flush by [`_sf_flush_moment`](@ref) +rather than costing an atomic on each pair. +""" +@inline _sf_accum_moments(::Val{6}) = (1, 2, 4, 5) +@inline _sf_accum_moments(::Val{1}) = (1,) + +"""Value of moment `m` in bin `bin`, differencing the two moments that are never accumulated.""" +@inline function _sf_flush_moment(::Val{6}, ssum, NB::Int, m::Int, bin::Int) + @inbounds begin + m == 3 && return ssum[bin] - ssum[NB + bin] + m == 6 && return ssum[3 * NB + bin] - ssum[4 * NB + bin] + return ssum[(m - 1) * NB + bin] + end +end +@inline _sf_flush_moment(::Val{1}, ssum, ::Int, ::Int, bin::Int) = @inbounds ssum[bin] + # ----------------------------------------------------------------------------- # Shared-histogram layout (lane axis = R replicas or W batch strip) # diff --git a/ext/gpu/sf_tiled.jl b/ext/gpu/sf_tiled.jl index 1d73140..036d413 100644 --- a/ext/gpu/sf_tiled.jl +++ b/ext/gpu/sf_tiled.jl @@ -24,6 +24,7 @@ KA.@kernel unsafe_indices = true function sf_tiled_1d_varying!( ::Val{D}, ::Val{NMOM}, ::Val{R}, + geom, ) where {D, NMOM, R} shared_xi = @localmem eltype(x) (D * SF_GPU_TILE,) shared_xj = @localmem eltype(x) (D * SF_GPU_TILE,) @@ -120,12 +121,10 @@ KA.@kernel unsafe_indices = true function sf_tiled_1d_varying!( Ui = _sf_load_pt(Val(D), shared_ui, ia) Uj = _sf_load_pt(Val(D), shared_ui, jb) end - dX = Xj - Xi - dist = sqrt(_sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = digitizer(dist) - if 1 <= bin <= NB - rhat = dX / dist - dU = Uj - Ui + if ok && 1 <= bin <= NB + dU, rhat = SFH.pair_increments(geom, frame, dist, Xi, Xj, Ui, Uj) moments = _sf_moments(Val(NMOM), sf_type, dU, rhat) # accumulate into replica `lane` (inline localmem atomics) abase = (bin - 1) * R + lane @@ -181,6 +180,21 @@ end # Launch wrappers # ----------------------------------------------------------------------------- +""" + _sf_tiled_1d_check_nb(NB) + +Assert `NB` fits the 1D tiled kernels' shared histogram. Both `sf_tiled_1d_varying!` and +`sf_tiled_1d_fixed!` size `@localmem` from the compile-time `SF_GPU_MAX_BINS` but index it by the +runtime `NB` under `@inbounds`, so `NB > SF_GPU_MAX_BINS` would write out of bounds in shared memory +and silently corrupt the histogram. Must be called by every launcher of those kernels. +""" +@inline function _sf_tiled_1d_check_nb(NB::Int) + NB > SF_GPU_MAX_BINS && error( + "GPUExt: 1D tiled kernels support at most $SF_GPU_MAX_BINS distance bins (got NB=$NB)", + ) + return nothing +end + """Replication factor R for the 1D varying-x shared histogram, from the A100 R/W sweep (gpu/benchmark_results/tune_*.md). Regime-dependent: - Individual SF (NMOM=1): tiny histogram, extreme per-bin contention → R=2 helps @@ -193,9 +207,10 @@ sweep (gpu/benchmark_results/tune_*.md). Regime-dependent: `x_dev`, `u_dev` are (D, N, B); `out_dev`, `cnt_dev` are (NMOM, NB, B).""" function _launch_sf_tiled_1d_varying!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, - N::Int, NB::Int, B::Int, ::Val{D}, ::Val{NMOM}; + N::Int, NB::Int, B::Int, ::Val{D}, ::Val{NMOM}, geom; R::Int = _sf_tiled_1d_replication(eltype(out_dev), D, NMOM), ) where {D, NMOM} + _sf_tiled_1d_check_nb(NB) n_tiles = cld(N, SF_GPU_TILE) n_tile_blocks = n_tiles * (n_tiles + 1) ÷ 2 ws = SF_GPU_TILED_WS @@ -203,19 +218,19 @@ function _launch_sf_tiled_1d_varying!( kernel! = sf_tiled_1d_varying!(backend, ws) if R == 16 kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, N, NB, - n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(16); ndrange = ndrange) + n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(16), geom; ndrange = ndrange) elseif R == 8 kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, N, NB, - n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(8); ndrange = ndrange) + n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(8), geom; ndrange = ndrange) elseif R == 4 kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, N, NB, - n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(4); ndrange = ndrange) + n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(4), geom; ndrange = ndrange) elseif R == 2 kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, N, NB, - n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(2); ndrange = ndrange) + n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(2), geom; ndrange = ndrange) else kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, N, NB, - n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(1); ndrange = ndrange) + n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(1), geom; ndrange = ndrange) end return nothing end @@ -250,6 +265,7 @@ KA.@kernel unsafe_indices = true function sf_tiled_1d_fixed!( ::Val{D}, ::Val{NMOM}, ::Val{W}, + geom, ) where {D, NMOM, W} shared_xi = @localmem eltype(x) (D * SF_GPU_TILE,) shared_xj = @localmem eltype(x) (D * SF_GPU_TILE,) @@ -345,11 +361,11 @@ KA.@kernel unsafe_indices = true function sf_tiled_1d_fixed!( Xi = _sf_load_pt(Val(D), shared_xi, ia) Xj = _sf_load_pt(Val(D), shared_xi, jb) end - dX = Xj - Xi - dist = sqrt(_sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = digitizer(dist) - if 1 <= bin <= NB - rhat = dX / dist + if ok && 1 <= bin <= NB + # Loop-invariant across the strip: one frame serves all bw fields. + rhat = SFH.pair_direction(geom, frame, dist) @inbounds for w in 1:bw Ui = off_diag ? _sf_load_field(Val(D), shared_ui, w, ia) : @@ -357,7 +373,7 @@ KA.@kernel unsafe_indices = true function sf_tiled_1d_fixed!( Uj = off_diag ? _sf_load_field(Val(D), shared_uj, w, jb) : _sf_load_field(Val(D), shared_ui, w, jb) - dU = Uj - Ui + dU = SFH.pair_delta(geom, frame, Xi, Xj, Ui, Uj) moments = _sf_moments(Val(NMOM), sf_type, dU, rhat) # sums: lane = field w (scatter, not summed) base = (bin - 1) * W + w @@ -426,9 +442,10 @@ end out_dev/cnt_dev=(NMOM,NB,B). Single synchronize after all strips.""" function _launch_sf_tiled_1d_fixed!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, - N::Int, NB::Int, B::Int, ::Val{D}, ::Val{NMOM}; + N::Int, NB::Int, B::Int, ::Val{D}, ::Val{NMOM}, geom; W::Int = _sf_tiled_1d_fixed_strip(eltype(out_dev), D, NMOM), ) where {D, NMOM} + _sf_tiled_1d_check_nb(NB) n_tiles = cld(N, SF_GPU_TILE) n_tile_blocks = n_tiles * (n_tiles + 1) ÷ 2 ws = SF_GPU_TILED_WS @@ -439,7 +456,7 @@ function _launch_sf_tiled_1d_fixed!( while b_base <= B bw = min(Wv, B - b_base + 1) kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, digitizer, N, NB, - b_base, bw, n_tiles, n_tile_blocks, ws, Val(D), Val(NMOM), Val(Wv); + b_base, bw, n_tiles, n_tile_blocks, ws, Val(D), Val(NMOM), Val(Wv), geom; ndrange = ndrange) b_base += bw end @@ -475,6 +492,7 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_varying!( B::Int, ::Val{D}, ::Val{NMOM}, + geom, ) where {D, NMOM} shared_xi = @localmem eltype(x) (D * SF_GPU_TILE,) shared_xj = @localmem eltype(x) (D * SF_GPU_TILE,) @@ -548,12 +566,10 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_varying!( Ui = _sf_load_pt(Val(D), shared_ui, ia) Uj = _sf_load_pt(Val(D), shared_ui, jb) end - dX = Xj - Xi - dist = sqrt(_sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = dist_digitizer(dist) - if 1 <= dbin <= n_dist - rhat = dX / dist - dU = Uj - Ui + if ok && 1 <= dbin <= n_dist + dU, rhat = SFH.pair_increments(geom, frame, dist, Xi, Xj, Ui, Uj) moments = _sf_moments(Val(NMOM), sf_type, dU, rhat) @inbounds for m in 1:NMOM vbin = _gpu_digitize_value_plan(moments[m], val_plan, m, n_val + 1) @@ -573,14 +589,14 @@ end x_dev,u_dev=(D,N,B); out_dev,cnt_dev=(NMOM,n_dist,n_val,B).""" function _launch_sf_tiled_2d_varying!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, - N::Int, n_dist::Int, n_val::Int, B::Int, ::Val{D}, ::Val{NMOM}, + N::Int, n_dist::Int, n_val::Int, B::Int, ::Val{D}, ::Val{NMOM}, geom, ) where {D, NMOM} n_tiles = cld(N, SF_GPU_TILE) n_tile_blocks = n_tiles * (n_tiles + 1) ÷ 2 ws = SF_GPU_TILED_WS kernel! = sf_tiled_2d_varying!(backend, ws) kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, - N, n_dist, n_val, n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM); + N, n_dist, n_val, n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), geom; ndrange = n_tile_blocks * ws * B) return nothing end @@ -612,6 +628,7 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_shared!( ::Val{NMOM}, ::Val{NCELLS}, ::Val{FIXED_X}, + geom, ) where {D, NMOM, NCELLS, FIXED_X} shared_xi = @localmem eltype(x) (D * SF_GPU_TILE,) shared_xj = @localmem eltype(x) (D * SF_GPU_TILE,) @@ -702,12 +719,10 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_shared!( Ui = _sf_load_pt(Val(D), shared_ui, ia) Uj = _sf_load_pt(Val(D), shared_ui, jb) end - dX = Xj - Xi - dist = sqrt(_sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = dist_digitizer(dist) - if 1 <= dbin <= n_dist - rhat = dX / dist - dU = Uj - Ui + if ok && 1 <= dbin <= n_dist + dU, rhat = SFH.pair_increments(geom, frame, dist, Xi, Xj, Ui, Uj) moments = _sf_moments(Val(NMOM), sf_type, dU, rhat) @inbounds for m in 1:NMOM vbin = _gpu_digitize_value_plan(moments[m], val_plan, m, n_val + 1) @@ -760,7 +775,7 @@ end `x_dev` is (D,N,B) for varying-x or (D,N,1) for fixed-x; `u_dev` is (D,N,B).""" function _launch_sf_tiled_2d_shared!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, - N::Int, n_dist::Int, n_val::Int, B::Int, ::Val{D}, ::Val{NMOM}, fixed_x::Bool, + N::Int, n_dist::Int, n_val::Int, B::Int, ::Val{D}, ::Val{NMOM}, fixed_x::Bool, geom, ) where {D, NMOM} n_tiles = cld(N, SF_GPU_TILE) n_tile_blocks = n_tiles * (n_tiles + 1) ÷ 2 @@ -769,11 +784,11 @@ function _launch_sf_tiled_2d_shared!( kernel! = sf_tiled_2d_shared!(backend, ws) if fixed_x kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, - N, n_dist, n_val, n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(n_dist * n_val), Val(true); + N, n_dist, n_val, n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(n_dist * n_val), Val(true), geom; ndrange = ndrange) else kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, - N, n_dist, n_val, n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(n_dist * n_val), Val(false); + N, n_dist, n_val, n_tiles, n_tile_blocks, ws, B, Val(D), Val(NMOM), Val(n_dist * n_val), Val(false), geom; ndrange = ndrange) end return nothing @@ -800,6 +815,7 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_fixed!( ::Val{D}, ::Val{NMOM}, ::Val{W}, + geom, ) where {D, NMOM, W} shared_xi = @localmem eltype(x) (D * SF_GPU_TILE,) shared_xj = @localmem eltype(x) (D * SF_GPU_TILE,) @@ -875,16 +891,16 @@ KA.@kernel unsafe_indices = true function sf_tiled_2d_fixed!( Xi = _sf_load_pt(Val(D), shared_xi, ia) Xj = _sf_load_pt(Val(D), shared_xi, jb) end - dX = Xj - Xi - dist = sqrt(_sf_dot(dX, dX)) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = dist_digitizer(dist) - if 1 <= dbin <= n_dist - rhat = dX / dist + if ok && 1 <= dbin <= n_dist + # Loop-invariant across the strip: one frame serves all bw fields. + rhat = SFH.pair_direction(geom, frame, dist) @inbounds for w in 1:bw Ui = _sf_load_field(Val(D), shared_ui, w, ia) Uj = off_diag ? _sf_load_field(Val(D), shared_uj, w, jb) : _sf_load_field(Val(D), shared_ui, w, jb) - dU = Uj - Ui + dU = SFH.pair_delta(geom, frame, Xi, Xj, Ui, Uj) moments = _sf_moments(Val(NMOM), sf_type, dU, rhat) bb = b_base + w - 1 for m in 1:NMOM @@ -915,7 +931,7 @@ end """Launch fixed-x batch 2D over ⌈B/W⌉ strips. x_dev=(D,N), u_dev=(D,N,B).""" function _launch_sf_tiled_2d_fixed!( backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, - N::Int, n_dist::Int, n_val::Int, B::Int, ::Val{D}, ::Val{NMOM}; + N::Int, n_dist::Int, n_val::Int, B::Int, ::Val{D}, ::Val{NMOM}, geom; W::Int = _sf_tiled_2d_fixed_strip(eltype(out_dev), D), ) where {D, NMOM} n_tiles = cld(N, SF_GPU_TILE) @@ -929,7 +945,7 @@ function _launch_sf_tiled_2d_fixed!( bw = min(Wv, B - b_base + 1) kernel!(out_dev, cnt_dev, x_dev, u_dev, sf_type, dist_digitizer, val_plan, N, n_dist, n_val, b_base, bw, n_tiles, n_tile_blocks, ws, - Val(D), Val(NMOM), Val(Wv); ndrange = ndrange) + Val(D), Val(NMOM), Val(Wv), geom; ndrange = ndrange) b_base += bw end end @@ -961,11 +977,11 @@ end """Dispatch a 2D batch launch on runtime D ∈ {2,3} into the Val-specialized launchers.""" function _sf_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, - N, n_dist, n_val, B, D::Int, ::Val{NMOM}, fixed_x::Bool) where {NMOM} + N, n_dist, n_val, B, D::Int, ::Val{NMOM}, fixed_x::Bool, geom) where {NMOM} # CUDA fast path (N-body broadcast + dynamic-shared privatized histogram, # TILE=1024) when StructureFunctionsCUDAExt is active and it fits the device. SFC.gpu_fast_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, - N, n_dist, n_val, B, D, NMOM, fixed_x) && return nothing + N, n_dist, n_val, B, D, NMOM, fixed_x, geom) && return nothing # Prefer the shared-histogram kernel (fixed or varying) when the histogram # fits (~7× faster than direct global atomics); fall back to global for large # bin counts that don't fit in shared memory. @@ -974,10 +990,10 @@ function _sf_launch_2d_batch!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, use_shared ? _launch_sf_tiled_2d_shared!(backend, out_dev, cnt_dev, (fixed_x ? reshape(x_dev, size(x_dev, 1), size(x_dev, 2), 1) : x_dev), - u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, Dv, Val(NMOM), fixed_x) : + u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, Dv, Val(NMOM), fixed_x, geom) : fixed_x ? - _launch_sf_tiled_2d_fixed!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, Dv, Val(NMOM)) : - _launch_sf_tiled_2d_varying!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, Dv, Val(NMOM)) + _launch_sf_tiled_2d_fixed!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, Dv, Val(NMOM), geom) : + _launch_sf_tiled_2d_varying!(backend, out_dev, cnt_dev, x_dev, u_dev, sf_type, ddig, vplan, N, n_dist, n_val, B, Dv, Val(NMOM), geom) D == 2 ? go(Val(2)) : D == 3 ? go(Val(3)) : error("GPU 2D batch requires D ∈ {2,3} (got $D)") return nothing end @@ -985,14 +1001,14 @@ end """Dispatch a 1D batch launch on runtime D ∈ {2,3} into the Val-specialized launchers. `out`/`cnt` are (NMOM, NB, B); x_dev/u_dev are (D,N,B) varying or x=(D,N),u=(D,N,B) fixed.""" function _sf_launch_1d_batch!(backend, out, cnt, x_dev, u_dev, sf_type, dig, - N, NB, B, D::Int, ::Val{NMOM}, fixed_x::Bool) where {NMOM} + N, NB, B, D::Int, ::Val{NMOM}, fixed_x::Bool, geom) where {NMOM} # CUDA fast path (N-body broadcast + static-shared privatized histogram, # TILE=256) when StructureFunctionsCUDAExt is active and NB fits. SFC.gpu_fast_launch_1d_batch!(backend, out, cnt, x_dev, u_dev, sf_type, dig, - N, NB, B, D, NMOM, fixed_x) && return nothing + N, NB, B, D, NMOM, fixed_x, geom) && return nothing go(Dv) = fixed_x ? - _launch_sf_tiled_1d_fixed!(backend, out, cnt, x_dev, u_dev, sf_type, dig, N, NB, B, Dv, Val(NMOM)) : - _launch_sf_tiled_1d_varying!(backend, out, cnt, x_dev, u_dev, sf_type, dig, N, NB, B, Dv, Val(NMOM)) + _launch_sf_tiled_1d_fixed!(backend, out, cnt, x_dev, u_dev, sf_type, dig, N, NB, B, Dv, Val(NMOM), geom) : + _launch_sf_tiled_1d_varying!(backend, out, cnt, x_dev, u_dev, sf_type, dig, N, NB, B, Dv, Val(NMOM), geom) D == 2 ? go(Val(2)) : D == 3 ? go(Val(3)) : error("GPU 1D batch requires D ∈ {2,3} (got $D)") return nothing end diff --git a/ext/gpu/sp2d_accumulation_strategy.jl b/ext/gpu/sp2d_accumulation_strategy.jl index d568102..d10b43d 100644 --- a/ext/gpu/sp2d_accumulation_strategy.jl +++ b/ext/gpu/sp2d_accumulation_strategy.jl @@ -26,15 +26,55 @@ Frozen HTP-EJ histogram accumulation strategy for one `(n_dist, n_val, FT)` work """ struct SP2DAccumulationStrategy n_joint_cells::Int + shared_cells::Int accum_mode::Symbol smem_per_block::Int max_shared_cells::Int plane_cells::Int + plane_shared_cells::Int types_per_pass::Int n_type_passes::Int needs_partition_merge::Bool end +""" +Joint-histogram bytes above which plain global atomics beat `:direct`, so `_launch_single_pass_2d!` +routes past it. + +`:direct` gives up the on-chip histogram for block-private global partitions plus a merge pass, so +its cost grows with cells × tile-blocks; plain global atomics get *cheaper* as more cells spread the +contention. Measured on A100 at N=8000, `:direct` vs naive in bapps: + +| hist bytes | Float32 | Float64 | +|---|---|---| +| 253–307 KB | 3.85 vs 3.46 → `:direct` | 3.44 vs 3.47 → wash | +| 373–389 KB | 3.52 vs 4.33 → naive | 3.41 vs 4.21 → naive | +| 461–720 KB | 2.43 vs 6.22 → naive | 1.87 vs 6.70 → naive | + +The crossover falls between 307 and 373 KB for both element types, and naive's margin grows steeply +above it. `:shared` and `:typeplane` keep the histogram on chip and are unaffected. See +`gpu/SPEED_OF_LIGHT.md`. +""" +const SP2D_GLOBAL_ATOMIC_HIST_BYTES = 340 * 1024 + +""" + _sp2d_prefers_global_atomics(n_dist, n_val, FT, caps) -> Bool + +Whether SP2D should hand this shape to the plain global-atomic kernel instead of `:direct`. + +Consulted in **two** places that must agree: where the value plan is built +(`_gpu_run_single_pass_2d!`, which must produce a `GPUValueVectorCols` because that is the plan the +global-atomic kernel has methods for) and where the kernel is launched +(`_launch_single_pass_2d!`). Splitting the rule between them silently routes a typed value plan into +a kernel with no matching method, which surfaces as +`ArgumentError: single-pass 2D global-atomic path unsupported for ...`. +""" +function _sp2d_prefers_global_atomics(n_dist::Int, n_val::Int, ::Type{FT}, caps) where {FT} + hist_bytes = SF_GPU_SINGLE_PASS_N * n_dist * n_val * (sizeof(FT) + sizeof(UInt32)) + hist_bytes <= SP2D_GLOBAL_ATOMIC_HIST_BYTES && return false + return _sp2d_accumulation_strategy(n_dist, n_val, FT, caps).accum_mode === :direct +end + """Total joint histogram cells `6 × n_dist × n_val`.""" @inline _sp2d_joint_cells(n_dist::Int, n_val::Int) = SF_GPU_SINGLE_PASS_N * n_dist * n_val @@ -82,27 +122,41 @@ end end """ - _sp2d_accumulation_strategy(n_dist, n_val, FT) -> SP2DAccumulationStrategy + _sp2d_accumulation_strategy(n_dist, n_val, FT, caps) -> SP2DAccumulationStrategy -Select `:shared`, `:typeplane`, or `:direct` from the 48 KiB shared-memory budget. -Typeplane packs `types_per_pass` SF planes per pair traversal (`n_type_passes` total). -Sets `needs_partition_merge = (mode == :direct)` for host launch/workspace routing. +Select `:shared`, `:typeplane`, or `:direct` from the budget this device allows a *static* +`@localmem` kernel — `gpu_static_smem_budget(caps)`, not a fixed constant, so a device offering less +than the architectural static cap is handled. Typeplane packs `types_per_pass` SF planes per pair +traversal (`n_type_passes` total). Sets `needs_partition_merge = (mode == :direct)` for host +launch/workspace routing. + +The budget is bounded by [`GPU_SMEM_STATIC_MAX`] however generous the device is: static shared has a +hard architectural cap, and the larger opt-in figure applies only to dynamic shared memory, which +KernelAbstractions cannot express portably. """ -function _sp2d_accumulation_strategy(n_dist::Int, n_val::Int, ::Type{FT}) where {FT} +function _sp2d_accumulation_strategy( + n_dist::Int, n_val::Int, ::Type{FT}, + caps::SFC.GPUDeviceCaps = SFC.gpu_device_caps(nothing), +) where {FT} C = _sp2d_joint_cells(n_dist, n_val) plane = n_dist * n_val - smem = SF_GPU_SMEM_DEFAULT + # What must fit on chip is the bank-conflict-padded layout, which is larger than the cell count. + Cs = _sp2d_shared_cells(n_dist, n_val) + plane_s = _sp2d_plane_cells(n_dist, n_val) + smem = SFC.gpu_static_smem_budget(caps) max_shared = _sp2d_max_shared_cells(smem, FT) - mode = if C <= max_shared + mode = if Cs <= max_shared :shared - elseif plane <= max_shared + elseif plane_s <= max_shared :typeplane else :direct end - tpp = mode == :typeplane ? _sp2d_types_per_pass(plane, max_shared) : SF_GPU_SINGLE_PASS_N + tpp = mode == :typeplane ? _sp2d_types_per_pass(plane_s, max_shared) : SF_GPU_SINGLE_PASS_N ntp = mode == :typeplane ? _sp2d_n_type_passes(tpp) : 1 - return SP2DAccumulationStrategy(C, mode, smem, max_shared, plane, tpp, ntp, mode == :direct) + return SP2DAccumulationStrategy( + C, Cs, mode, smem, max_shared, plane, plane_s, tpp, ntp, mode == :direct, + ) end """Block-private partition bytes for `n_tile_blocks` upper-triangle tile blocks.""" @@ -111,9 +165,30 @@ end return n_tile_blocks * config.n_joint_cells * cell_bytes end -"""Compile-time `@localmem` histogram width for shared-histogram kernels.""" +"""Cell granularity for the compile-time histogram width; coarse so distinct configs share kernels.""" +const SP2D_COMPILE_CELL_QUANTUM = 1024 + +""" + _sp2d_sharedhist_compile_cells(config) -> Int + +Compile-time `@localmem` histogram width. Sized to what the config actually needs, rounded up to +[`SP2D_COMPILE_CELL_QUANTUM`] so nearby configs reuse one compiled kernel instead of each forcing +its own. Reserving the whole budget instead would cost residency: a config needing 3072 cells would +hold 5371 cells of shared and drop from 5 blocks per SM to 3. +""" @inline function _sp2d_sharedhist_compile_cells(config::SP2DAccumulationStrategy) - return config.max_shared_cells + # Both branches must use the PADDED extents: the kernel indexes and bounds its loops with the + # padded layout, so sizing `@localmem` from the logical cell counts runs it off the end. + need = if config.accum_mode === :shared + config.shared_cells + elseif config.accum_mode === :typeplane + config.types_per_pass * config.plane_shared_cells + else + 0 + end + need <= 0 && return 1 + quantized = cld(need, SP2D_COMPILE_CELL_QUANTUM) * SP2D_COMPILE_CELL_QUANTUM + return min(quantized, config.max_shared_cells) end function _sp2d_dist_variant(::LinearBinEdges) @@ -122,3 +197,7 @@ end function _sp2d_dist_variant(::LogBinEdges) return :log_linear end +"""Arbitrary (non-uniform, non-log) distance edges: device binary search.""" +function _sp2d_dist_variant(::AbstractVector) + return :general +end diff --git a/ext/gpu/value_digitize_plans.jl b/ext/gpu/value_digitize_plans.jl index fcb7448..b257b5c 100644 --- a/ext/gpu/value_digitize_plans.jl +++ b/ext/gpu/value_digitize_plans.jl @@ -5,7 +5,6 @@ struct GPUValueLinearShared{T} first::T last::T inv_step::T - offset::T step::T end @@ -14,7 +13,6 @@ struct GPUValueLinearCols{T} first::SA.SVector{SF_GPU_SINGLE_PASS_N, T} last::SA.SVector{SF_GPU_SINGLE_PASS_N, T} inv_step::SA.SVector{SF_GPU_SINGLE_PASS_N, T} - offset::SA.SVector{SF_GPU_SINGLE_PASS_N, T} step::SA.SVector{SF_GPU_SINGLE_PASS_N, T} end @@ -23,7 +21,6 @@ struct GPUValueInfLinearShared{T} first::T last::T inv_step::T - offset::T step::T n_inner_edges::Int inner_last::T @@ -34,7 +31,6 @@ struct GPUValueInfLinearCols{T} first::SA.SVector{SF_GPU_SINGLE_PASS_N, T} last::SA.SVector{SF_GPU_SINGLE_PASS_N, T} inv_step::SA.SVector{SF_GPU_SINGLE_PASS_N, T} - offset::SA.SVector{SF_GPU_SINGLE_PASS_N, T} step::SA.SVector{SF_GPU_SINGLE_PASS_N, T} inner_last::SA.SVector{SF_GPU_SINGLE_PASS_N, T} n_inner_edges::Int @@ -45,7 +41,6 @@ struct GPUValueLogLinearShared{T} first::T last::T inv_step::T - offset::T step::T end @@ -54,7 +49,6 @@ struct GPUValueLogLinearCols{T} first::SA.SVector{SF_GPU_SINGLE_PASS_N, T} last::SA.SVector{SF_GPU_SINGLE_PASS_N, T} inv_step::SA.SVector{SF_GPU_SINGLE_PASS_N, T} - offset::SA.SVector{SF_GPU_SINGLE_PASS_N, T} step::SA.SVector{SF_GPU_SINGLE_PASS_N, T} end @@ -105,7 +99,6 @@ function _linear_plan_fields(lbe::LinearBinEdges) lbe.first_edge, lbe.last_edge, lbe.inv_step, - lbe.offset, lbe.step_val, ) end @@ -121,8 +114,8 @@ function _gpu_build_value_digitize_plan( ::KA.Backend, vb::LinearBinEdges, ) - f, l, inv, off, st = _linear_plan_fields(vb) - return GPUValueLinearShared(f, l, inv, off, st) + f, l, inv, st = _linear_plan_fields(vb) + return GPUValueLinearShared(f, l, inv, st) end function _gpu_build_value_digitize_plan( @@ -133,9 +126,8 @@ function _gpu_build_value_digitize_plan( f = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_linear_plan_fields(vb[t])[1] for t in 1:SF_GPU_SINGLE_PASS_N) l = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_linear_plan_fields(vb[t])[2] for t in 1:SF_GPU_SINGLE_PASS_N) inv = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_linear_plan_fields(vb[t])[3] for t in 1:SF_GPU_SINGLE_PASS_N) - off = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_linear_plan_fields(vb[t])[4] for t in 1:SF_GPU_SINGLE_PASS_N) - st = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_linear_plan_fields(vb[t])[5] for t in 1:SF_GPU_SINGLE_PASS_N) - return GPUValueLinearCols(f, l, inv, off, st) + st = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_linear_plan_fields(vb[t])[4] for t in 1:SF_GPU_SINGLE_PASS_N) + return GPUValueLinearCols(f, l, inv, st) end function _gpu_build_value_digitize_plan( @@ -143,8 +135,8 @@ function _gpu_build_value_digitize_plan( vb::InfPaddedBinEdges, ) inner = _inflinear_inner(vb) - f, l, inv, off, st = _linear_plan_fields(inner) - return GPUValueInfLinearShared(f, l, inv, off, st, length(inner.edges), inner.last_edge) + f, l, inv, st = _linear_plan_fields(inner) + return GPUValueInfLinearShared(f, l, inv, st, length(inner.edges), inner.last_edge) end function _gpu_build_value_digitize_plan( @@ -161,10 +153,9 @@ function _gpu_build_value_digitize_plan( f = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(inners[t].first_edge for t in 1:SF_GPU_SINGLE_PASS_N) l = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(inners[t].last_edge for t in 1:SF_GPU_SINGLE_PASS_N) inv = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(inners[t].inv_step for t in 1:SF_GPU_SINGLE_PASS_N) - off = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(inners[t].offset for t in 1:SF_GPU_SINGLE_PASS_N) st = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(inners[t].step_val for t in 1:SF_GPU_SINGLE_PASS_N) il = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(inners[t].last_edge for t in 1:SF_GPU_SINGLE_PASS_N) - return GPUValueInfLinearCols(f, l, inv, off, st, il, n_inner) + return GPUValueInfLinearCols(f, l, inv, st, il, n_inner) end function _log_linear_plan_fields(lbe::LogBinEdges) @@ -175,8 +166,8 @@ function _gpu_build_value_digitize_plan( ::KA.Backend, vb::LogBinEdges, ) - f, l, inv, off, st = _log_linear_plan_fields(vb) - return GPUValueLogLinearShared(f, l, inv, off, st) + f, l, inv, st = _log_linear_plan_fields(vb) + return GPUValueLogLinearShared(f, l, inv, st) end function _gpu_build_value_digitize_plan( @@ -192,9 +183,8 @@ function _gpu_build_value_digitize_plan( f = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_log_linear_plan_fields(vb[t])[1] for t in 1:SF_GPU_SINGLE_PASS_N) l = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_log_linear_plan_fields(vb[t])[2] for t in 1:SF_GPU_SINGLE_PASS_N) inv = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_log_linear_plan_fields(vb[t])[3] for t in 1:SF_GPU_SINGLE_PASS_N) - off = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_log_linear_plan_fields(vb[t])[4] for t in 1:SF_GPU_SINGLE_PASS_N) - st = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_log_linear_plan_fields(vb[t])[5] for t in 1:SF_GPU_SINGLE_PASS_N) - return GPUValueLogLinearCols{T}(f, l, inv, off, st) + st = SA.SVector{SF_GPU_SINGLE_PASS_N, T}(_log_linear_plan_fields(vb[t])[4] for t in 1:SF_GPU_SINGLE_PASS_N) + return GPUValueLogLinearCols{T}(f, l, inv, st) end function _gpu_build_value_vector_cols_plan( @@ -306,7 +296,7 @@ end n_edges::Int, ) return _gpu_digitize_linear( - x, plan.first, plan.last, plan.inv_step, plan.offset, plan.step, n_edges, + x, plan.first, plan.last, plan.inv_step, plan.step, n_edges, ) end @@ -321,7 +311,6 @@ end plan.first[col], plan.last[col], plan.inv_step[col], - plan.offset[col], plan.step[col], n_edges, ) @@ -338,7 +327,6 @@ end plan.first, plan.last, plan.inv_step, - plan.offset, plan.step, plan.n_inner_edges, plan.inner_last, @@ -356,7 +344,6 @@ end plan.first[col], plan.last[col], plan.inv_step[col], - plan.offset[col], plan.step[col], plan.n_inner_edges, plan.inner_last[col], @@ -370,7 +357,7 @@ end n_edges::Int, ) return _gpu_digitize_log_spaced( - x, plan.first, plan.last, plan.inv_step, plan.offset, plan.step, n_edges, + x, plan.first, plan.last, plan.inv_step, plan.step, n_edges, ) end @@ -385,7 +372,6 @@ end plan.first, plan.last, plan.inv_step, - plan.offset, plan.step, col, n_edges, diff --git a/ext/gpu/workspace.jl b/ext/gpu/workspace.jl index b96cc99..e4ddde4 100644 --- a/ext/gpu/workspace.jl +++ b/ext/gpu/workspace.jl @@ -1,5 +1,5 @@ # GPUSFWorkspace — device-resident histogram buffers and cached bin edges for GPU SF paths. -# Included from StructureFunctionsGPUExt.jl (uses _gpu_normalize_bins, etc.). +# Included from StructureFunctionsKernelAbstractionsExt.jl (uses _gpu_normalize_bins, etc.). """ GPUSFWorkspace @@ -252,7 +252,7 @@ function _gpusf_workspace_sp2d!( out_sums_dev = KA.zeros(backend, FT, SF_GPU_SINGLE_PASS_N, NB, hist_n_val) out_cnts_dev = KA.zeros(backend, UInt32, SF_GPU_SINGLE_PASS_N, NB, hist_n_val) - strategy = _sp2d_accumulation_strategy(NB, hist_n_val, FT) + strategy = _sp2d_accumulation_strategy(NB, hist_n_val, FT, SFC.gpu_device_caps(backend)) ws = GPUSFWorkspace( backend, FT, :single_pass_2d, dist_bins, value_bins, diff --git a/gpu/OPTIMAL_KERNEL_DESIGN.md b/gpu/OPTIMAL_KERNEL_DESIGN.md index 9835841..fbbf3d1 100644 --- a/gpu/OPTIMAL_KERNEL_DESIGN.md +++ b/gpu/OPTIMAL_KERNEL_DESIGN.md @@ -255,6 +255,11 @@ wastes GPU time. Raw evidence is in `gpu/benchmark_results/` (job IDs cited). - **TILE=1024 for 2D**: 50% occupancy beats 25% (TILE=512) on the histogram-pinned 50×50 case — 8.36 vs 6.39 bapps (job 238806). - **O(1) FMA value digitize** (`GPUValueLinearShared` from `LinearBinEdges`) vs general binary-search (`GPUValueVectorCols`): ~3× in the 6-per-pair hot loop → 58 s vs the proto's 193 s estimate. **Always benchmark with the production value-plan type, not a general fallback.** - **Single fused launch** for batch/slices (no host `for b`/`for slice` loop): the original ~17 s batch-joint2d regression was a naive per-cell `(N,N)` kernel inside a host loop. +- **Global-`u` strip kernel for fixed-x individual SF** (strip 128 / 63 sweeps): ~48 s at NB=50-64 vs + ~12 s for the u-smem strip-16 / 504-sweep kernel (A100, Mar 2026). Fewer geometry replays were + canceled by 8x more inner-loop atomics per pair and uncached global `u` loads. The kernel carried + this note in `kernels_batch.jl` while unreachable from any launcher; deleted in Stage 6i, recorded + here. Do not re-wire without profiling. - **Stagger the REPLICA index, never the bin index** (if replication is ever used): offsetting the bin corrupts the histogram — the prior botched attempt. ## Compile pitfalls (KA.CPU() catches NONE — only `@cuda` compile does) diff --git a/gpu/Project.toml b/gpu/Project.toml index 643cea7..9042268 100644 --- a/gpu/Project.toml +++ b/gpu/Project.toml @@ -1,7 +1,10 @@ [deps] +ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" +Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" diff --git a/gpu/README.md b/gpu/README.md index cec9568..481fb6a 100644 --- a/gpu/README.md +++ b/gpu/README.md @@ -1,7 +1,7 @@ CUDA validation, benchmark entry points, and profiling helpers for StructureFunctions.jl GPU work. -Production GPU code lives in `ext/StructureFunctionsGPUExt.jl` and `ext/gpu/`. +Production GPU code lives in `ext/StructureFunctionsKernelAbstractionsExt.jl` and `ext/gpu/`. General user documentation lives in [`docs/gpu.md`](../docs/gpu.md). ## File Inventory diff --git a/gpu/SPEED_OF_LIGHT.md b/gpu/SPEED_OF_LIGHT.md new file mode 100644 index 0000000..835d0f3 --- /dev/null +++ b/gpu/SPEED_OF_LIGHT.md @@ -0,0 +1,738 @@ +# Speed-of-light analysis and exploration plan (GPU pair kernels) + +**Status: working document. Nothing here is gospel — including this sentence.** + +Every claim is tagged so a later reader knows what it rests on: + +- **[M]** measured this session, with the method stated so it can be re-run and falsified. +- **[D]** derived from first principles / algebra, with the derivation shown. +- **[I]** inherited claim from `OPTIMAL_KERNEL_DESIGN.md` or code comments, **not re-verified here**. +- **[H]** hypothesis, untested, with a stated kill criterion. + +Companion to `OPTIMAL_KERNEL_DESIGN.md`, which records the June 2026 design. That document's +measurements were taken on a different code state and several of its conclusions are premised on +assumptions that later work can invalidate (see §5). Treat it as background, not as fact. + +Hardware for all **[M]** numbers: NVIDIA A100-SXM4-80GB, 108 SMs, 1.41 GHz, 164 KB shared/SM, +65536 registers/SM, 163 KB shared/block opt-in. Julia 1.12.7, CUDA.jl as pinned in `gpu/`. + +--- + +## 1. What the workload actually is + +Per unordered pair `(i,j)`, `D=2`, single-pass (6 invariants): + +| stage | cost | +|---|---| +| `dx = x_j - x_i`, `r² = dx·dx`, `r = sqrt(r²)` | ~5 FLOP + 1 sqrt | +| `bin = digitize(r)` (FMA route) | ~2 FLOP | +| `du = u_j - u_i`, `du_L = du·dx/r`, `|du|²` | ~8 FLOP | +| 6 moments | ~4 FLOP | +| **accumulate** | **6 shared sum-atomics + 1 shared count-atomic** | + +So ~20 FLOP and **7 shared-memory atomics** per pair. The FLOPs are free; the atomics are not. + +## 2. Validated cost model: atomics ≈ 56%, fixed geometry ≈ 44% **[M]** + +Measured by holding the kernel family fixed (N-body, **varying-x** so both NMOM route to the same +kernel) and varying only `NMOM`. Float32, `N=20000`, `LinearBinEdges(range(0, 0.3; length=33))`, +`CUDA.@elapsed` over 3 iterations after warmup. + +| B | NMOM=1 (2 atomics/pair) | NMOM=6 (7 atomics/pair) | t6/t1 | +|---|---|---|---| +| 1 | 106.8 bapps | 64.2 | 1.66 | +| 8 | 119.7 | 71.3 | 1.68 | +| 64 | **149.3** | **89.1** | **1.68** | + +Fit `t_per_pair = a + b·n_atomics` at B=64: `a = 0.00489`, `b = 0.000905` (bapps⁻¹). + +- **atomic-attributable share at NMOM=6: ~56%** +- **fixed share (geometry, sqrt, shared loads, loop): ~44%** + +**[D] Consequences.** Removing atomics *entirely* would give at most `1/0.436 ≈ 2.3×`. Any +atomic-reduction lever (§3, §4) is therefore bounded by ~2×, not by an order of magnitude. The other +~44% is only reachable by attacking geometry cost and occupancy (§8). + +### Why the naive roofline framing is wrong — a falsified analysis, kept as a warning **[M]** + +An earlier version of this section computed: A100 shared-atomic ceiling +`108 SM × 1.41 GHz × 32 banks = 4.9e12 ops/s`; our 64 bapps × 7 atomics = 4.5e11 = **9%** of it; +CADISHI's ~495 bapps × 1 atomic ≈ 10%. It concluded there was ~10× of atomic headroom. + +**That conclusion does not follow, and the measurement above refutes it.** Being at 9% of the +*atomic* ceiling is irrelevant when atomics are only ~56% of runtime — the bound is ~2×. + +Two experimental errors produced it, both worth avoiding again: + +1. **Comparing across kernel families.** The first attempt compared NMOM=1 against NMOM=6 using + `x=(D,N)`, `u=(D,N,1)`. That is the **fixed-x** regime, which routes to a completely different + *global*-atomic warp-replica kernel. It measured 37.3 bapps for NMOM=1 vs 64.5 for NMOM=6 — i.e. + *more* atomics running *faster* — which is a routing artifact, not a hardware property. Always + confirm both arms hit the same kernel before attributing a difference to one variable. +2. **Comparing an unsaturated point to a saturated reference.** `B=1` does not saturate the device; + the bapps figures in `OPTIMAL_KERNEL_DESIGN.md` are at `B/T=8064`. Comparing our B=1 number to + CADISHI's saturated ~495 bapps is not a like-for-like comparison. + +## 3. Lever A — two of the six moments are exactly redundant **[D]** + +The six accumulated invariants are not independent: + +``` +S2 = |δu|² L2 = δu_L² +T2 = |δu|² − δu_L² = S2 − L2 +S3 = δu_L·|δu|² L3 = δu_L·δu_L² +L1T2 = δu_L·T2 = δu_L·(|δu|² − δu_L²) = S3 − L3 +``` + +Histogram accumulation is linear, so **per bin** `Σ T2 = Σ S2 − Σ L2` and `Σ L1T2 = Σ S3 − Σ L3` +exactly. `T2` and `L1T2` never need a per-pair atomic; they are one subtraction each at flush, +over `NB` bins rather than over `N²/2` pairs. + +**Atomics per pair: 7 → 5.** Using the validated cost model of §2 (`a = 0.00489`, `b = 0.000905`): +`t = a + 5b = 0.00941` → **106.2 bapps predicted vs 89.1 baseline = 1.19×**, at B=64 Float32. +(An earlier estimate of ~1.4× assumed atomics dominated; §2 shows they are ~56%.) + +### IMPLEMENTED and measured — CUDA 1D N-body kernel **[M]** + +`_sf_accum_moments` / `_sf_flush_moment` in `ext/gpu/sf_core.jl`; applied in +`ext/cuda/kernels_1d.jl`. + +| | before | after | speedup | +|---|---|---|---| +| Float32, B=64 | 89.1 bapps | **105.1 bapps** | **1.18×** | +| Float32, B=1 | 3.12 ms | 2.66 ms | 1.17× | +| Float64, B=1 | 5.35 ms | 4.50 ms | 1.19× | + +**Predicted 1.19×, measured 1.18× — the cost model of §2 is accurate to ~1%**, which is the more +valuable result: it can now be used to rank the remaining levers before writing code. + +Precision, against a CPU serial reference, with the KA path (which still accumulates all six +directly) as the control: + +| moment | direct-6 | reconstructed-4 | +|---|---|---| +| T2 Float32 | 3.89e-5 | 3.82e-5 | +| L1T2 Float32 | 5.97e-5 | 7.82e-5 | +| T2 Float64 | 2.20e-14 | 2.09e-14 | +| L1T2 Float64 | 1.81e-14 | 2.08e-14 | + +Worst case (L1T2/F32, 7.8e-5) is comparable to the directly-accumulated L3 (5.5e-5) and well inside +the documented ~1e-3 near-cancelling tolerance. Kill criterion not triggered. CUDA suite 29/29. + +### Scope limit — does NOT apply to SP2D **[D]** + +In single-pass **2D**, each moment is binned by **its own value** on the value axis +(`vbin = digitize(vals[t])`, `ext/gpu/kernels_2d_direct.jl`). The pairs contributing to cell +`(t=3, dbin, vbin)` are selected by `T2`'s value, not by `S2`'s or `L2`'s, so +`Σ_cell T2 ≠ Σ_cell S2 − Σ_cell L2`. **The reconstruction is only valid where all moments share +one bin, i.e. sp1d.** Do not propagate it into any 2D value-axis kernel. + +Still to propagate (same algebra, same validity condition): the KA sp1d kernels +(`ext/gpu/kernels_1d_single_pass.jl`, `ext/gpu/sf_tiled.jl`, the global-atomic fallbacks), which +serve the **non-batch** path, and the CPU `_sp1d_pairs!` (6 stores → 4, plus the redundant 6× +identical count writes → 1). + +Caveats to measure, not assume: +- **Precision.** `Σ(a−b)` and `Σa − Σb` differ in rounding. `T2` is a difference of same-sign + quantities and can be near-cancelling; `OPTIMAL_KERNEL_DESIGN.md` already reports ~1e-3 relative + FP32 error on near-cancelling single-pass cells **[I]**. This change could worsen that. **Kill + criterion:** if FP32 relative error on `T2`/`L1T2` degrades beyond the existing GPU-vs-CPU + tolerance on a turbulence-like field, keep 6 accumulators in FP32 and apply the reduction only + for FP64, or accumulate `T2` directly and derive `L1T2` only. +- Applies identically to CPU, where the 6 moment stores are plain writes but still 6× the traffic. +- **[M]** The CUDA N-body kernel already issues only **one** count atomic (`scnt[bin] += 1`, + `ext/cuda/kernels_1d.jl`), so counts are not a redundancy there. The CPU `_sp1d_pairs!` loop + writes the same count 6× (`for t in 1:SINGLE_PASS_N; counts[t,bin] += 1`) — free to fix. + +## 4. Lever B — spatial sorting changes the premise under which warp aggregation was rejected **[H]** + +`OPTIMAL_KERNEL_DESIGN.md` rejects warp-aggregated atomics: *"only pays when warp lanes share few +bins; our bins are scattered → degenerates to ~32 atomics"* **[I]**. + +That rejection is not a statement about the algorithm — it is a statement about **the input +ordering**, which is an artifact we control. If points are spatially sorted (Morton/Hilbert order, +or cell-list order), then in the N-body inner loop thread `i` walks `j` through spatially adjacent +points, so `r = |x_i − x_j|` varies smoothly and consecutive `j` land in the *same or adjacent* bin. + +Three things unlock from the same preprocessing pass, and none of them work without it: + +1. **Run-length accumulation in registers.** A thread accumulates while the bin is unchanged and + issues one atomic per run instead of one per pair. +2. **Warp aggregation becomes viable** — the rejected optimization, under its stated precondition + now satisfied rather than violated. +3. **Tile-level distance culling** (already noted as "optional" in `OPTIMAL_KERNEL_DESIGN.md` §3.1 + but never implemented) becomes effective, because a spatially sorted tile has a tight AABB. + +**[M]** Independent measurement supporting (3): at `r_max/L = 0.05`, only **0.75%** of pairs fall +in range (exact count over all 2.0e8 pairs, N=20000 in a unit square); at 0.10, 2.9%. Nothing in the +current code prunes — `for j in (i+1):n_points` visits every pair and discards after computing the +distance (`src/Calculations/serial_single_pass.jl:311-315`). + +**Kill criterion:** if, on a *non-uniform* (turbulence-like) field with realistic bin edges, the +mean run length at the chosen tile size is < 2, drop lever B entirely — the sort cost and the +register pressure will not be repaid. + +Note this composes with, and largely subsumes, the "Stage 7 cell-list" item: both need one +spatial sort, and sorting is safe because a structure function is a sum over *unordered* pairs, so +any permutation of points leaves the histogram identical up to FP summation order. + +## 5. Inherited claims that are premise-dependent — re-test before trusting **[I]** + +These are recorded as settled in `OPTIMAL_KERNEL_DESIGN.md`. Each is conditional on something that +later work can change; none were re-measured this session. + +| inherited claim | the premise it rests on | why it may not hold | +|---|---|---| +| replication R>1 loses (R1=33, R2=34, R4=23, R8=12) | shared memory is scarce, so replicas cost occupancy | **[M]** sp1d Float32 is *register*-bound (5 blocks/SM by registers vs 21 by shared) — shared is slack there, so the stated cost mechanism does not apply in that regime | +| warp aggregation is marginal | "our bins are scattered" | bin scatter is a property of input ordering (§4), not of the algorithm | +| tile-level distance cull "optional… free otherwise" | never implemented or measured | **[M]** 0.75% in-range pairs at `r_max/L=0.05` is not "free otherwise" territory | +| non-batch stays on tiled128 because it is "sub-10 ms" | that sub-10 ms does not matter | **[M]** it is 1.24–1.58× slower than the N-body path in Float32 (§6) | +| constant memory | **never tried — absent from the ruled-out table** | see §7 | + +## 5b. BUG FOUND AND FIXED: Float64 fixed-x batch never compiled **[M]** + +`_batch_fixed_x_usmem_priv!` stages `512 + 512·W` elements of `FT` in **static** `@localmem` with a +hardcoded `BATCH_USMEM_STRIP_W = 16`. That is an unstated Float32 assumption: + +| FT | staging | 48 KB static cap | +|---|---|---| +| Float32 | 8704 × 4 = 34,816 B | fits | +| Float64 | 8704 × 8 = **69,632 B** (`0x11000`) | **exceeds `0xc000`** | + +So `calculate_structure_function(sf, x::CuArray{Float64,2}, u::CuArray{Float64,3}, bins)` — fixed-x +batch, Float64 — died at launch with `ptxas error: uses too much shared data (0x11000 bytes, 0xc000 +max)`. The path had therefore **never executed**, so its numerics had never been validated either. + +Fixed by making the strip width a budget computation rather than a constant — +`_batch_usmem_strip_w(FT) = clamp(GPU_SMEM_STATIC_MAX ÷ (512·sizeof(FT)) − 1)`, rounded down to a +power of two: 16 for Float32 (unchanged), 8 for Float64. Verified after the fix against a CPU serial +reference: **counts exact**, sums 1.5e-14 (F64) / 2.0e-5 (F32) relative, at B=1 and B=5. + +**Lesson for the next reader:** this is the second bug of exactly this shape (the first was static +staging checked against the *opt-in* limit instead of the *static* cap). Any `@localmem` sized from +a compile-time constant is a Float64 hazard — size it from `sizeof(FT)` against +`GPU_SMEM_STATIC_MAX`, and test Float64, which is where these surface. + +## 6. Measured: the non-batch entry points run the slower structure **[M]** + +Same workload, Float32, N=20000. Non-batch calls run the KA thread-owns-a-pair kernel; passing +`reshape(u, D, N, 1)` routes to the batch launcher, which reaches the CUDA N-body kernel. + +Full per-regime A/B, N=20000, after Lever A and the §5b fix. Ratio > 1 means routing non-batch +through the batch launcher wins: + +| regime | Float32 | Float64 | route non-batch to batch dispatcher? | +|---|---|---|---| +| 1D individual (L2SF) | **0.64×** | **0.76×** | **NO — non-batch wins in both** | +| 1D single-pass | 1.90× | 1.32× | yes | +| joint 2D | 1.48× | 1.18× | yes | +| single-pass 2D | 1.24× | **2.58×** | yes | + +Verified equivalent, not merely faster: worst relative difference across all six invariants is +**7.7e-14 (Float64)** and **3.3e-4 (Float32)** — a different summation order over ~4.8e7 in-range +pairs, nothing more. + +### Why 1D-individual loses on the batch route — the mechanism, not just the ratio **[M]** + +From `CUDA.@profile`, Float32, N=20000: + +| arm | kernels launched | main kernel | regs | smem | +|---|---|---|---|---| +| non-batch (3.45 ms) | **1** — `_sf_kernel_tiled128_2d_linear_u32` | 3.28 ms | 38 | 5,120 B | +| batch B=1 (5.42 ms) | **4** — permutedims + main + 2 merges | 3.84 ms | 50 | 34,816 B | +| sp1d batch B=1 (2.63 ms) | **1** — `_cuda_sf_1d_kernel` (N-body) | 2.53 ms | 38 | 11,776 B | + +Three causes, additive: + +1. **It never reaches the N-body kernel.** sp1d batch lands on `_cuda_sf_1d_kernel` (grid 3160 → + TILE=256, N-body); individual fixed-x batch lands on the KA `_batch_fixed_x_usmem_priv` + (grid 12403 → TILE=128). The 1.90× and the 0.64× are not the same comparison. +2. **Four kernels instead of one** — a `permutedims`, the main kernel, and two merge kernels + (0.40 ms) plus per-launch overhead. +3. **The main kernel is slower at B=1** (3.84 vs 3.28 ms) with 50 vs 38 registers and **6.8× the + shared memory**, because it stages a width-16 velocity strip to serve a batch of one. + +**[D] The unifying reason:** the fixed-x batch path exists to amortize per-tile geometry across a +wide batch strip. At `B=1` there is nothing to amortize, so strip staging, block-private partials +and the merge kernels are pure overhead. This *reconciles* rather than contradicts +`OPTIMAL_KERNEL_DESIGN.md`, whose 147-bapps figure for this kernel is at `B=8064` where the +amortization does pay — so the correct statement is that the routing decision is **B-dependent**, +not purely regime-dependent, which is sharper than what the older document says. + +**[H] Latent optimization, not taken:** when `bw == 1` the strip machinery and both merge kernels +are provably unnecessary and the batch path could shed them. Not rerouting achieves the same result +more cheaply, so this is only worth doing if the `B=1`-through-batch path is ever needed for another +reason. + +Note the sp1d Float32 ratio rose 1.58× → 1.90× after Lever A, because Lever A speeds up the batch +arm. `1.58 × 1.18 = 1.86` vs 1.90 measured — the two levers compose as the model predicts. + +## 6b. IMPLEMENTED — sp1d non-batch reroute **[M]** + +`_sp1d_try_fast_batch!` in `StructureFunctionsKernelAbstractionsExt.jl`, called as the first +statement of all three `_launch_single_pass_kernel!` route methods (linear / log / general). It +offers the launch to `SFC.gpu_fast_launch_1d_batch!` as `B=1`; a `false` return means the hook +declined and the caller continues to the tiled128 path unchanged. This is the same +hook-or-fall-through pattern `_sf_launch_1d_batch!` already uses, so non-CUDA backends — where +there is no measurement — are untouched by construction. + +| FT | route | before | after | +|---|---|---|---| +| Float32 | linear | 5.00 ms | **2.63 ms (1.90×)** | +| Float32 | log | — | 3.42 ms | +| Float32 | general | — | 4.34 ms | +| Float64 | linear | 5.94 ms | **4.64 ms (1.28×)** | + +**1D-individual is deliberately NOT rerouted** (0.64×/0.76×, mechanism in §6). + +### joint2d and sp2d reroutes — also implemented **[M]** + +`_joint2d_try_fast_batch!` (3 route methods in `StructureFunctionsKernelAbstractionsExt.jl`) and +`_sp2d_try_fast_batch!` (`ext/gpu/launch.jl`), same hook-or-fall-through pattern. `sp2d` respects +`force_global_atomic` — an explicit request for the global path is not overridden. joint2d declines +when `val_plan === nothing` (no plan to hand the batch kernel). + +| regime | FT | before | after | speedup | +|---|---|---|---|---| +| joint 2D | Float32 | 4.39 ms | 2.95 ms | 1.49× | +| joint 2D | Float64 | 5.24 ms | 4.51 ms | 1.16× | +| single-pass 2D | Float32 | 10.30 ms | 8.28 ms | 1.24× | +| **single-pass 2D** | **Float64** | **27.98 ms** | **10.90 ms** | **2.57×** | + +joint2d's `(n_dist, n_val)` output reshapes to `(1, n_dist, n_val, 1)` free of charge — column-major +layout is byte-identical. + +### Counts are REDISTRIBUTED, not lost — how to check this properly **[M]** + +The sp2d reroute changes per-cell counts for exactly `T2` and `L1T2`, the two moments built on the +cancelling `|δu|² − δu_L²`, so their computed value can land on the other side of a **value**-bin +edge. Measured (Float32, N=800, 26495–48300 counted pairs per moment): + +| moment | Σ\|Δcount\| KA.CPU (not rerouted) | Σ\|Δcount\| CUDA (rerouted) | total conserved? | +|---|---|---|---| +| S2, L2, S3, L3 | 0 | 0 | identical | +| T2 | **4** (pre-existing) | 14 | **yes** | +| L1T2 | 0 | 12 | **yes** | + +`T2` already differed before any reroute, so that part is pre-existing; `L1T2` is new. **The +decisive check is the total, not the per-cell diff** — a per-cell diff cannot distinguish "pair +moved to the adjacent bin" from "pair lost". Totals match exactly for all six moments, so ~7 pairs +per moment (0.015%) shifted between adjacent value bins and none were lost or double-counted. Sums +move by 5.0e-6 (F32) / 7.0e-15 (F64) relative. Verified: CUDA 29/29, KA/CPU 951 assertions. + +Any future change to 2D value binning should be judged the same way: **compare totals first**, then +per-cell. + +### Accuracy: judge by a control, not by the raw relative error **[M]** + +A naive "worst relative error vs CPU" reads 3.0e-3 for Float32 and looks like a regression. It is a +denominator artifact. Each moment is an array over distance bins; the odd-order moments are sums of +**signed** terms, so an individual bin can nearly cancel to zero while the moment as a whole is +O(0.1). Dividing by such a bin inflates a negligible absolute difference. + +Measured (Float32, N=3000, seed 3, 16 bins). "typical magnitude" = `max|value|` over that moment's +own bins: + +| moment | worst rel | value at that bin | typical magnitude | abs Δ | +|---|---|---|---|---| +| S2 (sum of squares, no cancellation) | 6.0e-6 | 4.08 | 4.11 | 2.4e-5 | +| L2 | 1.6e-5 | 2.02 | 2.05 | 3.3e-5 | +| T2 (reconstructed) | 2.0e-5 | 2.03 | 2.07 | 4.1e-5 | +| L3 (sum of cubes, signed) | 3.1e-3 | **1.18e-4** | **1.61e-1** | 3.6e-7 | + +L3's worst bin is 1371× below that moment's typical magnitude — millions of signed cubes of order +0.1 cancelling down to 1e-4. Every bin of S2 is ≈4.08 by contrast, because squares cannot cancel. + +**Do not conclude from this that "divide by the typical magnitude instead" is the right metric** — +that reasoning can equally hide a real defect, and a near-cancelling bin genuinely carries only a +couple of trustworthy Float32 digits on *any* hardware. What actually settles whether a change hurt +accuracy is a **control on identical data**: accumulate all six directly vs accumulate four and +reconstruct two, both against the same CPU reference. That gave **6.0e-5 vs 7.8e-5** worst case — +the change moved the error ~30%, not 50×. Use that comparison, not the raw ratio, to judge any +future change here. Verified: CUDA 29/29, KA/CPU 842 assertions. + +## 6c. CPU: Lever A applied, and an anomaly it exposed **[M]** + +Lever A also applies to the CPU sp1d kernels, where the stores are plain writes rather than atomics. +Both `_sp1d_pairs!` (scalar) and `_pf_sp_simd_pairs!` (the Euclidean D∈{2,3} SIMD scatter — the +common path) now store 4 sums + 1 count and call `_sp1d_derive_rows!` at the **end of the kernel**. + +Placing the derive inside the kernel rather than at the callers is what makes this safe: there are +20+ accumulator assembly points across serial/threaded/MPI/distributed/batch-leading, several of +them sp2d (where Lever A is invalid, §3) or batch-leading with a different axis order. The derive +uses `=`, never `+=`, so it is idempotent and correct however many times a kernel runs over a +buffer, and correct under partial/threaded reduction because it is linear. + +**Measured: sp1d 6.00 → 4.57 ns/pair = 1.31×** (N=4000, Float64, 32 bins, serial), better than the +1.22× a scalar micro-benchmark predicted, because the SIMD path gains more. + +### Anomaly: sf1d (1 moment) is SLOWER than sp1d (6 moments) **[M]** + +| | ns/pair (min, N=4000) | +|---|---| +| sf1d — one invariant | **5.03** | +| sp1d — six invariants | **4.64** | + +Reproducible at N=2000 and N=4000. Computing and storing six invariants is ~10% *cheaper* than one, +which means sf1d carries structural overhead sp1d does not. The difference is that +`_pf_simd_pairs!` (sf1d, `serial.jl`) keeps a **per-`i` local histogram**: `fill!` two `nb+2` +buffers, scatter branchlessly via `clamp` into guard cells, then merge `nb` bins into the output — +every `i`. `_pf_sp_simd_pairs!` (sp1d) instead branches (`if 1 <= bin <= nb`) and scatters straight +into the output. + +Isolated micro-benchmark of the two scatter strategies, identical compute (N=4000, Float64): + +| nb | per-`i` local hist | direct branchy scatter | ratio | +|---|---|---|---| +| 8 | 10.96 ns | 9.78 ns | 1.121 | +| 32 | 10.50 ns | 9.80 ns | 1.071 | +| 128 | 10.28 ns | 9.96 ns | 1.032 | +| 256 | 10.25 ns | 9.79 ns | 1.047 | + +**Direct scatter wins at every bin count tested — no crossover**, so this is not regime-dependent. + +**[H] Mechanism NOT established — do not repeat this claim without evidence.** The obvious +explanation (the `2(nb+2) + nb` fill/merge ops per `i`) predicts a penalty that *grows* with `nb`. +The measured gap is roughly constant at ~0.6 ns/pair from nb=8 to nb=256, which contradicts it. The +extra buffer round-trip is a better candidate, but that is a hypothesis, not a finding. The +optimization is justified by the measurement regardless; the *reason* is open. + +### APPLIED — `_pf_simd_pairs!` converted to direct scatter **[M]** + +`clamp(bin, 0, nb+1) + 1` into guard cells 1 and `nb+2` (dropped at merge) is exactly equivalent to +`if 1 <= bin <= nb`, so the scatter now writes straight into `output`/`counts` and the `hloc`/`cloc` +buffers, their allocations, and the per-`i` merge loop are gone (2 call sites: `serial.jl`, +`StructureFunctionsOhMyThreadsExt.jl`). + +| | before | after | | +|---|---|---|---| +| sf1d (1 moment) | 5.03 ns/pair | **4.35** | **1.16×** | +| sp1d (6 moments) | 4.64 | 4.75 | — | + +The anomaly is resolved: the one-moment kernel is now correctly *cheaper* than the six-moment one, +and sf1d also beats the 4.47 ns/pair session baseline. Verified: 4414 assertions across 16 files, +plus JET 48/48, Aqua 10/10, `test_parallel_equivalence` 14/14 — zero failures. + +**Ordering lesson worth keeping:** this was found only by benchmarking two kernels *against each +other* and noticing the result was physically impossible (more work, less time). Absolute timings +against a baseline would not have surfaced it — the baseline for sf1d (4.47) looked fine. + +## 7. Constant memory: what CADISHI does, and when it could pay here **[D]** + +CADISHI (`bio-phys/cadishi`, `cadishi/kernel/c_cudh_functions.cu`) holds **coordinates in the 64 KB +`__constant__` bank** and gives shared memory entirely to histogram bins: + +```c +const int histo_advanced_cmem_bytes = 64000; +__constant__ char histo_advanced_coords_cmem[histo_advanced_cmem_bytes]; +extern __shared__ uint32_t smem_bins[]; +cudaMemcpyToSymbol(histo_advanced_coords_cmem, &coord_d[iOffset], cmem_tile_n_elem*sizeof(TUPLE3_T)); +``` + +Tile = `64000/sizeof(TUPLE3_T)` ≈ 5333 points (float3) vs our 128-point shared tile. It also blocks +the *bin range* across `blockIdx.y` (`bin_lo = smem_nbins * blockIdx.y`) instead of falling back to +global atomics when bins exceed shared capacity. + +**[D] Where this can and cannot pay.** Shared memory already broadcasts at full speed when every +lane reads the same address — which is exactly the N-body access pattern — so the win is *not* read +latency. The win is that coordinates stop consuming shared memory. Therefore it helps **only where +shared memory is the binding constraint**: + +- **1D single-pass: no.** **[M]** register-bound at 5 blocks/SM; shared would allow 21. The ~4.5 KB + reclaimed is already slack. +- **SP2D 50×50: plausibly yes.** **[I]** the 117 KB dynamic histogram "pins 1 block/SM, so + threads/block IS occupancy". Moving 32 KB of staging out of shared is the difference between 1 and + 2 blocks/SM, in the one regime the design doc calls "near its practical floor". + +### DEAD LEVER — measured, do not retry **[M]** + +**The precise CUDA.jl blocker.** The primitives exist: `AS.Constant = 4` (`pointer.jl`), `CuGlobal` ++ `cuModuleGetGlobal_v2`, and a working example in `random.jl`. But `emit_constant_array` bakes the +data into the LLVM IR as a compile-time `ConstantArray` initializer — fine for Random's fixed +ziggurat tables, useless for per-call coordinates (it would mean recompiling the kernel per tile). +The real gap is narrower than "no constant memory": **no supported way to declare a runtime-written +`__constant__` array in a CUDA.jl kernel and address it from the host.** Kernel *parameters* do live +in constant bank 0 but cap at ~4 KB ≈ 256 points, only 2× the current tile. + +**`CuTexture` was the fallback, and it fails on both branches:** + +1. **Float64 textures do not exist.** `CuTextureArray(CuArray{Float64})` → + `ArgumentError: CUDA does not support texture arrays for element type Float64`. Hardware limit + (texture fetch is 32-bit), not a CUDA.jl gap. Float32 textures *do* work — verified with an exact + fetch (`max|Δ| = 0`) in a real `@cuda` kernel. But the biggest SP2D win (2.58×) is the Float64 + case. +2. **For Float32, shared memory is not the binding constraint anyway.** Measured SP2D occupancy: + +| | regs | block | shared | blk/SM (reg) | blk/SM (shared) | limiter | +|---|---|---|---|---|---|---| +| F32 32×16 | 40 | 1024 | 58,880 | **1** | 2 | REGISTERS | +| F32 50×50 | 40 | 1024 | 155,168 | **1** | 1 | REGISTERS | +| F64 32×16 | 58 | 512 | 71,936 | 2 | 2 | REGISTERS | +| F64 50×50 | 74 | 256 | 45,192 | 3 | 3 | REGISTERS | + +Freeing the whole 32 KB staging via textures leaves 32×16 still at **1 block/SM** (40 regs × 1024 +threads pins it), and 50×50 at 1 block (155 KB → 122 KB, still > 164/2). Zero occupancy gain. + +**[M] This also corrects an inherited claim.** `OPTIMAL_KERNEL_DESIGN.md` states the dynamic +histogram "pins 1 block/SM, so threads/block IS occupancy" **[I]** — implying *shared* is the +constraint. On current code SP2D is **register**-limited in every configuration measured. Combined +with §8b (occupancy itself buys ≤3%), the entire "free up shared memory" family of optimizations is +dead for this workload. + +### The decisive measurement — textures are SLOWER, timed **[M]** + +The occupancy argument above is not sufficient on its own (§8b established this kernel is *not* +occupancy-bound, so "textures don't raise occupancy" does not prove they cannot help — a separate +cache path could still cut LSU traffic). So it was timed directly: two kernels, identical N-body pair +loop over `TILE=256`, `N=20000`, Float32; one stages the j-tile in shared, the other reads j from a +`CuTexture`. + +| | time | +|---|---| +| j staged in **shared** | **4.024 ms** | +| j read from **texture** | 4.369 ms | +| ratio | **1.086 — texture 8.6% SLOWER** | + +Identical results (max rel diff 4.1e-7, Float32 atomic ordering). + +**[D] Mechanism.** In the N-body loop every lane reads the *same* address (`sxj[j]`), and a +shared-memory broadcast costs one cycle. A texture fetch goes through the texture cache at higher +latency. Replacing a free broadcast with a cached fetch can only lose. + +### Calibration against CADISHI — we are NOT structurally behind **[M]** + +The obvious objection: if constant memory does nothing, how did CADISHI reach ~495 bapps? Answer: +**that figure is for a pure distance histogram** — one *integer* atomic, no velocity increments, no +float accumulation. Measured here with a comparable kernel (thread owns `i` in registers, streams the +`j` tile from shared, `UInt32` shared histogram, 32 bins, N=20000, Float32, full N² ordered pairs): + +| TILE | time | bapps | +|---|---|---| +| **256** | 1.086 ms | **368.3** | +| 512 | 1.134 | 352.7 | +| 1024 | 1.188 | 336.7 | +| 2048 | 1.238 | 323.0 | +| 4096 | 4.902 | 81.6 | + +- **Our pure-distance rate is 368 bapps vs their ~495 on an older GPU generation — 1.35×, not a + structural gap.** For comparable work we are near parity. +- **Larger tiles are monotonically WORSE.** This refutes the plausible story that constant memory's + real value is a 20× bigger tile (5333 points vs 256): a bigger tile does not help *us* even when + shared memory can hold it, so the 64 KB constant bank buys nothing on that axis either. +- Our real sp1d workload runs ~105 bapps. The **3.5× ratio to 368 is the cost of the physics** + (`du`, `du·dx`, `|du|²`, 4 float atomics vs 1 integer atomic), consistent with the §2 cost model — + not an implementation deficiency. + +**[M] Correction to an earlier estimate in this session:** a first pass put our pure-distance rate at +~99 bapps and concluded we were 5× behind CADISHI. That kernel used a *float* atomic and parallelised +only over `lid <= ni`, so it was not a fair pure-distance comparison. The properly structured kernel +gives 368. Do not cite the 99 figure. + +## 8. Register pressure is the binding constraint in 1D, and nobody has attacked it **[M]** + +| | time | regs/thread | shared/block | blocks/SM (reg) | blocks/SM (shared) | +|---|---|---|---|---|---| +| Float64 | 5.75 ms | 48 | 14,848 B | **5** | 11 | +| Float32 | 4.77 ms | 46 | 7,680 B | **5** | 21 | + +`ncu` confirms: `launch__occupancy_limit_registers = 5`, `_shared_mem = 6`, `_warps = 8`; achieved +`sm__warps_active = 61.3%` vs 62.5% predicted. `gpu__dram_throughput = 0.01%` — **not** memory-bound. +`sm__throughput = 76.5%`. Local memory 0, so no spilling. + +Getting to 40 regs/thread → 6 blocks/SM (75% occupancy); to 32 → 8 blocks (100%). Float32 halves +shared and removes the Float64 16-slot bank floor (32 banks ÷ 2 words per Float64 = 16 independent +slots, forcing ≥2-way serialization for a 32-lane warp) yet gains only 1.2× — **confirming bank +conflicts are not the dominant term and register-limited occupancy is.** + +## 8b. DEAD LEVER — occupancy is not the bottleneck **[M]** + +§8 showed the sp1d kernel is register-limited, which *looks* like the obvious thing to attack. It is +not. Measured after the reroute, on the CUDA N-body kernel (N=20000): + +| | regs | shared | blocks/SM | occupancy | +|---|---|---|---|---| +| Float32 | 38 | 11,776 B | 6 (reg-limited) | 75% | +| Float64 | 56 | 23,040 B | 4 (reg-limited) | 50% | + +Capping registers with `maxregs` on the `@cuda` launch, sweeping the cap (Float64): + +| maxregs | regs | blocks/SM | occupancy | time | +|---|---|---|---|---| +| default | 56 | 4 | 50% | 4.58 ms | +| 51 | 51 | 5 | 62.5% | 4.56 ms | +| 42 | 42 | 6 | 75% | 4.43 ms | +| 38 | 38 | 6 | 75% | 4.44 ms | +| 32 | 32 | 8 | 100% | 4.45 ms | + +**`local memory / thread = 0` at every setting** — ptxas never spills, it rematerializes. So this is +a clean occupancy experiment with no spill confound, and **doubling occupancy from 50% to 100% buys +at most ~3%**; 75% → 100% buys nothing. + +A careful 25-sample rerun of default vs `maxregs=42` is ambiguous — `min` 4.156 vs 4.306 (default +better), `median` 4.489 vs 4.333 and `mean` 4.444 vs 4.343 (cap better), against a default `std` of +0.145 ms. The metrics disagree and the effect is inside run-to-run variability. + +**Conclusion: not applied, and register reduction is dead as a major lever.** The ~44% non-atomic +share of §2 is *not* recoverable through occupancy — it is latency/instruction-bound work. Do not +re-run this sweep; it costs GPU time and the answer is here. + +## 8c. SP2D bin-count sweep: a 3× cliff, a hard failure, and a test-coverage hole **[M]** + +Nobody had swept the bin count. Every prior SP2D measurement in this repo (mine included) used +32×16 or 50×50. Sweeping it (N=8000, full pipeline, A100): + +| FT | bins | bapps | shared | kernel actually used | +|---|---|---|---|---| +| F32 | 32×16 | 7.6 | 58,880 | `_cuda_sf_2d_kernel` (CUDA fast path) | +| F32 | 64×64 | **5.6** | 45,192 | KA `sp2d_typeplane` (on-chip) | +| F32 | 100×100 | **1.9** | 4,200 | `sp2d_directpartition` ← **3× cliff** | +| F32 | 128×128 | 1.1 | 4,200 | `sp2d_directpartition` | +| F64 | 32×16 | 10.6 | 71,936 | CUDA fast path | +| F64 | 64×64 | **4.1** | 8,296 | `directpartition` ← cliff arrives earlier | + +### BUG FIXED — SP2D threw for any `n_dist > 128` **[M]** + +At ≥160×160 the call died with +`ArgumentError: naive single-pass 2D linear+linear requires vector value workspace` +(`ext/gpu/launch.jl`). Cause: `n_dist > SF_GPU_MAX_BINS` makes the tiled path ineligible, leaving +only the naive global kernel, which digitizes the value axis by binary search and demanded +`workspace.value_edges_sp2d_dev`. With no workspace supplied — the default — every large-bin call +failed outright. Fixed by reconstructing the edge vector from the linear plan's `first`/`last` +(the same allocate-on-demand pattern the general-bins routes already use). + +Verified at 160×160 and 200×200 vs a CPU serial reference: **Σcounts exact**, Float64 sums to +1.7e-15 / 2.3e-15. + +**Float32 shows 1.2–3.9% error there — and that is Float32, not the path.** Control: + +| moment | CPU32 vs CPU64 | GPU32 vs CPU32 | GPU64 vs CPU64 | +|---|---|---|---| +| S2 | 1.67e-2 | 1.67e-2 | 4.5e-16 | +| L1T2 | 5.00e-2 | 3.87e-2 | 1.6e-15 | + +The *CPU* in Float32 already differs from Float64 by 1.7–5.0%. A 160×160 histogram at N=1200 is +~28 pairs/cell with cancelling odd moments — beyond Float32's ~7 digits. **Use Float64 for large 2D +bin counts.** Always run this control before attributing a Float32 discrepancy to a code path. + +### Why this was invisible: the test suite never goes there **[M]** + +Audited `test/`: the largest 2D configuration tested anywhere is **60×60** +(`n_dist_bins`/`n_val_bins` ≤ 60); nothing exceeds ~128 bins on an axis except one *1D* over-cap +test. And **no test asserts which kernel or strategy runs.** So both the 3× routing cliff and the +outright failure sat in a regime that is neither tested nor benchmarked. + +**Actionable gap:** add SP2D cases at 100×100 and 200×200 (Float64 for the sums check), and assert +the selected `SP2DAccumulationStrategy` mode where it matters, so a routing regression is visible. + +### RESOLVED — route `:direct` to plain global atomics above a measured byte threshold **[M]** + +Two candidate fixes were implemented and measured; **the simpler one won and the clever one was +reverted.** + +1. **CUDA typeplane mode (implemented, measured, REVERTED).** Splitting the histogram into moment + planes so the CUDA fast kernel stays on chip gave 100×100 → 3.2 bapps and 128×128 → 3.1, i.e. + 1.68–2.8× over `:direct`. But plain global atomics reach 4.4–4.8 there, so typeplane was ~1.5× + *slower than doing nothing clever*. Reverted rather than left in the tree as a slower path; + `_cuda_2d_pick_tile` keeps its original all-or-nothing test, now documented as deliberate. +2. **Routing (adopted).** `:direct` abandons the on-chip histogram for block-private global + partitions plus a merge, so its cost grows with cells × tile-blocks, while plain global atomics get + *cheaper* as more cells spread contention. Above `SP2D_GLOBAL_ATOMIC_HIST_BYTES = 340 KB` + (`ext/gpu/sp2d_accumulation_strategy.jl`) `_launch_single_pass_2d!` routes past `:direct`. + +| FT | bins | before | after | | kernel after | +|---|---|---|---|---|---| +| F32 | 32×16 | 7.6 | 7.6 | — | CUDA on-chip | +| F32 | 64×64 | 5.6 | 5.6 | — | `:typeplane` | +| F32 | 100×100 | 1.9 | **4.4** | 2.3× | naive | +| F32 | 128×128 | 1.1 | **4.8** | 4.4× | naive | +| F64 | 100×100 | 1.9 | **4.3** | 2.3× | naive | +| F64 | 128×128 | 1.1 | **3.5** | 3.2× | naive | +| both | 160×160 / 200×200 | ERROR | 4.4–7.1 | — | naive (§8c bug fix) | + +**Why a threshold rather than "always skip `:direct`":** an unconditional skip made `:direct` — the +63-kernel template in `kernels_2d_direct.jl`, its partition buffers and merge kernels — unreachable, +and it overfits one device (the doc notes L40 has 100 KB and V100 96 KB of shared). The threshold +keeps `:direct` live below the crossover, where Float32 measured +11% for it, and captures every +measured win above. + +**[M] Noise caution.** Float64 64×64 measured 4.1 and 3.1 bapps in two runs of the *same* code path +(253 KB < threshold, so untouched by this change). Run-to-run spread on that configuration is ~25%; +do not read differences below ~1.3× from single runs here. + +### Superseded: "the CUDA 2D fast path has no typeplane mode" **[M]** + +`_cuda_2d_pick_tile` requires the *whole* 6-moment histogram to fit +(`dynb = NMOM * n_dist * val_stride * (sizeof(FT)+4)`); otherwise it returns `TILE == 0` and declines +entirely, dropping to the KA path capped at 48 KB static and then to `directpartition`. +`grep -c typeplane ext/cuda/kernels_2d.jl` = **0**, while the KA path *does* have typeplane — and +typeplane is the mode beating directpartition 5.6 vs 1.9 bapps. + +One plane at 64×64 Float32 is `1 × 64 × 65 × 8 = 32.5 KB`, plus 32 KB staging = 65 KB against a +163 KB opt-in — room for ~3 planes per pass. **Estimated ~3× in the 100×100–128×128 regime.** Kill +criterion: if a CUDA typeplane does not beat `directpartition`'s 1.9 bapps at 100×100, drop it. + +## 8d. DEAD LEVER — `rsqrt` in place of `sqrt` + divide **[M]** + +The flat per-pair path computes `r = sqrt(dot(dx,dx))` (`pair_frame`) and then `dot(δu, frame) / r` +(`pair_invariants`) — one `sqrt` plus one IEEE divide. `r` is needed only for the bin and `1/r` only +for `δu_L`, so both can in principle collapse into a single `rsqrt`: bin from `r²` (the CPU already +does this via `squared_digitize_plan`), and get `δu_L = dot(δu,dx) * inv_r`. + +Measured with two otherwise-identical N-body kernels (TILE=256, N=20000, 32 bins, A100): + +| | sqrt + divide | rsqrt | ratio | +|---|---|---|---| +| Float32 | 4.031 ms (99.2 bapps) | 4.150 ms (96.4) | **0.97× — slower** | +| Float64 | 6.644 ms (60.2 bapps) | 6.533 ms (61.2) | 1.02× — noise | + +**No gain.** Consistent with §2: the ~44% non-atomic share is dominated by shared-memory loads and +loop overhead, not by the two transcendental ops, so removing one of them is invisible. Do not retry. + +## 8e. `:typeplane` earns its complexity **[M]** + +After the §7 routing change `:typeplane` survives in a narrow band, so it was worth asking whether it +still pays. At its operating point (Float32 64×64, 4096 cells) it measures **7.27 bapps vs 3.05 for +plain global atomics** — a 2.4× win. Keep it. + +## 8f. Test coverage closed, and it immediately caught a bug **[M]** + +§8c identified that nothing in the suite exercised 2D bin counts past 60×60 and that no test asserted +*which* kernel ran. Added to `test/test_gpu_sp2d_partitioned.jl`: + +- **`GPU sp2d large bin counts`** — 100×100 and 200×200 against a CPU serial reference, no workspace + (the configuration that used to raise `ArgumentError`), Float64 because Float32 disagrees with a + Float64 reference by percent in this sparse regime even on the CPU (§8c). +- **`GPU sp2d strategy routing thresholds`** — asserts the byte crossover directly: 60×60 Float64 and + 80×80 Float32 below it, 100×100 Float64 and 128×128 Float32 above it. + +**It found a real hole in the §7 fix on its first run.** The routing handled `GPUValueLinearShared` +but not the per-moment `GPUValueLinearCols` plan produced by an NTuple of value bins: above 128 bins +the global-atomic kernel has no method for it and the tiled fallback is ineligible, so it threw +`ArgumentError`. Root cause was the rule being **split across two places** — the value-plan builder +in `_gpu_run_single_pass_2d!` and the launcher in `_launch_single_pass_2d!` — which could disagree. +Both now consult one `_sp2d_prefers_global_atomics` predicate, and the plan builder produces +`GPUValueVectorCols` exactly when the launcher will route global. + +## 9. Ordered exploration plan + +Ordered by (expected gain) / (risk × effort). Each step states its own kill criterion. + +1. ~~**Lever A, 6→4 moment atomics**~~ — **DONE (§3).** GPU 1.18×, CPU 1.31×, KA path done. (§3). Exact algebra, contained change, ~1.4× expected on an + atomic-bound kernel. Kill if FP32 `T2`/`L1T2` error exceeds current tolerance on a turbulence + field; fall back to FP64-only or partial reduction. +2. ~~**Per-regime A/B of non-batch → regime dispatcher**~~ — **DONE (§6, §6b).** 1.16–2.57×; 1D-individual deliberately excluded. (§6). No new kernels; 1.24–1.58× where it + wins. Kill per regime where it loses — expected to lose on 1D-individual-fixed-x. +3. ~~**Register reduction to lift occupancy**~~ — **DEAD, measured (§8b).** 50% → 100% occupancy + buys ≤3% and the metrics disagree at that scale. Not occupancy-bound. +4. **Spatial sort + run-length accumulation, then warp aggregation** (§4). Bounded by the ~2× of + §2 for the atomic part — but it *also* unlocks tile culling, whose ceiling is set by the in-range + pair fraction (0.75% at `r_max/L=0.05` **[M]**) and is therefore much larger when `r_max` is + small. Subsumes the cell-list item. Kill if mean run length < 2 on a non-uniform field. +5. ~~**Constant/texture staging for SP2D**~~ — **DEAD, measured (§7).** Float64 textures do not + exist in hardware, and Float32 SP2D is register-limited, not shared-limited, so freeing the + staging gains no occupancy. + +**Benchmark discipline** (learned the hard way, and worth repeating): always benchmark with the +production bin/value-plan types — a general binary-search fallback misrepresents the hot loop by +~3× **[I]**. Always compare Float32 *and* Float64; they are bound by different resources **[M]**. +And verify equivalence, not just speed, before reporting any win. diff --git a/gpu/bench_1d_old_vs_nbody.jl b/gpu/bench_1d_old_vs_nbody.jl index c8f8b78..e153e73 100644 --- a/gpu/bench_1d_old_vs_nbody.jl +++ b/gpu/bench_1d_old_vs_nbody.jl @@ -1,9 +1,14 @@ # ============================================================================= -# Head-to-head: OLD batch launchers (global warp-replica + W-strip + merge) vs -# NEW CUDA N-body kernels, for the 1D regimes, at the SAME config (N=20000). -# Decides per-regime routing for "optimal everywhere". Also verifies the two -# produce equal histograms. +# Head-to-head for the ONE 1D regime where the routing choice is still live: +# fixed-x individual SF, where the warp-replica strip kernel beats the CUDA +# N-body kernel (tiny-histogram, contention-bound). Verifies equal histograms. # julia --project=gpu gpu/bench_1d_old_vs_nbody.jl +# +# The other regimes were measured head-to-head and are no longer a choice — the +# losing launchers were unreachable from production and have been deleted: +# ind varying 61 vs 115 bapps, SP1D fixed 30 vs 43, SP1D varying 28 vs 43, +# SP2D fixed 5 vs 25, SP2D varying 1 vs 25 (all: N-body/unified wins). +# See gpu/OPTIMAL_KERNEL_DESIGN.md. # ============================================================================= using StructureFunctions import KernelAbstractions as KA @@ -11,7 +16,7 @@ using CUDA, Printf using Statistics: median const SF = StructureFunctions const SFC = SF.Calculations -const GE = Base.get_extension(SF, :StructureFunctionsGPUExt) +const GE = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) const SFT = SF.StructureFunctionTypes using StructureFunctions: LinearBinEdges const FT = Float32 @@ -21,52 +26,33 @@ const B = parse(Int, get(ENV, "SF_B", "64")) const NB = 50 const D = 2 const BE = CUDA.CUDABackend() -tput(t) = (N*(N-1)/2)*B/t/1e9 -bench(f) = (f(); f(); ts = Float64[]; for _ in 1:5; t = time_ns(); f(); push!(ts, (time_ns()-t)/1e9); end; median(ts)) +tput(t) = (N * (N - 1) / 2) * B / t / 1e9 +bench(f) = (f(); f(); ts = Float64[]; for _ in 1:5 + t = time_ns(); f(); push!(ts, (time_ns() - t) / 1e9) +end; median(ts)) lbe = LinearBinEdges(collect(range(0.05f0, 2.0f0; length = NB + 1))) dig = GE._sf_batch_dist_digitizer(BE, lbe) -x_fix = rand(FT, D, N); u = randn(FT, D, N, B); x_var = rand(FT, D, N, B) +x_fix = rand(FT, D, N); u = randn(FT, D, N, B) -println("OLD vs N-body, 1D, N=$N B=$B NB=$NB\n") -println("| regime | old bapps (s@8064) | nbody bapps (s@8064) | winner | equal? |") +println("warp-replica strip vs N-body, 1D individual fixed-x, N=$N B=$B NB=$NB\n") +println("| regime | strip bapps (s@8064) | nbody bapps (s@8064) | winner | equal? |") -# ---- individual fixed (NMOM=1) ---- let xo, uo = GE._stage_batch_device(BE, x_fix, u; fixed_x = true) so = CUDA.zeros(FT, NB, B); co = CUDA.zeros(UInt32, NB, B) - fo() = (CUDA.fill!(so,0f0); CUDA.fill!(co,UInt32(0)); GE._launch_batch_fixed_x_sf!(BE, so, co, xo, uo, sf2, N, B, lbe); CUDA.synchronize()) + fo() = (CUDA.fill!(so, 0f0); CUDA.fill!(co, UInt32(0)); + GE._launch_batch_fixed_x_sf!(BE, so, co, xo, uo, sf2, N, B, lbe); CUDA.synchronize()) to = bench(fo) - xn = CuArray(x_fix); un = CuArray(u); sn = CUDA.zeros(FT,1,NB,B); cn = CUDA.zeros(UInt32,1,NB,B) - fn() = (CUDA.fill!(sn,0f0); CUDA.fill!(cn,UInt32(0)); SFC.gpu_fast_launch_1d_batch!(BE, sn, cn, xn, un, sf2, dig, N, NB, B, D, 1, true); CUDA.synchronize()) + xn = CuArray(x_fix); un = CuArray(u) + sn = CUDA.zeros(FT, 1, NB, B); cn = CUDA.zeros(UInt32, 1, NB, B) + fn() = (CUDA.fill!(sn, 0f0); CUDA.fill!(cn, UInt32(0)); + SFC.gpu_fast_launch_1d_batch!(BE, sn, cn, xn, un, sf2, dig, N, NB, B, D, 1, true); + CUDA.synchronize()) tn = bench(fn) eq = Array(co) == reshape(Array(cn), NB, B) - @printf("| ind fixed | %.0f (%.1f) | %.0f (%.1f) | %s | %s |\n", tput(to), to*8064/B, tput(tn), tn*8064/B, tput(to)>tput(tn) ? "OLD" : "nbody", eq) -end - -# ---- individual varying (NMOM=1) ---- -let - xo, uo = GE._stage_batch_device(BE, x_var, u; fixed_x = false) - so = CUDA.zeros(FT, NB, B); co = CUDA.zeros(UInt32, NB, B) - fo() = (CUDA.fill!(so,0f0); CUDA.fill!(co,UInt32(0)); GE._launch_batch_varying_x_sf!(BE, so, co, xo, uo, sf2, N, B, lbe); CUDA.synchronize()) - to = bench(fo) - xn = CuArray(x_var); un = CuArray(u); sn = CUDA.zeros(FT,1,NB,B); cn = CUDA.zeros(UInt32,1,NB,B) - fn() = (CUDA.fill!(sn,0f0); CUDA.fill!(cn,UInt32(0)); SFC.gpu_fast_launch_1d_batch!(BE, sn, cn, xn, un, sf2, dig, N, NB, B, D, 1, false); CUDA.synchronize()) - tn = bench(fn) - eq = Array(co) == reshape(Array(cn), NB, B) - @printf("| ind varying | %.0f (%.1f) | %.0f (%.1f) | %s | %s |\n", tput(to), to*8064/B, tput(tn), tn*8064/B, tput(to)>tput(tn) ? "OLD" : "nbody", eq) -end - -# ---- SP1D fixed (NMOM=6) ---- -let - xo, uo = GE._stage_batch_device(BE, x_fix, u; fixed_x = true) - so = CUDA.zeros(FT, 6, NB, B); co = CUDA.zeros(UInt32, 6, NB, B) - fo() = (CUDA.fill!(so,0f0); CUDA.fill!(co,UInt32(0)); GE._launch_batch_fixed_x_sp1d!(BE, so, co, xo, uo, N, B, lbe); CUDA.synchronize()) - to = bench(fo) - xn = CuArray(x_fix); un = CuArray(u); sn = CUDA.zeros(FT,6,NB,B); cn = CUDA.zeros(UInt32,6,NB,B) - fn() = (CUDA.fill!(sn,0f0); CUDA.fill!(cn,UInt32(0)); SFC.gpu_fast_launch_1d_batch!(BE, sn, cn, xn, un, sf2, dig, N, NB, B, D, 6, true); CUDA.synchronize()) - tn = bench(fn) - eq = Array(co) == Array(cn) - @printf("| SP1D fixed | %.0f (%.1f) | %.0f (%.1f) | %s | %s |\n", tput(to), to*8064/B, tput(tn), tn*8064/B, tput(to)>tput(tn) ? "OLD" : "nbody", eq) + @printf("| ind fixed | %.0f (%.1f) | %.0f (%.1f) | %s | %s |\n", + tput(to), to * 8064 / B, tput(tn), tn * 8064 / B, + tput(to) > tput(tn) ? "strip" : "nbody", eq) end println("\nDONE_BENCH") diff --git a/gpu/benchmark_2d_grid_scaling.jl b/gpu/benchmark_2d_grid_scaling.jl index bbc64a2..cfb8b5c 100644 --- a/gpu/benchmark_2d_grid_scaling.jl +++ b/gpu/benchmark_2d_grid_scaling.jl @@ -24,6 +24,7 @@ Run on GPU: N_DIST=50 N_VAL=50 julia --project=gpu gpu/benchmark_2d_grid_scaling.jl """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using OhMyThreads: OhMyThreads @@ -60,8 +61,8 @@ end using Dates: Dates -const _GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) -_GPUExt === nothing && error("StructureFunctionsGPUExt not loaded — activate gpu project with CUDA") +const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) +_GPUExt === nothing && error("StructureFunctionsKernelAbstractionsExt not loaded — activate gpu project with CUDA") function main() CUDA.functional() || error("CUDA not functional") @@ -73,7 +74,7 @@ function main() repeat_ = parse(Int, get(ENV, "REPEAT", "5")) FT = Float32 backend = CUDA.CUDABackend() - gpu = SF.GPUBackend(backend) + gpu = CB.GPUBackend(backend) dist = _dist_bins(n_dist, FT) value_bins = _value_shared(n_val_inner, FT) diff --git a/gpu/benchmark_batch_matrix.jl b/gpu/benchmark_batch_matrix.jl index d3c853c..ed0006a 100644 --- a/gpu/benchmark_batch_matrix.jl +++ b/gpu/benchmark_batch_matrix.jl @@ -14,6 +14,7 @@ # # The explicit slice baselines in this file are GPU baselines. CPU serial baselines # belong in CPU benchmark scripts and are intentionally not mixed into this matrix. +using ComputationalBackends: ComputationalBackends as CB using Printf: @printf using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA @@ -66,17 +67,17 @@ end function _resolve_gpu_backend(backend) if backend !== nothing - backend isa SFC.GPUBackend && return backend, backend.backend - return SFC.GPUBackend(backend), backend + backend isa CB.GPUBackend && return backend, backend.backend + return CB.GPUBackend(backend), backend end if CUDA.functional() ka_backend = CUDA.CUDABackend() println("backend: CUDA ($(CUDA.name(CUDA.device())))") - return SFC.GPUBackend(ka_backend), ka_backend + return CB.GPUBackend(ka_backend), ka_backend end ka_backend = KA.CPU() println("backend: KA.CPU (CUDA not functional)") - return SFC.GPUBackend(ka_backend), ka_backend + return CB.GPUBackend(ka_backend), ka_backend end function _bench_row(label::String, f::Function, ka_backend; warmup::Int = 1) @@ -129,8 +130,7 @@ function _bench_explicit_gpu_shared_loop( () -> begin @views for b in sample_indices SFC.gpu_calculate_structure_function( - sf, ka_backend, xd, ud[:, :, b], edges; - return_sums_and_counts = true, + sf, ka_backend, xd, ud[:, :, b], edges ) end end, @@ -186,8 +186,7 @@ function _bench_explicit_gpu_varying_sf_loop( () -> begin @views for b in sample_indices SFC.gpu_calculate_structure_function( - sf, ka_backend, xd[:, :, b], ud[:, :, b], edges; - return_sums_and_counts = true, + sf, ka_backend, xd[:, :, b], ud[:, :, b], edges ) end end, @@ -349,7 +348,7 @@ function run_batch_matrix_benchmark(; push!(rows, :individual_fixed => _bench_row("individual 1D fixed-x (GPU batch)", () -> begin SFC.calculate_structure_function( sf, x_fix, u_fix, edges; - backend = gpu_backend, return_sums_and_counts = true, verbose = false, + backend = gpu_backend, verbose = false, ) end, ka_backend; warmup = warmup)) end @@ -488,7 +487,7 @@ function run_batch_matrix_benchmark(; push!(rows, :joint2d_fixed => _bench_row("joint 2D single-type fixed-x (GPU batch)", () -> begin SFC.calculate_structure_function( sf, x_fix, u_fix, edges, val_edges; - backend = gpu_backend, return_sums_and_counts = true, verbose = false, + backend = gpu_backend, verbose = false, ) end, ka_backend; warmup = warmup)) end diff --git a/gpu/benchmark_cuda.jl b/gpu/benchmark_cuda.jl index bd8faf8..04b6916 100644 --- a/gpu/benchmark_cuda.jl +++ b/gpu/benchmark_cuda.jl @@ -4,7 +4,7 @@ GPU vs CPU timing at the **same** N, bins, and SF type. Compares three backends: - - `ThreadedBackend()` — production CPU path (same as `benchmark/benchmark_worker.jl`) + - `CB.ThreadedBackend()` — production CPU path (same as `benchmark/benchmark_worker.jl`) - `KA.CPU()` — GPU extension kernel on CPU (parity reference only) - `CUDA.CUDABackend()` — GPU @@ -13,6 +13,7 @@ Run once per SLURM session. See `gpu/README.md`: include(joinpath("/path/to/StructureFunctions.jl", "gpu", "benchmark_cuda.jl")) """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using OhMyThreads: OhMyThreads @@ -42,7 +43,7 @@ function main() bin_edges = LinearBinEdges(range(FT(0.1), FT(2.0); length = 21)) sft = SFT.L2SFType() - threaded_backend = SFC.ThreadedBackend() + threaded_backend = CB.ThreadedBackend() # Warmup SFC.calculate_structure_function( diff --git a/gpu/benchmark_joint2d_diagnose.jl b/gpu/benchmark_joint2d_diagnose.jl index d6eef10..ccc72ec 100644 --- a/gpu/benchmark_joint2d_diagnose.jl +++ b/gpu/benchmark_joint2d_diagnose.jl @@ -20,8 +20,8 @@ using StructureFunctions.Calculations: Calculations as SFC using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges, joint2d_smem_max using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT -const _GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) -_GPUExt === nothing && error("StructureFunctionsGPUExt not loaded") +const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) +_GPUExt === nothing && error("StructureFunctionsKernelAbstractionsExt not loaded") function _dist_bins(n_dist::Int, ::Type{FT}) where {FT} return LogBinEdges(Vector{FT}(exp.(range(log(FT(1000)), log(FT(50000)); length = n_dist + 1)))) diff --git a/gpu/benchmark_joint_value_route_ab.jl b/gpu/benchmark_joint_value_route_ab.jl index b98badd..f6d2e31 100644 --- a/gpu/benchmark_joint_value_route_ab.jl +++ b/gpu/benchmark_joint_value_route_ab.jl @@ -17,6 +17,7 @@ For isolated digitize impact at larger B, also run: julia --project=gpu gpu/benchmark_value_axis_dispatch.jl """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using Printf: @printf @@ -26,8 +27,8 @@ using StructureFunctions.Calculations: Calculations as SFC using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT -const _GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) -_GPUExt === nothing && error("StructureFunctionsGPUExt not loaded — use julia --project=gpu") +const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) +_GPUExt === nothing && error("StructureFunctionsKernelAbstractionsExt not loaded — use julia --project=gpu") function _bench(f, warmup::Int, repeat_::Int) for _ in 1:warmup @@ -124,7 +125,7 @@ function main() if check_parity ref = SFC.calculate_structure_function( sft, x, u, dist, val_typed; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) gpu_t = SFC.gpu_calculate_structure_function_2d(sft, backend, x, u, dist, val_typed; workspace = ws_typed) gpu_g = SFC.gpu_calculate_structure_function_2d(sft, backend, x, u, dist, val_general; workspace = ws_general) diff --git a/gpu/benchmark_scaling_helpers.jl b/gpu/benchmark_scaling_helpers.jl index 5f50191..fbe4da7 100644 --- a/gpu/benchmark_scaling_helpers.jl +++ b/gpu/benchmark_scaling_helpers.jl @@ -7,6 +7,7 @@ Included by `benchmark_slices.jl`, `benchmark_workspace.jl`, and `collect_benchm Expects `CUDA` to be loaded by the including script when using `CUDA.CUDABackend()`. """ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: Calculations as SFC using Statistics: Statistics @@ -47,12 +48,12 @@ function bench_cpu_serial_sf(x_arr, u_arr, bins, sft; warmup::Int = 1) for _ in 1:warmup SFC.calculate_structure_function( sft, x_arr, u_arr, bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) end return @elapsed SFC.calculate_structure_function( sft, x_arr, u_arr, bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) end @@ -68,7 +69,7 @@ function bench_gpu_sf_with_workspace( for _ in 1:warmup SFC.gpu_calculate_structure_function( sft, backend, x_dev, u_dev, bins; - return_sums_and_counts = true, workspace = ws, + workspace = ws, ) end gpu_sync!(backend) @@ -76,7 +77,7 @@ function bench_gpu_sf_with_workspace( for _ in 1:repeat t = @elapsed SFC.gpu_calculate_structure_function( sft, backend, x_dev, u_dev, bins; - return_sums_and_counts = true, workspace = ws, + workspace = ws, ) gpu_sync!(backend) push!(times, t) @@ -92,14 +93,12 @@ Time one GPU call without workspace (fresh device histogram alloc each call). function bench_gpu_sf_fresh(backend, x_dev, u_dev, bins, sft; warmup::Int = 1) for _ in 1:warmup SFC.gpu_calculate_structure_function( - sft, backend, x_dev, u_dev, bins; - return_sums_and_counts = true, + sft, backend, x_dev, u_dev, bins ) end gpu_sync!(backend) t = @elapsed SFC.gpu_calculate_structure_function( - sft, backend, x_dev, u_dev, bins; - return_sums_and_counts = true, + sft, backend, x_dev, u_dev, bins ) gpu_sync!(backend) return t @@ -116,8 +115,7 @@ function bench_naive_slice_loop!( function run!() for t in 1:T res = SFC.gpu_calculate_structure_function( - sft, backend, x_host[:, :, t], u_host[:, :, t], bins; - return_sums_and_counts = true, + sft, backend, x_host[:, :, t], u_host[:, :, t], bins ) sums[:, t] .= res.sums counts[:, t] .= res.counts @@ -152,8 +150,7 @@ function bench_cpu_serial_slice_loop!(x_batch, u_batch, bins, sft, sums, counts; for t in 1:T res = SFC.calculate_structure_function( sft, @view(x_batch[:, :, t]), @view(u_batch[:, :, t]), bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, - return_sums_and_counts = true, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) sums[:, t] .= res.sums counts[:, t] .= res.counts diff --git a/gpu/benchmark_single_pass_2d_scaling.jl b/gpu/benchmark_single_pass_2d_scaling.jl index cbe6f44..971df76 100644 --- a/gpu/benchmark_single_pass_2d_scaling.jl +++ b/gpu/benchmark_single_pass_2d_scaling.jl @@ -12,6 +12,7 @@ Loads GPUExt the same way as ``gpu/benchmark_cuda.jl`` (CUDA + KernelAbstraction OhMyThreads + StructureFunctions). """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using OhMyThreads: OhMyThreads @@ -50,7 +51,7 @@ function main() repeat_ = parse(Int, get(ENV, "REPEAT", "3")) FT = get(ENV, "FT", "Float32") == "Float64" ? Float64 : Float32 ka_backend = CUDA.CUDABackend() - gpu_backend = SF.GPUBackend(ka_backend) + gpu_backend = CB.GPUBackend(ka_backend) println("=" ^ 72) println("Six-type single_pass_2d vs GPU reference kernels (T=1 hour each)") diff --git a/gpu/benchmark_slices.jl b/gpu/benchmark_slices.jl index 302d725..ff7d3d5 100644 --- a/gpu/benchmark_slices.jl +++ b/gpu/benchmark_slices.jl @@ -25,7 +25,6 @@ function bench_manual_loop!( for t in 1:T res = SFC.gpu_calculate_structure_function( sft, backend, view(x_batch, :, :, t), view(u_batch, :, :, t), bins; - return_sums_and_counts = true, workspace = ws, ) sums[:, t] .= res.sums diff --git a/gpu/benchmark_suite.jl b/gpu/benchmark_suite.jl index 1fef0db..63e49bc 100644 --- a/gpu/benchmark_suite.jl +++ b/gpu/benchmark_suite.jl @@ -19,6 +19,7 @@ Useful environment variables: - `WARMUP=1` """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using Dates: Dates using JSON: JSON @@ -81,8 +82,7 @@ end function _explicit_aux_loop_shared_positions(sft, backend, x, u, distance_bins) @views for b in axes(u, 3) SFC.gpu_calculate_structure_function( - sft, backend, x, u[:, :, b], distance_bins; return_sums_and_counts = true, - ) + sft, backend, x, u[:, :, b], distance_bins) end return nothing end @@ -90,8 +90,7 @@ end function _explicit_aux_loop_varying_positions(sft, backend, x, u, distance_bins) @views for b in axes(u, 3) SFC.gpu_calculate_structure_function( - sft, backend, x[:, :, b], u[:, :, b], distance_bins; return_sums_and_counts = true, - ) + sft, backend, x[:, :, b], u[:, :, b], distance_bins) end return nothing end @@ -124,16 +123,16 @@ function main() ws1d = SFC.GPUSFWorkspace(backend, dist_bins) push!(rows, _timed("sf1d_fresh", backend, () -> begin - SFC.gpu_calculate_structure_function(sft, backend, xd, ud, dist_bins; return_sums_and_counts = true) + SFC.gpu_calculate_structure_function(sft, backend, xd, ud, dist_bins) end; warmup = warmup, repeat = repeat)) push!(rows, _timed("sf1d_workspace", backend, () -> begin SFC.gpu_calculate_structure_function( - sft, backend, xd, ud, dist_bins; return_sums_and_counts = true, workspace = ws1d, + sft, backend, xd, ud, dist_bins; workspace = ws1d, ) end; warmup = warmup, repeat = repeat)) push!(rows, _timed("sf1d_3d_workspace", backend, () -> begin SFC.gpu_calculate_structure_function( - sft, backend, xd3, ud3, dist_bins; return_sums_and_counts = true, workspace = ws1d, + sft, backend, xd3, ud3, dist_bins; workspace = ws1d, ) end; warmup = warmup, repeat = repeat)) @@ -153,7 +152,7 @@ function main() push!(rows, _timed("aux_shared_positions_sf1d", backend, () -> begin SFC.calculate_structure_function( sft, xd_shared, ud_shared, dist_bins; - backend = SFC.GPUBackend(backend), return_sums_and_counts = true, verbose = false, + backend = CB.GPUBackend(backend), verbose = false, ) end; warmup = warmup, repeat = repeat)) push!(rows, _timed("aux_shared_positions_explicit_loop", backend, () -> begin @@ -167,7 +166,7 @@ function main() push!(rows, _timed("aux_varying_positions_sf1d", backend, () -> begin SFC.calculate_structure_function( sft, xd_varying, ud_varying, dist_bins; - backend = SFC.GPUBackend(backend), return_sums_and_counts = true, verbose = false, + backend = CB.GPUBackend(backend), verbose = false, ) end; warmup = warmup, repeat = repeat)) push!(rows, _timed("aux_varying_positions_explicit_loop", backend, () -> begin diff --git a/gpu/benchmark_value_axis_dispatch.jl b/gpu/benchmark_value_axis_dispatch.jl index aacc480..7e17a7d 100644 --- a/gpu/benchmark_value_axis_dispatch.jl +++ b/gpu/benchmark_value_axis_dispatch.jl @@ -16,6 +16,7 @@ Scenarios (log distance bins, N≈20k–30k): - `vector_cols` — eight raw edge vectors (binary search fallback) """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using OhMyThreads: OhMyThreads @@ -79,7 +80,7 @@ function main() repeat_ = parse(Int, get(ENV, "REPEAT", "5")) FT = get(ENV, "FT", "Float32") == "Float64" ? Float64 : Float32 ka_backend = CUDA.CUDABackend() - gpu_backend = SF.GPUBackend(ka_backend) + gpu_backend = CB.GPUBackend(ka_backend) println("=" ^ 72) println("Single-pass 2D value-axis dispatch benchmark (CUDA)") diff --git a/gpu/collect_benchmark_assets.jl b/gpu/collect_benchmark_assets.jl index 40471fd..15a85ec 100644 --- a/gpu/collect_benchmark_assets.jl +++ b/gpu/collect_benchmark_assets.jl @@ -56,7 +56,7 @@ function _warmup_gpu_session!(backend, warmup::Int) for _ in 1:warmup SFC.gpu_calculate_structure_function( SCALING_SFT, backend, x_dev, u_dev, bins; - return_sums_and_counts = true, workspace = ws, + workspace = ws, ) end gpu_sync!(backend) diff --git a/gpu/plot_cuda_parity.jl b/gpu/plot_cuda_parity.jl index a2fd170..d18b99d 100644 --- a/gpu/plot_cuda_parity.jl +++ b/gpu/plot_cuda_parity.jl @@ -12,7 +12,8 @@ on the same small problem as `test_cuda_parity.jl`. using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: - StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT + StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO using Random: Random function main() @@ -30,10 +31,11 @@ function main() ref = SFC.calculate_structure_function( sft, x_cpu, u_cpu, bins; - return_sums_and_counts = true, verbose = false, show_progress = false, + output_type = SFO.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false, ) gpu_res = SFC.gpu_calculate_structure_function( - sft, CUDA.CUDABackend(), x_gpu, u_gpu, bins; return_sums_and_counts = true, + sft, CUDA.CUDABackend(), x_gpu, u_gpu, bins, ) CUDA.synchronize() diff --git a/gpu/profile_joint2d.jl b/gpu/profile_joint2d.jl index 0369ff3..c4bee6c 100644 --- a/gpu/profile_joint2d.jl +++ b/gpu/profile_joint2d.jl @@ -35,8 +35,8 @@ using StructureFunctions.Calculations: Calculations as SFC using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT -const _GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) -_GPUExt === nothing && error("StructureFunctionsGPUExt not loaded — use julia --project=gpu") +const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) +_GPUExt === nothing && error("StructureFunctionsKernelAbstractionsExt not loaded — use julia --project=gpu") function _bench(f, warmup::Int, repeat_::Int) for _ in 1:warmup diff --git a/gpu/profile_joint2d_ncu.jl b/gpu/profile_joint2d_ncu.jl index 32711b2..a84cbaa 100644 --- a/gpu/profile_joint2d_ncu.jl +++ b/gpu/profile_joint2d_ncu.jl @@ -18,15 +18,15 @@ Environment: using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA -using Printf: @printf, @sprintf +using Printf: Printf using Random: Random using StructureFunctions: StructureFunctions as SF using StructureFunctions.Calculations: Calculations as SFC using StructureFunctions: InfPaddedBinEdges, LinearBinEdges, LogBinEdges, joint2d_smem_max using StructureFunctions.StructureFunctionTypes: StructureFunctionTypes as SFT -const _GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) -_GPUExt === nothing && error("StructureFunctionsGPUExt not loaded — use julia --project=gpu") +const _GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) +_GPUExt === nothing && error("StructureFunctionsKernelAbstractionsExt not loaded — use julia --project=gpu") function _dist_bins(n_dist::Int, ::Type{FT}) where {FT} return LogBinEdges(Vector{FT}(exp.(range(log(FT(1000)), log(FT(50000)); length = n_dist + 1)))) @@ -96,7 +96,7 @@ function main() dist_r = _GPUExt._joint2d_dist_route(ws.dist_bins) val_r = _GPUExt._joint2d_val_route(ws.val_plan) gpu_fn = ws.joint2d_kernel === nothing ? :unknown : nameof(ws.joint2d_kernel.f) - msg = @sprintf( + msg = Printf.@sprintf( "ncu workload: N=%d n_dist=%d n_val=%d NB2=%d route=%s/%s compile_cells=%d prewarm=%d gpu_fn=%s", N, n_dist, length(value_bins) - 1, nb2, dist_r, val_r, ws.joint2d_compile_cells, prewarm, gpu_fn, ) diff --git a/gpu/smoke_cuda.jl b/gpu/smoke_cuda.jl index 8b24638..7f66244 100644 --- a/gpu/smoke_cuda.jl +++ b/gpu/smoke_cuda.jl @@ -8,6 +8,7 @@ Run from the repository root: julia --project=gpu gpu/smoke_cuda.jl """ +using ComputationalBackends: ComputationalBackends as CB using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: @@ -38,8 +39,7 @@ function main() sft = SFT.L2SFType() res = SFC.gpu_calculate_structure_function( - sft, CUDA.CUDABackend(), x, u, bin_edges; - return_sums_and_counts = true, + sft, CUDA.CUDABackend(), x, u, bin_edges ) CUDA.synchronize() @@ -48,7 +48,7 @@ function main() println("Total pair count: ", n_pairs) println("Max bin sum: ", maximum(res.sums)) - backend = SF.GPUBackend(CUDA.CUDABackend()) + backend = CB.GPUBackend(CUDA.CUDABackend()) x_cpu = Array(x) u_cpu = Array(u) result = SFC.calculate_structure_function( diff --git a/gpu/test_cuda_1d_parity.jl b/gpu/test_cuda_1d_parity.jl index 8338c54..0409a23 100644 --- a/gpu/test_cuda_1d_parity.jl +++ b/gpu/test_cuda_1d_parity.jl @@ -11,7 +11,7 @@ using CUDA, StaticArrays, Printf using Statistics: median const SF = StructureFunctions const SFC = SF.Calculations -const GE = Base.get_extension(SF, :StructureFunctionsGPUExt) +const GE = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) const SFT = SF.StructureFunctionTypes const FT = Float32 const N = parse(Int, get(ENV, "SF_T_N", "3000")) diff --git a/gpu/test_cuda_2d_parity.jl b/gpu/test_cuda_2d_parity.jl index 17cb328..5cd5059 100644 --- a/gpu/test_cuda_2d_parity.jl +++ b/gpu/test_cuda_2d_parity.jl @@ -11,7 +11,7 @@ using CUDA, StaticArrays, Printf using Statistics: median const SF = StructureFunctions const SFC = SF.Calculations -const GE = Base.get_extension(SF, :StructureFunctionsGPUExt) +const GE = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) const SFT = SF.StructureFunctionTypes const FT = Float32 diff --git a/gpu/test_cuda_parity.jl b/gpu/test_cuda_parity.jl index 34f89e4..4cfa6d9 100644 --- a/gpu/test_cuda_parity.jl +++ b/gpu/test_cuda_parity.jl @@ -7,12 +7,13 @@ against the serial CPU reference. Included by `runtests.jl`; not run from the main `test/` suite. """ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, - LinearBinEdges, LogBinEdges + StructureFunctionObjects as SFO, LinearBinEdges, LogBinEdges using Random: Random Random.seed!(42) @@ -34,12 +35,12 @@ Test.@testset "CUDA structure-function parity" begin sft, x_cpu, u_cpu, bin_edges; verbose = false, show_progress = false, - return_sums_and_counts = true, + output_type = SFO.StructureFunctionSumsAndCounts, ) + # The GPU 1D entry returns sums and counts unconditionally. res_cuda = SFC.gpu_calculate_structure_function( - sft, CUDA.CUDABackend(), x_gpu, u_gpu, bin_edges; - return_sums_and_counts = true, + sft, CUDA.CUDABackend(), x_gpu, u_gpu, bin_edges, ) CUDA.synchronize() @@ -70,12 +71,11 @@ Test.@testset "CUDA log-spaced bin parity" begin sft, x_cpu, u_cpu, bin_edges; verbose = false, show_progress = false, - return_sums_and_counts = true, + output_type = SFO.StructureFunctionSumsAndCounts, ) res_cuda = SFC.gpu_calculate_structure_function( - sft, CUDA.CUDABackend(), x_gpu, u_gpu, bin_edges; - return_sums_and_counts = true, + sft, CUDA.CUDABackend(), x_gpu, u_gpu, bin_edges, ) CUDA.synchronize() @@ -103,7 +103,7 @@ Test.@testset "CUDA joint 2D structure-function parity" begin ) gpu = SFC.calculate_structure_function( sft, x_cpu, u_cpu, distance_bins, value_bins; - backend = SF.GPUBackend(CUDA.CUDABackend()), + backend = CB.GPUBackend(CUDA.CUDABackend()), verbose = false, show_progress = false, ) CUDA.synchronize() @@ -128,12 +128,12 @@ Test.@testset "CUDA joint 2D log distance bins" begin ref = SFC.calculate_structure_function( sft, x_cpu, u_cpu, distance_bins, value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) gpu = SFC.calculate_structure_function( sft, x_cpu, u_cpu, distance_bins, value_bins; - backend = SF.GPUBackend(CUDA.CUDABackend()), + backend = CB.GPUBackend(CUDA.CUDABackend()), verbose = false, show_progress = false, ) CUDA.synchronize() @@ -165,13 +165,13 @@ Test.@testset "CUDA single-pass 2D parity" begin counts_ref = zeros(UInt32, size(sums_ref)) SFC.calculate_structure_functions_single_pass_2d!( sums_ref, counts_ref, x_cpu, u_cpu, distance_bins, value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) inv = (:S2, :L2, :T2, :S3, :L3, :L1T2) sp_gpu = SFC.calculate_structure_functions_single_pass_2d( x_cpu, u_cpu, distance_bins, value_bins; - backend = SF.GPUBackend(CUDA.CUDABackend()), + backend = CB.GPUBackend(CUDA.CUDABackend()), ) CUDA.synchronize() diff --git a/gpu/test_e2e_2d_cuda.jl b/gpu/test_e2e_2d_cuda.jl index 2335da9..8dccc43 100644 --- a/gpu/test_e2e_2d_cuda.jl +++ b/gpu/test_e2e_2d_cuda.jl @@ -4,6 +4,7 @@ # serial CPU reference, plus headline real-N (20000) SP2D 50x50 wall-clock. # julia --project=gpu gpu/test_e2e_2d_cuda.jl # ============================================================================= +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions import KernelAbstractions as KA using CUDA, Printf @@ -15,7 +16,7 @@ using StructureFunctions: LinearBinEdges using StructureFunctions.Calculations: serial_calculate_structure_functions_single_pass_2d!, auxiliary_joint2d! const FT = Float32 -const GPU_BE = SFC.GPUBackend(CUDA.CUDABackend()) +const GPU_BE = CB.GPUBackend(CUDA.CUDABackend()) const SF_TYPE = SFT.L2SFType() const SP2D_INV = (:S2, :L2, :T2, :S3, :L3, :L1T2) diff --git a/gpu/test_slices_e2e.jl b/gpu/test_slices_e2e.jl index 4ed3091..6ed8091 100644 --- a/gpu/test_slices_e2e.jl +++ b/gpu/test_slices_e2e.jl @@ -5,6 +5,7 @@ # loops is correct on GPU, plus timing. # julia --project=gpu gpu/test_slices_e2e.jl # ============================================================================= +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions import KernelAbstractions as KA using CUDA, Printf @@ -18,7 +19,7 @@ using StructureFunctions.Calculations: serial_calculate_structure_functions_single_pass_2d!, auxiliary_varying_positions!, auxiliary_joint2d! const FT = Float32 -const GPU_BE = SFC.GPUBackend(CUDA.CUDABackend()) +const GPU_BE = CB.GPUBackend(CUDA.CUDABackend()) const sf2 = SFT.L2SFType() maxrel(a, b) = maximum(abs.(a .- b) ./ max.(abs.(b), 1f-3)) diff --git a/gpu/test_workspace_cuda.jl b/gpu/test_workspace_cuda.jl index 0c38752..d643a0b 100644 --- a/gpu/test_workspace_cuda.jl +++ b/gpu/test_workspace_cuda.jl @@ -13,7 +13,8 @@ using Test: Test using CUDA: CUDA using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: - StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT + StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, + StructureFunctionObjects as SFO using Random: Random Random.seed!(42) @@ -35,11 +36,12 @@ Test.@testset "CUDA GPUSFWorkspace & slices" begin ref = SFC.calculate_structure_function( sft, x_cpu, u_cpu, bins; - return_sums_and_counts = true, verbose = false, show_progress = false, + output_type = SFO.StructureFunctionSumsAndCounts, + verbose = false, show_progress = false, ) res_fresh = SFC.gpu_calculate_structure_function( - sft, backend, x_gpu, u_gpu, bins; return_sums_and_counts = true, + sft, backend, x_gpu, u_gpu, bins, ) CUDA.synchronize() Test.@test res_fresh.counts ≈ ref.counts atol = 0.0 @@ -49,7 +51,7 @@ Test.@testset "CUDA GPUSFWorkspace & slices" begin ws = SFC.GPUSFWorkspace(backend, bins) res_ws = SFC.gpu_calculate_structure_function( - sft, backend, x_gpu, u_gpu, bins; return_sums_and_counts = true, workspace = ws, + sft, backend, x_gpu, u_gpu, bins; workspace = ws, ) CUDA.synchronize() Test.@test res_ws.counts ≈ ref.counts atol = 0.0 @@ -79,8 +81,7 @@ Test.@testset "CUDA GPUSFWorkspace & slices" begin counts_ref = zeros(UInt32, NB, T) for t in 1:T ref_t = SFC.gpu_calculate_structure_function( - sft, backend, x_batch_cpu[:, :, t], u_batch_cpu[:, :, t], bins; - return_sums_and_counts = true, + sft, backend, x_batch_cpu[:, :, t], u_batch_cpu[:, :, t], bins, ) CUDA.synchronize() sums_ref[:, t] .= ref_t.sums diff --git a/src/BinEdges.jl b/src/BinEdges.jl index 3efc47b..fc45071 100644 --- a/src/BinEdges.jl +++ b/src/BinEdges.jl @@ -24,7 +24,7 @@ primary computational bottleneck in the package. - Plain `AbstractVector` bin edges are valid everywhere but use generic `searchsortedfirst` / binary search. - Pass [`LinearBinEdges`](@ref), [`LogBinEdges`](@ref), or [`InfPaddedBinEdges`](@ref) for O(1) CPU digitize - and matching GPU tiled kernels (see `StructureFunctionsGPUExt`). + and matching GPU tiled kernels (see `StructureFunctionsKernelAbstractionsExt`). - [`InfPaddedBinEdges`](@ref) adds implicit catch-all under/overflow bins; do not `vcat(-Inf, …, Inf)` manually. - Classic serial/threaded pair-loop paths normalize once via [`BinEdges`](@ref); single-pass APIs expect callers to choose edge types explicitly (no auto-wrap on GPU). @@ -94,7 +94,6 @@ Reduces lookup time from **~46 ns** to **~3 ns** (a 15x speedup), completely eli struct LinearBinEdges{T, RT <: AbstractRange{T}} <: AbstractBinEdges{T} edges::RT inv_step::T - offset::T first_edge::T last_edge::T step_val::T @@ -104,9 +103,8 @@ end function LinearBinEdges(edges::AbstractRange{T}) where {T} inv_step = inv(step(edges)) - offset = T(1.0) - first(edges) * inv_step return LinearBinEdges{T, typeof(edges)}( - edges, inv_step, offset, first(edges), last(edges), step(edges) + edges, inv_step, first(edges), last(edges), step(edges) ) end @@ -363,3 +361,199 @@ Normalize flat edge input to [`AbstractBinEdges`](@ref) for hot-loop `digitize`: """ BinEdges(edges::AbstractBinEdges) = edges BinEdges(edges::AbstractRange) = LinearBinEdges(edges) + +# ========================================================================================= # +# 5. Squared-distance digitize plans +# ========================================================================================= # + +""" + _fast_log2(x) + +`log2(x)` for finite `x > 0`, max error ~4e-8 (Float64). Exponent extract plus an odd series on a +mantissa recentred to `[1/√2, √2)`; vectorizes, unlike the scalar `libm log`. Approximate — the bin +is decided by [`squared_digitize`](@ref)'s correction, not by this. +""" +@inline function _fast_log2(x::Float64) + ix = reinterpret(UInt64, x) + e = Int((ix >> 52) & 0x7ff) - 1023 + m = reinterpret(Float64, (ix & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000) + big = m > 1.4142135623730951 + m = big ? 0.5m : m + e = big ? e + 1 : e + t = (m - 1) / (m + 1) + t2 = t * t + s = muladd(t2, muladd(t2, muladd(t2, 1 / 7, 1 / 5), 1 / 3), 1.0) + return e + 2 * t * s * 1.4426950408889634 +end + +@inline function _fast_log2(x::Float32) + ix = reinterpret(UInt32, x) + e = Int((ix >> 23) & 0xff) - 127 + m = reinterpret(Float32, (ix & 0x007f_ffff) | 0x3f80_0000) + big = m > 1.4142135f0 + m = big ? 0.5f0m : m + e = big ? e + 1 : e + t = (m - 1f0) / (m + 1f0) + t2 = t * t + s = muladd(t2, muladd(t2, 1f0 / 5, 1f0 / 3), 1f0) + return Float32(e) + 2f0 * t * s * 1.442695f0 +end + +""" + AbstractSquaredDigitizePlan + +Maps a squared separation `r²` to the bin index `digitize(r, edges)` would give. + +Edges are strictly positive, so `e_{i-1} < r ≤ e_i` iff `e_{i-1}² < r² ≤ e_i²`. The index is +approximate; [`squared_digitize`](@ref) corrects it against the true squared edges. +""" +abstract type AbstractSquaredDigitizePlan{T} end + +"""Log-uniform edges: index from `_fast_log2(r²)` and one FMA, then corrected.""" +struct SquaredLogPlan{T, V <: AbstractVector{T}} <: AbstractSquaredDigitizePlan{T} + a::T # ln2 / (2·log-step) + b::T # -log(first edge) / log-step + n_bins::Int + sqedges::V +end + +"""Uniform-in-`r` edges: squares of a uniform grid are not uniform, so this keeps one `sqrt` and the +existing O(1) FMA search.""" +struct SquaredLinearPlan{T, E <: LinearBinEdges{T}, V <: AbstractVector{T}} <: AbstractSquaredDigitizePlan{T} + edges::E + n_bins::Int + sqedges::V +end + +"""Arbitrary sorted edges: binary search on the precomputed squared edges (skips the `sqrt`).""" +struct SquaredGeneralPlan{T, V <: AbstractVector{T}} <: AbstractSquaredDigitizePlan{T} + n_bins::Int + sqedges::V +end + +"""Implicit ±Inf catch-all bins around an inner plan; every pair lands somewhere.""" +struct SquaredInfPaddedPlan{T, P <: AbstractSquaredDigitizePlan{T}} <: AbstractSquaredDigitizePlan{T} + inner::P +end + +# Correctly-rounded squares of the actual edges; extended precision so the table adds no rounding. +_sq_edges(::Type{T}, v) where {T} = T[T(big(v[i])^2) for i in eachindex(v)] + +""" + squared_digitize_plan(edges) -> AbstractSquaredDigitizePlan + +Build the `r²` digitize plan for `edges`, once per call (never in the pair loop). +""" +function squared_digitize_plan(v::LogBinEdges{T}) where {T} + le = v.log_edges + sq = _sq_edges(T, v) + return SquaredLogPlan{T, typeof(sq)}( + T(log(2) / (2 * step(le))), T(-first(le) / step(le)), length(le) - 1, sq, + ) +end + +function squared_digitize_plan(v::LinearBinEdges{T}) where {T} + sq = _sq_edges(T, v.edges) + return SquaredLinearPlan{T, typeof(v), typeof(sq)}(v, length(v.edges) - 1, sq) +end + +function squared_digitize_plan(v::AbstractBinEdges{T}) where {T} + sq = _sq_edges(T, v) + return SquaredGeneralPlan{T, typeof(sq)}(length(v) - 1, sq) +end + +# Explicit: `InfPaddedBinEdges(::AbstractVector)` wraps a `@view`, which would otherwise fall to +# the generic binary-search plan. +squared_digitize_plan(v::InfPaddedBinEdges) = SquaredInfPaddedPlan(squared_digitize_plan(v.edges)) + +squared_digitize_plan(edges::AbstractVector) = squared_digitize_plan(BinEdges(edges)) + +"""Bins covered by the plan (`digitize` results in `1:n_bins` are in range).""" +@inline n_histogram_bins(p::AbstractSquaredDigitizePlan) = p.n_bins +@inline n_histogram_bins(p::SquaredInfPaddedPlan) = n_histogram_bins(p.inner) + 2 + +""" + has_vector_index(plan) -> Bool + +Whether the plan's index is branch-free, and so worth computing in the vectorized half of a pair +kernel. False for the linear and general plans, whose `searchsortedfirst` branches would +de-vectorize the whole `@simd` body. +""" +@inline has_vector_index(::AbstractSquaredDigitizePlan) = false +@inline has_vector_index(::SquaredLogPlan) = true +@inline has_vector_index(p::SquaredInfPaddedPlan) = has_vector_index(p.inner) + +""" + squared_approx_index(plan, r2) -> Int32 + +Approximate `searchsortedfirst` index for `r²`, branch-free, for the vectorized half of a pair +kernel. Meaningful only when [`has_vector_index`](@ref); other plans return `0`. +""" +@inline squared_approx_index(p::SquaredLogPlan, r2) = + unsafe_trunc(Int32, floor(muladd(_fast_log2(r2), p.a, p.b))) + Int32(1) +@inline squared_approx_index(::AbstractSquaredDigitizePlan, r2) = Int32(0) +@inline squared_approx_index(p::SquaredInfPaddedPlan, r2) = squared_approx_index(p.inner, r2) + +""" + digitize_key(plan, r2) + +The quantity the plan's scalar half compares against, computed in the vectorized half from `r²`. + +`r²` for the log and general plans; `√r²` for the linear plan, whose grid is uniform in `r`. +""" +@inline digitize_key(::SquaredLogPlan, r2) = r2 +@inline digitize_key(::SquaredGeneralPlan, r2) = r2 +@inline digitize_key(::SquaredLinearPlan, r2) = sqrt(r2) +@inline digitize_key(p::SquaredInfPaddedPlan, r2) = digitize_key(p.inner, r2) + +""" + squared_bin(plan, key, i) -> Int + +The bin, in the scalar half, from [`digitize_key`](@ref). When [`has_vector_index`](@ref), `i` is +the precomputed approximate index and this only corrects it; otherwise `i` is ignored. +""" +@inline squared_bin(p::SquaredLogPlan, key, i::Integer) = squared_correct(p, key, i) - 1 +@inline squared_bin(p::SquaredLinearPlan, key, ::Integer) = searchsortedfirst(p.edges, key) - 1 +@inline squared_bin(p::SquaredGeneralPlan, key, ::Integer) = searchsortedfirst(p.sqedges, key) - 1 +# The implicit -Inf edge shifts every inner index up by one; the inner plan already reports +# `n_bins + 1` above its last edge, which becomes the overflow bin. No separate range test needed. +@inline squared_bin(p::SquaredInfPaddedPlan, key, i::Integer) = squared_bin(p.inner, key, i) + 1 + +""" + squared_correct(plan, r2, i) -> Int + +Walk `i` to the exact `searchsortedfirst(sqedges, r²)`. 0 or 1 step for random separations; a loop +rather than a fixed step because within a few ulps of an edge more can be needed. +""" +@inline function squared_correct(p::AbstractSquaredDigitizePlan, r2, i::Integer) + sq = p.sqedges + n = p.n_bins + k = clamp(Int(i), 1, n + 2) + @inbounds begin + while k > 1 && sq[k - 1] >= r2 + k -= 1 + end + while k <= n + 1 && sq[k] < r2 + k += 1 + end + end + return k +end + +""" + squared_digitize(plan, r2) -> Int + +Exact `digitize(r, edges)` computed from `r²` alone. Out-of-range gives `0` (below) or `n_bins + 1` +(above), matching [`digitize`](@ref). +""" +@inline squared_digitize(p::AbstractSquaredDigitizePlan, r2) = + squared_bin(p, digitize_key(p, r2), squared_approx_index(p, r2)) + +# The implicit -Inf edge shifts every inner index up by one. +@inline function squared_correct(p::SquaredInfPaddedPlan, r2, i::Integer) + inner = p.inner + @inbounds hi = inner.sqedges[inner.n_bins + 1] + r2 > hi && return inner.n_bins + 3 + return squared_correct(inner, r2, i) + 1 +end + diff --git a/src/Calculations.jl b/src/Calculations.jl index b4af28c..e83f603 100644 --- a/src/Calculations.jl +++ b/src/Calculations.jl @@ -9,7 +9,9 @@ using ..HelperFunctions: HelperFunctions as SFH using ..StructureFunctionTypes: StructureFunctionTypes as SFT using ..StructureFunctionObjects: StructureFunctionObjects as SFO using ..StructureFunctions: AbstractBinEdges, BinEdges, LinearBinEdges, LogBinEdges, - InfPaddedBinEdges, n_histogram_bins + InfPaddedBinEdges, n_histogram_bins, + AbstractSquaredDigitizePlan, squared_digitize_plan, squared_digitize, + squared_approx_index, squared_correct, squared_bin, has_vector_index, digitize_key using StaticArrays: StaticArrays as SA using LinearAlgebra: LinearAlgebra as LA @@ -29,8 +31,6 @@ export calculate_structure_function, gpu_calculate_structure_function_2d, gpu_calculate_structure_function_2d_batch, gpu_calculate_structure_functions_single_pass_2d, gpu_calculate_structure_functions_single_pass_2d!, - AbstractExecutionBackend, SerialBackend, ThreadedBackend, DistributedBackend, - GPUBackend, AutoBackend, AbstractThreadingBackend, AutoThreadingBackend, serial_calculate_structure_function, threaded_calculate_structure_function, calculate_structure_functions_single_pass, calculate_structure_functions_single_pass!, @@ -44,7 +44,7 @@ export calculate_structure_function, calculate_structure_function_tensor, calculate_structure_function_tensor!, serial_calculate_structure_function_tensor!, gpu_calculate_structure_function!, calculate_structure_function!, - GPUSFWorkspace, reset_histogram!, release!, + GPUSFWorkspace, CPUSFWorkspace, reset_histogram!, release!, joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256, calculate_structure_function_batch!, calculate_structure_function_2d_batch!, calculate_structure_functions_single_pass_batch!, @@ -60,6 +60,7 @@ include("Calculations/shapes.jl") include("Calculations/batch_api.jl") include("Calculations/gpu_stubs.jl") include("Calculations/batch_leading.jl") +include("Calculations/workspace.jl") include("Calculations/batch.jl") include("Calculations/serial.jl") include("Calculations/serial_2d.jl") diff --git a/src/Calculations/backends.jl b/src/Calculations/backends.jl index b43b739..7808c52 100644 --- a/src/Calculations/backends.jl +++ b/src/Calculations/backends.jl @@ -1,189 +1,33 @@ -# Calculations Execution Backends +# Backend tags come from ComputationalBackends; methods dispatch on the abstract types so +# downstream concrete backends reach these kernels. -abstract type AbstractExecutionBackend end +using ComputationalBackends: ComputationalBackends as CB """ - SerialBackend <: AbstractExecutionBackend + resolve_auto_backend(shape, threaded_available, distributed_available) -> AbstractExecutionBackend -Serial (CPU, single-threaded) execution backend for structure function calculations. - -Use this backend when: -- Running on a single thread (default for Julia) -- Parallelization is not available or not desired -- Debugging or validating calculations - -This is the reference implementation that all other backends are validated against. - -# Examples -```julia -using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT - -sf_type = SFT.LongitudinalSecondOrderStructureFunctionType() -x = ([1.0, 2.0, 3.0], [0.0, 0.0, 0.0]) -u = ([0.1, 0.2, 0.3], [0.0, 0.0, 0.0]) -bins = [0.0, 1.0, 2.0] - -result = SFC.calculate_structure_function(sf_type, x, u, bins; backend=SFC.SerialBackend()) -``` -""" -struct SerialBackend <: AbstractExecutionBackend end - -""" - ThreadedBackend <: AbstractExecutionBackend - -Multi-threaded (CPU) execution backend using OhMyThreads for structure function calculations. - -Requires the `OhMyThreads.jl` package to be loaded. Use this backend when: -- Multiple CPU threads are available (`Threads.nthreads() > 1`) -- Speed is important and shared-memory parallelism is suitable -- Dataset fits in memory - -Partitions the outer loop index `i` across CPU tasks (via OhMyThreads when loaded). -For O(N²) pair loops, the threaded extension uses round-robin outer-index chunks -(`OMT.RoundRobin`) so each task gets ~equal pair work; contiguous equal-size chunks -would severely load-imbalance this kernel. Thread-local reductions ensure thread safety -without locks or `threadid()` indexing. - -# Examples -```julia -using Base.Threads: nthreads - -if nthreads() > 1 - result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.ThreadedBackend()) -end -``` -""" -struct ThreadedBackend <: AbstractExecutionBackend end - -""" - DistributedBackend{Inner} <: AbstractExecutionBackend - DistributedBackend(inner = SerialBackend()) - -Distributed (multi-process/multi-node) execution backend using Distributed.jl. - -Parametric on the per-worker `inner` backend (like [`GPUBackend`](@ref) is parametric on its -device backend): distribution across processes and local execution within a process are -orthogonal axes. `inner` selects how each worker computes its share of the pairs: - -- `DistributedBackend()` / `DistributedBackend(SerialBackend())` — each worker runs serially. -- `DistributedBackend(ThreadedBackend())` — hybrid: each worker threads over its share - (requires `OhMyThreads` and worker threads, e.g. `addprocs(n; exeflags="-t k")`). On a - multi-socket node this enables one-process-per-socket × threaded-within-socket, which scales - past the single-socket memory-bandwidth ceiling of pure threading. - -Requires workers started via `addprocs()`. - -# Examples -```julia -using Distributed: addprocs -addprocs(4) -result = SFC.calculate_structure_function(sf_type, x, u, bins; backend=SFC.DistributedBackend()) - -# hybrid distributed + threaded (workers each with 8 threads): -# addprocs(2; exeflags="-t 8"); @everywhere using OhMyThreads -# backend = SFC.DistributedBackend(SFC.ThreadedBackend()) -``` +What `AutoBackend` resolves to. `threaded_available`/`distributed_available` are zero-argument +predicates because each entry family probes a different dispatch. """ -struct DistributedBackend{Inner <: AbstractExecutionBackend} <: AbstractExecutionBackend - inner::Inner +function resolve_auto_backend(shape, threaded_available::F, distributed_available::G) where {F, G} + (distributed_workers_available(Val(:distributed)) && distributed_available()) && + return CB.DistributedBackend() + has_auxiliary_axes(shape) && + return Threads.nthreads() > 1 ? CB.ThreadedBackend() : CB.SerialBackend() + (Threads.nthreads() > 1 && threaded_available()) && return CB.ThreadedBackend() + return CB.SerialBackend() end -DistributedBackend() = DistributedBackend(SerialBackend()) - -""" - MPIBackend{Inner} <: AbstractExecutionBackend - MPIBackend(inner = SerialBackend(); comm = MPI.COMM_WORLD) - -Multi-rank execution via MPI.jl, parametric on the per-rank `inner` backend (like -[`DistributedBackend`](@ref)). Each rank computes a balanced share of the pairs with `inner` -(Serial/Threaded), then the partial histograms are combined with `MPI.Allreduce!` so every -rank holds the full result. Requires `MPI` to be loaded; the program must run under `mpiexec` -(or equivalent) with `MPI.Init()` called. Offered for multi-node adoption. - -# Examples -```julia -using MPI; MPI.Init() -backend = SFC.MPIBackend(SFC.ThreadedBackend()) # hybrid MPI + threads -result = SFC.calculate_structure_function(sf_type, x, u, bins; backend=backend) -``` -""" -struct MPIBackend{Inner <: AbstractExecutionBackend, C} <: AbstractExecutionBackend - inner::Inner - comm::C -end -# `comm = nothing` ⇒ the MPI extension uses `MPI.COMM_WORLD` (core cannot reference MPI). -MPIBackend(inner::AbstractExecutionBackend = SerialBackend(); comm = nothing) = - MPIBackend(inner, comm) function _dispatch_execution_backend( - ::MPIBackend, args...; kwargs..., + ::CB.AbstractMPIBackend, args...; kwargs..., ) throw(ArgumentError("MPI backend is unavailable. Load MPI (`using MPI`) to enable StructureFunctionsMPIExt, or use a different backend.")) end -""" - GPUBackend{B} <: AbstractExecutionBackend - -GPU-accelerated execution backend using KernelAbstractions.jl. - -Parameterized by the target GPU backend (e.g., `KernelAbstractions.CPU()`, `CUDA.CUDABackend()`). -Requires the `KernelAbstractions.jl` package. Use this backend when: -- NVIDIA GPU (CUDA) or other supported GPU hardware is available -- Computation time is critical -- Kernel compatibility is high (most SF calculations are embarrassingly parallel) - -# Examples -```julia -using KernelAbstractions: CPU - -# CPU backend (for testing parity) -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.GPUBackend(CPU())) - -# NVIDIA GPU backend (requires CUDA.jl) -using CUDA -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.GPUBackend(CUDABackend())) -``` -""" -struct GPUBackend{B} <: AbstractExecutionBackend - backend::B -end - -""" - AutoBackend <: AbstractExecutionBackend - -Automatic backend selection based on availability and runtime state. - -The selection order is: - 1. Distributed when workers are available (`nworkers() > 1`) - 2. Threaded when multiple CPU threads available (`nthreads() > 1`) - 3. Serial - -Use this backend when: -- You want the package to choose the best available backend automatically -- You are writing portable code that should adapt to the execution environment - -# Examples -```julia -# Package automatically chooses the best backend -result = SFC.calculate_structure_function(sf_type, x, u, bins) # Defaults to AutoBackend - -# Or explicitly: -result = SFC.calculate_structure_function(sf_type, x, u, bins; - backend=SFC.AutoBackend()) -``` -""" -struct AutoBackend <: AbstractExecutionBackend end - -# Backward-compatible aliases for in-flight API migration. -const AbstractThreadingBackend = AbstractExecutionBackend -const AutoThreadingBackend = AutoBackend - function threaded_calculate_structure_function(args...; kwargs...) throw( ArgumentError( - "Threaded backend is unavailable. Load the OhMyThreads extension or use backend=SerialBackend().", + "Threaded backend is unavailable. Load the OhMyThreads extension or use backend=CB.SerialBackend().", ), ) end @@ -191,7 +35,7 @@ end function threaded_calculate_structure_function!(args...; kwargs...) throw( ArgumentError( - "Threaded backend is unavailable. Load the OhMyThreads extension or use backend=SerialBackend().", + "Threaded backend is unavailable. Load the OhMyThreads extension or use backend=CB.SerialBackend().", ), ) end @@ -238,27 +82,27 @@ function _threaded_backend_available!( end function _dispatch_execution_backend( - ::DistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + ::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) - throw(ArgumentError("Distributed backend is unavailable. Load Distributed/SharedArrays extension or use backend=SerialBackend().")) + throw(ArgumentError("Distributed backend is unavailable. Load Distributed (`using Distributed`) or use backend=CB.SerialBackend().")) end function _dispatch_execution_backend( - ::DistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractDistributedBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) - throw(ArgumentError("Distributed backend is unavailable. Load Distributed/SharedArrays extension or use backend=SerialBackend().")) + throw(ArgumentError("Distributed backend is unavailable. Load Distributed (`using Distributed`) or use backend=CB.SerialBackend().")) end function _dispatch_execution_backend!( - ::DistributedBackend, sums::AbstractArray, counts::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + ::CB.AbstractDistributedBackend, sums::AbstractArray, counts::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) - throw(ArgumentError("Distributed backend is unavailable. Load Distributed/SharedArrays extension or use backend=SerialBackend().")) + throw(ArgumentError("Distributed backend is unavailable. Load Distributed (`using Distributed`) or use backend=CB.SerialBackend().")) end function _dispatch_execution_backend!( - ::DistributedBackend, sums_2d::AbstractArray, counts_2d::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractDistributedBackend, sums_2d::AbstractArray, counts_2d::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) - throw(ArgumentError("Distributed backend is unavailable. Load Distributed/SharedArrays extension or use backend=SerialBackend().")) + throw(ArgumentError("Distributed backend is unavailable. Load Distributed (`using Distributed`) or use backend=CB.SerialBackend().")) end distributed_workers_available(::Val) = false diff --git a/src/Calculations/batch.jl b/src/Calculations/batch.jl index 16d21b6..e13936a 100644 --- a/src/Calculations/batch.jl +++ b/src/Calculations/batch.jl @@ -36,8 +36,11 @@ end Fixed geometry batch: `x` is (N_dims, N), `u` has trailing batch dims. """ function auxiliary_shared_positions!(sums, counts, x_mat::AbstractMatrix, u_batch, - sf_type::SFT.AbstractPairwiseStructureFunctionType, distance_bins; kwargs...) - _bl_run_1d!(sums, counts, sf_type, x_mat, u_batch, BinEdges(distance_bins), _bl_serial_exec) + sf_type::SFT.AbstractPairwiseStructureFunctionType, distance_bins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true) + _bl_run_1d!(sums, counts, sf_type, x_mat, u_batch, BinEdges(distance_bins), distance_metric, + _bl_serial_exec, workspace) end """ @@ -46,8 +49,11 @@ end Varying geometry batch: `x` and `u` have matching trailing batch dims. """ function auxiliary_varying_positions!(sums, counts, x_batch, u_batch, - sf_type::SFT.AbstractPairwiseStructureFunctionType, distance_bins; kwargs...) - _bl_run_1d!(sums, counts, sf_type, x_batch, u_batch, BinEdges(distance_bins), _bl_serial_exec) + sf_type::SFT.AbstractPairwiseStructureFunctionType, distance_bins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true) + _bl_run_1d!(sums, counts, sf_type, x_batch, u_batch, BinEdges(distance_bins), distance_metric, + _bl_serial_exec, workspace) end """ @@ -55,8 +61,10 @@ end Six-invariant-type single-pass 1D batch (serial). """ -function serial_calculate_structure_functions_single_pass!(sums, counts, x, u, distance_bins; kwargs...) - _bl_run_sp1d!(sums, counts, x, u, BinEdges(distance_bins), _bl_serial_exec) +function serial_calculate_structure_functions_single_pass!(sums, counts, x, u, distance_bins; + workspace = nothing, distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true) + _bl_run_sp1d!(sums, counts, x, u, BinEdges(distance_bins), distance_metric, _bl_serial_exec, workspace) end """ @@ -65,8 +73,11 @@ end Six-invariant-type SP2D batch (serial); output `(6, n_dist, n_val, batch…)`. """ function serial_calculate_structure_functions_single_pass_2d!(sums, counts, x, u, distance_bins, - value_bins::SinglePass2DValueBins; kwargs...) - _bl_run_sp2d!(sums, counts, x, u, BinEdges(distance_bins), value_bins, _bl_serial_exec) + value_bins::SinglePass2DValueBins; workspace = nothing, + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true) + _bl_run_sp2d!(sums, counts, x, u, BinEdges(distance_bins), value_bins, distance_metric, + _bl_serial_exec, workspace) end """ @@ -75,8 +86,11 @@ end Single-type joint 2D batch (serial); output `(n_dist, n_val, batch…)`. """ function auxiliary_joint2d!(sums, counts, sf_type::SFT.AbstractPairwiseStructureFunctionType, - x, u, distance_bins, value_bins; kwargs...) - _bl_run_joint2d!(sums, counts, sf_type, x, u, BinEdges(distance_bins), BinEdges(value_bins), _bl_serial_exec) + x, u, distance_bins, value_bins; workspace = nothing, + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, show_progress::Bool = true) + _bl_run_joint2d!(sums, counts, sf_type, x, u, BinEdges(distance_bins), BinEdges(value_bins), + distance_metric, _bl_serial_exec, workspace) end """Loop-over-slice gold reference for batch parity.""" @@ -103,7 +117,7 @@ function cpu_slice_baseline!( u_slice = batch_field_slice(u, b) end local_output = zeros(eltype(sums), n_bins) - local_counts = zeros(UInt32, n_bins) + local_counts = zeros(eltype(counts), n_bins) serial_calculate_structure_function!( local_output, local_counts, @@ -149,14 +163,16 @@ function _serial_calculate_structure_function_point( x::AbstractArray{FT1}, u::AbstractArray{FT2}, distance_bins::AbstractVector, - vD::Val{D}; - count_eltype::Type{CT} = UInt32, + vD::Val{D}, + ::Type{CT}; distance_metric::DI.PreMetric = DI.Euclidean(), verbose::Bool = true, show_progress::Bool = true, - kwargs..., ) where {FT1, FT2, D, CT} - x_tuple = _component_vector_views(x, vD) + _assert_counts_representable(CT, size(x, 2)) + # `D` is static here, so the geometry — and with it the coordinate width, which differs from `D` + # on a shell — is a concrete type. + x_tuple = _component_vector_views(x, SFH.coordinate_width(SFH.pair_geometry_for(distance_metric, vD))) u_tuple = _component_vector_views(u, vD) OT = promote_type(float(FT1), float(FT2)) output = zeros(OT, n_histogram_bins(distance_bins)) @@ -186,8 +202,8 @@ function serial_calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x::AbstractArray{FT1}, u::AbstractArray{FT2}, - distance_bins::AbstractVector; - count_eltype::Type{CT} = UInt32, + distance_bins::AbstractVector, + count_eltype::Type{CT} = UInt32; kwargs..., ) where {FT1 <: Number, FT2 <: Number, CT} if ndims(u) >= 3 @@ -201,34 +217,22 @@ function serial_calculate_structure_function( return SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, sums, counts) end # Point-field route: - D = size(x, 1) + D = size(u, 1) D == 2 && return _serial_calculate_structure_function_point( - structure_function_type, - x, - u, - distance_bins, - Val(2); - count_eltype = count_eltype, - kwargs..., + structure_function_type, x, u, distance_bins, Val(2), count_eltype; kwargs..., ) D == 3 && return _serial_calculate_structure_function_point( - structure_function_type, - x, - u, - distance_bins, - Val(3); - count_eltype = count_eltype, - kwargs..., + structure_function_type, x, u, distance_bins, Val(3), count_eltype; kwargs..., ) - throw(DimensionMismatch("expected spatial/velocity dimension D=2 or D=3 on axis 1; got D=$D")) + return _validate_spatial_dimension(D) end function threaded_calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x::AbstractArray{FT1}, u::AbstractArray{FT2}, - distance_bins::AbstractVector; - count_eltype::Type{CT} = UInt32, + distance_bins::AbstractVector, + count_eltype::Type{CT} = UInt32; kwargs..., ) where {FT1 <: Number, FT2 <: Number, CT} if ndims(u) >= 3 @@ -241,5 +245,5 @@ function threaded_calculate_structure_function( auxiliary_structure_function_threaded!(sums, counts, structure_function_type, x, u, distance_bins; kwargs...) return SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, sums, counts) end - throw(ArgumentError("Threaded backend is unavailable for non-batch inputs. Load the OhMyThreads extension or use backend=SerialBackend().")) + throw(ArgumentError("Threaded backend is unavailable for non-batch inputs. Load the OhMyThreads extension or use backend=CB.SerialBackend().")) end diff --git a/src/Calculations/batch_api.jl b/src/Calculations/batch_api.jl index 666f5e3..32c10d4 100644 --- a/src/Calculations/batch_api.jl +++ b/src/Calculations/batch_api.jl @@ -11,38 +11,38 @@ CPU backends: not yet implemented (use a loop over `t` with `calculate_structure """ function calculate_structure_function_batch!( sums, counts, sf_type, x, u, distance_bins; - backend = SerialBackend(), kwargs... + backend = CB.SerialBackend(), kwargs... ) _dispatch_batch!(backend, sums, counts, sf_type, x, u, distance_bins; kwargs...) return nothing end function _dispatch_batch!( - ::SerialBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... + ::CB.AbstractSerialBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... ) auxiliary_structure_function!(sums, counts, sf_type, x, u, distance_bins; kwargs...) return nothing end function _dispatch_batch!( - ::ThreadedBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... + ::CB.AbstractThreadedBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... ) auxiliary_structure_function_threaded!(sums, counts, sf_type, x, u, distance_bins; kwargs...) return nothing end function _dispatch_batch!( - ::DistributedBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... + ::CB.AbstractDistributedBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... ) throw( ArgumentError( - "Distributed slice batch driver is not implemented yet. Loop over time slices or use backend=GPUBackend(...).", + "Distributed slice batch driver is not implemented yet. Loop over time slices or use backend=CB.GPUBackend(...).", ), ) end function _dispatch_batch!( - backend::GPUBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... + backend::CB.AbstractGPUBackend, sums, counts, sf_type, x, u, distance_bins; kwargs... ) gpu_calculate_structure_function_batch!( sums, counts, sf_type, backend.backend, x, u, distance_bins; kwargs... @@ -57,34 +57,34 @@ Batch 2D joint histograms over `(N_dims, N_points, T)`; outputs `(n_dist, n_val, """ function calculate_structure_function_2d_batch!( sums, counts, sf_type, x, u, distance_bins, value_bins; - backend = SerialBackend(), kwargs... + backend = CB.SerialBackend(), kwargs... ) _dispatch_2d_batch!(backend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs...) return nothing end function _dispatch_2d_batch!( - ::SerialBackend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs... + ::CB.AbstractSerialBackend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs... ) auxiliary_joint2d!(sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs...) return nothing end function _dispatch_2d_batch!( - ::ThreadedBackend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs... + ::CB.AbstractThreadedBackend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs... ) auxiliary_joint2d_threaded!(sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs...) return nothing end function _dispatch_2d_batch!( - ::DistributedBackend, args...; kwargs... + ::CB.AbstractDistributedBackend, args...; kwargs... ) throw(ArgumentError("Distributed 2D joint slice batch not implemented yet; use GPUBackend or loop over t.")) end function _dispatch_2d_batch!( - backend::GPUBackend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs... + backend::CB.AbstractGPUBackend, sums, counts, sf_type, x, u, distance_bins, value_bins; kwargs... ) gpu_calculate_structure_function_2d_batch!( sums, counts, sf_type, backend.backend, x, u, distance_bins, value_bins; kwargs... @@ -103,6 +103,32 @@ const SinglePass2DValueBins = Union{AbstractVector, Tuple{Vararg{AbstractVector, @inline _sp2d_value_bin_at(value_bins, t::Int) = value_bins isa Tuple ? value_bins[t] : value_bins +""" + @sp2d_each_invariant value_bins t vb body + +Run `body` once per `SINGLE_PASS_N` invariant, with `t` bound to a literal index and `vb` to that +invariant's concretely-typed value bins. Each repetition gets its own `let` scope, so `vb` is a +distinct binding per invariant. + +`value_bins` may be a heterogeneous `NTuple{6}` (log bins for the non-negative invariants, linear +for the signed ones is the natural choice). Indexing it with a *runtime* `t` makes `vb` a `Union`, +which turns the `digitize` call into a dynamic dispatch on every pair × invariant in the hot loop. +A macro rather than a higher-order function: passing `body` as a closure measured 45 ns/pair slower +in the single-pass 2D scatter than emitting it inline. +""" +macro sp2d_each_invariant(value_bins, t, vb, body) + blocks = map(1:SINGLE_PASS_N) do i + Expr( + :let, + Expr(:block, + Expr(:(=), esc(t), i), + Expr(:(=), esc(vb), :($(_sp2d_value_bin_at)($(esc(value_bins)), $i)))), + esc(body), + ) + end + return Expr(:block, blocks...) +end + function _validate_value_bins!(value_bins, n_val::Int) if value_bins isa Tuple length(value_bins) == SINGLE_PASS_N || @@ -131,34 +157,34 @@ outputs `(6, NB, T)`. """ function calculate_structure_functions_single_pass_batch!( sums, counts, x, u, distance_bins; - backend = SerialBackend(), kwargs... + backend = CB.SerialBackend(), kwargs... ) _dispatch_single_pass_batch!(backend, sums, counts, x, u, distance_bins; kwargs...) return nothing end function _dispatch_single_pass_batch!( - ::SerialBackend, sums, counts, x, u, distance_bins; kwargs... + ::CB.AbstractSerialBackend, sums, counts, x, u, distance_bins; kwargs... ) serial_calculate_structure_functions_single_pass!(sums, counts, x, u, distance_bins; kwargs...) return nothing end function _dispatch_single_pass_batch!( - ::ThreadedBackend, sums, counts, x, u, distance_bins; kwargs... + ::CB.AbstractThreadedBackend, sums, counts, x, u, distance_bins; kwargs... ) threaded_calculate_structure_functions_single_pass!(sums, counts, x, u, distance_bins; kwargs...) return nothing end function _dispatch_single_pass_batch!( - ::DistributedBackend, args...; kwargs... + ::CB.AbstractDistributedBackend, args...; kwargs... ) throw(ArgumentError("Distributed single-pass slice batch not implemented yet; use GPUBackend or loop over t.")) end function _dispatch_single_pass_batch!( - backend::GPUBackend, sums, counts, x, u, distance_bins; kwargs... + backend::CB.AbstractGPUBackend, sums, counts, x, u, distance_bins; kwargs... ) gpu_calculate_structure_functions_single_pass_batch!( sums, counts, backend.backend, x, u, distance_bins; kwargs... @@ -175,7 +201,7 @@ if you have a length-6 vector of bin objects. """ function calculate_structure_functions_single_pass_2d_batch!( sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; - backend = SerialBackend(), kwargs... + backend = CB.SerialBackend(), kwargs... ) _dispatch_single_pass_2d_batch!( backend, sums, counts, x, u, distance_bins, value_bins; kwargs... @@ -184,27 +210,27 @@ function calculate_structure_functions_single_pass_2d_batch!( end function _dispatch_single_pass_2d_batch!( - ::SerialBackend, sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; kwargs... + ::CB.AbstractSerialBackend, sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; kwargs... ) serial_calculate_structure_functions_single_pass_2d!(sums, counts, x, u, distance_bins, value_bins; kwargs...) return nothing end function _dispatch_single_pass_2d_batch!( - ::ThreadedBackend, sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; kwargs... + ::CB.AbstractThreadedBackend, sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; kwargs... ) threaded_calculate_structure_functions_single_pass_2d!(sums, counts, x, u, distance_bins, value_bins; kwargs...) return nothing end function _dispatch_single_pass_2d_batch!( - ::DistributedBackend, args...; kwargs... + ::CB.AbstractDistributedBackend, args...; kwargs... ) throw(ArgumentError("Distributed single-pass 2D slice batch not implemented yet; use GPUBackend or loop over t.")) end function _dispatch_single_pass_2d_batch!( - backend::GPUBackend, sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; kwargs... + backend::CB.AbstractGPUBackend, sums, counts, x, u, distance_bins, value_bins::SinglePass2DValueBins; kwargs... ) gpu_calculate_structure_functions_single_pass_2d_batch!( sums, counts, backend.backend, x, u, distance_bins, value_bins; kwargs... diff --git a/src/Calculations/batch_leading.jl b/src/Calculations/batch_leading.jl index ba45f22..1b733b0 100644 --- a/src/Calculations/batch_leading.jl +++ b/src/Calculations/batch_leading.jl @@ -29,34 +29,74 @@ struct BatchLeading{A <: AbstractArray} data::A end +"""Position/velocity input a batch driver accepts: a plain `(D, N, B…)` array, or a +[`BatchLeading`](@ref) wrapper around a `(B, D, N)` one.""" +const BatchInput = Union{AbstractArray, BatchLeading} + @inline _bl_unwrap(u) = (u, false) # (array, already_batch_leading) @inline _bl_unwrap(u::BatchLeading) = (u.data, true) -@inline _sq(x) = x * x - # Prepare batch-leading (B,D,N) buffers. Handles the default plain `(D,N,B...)` (transposed # once) and `BatchLeading` `(B,D,N)` (zero-copy). `x` may be fixed (D,N) or varying. Called # once per top-level call (not in the hot loop), so the type-instability of the branch is a # harmless function barrier. Returns (xb, ub, B, D, N, fixed_x). -function _bl_prepare(x, u) +function _bl_prepare(x, u, workspace = nothing) u_raw, u_bl = _bl_unwrap(u) x_raw, x_bl = _bl_unwrap(x) fixed_x = ndims(x_raw) == 2 + # `W` is the coordinate width and `D` the velocity width; they differ on a shell, where a point + # takes two coordinates but the velocity may carry a third, radial, component. + W = x_bl ? size(x_raw, 2) : size(x_raw, 1) if u_bl B, D, N = size(u_raw) + _validate_ws_shape(workspace, B, N, D, W) ub = u_raw else - D, N = size(x_raw, 1), size(x_raw, 2) + D, N = size(u_raw, 1), size(u_raw, 2) B = prod(size(u_raw)[3:end]) - ub = _to_batch_leading(reshape(u_raw, D, N, B)) + _validate_ws_shape(workspace, B, N, D, W) + ub = _to_batch_leading(reshape(u_raw, D, N, B), _ws_ub(workspace)) end - xb = fixed_x ? x_raw : (x_bl ? x_raw : _to_batch_leading(reshape(x_raw, D, N, B))) - return xb, ub, B, D, N, fixed_x + xb = fixed_x ? x_raw : + (x_bl ? x_raw : _to_batch_leading(reshape(x_raw, W, N, B), _ws_xb(workspace))) + return xb, ub, B, D, W, N, fixed_x end +# Statically-sized loads for the two layouts the batch drivers hold: `(W, N)` shared positions and +# `(B, W, N)` batch-leading. The width comes from the geometry, never from the velocity rank. +Base.@propagate_inbounds _bl_pt(x::AbstractMatrix, i, ::Val{W}) where {W} = + SA.SVector{W}(ntuple(d -> x[d, i], Val(W))) +Base.@propagate_inbounds _bl_pt(xb::AbstractArray{<:Any, 3}, b, i, ::Val{W}) where {W} = + SA.SVector{W}(ntuple(d -> xb[b, d, i], Val(W))) +Base.@propagate_inbounds _bl_vel(ub, b, i, ::Val{D}) where {D} = + SA.SVector{D}(ntuple(d -> ub[b, d, i], Val(D))) + +""" +Throw unless the staged coordinate width matches what `geom` needs. + +The batch entry points take raw `(D, N, B…)` arrays rather than going through +[`_validate_array_shape`](@ref), so this is where a mismatched `x` is caught — before the kernels +load it under `@inbounds`. +""" +@inline function _validate_bl_geometry(geom, W::Int, D::Int) + want = _val_int(SFH.coordinate_width(geom)) + W == want || throw( + DimensionMismatch( + "$(nameof(typeof(geom))) locates a point with $want coordinate(s) on axis 1 of x, but " * + "got $W (velocity dimension D=$D)", + ), + ) + return nothing +end + +# The workspace's transpose buffers, or `nothing` for the allocate-fresh path. +@inline _ws_ub(::Nothing) = nothing +@inline _ws_xb(::Nothing) = nothing + # (D,N,B) -> (B,D,N) materialized batch-leading buffer (lazy PermutedDimsArray would put the # strided read back in the hot loop, so we materialize — cheap, O(D·N·B) ≪ O(N²·B)). -@inline _to_batch_leading(u_DNB) = permutedims(u_DNB, (3, 1, 2)) +@inline _to_batch_leading(u_DNB, ::Nothing) = permutedims(u_DNB, (3, 1, 2)) +@inline _to_batch_leading(u_DNB, dest::AbstractArray) = permutedims!(dest, u_DNB, (3, 1, 2)) # ---------------------------------------------------------------------------------------- # Shared positions ("same surface"): x is (D,N) fixed; geometry computed ONCE per pair. @@ -69,26 +109,30 @@ function _bl_shared_1d!( ub::AbstractArray{<:Any, 3}, sf_type::SFT.AbstractPairwiseStructureFunctionType, dist_be, + geom, ::Val{D}, irange, + brange, ) where {OT, CT, D} - B = size(ub, 1) N = size(ub, 3) nb = size(sums_bl, 2) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange - Xi = SA.SVector{D}(ntuple(d -> x[d, i], Val(D))) + Xi = _bl_pt(x, i, vW) for j in (i + 1):N - Xj = SA.SVector{D}(ntuple(d -> x[d, j], Val(D))) - dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) + Xj = _bl_pt(x, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = SFH.digitize(dist, dist_be) - (1 <= bin <= nb) || continue - rh = dx / dist - @simd for b in 1:B - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) + (ok && 1 <= bin <= nb) || continue + # Loop-invariant across the b strip: one frame and one direction serve every field. + rh = SFH.pair_direction(geom, frame, dist) + @simd for b in brange + du = SFH.pair_delta(geom, frame, Xi, Xj, _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) v = sf_type(du, rh) - sums_bl[b, bin] += v - counts_bl[b, bin] += one(CT) + sums_bl[b - boff, bin] += v + counts_bl[b - boff, bin] += one(CT) end end end @@ -105,23 +149,28 @@ function _bl_varying_1d!( ub::AbstractArray{<:Any, 3}, sf_type::SFT.AbstractPairwiseStructureFunctionType, dist_be, + geom, ::Val{D}, irange, + brange, ) where {OT, CT, D} - B = size(ub, 1) N = size(ub, 3) nb = size(sums_bl, 2) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange for j in (i + 1):N - @simd for b in 1:B - dx = SA.SVector{D}(ntuple(d -> xb[b, d, j] - xb[b, d, i], Val(D))) - dist = sqrt(LA.dot(dx, dx)) + @simd for b in brange + Xi = _bl_pt(xb, b, i, vW) + Xj = _bl_pt(xb, b, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = SFH.digitize(dist, dist_be) - if 1 <= bin <= nb - rh = dx / dist - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) - sums_bl[b, bin] += sf_type(du, rh) - counts_bl[b, bin] += one(CT) + if ok && 1 <= bin <= nb + du, rh = SFH.pair_increments(geom, frame, dist, Xi, Xj, + _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) + sums_bl[b - boff, bin] += sf_type(du, rh) + counts_bl[b - boff, bin] += one(CT) end end end @@ -136,26 +185,28 @@ end function _bl_joint2d_shared!( sums_bl::AbstractArray{OT, 3}, counts_bl::AbstractArray{CT, 3}, x::AbstractMatrix, ub::AbstractArray{<:Any, 3}, - sf_type::SFT.AbstractPairwiseStructureFunctionType, dist_be, val_be, ::Val{D}, irange, + sf_type::SFT.AbstractPairwiseStructureFunctionType, dist_be, val_be, geom, ::Val{D}, irange, brange, ) where {OT, CT, D} - B = size(ub, 1); N = size(ub, 3) + N = size(ub, 3) n_dist = size(sums_bl, 2); n_val = size(sums_bl, 3) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange - Xi = SA.SVector{D}(ntuple(d -> x[d, i], Val(D))) + Xi = _bl_pt(x, i, vW) for j in (i + 1):N - Xj = SA.SVector{D}(ntuple(d -> x[d, j], Val(D))) - dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) + Xj = _bl_pt(x, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = SFH.digitize(dist, dist_be) - (1 <= dbin <= n_dist) || continue - rh = dx / dist - for b in 1:B - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) + (ok && 1 <= dbin <= n_dist) || continue + rh = SFH.pair_direction(geom, frame, dist) + for b in brange + du = SFH.pair_delta(geom, frame, Xi, Xj, _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) val = sf_type(du, rh) vbin = SFH.digitize(val, val_be) if 1 <= vbin <= n_val - sums_bl[b, dbin, vbin] += val - counts_bl[b, dbin, vbin] += one(CT) + sums_bl[b - boff, dbin, vbin] += val + counts_bl[b - boff, dbin, vbin] += one(CT) end end end @@ -166,24 +217,28 @@ end function _bl_joint2d_varying!( sums_bl::AbstractArray{OT, 3}, counts_bl::AbstractArray{CT, 3}, xb::AbstractArray{<:Any, 3}, ub::AbstractArray{<:Any, 3}, - sf_type::SFT.AbstractPairwiseStructureFunctionType, dist_be, val_be, ::Val{D}, irange, + sf_type::SFT.AbstractPairwiseStructureFunctionType, dist_be, val_be, geom, ::Val{D}, irange, brange, ) where {OT, CT, D} - B = size(ub, 1); N = size(ub, 3) + N = size(ub, 3) n_dist = size(sums_bl, 2); n_val = size(sums_bl, 3) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange for j in (i + 1):N - for b in 1:B - dx = SA.SVector{D}(ntuple(d -> xb[b, d, j] - xb[b, d, i], Val(D))) - dist = sqrt(LA.dot(dx, dx)) + for b in brange + Xi = _bl_pt(xb, b, i, vW) + Xj = _bl_pt(xb, b, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = SFH.digitize(dist, dist_be) - (1 <= dbin <= n_dist) || continue - rh = dx / dist - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) + (ok && 1 <= dbin <= n_dist) || continue + du, rh = SFH.pair_increments(geom, frame, dist, Xi, Xj, + _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) val = sf_type(du, rh) vbin = SFH.digitize(val, val_be) if 1 <= vbin <= n_val - sums_bl[b, dbin, vbin] += val - counts_bl[b, dbin, vbin] += one(CT) + sums_bl[b - boff, dbin, vbin] += val + counts_bl[b - boff, dbin, vbin] += one(CT) end end end @@ -215,21 +270,23 @@ end function _bl_sp1d_shared!( sums_bl::AbstractArray{OT, 3}, counts_bl::AbstractArray{CT, 3}, - x::AbstractMatrix, ub::AbstractArray{<:Any, 3}, dist_be, ::Val{D}, irange, + x::AbstractMatrix, ub::AbstractArray{<:Any, 3}, dist_be, geom, ::Val{D}, irange, brange, ) where {OT, CT, D} - B = size(ub, 1); N = size(ub, 3); nb = size(sums_bl, 3) + N = size(ub, 3); nb = size(sums_bl, 3) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange - Xi = SA.SVector{D}(ntuple(d -> x[d, i], Val(D))) + Xi = _bl_pt(x, i, vW) for j in (i + 1):N - Xj = SA.SVector{D}(ntuple(d -> x[d, j], Val(D))) - dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) + Xj = _bl_pt(x, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = SFH.digitize(dist, dist_be) - (1 <= bin <= nb) || continue - rh = dx / dist - @simd for b in 1:B - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) - _bl_sp1d_write!(sums_bl, counts_bl, b, bin, LA.dot(du, rh), LA.dot(du, du), CT) + (ok && 1 <= bin <= nb) || continue + rh = SFH.pair_direction(geom, frame, dist) + @simd for b in brange + du = SFH.pair_delta(geom, frame, Xi, Xj, _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) + _bl_sp1d_write!(sums_bl, counts_bl, b - boff, bin, LA.dot(du, rh), LA.dot(du, du), CT) end end end @@ -238,19 +295,23 @@ end function _bl_sp1d_varying!( sums_bl::AbstractArray{OT, 3}, counts_bl::AbstractArray{CT, 3}, - xb::AbstractArray{<:Any, 3}, ub::AbstractArray{<:Any, 3}, dist_be, ::Val{D}, irange, + xb::AbstractArray{<:Any, 3}, ub::AbstractArray{<:Any, 3}, dist_be, geom, ::Val{D}, irange, brange, ) where {OT, CT, D} - B = size(ub, 1); N = size(ub, 3); nb = size(sums_bl, 3) + N = size(ub, 3); nb = size(sums_bl, 3) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange for j in (i + 1):N - @simd for b in 1:B - dx = SA.SVector{D}(ntuple(d -> xb[b, d, j] - xb[b, d, i], Val(D))) - dist = sqrt(LA.dot(dx, dx)) + @simd for b in brange + Xi = _bl_pt(xb, b, i, vW) + Xj = _bl_pt(xb, b, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) bin = SFH.digitize(dist, dist_be) - if 1 <= bin <= nb - rh = dx / dist - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) - _bl_sp1d_write!(sums_bl, counts_bl, b, bin, LA.dot(du, rh), LA.dot(du, du), CT) + if ok && 1 <= bin <= nb + du, rh = SFH.pair_increments(geom, frame, dist, Xi, Xj, + _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) + _bl_sp1d_write!(sums_bl, counts_bl, b - boff, bin, LA.dot(du, rh), LA.dot(du, du), CT) end end end @@ -269,12 +330,11 @@ end end @inline function _bl_sp2d_write!(sums_bl, counts_bl, b, dbin, vals, value_bins, n_val, ::Type{CT}) where {CT} - @inbounds for t in 1:SINGLE_PASS_N - vb = _sp2d_value_bin_at(value_bins, t) + @sp2d_each_invariant value_bins t vb begin vbin = SFH.digitize(vals[t], vb) if 1 <= vbin <= (length(vb) - 1) && vbin <= n_val - sums_bl[b, t, dbin, vbin] += vals[t] - counts_bl[b, t, dbin, vbin] += one(CT) + @inbounds sums_bl[b, t, dbin, vbin] += vals[t] + @inbounds counts_bl[b, t, dbin, vbin] += one(CT) end end return nothing @@ -282,22 +342,24 @@ end function _bl_sp2d_shared!( sums_bl::AbstractArray{OT, 4}, counts_bl::AbstractArray{CT, 4}, - x::AbstractMatrix, ub::AbstractArray{<:Any, 3}, dist_be, value_bins, ::Val{D}, irange, + x::AbstractMatrix, ub::AbstractArray{<:Any, 3}, dist_be, value_bins, geom, ::Val{D}, irange, brange, ) where {OT, CT, D} - B = size(ub, 1); N = size(ub, 3); nb = size(sums_bl, 3); n_val = size(sums_bl, 4) + N = size(ub, 3); nb = size(sums_bl, 3); n_val = size(sums_bl, 4) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange - Xi = SA.SVector{D}(ntuple(d -> x[d, i], Val(D))) + Xi = _bl_pt(x, i, vW) for j in (i + 1):N - Xj = SA.SVector{D}(ntuple(d -> x[d, j], Val(D))) - dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) + Xj = _bl_pt(x, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = SFH.digitize(dist, dist_be) - (1 <= dbin <= nb) || continue - rh = dx / dist - for b in 1:B - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) + (ok && 1 <= dbin <= nb) || continue + rh = SFH.pair_direction(geom, frame, dist) + for b in brange + du = SFH.pair_delta(geom, frame, Xi, Xj, _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) vals = _sp1d_vals(LA.dot(du, rh), LA.dot(du, du)) - _bl_sp2d_write!(sums_bl, counts_bl, b, dbin, vals, value_bins, n_val, CT) + _bl_sp2d_write!(sums_bl, counts_bl, b - boff, dbin, vals, value_bins, n_val, CT) end end end @@ -306,20 +368,24 @@ end function _bl_sp2d_varying!( sums_bl::AbstractArray{OT, 4}, counts_bl::AbstractArray{CT, 4}, - xb::AbstractArray{<:Any, 3}, ub::AbstractArray{<:Any, 3}, dist_be, value_bins, ::Val{D}, irange, + xb::AbstractArray{<:Any, 3}, ub::AbstractArray{<:Any, 3}, dist_be, value_bins, geom, ::Val{D}, irange, brange, ) where {OT, CT, D} - B = size(ub, 1); N = size(ub, 3); nb = size(sums_bl, 3); n_val = size(sums_bl, 4) + N = size(ub, 3); nb = size(sums_bl, 3); n_val = size(sums_bl, 4) + boff = first(brange) - 1 + vW = SFH.coordinate_width(geom) + vD = Val(D) @inbounds for i in irange for j in (i + 1):N - for b in 1:B - dx = SA.SVector{D}(ntuple(d -> xb[b, d, j] - xb[b, d, i], Val(D))) - dist = sqrt(LA.dot(dx, dx)) + for b in brange + Xi = _bl_pt(xb, b, i, vW) + Xj = _bl_pt(xb, b, j, vW) + ok, dist, frame = SFH.pair_frame(geom, Xi, Xj) dbin = SFH.digitize(dist, dist_be) - (1 <= dbin <= nb) || continue - rh = dx / dist - du = SA.SVector{D}(ntuple(d -> ub[b, d, j] - ub[b, d, i], Val(D))) + (ok && 1 <= dbin <= nb) || continue + du, rh = SFH.pair_increments(geom, frame, dist, Xi, Xj, + _bl_vel(ub, b, i, vD), _bl_vel(ub, b, j, vD)) vals = _sp1d_vals(LA.dot(du, rh), LA.dot(du, du)) - _bl_sp2d_write!(sums_bl, counts_bl, b, dbin, vals, value_bins, n_val, CT) + _bl_sp2d_write!(sums_bl, counts_bl, b - boff, dbin, vals, value_bins, n_val, CT) end end end @@ -335,77 +401,176 @@ end # partition `i` with round-robin chunks (triangle load balance) and reduce thread-local # accumulators, mirroring the point-field threaded path. # -# executor(make_accum, run_chunk!, ifull) → reduced (sums_bl, counts_bl): -# make_accum() → fresh zeroed (sums_bl, counts_bl) -# run_chunk!((sums_bl,counts_bl), isub) → kernel over outer i ∈ isub -# serial : one accumulator over ifull -# threaded: per-chunk accumulators, reduced by elementwise + +# executor(make_accum, run_chunk!, ifull, B, accum_bytes, ws) → reduced (sums, counts), width B: +# make_accum(bw) → fresh zeroed (sums_bl, counts_bl) of batch width bw +# run_chunk!(acc, isub, brange) → kernel over outer i ∈ isub and batch b ∈ brange +# accum_bytes → bytes of one full-width accumulator, for the split model +# ws → CPUSFWorkspace to draw accumulators from, or `nothing` +# serial : one full-width accumulator over ifull +# threaded: partitions (i, b); per-task accumulators are only as wide as their b-chunk # ======================================================================================== -@inline function _bl_serial_exec(make_accum, run_chunk!, ifull) - acc = make_accum() - run_chunk!(acc, ifull) +@inline function _bl_serial_exec(make_accum, run_chunk!, ifull, B, accum_bytes, ws) + acc = _bl_accum_pool(ws, make_accum, [B])[1] + _bl_zero_accum!(acc) + run_chunk!(acc, ifull, 1:B) return acc end -function _bl_run_1d!(sums, counts, sf_type, x, u, dist_be, executor) +""" + _bl_accum_pool(ws, make_accum, widths) -> Vector + +One accumulator per task, of the given batch widths, drawn from the workspace when there is one and +allocated fresh otherwise. Always built outside the parallel region, so tasks only read their slot. +""" +_bl_accum_pool(::Nothing, make_accum::F, widths::Vector{Int}) where {F} = + [make_accum(w) for w in widths] + +"""The full-width reduction accumulator, from the workspace when there is one.""" +_bl_result_accum(::Nothing, make_accum::F, B::Int) where {F} = make_accum(B) + +@inline function _bl_zero_accum!(acc) + fill!(acc[1], zero(eltype(acc[1]))) + fill!(acc[2], zero(eltype(acc[2]))) + return acc +end + +"""Bytes in one full-width `(sums, counts)` accumulator of shape `dims`.""" +@inline _bl_accum_bytes(::Type{OT}, ::Type{CT}, dims::Vararg{Int}) where {OT, CT} = + prod(dims) * (sizeof(OT) + sizeof(CT)) + +""" + _bl_batch_chunk_count(accum_bytes, B, n_tasks) -> Int + +How many chunks to split the batch axis into, given the full-width accumulator size in bytes. + +Every task holds an accumulator, so the live footprint is `n_tasks * accum_bytes` — that is what +turns into GC and page-fault time, and it is what a batch chunk divides. Splitting `b` costs pair +geometry, recomputed once per batch chunk, so the right answer is the SMALLEST split that brings +the footprint under budget. Kernels whose footprint already fits (the 1D batch accumulator is tens +of KiB) keep `Bc == 1` and never pay geometry twice; the single-pass 2D accumulator at large `B` +and many threads reaches hundreds of MiB and is split until it fits. +""" +@inline function _bl_batch_chunk_count(accum_bytes::Int, B::Int, n_tasks::Int) + footprint = accum_bytes * n_tasks + footprint <= _BL_ACCUM_BUDGET && return 1 + return clamp(cld(footprint, _BL_ACCUM_BUDGET), 1, min(n_tasks, B)) +end + +# Live accumulator footprint across all tasks, above which the batch axis is split. +const _BL_ACCUM_BUDGET = 64 * 1024 * 1024 + +"""Contiguous batch-axis chunks; `_bl_batch_chunk_count` picks `n`.""" +@inline _bl_batch_chunks(B::Int, n::Int) = + [(((k - 1) * B) ÷ n + 1):((k * B) ÷ n) for k in 1:n] + +""" + _bl_n_tasks(backend) -> Int + +How many tasks a batch call on `backend` splits into, and therefore how many accumulators a +[`CPUSFWorkspace`](@ref) must hold. A threaded backend falls back to the serial executor when +OhMyThreads is not loaded, so the count follows the executor that will actually run. +""" +_bl_n_tasks(::CB.AbstractExecutionBackend) = 1 +_bl_n_tasks(::CB.AbstractThreadedBackend) = _ohmythreads_loaded() ? Threads.nthreads() : 1 +_bl_n_tasks(b::CB.AbstractMPIBackend) = _bl_n_tasks(CB.local_backend(b)) +_bl_n_tasks(b::CB.AbstractDistributedBackend) = _bl_n_tasks(CB.local_backend(b)) + +""" + _bl_executor(backend) -> executor + +The batch-leading executor a local backend runs with, as a value. Backends that compose over a +local inner backend (MPI) look it up here; extensions add methods for the backends they provide. +""" +_bl_executor(::CB.AbstractSerialBackend) = _bl_serial_exec +_bl_executor(b::CB.AbstractExecutionBackend) = throw(ArgumentError( + "no batch-leading executor for $(nameof(typeof(b))); use SerialBackend, or load the extension \ + providing it (ThreadedBackend needs OhMyThreads).")) + +""" + _bl_add_permuted!(dest, src_bl, perm) + +Add the batch-leading accumulator `src_bl` into `dest` through the permutation `perm`. + +`!` entry points across the package **accumulate** into the caller's buffers; zeroing belongs to the +non-mutating wrappers. `PermutedDimsArray` is a lazy view, so this fuses the permute with the add +and allocates nothing. +""" +@inline function _bl_add_permuted!(dest, src_bl, perm) + dest .+= PermutedDimsArray(src_bl, perm) + return dest +end + +function _bl_run_1d!(sums, counts, sf_type, x, u, dist_be, distance_metric, executor, workspace = nothing) n_bins = n_histogram_bins(dist_be) OT = eltype(sums); CT = eltype(counts) - xb, ub, B, D, N, fixed_x = _bl_prepare(x, u) + xb, ub, B, D, W, N, fixed_x = _bl_prepare(x, u, workspace) vD = Val(D) - make_accum() = (zeros(OT, B, n_bins), zeros(CT, B, n_bins)) + geom = SFH.pair_geometry_for(distance_metric, vD) + _validate_bl_geometry(geom, W, D) + _validate_ws_layout(workspace, :sf1d, (n_bins,)) + make_accum(bw) = (zeros(OT, bw, n_bins), zeros(CT, bw, n_bins)) run_chunk! = fixed_x ? - ((acc, isub) -> _bl_shared_1d!(acc[1], acc[2], xb, ub, sf_type, dist_be, vD, isub)) : - ((acc, isub) -> _bl_varying_1d!(acc[1], acc[2], xb, ub, sf_type, dist_be, vD, isub)) - sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1)) - permutedims!(reshape(sums, n_bins, B), sums_bl, (2, 1)) - permutedims!(reshape(counts, n_bins, B), counts_bl, (2, 1)) + ((acc, isub, br) -> _bl_shared_1d!(acc[1], acc[2], xb, ub, sf_type, dist_be, geom, vD, isub, br)) : + ((acc, isub, br) -> _bl_varying_1d!(acc[1], acc[2], xb, ub, sf_type, dist_be, geom, vD, isub, br)) + sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1), B, _bl_accum_bytes(OT, CT, B, n_bins), workspace) + _bl_add_permuted!(reshape(sums, n_bins, B), sums_bl, (2, 1)) + _bl_add_permuted!(reshape(counts, n_bins, B), counts_bl, (2, 1)) return nothing end -function _bl_run_joint2d!(sums, counts, sf_type, x, u, dist_be, val_be, executor) +function _bl_run_joint2d!(sums, counts, sf_type, x, u, dist_be, val_be, distance_metric, executor, workspace = nothing) n_dist = n_histogram_bins(dist_be); n_val = n_histogram_bins(val_be) OT = eltype(sums); CT = eltype(counts) - xb, ub, B, D, N, fixed_x = _bl_prepare(x, u) + xb, ub, B, D, W, N, fixed_x = _bl_prepare(x, u, workspace) vD = Val(D) - make_accum() = (zeros(OT, B, n_dist, n_val), zeros(CT, B, n_dist, n_val)) + geom = SFH.pair_geometry_for(distance_metric, vD) + _validate_bl_geometry(geom, W, D) + _validate_ws_layout(workspace, :joint2d, (n_dist, n_val)) + make_accum(bw) = (zeros(OT, bw, n_dist, n_val), zeros(CT, bw, n_dist, n_val)) run_chunk! = fixed_x ? - ((acc, isub) -> _bl_joint2d_shared!(acc[1], acc[2], xb, ub, sf_type, dist_be, val_be, vD, isub)) : - ((acc, isub) -> _bl_joint2d_varying!(acc[1], acc[2], xb, ub, sf_type, dist_be, val_be, vD, isub)) - sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1)) - permutedims!(reshape(sums, n_dist, n_val, B), sums_bl, (2, 3, 1)) - permutedims!(reshape(counts, n_dist, n_val, B), counts_bl, (2, 3, 1)) + ((acc, isub, br) -> _bl_joint2d_shared!(acc[1], acc[2], xb, ub, sf_type, dist_be, val_be, geom, vD, isub, br)) : + ((acc, isub, br) -> _bl_joint2d_varying!(acc[1], acc[2], xb, ub, sf_type, dist_be, val_be, geom, vD, isub, br)) + sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1), B, _bl_accum_bytes(OT, CT, B, n_dist, n_val), workspace) + _bl_add_permuted!(reshape(sums, n_dist, n_val, B), sums_bl, (2, 3, 1)) + _bl_add_permuted!(reshape(counts, n_dist, n_val, B), counts_bl, (2, 3, 1)) return nothing end -function _bl_run_sp1d!(sums, counts, x, u, dist_be, executor) +function _bl_run_sp1d!(sums, counts, x, u, dist_be, distance_metric, executor, workspace = nothing) n_bins = n_histogram_bins(dist_be) OT = eltype(sums); CT = eltype(counts) - xb, ub, B, D, N, fixed_x = _bl_prepare(x, u) + xb, ub, B, D, W, N, fixed_x = _bl_prepare(x, u, workspace) vD = Val(D) - make_accum() = (zeros(OT, B, SINGLE_PASS_N, n_bins), zeros(CT, B, SINGLE_PASS_N, n_bins)) + geom = SFH.pair_geometry_for(distance_metric, vD) + _validate_bl_geometry(geom, W, D) + _validate_ws_layout(workspace, :single_pass, (SINGLE_PASS_N, n_bins)) + make_accum(bw) = (zeros(OT, bw, SINGLE_PASS_N, n_bins), zeros(CT, bw, SINGLE_PASS_N, n_bins)) run_chunk! = fixed_x ? - ((acc, isub) -> _bl_sp1d_shared!(acc[1], acc[2], xb, ub, dist_be, vD, isub)) : - ((acc, isub) -> _bl_sp1d_varying!(acc[1], acc[2], xb, ub, dist_be, vD, isub)) - sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1)) - permutedims!(reshape(sums, SINGLE_PASS_N, n_bins, B), sums_bl, (2, 3, 1)) - permutedims!(reshape(counts, SINGLE_PASS_N, n_bins, B), counts_bl, (2, 3, 1)) + ((acc, isub, br) -> _bl_sp1d_shared!(acc[1], acc[2], xb, ub, dist_be, geom, vD, isub, br)) : + ((acc, isub, br) -> _bl_sp1d_varying!(acc[1], acc[2], xb, ub, dist_be, geom, vD, isub, br)) + sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1), B, _bl_accum_bytes(OT, CT, B, SINGLE_PASS_N, n_bins), workspace) + _bl_add_permuted!(reshape(sums, SINGLE_PASS_N, n_bins, B), sums_bl, (2, 3, 1)) + _bl_add_permuted!(reshape(counts, SINGLE_PASS_N, n_bins, B), counts_bl, (2, 3, 1)) return nothing end -function _bl_run_sp2d!(sums, counts, x, u, dist_be, value_bins, executor) +function _bl_run_sp2d!(sums, counts, x, u, dist_be, value_bins, distance_metric, executor, workspace = nothing) n_bins = n_histogram_bins(dist_be) n_val = size(sums, 3) _validate_value_bins!(value_bins, n_val) OT = eltype(sums); CT = eltype(counts) - xb, ub, B, D, N, fixed_x = _bl_prepare(x, u) + xb, ub, B, D, W, N, fixed_x = _bl_prepare(x, u, workspace) vD = Val(D) - make_accum() = (zeros(OT, B, SINGLE_PASS_N, n_bins, n_val), zeros(CT, B, SINGLE_PASS_N, n_bins, n_val)) + geom = SFH.pair_geometry_for(distance_metric, vD) + _validate_bl_geometry(geom, W, D) + _validate_ws_layout(workspace, :single_pass_2d, (SINGLE_PASS_N, n_bins, n_val)) + make_accum(bw) = (zeros(OT, bw, SINGLE_PASS_N, n_bins, n_val), zeros(CT, bw, SINGLE_PASS_N, n_bins, n_val)) run_chunk! = fixed_x ? - ((acc, isub) -> _bl_sp2d_shared!(acc[1], acc[2], xb, ub, dist_be, value_bins, vD, isub)) : - ((acc, isub) -> _bl_sp2d_varying!(acc[1], acc[2], xb, ub, dist_be, value_bins, vD, isub)) - sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1)) - permutedims!(reshape(sums, SINGLE_PASS_N, n_bins, n_val, B), sums_bl, (2, 3, 4, 1)) - permutedims!(reshape(counts, SINGLE_PASS_N, n_bins, n_val, B), counts_bl, (2, 3, 4, 1)) + ((acc, isub, br) -> _bl_sp2d_shared!(acc[1], acc[2], xb, ub, dist_be, value_bins, geom, vD, isub, br)) : + ((acc, isub, br) -> _bl_sp2d_varying!(acc[1], acc[2], xb, ub, dist_be, value_bins, geom, vD, isub, br)) + sums_bl, counts_bl = executor(make_accum, run_chunk!, 1:(N - 1), B, _bl_accum_bytes(OT, CT, B, SINGLE_PASS_N, n_bins, n_val), workspace) + _bl_add_permuted!(reshape(sums, SINGLE_PASS_N, n_bins, n_val, B), sums_bl, (2, 3, 4, 1)) + _bl_add_permuted!(reshape(counts, SINGLE_PASS_N, n_bins, n_val, B), counts_bl, (2, 3, 4, 1)) return nothing end diff --git a/src/Calculations/dispatch.jl b/src/Calculations/dispatch.jl index 285361e..5bc1a1c 100644 --- a/src/Calculations/dispatch.jl +++ b/src/Calculations/dispatch.jl @@ -65,19 +65,26 @@ function calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x::AbstractArray{FT1}, u::AbstractArray{FT2}, - distance_bins::AbstractVector; - backend::AbstractExecutionBackend = AutoBackend(), + distance_bins::AbstractVector, + count_eltype::Type{CT} = UInt32 + ; + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), output_type::Type{OT} = SFO.StructureFunction, + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., -) where {FT1, FT2, OT} - shape = _validate_array_shape(x, u) +) where {FT1, FT2, OT, CT} + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(CT, size(x, 2)) raw = _dispatch_execution_backend( backend, shape, structure_function_type, x, u, - distance_bins; + distance_bins, + count_eltype + ; + distance_metric, kwargs..., ) return _finalize(raw, output_type) @@ -89,7 +96,7 @@ function calculate_structure_function( u_vecs::Tuple, distance_bins::AbstractVector, value_bins::AbstractVector; - backend::AbstractExecutionBackend = AutoBackend(), + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), kwargs..., ) _unsupported_tuple_input() @@ -103,12 +110,16 @@ function calculate_structure_function( x::AbstractArray{FT1}, u::AbstractArray{FT2}, distance_bins::AbstractVector, - value_bins::AbstractVector; - backend::AbstractExecutionBackend = AutoBackend(), + value_bins::AbstractVector, + count_eltype::Type{CT} = UInt32 + ; + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), output_type::Type{OT} = SFO.StructureFunction2DSumsAndCounts, + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., -) where {FT1, FT2, OT} - shape = _validate_array_shape(x, u) +) where {FT1, FT2, OT, CT} + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(CT, size(x, 2)) raw = _dispatch_execution_backend( backend, shape, @@ -117,6 +128,8 @@ function calculate_structure_function( u, distance_bins, value_bins; + distance_metric, + count_eltype, kwargs..., ) return _finalize(raw, output_type) @@ -143,13 +156,13 @@ function calculate_structure_function( u::AbstractArray{FT2}, distance_bins::Int, args...; + distance_metric::DI.PreMetric = DI.Euclidean(), + bin_spacing::Type{<:AbstractBinEdges} = LogBinEdges, + verbose::Bool = true, + show_progress::Bool = true, kwargs..., ) where {FT1, FT2} - shape = _validate_array_shape(x, u) - distance_metric = get(kwargs, :distance_metric, DI.Euclidean()) - bin_spacing = get(kwargs, :bin_spacing, LogBinEdges) - verbose = get(kwargs, :verbose, true) - show_progress = get(kwargs, :show_progress, true) + shape = _validate_array_shape(x, u, distance_metric) if verbose @info("Calculating min and max distances and generating bins") @@ -157,12 +170,17 @@ function calculate_structure_function( min_distance, max_distance = _minmax_for_autobins(shape, x, distance_metric, show_progress) actual_bins = _auto_distance_bins(min_distance, max_distance, distance_bins, bin_spacing) + # `bin_spacing` selected these edges and means nothing downstream, so it is consumed here + # rather than forwarded into a `kwargs...` sink that would silently swallow it. return calculate_structure_function( structure_function_type, x, u, actual_bins, args...; + distance_metric, + verbose, + show_progress, kwargs..., ) end @@ -193,7 +211,9 @@ function _minmax_for_autobins(::SharedPositionField, x::AbstractMatrix, distance end function _minmax_matrix_for_autobins(x::AbstractMatrix, distance_metric, show_progress::Bool) - min_distance, max_distance = Inf, 0.0 + # Accumulate in the input eltype; Float64 literals here would widen the bin edges. + FT = float(eltype(x)) + min_distance, max_distance = FT(Inf), FT(0) PM.@showprogress enabled = show_progress for i in axes(x, 2) _min_distance, _max_distance = minmax_i(i, x, distance_metric) min_distance = min(min_distance, _min_distance) @@ -206,7 +226,8 @@ function _minmax_for_autobins(::VaryingPositionField, x::AbstractArray, distance D, N = size(x, 1), size(x, 2) B = prod(size(x)[3:end]) x_flat = reshape(x, D, N, B) - min_distance, max_distance = Inf, 0.0 + FT = float(eltype(x)) + min_distance, max_distance = FT(Inf), FT(0) PM.@showprogress enabled = show_progress for b in 1:B x_slice = @view x_flat[:, :, b] for i in axes(x_slice, 2) @@ -236,8 +257,9 @@ function minmax_i( min_distance, max_distance = FT(Inf), FT(0.0) iter_inds = eachindex(x_vecs[1]) + # `j > i`: the metric is symmetric, so `j != i` measured every pair twice. for j in iter_inds - if i != j + if j > i X2 = SA.SVector{D, FT}(ntuple(k -> x_vecs[k][j], Val(D))) distance = distance_metric(X1, X2) if distance < min_distance @@ -316,40 +338,44 @@ end function calculate_structure_function!( sums, counts, sf_type, x::Tuple, u::Tuple, distance_bins; - backend=SerialBackend(), kwargs... + backend=CB.SerialBackend(), kwargs... ) _unsupported_tuple_input() end function calculate_structure_function!( sums, counts, sf_type, x::AbstractArray, u::AbstractArray, distance_bins; - backend=SerialBackend(), kwargs... + backend=CB.SerialBackend(), distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) - shape = _validate_array_shape(x, u) - _dispatch_execution_backend!(backend, shape, sums, counts, sf_type, x, u, distance_bins; kwargs...) + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(eltype(counts), size(x, 2)) + _dispatch_execution_backend!(backend, shape, sums, counts, sf_type, x, u, distance_bins; + distance_metric, kwargs...) return nothing end function calculate_structure_function!( sums_2d, counts_2d, sf_type, x::Tuple, u::Tuple, distance_bins, value_bins; - backend=SerialBackend(), kwargs... + backend=CB.SerialBackend(), kwargs... ) _unsupported_tuple_input() end function calculate_structure_function!( sums_2d, counts_2d, sf_type, x::AbstractArray, u::AbstractArray, distance_bins, value_bins; - backend=SerialBackend(), kwargs... + backend=CB.SerialBackend(), distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) - shape = _validate_array_shape(x, u) - _dispatch_execution_backend!(backend, shape, sums_2d, counts_2d, sf_type, x, u, distance_bins, value_bins; kwargs...) + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(eltype(counts_2d), size(x, 2)) + _dispatch_execution_backend!(backend, shape, sums_2d, counts_2d, sf_type, x, u, distance_bins, value_bins; + distance_metric, kwargs...) return nothing end # # --- Backend Dispatch Layers for Mutating API --- function _dispatch_execution_backend!( - ::SerialBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + ::CB.AbstractSerialBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) if has_auxiliary_axes(shape) auxiliary_structure_function!(sums, counts, structure_function_type, x, u, distance_bins; kwargs...) @@ -360,7 +386,7 @@ function _dispatch_execution_backend!( end function _dispatch_execution_backend!( - ::ThreadedBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + ::CB.AbstractThreadedBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) if has_auxiliary_axes(shape) auxiliary_structure_function_threaded!(sums, counts, structure_function_type, x, u, distance_bins; kwargs...) @@ -371,27 +397,27 @@ function _dispatch_execution_backend!( end function _dispatch_execution_backend!( - backend::GPUBackend, shape::PointField, sums::AbstractVector, counts::AbstractVector, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + backend::CB.AbstractGPUBackend, shape::PointField, sums::AbstractVector, counts::AbstractVector, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) gpu_calculate_structure_function!(sums, counts, structure_function_type, backend.backend, x, u, distance_bins; kwargs...) return nothing end function _dispatch_execution_backend!( - backend::GPUBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + backend::CB.AbstractGPUBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) throw(ArgumentError("in-place auxiliary-axis calculate_structure_function! is not implemented for GPUBackend")) end # --- Replaced AutoBackend Mutating Dispatch --- function _dispatch_execution_backend!( - ::AutoBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + ::CB.AbstractAutoBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) if has_auxiliary_axes(shape) if Threads.nthreads() > 1 - return _dispatch_execution_backend!(ThreadedBackend(), shape, sums, counts, structure_function_type, x, u, distance_bins; kwargs...) + return _dispatch_execution_backend!(CB.ThreadedBackend(), shape, sums, counts, structure_function_type, x, u, distance_bins; kwargs...) end - return _dispatch_execution_backend!(SerialBackend(), shape, sums, counts, structure_function_type, x, u, distance_bins; kwargs...) + return _dispatch_execution_backend!(CB.SerialBackend(), shape, sums, counts, structure_function_type, x, u, distance_bins; kwargs...) end if Threads.nthreads() > 1 && @@ -405,7 +431,7 @@ end # --- Mutating 2D Backend Dispatch Layers --- function _dispatch_execution_backend!( - ::SerialBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractSerialBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) if has_auxiliary_axes(shape) auxiliary_joint2d!(sums_2d, counts_2d, structure_function_type, x, u, distance_bins, value_bins; kwargs...) @@ -416,7 +442,7 @@ function _dispatch_execution_backend!( end function _dispatch_execution_backend!( - ::ThreadedBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractThreadedBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) if has_auxiliary_axes(shape) auxiliary_joint2d_threaded!(sums_2d, counts_2d, structure_function_type, x, u, distance_bins, value_bins; kwargs...) @@ -427,19 +453,19 @@ function _dispatch_execution_backend!( end function _dispatch_execution_backend!( - backend::GPUBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + backend::CB.AbstractGPUBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) throw(ArgumentError("In-place calculate_structure_function! is not supported on GPU backend.")) end function _dispatch_execution_backend!( - ::AutoBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractAutoBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) if has_auxiliary_axes(shape) if Threads.nthreads() > 1 - return _dispatch_execution_backend!(ThreadedBackend(), shape, sums_2d, counts_2d, structure_function_type, x, u, distance_bins, value_bins; kwargs...) + return _dispatch_execution_backend!(CB.ThreadedBackend(), shape, sums_2d, counts_2d, structure_function_type, x, u, distance_bins, value_bins; kwargs...) end - return _dispatch_execution_backend!(SerialBackend(), shape, sums_2d, counts_2d, structure_function_type, x, u, distance_bins, value_bins; kwargs...) + return _dispatch_execution_backend!(CB.SerialBackend(), shape, sums_2d, counts_2d, structure_function_type, x, u, distance_bins, value_bins; kwargs...) end if Threads.nthreads() > 1 && @@ -451,25 +477,25 @@ function _dispatch_execution_backend!( end function _dispatch_execution_backend!( - ::DistributedBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + ::CB.AbstractDistributedBackend, shape::AbstractFieldShape, sums, counts, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) throw(ArgumentError("calculate_structure_function! is not implemented for DistributedBackend.")) end function _dispatch_execution_backend!( - backend::AbstractExecutionBackend, sums::AbstractArray, counts::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... + backend::CB.AbstractExecutionBackend, sums::AbstractArray, counts::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... ) throw(ArgumentError("calculate_structure_function! is not implemented for backend $(typeof(backend)).")) end function _dispatch_execution_backend!( - ::DistributedBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractDistributedBackend, shape::AbstractFieldShape, sums_2d, counts_2d, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) throw(ArgumentError("calculate_structure_function! with distance_bins and value_bins is not implemented for DistributedBackend.")) end function _dispatch_execution_backend!( - backend::AbstractExecutionBackend, sums_2d::AbstractArray, counts_2d::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + backend::CB.AbstractExecutionBackend, sums_2d::AbstractArray, counts_2d::AbstractArray, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) throw(ArgumentError("calculate_structure_function! with distance_bins and value_bins is not implemented for backend $(typeof(backend)).")) end @@ -482,83 +508,73 @@ end # 1D function _dispatch_execution_backend( - ::SerialBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... -) - return serial_calculate_structure_function(structure_function_type, x, u, distance_bins; kwargs...) + ::CB.AbstractSerialBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... +) where {CT} + return serial_calculate_structure_function(structure_function_type, x, u, distance_bins, count_eltype; kwargs...) end function _dispatch_execution_backend( - ::SerialBackend, shape::PointField{D}, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... -) where {D} + ::CB.AbstractSerialBackend, shape::PointField{D}, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; + kwargs... +) where {D, CT} return _serial_calculate_structure_function_point( - structure_function_type, x, u, distance_bins, Val(D); kwargs..., + structure_function_type, x, u, distance_bins, Val(D), count_eltype; kwargs..., ) end function _dispatch_execution_backend( - ::ThreadedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... -) - return threaded_calculate_structure_function(structure_function_type, x, u, distance_bins; kwargs...) + ::CB.AbstractThreadedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... +) where {CT} + return threaded_calculate_structure_function(structure_function_type, x, u, distance_bins, count_eltype; kwargs...) end function _dispatch_execution_backend( - backend::DistributedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... -) - return _dispatch_execution_backend(backend, structure_function_type, x, u, distance_bins; kwargs...) + backend::CB.AbstractDistributedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... +) where {CT} + return _dispatch_execution_backend(backend, structure_function_type, x, u, distance_bins; count_eltype, kwargs...) end function _dispatch_execution_backend( - backend::GPUBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... -) + backend::CB.AbstractGPUBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... +) where {CT} if has_auxiliary_axes(shape) - return gpu_calculate_structure_function_batch(structure_function_type, backend.backend, x, u, distance_bins; kwargs...) + return gpu_calculate_structure_function_batch(structure_function_type, backend.backend, x, u, distance_bins; count_eltype, kwargs...) end - return gpu_calculate_structure_function(structure_function_type, backend.backend, x, u, distance_bins; kwargs...) + return gpu_calculate_structure_function(structure_function_type, backend.backend, x, u, distance_bins; count_eltype, kwargs...) end function _dispatch_execution_backend( - ::AutoBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins; kwargs... -) - if distributed_workers_available(Val(:distributed)) - return _dispatch_execution_backend(DistributedBackend(), shape, structure_function_type, x, u, distance_bins; kwargs...) - end - - if has_auxiliary_axes(shape) - if Threads.nthreads() > 1 - return _dispatch_execution_backend(ThreadedBackend(), shape, structure_function_type, x, u, distance_bins; kwargs...) - end - return _dispatch_execution_backend(SerialBackend(), shape, structure_function_type, x, u, distance_bins; kwargs...) - end - - if Threads.nthreads() > 1 && - _threaded_backend_available(structure_function_type, x, u, distance_bins) - return _dispatch_execution_backend(ThreadedBackend(), shape, structure_function_type, x, u, distance_bins; kwargs...) - end - - return _dispatch_execution_backend(SerialBackend(), shape, structure_function_type, x, u, distance_bins; kwargs...) + ::CB.AbstractAutoBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, count_eltype::Type{CT} = UInt32; kwargs... +) where {CT} + backend = resolve_auto_backend( + shape, + () -> _threaded_backend_available(structure_function_type, x, u, distance_bins), + () -> true, + ) + return _dispatch_execution_backend(backend, shape, structure_function_type, x, u, distance_bins, count_eltype; kwargs...) end # 2D (joint distance×value) function _dispatch_execution_backend( - ::SerialBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractSerialBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) return serial_calculate_structure_function(structure_function_type, x, u, distance_bins, value_bins; kwargs...) end function _dispatch_execution_backend( - ::ThreadedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractThreadedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) return threaded_calculate_structure_function(structure_function_type, x, u, distance_bins, value_bins; kwargs...) end function _dispatch_execution_backend( - backend::DistributedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + backend::CB.AbstractDistributedBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) return _dispatch_execution_backend(backend, structure_function_type, x, u, distance_bins, value_bins; kwargs...) end function _dispatch_execution_backend( - backend::GPUBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + backend::CB.AbstractGPUBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) if has_auxiliary_axes(shape) return gpu_calculate_structure_function_2d_batch(structure_function_type, backend.backend, x, u, distance_bins, value_bins; kwargs...) @@ -567,23 +583,12 @@ function _dispatch_execution_backend( end function _dispatch_execution_backend( - ::AutoBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... + ::CB.AbstractAutoBackend, shape::AbstractFieldShape, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x, u, distance_bins, value_bins::AbstractVector; kwargs... ) - if distributed_workers_available(Val(:distributed)) - return _dispatch_execution_backend(DistributedBackend(), shape, structure_function_type, x, u, distance_bins, value_bins; kwargs...) - end - - if has_auxiliary_axes(shape) - if Threads.nthreads() > 1 - return _dispatch_execution_backend(ThreadedBackend(), shape, structure_function_type, x, u, distance_bins, value_bins; kwargs...) - end - return _dispatch_execution_backend(SerialBackend(), shape, structure_function_type, x, u, distance_bins, value_bins; kwargs...) - end - - if Threads.nthreads() > 1 && - _threaded_backend_available(structure_function_type, x, u, distance_bins) - return _dispatch_execution_backend(ThreadedBackend(), shape, structure_function_type, x, u, distance_bins, value_bins; kwargs...) - end - - return _dispatch_execution_backend(SerialBackend(), shape, structure_function_type, x, u, distance_bins, value_bins; kwargs...) + backend = resolve_auto_backend( + shape, + () -> _threaded_backend_available(structure_function_type, x, u, distance_bins), + () -> true, + ) + return _dispatch_execution_backend(backend, shape, structure_function_type, x, u, distance_bins, value_bins; kwargs...) end diff --git a/src/Calculations/gpu_stubs.jl b/src/Calculations/gpu_stubs.jl index c84e6d8..34b3ef0 100644 --- a/src/Calculations/gpu_stubs.jl +++ b/src/Calculations/gpu_stubs.jl @@ -15,15 +15,84 @@ shared for large single-pass). Returns `true` if handled, `false` to fall back to the portable KA tiled kernel. Overridden by `StructureFunctionsCUDAExt`.""" gpu_fast_launch_2d_batch!(backend, out, cnt, x, u, sf_type, dist_dig, val_plan, - N, n_dist, n_val, B, D, nmom, fixed_x) = false + N, n_dist, n_val, B, D, nmom, fixed_x, geom) = false """Try the CUDA fast 1D launch (N-body broadcast + privatized shared histogram). Returns `true` if handled, `false` to fall back to the portable KA tiled kernel. Overridden by `StructureFunctionsCUDAExt`.""" gpu_fast_launch_1d_batch!(backend, out, cnt, x, u, sf_type, dist_dig, - N, NB, B, D, nmom, fixed_x) = false + N, NB, B, D, nmom, fixed_x, geom) = false +""" + GPUDeviceCaps + +What a GPU backend can actually offer, queried rather than assumed, so shared-memory strategy is +chosen per device instead of per hardcoded constant. Shared memory per block differs by an order of +magnitude across parts a user may run on (V100 96 KiB, L40S 100 KiB, A100 163 KiB, later parts +more), and the right accumulation strategy differs with it. + +`smem_per_block` is the **opt-in** maximum, reachable only by *dynamic* shared memory that a kernel +explicitly requests; `smem_per_sm` bounds how many blocks stay resident and is what makes "use every +byte" the wrong default. + +Static shared memory is capped far lower and independently — see [`GPU_SMEM_STATIC_MAX`]. +KernelAbstractions' `@localmem` lowers to a *static* allocation (`CuStaticSharedArray` on CUDA) and +its launch path passes no `shmem`, so a kernel written once for every backend is bound by the static +cap. Reaching `smem_per_block` therefore takes a backend-specialized kernel that declares dynamic +shared memory and opts in at launch — which is what the vendor fast paths do, with the portable +kernel remaining as the correctness fallback for backends that have none. +""" +struct GPUDeviceCaps + smem_per_block::Int + smem_per_sm::Int + n_sms::Int + warp::Int +end + +""" +Largest *static* shared allocation a block may declare. Measured, not assumed: on an A100 a static +`@localmem` of 48 KiB compiles and 64 KiB fails `ptxas`, while dynamic shared reaches the full +163 KiB opt-in. This is an architectural limit rather than a per-device one, so exceeding a device's +opt-in maximum is a separate check. +""" +const GPU_SMEM_STATIC_MAX = 48 * 1024 + +"""Shared memory every CUDA-class device provides without opting in.""" +const GPU_SMEM_UNIVERSAL_FLOOR = 48 * 1024 + +""" + gpu_static_smem_budget(caps) -> Int + +Bytes a portable (static `@localmem`) kernel may use on this device: the static cap, further limited +if the device offers less than it. +""" +@inline gpu_static_smem_budget(caps::GPUDeviceCaps) = + min(GPU_SMEM_STATIC_MAX, caps.smem_per_block) + +""" + gpu_dynamic_smem_budget(caps; target_blocks_per_sm = 2) -> Int + +Bytes a dynamic-shared kernel should use per block. Expressed in device-relative terms — the opt-in +ceiling, and the per-SM pool divided by an occupancy target — so the same rule sizes correctly on any +part rather than encoding one device's byte count. `target_blocks_per_sm` is the only free parameter +and is dimensionless. +""" +@inline function gpu_dynamic_smem_budget(caps::GPUDeviceCaps; target_blocks_per_sm::Int = 2) + per_sm_share = caps.smem_per_sm ÷ max(1, target_blocks_per_sm) + return max(GPU_SMEM_UNIVERSAL_FLOOR, min(caps.smem_per_block, per_sm_share)) +end + +""" + gpu_device_caps(backend) -> GPUDeviceCaps + +Capabilities of `backend`. The default is deliberately the universal floor: a backend with no +override behaves exactly as the package did before device querying existed, so an unknown or future +backend degrades to "correct and portable" rather than to "assumes an A100". `StructureFunctionsCUDAExt` +overrides this with the real device attributes. +""" +gpu_device_caps(::Any) = GPUDeviceCaps(GPU_SMEM_UNIVERSAL_FLOOR, GPU_SMEM_UNIVERSAL_FLOOR, 1, 32) + """ GPUSFWorkspace(backend, distance_bins; kind=:sf1d) diff --git a/src/Calculations/serial.jl b/src/Calculations/serial.jl index a350636..4eb17b9 100644 --- a/src/Calculations/serial.jl +++ b/src/Calculations/serial.jl @@ -20,7 +20,7 @@ function serial_calculate_structure_function!( # Fast path: Euclidean + D ∈ (2,3) uses the SIMD compute/scatter-split kernel (vectorizes # the per-pair compute over j; only the histogram scatter is scalar). Other metrics/D fall # back to the scalar per-i kernel. - D = length(x_vecs) + D = length(u_vecs) if distance_metric isa DI.Euclidean && D == 2 return _pf_simd_run!(output, counts, structure_function_type, x_vecs, u_vecs, distance_bins, Val(2)) elseif distance_metric isa DI.Euclidean && D == 3 @@ -50,33 +50,30 @@ function _pf_simd_run!( sf::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, dist_be, ::Val{D}, ) where {OT, CT, D} - xc = ntuple(d -> collect(x_vecs[d]), Val(D)) # contiguous component vectors - uc = ntuple(d -> collect(u_vecs[d]), Val(D)) - N = length(xc[1]) - distbuf = Vector{eltype(xc[1])}(undef, N) - valbuf = Vector{OT}(undef, N) - _pf_simd_pairs!(output, counts, sf, xc, uc, dist_be, Val(D), distbuf, valbuf, 1:(N - 1)) - return nothing + N = length(x_vecs[1]) + return _pf_simd_partial!(output, counts, sf, x_vecs, u_vecs, dist_be, Val(D), 1:(N - 1)) end """ - _pf_simd_pairs!(output, counts, sf, xc, uc, dist_be, ::Val{D}, distbuf, valbuf, irange) - -Core point-field SIMD compute/scatter kernel over outer indices `irange` (each `i` contributes -pairs `(i, j>i)`). For each `i`: `@simd` over `j` computes distance + SF value into the buffers -(contiguous components ⇒ packed loads, no scatter ⇒ vectorizes), then a scalar loop digitizes + -scatters. The `i`-loop AND the inner `@simd` live in THIS function body and it is called once per -range — factoring the inner loop into a per-`i` helper stops the `@simd` from vectorizing. Shared -by the serial driver (full range) and the threaded extension (one chunk per task). + _pf_simd_pairs!(output, counts, sf, xc, uc, plan, ::Val{D}, r2buf, valbuf, idxbuf, irange) + +Accumulate pairs `(i, j>i)` for `i in irange` into `output`/`counts`. + +The `@simd` half writes `r²`, the SF value, and the approximate bin index to buffers; the scalar +half corrects the index and scatters straight into `output`/`counts`, skipping out-of-range bins. + +The `i`-loop and the inner `@simd` must stay in this function body; factoring the inner loop into a +per-`i` helper stops it vectorizing. """ function _pf_simd_pairs!( output::AbstractVector{OT}, counts::AbstractVector{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, - xc::NTuple{D}, uc::NTuple{D}, dist_be, ::Val{D}, - distbuf::AbstractVector, valbuf::AbstractVector, irange, + xc::NTuple{D}, uc::NTuple{D}, plan::AbstractSquaredDigitizePlan, ::Val{D}, + r2buf::AbstractVector, valbuf::AbstractVector, idxbuf::AbstractVector{Int32}, + irange, ) where {OT, CT, D} N = length(xc[1]) - nb = n_histogram_bins(dist_be) + nb = n_histogram_bins(plan) FTx = eltype(xc[1]) @inbounds for i in irange Xi = SA.SVector{D, FTx}(ntuple(d -> xc[d][i], Val(D))) @@ -84,23 +81,44 @@ function _pf_simd_pairs!( @simd for j in (i + 1):N Xj = SA.SVector{D, FTx}(ntuple(d -> xc[d][j], Val(D))) dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) + r2 = LA.dot(dx, dx) Uj = SA.SVector{D}(ntuple(d -> uc[d][j], Val(D))) - rh = dx / dist - distbuf[j] = dist - valbuf[j] = sf(Uj - Ui, rh) + r2buf[j] = digitize_key(plan, r2) + valbuf[j] = SFT._sf_raw(sf, Uj - Ui, dx, r2) + if has_vector_index(plan) # constant-folded: depends only on the plan type + idxbuf[j] = squared_approx_index(plan, r2) + end end for j in (i + 1):N - bin = SFH.digitize(distbuf[j], dist_be) - if 1 <= bin <= nb - output[bin] += valbuf[j] - counts[bin] += one(CT) + b = squared_bin(plan, r2buf[j], idxbuf[j]) + if 1 <= b <= nb + output[b] += valbuf[j] + counts[b] += one(CT) end end end return nothing end +""" + _assert_counts_representable(CT, n_points) + +Throw unless the worst-case pair count `n_points*(n_points-1)÷2` fits in `CT`. + +Every pair can land in one bin, so that product is the only safe bound. `UInt32` saturates at +`N = 92682`, past which the counter wraps silently. +""" +@inline function _assert_counts_representable(::Type{CT}, n_points::Integer) where {CT <: Integer} + n_pairs = (Int128(n_points) * (Int128(n_points) - 1)) ÷ 2 + n_pairs <= Int128(typemax(CT)) || throw( + ArgumentError( + "count_eltype=$CT cannot represent the worst-case pair count $n_pairs for N=$n_points " * + "(typemax($CT) = $(typemax(CT))); pass count_eltype=UInt64 or Int64.", + ), + ) + return nothing +end + """ _bin_average!(out, sums, counts) _bin_average(sums, counts) @@ -159,6 +177,7 @@ function serial_calculate_structure_function( count_eltype::Type{CT} = UInt32, kwargs..., ) where {T1, T2, CT} + _assert_counts_representable(CT, length(x_vecs[1])) FT1 = eltype(T1) FT2 = eltype(T2) OT = promote_type(float(FT1), float(FT2)) @@ -193,9 +212,8 @@ function serial_calculate_structure_function!( distance_bins::AbstractVector; kwargs..., ) where {OT, FT1 <: Number, FT2 <: Number} - N_dims = size(x_arr, 1) - x_tuple = ntuple(k -> view(x_arr, k, :), N_dims) - u_tuple = ntuple(k -> view(u_arr, k, :), N_dims) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return serial_calculate_structure_function!( sums, counts, @@ -222,21 +240,26 @@ function calculate_structure_function_i!( FT2 = eltype(T2) N3 = length(distance_bins) - X1 = SA.SVector{N, FT1}(ntuple(k -> @inbounds(x_vecs[k][i]), Val(N))) + # `N` is the velocity dimension; the coordinate count is the x tuple's own (static) length, + # which differs on a shell. + W = length(x_vecs) + vW = Val(W) + X1 = SA.SVector{W, FT1}(ntuple(k -> @inbounds(x_vecs[k][i]), vW)) U1 = SA.SVector{N, FT2}(ntuple(k -> @inbounds(u_vecs[k][i]), Val(N))) iter_inds = eachindex(x_vecs[1]) + geom = SFH.pair_geometry_for(distance_metric, Val(N)) # @inbounds: x_vecs[k] are strided views; the bounds checks on every component access # were a large per-pair overhead. U2 is built only for in-range pairs. @inbounds for j in (i + 1):last(iter_inds) - X2 = SA.SVector{N, FT1}(ntuple(k -> x_vecs[k][j], Val(N))) + X2 = SA.SVector{W, FT1}(ntuple(k -> x_vecs[k][j], vW)) - distance = distance_metric(X1, X2) + ok, distance, frame = SFH.pair_frame(geom, X1, X2) bin = SFH.digitize(distance, distance_bins) - if 1 <= bin < N3 + if ok && 1 <= bin < N3 U2 = SA.SVector{N, FT2}(ntuple(k -> u_vecs[k][j], Val(N))) - rh = SFH.r̂(X1, X2, distance_metric, distance) - output[bin] += structure_function_type(U2 - U1, rh) + δu, rh = SFH.pair_increments(geom, frame, distance, X1, X2, U1, U2) + output[bin] += structure_function_type(δu, rh) counts[bin] += 1 end end @@ -252,13 +275,14 @@ function calculate_structure_function_i( distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, ) where {CT} + _assert_counts_representable(CT, length(x_vecs[1])) OT = promote_type(float(eltype(eltype(x_vecs))), float(eltype(eltype(u_vecs)))) N3 = n_histogram_bins(distance_bins) local_output = zeros(OT, N3) local_counts = zeros(CT, N3) calculate_structure_function_i!( local_output, local_counts, - Val(length(x_vecs)), + Val(length(u_vecs)), structure_function_type, i, x_vecs, u_vecs, BinEdges(distance_bins); distance_metric = distance_metric, ) @@ -276,11 +300,11 @@ end Partial 1D sums/counts over an explicit outer-index list `ilist` (each `i` contributes pairs `(i, j>i)`). Used by the distributed driver to give each worker a balanced share; `inner` selects how the worker computes its share locally. This generic method runs SERIALLY for any -backend; the OhMyThreads extension adds a `::ThreadedBackend` method that threads over `ilist` +backend; the OhMyThreads extension adds a `::CB.AbstractThreadedBackend` method that threads over `ilist` (enabling hybrid distributed+threaded). Returns a `StructureFunctionSumsAndCounts`. """ function _partial_sums_counts( - ::AbstractExecutionBackend, + ::CB.AbstractExecutionBackend, structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, @@ -289,12 +313,23 @@ function _partial_sums_counts( distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, ) where {CT} + _assert_counts_representable(CT, length(x_vecs[1])) OT = promote_type(float(eltype(eltype(x_vecs))), float(eltype(eltype(u_vecs)))) nb = n_histogram_bins(distance_bins) sums = zeros(OT, nb) counts = zeros(CT, nb) be = BinEdges(distance_bins) - vN = Val(length(x_vecs)) + D = length(u_vecs) + # Euclidean D ∈ {2,3} takes the SIMD compute/scatter kernel, the same one the serial and + # threaded drivers use; `_pf_simd_pairs!` accepts an arbitrary `irange`. Other metrics or + # dimensions fall back to the scalar per-`i` kernel. + if distance_metric isa DI.Euclidean && (D == 2 || D == 3) + vD = D == 2 ? Val(2) : Val(3) + _pf_simd_partial!(sums, counts, structure_function_type, x_vecs, u_vecs, be, vD, ilist) + return SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, sums, counts) + end + + vN = Val(D) for i in ilist calculate_structure_function_i!( sums, counts, vN, structure_function_type, i, x_vecs, u_vecs, be; @@ -304,6 +339,30 @@ function _partial_sums_counts( return SFO.StructureFunctionSumsAndCounts(structure_function_type, distance_bins, sums, counts) end +""" + _pf_simd_partial!(sums, counts, sf, x_vecs, u_vecs, dist_be, ::Val{D}, ilist) + +Run [`_pf_simd_pairs!`](@ref) over an explicit outer-index list, materializing the contiguous +component vectors and scratch buffers this worker needs. Shared by the distributed, MPI and +hybrid drivers, whose inputs arrive as strided views. +""" +function _pf_simd_partial!( + sums::AbstractVector{OT}, counts::AbstractVector{CT}, + sf::SFT.AbstractPairwiseStructureFunctionType, + x_vecs::Tuple, u_vecs::Tuple, dist_be, ::Val{D}, ilist, +) where {OT, CT, D} + xc = ntuple(d -> collect(x_vecs[d]), Val(D)) # contiguous component vectors + uc = ntuple(d -> collect(u_vecs[d]), Val(D)) + N = length(xc[1]) + plan = squared_digitize_plan(dist_be) + nb = n_histogram_bins(plan) + r2buf = Vector{eltype(xc[1])}(undef, N) + valbuf = Vector{OT}(undef, N) + idxbuf = Vector{Int32}(undef, N) + _pf_simd_pairs!(sums, counts, sf, xc, uc, plan, Val(D), r2buf, valbuf, idxbuf, ilist) + return nothing +end + """ _balanced_index_chunks(N, k) -> Vector of k index-lists @@ -312,5 +371,7 @@ Round-robin assignment (`i ≡ w (mod k)`) gives each chunk a mix of cheap/expen """ function _balanced_index_chunks(N::Integer, k::Integer) k = max(1, k) - return [collect(w:k:N) for w in 1:k] + # Ranges, not materialized vectors: `_partial_sums_counts` only iterates them, and the + # distributed driver serializes one per worker. + return [w:k:N for w in 1:k] end diff --git a/src/Calculations/serial_2d.jl b/src/Calculations/serial_2d.jl index 457f1ad..fbd918a 100644 --- a/src/Calculations/serial_2d.jl +++ b/src/Calculations/serial_2d.jl @@ -21,7 +21,7 @@ function serial_calculate_structure_function!( # Fast path: Euclidean + D ∈ (2,3) via the SIMD compute/scatter split (distance + SF value # vectorize over j; the 2D (dist,value) scatter stays scalar). - D = length(x_vecs) + D = length(u_vecs) if distance_metric isa DI.Euclidean && (D == 2 || D == 3) _pf_2d_simd_run!(sums_2d, counts_2d, structure_function_type, x_vecs, u_vecs, distance_bins, value_bins, D == 2 ? Val(2) : Val(3)) @@ -49,11 +49,11 @@ range) so the `@simd` vectorizes; shared by serial + threaded. function _pf_2d_simd_pairs!( sums2d::AbstractMatrix{OT}, counts2d::AbstractMatrix{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, - xc::NTuple{D}, uc::NTuple{D}, dist_be, val_be, ::Val{D}, - distbuf::AbstractVector, valbuf::AbstractVector, irange, + xc::NTuple{D}, uc::NTuple{D}, plan::AbstractSquaredDigitizePlan, val_be, ::Val{D}, + keybuf::AbstractVector, valbuf::AbstractVector, idxbuf::AbstractVector{Int32}, irange, ) where {OT, CT, D} N = length(xc[1]) - n_dist = n_histogram_bins(dist_be) + n_dist = n_histogram_bins(plan) n_val = n_histogram_bins(val_be) FTx = eltype(xc[1]) @inbounds for i in irange @@ -62,14 +62,16 @@ function _pf_2d_simd_pairs!( @simd for j in (i + 1):N Xj = SA.SVector{D, FTx}(ntuple(d -> xc[d][j], Val(D))) dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) - rh = dx / dist + r2 = LA.dot(dx, dx) Uj = SA.SVector{D}(ntuple(d -> uc[d][j], Val(D))) - distbuf[j] = dist - valbuf[j] = sf(Uj - Ui, rh) + keybuf[j] = digitize_key(plan, r2) + valbuf[j] = SFT._sf_raw(sf, Uj - Ui, dx, r2) + if has_vector_index(plan) + idxbuf[j] = squared_approx_index(plan, r2) + end end for j in (i + 1):N - dbin = SFH.digitize(distbuf[j], dist_be) + dbin = squared_bin(plan, keybuf[j], idxbuf[j]) if 1 <= dbin <= n_dist vbin = SFH.digitize(valbuf[j], val_be) if 1 <= vbin <= n_val @@ -86,16 +88,78 @@ function _pf_2d_simd_run!( sums2d::AbstractMatrix{OT}, counts2d::AbstractMatrix{CT}, sf::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple, u_vecs::Tuple, dist_be, val_be, ::Val{D}, +) where {OT, CT, D} + N = length(x_vecs[1]) + return _pf_2d_simd_partial!(sums2d, counts2d, sf, x_vecs, u_vecs, dist_be, val_be, Val(D), 1:(N - 1)) +end + +""" + _pf_2d_simd_partial!(sums2d, counts2d, sf, x_vecs, u_vecs, dist_be, val_be, ::Val{D}, ilist) + +Run [`_pf_2d_simd_pairs!`](@ref) over an explicit outer-index list, materializing the contiguous +component vectors and scratch buffers this worker needs. Shared by the serial, distributed and MPI +drivers, whose inputs arrive as strided views. +""" +function _pf_2d_simd_partial!( + sums2d::AbstractMatrix{OT}, counts2d::AbstractMatrix{CT}, + sf::SFT.AbstractPairwiseStructureFunctionType, + x_vecs::Tuple, u_vecs::Tuple, dist_be, val_be, ::Val{D}, ilist, ) where {OT, CT, D} xc = ntuple(d -> collect(x_vecs[d]), Val(D)) uc = ntuple(d -> collect(u_vecs[d]), Val(D)) N = length(xc[1]) - distbuf = Vector{eltype(xc[1])}(undef, N) + keybuf = Vector{eltype(xc[1])}(undef, N) valbuf = Vector{OT}(undef, N) - _pf_2d_simd_pairs!(sums2d, counts2d, sf, xc, uc, dist_be, val_be, Val(D), distbuf, valbuf, 1:(N - 1)) + idxbuf = Vector{Int32}(undef, N) + plan = squared_digitize_plan(dist_be) + _pf_2d_simd_pairs!(sums2d, counts2d, sf, xc, uc, plan, val_be, Val(D), keybuf, valbuf, idxbuf, ilist) return nothing end +""" + _partial_2d_sums_counts(inner, sf_type, x_vecs, u_vecs, distance_bins, value_bins, ilist; kwargs...) + +Partial 2D-joint sums/counts over an explicit outer-index list `ilist`, the 2D analogue of +[`_partial_sums_counts`](@ref). Euclidean `D ∈ {2,3}` takes the SIMD compute/scatter kernel; other +metrics fall back to the scalar per-`i` kernel. Returns `(sums, counts)`. +""" +function _partial_2d_sums_counts( + ::CB.AbstractExecutionBackend, + structure_function_type::SFT.AbstractPairwiseStructureFunctionType, + x_vecs::Tuple, + u_vecs::Tuple, + distance_bins::AbstractVector, + value_bins::AbstractVector, + ilist; + distance_metric::DI.PreMetric = DI.Euclidean(), + count_eltype::Type{CT} = UInt32, +) where {CT} + _assert_counts_representable(CT, length(x_vecs[1])) + OT = promote_type(float(eltype(eltype(x_vecs))), float(eltype(eltype(u_vecs)))) + nd = n_histogram_bins(distance_bins) + nv = n_histogram_bins(value_bins) + sums = zeros(OT, nd, nv) + counts = zeros(CT, nd, nv) + dist_be = BinEdges(distance_bins) + val_be = BinEdges(value_bins) + D = length(u_vecs) + + if distance_metric isa DI.Euclidean && (D == 2 || D == 3) + vD = D == 2 ? Val(2) : Val(3) + _pf_2d_simd_partial!(sums, counts, structure_function_type, x_vecs, u_vecs, dist_be, val_be, vD, ilist) + return sums, counts + end + + vN = Val(D) + for i in ilist + calculate_structure_function_2d_i!( + sums, counts, vN, structure_function_type, i, x_vecs, u_vecs, dist_be, val_be; + distance_metric = distance_metric, + ) + end + return sums, counts +end + function serial_calculate_structure_function( structure_function_type::SFT.AbstractPairwiseStructureFunctionType, x_vecs::Tuple{T1, Vararg{T1}}, @@ -105,6 +169,7 @@ function serial_calculate_structure_function( count_eltype::Type{CT} = UInt32, kwargs..., ) where {T1, T2, CT} + _assert_counts_representable(CT, length(x_vecs[1])) FT1 = eltype(T1) FT2 = eltype(T2) OT = promote_type(float(FT1), float(FT2)) @@ -144,9 +209,8 @@ function serial_calculate_structure_function!( value_bins::AbstractVector; kwargs..., ) where {OT, FT1 <: Number, FT2 <: Number} - N_dims = size(x_arr, 1) - x_tuple = ntuple(k -> view(x_arr, k, :), N_dims) - u_tuple = ntuple(k -> view(u_arr, k, :), N_dims) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return serial_calculate_structure_function!( sums_2d, counts_2d, @@ -165,27 +229,30 @@ function serial_calculate_structure_function( u_arr::AbstractArray{FT2}, distance_bins::AbstractVector, value_bins::AbstractVector; + count_eltype::Type{CT} = UInt32, kwargs..., -) where {FT1 <: Number, FT2 <: Number} +) where {FT1 <: Number, FT2 <: Number, CT} if ndims(u_arr) >= 3 FT = promote_type(float(FT1), float(FT2)) n_dist = length(distance_bins) - 1 n_val = length(value_bins) - 1 bdims = batch_dims(u_arr) sums = zeros(FT, n_dist, n_val, bdims...) - counts = zeros(UInt32, n_dist, n_val, bdims...) + # Consumed here, where `counts` is allocated. `auxiliary_joint2d!` takes already-allocated + # buffers, so forwarding `count_eltype` into it is a MethodError. + counts = zeros(CT, n_dist, n_val, bdims...) auxiliary_joint2d!(sums, counts, structure_function_type, x_arr, u_arr, distance_bins, value_bins; kwargs...) return SFO.StructureFunction2DSumsAndCounts(structure_function_type, distance_bins, value_bins, sums, counts) end - N_dims = size(x_arr, 1) - x_tuple = ntuple(k -> view(x_arr, k, :), N_dims) - u_tuple = ntuple(k -> view(u_arr, k, :), N_dims) + x_tuple = ntuple(k -> view(x_arr, k, :), size(x_arr, 1)) + u_tuple = ntuple(k -> view(u_arr, k, :), size(u_arr, 1)) return serial_calculate_structure_function( structure_function_type, x_tuple, u_tuple, distance_bins, value_bins; + count_eltype = count_eltype, kwargs..., ) end @@ -207,19 +274,23 @@ function calculate_structure_function_2d_i!( N3 = length(distance_bins) N4 = length(value_bins) - X1 = SA.SVector{N, FT1}(ntuple(k -> x_vecs[k][i], Val(N))) + # `N` is the velocity dimension; the coordinate count is the x tuple's own (static) length. + W = length(x_vecs) + vW = Val(W) + X1 = SA.SVector{W, FT1}(ntuple(k -> x_vecs[k][i], vW)) U1 = SA.SVector{N, FT2}(ntuple(k -> u_vecs[k][i], Val(N))) iter_inds = eachindex(x_vecs[1]) + geom = SFH.pair_geometry_for(distance_metric, Val(N)) for j in (i + 1):last(iter_inds) - X2 = SA.SVector{N, FT1}(ntuple(k -> x_vecs[k][j], Val(N))) + X2 = SA.SVector{W, FT1}(ntuple(k -> x_vecs[k][j], vW)) U2 = SA.SVector{N, FT2}(ntuple(k -> u_vecs[k][j], Val(N))) - distance = distance_metric(X1, X2) + ok, distance, frame = SFH.pair_frame(geom, X1, X2) dist_bin = SFH.digitize(distance, distance_bins) - if 1 <= dist_bin < N3 - rh = SFH.r̂(X1, X2, distance_metric, distance) - val = structure_function_type(U2 - U1, rh) + if ok && 1 <= dist_bin < N3 + δu, rh = SFH.pair_increments(geom, frame, distance, X1, X2, U1, U2) + val = structure_function_type(δu, rh) val_bin = SFH.digitize(val, value_bins) if 1 <= val_bin < N4 @@ -241,7 +312,7 @@ function calculate_structure_function_2d_i( distance_metric::DI.PreMetric = DI.Euclidean(), count_eltype::Type{CT} = UInt32, ) where {CT} - N = length(x_vecs) + N = length(u_vecs) FT1 = eltype(x_vecs[1]) FT2 = eltype(u_vecs[1]) N3 = n_histogram_bins(distance_bins) diff --git a/src/Calculations/serial_single_pass.jl b/src/Calculations/serial_single_pass.jl index 7712fc9..91ff818 100644 --- a/src/Calculations/serial_single_pass.jl +++ b/src/Calculations/serial_single_pass.jl @@ -47,19 +47,16 @@ function helmholtz_decompose_2d( length(distance_bins) == n_bins + 1 || throw(DimensionMismatch("distance_bins must have length n_bins + 1")) - # Calculate bin midpoints from log-spaced edges - min_log_dist = log(distance_bins[1]) - max_log_dist = log(distance_bins[end]) - log_step = (max_log_dist - min_log_dist) / n_bins - + # Geometric midpoint of each bin's actual edges; NaN where r <= 0 has no midpoint. bin_mids = zeros(FT3, n_bins) for k in 1:n_bins - bin_mids[k] = exp(min_log_dist + (k - 0.5f0) * log_step) + lo, hi = distance_bins[k], distance_bins[k + 1] + bin_mids[k] = lo > zero(FT3) ? sqrt(lo * hi) : FT3(NaN) end - - # Compute normalized second-order longitudinal (2) and transverse (3) functions - D_LL = L2_sums ./ max.(L2_counts, 1) - D_TT = T2_sums ./ max.(T2_counts, 1) + + # Empty bins are NaN, never 0: the integral below is cumulative. + D_LL = _bin_average(L2_sums, L2_counts) + D_TT = _bin_average(T2_sums, T2_counts) # Evaluate cumulative trapezoidal integral I = zeros(OT, n_bins) @@ -173,15 +170,13 @@ function _accumulate_single_pass_1d!( distance_bins::AbstractVector{FT3}; distance_metric::DI.PreMetric = DI.Euclidean(), ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} - D = size(x, 1) + D = size(u, 1) n_points = size(x, 2) n_bins = length(distance_bins) - 1 size(sums) == (SINGLE_PASS_N, n_bins) || throw(DimensionMismatch("sums must have shape ($SINGLE_PASS_N, n_bins); got $(size(sums))")) size(counts) == (SINGLE_PASS_N, n_bins) || throw(DimensionMismatch("counts must have shape ($SINGLE_PASS_N, n_bins); got $(size(counts))")) - vD = Val(D) - # Fast path: Euclidean + D ∈ (2,3) via the SIMD compute/scatter split (vectorizes the # per-pair du_L / |du|² compute over j; the 6-way histogram scatter stays scalar). if distance_metric isa DI.Euclidean && (D == 2 || D == 3) @@ -189,41 +184,37 @@ function _accumulate_single_pass_1d!( return sums, counts end - for i in 1:n_points - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) - - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) - - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) + vW, vD = _pair_dims(distance_metric, D) + _sp1d_pairs!(sums, counts, x, u, BinEdges(distance_bins), vW, vD, + distance_metric, n_bins, 1:n_points) + return sums, counts +end - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i +""" + _sp1d_derive_rows!(sums, counts) - rh = SFH.r̂(x_i, x_j, distance_metric, r) - du_L = LA.dot(du, rh) - du_L2 = du_L * du_L - du_norm2 = LA.dot(du, du) - du_T2 = du_norm2 - du_L2 +Fill the two derived invariant rows and replicate the shared count of a `(SINGLE_PASS_N, n_bins)` +accumulator. - @inbounds sums[1, bin_idx] += du_norm2 - @inbounds sums[2, bin_idx] += du_L2 - @inbounds sums[3, bin_idx] += du_T2 - @inbounds sums[4, bin_idx] += du_L * du_norm2 - @inbounds sums[5, bin_idx] += du_L * du_L2 - @inbounds sums[6, bin_idx] += du_L * du_T2 +`T2 = S2 - L2` and `L1T2 = S3 - L3` hold for every pair, and a bin is a sum, so the pair loops store +only rows 1, 2, 4, 5 — four stores per pair instead of six — and these two are differenced once per +call. The count is identical across all six rows, so it is accumulated into row 1 and broadcast here. - @inbounds for t in 1:SINGLE_PASS_N - counts[t, bin_idx] += one(CT) - end - end +Uses `=`, never `+=`, so it is **idempotent**: correct whether a kernel runs once or many times over +the same buffer, and correct under threaded/partial reduction because the derivation is linear +(`Σ(S2-L2) = ΣS2 - ΣL2`). That is why it belongs at the end of each pair kernel rather than at the +callers' assembly points, of which there are more than twenty. +""" +@inline function _sp1d_derive_rows!(sums::AbstractMatrix, counts::AbstractMatrix) + @inbounds for b in axes(sums, 2) + sums[3, b] = sums[1, b] - sums[2, b] + sums[6, b] = sums[4, b] - sums[5, b] + c = counts[1, b] + for t in 2:SINGLE_PASS_N + counts[t, b] = c end end - - return sums, counts + return nothing end """ @@ -237,11 +228,12 @@ and scatters the 6 invariants. Like `_pf_simd_pairs!`, the loop must live in thi """ function _pf_sp_simd_pairs!( sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, - xc::NTuple{D}, uc::NTuple{D}, dist_be, ::Val{D}, - distbuf::AbstractVector, duLbuf::AbstractVector, dn2buf::AbstractVector, irange, + xc::NTuple{D}, uc::NTuple{D}, plan::AbstractSquaredDigitizePlan, ::Val{D}, + keybuf::AbstractVector, duLbuf::AbstractVector, dn2buf::AbstractVector, + idxbuf::AbstractVector{Int32}, irange, ) where {OT, CT, D} N = length(xc[1]) - nb = n_histogram_bins(dist_be) + nb = n_histogram_bins(plan) FTx = eltype(xc[1]) @inbounds for i in irange Xi = SA.SVector{D, FTx}(ntuple(d -> xc[d][i], Val(D))) @@ -249,56 +241,167 @@ function _pf_sp_simd_pairs!( @simd for j in (i + 1):N Xj = SA.SVector{D, FTx}(ntuple(d -> xc[d][j], Val(D))) dx = Xj - Xi - dist = sqrt(LA.dot(dx, dx)) - rh = dx / dist + r2 = LA.dot(dx, dx) du = SA.SVector{D}(ntuple(d -> uc[d][j], Val(D))) - Ui - distbuf[j] = dist - duLbuf[j] = LA.dot(du, rh) + # δu_L needs r, so one reciprocal-sqrt stays; it vectorizes. + inv_r = inv(sqrt(r2)) + keybuf[j] = digitize_key(plan, r2) + duLbuf[j] = LA.dot(du, dx) * inv_r dn2buf[j] = LA.dot(du, du) + if has_vector_index(plan) + idxbuf[j] = squared_approx_index(plan, r2) + end end for j in (i + 1):N - bin = SFH.digitize(distbuf[j], dist_be) + bin = squared_bin(plan, keybuf[j], idxbuf[j]) if 1 <= bin <= nb duL = duLbuf[j] dn2 = dn2buf[j] duL2 = duL * duL - duT2 = dn2 - duL2 sums[1, bin] += dn2 sums[2, bin] += duL2 - sums[3, bin] += duT2 sums[4, bin] += duL * dn2 sums[5, bin] += duL * duL2 - sums[6, bin] += duL * duT2 - for t in 1:SINGLE_PASS_N - counts[t, bin] += one(CT) - end + counts[1, bin] += one(CT) end end end + _sp1d_derive_rows!(sums, counts) return nothing end -# Serial driver: materialize contiguous component vectors + buffers, run over the full range. +# Serial driver: the full outer range through the same per-worker kernel. function _sp_simd_run!( sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, x::AbstractMatrix, u::AbstractMatrix, dist_be, ::Val{D}, +) where {OT, CT, D} + N = size(x, 2) + return _sp_simd_partial!(sums, counts, x, u, dist_be, Val(D), 1:(N - 1)) +end + +""" + _partial_single_pass_1d(x, u, distance_bins, ilist; distance_metric, count_eltype) + +Six-invariant partial sums/counts over an explicit outer-index list, for one distributed worker or +MPI rank. Euclidean `D ∈ {2,3}` takes the SIMD kernel; other metrics use the scalar loop. The +accumulator element type comes from the inputs. +""" +function _partial_single_pass_1d( + x::AbstractMatrix{FT1}, + u::AbstractMatrix{FT2}, + distance_bins::AbstractVector, + ilist; + distance_metric::DI.PreMetric = DI.Euclidean(), + count_eltype::Type{CT} = UInt32, +) where {FT1 <: Number, FT2 <: Number, CT} + OT = promote_type(float(FT1), float(FT2)) + D = size(u, 1) + nb = n_histogram_bins(distance_bins) + sums = zeros(OT, SINGLE_PASS_N, nb) + counts = zeros(CT, SINGLE_PASS_N, nb) + dist_be = BinEdges(distance_bins) + + if distance_metric isa DI.Euclidean && (D == 2 || D == 3) + _sp_simd_partial!(sums, counts, x, u, dist_be, D == 2 ? Val(2) : Val(3), ilist) + return sums, counts + end + + vW, vD = _pair_dims(distance_metric, D) + _sp1d_pairs!(sums, counts, x, u, dist_be, vW, vD, distance_metric, nb, ilist) + return sums, counts +end + +""" + _sp1d_pairs!(sums, counts, x, u, dist_be, ::Val{W}, ::Val{D}, metric, n_bins, ilist) + +Six-invariant scalar pair loop over the outer indices `ilist`, for geometries with no SIMD fast +path. `W` is the coordinate width and `D` the velocity width; both are type parameters so the +`SVector`s stay concrete inside the loop. +""" +function _sp1d_pairs!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, + x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, + dist_be, ::Val{W}, ::Val{D}, distance_metric, n_bins::Int, ilist, +) where {OT, CT, FT1, FT2, W, D} + n_points = size(x, 2) + vW = Val(W) + vD = Val(D) + geom = SFH.pair_geometry_for(distance_metric, vD) + @inbounds for i in ilist + x_i = SA.SVector{W, FT1}(ntuple(d -> x[d, i], vW)) + u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) + for j in (i + 1):n_points + x_j = SA.SVector{W, FT1}(ntuple(d -> x[d, j], vW)) + ok, r, frame = SFH.pair_frame(geom, x_i, x_j) + bin = SFH.digitize(r, dist_be) + if ok && 1 <= bin <= n_bins + u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) + du, rh = SFH.pair_increments(geom, frame, r, x_i, x_j, u_i, u_j) + duL = LA.dot(du, rh) + duL2 = duL * duL + dn2 = LA.dot(du, du) + sums[1, bin] += dn2 + sums[2, bin] += duL2 + sums[4, bin] += duL * dn2 + sums[5, bin] += duL * duL2 + counts[1, bin] += one(CT) + end + end + end + _sp1d_derive_rows!(sums, counts) + return nothing +end + +"""Run [`_pf_sp_simd_pairs!`](@ref) over an explicit outer-index list, with this worker's buffers.""" +function _sp_simd_partial!( + sums::AbstractMatrix{OT}, counts::AbstractMatrix{CT}, + x::AbstractMatrix, u::AbstractMatrix, dist_be, ::Val{D}, ilist, ) where {OT, CT, D} xc = ntuple(d -> collect(view(x, d, :)), Val(D)) uc = ntuple(d -> collect(view(u, d, :)), Val(D)) N = length(xc[1]) FTx = eltype(xc[1]) - distbuf = Vector{FTx}(undef, N) + keybuf = Vector{FTx}(undef, N) duLbuf = Vector{OT}(undef, N) dn2buf = Vector{OT}(undef, N) - _pf_sp_simd_pairs!(sums, counts, xc, uc, dist_be, Val(D), distbuf, duLbuf, dn2buf, 1:(N - 1)) + idxbuf = Vector{Int32}(undef, N) + plan = squared_digitize_plan(dist_be) + _pf_sp_simd_pairs!(sums, counts, xc, uc, plan, Val(D), keybuf, duLbuf, dn2buf, idxbuf, ilist) return nothing end +""" + _partial_single_pass_2d(x, u, distance_bins, value_bins, ilist; distance_metric, count_eltype) + +Six-invariant 2D joint partial sums/counts over an explicit outer-index list, for one distributed +worker or MPI rank. The accumulator element type comes from the inputs. +""" +function _partial_single_pass_2d( + x::AbstractMatrix{FT1}, + u::AbstractMatrix{FT2}, + distance_bins::AbstractVector, + value_bins::SinglePass2DValueBins, + ilist; + distance_metric::DI.PreMetric = DI.Euclidean(), + count_eltype::Type{CT} = UInt32, +) where {FT1 <: Number, FT2 <: Number, CT} + OT = promote_type(float(FT1), float(FT2)) + n_bins = n_histogram_bins(distance_bins) + n_val = length(_sp2d_value_bin_at(value_bins, 1)) - 1 + _validate_value_bins!(value_bins, n_val) + _assert_counts_representable(CT, size(x, 2)) + sums = zeros(OT, SINGLE_PASS_N, n_bins, n_val) + counts = zeros(CT, SINGLE_PASS_N, n_bins, n_val) + _sp2d_accumulate_range!(sums, counts, x, u, BinEdges(distance_bins), value_bins, + distance_metric, n_bins, n_val, ilist) + return sums, counts +end + function _dispatch_single_pass end function _dispatch_single_pass! end """ - calculate_structure_functions_single_pass!(sums, counts, x, u, distance_bins; backend=SerialBackend(), kwargs...) + calculate_structure_functions_single_pass!(sums, counts, x, u, distance_bins; backend=CB.SerialBackend(), kwargs...) Accumulate into pre-allocated ``(6, n_bins)`` buffers using the requested execution backend. """ @@ -308,53 +411,54 @@ function calculate_structure_functions_single_pass!( x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}; - backend::AbstractExecutionBackend = SerialBackend(), + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} - _validate_array_shape(x, u) - _dispatch_single_pass!(backend, sums, counts, x, u, distance_bins; kwargs...) + _validate_array_shape(x, u, distance_metric) + _dispatch_single_pass!(backend, sums, counts, x, u, distance_bins; distance_metric, kwargs...) return sums, counts end function _dispatch_single_pass!( - ::SerialBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... + ::CB.AbstractSerialBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... ) return _accumulate_single_pass_1d!(sums, counts, x, u, distance_bins; kwargs...) end function _dispatch_single_pass!( - ::ThreadedBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... + ::CB.AbstractThreadedBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... ) - throw(ArgumentError("Threaded in-place single-pass is unavailable. Load OhMyThreads or use backend=SerialBackend().")) + throw(ArgumentError("Threaded in-place single-pass is unavailable. Load OhMyThreads or use backend=CB.SerialBackend().")) end function _dispatch_single_pass!( - ::DistributedBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... + ::CB.AbstractDistributedBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... ) - throw(ArgumentError("Distributed in-place single-pass is unavailable. Load Distributed or use backend=SerialBackend().")) + throw(ArgumentError("Distributed in-place single-pass is unavailable. Load Distributed or use backend=CB.SerialBackend().")) end function _dispatch_single_pass!( - ::GPUBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... + ::CB.AbstractGPUBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... ) - throw(ArgumentError("GPU in-place single-pass is unavailable. Load GPUExt or use backend=SerialBackend().")) + throw(ArgumentError("GPU in-place single-pass is unavailable. Load GPUExt or use backend=CB.SerialBackend().")) end function _dispatch_single_pass!( - ::AutoBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... + ::CB.AbstractAutoBackend, sums::AbstractMatrix, counts::AbstractMatrix, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector; kwargs... ) if distributed_workers_available(Val(:distributed)) && _distributed_single_pass_available(x, u, distance_bins) - return _dispatch_single_pass!(DistributedBackend(), sums, counts, x, u, distance_bins; kwargs...) + return _dispatch_single_pass!(CB.DistributedBackend(), sums, counts, x, u, distance_bins; kwargs...) end if Threads.nthreads() > 1 && _threaded_single_pass_available(x, u, distance_bins) - return _dispatch_single_pass!(ThreadedBackend(), sums, counts, x, u, distance_bins; kwargs...) + return _dispatch_single_pass!(CB.ThreadedBackend(), sums, counts, x, u, distance_bins; kwargs...) end - return _dispatch_single_pass!(SerialBackend(), sums, counts, x, u, distance_bins; kwargs...) + return _dispatch_single_pass!(CB.SerialBackend(), sums, counts, x, u, distance_bins; kwargs...) end function _dispatch_single_pass( - ::SerialBackend, + ::CB.AbstractSerialBackend, ::PointField, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, @@ -383,7 +487,7 @@ function _dispatch_single_pass( end function _dispatch_single_pass( - ::SerialBackend, + ::CB.AbstractSerialBackend, ::Union{SharedPositionField, VaryingPositionField}, x::AbstractArray{FT1}, u::AbstractArray{FT2}, @@ -401,7 +505,7 @@ function _dispatch_single_pass( end function _dispatch_single_pass( - ::ThreadedBackend, + ::CB.AbstractThreadedBackend, ::PointField, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, @@ -409,11 +513,11 @@ function _dispatch_single_pass( count_eltype::Type{CT} = UInt32, kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, CT} - return _dispatch_single_pass(ThreadedBackend(), x, u, distance_bins; count_eltype = CT, kwargs...) + return _dispatch_single_pass(CB.ThreadedBackend(), x, u, distance_bins; count_eltype = CT, kwargs...) end function _dispatch_single_pass( - ::ThreadedBackend, + ::CB.AbstractThreadedBackend, ::Union{SharedPositionField, VaryingPositionField}, x::AbstractArray{FT1}, u::AbstractArray{FT2}, @@ -430,20 +534,24 @@ function _dispatch_single_pass( return (sums = sums, counts = counts) end -function _dispatch_single_pass(::ThreadedBackend, args...; kwargs...) - throw(ArgumentError("Threaded single-pass backend is unavailable. Load the OhMyThreads extension or use backend=SerialBackend().")) +function _dispatch_single_pass(::CB.AbstractThreadedBackend, args...; kwargs...) + throw(ArgumentError("Threaded single-pass backend is unavailable. Load the OhMyThreads extension or use backend=CB.SerialBackend().")) end -function _dispatch_single_pass(::DistributedBackend, args...; kwargs...) - throw(ArgumentError("Distributed single-pass backend is unavailable. Load the Distributed/SharedArrays extension or use backend=SerialBackend().")) +function _dispatch_single_pass(::CB.AbstractDistributedBackend, args...; kwargs...) + throw(ArgumentError("Distributed single-pass backend is unavailable. Load Distributed (`using Distributed`) or use backend=CB.SerialBackend().")) end -function _dispatch_single_pass(::GPUBackend, args...; kwargs...) - throw(ArgumentError("GPU single-pass backend is unavailable. Load the GPUExt extension or use backend=SerialBackend().")) +function _dispatch_single_pass(::CB.AbstractGPUBackend, args...; kwargs...) + throw(ArgumentError("GPU single-pass backend is unavailable. Load the GPUExt extension or use backend=CB.SerialBackend().")) +end + +function _dispatch_single_pass(::CB.AbstractMPIBackend, args...; kwargs...) + throw(ArgumentError("MPI single-pass backend is unavailable. Load MPI (`using MPI`) or use backend=CB.SerialBackend().")) end function _dispatch_single_pass( - backend::GPUBackend, + backend::CB.AbstractGPUBackend, ::AbstractFieldShape, x::AbstractArray, u::AbstractArray, @@ -454,7 +562,7 @@ function _dispatch_single_pass( end function _dispatch_single_pass( - backend::DistributedBackend, + backend::CB.AbstractDistributedBackend, ::AbstractFieldShape, x::AbstractArray, u::AbstractArray, @@ -466,33 +574,21 @@ end _threaded_single_pass_available(x, u, distance_bins) = hasmethod( _dispatch_single_pass, - Tuple{ThreadedBackend, typeof(x), typeof(u), typeof(distance_bins)} + Tuple{CB.ThreadedBackend, typeof(x), typeof(u), typeof(distance_bins)} ) _distributed_single_pass_available(x, u, distance_bins) = hasmethod( _dispatch_single_pass, - Tuple{DistributedBackend, typeof(x), typeof(u), typeof(distance_bins)} + Tuple{CB.DistributedBackend, typeof(x), typeof(u), typeof(distance_bins)} ) -function _dispatch_single_pass(::AutoBackend, shape::AbstractFieldShape, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector; kwargs...) - if distributed_workers_available(Val(:distributed)) && - _distributed_single_pass_available(x, u, distance_bins) - return _dispatch_single_pass(DistributedBackend(), shape, x, u, distance_bins; kwargs...) - end - - if has_auxiliary_axes(shape) - if Threads.nthreads() > 1 - return _dispatch_single_pass(ThreadedBackend(), shape, x, u, distance_bins; kwargs...) - end - return _dispatch_single_pass(SerialBackend(), shape, x, u, distance_bins; kwargs...) - end - - if Threads.nthreads() > 1 && - _threaded_single_pass_available(x, u, distance_bins) - return _dispatch_single_pass(ThreadedBackend(), shape, x, u, distance_bins; kwargs...) - end - - return _dispatch_single_pass(SerialBackend(), shape, x, u, distance_bins; kwargs...) +function _dispatch_single_pass(::CB.AbstractAutoBackend, shape::AbstractFieldShape, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector; kwargs...) + backend = resolve_auto_backend( + shape, + () -> _threaded_single_pass_available(x, u, distance_bins), + () -> _distributed_single_pass_available(x, u, distance_bins), + ) + return _dispatch_single_pass(backend, shape, x, u, distance_bins; kwargs...) end # --- Single-pass result collections (keyed by invariant) --- @@ -547,7 +643,7 @@ function _single_pass_collection_1d( end """ - calculate_structure_functions_single_pass(x, u, distance_bins; backend=AutoBackend(), + calculate_structure_functions_single_pass(x, u, distance_bins; backend=CB.AutoBackend(), output_type=StructureFunction, kwargs...) Compute the six native invariant structure functions (S2, L2, T2, S3, L3, L1T2) in one pair @@ -568,15 +664,18 @@ function calculate_structure_functions_single_pass( x::AbstractArray{FT1}, u::AbstractArray{FT2, M}, distance_bins::AbstractVector{FT3}; - backend::AbstractExecutionBackend = AutoBackend(), + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), output_type::Type{OT} = SFO.StructureFunction, count_eltype::Type{CT} = UInt32, + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, M, OT, CT} - shape = _validate_array_shape(x, u) + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(CT, size(x, 2)) raw = _dispatch_single_pass( backend, shape, x, u, distance_bins; count_eltype = count_eltype, + distance_metric, kwargs..., ) # The accumulator's element/rank are fully determined by the inputs: the sum element type is @@ -617,12 +716,13 @@ function calculate_structure_functions_single_pass_2d!( u::AbstractMatrix{FT2}, distance_bins::AbstractVector{FT3}, value_bins::SinglePass2DValueBins; - backend::AbstractExecutionBackend = SerialBackend(), + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs... ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} - _validate_array_shape(x, u) + _validate_array_shape(x, u, distance_metric) _dispatch_single_pass_2d!( - backend, sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs... + backend, sums_3d, counts_3d, x, u, distance_bins, value_bins; distance_metric, kwargs... ) return sums_3d, counts_3d end @@ -637,7 +737,6 @@ function _accumulate_single_pass_2d!( value_bins::SinglePass2DValueBins; distance_metric::DI.PreMetric = DI.Euclidean(), ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} - D = size(x, 1) n_points = size(x, 2) n_bins = length(distance_bins) - 1 n_val = size(sums_3d, 3) @@ -646,89 +745,229 @@ function _accumulate_single_pass_2d!( size(counts_3d) == size(sums_3d) || throw(DimensionMismatch("counts and sums must have the same shape")) _validate_value_bins!(value_bins, n_val) - vD = Val(D) - for i in 1:n_points - x_i = SA.SVector{D, FT1}(ntuple(d -> x[d, i], vD)) - u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) + dist_be = BinEdges(distance_bins) + _sp2d_accumulate_range!(sums_3d, counts_3d, x, u, dist_be, value_bins, distance_metric, + n_bins, n_val, 1:n_points) + return sums_3d, counts_3d +end - for j in (i + 1):n_points - x_j = SA.SVector{D, FT1}(ntuple(d -> x[d, j], vD)) +"""Accumulate single-pass 2D pairs for outer indices `ilist` into the caller's sums/counts.""" +function _sp2d_accumulate_range!( + sums_3d::AbstractArray{OT, 3}, counts_3d::AbstractArray{CT, 3}, + x::AbstractMatrix, u::AbstractMatrix, dist_be, value_bins, distance_metric, + n_bins::Int, n_val::Int, ilist, +) where {OT, CT} + h = _sp2d_histogram(OT, n_bins, n_val) + _sp2d_fill!(h, x, u, dist_be, value_bins, distance_metric, n_bins, n_val, ilist) + return _sp2d_unpack!(sums_3d, counts_3d, h, n_bins, n_val) +end - r = distance_metric(x_i, x_j) - bin_idx = SFH.digitize(r, distance_bins) +""" +Fill the interleaved accumulator from pairs whose outer index is in `ilist`. Euclidean `D ∈ {2,3}` +takes the SIMD compute/scatter split; other metrics or dimensions take the scalar loop. The `Val{D}` +branch is a function barrier: `D` must be a type parameter inside the loop, or `SVector{D}` builds +its type per point. +""" +function _sp2d_fill!( + h::AbstractArray{OT, 4}, + x::AbstractMatrix, u::AbstractMatrix, dist_be, value_bins, distance_metric, + n_bins::Int, n_val::Int, ilist, +) where {OT} + D = size(u, 1) + if distance_metric isa DI.Euclidean && (D == 2 || D == 3) + _sp2d_simd_partial!(h, x, u, dist_be, value_bins, D == 2 ? Val(2) : Val(3), n_val, ilist) + return nothing + end + plan = squared_digitize_plan(dist_be) + vW, vD = _pair_dims(distance_metric, D) + _sp2d_pairs!(h, x, u, dist_be, plan, value_bins, vW, vD, + distance_metric, n_bins, n_val, ilist) + return nothing +end - if 1 <= bin_idx <= n_bins - u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) - du = u_j - u_i +""" + _sp2d_histogram(OT, n_bins, n_val) -> Array{OT,4} - rh = SFH.r̂(x_i, x_j, distance_metric, r) +The single-pass 2D accumulator, laid out `(sum|count, invariant, value_bin, distance_bin)`. + +Each pair writes all six invariants at ONE distance bin but six different value bins, so putting +the value axis inside the distance axis keeps a pair's six updates inside one distance slab, and +interleaving sum with count puts each invariant's two updates on one cache line: 6 lines touched +per pair instead of 12, and the cost stops scaling with histogram size. +""" +@inline _sp2d_histogram(::Type{OT}, n_bins::Int, n_val::Int) where {OT} = + zeros(OT, 2, SINGLE_PASS_N, n_val, n_bins) + +"""Add the interleaved accumulator into the caller's `(6, n_bins, n_val)` sums/counts.""" +function _sp2d_unpack!( + sums_3d::AbstractArray{OT, 3}, counts_3d::AbstractArray{CT, 3}, + h::AbstractArray, n_bins::Int, n_val::Int, +) where {OT, CT} + @inbounds for d in 1:n_bins, v in 1:n_val, t in 1:SINGLE_PASS_N + sums_3d[t, d, v] += h[1, t, v, d] + counts_3d[t, d, v] += CT(h[2, t, v, d]) + end + return nothing +end + +""" + _sp2d_pairs!(h, x, u, dist_be, plan, value_bins, ::Val{D}, metric, n_bins, n_val, ilist) + +Single-pass 2D scalar pair loop over the outer indices `ilist`, for non-Euclidean metrics. +Specialized on the spatial dimension `D` so the `SVector`s are concrete. +""" +function _sp2d_pairs!( + h::AbstractArray{OT, 4}, + x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, + dist_be, plan, value_bins, ::Val{W}, ::Val{D}, distance_metric, n_bins::Int, n_val::Int, ilist, +) where {OT, FT1, FT2, W, D} + n_points = size(x, 2) + vW = Val(W) + vD = Val(D) + geom = SFH.pair_geometry_for(distance_metric, vD) + @inbounds for i in ilist + x_i = SA.SVector{W, FT1}(ntuple(d -> x[d, i], vW)) + u_i = SA.SVector{D, FT2}(ntuple(d -> u[d, i], vD)) + for j in (i + 1):n_points + x_j = SA.SVector{W, FT1}(ntuple(d -> x[d, j], vW)) + ok, r, frame = SFH.pair_frame(geom, x_i, x_j) + bin_idx = SFH.digitize(r, dist_be) + if ok && 1 <= bin_idx <= n_bins + u_j = SA.SVector{D, FT2}(ntuple(d -> u[d, j], vD)) + du, rh = SFH.pair_increments(geom, frame, r, x_i, x_j, u_i, u_j) du_L = LA.dot(du, rh) du_L2 = du_L * du_L du_norm2 = LA.dot(du, du) du_T2 = du_norm2 - du_L2 + vals = (du_norm2, du_L2, du_T2, du_L * du_norm2, du_L * du_L2, du_L * du_T2) + _sp2d_scatter!(h, bin_idx, vals, value_bins, n_val) + end + end + end + return nothing +end - vals = ( - du_norm2, - du_L2, - du_T2, - du_L * du_norm2, - du_L * du_L2, - du_L * du_T2, - ) - - for t in 1:SINGLE_PASS_N - vb = _sp2d_value_bin_at(value_bins, t) - vbin = SFH.digitize(vals[t], vb) - n_val_t = length(vb) - 1 - if 1 <= vbin <= n_val_t && vbin <= n_val - @inbounds sums_3d[t, bin_idx, vbin] += vals[t] - @inbounds counts_3d[t, bin_idx, vbin] += 1 - end - end +"""Scatter the six invariants of one pair into their cells of the interleaved accumulator.""" +@inline function _sp2d_scatter!( + h::AbstractArray{OT, 4}, dbin::Int, vals::NTuple{SINGLE_PASS_N}, value_bins, n_val::Int, +) where {OT} + @sp2d_each_invariant value_bins t vb begin + vbin = SFH.digitize(vals[t], vb) + if 1 <= vbin <= (length(vb) - 1) && vbin <= n_val + @inbounds h[1, t, vbin, dbin] += vals[t] + @inbounds h[2, t, vbin, dbin] += one(OT) + end + end + return nothing +end + +""" + _sp2d_simd_pairs!(h, xc, uc, plan, value_bins, ::Val{D}, keybuf, duLbuf, dn2buf, idxbuf, n_val, irange) + +Single-pass 2D point-field SIMD compute/scatter kernel over outer indices `irange`, the 2D analogue +of [`_pf_sp_simd_pairs!`](@ref). The `@simd` half computes distance, `du_L` and `|du|²` into buffers; +the scalar half derives the six invariants from those two scalars and scatters each into its own +`(distance, value)` cell. Shared by serial + threaded. +""" +function _sp2d_simd_pairs!( + h::AbstractArray{OT, 4}, + xc::NTuple{D}, uc::NTuple{D}, plan::AbstractSquaredDigitizePlan, value_bins, ::Val{D}, + keybuf::AbstractVector, duLbuf::AbstractVector, dn2buf::AbstractVector, + idxbuf::AbstractVector{Int32}, n_val::Int, irange, +) where {OT, D} + N = length(xc[1]) + nb = n_histogram_bins(plan) + FTx = eltype(xc[1]) + @inbounds for i in irange + Xi = SA.SVector{D, FTx}(ntuple(d -> xc[d][i], Val(D))) + Ui = SA.SVector{D}(ntuple(d -> uc[d][i], Val(D))) + @simd for j in (i + 1):N + Xj = SA.SVector{D, FTx}(ntuple(d -> xc[d][j], Val(D))) + dx = Xj - Xi + r2 = LA.dot(dx, dx) + du = SA.SVector{D}(ntuple(d -> uc[d][j], Val(D))) - Ui + inv_r = inv(sqrt(r2)) + keybuf[j] = digitize_key(plan, r2) + duLbuf[j] = LA.dot(du, dx) * inv_r + dn2buf[j] = LA.dot(du, du) + if has_vector_index(plan) + idxbuf[j] = squared_approx_index(plan, r2) + end + end + for j in (i + 1):N + dbin = squared_bin(plan, keybuf[j], idxbuf[j]) + if 1 <= dbin <= nb + duL = duLbuf[j] + dn2 = dn2buf[j] + duL2 = duL * duL + duT2 = dn2 - duL2 + vals = (dn2, duL2, duT2, duL * dn2, duL * duL2, duL * duT2) + _sp2d_scatter!(h, dbin, vals, value_bins, n_val) end end end + return nothing +end - return sums_3d, counts_3d +""" + _sp2d_simd_partial!(h, x, u, dist_be, value_bins, ::Val{D}, n_val, ilist) + +Run [`_sp2d_simd_pairs!`](@ref) over an explicit outer-index list, with this worker's buffers. +""" +function _sp2d_simd_partial!( + h::AbstractArray{OT, 4}, + x::AbstractMatrix, u::AbstractMatrix, dist_be, value_bins, ::Val{D}, n_val::Int, ilist, +) where {OT, D} + xc = ntuple(d -> collect(view(x, d, :)), Val(D)) + uc = ntuple(d -> collect(view(u, d, :)), Val(D)) + N = length(xc[1]) + keybuf = Vector{eltype(xc[1])}(undef, N) + duLbuf = Vector{OT}(undef, N) + dn2buf = Vector{OT}(undef, N) + idxbuf = Vector{Int32}(undef, N) + plan = squared_digitize_plan(dist_be) + _sp2d_simd_pairs!(h, xc, uc, plan, value_bins, Val(D), + keybuf, duLbuf, dn2buf, idxbuf, n_val, ilist) + return nothing end function _dispatch_single_pass_2d!( - ::SerialBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... + ::CB.AbstractSerialBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... ) return _accumulate_single_pass_2d!(sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) end function _dispatch_single_pass_2d!( - ::ThreadedBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... + ::CB.AbstractThreadedBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... ) - throw(ArgumentError("Threaded in-place 2D single-pass is unavailable. Load OhMyThreads or use backend=SerialBackend().")) + throw(ArgumentError("Threaded in-place 2D single-pass is unavailable. Load OhMyThreads or use backend=CB.SerialBackend().")) end function _dispatch_single_pass_2d!( - ::DistributedBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... + ::CB.AbstractDistributedBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... ) - throw(ArgumentError("Distributed in-place 2D single-pass is unavailable. Load Distributed or use backend=SerialBackend().")) + throw(ArgumentError("Distributed in-place 2D single-pass is unavailable. Load Distributed or use backend=CB.SerialBackend().")) end function _dispatch_single_pass_2d!( - backend::GPUBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... + backend::CB.AbstractGPUBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... ) gpu_calculate_structure_functions_single_pass_2d!(sums_3d, counts_3d, backend.backend, x, u, distance_bins, value_bins; kwargs...) return sums_3d, counts_3d end function _dispatch_single_pass_2d!( - ::AutoBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... + ::CB.AbstractAutoBackend, sums_3d::AbstractArray, counts_3d::AbstractArray, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs... ) if distributed_workers_available(Val(:distributed)) && _distributed_single_pass_2d_available(x, u, distance_bins, value_bins) - return _dispatch_single_pass_2d!(DistributedBackend(), sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) + return _dispatch_single_pass_2d!(CB.DistributedBackend(), sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) end if Threads.nthreads() > 1 && _threaded_single_pass_2d_available(x, u, distance_bins, value_bins) - return _dispatch_single_pass_2d!(ThreadedBackend(), sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) + return _dispatch_single_pass_2d!(CB.ThreadedBackend(), sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) end - return _dispatch_single_pass_2d!(SerialBackend(), sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) + return _dispatch_single_pass_2d!(CB.SerialBackend(), sums_3d, counts_3d, x, u, distance_bins, value_bins; kwargs...) end # Specific method for matrix inputs to handle standard non-batch 2D single-pass @@ -756,7 +995,7 @@ function _dispatch_single_pass_2d_matrix( end function _dispatch_single_pass_2d( - ::SerialBackend, + ::CB.AbstractSerialBackend, ::PointField, x::AbstractMatrix{FT1}, u::AbstractMatrix{FT2}, @@ -772,7 +1011,7 @@ function _dispatch_single_pass_2d( end function _dispatch_single_pass_2d( - ::SerialBackend, + ::CB.AbstractSerialBackend, ::Union{SharedPositionField, VaryingPositionField}, x::AbstractArray{FT1}, u::AbstractArray{FT2}, @@ -792,12 +1031,12 @@ function _dispatch_single_pass_2d( return (sums = sums, counts = counts) end -function _dispatch_single_pass_2d(::ThreadedBackend, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) - throw(ArgumentError("Threaded 2D single-pass backend is unavailable. Load the OhMyThreads extension or use backend=SerialBackend().")) +function _dispatch_single_pass_2d(::CB.AbstractThreadedBackend, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) + throw(ArgumentError("Threaded 2D single-pass backend is unavailable. Load the OhMyThreads extension or use backend=CB.SerialBackend().")) end function _dispatch_single_pass_2d( - backend::ThreadedBackend, + backend::CB.AbstractThreadedBackend, ::PointField, x::AbstractMatrix, u::AbstractMatrix, @@ -809,7 +1048,7 @@ function _dispatch_single_pass_2d( end function _dispatch_single_pass_2d( - ::ThreadedBackend, + ::CB.AbstractThreadedBackend, ::Union{SharedPositionField, VaryingPositionField}, x::AbstractArray{FT1}, u::AbstractArray{FT2}, @@ -829,12 +1068,16 @@ function _dispatch_single_pass_2d( return (sums = sums, counts = counts) end -function _dispatch_single_pass_2d(::DistributedBackend, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) - throw(ArgumentError("Distributed 2D single-pass backend is unavailable. Load the Distributed extension or use backend=SerialBackend().")) +function _dispatch_single_pass_2d(::CB.AbstractDistributedBackend, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) + throw(ArgumentError("Distributed 2D single-pass backend is unavailable. Load the Distributed extension or use backend=CB.SerialBackend().")) +end + +function _dispatch_single_pass_2d(::CB.AbstractMPIBackend, args...; kwargs...) + throw(ArgumentError("MPI 2D single-pass backend is unavailable. Load MPI (`using MPI`) or use backend=CB.SerialBackend().")) end function _dispatch_single_pass_2d( - backend::DistributedBackend, + backend::CB.AbstractDistributedBackend, ::AbstractFieldShape, x::AbstractArray, u::AbstractArray, @@ -845,12 +1088,12 @@ function _dispatch_single_pass_2d( return _dispatch_single_pass_2d(backend, x, u, distance_bins, value_bins; kwargs...) end -function _dispatch_single_pass_2d(backend::GPUBackend, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) +function _dispatch_single_pass_2d(backend::CB.AbstractGPUBackend, x::AbstractMatrix, u::AbstractMatrix, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) return gpu_calculate_structure_functions_single_pass_2d(backend.backend, x, u, distance_bins, value_bins; kwargs...) end function _dispatch_single_pass_2d( - backend::GPUBackend, + backend::CB.AbstractGPUBackend, ::AbstractFieldShape, x::AbstractArray, u::AbstractArray, @@ -863,30 +1106,21 @@ end _threaded_single_pass_2d_available(x, u, distance_bins, value_bins) = hasmethod( _dispatch_single_pass_2d, - Tuple{ThreadedBackend, typeof(x), typeof(u), typeof(distance_bins), typeof(value_bins)}, + Tuple{CB.ThreadedBackend, typeof(x), typeof(u), typeof(distance_bins), typeof(value_bins)}, ) _distributed_single_pass_2d_available(x, u, distance_bins, value_bins) = hasmethod( _dispatch_single_pass_2d, - Tuple{DistributedBackend, typeof(x), typeof(u), typeof(distance_bins), typeof(value_bins)}, + Tuple{CB.DistributedBackend, typeof(x), typeof(u), typeof(distance_bins), typeof(value_bins)}, ) -function _dispatch_single_pass_2d(::AutoBackend, shape::AbstractFieldShape, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) - if distributed_workers_available(Val(:distributed)) && - _distributed_single_pass_2d_available(x, u, distance_bins, value_bins) - return _dispatch_single_pass_2d(DistributedBackend(), shape, x, u, distance_bins, value_bins; kwargs...) - end - if has_auxiliary_axes(shape) - if Threads.nthreads() > 1 - return _dispatch_single_pass_2d(ThreadedBackend(), shape, x, u, distance_bins, value_bins; kwargs...) - end - return _dispatch_single_pass_2d(SerialBackend(), shape, x, u, distance_bins, value_bins; kwargs...) - end - if Threads.nthreads() > 1 && - _threaded_single_pass_2d_available(x, u, distance_bins, value_bins) - return _dispatch_single_pass_2d(ThreadedBackend(), shape, x, u, distance_bins, value_bins; kwargs...) - end - return _dispatch_single_pass_2d(SerialBackend(), shape, x, u, distance_bins, value_bins; kwargs...) +function _dispatch_single_pass_2d(::CB.AbstractAutoBackend, shape::AbstractFieldShape, x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector, value_bins::SinglePass2DValueBins; kwargs...) + backend = resolve_auto_backend( + shape, + () -> _threaded_single_pass_2d_available(x, u, distance_bins, value_bins), + () -> _distributed_single_pass_2d_available(x, u, distance_bins, value_bins), + ) + return _dispatch_single_pass_2d(backend, shape, x, u, distance_bins, value_bins; kwargs...) end # Per-invariant value bins: a single vector is shared across invariants; a 6-tuple is per-invariant. @@ -916,7 +1150,7 @@ function _single_pass_collection_2d( end """ - calculate_structure_functions_single_pass_2d(x, u, distance_bins, value_bins; backend=AutoBackend(), + calculate_structure_functions_single_pass_2d(x, u, distance_bins, value_bins; backend=CB.AutoBackend(), output_type=StructureFunction2DSumsAndCounts, kwargs...) Compute the six invariant 2D joint structure-function histograms in one pass, returned as a @@ -929,15 +1163,19 @@ function calculate_structure_functions_single_pass_2d( u::AbstractArray{FT2}, distance_bins::AbstractVector{FT3}, value_bins::SinglePass2DValueBins; - backend::AbstractExecutionBackend = AutoBackend(), + backend::CB.AbstractExecutionBackend = CB.AutoBackend(), output_type::Type{OT} = SFO.StructureFunction2DSumsAndCounts, count_eltype::Type{CT} = UInt32, - kwargs... + distance_metric::DI.PreMetric = DI.Euclidean(), + verbose::Bool = true, + show_progress::Bool = true, ) where {FT1 <: Number, FT2 <: Number, FT3 <: Number, OT, CT} - shape = _validate_array_shape(x, u) + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(CT, size(x, 2)) + # Only forward knobs the kernels accept; they have no `kwargs...` sink. raw = _dispatch_single_pass_2d( backend, shape, x, u, distance_bins, value_bins; - count_eltype = count_eltype, kwargs..., + count_eltype = count_eltype, distance_metric = distance_metric, ) return _single_pass_collection_2d(raw[1], raw[2], distance_bins, value_bins, output_type) end diff --git a/src/Calculations/shapes.jl b/src/Calculations/shapes.jl index 0e6b834..5801b29 100644 --- a/src/Calculations/shapes.jl +++ b/src/Calculations/shapes.jl @@ -1,11 +1,40 @@ # Array shape contract for public calculation APIs. +""" + AbstractFieldShape{D} + +Which array-rank pattern a validated `(x, u)` pair forms, with `D` the number of velocity components +on axis 1 of `u`. Backends dispatch on this, so `D` reaches the kernels as a static method parameter. + +- [`PointField`](@ref): `u` is `(D, N)`. +- [`SharedPositionField`](@ref): `u` is `(D, N, auxiliary...)` — one set of positions, many fields. +- [`VaryingPositionField`](@ref): `x` and `u` both carry matching auxiliary axes. + +The coordinate count on axis 1 of `x` is deliberately **not** here: it is fixed by the metric's +geometry (see `HelperFunctions.coordinate_width`), so it is read off that geometry once `D` is +static rather than being restated as a shape parameter. +""" abstract type AbstractFieldShape{D} end struct PointField{D} <: AbstractFieldShape{D} end struct SharedPositionField{D} <: AbstractFieldShape{D} end struct VaryingPositionField{D} <: AbstractFieldShape{D} end +"""Velocity components on axis 1 of `u`.""" @inline spatial_dimension(::AbstractFieldShape{D}) where {D} = D + +""" + _pair_dims(metric, D) -> (Val{W}, Val{D}) + +Coordinate and velocity widths as type parameters, for the kernels that take `x`/`u` as `Array`s +(whose axis-1 lengths are values, not type parameters). `D` is already restricted to 2 or 3 by +[`_validate_spatial_dimension`](@ref), so dispatching on those two makes both results concrete; +`W` comes from the metric's geometry, which is what defines it. +""" +@inline function _pair_dims(distance_metric, D::Int) + D == 2 && return (SFH.coordinate_width(SFH.pair_geometry_for(distance_metric, Val(2))), Val(2)) + D == 3 && return (SFH.coordinate_width(SFH.pair_geometry_for(distance_metric, Val(3))), Val(3)) + return _validate_spatial_dimension(D) +end @inline has_auxiliary_axes(::PointField) = false @inline has_auxiliary_axes(::SharedPositionField) = true @inline has_auxiliary_axes(::VaryingPositionField) = true @@ -25,19 +54,36 @@ function _validate_spatial_dimension(D::Integer) return nothing end -function _validate_array_shape(x::AbstractArray, u::AbstractArray) +@inline _val_int(::Val{W}) where {W} = W + +""" + _validate_array_shape(x, u, distance_metric) -> AbstractFieldShape + +Axis-1 of `u` is the velocity dimension `D`; axis-1 of `x` is however many coordinates the +metric's geometry needs to locate a point, which is **not** always `D`. On a sphere a point takes +two coordinates whether or not the velocity carries a third, radial, component — the shell radius +belongs to the geometry, not to each point — so `x` is `(2, N)` while `u` may be `(3, N)`. +""" +function _validate_array_shape(x::AbstractArray, u::AbstractArray, distance_metric) ndims(x) >= 2 || - throw(DimensionMismatch("x must have shape (D, N) or (D, N, auxiliary...); got ndims(x)=$(ndims(x))")) + throw(DimensionMismatch("x must have shape (Dx, N) or (Dx, N, auxiliary...); got ndims(x)=$(ndims(x))")) ndims(u) >= 2 || throw(DimensionMismatch("u must have shape (D, N) or (D, N, auxiliary...); got ndims(u)=$(ndims(u))")) - D = size(x, 1) + D = size(u, 1) _validate_spatial_dimension(D) - size(u, 1) == D || - throw(DimensionMismatch("x and u must share axis-1 spatial dimension D; got size(x,1)=$D and size(u,1)=$(size(u, 1))")) + W = _val_int(first(_pair_dims(distance_metric, D))) + size(x, 1) == W || throw( + DimensionMismatch( + "this geometry locates a point with $W coordinate(s) on axis 1 of x, but got " * + "size(x,1)=$(size(x, 1)) (velocity dimension D=$D from size(u,1))", + ), + ) size(u, 2) == size(x, 2) || throw(DimensionMismatch("x and u must share axis-2 point count N; got size(x,2)=$(size(x, 2)) and size(u,2)=$(size(u, 2))")) + # Classify by array rank. The ternaries make `D` a literal type parameter, so the backend + # methods that dispatch on `PointField{D}` etc. specialize on it. if ndims(x) == 2 && ndims(u) == 2 return D == 2 ? PointField{2}() : PointField{3}() elseif ndims(x) == 2 && ndims(u) >= 3 @@ -52,7 +98,7 @@ function _validate_array_shape(x::AbstractArray, u::AbstractArray) throw( DimensionMismatch( "unsupported shape combination: x has shape $(size(x)), u has shape $(size(u)); " * - "valid forms are (D,N)/(D,N), (D,N)/(D,N,auxiliary...), or matched (D,N,auxiliary...) arrays", + "valid forms are (Dx,N)/(D,N), (Dx,N)/(D,N,auxiliary...), or matched (Dx,N,auxiliary...) arrays", ), ) end diff --git a/src/Calculations/tensor.jl b/src/Calculations/tensor.jl index e231ceb..74be542 100644 --- a/src/Calculations/tensor.jl +++ b/src/Calculations/tensor.jl @@ -5,12 +5,14 @@ function calculate_structure_function_tensor( x::AbstractArray{FT1}, u::AbstractArray{FT2}, distance_bins::AbstractVector{FT3}; - backend::AbstractExecutionBackend = SerialBackend(), + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), output_type::Type{OTT} = SFO.StructureFunctionTensor, count_eltype::Type{CT} = UInt32, + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., ) where {P, FT1, FT2, FT3, OTT, CT} - shape = _validate_array_shape(x, u) + shape = _validate_array_shape(x, u, distance_metric) + _assert_counts_representable(CT, size(x, 2)) D = spatial_dimension(shape) n_bins = n_histogram_bins(distance_bins) auxiliary_dims = has_auxiliary_axes(shape) ? size(u)[3:end] : () @@ -19,7 +21,7 @@ function calculate_structure_function_tensor( sums = zeros(OT, tensor_dims..., n_bins, auxiliary_dims...) counts = zeros(CT, n_bins, auxiliary_dims...) calculate_structure_function_tensor!( - sums, counts, order, x, u, distance_bins; backend = backend, kwargs... + sums, counts, order, x, u, distance_bins; backend = backend, distance_metric, kwargs... ) # The backend produces the raw accumulator; `_finalize` returns it as-is or as the averaged # mean tensor (the default), mirroring the 1D output-type dispatch. @@ -34,17 +36,20 @@ function calculate_structure_function_tensor!( x::AbstractArray, u::AbstractArray, distance_bins::AbstractVector; - backend::AbstractExecutionBackend = SerialBackend(), + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + distance_metric::DI.PreMetric = DI.Euclidean(), kwargs..., ) where {P} - shape = _validate_array_shape(x, u) + shape = _validate_array_shape(x, u, distance_metric) + # Only forward knobs the kernel accepts; it has no `kwargs...` sink. return _dispatch_tensor!( - backend, shape, sums, counts, order, x, u, distance_bins; kwargs... + backend, shape, sums, counts, order, x, u, distance_bins; + distance_metric = distance_metric, ) end function _dispatch_tensor!( - ::SerialBackend, + ::CB.AbstractSerialBackend, shape::AbstractFieldShape, sums::AbstractArray, counts::AbstractArray, @@ -60,7 +65,7 @@ function _dispatch_tensor!( end function _dispatch_tensor!( - ::AutoBackend, + ::CB.AbstractAutoBackend, shape::AbstractFieldShape, sums::AbstractArray, counts::AbstractArray, @@ -71,19 +76,19 @@ function _dispatch_tensor!( kwargs..., ) return _dispatch_tensor!( - SerialBackend(), shape, sums, counts, order, x, u, distance_bins; kwargs... + CB.SerialBackend(), shape, sums, counts, order, x, u, distance_bins; kwargs... ) end function _dispatch_tensor!( - backend::Union{ThreadedBackend, DistributedBackend, GPUBackend}, + backend::Union{CB.AbstractThreadedBackend, CB.AbstractDistributedBackend, CB.AbstractGPUBackend}, ::AbstractFieldShape, args...; kwargs..., ) throw( ArgumentError( - "$(typeof(backend)) tensor backend is not implemented yet; use backend=SerialBackend()", + "$(typeof(backend)) tensor backend is not implemented yet; use backend=CB.SerialBackend()", ), ) end @@ -110,10 +115,10 @@ function serial_calculate_structure_function_tensor!( size(counts) == expected_counts || throw(DimensionMismatch("counts must have shape $expected_counts; got $(size(counts))")) - fill!(sums, zero(eltype(sums))) - fill!(counts, zero(eltype(counts))) - dist_be = BinEdges(distance_bins) + # Euclidean bins on r²; other metrics keep the scalar digitize. + plan = squared_digitize_plan(dist_be) + euclid = distance_metric isa DI.Euclidean N = size(u, 2) B = isempty(auxiliary_dims) ? 1 : prod(auxiliary_dims) fixed_x = ndims(x) == 2 @@ -130,8 +135,9 @@ function serial_calculate_structure_function_tensor!( if fixed_x X1 = SA.SVector{D, eltype(x)}(ntuple(d -> x_fixed[d, i], vD)) X2 = SA.SVector{D, eltype(x)}(ntuple(d -> x_fixed[d, j], vD)) - dist = distance_metric(X1, X2) - bin = SFH.digitize(dist, dist_be) + dx = X2 - X1 + bin = euclid ? squared_digitize(plan, LA.dot(dx, dx)) : + SFH.digitize(distance_metric(X1, X2), dist_be) if 1 <= bin <= n_bins for b in 1:B U1 = SA.SVector{D, eltype(u)}(ntuple(d -> u_flat[d, i, b], vD)) @@ -143,8 +149,9 @@ function serial_calculate_structure_function_tensor!( for b in 1:B X1 = SA.SVector{D, eltype(x)}(ntuple(d -> x_flat[d, i, b], vD)) X2 = SA.SVector{D, eltype(x)}(ntuple(d -> x_flat[d, j, b], vD)) - dist = distance_metric(X1, X2) - bin = SFH.digitize(dist, dist_be) + dx = X2 - X1 + bin = euclid ? squared_digitize(plan, LA.dot(dx, dx)) : + SFH.digitize(distance_metric(X1, X2), dist_be) if 1 <= bin <= n_bins U1 = SA.SVector{D, eltype(u)}(ntuple(d -> u_flat[d, i, b], vD)) U2 = SA.SVector{D, eltype(u)}(ntuple(d -> u_flat[d, j, b], vD)) diff --git a/src/Calculations/workspace.jl b/src/Calculations/workspace.jl new file mode 100644 index 0000000..a38c05a --- /dev/null +++ b/src/Calculations/workspace.jl @@ -0,0 +1,159 @@ +# CPUSFWorkspace — reusable host scratch for the batch (auxiliary-axis) drivers. + +""" + _bl_partition(B, n_tasks, accum_bytes) -> (bchunks, n_ichunks) + +The batch-axis chunks and the number of outer-index chunks each is split into. Shared by the +threaded executor and by [`CPUSFWorkspace`](@ref) so a workspace cannot be sized for a partition +the executor will not use. +""" +@inline function _bl_partition(B::Int, n_tasks::Int, accum_bytes::Int) + n_bchunks = _bl_batch_chunk_count(accum_bytes, B, n_tasks) + bchunks = _bl_batch_chunks(B, n_bchunks) + return bchunks, max(1, n_tasks ÷ n_bchunks) +end + +"""Accumulator axes after the leading batch axis, per workspace kind.""" +@inline _bl_accum_tail(::Val{:sf1d}, n_bins::Int, ::Int) = (n_bins,) +@inline _bl_accum_tail(::Val{:joint2d}, n_bins::Int, n_val::Int) = (n_bins, n_val) +@inline _bl_accum_tail(::Val{:single_pass}, n_bins::Int, ::Int) = (SINGLE_PASS_N, n_bins) +@inline _bl_accum_tail(::Val{:single_pass_2d}, n_bins::Int, n_val::Int) = + (SINGLE_PASS_N, n_bins, n_val) + +""" + CPUSFWorkspace{kind}(x, u, distance_bins[, value_bins]; backend = SerialBackend(), count_eltype = UInt32) + +Reusable CPU scratch for the batch drivers: the batch-leading working copies of `x`/`u`, one +accumulator per task, and the full-width reduction accumulator. Pass to a batch entry point as +`workspace = ...` to make repeated calls allocation-free. + +Without it a batch call allocates one accumulator per task — tens of MiB at large `B` — on every +call. That does not slow the fastest call, but the resulting GC pauses land on *some* calls, so the +typical call is far slower than the best one and the spread is wide. Reusing the buffers removes +the pauses, not the peak. + +`kind` matches [`GPUSFWorkspace`](@ref): `:sf1d`, `:joint2d`, `:single_pass` or `:single_pass_2d`. +It is a type parameter, so the accumulator rank is fixed at construction and every field is +concretely typed. + +Built from the same arguments as the call it serves — including `backend`, which fixes how many +accumulators it holds — and checked against them on use: a workspace built for a different shape, +element type or backend is a hard error, never a silent reallocation. Composes with [`BatchLeading`](@ref) — when the input is already batch-leading the +transpose buffers have length zero and are never touched. + +Not thread-safe: one workspace serves one call at a time, exactly like [`GPUSFWorkspace`](@ref). +""" +struct CPUSFWorkspace{kind, OT, CT, FTx, FTu, NA} + xb::Array{FTx, 3} + ub::Array{FTu, 3} + accs::Vector{Tuple{Array{OT, NA}, Array{CT, NA}}} + result::Tuple{Array{OT, NA}, Array{CT, NA}} + widths::Vector{Int} + B::Int + N::Int + D::Int + W::Int + n_tasks::Int +end + +function CPUSFWorkspace{kind}( + x::BatchInput, + u::BatchInput, + distance_bins::AbstractVector, + value_bins = nothing; + backend::CB.AbstractExecutionBackend = CB.SerialBackend(), + count_eltype::Type{CT} = UInt32, +) where {kind, CT} + kind in (:sf1d, :joint2d, :single_pass, :single_pass_2d) || throw(ArgumentError( + "CPUSFWorkspace kind must be :sf1d, :joint2d, :single_pass or :single_pass_2d; got :$kind")) + x_raw, x_bl = _bl_unwrap(x) + u_raw, u_bl = _bl_unwrap(u) + fixed_x = ndims(x_raw) == 2 + FTx, FTu = eltype(x_raw), eltype(u_raw) + OT = promote_type(float(FTx), float(FTu)) + + # Coordinate width and velocity width are independent: on a shell `x` is (2, N) while `u` may + # be (3, N), so the two transpose buffers are sized separately. + W = x_bl ? size(x_raw, 2) : size(x_raw, 1) + if u_bl + B, D, N = size(u_raw) + else + D, N = size(u_raw, 1), size(u_raw, 2) + B = prod(size(u_raw)[3:end]) + end + n_bins = n_histogram_bins(distance_bins) + n_val = value_bins === nothing ? 0 : + n_histogram_bins(value_bins isa Tuple ? value_bins[1] : value_bins) + tail = _bl_accum_tail(Val(kind), n_bins, n_val) + + # Length zero when the input is already batch-leading: there is nothing to transpose into. + xb = Array{FTx, 3}(undef, (fixed_x || x_bl) ? (0, 0, 0) : (B, W, N)) + ub = Array{FTu, 3}(undef, u_bl ? (0, 0, 0) : (B, D, N)) + + n_tasks = _bl_n_tasks(backend) + accum_bytes = B * prod(tail) * (sizeof(OT) + sizeof(CT)) + bchunks, n_ichunks = _bl_partition(B, n_tasks, accum_bytes) + widths = [length(bc) for bc in bchunks for _ in 1:n_ichunks] + accs = [(zeros(OT, w, tail...), zeros(CT, w, tail...)) for w in widths] + result = (zeros(OT, B, tail...), zeros(CT, B, tail...)) + + return CPUSFWorkspace{kind, OT, CT, FTx, FTu, length(tail) + 1}( + xb, ub, accs, result, widths, B, N, D, W, n_tasks, + ) +end + +"""Accumulator axes after the batch axis, as the workspace was built for.""" +@inline _ws_tail(ws::CPUSFWorkspace) = size(ws.result[1])[2:end] + +# The kernels write through `@inbounds`, so a workspace built for other inputs must be rejected +# before it is used, never left to corrupt memory. The two checks run where their information first +# exists: the input shape inside `_bl_prepare`, the accumulator layout in the driver. + +"""Throw unless `ws` was built for this input shape. Checked before the transpose buffers are used.""" +@inline _validate_ws_shape(::Nothing, ::Int, ::Int, ::Int, ::Int) = nothing + +function _validate_ws_shape(ws::CPUSFWorkspace, B::Int, N::Int, D::Int, W::Int) + (ws.B, ws.N, ws.D, ws.W) == (B, N, D, W) || throw(ArgumentError( + "CPUSFWorkspace built for (B, N, D, W) = $((ws.B, ws.N, ws.D, ws.W)); called with $((B, N, D, W))")) + return nothing +end + +"""Throw unless `ws` holds accumulators of this kind and shape. Checked before they are used.""" +@inline _validate_ws_layout(::Nothing, ::Symbol, ::Tuple) = nothing + +function _validate_ws_layout(ws::CPUSFWorkspace{kind}, want_kind::Symbol, tail::Tuple) where {kind} + kind === want_kind || + throw(ArgumentError("CPUSFWorkspace kind :$kind incompatible with requested :$want_kind")) + _ws_tail(ws) == tail || throw(ArgumentError( + "CPUSFWorkspace built for accumulator axes $(_ws_tail(ws)); called with $tail")) + return nothing +end + +"""Zero every accumulator held by a [`CPUSFWorkspace`](@ref); the drivers do this per call.""" +function reset_histogram!(ws::CPUSFWorkspace) + for (s, c) in ws.accs + fill!(s, zero(eltype(s))) + fill!(c, zero(eltype(c))) + end + fill!(ws.result[1], zero(eltype(ws.result[1]))) + fill!(ws.result[2], zero(eltype(ws.result[2]))) + return ws +end + +# --- Buffer providers for the batch drivers (the `::Nothing` fallbacks live in batch_leading.jl, +# which loads before this type exists) --- + +@inline _ws_ub(ws::CPUSFWorkspace) = ws.ub +@inline _ws_xb(ws::CPUSFWorkspace) = ws.xb + +function _bl_accum_pool(ws::CPUSFWorkspace, ::F, widths::Vector{Int}) where {F} + ws.widths == widths || throw(ArgumentError( + "CPUSFWorkspace holds accumulators of batch widths $(ws.widths); this call needs $widths. \ + Rebuild it with the same inputs, backend and n_tasks as the call.")) + return ws.accs +end + +function _bl_result_accum(ws::CPUSFWorkspace, ::F, ::Int) where {F} + _bl_zero_accum!(ws.result) + return ws.result +end diff --git a/src/HelperFunctions.jl b/src/HelperFunctions.jl index 618ab83..1e4176b 100644 --- a/src/HelperFunctions.jl +++ b/src/HelperFunctions.jl @@ -29,6 +29,20 @@ export digitize, r̂, n̂, δr, + unit_position, + local_east_north, + geodesic_frame, + geodesic_increments, + FlatGeometry, + SphericalGeometry, + coordinate_width, + pair_frame, + pair_direction, + pair_delta, + pair_invariants, + pair_increments, + pair_geometry, + pair_geometry_for, midpoints, flatten_data, remove_nans @@ -97,17 +111,13 @@ end @inline LA.normalize(x::Tuple{T, Vararg{T}}) where {T} = NTuple{length(x), T}(LA.normalize(SA.SVector(x))) +"""Return the vector from `x1` to `x2`.""" @inline function δr(x1, x2) - """ - Return the vector from x1 to x2 - """ return x2 .- x1 end +"""Return the longitudinal (parallel) unit vector from `x1` to `x2`.""" @inline function r̂(x1, x2) - """ - Return the longitudinal (parallel) unit vector from x1 to x2 - """ return LA.normalize(δr(x1, x2)) end @@ -116,46 +126,357 @@ end # If dynamic Vectors are ever used, LA.normalize would be ~2.5x slower due to scaling checks. @inline r̂(x1, x2, ::DI.PreMetric, distance) = LA.normalize(δr(x1, x2)) +# ----------------------------------------------------------------------------- +# Spherical geometry: unit positions, geodesic frames, parallel transport +# ----------------------------------------------------------------------------- + +@inline _unit_position(sλ, cλ, sφ, cφ) = SA.SVector(cφ * cλ, cφ * sλ, sφ) + +@inline _local_east_north(sλ, cλ, sφ, cφ) = + (SA.SVector(-sλ, cλ, zero(sλ)), SA.SVector(-sφ * cλ, -sφ * sλ, cφ)) + +""" + unit_position(lon, lat) -> SVector{3} + +Unit position vector on the sphere from longitude/latitude **in degrees** (the +`Distances.Haversine` convention). `x` toward (0°N, 0°E), `z` toward the north pole. +""" +@inline unit_position(lon, lat) = _unit_position(sincosd(lon)..., sincosd(lat)...) + +""" + local_east_north(lon, lat) -> (Ê, N̂) + +Local east and north unit vectors at longitude/latitude **in degrees**. Together with +[`unit_position`](@ref) as the local up they form a right-handed orthonormal triad +(`Ê × N̂ = p̂`). Only used at ingest: `p̂` itself is well defined at the poles, this basis is not. +""" +@inline local_east_north(lon, lat) = _local_east_north(sincosd(lon)..., sincosd(lat)...) + +""" +Smallest `sin²σ` for which the separation direction is still representable. + +This guards only against `1/0`, NOT against a physical scale: the normalization is exact in the +`σ → 0` limit (`t_A ≈ d` has magnitude `O(σ)` and `inv_s ≈ 1/σ`, so the product stays `O(1)`), so +short pairs are fine and must not be dropped. `eps(T)` would be catastrophically wrong here — +`sin²σ` for a 1 km separation on Earth is `2.5e-8`, below `eps(Float32)`, which would silently +discard every pair closer than ~2 km in Float32. +""" +@inline _geodesic_degeneracy_tol(::Type{T}) where {T} = floatmin(T) + +""" + geodesic_frame(p̂, q̂) -> (σ, t̂_A, t̂_B, m̂, ok) + +Great-circle frame for the pair `(p̂, q̂)` of unit position vectors: central angle `σ`, the +longitudinal unit tangent at each endpoint (`t̂_A` at `p̂` toward `q̂`, `t̂_B` at `q̂` continuing along +the geodesic), and the shared transverse unit vector `m̂`. + +`m̂` is the same 3-vector at both endpoints: the great-circle normal is perpendicular to every point +of that circle, hence tangent to the sphere at each of them, and it is parallel along the geodesic. +Both tangents also share one normalizer, since `‖q̂ − (p̂·q̂)p̂‖² = ‖(p̂·q̂)q̂ − p̂‖² = 1 − (p̂·q̂)²`. +So the whole frame costs one `sqrt`. + +`σ` uses the tangent-half-angle form `2·atan(‖p̂−q̂‖, ‖p̂+q̂‖)`, which is accurate for every `σ` +including antipodal, unlike `acos(p̂·q̂)` (which loses half the mantissa near `σ=0` — fatal in Float32). + +`ok` is `false` for coincident (`σ=0`) and antipodal (`σ=π`) pairs, where the direction is genuinely +undefined — antipodal points are joined by infinitely many great circles, so parallel transport +between them is not unique. Callers must skip such pairs: `1/s` is otherwise `Inf` and a single NaN +lane poisons an entire atomic accumulator. +""" +@inline function geodesic_frame(p̂::SA.SVector{3, T}, q̂::SA.SVector{3, T}) where {T} + # Work through d = q̂ - p̂ (magnitude O(σ)): forming `q̂ - (p̂·q̂)p̂` directly cancels + # catastrophically as σ → 0 because both terms approach p̂. + d = q̂ - p̂ + sum_pq = p̂ + q̂ + dp = LA.dot(d, p̂) # = p̂·q̂ - 1 = -2sin²(σ/2), small and accurate + t_A = d - dp * p̂ # ≡ q̂ - (p̂·q̂)p̂ + t_B = dp * q̂ + d # ≡ (p̂·q̂)q̂ - p̂ + w = LA.cross(p̂, d) # ≡ p̂ × q̂ + s2 = LA.dot(w, w) # = sin²σ + σ = 2 * atan(sqrt(LA.dot(d, d)), sqrt(LA.dot(sum_pq, sum_pq))) + ok = s2 > _geodesic_degeneracy_tol(T) + inv_s = ok ? inv(sqrt(s2)) : zero(T) + return σ, t_A * inv_s, t_B * inv_s, w * inv_s, ok +end + +""" + FlatGeometry{D}() + +Flat `D`-dimensional space with the Euclidean ruler: the separation is the straight chord and no +transport is needed. +""" +struct FlatGeometry{D} end + +""" + SphericalGeometry{D}(metric, radius) + +Sphere of the given `radius`. `D` is the velocity dimension: `2` for horizontal `(east, north)` +velocities, `3` for a thin shell carrying an additional radial component. + +`D` cannot be inferred from the coordinates — a point on a shell has two of them either way — and it +changes the answer, because `transverse_component_norm2` divides the transverse energy by `D - 1`. + +`metric` is retained because the coordinates mean whatever it says they mean: it is what fixes their +angle unit, which `pair_frame` needs in order to take a `sincos`. See [`unit_position`](@ref). +""" +struct SphericalGeometry{D, M, T} + metric::M + radius::T +end +SphericalGeometry{D}(metric::M, radius::T) where {D, M, T} = SphericalGeometry{D, M, T}(metric, radius) + +""" + coordinate_width(geometry) -> Val{W} + +How many numbers locate one point in this geometry, as a `Val` so callers can build a +statically-sized load. This is **not** the velocity dimension: on a shell a point takes two +coordinates whether or not the velocity carries a third, radial, component. +""" +@inline coordinate_width(::FlatGeometry{D}) where {D} = Val(D) +@inline coordinate_width(::SphericalGeometry) = Val(2) + +""" + pair_frame(geometry, x1, x2) -> (ok, r, frame) + +Separation and the geometry-specific frame data for one pair, touching **no velocities**. + +Split from [`pair_increments`](@ref) because callers depend on that order: the scalar kernels reject +out-of-range pairs before loading `u_j` at all, and the batch kernels build one frame per `(i, j)` +and reuse it across a whole strip of velocity fields. A single call taking the velocities would +defeat both. +""" +@inline function pair_frame(::FlatGeometry, x1, x2) + dx = δr(x1, x2) + # Carry the RAW displacement, not `dx / r`: normalizing here would make every out-of-range pair + # pay a divide and D multiplies for a direction the bin test is about to discard. + return true, sqrt(LA.dot(dx, dx)), dx +end + +""" +Spherical frame from raw `(lon, lat)` coordinates, expressed in each endpoint's own local +`(east, north)` basis. + +The ambient form of [`geodesic_frame`](@ref) needs 3-vectors, which would force the caller's `(2, N)` +lon/lat array to be widened to `(3, N)`. Projecting the geodesic tangents onto the local bases +instead keeps everything the width the caller passed — the longitudinal direction at `A` is just +`(sin α₁, cos α₁)` for the forward azimuth `α₁`, and the transverse is its right-handed quarter turn. +Parallel transport is still exact: it preserves the angle to the geodesic, which is what `α` measures. +""" +@inline function pair_frame(g::SphericalGeometry, x1, x2) + p̂ = unit_position(g.metric, x1[1], x1[2]) + q̂ = unit_position(g.metric, x2[1], x2[2]) + σ, t_A, t_B, m̂, ok = geodesic_frame(p̂, q̂) + Ê_A, N̂_A = local_east_north(g.metric, x1[1], x1[2]) + Ê_B, N̂_B = local_east_north(g.metric, x2[1], x2[2]) + FT = typeof(σ) + # Local components of the longitudinal tangent at each end; n̂ = ẑ × t̂ within the tangent plane. + tA = SA.SVector{2, FT}(LA.dot(t_A, Ê_A), LA.dot(t_A, N̂_A)) + tB = SA.SVector{2, FT}(LA.dot(t_B, Ê_B), LA.dot(t_B, N̂_B)) + return ok, g.radius * σ, (tA, tB, p̂, q̂, m̂, Ê_A, N̂_A, Ê_B, N̂_B) +end + +""" + pair_direction(geometry, frame, r) -> r̂ + +Longitudinal unit vector for one pair. Depends only on the geometry of the pair, never on the +velocities, so a caller sweeping many velocity fields over one `(i, j)` hoists this out of that loop. +""" +@inline pair_direction(::FlatGeometry, frame, r) = frame / r + +""" +On the sphere the frame IS the basis, so the longitudinal direction is `ê₁` by construction. +""" +@inline pair_direction(::SphericalGeometry{D}, frame, r) where {D} = + SA.SVector{D}(ntuple(i -> i == 1 ? one(eltype(frame[1])) : zero(eltype(frame[1])), Val(D))) + +""" + pair_invariants(geometry, frame, r, u1, u2) -> (δu_L, ‖δu‖²) + +The only two scalars the six isotropic invariants consume: every one of them is built from `δu_L`, +`δu_L²` and `δu_T² = ‖δu‖² − δu_L²`. Kernels that need no separation direction call this instead of +[`pair_increments`](@ref) and never form `r̂`. +""" +@inline function pair_invariants(::FlatGeometry, frame, r, u1, u2) + δu = u2 - u1 + # `dot(δu, frame) / r`, not `dot(δu, frame / r)`: one rounding, and the same operation order the + # flat kernels have always used. + return LA.dot(δu, frame) / r, LA.dot(δu, δu) +end + +@inline function pair_invariants(g::SphericalGeometry, frame, r, u1, u2) + δu = pair_delta(g, frame, nothing, nothing, u1, u2) + return δu[1], LA.dot(δu, δu) +end + +""" + pair_delta(geometry, frame, x1, x2, u1, u2) -> δu +Velocity difference expressed in the pair's common frame, given the `frame` from +[`pair_frame`](@ref). The per-velocity-field half of [`pair_increments`](@ref). +""" +@inline pair_delta(::FlatGeometry, frame, x1, x2, u1, u2) = u2 - u1 + +""" +Increments for `u = (east, north)` on the sphere. Each endpoint's velocity is projected onto its own +geodesic frame and only then differenced — that IS the parallel transport, because transport along a +geodesic preserves the angle to it. `n̂ = ẑ × t̂ = (−t̂₂, t̂₁)` matches the package handedness. +""" +@inline function pair_delta(::SphericalGeometry{2}, frame, x1, x2, u_A, u_B) + tA, tB = frame[1], frame[2] + nA = SA.SVector(-tA[2], tA[1]) + nB = SA.SVector(-tB[2], tB[1]) + δu_L = LA.dot(u_B, tB) - LA.dot(u_A, tA) + δu_T = LA.dot(u_B, nB) - LA.dot(u_A, nA) + return SA.SVector{2, typeof(δu_L)}(δu_L, δu_T) +end + +""" +Thin shell, `u = (east, north, up)`. Horizontal components transport exactly as in 2D; the radial +component is a scalar difference needing no transport, since the geodesic frame is tangent to the +sphere and therefore orthogonal to the radial direction at both endpoints. +""" +@inline function pair_delta(::SphericalGeometry{3}, frame, x1, x2, u_A, u_B) + tA, tB = frame[1], frame[2] + nA = SA.SVector(-tA[2], tA[1]) + nB = SA.SVector(-tB[2], tB[1]) + hA = SA.SVector(u_A[1], u_A[2]) + hB = SA.SVector(u_B[1], u_B[2]) + δu_L = LA.dot(hB, tB) - LA.dot(hA, tA) + δu_T = LA.dot(hB, nB) - LA.dot(hA, nA) + δw = u_B[3] - u_A[3] + return SA.SVector{3, typeof(δu_L)}(δu_L, δu_T, δw) +end + +""" + pair_increments(geometry, frame, r, x1, x2, u1, u2) -> (δu, r̂) + +Velocity difference and longitudinal unit vector in one common frame, given the `frame` and +separation `r` from [`pair_frame`](@ref). See [`pair_geometry`](@ref) for what the result means per +geometry. Called only for pairs that survive the bin test, so this is where the direction is formed. +""" +@inline pair_increments(g, frame, r, x1, x2, u1, u2) = + (pair_delta(g, frame, x1, x2, u1, u2), pair_direction(g, frame, r)) + +""" + pair_geometry(geometry, x1, x2, u1, u2) -> (ok, r, δu, r̂) + +Resolve one pair into a separation `r`, a velocity difference `δu`, and a longitudinal unit vector +`r̂`, **all in one common frame**, so that every structure-function operator — which consumes only +`δu·r̂` and `δu·n̂(r̂)` — works unchanged for any geometry. `ok == false` marks a pair with no defined +separation direction; callers must skip it. + +For [`SphericalGeometry`](@ref), `x1`/`x2` are `(lon, lat)` in the metric's angle unit and `u1`/`u2` +are `(east, north[, up])`. The result is expressed in the local geodesic frame, so `r̂ = ê₁` and +`δu = (δu_L, δu_T)` (plus the radial difference for `D = 3`). The radial component needs no transport +and cannot leak into `δu_L`/`δu_T`, because `t̂ ⟂ p̂` and `m̂ ⟂ p̂, q̂`. + +This is the one-shot convenience form; hot loops use [`pair_frame`](@ref) and +[`pair_increments`](@ref) separately so the frame can gate the bin test and be reused across fields. +""" +@inline function pair_geometry(g, x1, x2, u1, u2) + ok, r, frame = pair_frame(g, x1, x2) + δu, rhat = pair_increments(g, frame, r, x1, x2, u1, u2) + return ok, r, δu, rhat +end + +""" + pair_geometry_for(metric, ::Val{D}) -> geometry + +Geometry implied by `metric` for user-facing dimension `D`. A distance function alone does not define +a direction or a transport rule, so there is deliberately **no generic method**: an unrecognized +metric raises rather than silently assuming flat space. Add a method here (and a +[`pair_geometry`](@ref) method for the geometry it returns) to support another manifold. +""" +pair_geometry_for(::DI.Euclidean, ::Val{D}) where {D} = FlatGeometry{D}() +pair_geometry_for(m::DI.Haversine, ::Val{D}) where {D} = SphericalGeometry{D}(m, m.radius) +# SphericalAngle reports the central angle itself, i.e. a unit sphere. +pair_geometry_for(m::DI.SphericalAngle, ::Val{D}) where {D} = SphericalGeometry{D}(m, 1) + +""" + unit_position(metric, lon, lat) -> SVector{3} + local_east_north(metric, lon, lat) -> (Ê, N̂) + +Ingest helpers that take the angle unit from the metric's own documented convention: +`Distances.Haversine` is **degrees**, `Distances.SphericalAngle` is **radians**. Confusing the two +silently rescales every separation by a factor of ~57, so the convention is pinned next to the metric +that defines it rather than repeated at each call site. +""" +@inline unit_position(::DI.Haversine, lon, lat) = unit_position(lon, lat) +@inline local_east_north(::DI.Haversine, lon, lat) = local_east_north(lon, lat) +@inline unit_position(::DI.SphericalAngle, lon, lat) = + _unit_position(sincos(lon)..., sincos(lat)...) +@inline local_east_north(::DI.SphericalAngle, lon, lat) = + _local_east_north(sincos(lon)..., sincos(lat)...) + +pair_geometry_for(m, ::Val{D}) where {D} = throw(ArgumentError( + "no pair geometry is defined for distance_metric=$(typeof(m)). A distance function fixes which " * + "histogram bin a pair falls in, but it does not define the separation direction or how to " * + "compare velocities at two different points, so this package will not guess one. Define " * + "`StructureFunctions.HelperFunctions.pair_geometry_for(::$(typeof(m)), ::Val)` returning a " * + "geometry, plus a `pair_geometry` method for it.", +)) + +""" + geodesic_increments(t̂_A, t̂_B, m̂, u_A, u_B) -> (δu_L, δu_T) + +Longitudinal and transverse components of the parallel-transported velocity difference, given the +frame from [`geodesic_frame`](@ref) and the two ambient tangent velocities. + +Projecting each endpoint's velocity onto its own geodesic tangent **is** parallel transport, not an +approximation: a geodesic parallel-transports its own tangent, and transport on the sphere is an +orientation-preserving isometry, so the transported basis from `A` arrives at `B` rotated by exactly +the difference of forward azimuths. The transverse term needs a single dot product because `m̂` is +shared between the endpoints. +""" +@inline function geodesic_increments(t̂_A, t̂_B, m̂, u_A, u_B) + δu_L = LA.dot(u_B, t̂_B) - LA.dot(u_A, t̂_A) + δu_T = LA.dot(u_B - u_A, m̂) + return δu_L, δu_T +end + + +""" + n̂(r_hat) + +Oriented transverse unit vector for the longitudinal unit vector `r_hat`. + +2D: `n̂ = ẑ × r̂ = (−r̂₂, r̂₁)`, the counterclockwise quarter turn, so `(r̂, n̂, ẑ)` is right-handed. +3D: `n̂ = normalize(ẑ × r̂)`, the same rule with `ẑ = (0,0,1)` as the reference axis. + +Only operators odd in the transverse component see this sign — `ProjectedStructureFunctionType{2,1}` +and `{0,3}`. Everything else consumes `δu_T²` (see [`transverse_norm2`](@ref)) and is sign-blind. +The 3D form is singular when `r̂ ∥ ẑ`; [`ReferenceAxisTransverseBasis`](@ref) is the guarded version. +""" @inline function n̂(r_hat::AbstractVector{FT}) where {FT} - """ - Return the transverse (perpendicular) unit vector given the longitudinal unit vector r_hat. - In 2D: n̂ = [r_hat[2], -r_hat[1]] - In 3D: n̂ = normalize(cross(r_hat, k_hat)) where k_hat = [0,0,1] - """ ND::Int = length(r_hat) if ND == 2 - return SA.SVector{2, FT}(r_hat[2], -r_hat[1]) # assume normalized + return SA.SVector{2, FT}(-r_hat[2], r_hat[1]) # assume normalized elseif ND == 3 k_hat = SA.SVector{3, FT}(0, 0, 1) - # Lindberg and Cho defined this order in NH and opposite in SH but we're just doing the same for both return LA.normalize( - LA.cross(SA.SVector{3, FT}(r_hat[1], r_hat[2], r_hat[3]), k_hat), + LA.cross(k_hat, SA.SVector{3, FT}(r_hat[1], r_hat[2], r_hat[3])), ) else error("Only 2D and 3D supported") end end -@inline n̂(r_hat::SA.SVector{2, T}) where {T} = SA.SVector{2, T}(r_hat[2], -r_hat[1]) +@inline n̂(r_hat::SA.SVector{2, T}) where {T} = SA.SVector{2, T}(-r_hat[2], r_hat[1]) @inline n̂(r_hat::SA.SVector{3, T}) where {T} = LA.normalize( - LA.cross(SA.SVector{3, T}(r_hat[1], r_hat[2], r_hat[3]), SA.SVector{3, T}(0, 0, 1)), + LA.cross(SA.SVector{3, T}(0, 0, 1), SA.SVector{3, T}(r_hat[1], r_hat[2], r_hat[3])), ) -@inline n̂(r_hat::NTuple{2, T}) where {T} = (r_hat[2], -r_hat[1]) -# @inline n̂(r_hat::NTuple{3, T}) where {T} = error("see if we can make this stay in tuple land without any burden") LA.normalize( - # LA.cross(SA.SVector{3, T}(r_hat[1], r_hat[2], r_hat[3]), SA.SVector{3, T}(0, 0, 1)), -# ) +@inline n̂(r_hat::NTuple{2, T}) where {T} = (-r_hat[2], r_hat[1]) +""" +Return the transverse (perpendicular) unit vector from `x1` to `x2`, defined as the cross product +of the local vertical with the longitudinal unit vector. This naming is opposite to the Lindborg +and Cho convention. +""" @inline function n̂(x1, x2) - """ - Return the transverse (perpendicular) unit vector from x to y - Calling this n̂ is opposite of Lindberg and Cho notation, but idk... - This is defined as the cross between the unit vector in the vertical direction and the longitudinal unit vector - """ return n̂(r̂(x1, x2)) end @@ -296,28 +617,28 @@ end end +""" +Return the signed longitudinal magnitude of `δu` along `r_hat`. The caller must ensure `r_hat` is +a unit vector. +""" @inline function magnitude_δu_longitudinal(δu, r_hat) - """ - Return the longitudinal component of u (along the vector) - Left to the user to ensure r_hat has norm 1 - """ return LA.dot(δu, r_hat) # r_hat is unit vector so just dot product end +""" +Return the longitudinal component of `δu` along `r_hat`, as a vector. The caller must ensure +`r_hat` is a unit vector. +""" @inline function δu_longitudinal(δu, r_hat) - """ - Return the longitudinal component of u (along the vector) - Left to the user to ensure r_hat has norm 1 - """ return magnitude_δu_longitudinal(δu, r_hat) * r_hat end +""" +Return the transverse magnitude of `δu`, signed relative to the normal vector `n̂(r_hat)`. The +caller must ensure `r_hat` is a unit vector. +""" @inline function magnitude_δu_transverse(δu, r_hat) - """ - Return the magnitude of the transverse component of u (perpendicular to the vector) relative to the normal vector... - Left to the user to ensure r_hat has norm 1 - """ - # This instead of LA.norm(δu .- δu_longitudinal(δu, r_hat)) because we want the signed magnitude relative to the normal vector... + # Signed relative to n̂, unlike LA.norm(δu .- δu_longitudinal(δu, r_hat)). return LA.dot(δu, n̂(r_hat)) end @@ -330,16 +651,12 @@ end return transverse_component(δu, r_hat, basis, basis_index) end +""" +Return the transverse component of `δu` (perpendicular to `r_hat`), as a vector. The caller must +ensure `r_hat` is a unit vector. +""" @inline function δu_transverse(δu, r_hat) - """ - Return the transverse component of u (perpendicular to the vector) - Left to the user to ensure r_hat (and local_unit_vertical) has norm 1 - - -- note, it appears these two methods turned out to be identical -- see if we can simplify... - """ - - return δu .- δu_longitudinal(δu, r_hat) # I think this is faster than magnitude_δu_transverse(δu, r_hat) * n̂(δu, r_hat) - + return δu .- δu_longitudinal(δu, r_hat) end """ diff --git a/src/StructureFunctionTypes.jl b/src/StructureFunctionTypes.jl index 3342506..87c8282 100644 --- a/src/StructureFunctionTypes.jl +++ b/src/StructureFunctionTypes.jl @@ -211,6 +211,38 @@ const T3SF = OffDiagonalConsistentThirdOrderStructureFunction const L2T1SF = DiagonalInconsistentThirdOrderStructureFunction const L1T2SF = OffDiagonalInconsistentThirdOrderStructureFunction +# --------------------------------------------------------------------------- +# Raw-geometry evaluation (pair kernels) +# --------------------------------------------------------------------------- + +""" + _sf_raw(sf, δu, dx, r2) + +Evaluate `sf` from raw pair geometry: separation `dx`, its squared length `r2 = dx⋅dx`, and `δu`. + +Identical to `sf(δu, dx/√r2)` for every operator. The second-order specializations below are +polynomials in `p = δu⋅dx` and `‖δu‖²` over a power of `r²`, so they need no `sqrt`; odd orders and +odd transverse orders need `r̂` and fall through to the generic method. +""" +@inline _sf_raw(sf::AbstractStructureFunctionType, δu, dx, r2) = sf(δu, dx / sqrt(r2)) + +@inline _sf_raw(::SecondOrderStructureFunctionType, δu, dx, r2) = norm2(δu) + +@inline function _sf_raw(::ProjectedStructureFunctionType{2, 0}, δu, dx, r2) + p = LA.dot(δu, dx) + return p * p / r2 +end + +@inline function _sf_raw(::ProjectedStructureFunctionType{0, 2}, δu, dx, r2) + p = LA.dot(δu, dx) + return norm2(δu) - p * p / r2 +end + +@inline function _sf_raw(::TransverseComponentSecondOrderStructureFunctionType, δu, dx, r2) + p = LA.dot(δu, dx) + return (norm2(δu) - p * p / r2) / (length(dx) - 1) +end + """ RotationalSecondOrderStructureFunctionType() diff --git a/src/StructureFunctions.jl b/src/StructureFunctions.jl index 0acca4a..90ba87c 100644 --- a/src/StructureFunctions.jl +++ b/src/StructureFunctions.jl @@ -39,11 +39,9 @@ export calculate_structure_function, calculate_structure_function!, calculate_st calculate_structure_function_tensor, calculate_structure_function_tensor!, calculate_structure_function_batch!, calculate_structure_function_2d_batch!, calculate_structure_functions_single_pass_batch!, calculate_structure_functions_single_pass_2d_batch!, - GPUSFWorkspace, reset_histogram!, release!, + GPUSFWorkspace, CPUSFWorkspace, reset_histogram!, release!, joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256 export marginalize -export AbstractExecutionBackend, SerialBackend, ThreadedBackend, DistributedBackend, - GPUBackend, AutoBackend, AbstractThreadingBackend, AutoThreadingBackend export AbstractStructureFunction, StructureFunction, StructureFunctionSumsAndCounts, StructureFunction2DSumsAndCounts export StructureFunctionTensor, StructureFunctionTensorSumsAndCounts, HelmholtzDecomposition2D export LongitudinalSecondOrderStructureFunctionType, diff --git a/test/Project.toml b/test/Project.toml index b05bd1a..5441d72 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,4 +1,5 @@ [deps] +ComputationalBackends = "5c6e2104-4040-447f-8fc0-66ec2223b019" Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" diff --git a/test/mpi_rankscript.jl b/test/mpi_rankscript.jl index 91eaeb6..86e596e 100644 --- a/test/mpi_rankscript.jl +++ b/test/mpi_rankscript.jl @@ -1,30 +1,73 @@ -# Launched under mpiexec by test_mpi.jl. Each rank computes its share via MPIBackend; -# rank 0 compares the Allreduce'd result to a serial reference (identical seeded data on all -# ranks) and prints a marker the parent test greps for. -using MPI +# Launched under mpiexec by test_mpi.jl. Each rank computes its share via MPIBackend; rank 0 +# compares the Allreduce'd result to a serial reference (identical seeded data on all ranks) and +# prints a marker the parent test greps for. Covers every entry family and shape, with both a +# serial and a threaded inner backend. +using ComputationalBackends: ComputationalBackends as CB +using MPI: MPI MPI.Init() +using OhMyThreads: OhMyThreads using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, StructureFunctionObjects as SFO -using Random +using Random: Random comm = MPI.COMM_WORLD rank = MPI.Comm_rank(comm) sft = SFT.LongitudinalSecondOrderStructureFunctionType() + Random.seed!(123) # same data on every rank -N = 200 -x = rand(3, N); u = rand(3, N) +N, B = 120, 4 +x2 = rand(2, N); u2 = rand(2, N) +x3 = rand(3, N); u3 = rand(3, N) +ub = rand(2, N, B) # shared positions +xv = rand(2, N, B); uv = rand(2, N, B) # varying positions bins = collect(range(0.0, 1.5, 21)) +vbins = collect(range(-2.0, 2.0, 13)) + +# NaN marks an empty bin; two NaNs agree, a NaN opposite a number does not. +function same(a, b; rtol = 1e-8) + av, bv = vec(collect(a)), vec(collect(b)) + length(av) == length(bv) || return false + na, nb = isnan.(av), isnan.(bv) + na == nb || return false + keep = .!na + return isapprox(av[keep], bv[keep]; rtol = rtol) +end + +sc(o) = (o.sums, o.counts) +kw = (; verbose = false, show_progress = false) +raw = SFO.StructureFunctionSumsAndCounts + +function cases(be) + d = Dict{String, Any}() + d["pf1d_D2"] = sc(SFC.calculate_structure_function(sft, x2, u2, bins; backend = be, output_type = raw, kw...)) + d["pf1d_D3"] = sc(SFC.calculate_structure_function(sft, x3, u3, bins; backend = be, output_type = raw, kw...)) + d["pf2d"] = sc(SFC.calculate_structure_function(sft, x2, u2, bins, vbins; backend = be, kw...)) + d["batch1d_fixed"] = sc(SFC.calculate_structure_function(sft, x2, ub, bins; backend = be, output_type = raw, kw...)) + d["batch1d_vary"] = sc(SFC.calculate_structure_function(sft, xv, uv, bins; backend = be, output_type = raw, kw...)) + d["batch2d_fixed"] = sc(SFC.calculate_structure_function(sft, x2, ub, bins, vbins; backend = be, kw...)) + sp1 = SFC.calculate_structure_functions_single_pass(x2, u2, bins; backend = be) + d["sp1d"] = (sp1.S2.values, sp1.L1T2.values) + sp2 = SFC.calculate_structure_functions_single_pass_2d(x2, u2, bins, vbins; backend = be) + d["sp2d"] = (sp2.S2.sums, sp2.L1T2.sums) + sp1b = SFC.calculate_structure_functions_single_pass(x2, ub, bins; backend = be) + d["sp1d_batch"] = (sp1b.S2.values, sp1b.L1T2.values) + sp2b = SFC.calculate_structure_functions_single_pass_2d(x2, ub, bins, vbins; backend = be) + d["sp2d_batch"] = (sp2b.S2.sums, sp2b.L1T2.sums) + return d +end -res = SFC.calculate_structure_function( - sft, x, u, bins; backend = SFC.MPIBackend(), - verbose = false, show_progress = false, output_type = SFO.StructureFunctionSumsAndCounts, -) +inners = (("serial", CB.SerialBackend()), ("threaded", CB.ThreadedBackend())) +results = Dict(name => cases(CB.MPIBackend(inner)) for (name, inner) in inners) if rank == 0 - ref = SFC.calculate_structure_function( - sft, x, u, bins; backend = SFC.SerialBackend(), - verbose = false, show_progress = false, output_type = SFO.StructureFunctionSumsAndCounts, - ) - ok = ref.counts == res.counts && isapprox(ref.sums, res.sums; rtol = 1e-8) - println(ok ? "MPI_PARITY_OK np=$(MPI.Comm_size(comm))" : "MPI_PARITY_FAIL") + ref = cases(CB.SerialBackend()) + failures = String[] + for (iname, got) in results, k in sort!(collect(keys(ref))) + all(p -> same(p[1], p[2]), zip(ref[k], got[k])) || push!(failures, "$iname/$k") + end + if isempty(failures) + println("MPI_PARITY_OK np=$(MPI.Comm_size(comm)) nthreads=$(Threads.nthreads()) cases=$(length(ref) * length(inners))") + else + println("MPI_PARITY_FAIL: ", join(failures, ", ")) + end end -MPI.Finalize() +MPI.Finalize() \ No newline at end of file diff --git a/test/runtests.jl b/test/runtests.jl index 9d09d43..46c9752 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -35,6 +35,9 @@ Test.@testset "StructureFunctions.jl" begin println("--- Running Shape Contract Test ---") include("test_shape_contract.jl") + println("--- Running Spherical Geometry Test ---") + include("test_spherical_geometry.jl") + println("--- Running GPU Shape Contract Test ---") include("test_gpu_shape_contract.jl") @@ -47,6 +50,9 @@ Test.@testset "StructureFunctions.jl" begin println("--- Running Triangle Outer Chunks Test ---") include("test_triangle_outer_chunks.jl") + println("--- Running CPU Workspace Test ---") + include("test_cpu_workspace.jl") + # println("--- Running Performance Benchmark Test ---") # This need not run all the time, but it's here for reference # include("benchmark_performance.jl") @@ -70,6 +76,9 @@ Test.@testset "StructureFunctions.jl" begin println("--- Running GPU sp2d HTP-EJ Partitioned Test ---") include("test_gpu_sp2d_partitioned.jl") + println("--- Running GPU sp2d 3D Test ---") + include("test_gpu_sp2d_3d.jl") + println("--- Running GPU joint2d smem Test ---") include("test_gpu_joint2d_smem.jl") diff --git a/test/test_2d_binning.jl b/test/test_2d_binning.jl index 7584a66..0f13d14 100644 --- a/test/test_2d_binning.jl +++ b/test/test_2d_binning.jl @@ -1,5 +1,6 @@ module Test2DBinning +using ComputationalBackends: ComputationalBackends as CB using Test using Random using OhMyThreads @@ -36,7 +37,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins; output_type = SF.StructureFunctionSumsAndCounts, - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -48,7 +49,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins, l2_value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -79,7 +80,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins; output_type = SF.StructureFunctionSumsAndCounts, - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -91,7 +92,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins, l3_value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -114,7 +115,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins, l2_value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -125,7 +126,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins, l2_value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -142,7 +143,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins, l2_value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false ) @@ -153,7 +154,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, u_mat, distance_bins, l2_value_bins; - backend = SFC.ThreadedBackend(), + backend = CB.ThreadedBackend(), verbose = false, show_progress = false ) diff --git a/test/test_batch_matrix.jl b/test/test_batch_matrix.jl index c14d51e..81ba34f 100644 --- a/test/test_batch_matrix.jl +++ b/test/test_batch_matrix.jl @@ -1,4 +1,5 @@ # Parity matrix for production batch fast paths (KA.CPU). +using ComputationalBackends: ComputationalBackends as CB using Test using Random using KernelAbstractions: KernelAbstractions as KA @@ -13,8 +14,8 @@ using StructureFunctions.Calculations: Random.seed!(2025) const SF_TYPE = SFT.L2SFType() -const CPU_BE = SFC.SerialBackend() -const GPU_BE = SFC.GPUBackend(KA.CPU()) +const CPU_BE = CB.SerialBackend() +const GPU_BE = CB.GPUBackend(KA.CPU()) function _rand_batch_fixed(N::Int, B::Int) FT = Float32 diff --git a/test/test_bin_edges.jl b/test/test_bin_edges.jl index 1096856..a42dca8 100644 --- a/test/test_bin_edges.jl +++ b/test/test_bin_edges.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT using Test: Test using Distances: Distances as DI @@ -157,12 +158,12 @@ Test.@testset "BinEdges Tests" begin ref_lin = SFC.calculate_structure_function( sft, x, u, SF.LinearBinEdges(lin_range); - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, ) via_range = SFC.calculate_structure_function( sft, x, u, collect(lin_range); - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, ) Test.@test via_range.sums ≈ ref_lin.sums @@ -170,12 +171,12 @@ Test.@testset "BinEdges Tests" begin ref_log = SFC.calculate_structure_function( sft, x, u, SF.LogBinEdges(log_vec); - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, ) via_log_vec = SFC.calculate_structure_function( sft, x, u, log_vec; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, ) Test.@test via_log_vec.sums ≈ ref_log.sums diff --git a/test/test_core_correctness.jl b/test/test_core_correctness.jl index cfd39f7..f0daba7 100644 --- a/test/test_core_correctness.jl +++ b/test/test_core_correctness.jl @@ -1,6 +1,7 @@ using StructureFunctions: StructureFunctions as SF, StructureFunctionTypes as SFT, Calculations as SFC using Test: Test +using Random: Random using StaticArrays: StaticArrays as SA Test.@testset "Core Correctness - Block A" begin @@ -116,7 +117,8 @@ Test.@testset "Core Correctness - Block A" begin show_progress = false, )[1][1] == 0.0 - # Off-Diagonal Consistent Third Order (t^3): (-1)^3 = -1 + # Off-Diagonal Consistent Third Order (t^3): with the right-handed n̂ = ẑ × r̂ the transverse + # component is +1 here, so t^3 = +1 (it was -1 under the old clockwise n̂). Test.@test SFC.calculate_structure_function( SFT.OffDiagonalConsistentThirdOrderStructureFunction, x, @@ -124,7 +126,7 @@ Test.@testset "Core Correctness - Block A" begin bins; verbose = false, show_progress = false, - )[1][1] == -1.0 + )[1][1] == 1.0 # Off-Diagonal Inconsistent Third Order (l*t^2): 0 * (-1)^2 = 0 Test.@test SFC.calculate_structure_function( @@ -157,8 +159,21 @@ Test.@testset "Core Correctness - Block A" begin δu = SA.SVector(2.0, 3.0) r̂ = SA.SVector(1.0, 0.0) - Test.@test SFT.L2T1SF(δu, r̂) ≈ -12.0 - Test.@test SFT.T3SF(δu, r̂) ≈ -27.0 + # n̂ = ẑ × r̂ = (0, 1) is the right-handed quarter turn, so δu_T = +3. These two operators are + # the ONLY ones whose sign depends on that choice; every other operator consumes δu_T². + Test.@test SFT.L2T1SF(δu, r̂) ≈ 12.0 + Test.@test SFT.T3SF(δu, r̂) ≈ 27.0 + + # Orientation is a property of the convention, not of this fixture: rotating the pair must + # leave both invariant, and reflecting it must flip exactly these two. + θ = 0.7 + Rot = SA.SMatrix{2, 2}(cos(θ), sin(θ), -sin(θ), cos(θ)) + Test.@test SFT.L2T1SF(Rot * δu, Rot * r̂) ≈ SFT.L2T1SF(δu, r̂) + Test.@test SFT.T3SF(Rot * δu, Rot * r̂) ≈ SFT.T3SF(δu, r̂) + Flip = SA.SMatrix{2, 2}(1.0, 0.0, 0.0, -1.0) + Test.@test SFT.L2T1SF(Flip * δu, Flip * r̂) ≈ -SFT.L2T1SF(δu, r̂) + Test.@test SFT.T3SF(Flip * δu, Flip * r̂) ≈ -SFT.T3SF(δu, r̂) + Test.@test SFT.T2SF(Flip * δu, Flip * r̂) ≈ SFT.T2SF(δu, r̂) end end @@ -203,3 +218,62 @@ Test.@testset "Type Stability and Performance - Block C" begin ) end end + +# `count_eltype` defaults to UInt32 everywhere (device histograms are UInt32 for shared-memory +# reasons). Every pair can land in one bin, so past N = 92682 an unsigned counter wraps silently and +# `_bin_average` then divides by the wrapped value — a plausible, wrong mean. The bound is checked. +Test.@testset "Count element type must represent the worst-case pair count" begin + Test.@test SFC._assert_counts_representable(UInt32, 92682) === nothing # 4_294_930_821 pairs + Test.@test_throws ArgumentError SFC._assert_counts_representable(UInt32, 92683) + Test.@test SFC._assert_counts_representable(UInt64, 1_000_000) === nothing + Test.@test SFC._assert_counts_representable(Int64, 1_000_000) === nothing + + bins_of = collect(Float32, range(0.0f0, 2.0f0; length = 9)) + sft = SFT.L2SFType() + big_x = zeros(Float32, 2, 100_000) + + # Fires at the public boundary, before any O(N^2) work is done. + Test.@test_throws ArgumentError SFC.calculate_structure_function( + sft, big_x, big_x, bins_of; verbose = false, show_progress = false, + ) + # A caller-supplied counts buffer is validated on its own element type. + Test.@test_throws ArgumentError SFC.calculate_structure_function!( + zeros(Float32, 8), zeros(UInt32, 8), sft, big_x, big_x, bins_of; + verbose = false, show_progress = false, + ) + # Small problems are unaffected. + small_x = rand(Float32, 2, 64) + Test.@test SFC.calculate_structure_function( + sft, small_x, small_x, bins_of; verbose = false, show_progress = false, + ) isa Any +end + +# The auto-binning min/max scan covers unordered pairs once (`j > i`) and accumulates in the input +# eltype; both are silent if wrong — the bins would just come out slightly different. +Test.@testset "Auto-binning min/max scan" begin + Random.seed!(808) + for FT in (Float64, Float32) + x = rand(FT, 2, 250) .* FT(10) + mn, mx = SFC._minmax_matrix_for_autobins(x, SFC.DI.Euclidean(), false) + + # brute force over every unordered pair + bmn, bmx = FT(Inf), FT(0) + for i in 1:size(x, 2), j in (i + 1):size(x, 2) + d = sqrt((x[1, j] - x[1, i])^2 + (x[2, j] - x[2, i])^2) + bmn = min(bmn, d); bmx = max(bmx, d) + end + Test.@test mn ≈ bmn + Test.@test mx ≈ bmx + # Float64 seed literals here would silently widen the bin edges for Float32 input. + Test.@test typeof(mn) === FT + Test.@test typeof(mx) === FT + end + + # Auto-binned edges stay in the input precision end to end. + x32 = rand(Float32, 2, 200); u32 = randn(Float32, 2, 200) + r = SFC.calculate_structure_function( + SFT.L2SFType(), x32, u32, 12; verbose = false, show_progress = false, + ) + Test.@test eltype(r.distance) === Float32 + Test.@test eltype(r.values) === Float32 +end diff --git a/test/test_cpu_workspace.jl b/test/test_cpu_workspace.jl new file mode 100644 index 0000000..3fc2a0d --- /dev/null +++ b/test/test_cpu_workspace.jl @@ -0,0 +1,92 @@ +using Test +using Random: Random +using StructureFunctions: Calculations as SFC, StructureFunctionTypes as SFT, + LinearBinEdges, CPUSFWorkspace, reset_histogram! +using ComputationalBackends: ComputationalBackends as CB +using OhMyThreads: OhMyThreads + +Test.@testset "CPUSFWorkspace" begin + Random.seed!(4242) + N, B, nd, nv = 60, 8, 12, 10 + nt = Threads.nthreads() + x = rand(2, N) + u = rand(2, N, B) + db = LinearBinEdges(range(0.0, 2.0; length = nd + 1)) + vb = LinearBinEdges(range(-3.0, 3.0; length = nv + 1)) + sft = SFT.L2SFType() + backends = CB.ThreadedBackend[] + Threads.nthreads() > 1 && push!(backends, CB.ThreadedBackend()) + + @testset "results identical with and without a workspace" begin + for backend in (CB.SerialBackend(), backends...) + ws = CPUSFWorkspace{:single_pass_2d}(x, u, db, vb; backend) + s1 = zeros(Float64, 6, nd, nv, B); c1 = zeros(UInt32, 6, nd, nv, B) + s2 = zeros(Float64, 6, nd, nv, B); c2 = zeros(UInt32, 6, nd, nv, B) + SFC.calculate_structure_functions_single_pass_2d_batch!(s1, c1, x, u, db, vb; backend) + SFC.calculate_structure_functions_single_pass_2d_batch!(s2, c2, x, u, db, vb; backend, workspace = ws) + @test s1 == s2 + @test c1 == c2 + + ws1 = CPUSFWorkspace{:single_pass}(x, u, db; backend) + p1 = zeros(Float64, 6, nd, B); q1 = zeros(UInt32, 6, nd, B) + p2 = zeros(Float64, 6, nd, B); q2 = zeros(UInt32, 6, nd, B) + SFC.calculate_structure_functions_single_pass_batch!(p1, q1, x, u, db; backend) + SFC.calculate_structure_functions_single_pass_batch!(p2, q2, x, u, db; backend, workspace = ws1) + @test p1 == p2 + @test q1 == q2 + end + end + + @testset "reuse across calls is stable" begin + ws = CPUSFWorkspace{:single_pass_2d}(x, u, db, vb) + ref_s = zeros(Float64, 6, nd, nv, B); ref_c = zeros(UInt32, 6, nd, nv, B) + SFC.calculate_structure_functions_single_pass_2d_batch!( + ref_s, ref_c, x, u, db, vb; backend = CB.SerialBackend()) + for _ in 1:3 + s = zeros(Float64, 6, nd, nv, B); c = zeros(UInt32, 6, nd, nv, B) + SFC.calculate_structure_functions_single_pass_2d_batch!( + s, c, x, u, db, vb; backend = CB.SerialBackend(), workspace = ws) + @test s == ref_s + @test c == ref_c + end + end + + @testset "composes with BatchLeading (no transpose buffer)" begin + ubl = SFC.BatchLeading(permutedims(u, (3, 1, 2))) + ws = CPUSFWorkspace{:single_pass_2d}(x, ubl, db, vb) + @test length(ws.ub) == 0 + @test length(ws.xb) == 0 + s1 = zeros(Float64, 6, nd, nv, B); c1 = zeros(UInt32, 6, nd, nv, B) + s2 = zeros(Float64, 6, nd, nv, B); c2 = zeros(UInt32, 6, nd, nv, B) + SFC.calculate_structure_functions_single_pass_2d_batch!( + s1, c1, x, ubl, db, vb; backend = CB.SerialBackend()) + SFC.calculate_structure_functions_single_pass_2d_batch!( + s2, c2, x, ubl, db, vb; backend = CB.SerialBackend(), workspace = ws) + @test s1 == s2 + @test c1 == c2 + end + + @testset "a mismatched workspace is a hard error" begin + s = zeros(Float64, 6, nd, nv, B); c = zeros(UInt32, 6, nd, nv, B) + call!(ws) = SFC.calculate_structure_functions_single_pass_2d_batch!( + s, c, x, u, db, vb; backend = CB.SerialBackend(), workspace = ws) + + @test_throws ArgumentError call!(CPUSFWorkspace{:single_pass_2d}( + rand(2, N + 5), rand(2, N + 5, B), db, vb)) # wrong N + @test_throws ArgumentError call!(CPUSFWorkspace{:single_pass_2d}( + x, rand(2, N, B + 1), db, vb)) # wrong B + @test_throws ArgumentError call!(CPUSFWorkspace{:single_pass_2d}( + x, u, LinearBinEdges(range(0.0, 2.0; length = nd + 3)), vb)) # wrong n_bins + @test_throws ArgumentError call!(CPUSFWorkspace{:single_pass}(x, u, db)) # wrong kind + @test_throws ArgumentError CPUSFWorkspace{:nonsense}(x, u, db, vb) + end + + @testset "concretely typed" begin + ws = CPUSFWorkspace{:single_pass_2d}(x, u, db, vb) + T = typeof(ws) + @test isconcretetype(T) + @test all(isconcretetype, fieldtypes(T)) + @test reset_histogram!(ws) === ws + @test all(iszero, ws.result[1]) + end +end diff --git a/test/test_gpu_joint2d_smem.jl b/test/test_gpu_joint2d_smem.jl index f875b2b..3102a64 100644 --- a/test/test_gpu_joint2d_smem.jl +++ b/test/test_gpu_joint2d_smem.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: @@ -6,15 +7,15 @@ using StructureFunctions: joint2d_smem_max, joint2d_smem_exact, joint2d_smem_align256 using Random: Random -const GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) -GPUExt === nothing && error("StructureFunctionsGPUExt not loaded") +const GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) +GPUExt === nothing && error("StructureFunctionsKernelAbstractionsExt not loaded") Random.seed!(42) function _ref_joint(sft, x, u, dist, val) return SFC.calculate_structure_function( sft, x, u, dist, val; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) end diff --git a/test/test_gpu_script_hygiene.jl b/test/test_gpu_script_hygiene.jl index 4b18642..ad43773 100644 --- a/test/test_gpu_script_hygiene.jl +++ b/test/test_gpu_script_hygiene.jl @@ -19,7 +19,7 @@ end Test.@testset "GPU script hygiene" begin repo = normpath(joinpath(@__DIR__, "..")) paths = [ - joinpath(repo, "ext", "StructureFunctionsGPUExt.jl"), + joinpath(repo, "ext", "StructureFunctionsKernelAbstractionsExt.jl"), joinpath(repo, "ext", "gpu"), joinpath(repo, "gpu"), joinpath(repo, "benchmark"), diff --git a/test/test_gpu_shape_contract.jl b/test/test_gpu_shape_contract.jl index 9ac0cf9..29b3594 100644 --- a/test/test_gpu_shape_contract.jl +++ b/test/test_gpu_shape_contract.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test using Random using KernelAbstractions: KernelAbstractions as KA @@ -6,11 +7,12 @@ using StructureFunctions: StructureFunctionTypes as SFT, StructureFunctionObjects as SFO, batch_histograms_equal +using Distances: Distances as DI Random.seed!(20260621) -const GPU_SHAPE_BE = SFC.GPUBackend(KA.CPU()) -const GPU_SHAPE_CPU_BE = SFC.SerialBackend() +const GPU_SHAPE_BE = CB.GPUBackend(KA.CPU()) +const GPU_SHAPE_CPU_BE = CB.SerialBackend() function _gpu_shape_pairwise(sf, x, u, bins) return SFC.calculate_structure_function( @@ -146,3 +148,143 @@ end ) end end + +# Every GPU kernel family carries the geometry, so a non-Euclidean metric produces the transported +# answer on GPU exactly as on CPU — the two must agree, and neither may silently return a flat one. +Test.@testset "GPU point-field families honour a spherical metric" begin + FT = Float64 + N = 64 + R = 6.371e6 + m = DI.Haversine(R) + sft = SFT.L2SFType() + lon = 300 .* rand(N) .- 150 + lat = 100 .* rand(N) .- 50 + x = permutedims(hcat(lon, lat)) + u = permutedims(hcat(randn(N), randn(N))) + db = collect(FT, range(0.0, 9.0e6; length = 11)) + vb = collect(FT, range(-4.0, 4.0; length = 9)) + kw = (; verbose = false, show_progress = false, distance_metric = m) + + for (name, call) in ( + ("sf1d", (be,) -> SFC.calculate_structure_function( + sft, x, u, db; backend = be, output_type = SFO.StructureFunctionSumsAndCounts, kw...)), + ("joint2d", (be,) -> SFC.calculate_structure_function( + sft, x, u, db, vb; backend = be, kw...)), + ("sp1d", (be,) -> SFC.calculate_structure_functions_single_pass( + x, u, db; backend = be, output_type = SFO.StructureFunctionSumsAndCounts, + distance_metric = m)), + ("sp2d", (be,) -> SFC.calculate_structure_functions_single_pass_2d( + x, u, db, vb; backend = be, distance_metric = m)), + ) + g = call(GPU_SHAPE_BE); c = call(GPU_SHAPE_CPU_BE) + if g isa NamedTuple + for k in keys(c) + k === :helmholtz && continue + Test.@test g[k].counts == c[k].counts + Test.@test isapprox(g[k].sums, c[k].sums; rtol = 1e-8) + end + else + Test.@test g.counts == c.counts + Test.@test isapprox(g.sums, c.sums; rtol = 1e-8) + end + end + + # The metric genuinely changes the answer: the transported result is not the flat one. + raw(mm) = SFC.calculate_structure_function( + sft, x, u, db; backend = CB.SerialBackend(), verbose = false, show_progress = false, + distance_metric = mm, output_type = SFO.StructureFunctionSumsAndCounts, + ) + Test.@test raw(DI.Euclidean()).counts != raw(m).counts + + # And a metric with NO geometry is refused outright on every backend rather than being assumed + # flat — a distance function does not define a separation direction or a transport rule. + Test.@test_throws ArgumentError raw(DI.Cityblock()) +end + +# The auxiliary-axis (batch) families carry the geometry into their kernels, so they honour a +# spherical metric and must reproduce the CPU's transported answer rather than a flat one. +Test.@testset "GPU batch families honour a spherical metric" begin + FT = Float64 + N, B = 40, 3 + R = 6.371e6 + m = DI.Haversine(R) + lon = 300 .* rand(N) .- 150 + lat = 100 .* rand(N) .- 50 + x = permutedims(hcat(lon, lat)) + u3 = reshape(randn(FT, 2, N, B), 2, N, B) + db = collect(FT, range(0.0, 9.0e6; length = 11)) + vb = collect(FT, range(-4.0, 4.0; length = 9)) + sft = SFT.L2SFType() + kw = (; verbose = false, show_progress = false, distance_metric = m) + + for (name, call) in ( + ("sf1d batch", (be,) -> SFC.calculate_structure_function( + sft, x, u3, db; backend = be, output_type = SFO.StructureFunctionSumsAndCounts, kw...)), + ("sp1d batch", (be,) -> SFC.calculate_structure_functions_single_pass( + x, u3, db; backend = be, output_type = SFO.StructureFunctionSumsAndCounts, kw...)), + ("sp2d batch", (be,) -> SFC.calculate_structure_functions_single_pass_2d( + x, u3, db, vb; backend = be, kw...)), + ) + g = call(GPU_SHAPE_BE); c = call(GPU_SHAPE_CPU_BE) + if g isa NamedTuple + for k in keys(c) + k === :helmholtz && continue + Test.@test g[k].counts == c[k].counts + Test.@test isapprox(g[k].sums, c[k].sums; rtol = 1e-8) + end + else + Test.@test g.counts == c.counts + Test.@test isapprox(g.sums, c.sums; rtol = 1e-8) + end + end +end + +# The point-field single-pass 2D family carries the geometry into its kernels, so it honors a +# non-Euclidean metric rather than refusing it, and must produce the CPU's transported answer. +Test.@testset "GPU single-pass 2D honors a spherical metric" begin + FT = Float64 + N = 96 + lon = 300 .* rand(N) .- 150 + lat = 100 .* rand(N) .- 50 + x = permutedims(hcat(lon, lat)) + u = permutedims(hcat(randn(N), randn(N))) + db = collect(FT, range(0.0, 9.0e6; length = 11)) + vbn = collect(FT, range(-4.0, 4.0; length = 9)) + m = DI.Haversine(6.371e6) + + got = SFC.calculate_structure_functions_single_pass_2d( + x, u, db, vbn; backend = GPU_SHAPE_BE, distance_metric = m, + ) + ref = SFC.calculate_structure_functions_single_pass_2d( + x, u, db, vbn; backend = GPU_SHAPE_CPU_BE, distance_metric = m, + ) + for k in (:S2, :L2, :T2, :S3, :L3, :L1T2) + Test.@test got[k].counts == ref[k].counts + Test.@test isapprox(got[k].sums, ref[k].sums; rtol = 1e-10) + end + + # The metric genuinely changes the result: the transported answer is not the flat one. + flat = SFC.calculate_structure_functions_single_pass_2d( + x, u, db, vbn; backend = GPU_SHAPE_BE, distance_metric = DI.Euclidean(), + ) + Test.@test flat.L2.counts != got.L2.counts +end + +# The single-pass 2D GPU boundary used to splat display-only kwargs into a core with no `kwargs...` +# sink, so the package's own standard `verbose`/`show_progress` pair was a MethodError. +Test.@testset "GPU single-pass 2D accepts the standard display kwargs" begin + FT = Float64 + N = 16 + x, u = rand(FT, 2, N), rand(FT, 2, N) + db = collect(FT, range(0.0, 2.0; length = 9)) + vb = collect(FT, range(-2.0, 2.0; length = 7)) + ref = SFC.calculate_structure_functions_single_pass_2d(x, u, db, vb; backend = GPU_SHAPE_BE) + got = SFC.calculate_structure_functions_single_pass_2d( + x, u, db, vb; backend = GPU_SHAPE_BE, verbose = false, show_progress = false, + ) + Test.@test keys(got) == keys(ref) + for k in keys(ref) + Test.@test got[k].counts == ref[k].counts + Test.@test got[k].sums ≈ ref[k].sums + end +end diff --git a/test/test_gpu_single_pass_tiled.jl b/test/test_gpu_single_pass_tiled.jl index 14de5d6..2fbbfa9 100644 --- a/test/test_gpu_single_pass_tiled.jl +++ b/test/test_gpu_single_pass_tiled.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: StructureFunctions as SF, Calculations as SFC @@ -21,7 +22,7 @@ Test.@testset "GPU single-pass tiled parity — 1D log bins" begin sums_cpu = zeros(FT, 6, length(dist_vec) - 1) counts_cpu = zeros(Int32, 6, length(dist_vec) - 1) SFC.calculate_structure_functions_single_pass!( - sums_cpu, counts_cpu, x, u, dist_vec; backend = SFC.SerialBackend(), + sums_cpu, counts_cpu, x, u, dist_vec; backend = CB.SerialBackend(), ) sums_gpu = zeros(FT, 6, length(dist_vec) - 1) @@ -29,7 +30,7 @@ Test.@testset "GPU single-pass tiled parity — 1D log bins" begin ws = SFC.GPUSFWorkspace(KA.CPU(), dist_vec; kind = :single_pass) SFC.calculate_structure_functions_single_pass!( sums_gpu, counts_gpu, x, u, dist_vec; - backend = SF.GPUBackend(KA.CPU()), workspace = ws, + backend = CB.GPUBackend(KA.CPU()), workspace = ws, ) Test.@test sums_gpu ≈ sums_cpu rtol = FT(1e-4) @@ -50,7 +51,7 @@ Test.@testset "GPU single-pass tiled parity — 2D log dist + linear value" begi counts_cpu = zeros(Int32, 6, n_dist, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_cpu, counts_cpu, x, u, dist_vec, value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) sums_gpu = zeros(FT, 6, n_dist, n_val) @@ -58,7 +59,7 @@ Test.@testset "GPU single-pass tiled parity — 2D log dist + linear value" begi ws = SFC.GPUSFWorkspace(KA.CPU(), dist_vec, value_bins; kind = :single_pass_2d) SFC.calculate_structure_functions_single_pass_2d!( sums_gpu, counts_gpu, x, u, dist_vec, value_bins; - backend = SF.GPUBackend(KA.CPU()), workspace = ws, + backend = CB.GPUBackend(KA.CPU()), workspace = ws, ) Test.@test sums_gpu ≈ sums_cpu rtol = FT(1e-4) @@ -79,7 +80,7 @@ Test.@testset "GPU single-pass tiled parity — 2D InfPadded linear value catch- counts_cpu = zeros(Int32, 6, n_dist, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_cpu, counts_cpu, x, u, dist_vec, value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) sums_gpu = zeros(FT, 6, n_dist, n_val) @@ -87,7 +88,7 @@ Test.@testset "GPU single-pass tiled parity — 2D InfPadded linear value catch- ws = SFC.GPUSFWorkspace(KA.CPU(), dist_vec, value_bins; kind = :single_pass_2d, n_val = n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_gpu, counts_gpu, x, u, dist_vec, value_bins; - backend = SF.GPUBackend(KA.CPU()), workspace = ws, + backend = CB.GPUBackend(KA.CPU()), workspace = ws, ) Test.@test sums_gpu ≈ sums_cpu rtol = FT(1e-4) @@ -96,7 +97,7 @@ end Test.@testset "GPU single-pass global fallback parity — 2D and 3D" begin FT = Float32 - backend = SF.GPUBackend(KA.CPU()) + backend = CB.GPUBackend(KA.CPU()) for D in (2, 3) N = 18 @@ -115,7 +116,7 @@ Test.@testset "GPU single-pass global fallback parity — 2D and 3D" begin inv = (:S2, :L2, :T2, :S3, :L3, :L1T2) for bins in bin_sets sp_cpu = SFC.calculate_structure_functions_single_pass( - x, u, bins; backend = SFC.SerialBackend(), + x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) sp_gpu = SFC.calculate_structure_functions_single_pass( @@ -131,7 +132,7 @@ end Test.@testset "GPU single-pass 2D global fallback parity" begin FT = Float32 - backend = SF.GPUBackend(KA.CPU()) + backend = CB.GPUBackend(KA.CPU()) N = 16 x = rand(FT, 2, N) u = rand(FT, 2, N) @@ -149,14 +150,16 @@ Test.@testset "GPU single-pass 2D global fallback parity" begin inv = (:S2, :L2, :T2, :S3, :L3, :L1T2) for bins in bin_sets sp_cpu = SFC.calculate_structure_functions_single_pass_2d( - x, u, bins, value_bins; backend = SFC.SerialBackend(), + x, u, bins, value_bins; backend = CB.SerialBackend(), ) - sp_gpu = SFC.calculate_structure_functions_single_pass_2d( - x, u, bins, value_bins; backend, force_global_atomic = true, + # `force_global_atomic` is a GPU routing override, so it goes to the GPU entry rather + # than the backend-generic one, which would have to ignore it on a CPU backend. + gs, gc = SFC.gpu_calculate_structure_functions_single_pass_2d( + backend.backend, x, u, bins, value_bins; force_global_atomic = true, ) - for k in inv - Test.@test sp_gpu[k].counts == sp_cpu[k].counts - Test.@test sp_gpu[k].sums ≈ sp_cpu[k].sums atol = FT(1e-4) + for (t, k) in enumerate(inv) + Test.@test gc[t, :, :] == sp_cpu[k].counts + Test.@test gs[t, :, :] ≈ sp_cpu[k].sums atol = FT(1e-4) end end end diff --git a/test/test_gpu_sp2d_3d.jl b/test/test_gpu_sp2d_3d.jl new file mode 100644 index 0000000..0f8c9d5 --- /dev/null +++ b/test/test_gpu_sp2d_3d.jl @@ -0,0 +1,70 @@ +using Test +using Random: Random +using KernelAbstractions: KernelAbstractions as KA +using StructureFunctions: Calculations as SFC, LinearBinEdges, LogBinEdges + +# D = 3 single-pass 2D on the tiled shared-histogram path. Before this was supported, D = 3 fell +# through to the global-atomic kernel with the general binary-search value plan and ran ~38x slower +# (383 ms vs 10 ms at N=20000, 32x16, A100). The tiled kernel is dimension-generic because the six +# invariants need only du_L and |du_T|² = |du|² - du_L², which requires no transverse basis vector. +Test.@testset "GPU single-pass 2D, D = 3" begin + Random.seed!(20260816) + backend = KA.CPU() + FT = Float32 + + @testset "matches the CPU reference for D = $D, $(nd)x$(nv) bins" for D in (2, 3), + (nd, nv) in ((16, 8), (24, 12)) + N = 256 + x = rand(FT, D, N) + u = rand(FT, D, N) + db = LinearBinEdges(range(FT(0), FT(1.5); length = nd + 1)) + vb = LinearBinEdges(range(FT(-1), FT(2); length = nv + 1)) + + gs, gc = SFC.gpu_calculate_structure_functions_single_pass_2d(backend, x, u, db, vb) + cs = zeros(FT, 6, nd, nv) + cc = zeros(UInt32, 6, nd, nv) + SFC._accumulate_single_pass_2d!(cs, cc, x, u, db, vb) + + # Total counts are conserved exactly — no pair may be dropped or double-counted. Individual + # cells may differ by one where a pair sits within an ulp of a bin edge and GPU FMA rounds + # the other way; a systematic difference would be a real bug, a few boundary pairs are not. + gcm, ccm = Array(gc), cc + @test sum(Int.(gcm)) == sum(Int.(ccm)) + @test maximum(abs.(Int.(gcm) .- Int.(ccm))) <= 1 + @test count(gcm .!= ccm) <= max(4, length(ccm) ÷ 100) + @test isapprox(Array(gs), cs; rtol = 1e-4) + end + + @testset "log distance bins, D = 3" begin + N, nd, nv = 256, 16, 8 + x = rand(FT, 3, N) .+ FT(0.5) + u = rand(FT, 3, N) + db = LogBinEdges(FT.(10 .^ range(-1.5, 0.3; length = nd + 1))) + vb = LinearBinEdges(range(FT(-1), FT(2); length = nv + 1)) + + gs, gc = SFC.gpu_calculate_structure_functions_single_pass_2d(backend, x, u, db, vb) + cs = zeros(FT, 6, nd, nv) + cc = zeros(UInt32, 6, nd, nv) + SFC._accumulate_single_pass_2d!(cs, cc, x, u, db, vb) + gcm = Array(gc) + @test sum(Int.(gcm)) == sum(Int.(cc)) + @test maximum(abs.(Int.(gcm) .- Int.(cc))) <= 1 + @test isapprox(Array(gs), cs; rtol = 1e-4) + end + + @testset "workspace reuse is stable in 3D" begin + N, nd, nv = 256, 16, 8 + x = rand(FT, 3, N) + u = rand(FT, 3, N) + db = LinearBinEdges(range(FT(0), FT(1.5); length = nd + 1)) + vb = LinearBinEdges(range(FT(-1), FT(2); length = nv + 1)) + ws = SFC.GPUSFWorkspace(backend, db, vb; kind = :single_pass_2d) + ref_s, ref_c = SFC.gpu_calculate_structure_functions_single_pass_2d(backend, x, u, db, vb) + for _ in 1:3 + gs, gc = SFC.gpu_calculate_structure_functions_single_pass_2d( + backend, x, u, db, vb; workspace = ws) + @test Array(gc) == Array(ref_c) + @test Array(gs) ≈ Array(ref_s) + end + end +end diff --git a/test/test_gpu_sp2d_partitioned.jl b/test/test_gpu_sp2d_partitioned.jl index c6bc198..aeac1be 100644 --- a/test/test_gpu_sp2d_partitioned.jl +++ b/test/test_gpu_sp2d_partitioned.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: @@ -80,7 +81,7 @@ Test.@testset "GPU sp2d HTP-EJ partitioned (KA.CPU)" begin cnts_lin_ref = zeros(UInt32, 6, NB, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_lin_ref, cnts_lin_ref, x, u, linear_dist, value_bins_ntuple; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) for (db, sums_ref, cnts_ref) in ( (linear_dist, sums_lin_ref, cnts_lin_ref), @@ -89,7 +90,7 @@ Test.@testset "GPU sp2d HTP-EJ partitioned (KA.CPU)" begin cr = zeros(UInt32, 6, length(log_dist) - 1, n_val) SFC.calculate_structure_functions_single_pass_2d!( sr, cr, x, u, log_dist, value_bins_ntuple; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) (log_dist, sr, cr) end, @@ -98,7 +99,7 @@ Test.@testset "GPU sp2d HTP-EJ partitioned (KA.CPU)" begin cnts_gpu = zeros(UInt32, size(cnts_ref)...) SFC.calculate_structure_functions_single_pass_2d!( sums_gpu, cnts_gpu, x, u, db, value_bins_ntuple; - backend = SFC.GPUBackend(backend), + backend = CB.GPUBackend(backend), ) Test.@test sums_gpu ≈ sums_ref atol = 1e-11 Test.@test cnts_gpu == cnts_ref @@ -121,14 +122,14 @@ Test.@testset "GPU sp2d HTP-EJ partitioned (KA.CPU)" begin cnts_ref = zeros(UInt32, 6, n_log, n_val_inf) SFC.calculate_structure_functions_single_pass_2d!( sums_ref, cnts_ref, x, u, log_dist, inf_val; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) sums_gpu = zeros(FT, 6, n_log, n_val_inf) cnts_gpu = zeros(UInt32, 6, n_log, n_val_inf) ws_inf = SFC.GPUSFWorkspace(backend, log_dist, inf_val; kind = :single_pass_2d) SFC.calculate_structure_functions_single_pass_2d!( sums_gpu, cnts_gpu, x, u, log_dist, inf_val; - backend = SFC.GPUBackend(backend), workspace = ws_inf, + backend = CB.GPUBackend(backend), workspace = ws_inf, ) Test.@test sums_gpu ≈ sums_ref atol = 1e-11 Test.@test cnts_gpu == cnts_ref @@ -138,7 +139,7 @@ Test.@testset "GPU sp2d HTP-EJ partitioned (KA.CPU)" begin cnts_ws = zeros(UInt32, 6, NB, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_ws, cnts_ws, x, u, linear_dist, value_bins_ntuple; - backend = SFC.GPUBackend(backend), workspace = ws2, + backend = CB.GPUBackend(backend), workspace = ws2, ) Test.@test sums_ws ≈ sums_lin_ref atol = 1e-11 Test.@test cnts_ws == cnts_lin_ref @@ -162,7 +163,7 @@ Test.@testset "GPU sp2d merge kernels (KA.CPU)" begin ref_s[t, d, v] += partition_sums[t, d, v, b] ref_c[t, d, v] += partition_counts[t, d, v, b] end - GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) + GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) for mode in (:serial, :parallel) fill!(out_s, 0) fill!(out_c, 0) @@ -194,7 +195,7 @@ Test.@testset "GPU sp2d typeplane mode (KA.CPU)" begin cnts_ref = zeros(UInt32, 6, NB, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_ref, cnts_ref, x, u, linear_dist, value_bins_ntuple; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) ws = SFC.GPUSFWorkspace(backend, linear_dist, value_bins_ntuple) Test.@test ws.sp2d_accumulation_strategy.accum_mode == :typeplane @@ -237,7 +238,7 @@ Test.@testset "GPU sp2d typeplane production shape log+infpadded (KA.CPU)" begin cnts_ref = zeros(UInt32, 6, n_dist_bins, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_ref, cnts_ref, x, u, log_dist, inf_val; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) ws = SFC.GPUSFWorkspace(backend, log_dist, inf_val; kind = :single_pass_2d) @@ -247,7 +248,7 @@ Test.@testset "GPU sp2d typeplane production shape log+infpadded (KA.CPU)" begin cnts_gpu = zeros(UInt32, 6, n_dist_bins, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_gpu, cnts_gpu, x, u, log_dist, inf_val; - backend = SFC.GPUBackend(backend), workspace = ws, + backend = CB.GPUBackend(backend), workspace = ws, ) Test.@test sums_gpu ≈ sums_ref rtol = 1e-5 atol = 1e-6 Test.@test cnts_gpu == cnts_ref @@ -273,7 +274,7 @@ Test.@testset "GPU sp2d direct mode (KA.CPU)" begin cnts_ref = zeros(UInt32, 6, NB, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_ref, cnts_ref, x, u, linear_dist, value_bins_ntuple; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) ws = SFC.GPUSFWorkspace(backend, linear_dist, value_bins_ntuple) Test.@test ws.sp2d_accumulation_strategy.accum_mode == :direct @@ -289,6 +290,77 @@ Test.@testset "GPU sp2d direct mode (KA.CPU)" begin Test.@test ws.partition_sums_dev !== nothing end +Test.@testset "GPU sp2d general distance edges take the tiled path (KA.CPU)" begin + # Arbitrary (neither uniform nor log-uniform) distance edges digitize by device binary + # search. Before the :general route existed these fell through to the global-atomic + # kernel; the tiled shared-histogram path must agree with the CPU reference for every + # combination of value-bin form and dimensionality it now covers. + backend = KA.CPU() + FT = Float32 + N, nd, nv = 96, 16, 8 + # r^1.7 on a uniform grid: strictly increasing, and neither spacing family matches it. + dist_edges = collect(FT, range(FT(0), FT(1.5); length = nd + 1)) .^ FT(1.7) + GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) + Test.@test GPUExt._sp2d_dist_variant(dist_edges) == :general + + typed_val = LinearBinEdges(range(FT(-1), FT(2); length = nv + 1)) + raw_val = collect(FT, range(FT(-1), FT(2); length = nv + 1)) + inf_val = InfPaddedBinEdges(LinearBinEdges(range(FT(-0.5), FT(1.5); length = nv - 1))) + + Test.@testset "D = $D, $vname value bins" for D in (2, 3), + (vname, vb) in ( + ("typed", typed_val), ("raw", raw_val), ("infpadded", inf_val)) + Random.seed!(20260816 + D) + x = rand(FT, D, N) + u = rand(FT, D, N) + n_val = length(vb) - 1 + sums_ref = zeros(FT, 6, nd, n_val) + cnts_ref = zeros(UInt32, 6, nd, n_val) + SFC.calculate_structure_functions_single_pass_2d!( + sums_ref, cnts_ref, x, u, dist_edges, vb; backend = CB.SerialBackend(), + ) + + ws = SFC.GPUSFWorkspace(backend, dist_edges, vb; kind = :single_pass_2d) + sums_gpu = zeros(FT, 6, nd, n_val) + cnts_gpu = zeros(UInt32, 6, nd, n_val) + SFC.calculate_structure_functions_single_pass_2d!( + sums_gpu, cnts_gpu, x, u, dist_edges, vb; + backend = CB.GPUBackend(backend), workspace = ws, + ) + # A resolved pair kernel is what distinguishes the tiled route from the fallback. + Test.@test ws.sp2d_pair_kernel !== nothing + Test.@test cnts_gpu == cnts_ref + Test.@test sums_gpu ≈ sums_ref rtol = 1e-5 atol = 1e-6 + end +end + +Test.@testset "GPU sp2d keeps data precision when bins are narrower (KA.CPU)" begin + # The tiled kernel carries two element types: the coordinate tiles follow the data, the + # shared histogram follows the output. Binding both from the bin scalars instead would + # round Float64 coordinates to Float32 here, losing ~7 digits with nothing to show for it. + backend = KA.CPU() + N, nd, nv = 64, 10, 8 + Random.seed!(20260816) + x = rand(Float64, 2, N) + u = rand(Float64, 2, N) + db = LinearBinEdges(range(Float32(0), Float32(1.5); length = nd + 1)) + vb = _synthetic_value_bins_ntuple(nv, Float32) + + sums_ref = zeros(Float64, 6, nd, nv) + cnts_ref = zeros(UInt32, 6, nd, nv) + SFC.calculate_structure_functions_single_pass_2d!( + sums_ref, cnts_ref, x, u, db, vb; backend = CB.SerialBackend(), + ) + sums_gpu = zeros(Float64, 6, nd, nv) + cnts_gpu = zeros(UInt32, 6, nd, nv) + SFC.calculate_structure_functions_single_pass_2d!( + sums_gpu, cnts_gpu, x, u, db, vb; backend = CB.GPUBackend(backend), + ) + Test.@test cnts_gpu == cnts_ref + # Float32 tiles would land near 1e-7 here; full Float64 throughout is orders tighter. + Test.@test sums_gpu ≈ sums_ref rtol = 1e-12 +end + Test.@testset "GPU batch entry points accept log distance bins (KA.CPU)" begin # The GPU batch entry points route through the unified device path, whose # _sf_batch_dist_digitizer handles linear, log, and general edges. Guard @@ -316,14 +388,14 @@ Test.@testset "GPU batch entry points accept log distance bins (KA.CPU)" begin SFC.calculate_structure_functions_single_pass_2d!( view(sums_ref, :, :, :, t), view(cnts_ref, :, :, :, t), x[:, :, t], u[:, :, t], log_dist, inf_val; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) end sums_gpu = zeros(FT, 6, n_dist_bins, n_val, T) cnts_gpu = zeros(UInt32, 6, n_dist_bins, n_val, T) SFC.calculate_structure_functions_single_pass_2d_batch!( sums_gpu, cnts_gpu, x, u, log_dist, inf_val; - backend = SFC.GPUBackend(backend), + backend = CB.GPUBackend(backend), ) Test.@test sums_gpu ≈ sums_ref rtol = 1e-5 atol = 1e-6 Test.@test cnts_gpu == cnts_ref @@ -332,12 +404,12 @@ Test.@testset "GPU batch entry points accept log distance bins (KA.CPU)" begin sums1_ref = zeros(FT, 6, n_dist_bins, T) cnts1_ref = zeros(UInt32, 6, n_dist_bins, T) SFC.calculate_structure_functions_single_pass_batch!( - sums1_ref, cnts1_ref, x, u, log_dist; backend = SFC.SerialBackend(), + sums1_ref, cnts1_ref, x, u, log_dist; backend = CB.SerialBackend(), ) sums1_gpu = zeros(FT, 6, n_dist_bins, T) cnts1_gpu = zeros(UInt32, 6, n_dist_bins, T) SFC.calculate_structure_functions_single_pass_batch!( - sums1_gpu, cnts1_gpu, x, u, log_dist; backend = SFC.GPUBackend(backend), + sums1_gpu, cnts1_gpu, x, u, log_dist; backend = CB.GPUBackend(backend), ) Test.@test sums1_gpu ≈ sums1_ref rtol = 1e-5 atol = 1e-6 Test.@test cnts1_gpu == cnts1_ref @@ -347,19 +419,19 @@ Test.@testset "GPU batch entry points accept log distance bins (KA.CPU)" begin sumsi_ref = zeros(FT, n_dist_bins, T) cntsi_ref = zeros(UInt32, n_dist_bins, T) SFC.calculate_structure_function_batch!( - sumsi_ref, cntsi_ref, sf_type, x, u, log_dist; backend = SFC.SerialBackend(), + sumsi_ref, cntsi_ref, sf_type, x, u, log_dist; backend = CB.SerialBackend(), ) sumsi_gpu = zeros(FT, n_dist_bins, T) cntsi_gpu = zeros(UInt32, n_dist_bins, T) SFC.calculate_structure_function_batch!( - sumsi_gpu, cntsi_gpu, sf_type, x, u, log_dist; backend = SFC.GPUBackend(backend), + sumsi_gpu, cntsi_gpu, sf_type, x, u, log_dist; backend = CB.GPUBackend(backend), ) Test.@test sumsi_gpu ≈ sumsi_ref rtol = 1e-5 atol = 1e-6 Test.@test cntsi_gpu == cntsi_ref # Typed FMA fast-path routing: linear AND log qualify (same 5-param FMA # digitize, log in log space); raw vectors take the exact general digitizer. - GPUExt = Base.get_extension(SF, :StructureFunctionsGPUExt) + GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) Test.@test GPUExt._fma_distance_bins(log_dist) === log_dist lin = LinearBinEdges(range(FT(0.0), FT(1.5); length = n_dist_bins + 1)) Test.@test GPUExt._fma_distance_bins(lin) === lin @@ -370,9 +442,62 @@ Test.@testset "GPU batch entry points accept log distance bins (KA.CPU)" begin sumsf_ref = zeros(FT, n_dist_bins, T) cntsf_ref = zeros(UInt32, n_dist_bins, T) SFC.calculate_structure_function_batch!( - sumsf_ref, cntsf_ref, sf_type, x_fixed, u, log_dist; backend = SFC.SerialBackend(), + sumsf_ref, cntsf_ref, sf_type, x_fixed, u, log_dist; backend = CB.SerialBackend(), ) res = SFC.gpu_calculate_structure_function_batch(sf_type, backend, x_fixed, u, log_dist) Test.@test res.sums ≈ sumsf_ref rtol = 1e-5 atol = 1e-6 Test.@test res.counts == cntsf_ref end + +# Large 2D bin counts. Before these existed, nothing in the suite went past 60×60 on either axis, +# which is why two defects lived here unnoticed: SP2D threw outright for any `n_dist > 128` (the +# naive global-atomic route demanded a value-edge workspace that nothing supplies by default), and +# the `:direct` strategy was chosen over plain global atomics well past the point where it loses +# 2–4× (see `gpu/SPEED_OF_LIGHT.md`). Float64 because Float32 carries only ~7 digits and a histogram +# this sparse (few pairs per cell, cancelling odd moments) disagrees with a Float64 reference by +# percent even on the CPU — a Float32 assertion here would be testing arithmetic, not the kernel. +Test.@testset "GPU sp2d large bin counts (KA.CPU)" begin + backend = KA.CPU() + FT = Float64 + N = 64 + x = rand(FT, 2, N) + u = randn(FT, 2, N) + for (nd, nv) in ((100, 100), (200, 200)) + dist = LinearBinEdges(range(FT(0), FT(1); length = nd + 1)) + val = _synthetic_value_bins_ntuple(nv, FT) + sums_ref = zeros(FT, 6, nd, nv) + cnts_ref = zeros(UInt32, 6, nd, nv) + SFC.calculate_structure_functions_single_pass_2d!( + sums_ref, cnts_ref, x, u, dist, val; backend = CB.SerialBackend(), + ) + sums_gpu = zeros(FT, 6, nd, nv) + cnts_gpu = zeros(UInt32, 6, nd, nv) + # No workspace: the path that used to raise `ArgumentError` here. + SFC.calculate_structure_functions_single_pass_2d!( + sums_gpu, cnts_gpu, x, u, dist, val; backend = CB.GPUBackend(backend), + ) + Test.@test cnts_gpu == cnts_ref + Test.@test sums_gpu ≈ sums_ref rtol = 1e-10 atol = 1e-12 + end +end + +# The routing decision itself, not just the numbers a route produces. Every SP2D defect found so far +# was a *routing* fault that correctness assertions could not see, because each route computes the +# right answer — just at very different speeds. +Test.@testset "GPU sp2d strategy routing thresholds" begin + ext = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) + Test.@test ext !== nothing + cells_bytes(nd, nv, ::Type{FT}) where {FT} = 6 * nd * nv * (sizeof(FT) + sizeof(UInt32)) + # Small histograms stay on chip; large ones must not select `:direct`, which loses to plain + # global atomics above the measured crossover. + Test.@test cells_bytes(60, 60, Float64) <= ext.SP2D_GLOBAL_ATOMIC_HIST_BYTES + Test.@test cells_bytes(100, 100, Float64) > ext.SP2D_GLOBAL_ATOMIC_HIST_BYTES + Test.@test cells_bytes(128, 128, Float32) > ext.SP2D_GLOBAL_ATOMIC_HIST_BYTES + # 80×80 Float32 (307 KB) measured `:direct` still ahead by ~11%; it must stay below the cut. + Test.@test cells_bytes(80, 80, Float32) <= ext.SP2D_GLOBAL_ATOMIC_HIST_BYTES + for (nd, nv, FT) in ((16, 8, Float32), (60, 60, Float64), (100, 100, Float64)) + cfg = ext._sp2d_accumulation_strategy(nd, nv, FT, SFC.gpu_device_caps(nothing)) + Test.@test cfg.accum_mode in (:shared, :typeplane, :direct) + Test.@test cfg.n_joint_cells == 6 * nd * nv + end +end diff --git a/test/test_gpu_tiled_parity.jl b/test/test_gpu_tiled_parity.jl index 9e2611a..1b43a24 100644 --- a/test/test_gpu_tiled_parity.jl +++ b/test/test_gpu_tiled_parity.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: @@ -81,6 +82,24 @@ Test.@testset "GPU tiled parity — general monotone bins 2D" begin Test.@test gpu.sums ≈ ref.sums atol = 1e-10 end +# A struct carrying a device array into a kernel must adapt that field, or the launch dies with +# "KernelError: passing non-bitstype argument" on CUDA. KA.CPU cannot reach that failure — adapt is +# a no-op there — so assert the rule itself recurses. +struct _EdgeAdaptProbe end +KA.Adapt.adapt_storage(::_EdgeAdaptProbe, ::AbstractArray) = :adapted + +Test.@testset "device-array kernel args recurse through adapt" begin + GPUExt = Base.get_extension(SF, :StructureFunctionsKernelAbstractionsExt) + + dig = GPUExt.SFGeneralDigitizer(rand(Float32, 6), 6) + adapted = KA.Adapt.adapt(_EdgeAdaptProbe(), dig) + Test.@test adapted.edges === :adapted + Test.@test adapted.n_edges == 6 + + vcols = GPUExt.GPUValueVectorCols{Float32}(rand(Float32, 6, 6)) + Test.@test KA.Adapt.adapt(_EdgeAdaptProbe(), vcols).edges_dev === :adapted +end + Test.@testset "GPU tiled parity — medium N linear 2D" begin N = 500 FT = Float32 @@ -124,11 +143,11 @@ Test.@testset "GPU joint 2D parity — L2SF linear bins N=50" begin sft = SFT.L2SFType() ref = SFC.calculate_structure_function( sft, x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) gpu = SFC.calculate_structure_function( sft, x, u, distance_bins, value_bins; - backend = SF.GPUBackend(KA.CPU()), verbose = false, show_progress = false, + backend = CB.GPUBackend(KA.CPU()), verbose = false, show_progress = false, ) Test.@test gpu.counts == ref.counts Test.@test gpu.sums ≈ ref.sums atol = 1e-10 @@ -144,11 +163,11 @@ Test.@testset "GPU joint 2D parity — L3SF log distance bins" begin sft = SFT.L3SFType() ref = SFC.calculate_structure_function( sft, x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) gpu = SFC.calculate_structure_function( sft, x, u, distance_bins, value_bins; - backend = SF.GPUBackend(KA.CPU()), verbose = false, show_progress = false, + backend = CB.GPUBackend(KA.CPU()), verbose = false, show_progress = false, ) Test.@test gpu.counts == ref.counts Test.@test gpu.sums ≈ ref.sums atol = 1e-10 @@ -165,3 +184,34 @@ Test.@testset "GPU tiled parity — NB > SF_GPU_MAX_BINS errors" begin sft, KA.CPU(), x, u, bin_edges, ) end + +# The tiled kernels size `@localmem` from the compile-time SF_GPU_MAX_BINS but index it by the +# runtime NB under `@inbounds`, so an unguarded NB > 128 writes out of bounds in shared memory and +# corrupts the histogram silently. The batch entries had no guard at all; these pin it down. +Test.@testset "GPU batch — NB > SF_GPU_MAX_BINS errors (no silent shared-mem overrun)" begin + FT = Float32 + N, B = 20, 3 + sft = SFT.L2SFType() + gpu_be = CB.GPUBackend(KA.CPU()) + over = collect(FT, range(0.0f0, 2.0f0; length = 130)) # 129 bins (> 128 cap) + under = collect(FT, range(0.0f0, 2.0f0; length = 65)) # 64 bins (must still run) + + x_fixed = rand(FT, 2, N) + x_vary = rand(FT, 2, N, B) + u = rand(FT, 2, N, B) + + for (name, x) in (("varying-x", x_vary), ("fixed-x", x_fixed)) + Test.@testset "1D individual batch $name" begin + Test.@test_throws ErrorException SFC.gpu_calculate_structure_function_batch( + sft, KA.CPU(), x, u, over, + ) + Test.@test SFC.gpu_calculate_structure_function_batch( + sft, KA.CPU(), x, u, under, + ) isa Any + end + Test.@testset "single-pass 1D batch $name" begin + Test.@test_throws ErrorException SFC._dispatch_single_pass(gpu_be, x, u, over) + Test.@test SFC._dispatch_single_pass(gpu_be, x, u, under) isa Any + end + end +end diff --git a/test/test_gpu_workspace.jl b/test/test_gpu_workspace.jl index b172a36..8f25bae 100644 --- a/test/test_gpu_workspace.jl +++ b/test/test_gpu_workspace.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using KernelAbstractions: KernelAbstractions as KA using StructureFunctions: @@ -115,12 +116,12 @@ Test.@testset "GPU Workspace & Slice Batch (KA.CPU)" begin # --- single_pass --- sp_inv = (:S2, :L2, :T2, :S3, :L3, :L1T2) ref_sp = SFC.calculate_structure_functions_single_pass( - x2, u2, linear_bins; backend = SFC.GPUBackend(backend), + x2, u2, linear_bins; backend = CB.GPUBackend(backend), output_type = SF.StructureFunctionSumsAndCounts, ) ws_sp = SFC.GPUSFWorkspace(backend, linear_bins; kind = :single_pass) out_sp = SFC.calculate_structure_functions_single_pass( - x2, u2, linear_bins; backend = SFC.GPUBackend(backend), workspace = ws_sp, + x2, u2, linear_bins; backend = CB.GPUBackend(backend), workspace = ws_sp, output_type = SF.StructureFunctionSumsAndCounts, ) for k in sp_inv @@ -134,7 +135,7 @@ Test.@testset "GPU Workspace & Slice Batch (KA.CPU)" begin counts_sp2d = zeros(UInt32, 6, NB, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_sp2d, counts_sp2d, x2, u2, linear_bins, value_bins_ntuple; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) ws_sp2d = SFC.GPUSFWorkspace(backend, linear_bins, value_bins_ntuple) sums_gpu = zeros(FT, 6, NB, n_val) @@ -172,7 +173,7 @@ Test.@testset "GPU Workspace & Slice Batch (KA.CPU)" begin SFC.calculate_structure_function_batch!( sums_drv, counts_drv, sft, x_batch, u_batch, linear_bins; - backend = SFC.GPUBackend(backend), workspace = ws_slice, + backend = CB.GPUBackend(backend), workspace = ws_slice, ) Test.@test sums_drv ≈ sums_slices atol = 1e-12 @@ -203,7 +204,7 @@ Test.@testset "GPU Workspace & Slice Batch (KA.CPU)" begin for t in 1:T res = SFC.calculate_structure_functions_single_pass( x_batch[:, :, t], u_batch[:, :, t], linear_bins; - backend = SFC.GPUBackend(backend), + backend = CB.GPUBackend(backend), output_type = SF.StructureFunctionSumsAndCounts, ) for (i, k) in enumerate(sp_inv) @@ -228,7 +229,7 @@ Test.@testset "GPU Workspace & Slice Batch (KA.CPU)" begin ct = zeros(UInt32, 6, NB, n_val) SFC.calculate_structure_functions_single_pass_2d!( st, ct, x_batch[:, :, t], u_batch[:, :, t], linear_bins, value_bins_ntuple; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) sums_sp2d_ref[:, :, :, t] .= st counts_sp2d_ref[:, :, :, t] .= ct diff --git a/test/test_helpers.jl b/test/test_helpers.jl index 1bec117..8d9178d 100644 --- a/test/test_helpers.jl +++ b/test/test_helpers.jl @@ -33,28 +33,32 @@ Test.@testset "HelperFunctions.jl Unit Tests" begin Test.@test SFH.δr(x1, x2) == [1.0, 0.0] Test.@test SFH.r̂(x1, x2) == [1.0, 0.0] - # n̂ in 2D (90 deg clockwise) -> [r_hat[2], -r_hat[1]] - # If r_hat = [1, 0], n̂ = [0, -1] - Test.@test SFH.n̂(x1, x2) == [0.0, -1.0] + # n̂ is the right-handed quarter turn ẑ × r̂ -> [-r_hat[2], r_hat[1]], so (r̂, n̂, ẑ) is + # right-handed. If r_hat = [1, 0], n̂ = [0, 1]. + Test.@test SFH.n̂(x1, x2) == [-0.0, 1.0] + # pin the orientation itself, not just this instance: det[r̂ n̂] == +1 + let rh = SA.SVector(0.6, 0.8), nh = SFH.n̂(SA.SVector(0.6, 0.8)) + Test.@test rh[1] * nh[2] - rh[2] * nh[1] ≈ 1.0 + end # 3D case x1_3d = [0.0, 0.0, 0.0] x2_3d = [0.0, 1.0, 0.0] # y-axis # r̂ = [0, 1, 0] # k̂ = [0, 0, 1] - # n̂ = normalize(cross(r̂, k̂)) = normalize([1, 0, 0]) = [1, 0, 0] + # n̂ = normalize(cross(k̂, r̂)) = normalize([-1, 0, 0]) = [-1, 0, 0] Test.@test SFH.r̂(x1_3d, x2_3d) ≈ [0.0, 1.0, 0.0] - Test.@test SFH.n̂(x1_3d, x2_3d) ≈ [1.0, 0.0, 0.0] + Test.@test SFH.n̂(x1_3d, x2_3d) ≈ [-1.0, 0.0, 0.0] # Tuples and StaticArrays t1 = (0.0, 0.0) t2 = (1.0, 1.0) Test.@test SA.SVector(SFH.r̂(t1, t2)) ≈ SA.SVector(1 / sqrt(2), 1 / sqrt(2)) - Test.@test SA.SVector(SFH.n̂(t1, t2)) ≈ SA.SVector(1 / sqrt(2), -1 / sqrt(2)) + Test.@test SA.SVector(SFH.n̂(t1, t2)) ≈ SA.SVector(-1 / sqrt(2), 1 / sqrt(2)) end Test.@testset "Projections: longitudinal and transverse" begin - # r̂ = [1, 0], n̂ = [0, -1] + # r̂ = [1, 0], n̂ = [0, 1] r_hat = SA.SVector(1.0, 0.0) δu = SA.SVector(2.0, 3.0) @@ -62,8 +66,8 @@ Test.@testset "HelperFunctions.jl Unit Tests" begin Test.@test SFH.mδu_l(δu, r_hat) == 2.0 Test.@test SFH.δu_l(δu, r_hat) == [2.0, 0.0] - # Transverse: dot([2,3], n̂([1,0])) = dot([2,3], [0, -1]) = -3.0 - Test.@test SFH.mδu_t(δu, r_hat) == -3.0 + # Transverse: dot([2,3], n̂([1,0])) = dot([2,3], [0, 1]) = 3.0 + Test.@test SFH.mδu_t(δu, r_hat) == 3.0 Test.@test SFH.δu_t(δu, r_hat) == [0.0, 3.0] # δu - δu_l = [2,3] - [2,0] = [0,3] # Consistency check: magnitude squared diff --git a/test/test_inplace.jl b/test/test_inplace.jl index 5a07ce6..708901a 100644 --- a/test/test_inplace.jl +++ b/test/test_inplace.jl @@ -1,5 +1,6 @@ module TestInplace +using ComputationalBackends: ComputationalBackends as CB using Test using Random using OhMyThreads @@ -28,7 +29,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, # Baselines bas = SFC.calculate_structure_function( SFT.L2SF, x_mat, u_mat, distance_bins; - output_type = SF.StructureFunctionSumsAndCounts, backend = SFC.SerialBackend(), verbose = false, show_progress = false + output_type = SF.StructureFunctionSumsAndCounts, backend = CB.SerialBackend(), verbose = false, show_progress = false ) sums = zeros(Float64, n_dist) @@ -49,7 +50,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, @testset "1D Serial Mutating Array Correctness & Accumulation" begin bas = SFC.calculate_structure_function( SFT.L2SF, x_mat, u_mat, distance_bins; - output_type = SF.StructureFunctionSumsAndCounts, backend = SFC.SerialBackend(), verbose = false, show_progress = false + output_type = SF.StructureFunctionSumsAndCounts, backend = CB.SerialBackend(), verbose = false, show_progress = false ) sums = zeros(Float64, n_dist) @@ -68,7 +69,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, @testset "2D Serial Mutating Array & Array Correctness & Accumulation" begin bas_arr = SFC.calculate_structure_function( SFT.L2SF, x_mat, u_mat, distance_bins, value_bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false + backend = CB.SerialBackend(), verbose = false, show_progress = false ) sums_arr = zeros(Float64, n_dist, n_vals) @@ -137,7 +138,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, # 1D Public AutoBackend (resolves to threaded or serial) sums_pub = zeros(Float64, n_dist) counts_pub = zeros(UInt32, n_dist) - SF.calculate_structure_function!(sums_pub, counts_pub, SFT.L2SF, x_mat, u_mat, distance_bins; backend=SF.AutoBackend(), verbose=false, show_progress=false) + SF.calculate_structure_function!(sums_pub, counts_pub, SFT.L2SF, x_mat, u_mat, distance_bins; backend=CB.AutoBackend(), verbose=false, show_progress=false) sums_bas = zeros(Float64, n_dist) counts_bas = zeros(UInt32, n_dist) @@ -149,7 +150,7 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, # 2D Public AutoBackend sums_2d_pub = zeros(Float64, n_dist, n_vals) counts_2d_pub = zeros(UInt32, n_dist, n_vals) - SF.calculate_structure_function!(sums_2d_pub, counts_2d_pub, SFT.L2SF, x_mat, u_mat, distance_bins, value_bins; backend=SF.AutoBackend(), verbose=false, show_progress=false) + SF.calculate_structure_function!(sums_2d_pub, counts_2d_pub, SFT.L2SF, x_mat, u_mat, distance_bins, value_bins; backend=CB.AutoBackend(), verbose=false, show_progress=false) sums_2d_bas = zeros(Float64, n_dist, n_vals) counts_2d_bas = zeros(UInt32, n_dist, n_vals) @@ -160,4 +161,50 @@ using StructureFunctions: StructureFunctions as SF, Calculations as SFC, end end +# Every `!` entry ACCUMULATES into the caller's buffers; zeroing belongs to the non-mutating +# wrappers. Batch-leading drivers used to overwrite (via `permutedims!`) and the tensor driver used +# to `fill!` the caller's arrays, so which contract you got depended only on the rank of the input. +@testset "Mutating API accumulates for every input shape" begin + Random.seed!(4242) + FT = Float64 + N, B = 24, 3 + bins = collect(FT, range(0.0, 2.0; length = 7)) + nb = length(bins) - 1 + sft = SFT.L2SFType() + x2, u2 = rand(FT, 2, N), rand(FT, 2, N) + u3 = rand(FT, 2, N, B) + + # (a) point-field: the family that already accumulated. + s1, c1 = zeros(FT, nb), zeros(UInt32, nb) + SFC.calculate_structure_function!(s1, c1, sft, x2, u2, bins; verbose = false, show_progress = false) + s2, c2 = copy(s1), copy(c1) + SFC.calculate_structure_function!(s2, c2, sft, x2, u2, bins; verbose = false, show_progress = false) + @test s2 ≈ 2 .* s1 + @test c2 == 2 .* c1 + + # (b) batch / auxiliary axes: previously overwrote. + bs1, bc1 = zeros(FT, nb, B), zeros(UInt32, nb, B) + SFC.calculate_structure_function!(bs1, bc1, sft, x2, u3, bins; verbose = false, show_progress = false) + bs2, bc2 = copy(bs1), copy(bc1) + SFC.calculate_structure_function!(bs2, bc2, sft, x2, u3, bins; verbose = false, show_progress = false) + @test bs2 ≈ 2 .* bs1 + @test bc2 == 2 .* bc1 + + # (c) tensor: previously `fill!`ed the caller's arrays, so it could never accumulate. + ts1, tc1 = zeros(FT, 2, 2, nb), zeros(UInt32, nb) + SFC.calculate_structure_function_tensor!(ts1, tc1, Val(2), x2, u2, bins; verbose = false, show_progress = false) + ts2, tc2 = copy(ts1), copy(tc1) + SFC.calculate_structure_function_tensor!(ts2, tc2, Val(2), x2, u2, bins; verbose = false, show_progress = false) + @test ts2 ≈ 2 .* ts1 + @test tc2 == 2 .* tc1 + + # The non-mutating wrappers still own the zeroing, so repeated calls are independent. + r1 = SFC.calculate_structure_function_tensor(Val(2), x2, u2, bins; + output_type = SFO.StructureFunctionTensorSumsAndCounts) + r2 = SFC.calculate_structure_function_tensor(Val(2), x2, u2, bins; + output_type = SFO.StructureFunctionTensorSumsAndCounts) + @test r1.sums ≈ r2.sums + @test r1.counts == r2.counts +end + end # module diff --git a/test/test_jet.jl b/test/test_jet.jl index 6ca3286..fa0630d 100644 --- a/test/test_jet.jl +++ b/test/test_jet.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, HelperFunctions as SFH, Calculations as SFC, StructureFunctionTypes as SFT using JET: JET @@ -27,7 +28,7 @@ Test.@testset "JET Stability Audit" begin x, u, bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) @@ -62,7 +63,7 @@ Test.@testset "JET Stability Audit" begin xa, ua, bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) diff --git a/test/test_mpi.jl b/test/test_mpi.jl index 94c4d6f..83440f7 100644 --- a/test/test_mpi.jl +++ b/test/test_mpi.jl @@ -22,7 +22,7 @@ Test.@testset "MPI backend (multi-rank parity)" begin ok = try buf = IOBuffer() MPI.mpiexec() do exe - run(pipeline(`$exe -n 2 $(Base.julia_cmd()) --project=$proj $script`; + run(pipeline(`$exe -n 2 $(Base.julia_cmd()) --project=$proj --threads=2 $script`; stdout = buf, stderr = buf)) end out = String(take!(buf)) diff --git a/test/test_parallel_equivalence.jl b/test/test_parallel_equivalence.jl index e2cc5dd..7e8684e 100644 --- a/test/test_parallel_equivalence.jl +++ b/test/test_parallel_equivalence.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, LogBinEdges, LinearBinEdges @@ -16,7 +17,7 @@ Distributed.@everywhere using StructureFunctions: LogBinEdges, LinearBinEdges Distributed.@everywhere using StaticArrays: StaticArrays as SA Distributed.@everywhere using SharedArrays: SharedArrays -Distributed.@everywhere using OhMyThreads: OhMyThreads # for hybrid DistributedBackend(ThreadedBackend()) +Distributed.@everywhere using OhMyThreads: OhMyThreads # for hybrid CB.DistributedBackend(CB.ThreadedBackend()) Test.@testset "Parallel Equivalence Verification" begin # Dataset @@ -67,7 +68,7 @@ Test.@testset "Parallel Equivalence Verification" begin sx, su, bins; - backend = SFC.DistributedBackend(), + backend = CB.DistributedBackend(), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, @@ -80,13 +81,13 @@ Test.@testset "Parallel Equivalence Verification" begin Test.@test counts_serial == counts_dist end - # 3b. Hybrid: DistributedBackend(ThreadedBackend()) — each worker threads over its share. + # 3b. Hybrid: CB.DistributedBackend(CB.ThreadedBackend()) — each worker threads over its share. res_hybrid = SFC.calculate_structure_function( sf_type, sx, su, bins; - backend = SFC.DistributedBackend(SFC.ThreadedBackend()), + backend = CB.DistributedBackend(CB.ThreadedBackend()), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, @@ -102,14 +103,14 @@ Test.@testset "Parallel Equivalence Verification" begin ub = rand(2, N, 4) res_ser_b = SFC.calculate_structure_function( sf_type, xb, ub, bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, ) Test.@testset "Serial vs Distributed batched" begin - for inner in (SFC.SerialBackend(), SFC.ThreadedBackend()) + for inner in (CB.SerialBackend(), CB.ThreadedBackend()) res_db = SFC.calculate_structure_function( sf_type, xb, ub, bins; - backend = SFC.DistributedBackend(inner), verbose = false, show_progress = false, + backend = CB.DistributedBackend(inner), verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, ) Test.@test res_ser_b.counts == res_db.counts @@ -123,7 +124,7 @@ Test.@testset "Parallel Equivalence Verification" begin sx, su, 2; # n_bins = 2 - backend = SFC.DistributedBackend(), + backend = CB.DistributedBackend(), bin_spacing = LogBinEdges, verbose = false, show_progress = false, diff --git a/test/test_performance_regression.jl b/test/test_performance_regression.jl deleted file mode 100644 index cf3550f..0000000 --- a/test/test_performance_regression.jl +++ /dev/null @@ -1,122 +0,0 @@ -using Test: Test -using BenchmarkTools: BenchmarkTools -using StructureFunctions: StructureFunctions as SF -using StaticArrays: StaticArrays as SA -using Random: Random -using JSON: JSON - -# Benchmark Metadata -const RESULTS_FILE = joinpath(@__DIR__, "bench_results.json") - -function load_previous_results() - if isfile(RESULTS_FILE) - try - return JSON.parsefile(RESULTS_FILE) - catch - @warn "Failed to parse existing results file, starting fresh." - return Dict() - end - end - return Dict() -end - -function save_results(results) - open(RESULTS_FILE, "w") do f - JSON.print(f, results, 4) - end -end - -function run_sf_benchmark(x, u, bins, sf_type; threaded = false) - # Cap benchmarks to 0.2s to keep the test suite under 10s - if threaded - return @benchmark SF.calculate_structure_function( - $sf_type, - $x, - $u, - $bins; - verbose = false, - show_progress = false, - ) seconds = 0.2 samples = 50 - else - return @benchmark SF.calculate_structure_function( - $sf_type, - $x, - $u, - $bins; - verbose = false, - show_progress = false, - ) seconds = 0.2 samples = 50 - end -end - -Test.@testset "Phase 7 Performance Regression & Comprehensive Tracking" begin - Random.seed!(42) - N = 100 - - # 2D Setup - x2 = randn(2, N) - u2 = randn(2, N) - # 3D Setup - x3 = randn(3, N) - u3 = randn(3, N) - - # Matrix version of 2D - xm = randn(2, N) - um = randn(2, N) - - bins = [0.0, 0.5, 1.0, 1.5, 2.0] - - sf_2nd_long = SF.LongitudinalSecondOrderStructureFunction - sf_2nd_trans = SF.TransverseSecondOrderStructureFunction - sf_3rd_diag = SF.DiagonalConsistentThirdOrderStructureFunction - - previous_results = load_previous_results() - current_results = Dict() - - @info "Running Comprehensive Benchmarks..." - - # Matrix of tests - test_matrix = [ - ("sf_2d_array_2nd_long", x2, u2, sf_2nd_long), - ("sf_3d_array_2nd_long", x3, u3, sf_2nd_long), - ("sf_2d_matrix_2nd_long", xm, um, sf_2nd_long), - ("sf_2d_array_2nd_trans", x2, u2, sf_2nd_trans), - ("sf_2d_array_3rd_diag", x2, u2, sf_3rd_diag), - ] - - for (name, x_in, u_in, sft) in test_matrix - Test.@testset "$name" begin - b = run_sf_benchmark(x_in, u_in, bins, sft) - allocs = b.allocs - time_min = minimum(b.times) / 1e3 # μs - - current_results[name] = Dict("allocs" => allocs, "time_μs" => time_min) - @info "$name: $allocs allocs, $time_min μs" - - if haskey(previous_results, name) - prev = previous_results[name] - Test.@test allocs <= prev["allocs"] - else - @info " New baseline recorded for $name." - # Initial sanity gates - Test.@test allocs < 100000 - end - end - end - - Test.@testset "Static Constructor Efficiency" begin - r_hat = SA.SVector(1.0, 0.0) - b_nhat = @benchmark SF.HelperFunctions.n̂($r_hat) - - allocs = b_nhat.allocs - current_results["nhat_helper"] = - Dict("allocs" => allocs, "time_μs" => minimum(b_nhat.times) / 1e3) - @info "HelperFunctions.n̂: $allocs allocs" - - Test.@test allocs == 0 - end - - # Save current results as the new baseline - @info "Saving comprehensive benchmarks to $RESULTS_FILE" - save_results(current_results) -end diff --git a/test/test_shape_contract.jl b/test/test_shape_contract.jl index 8fc719d..38c5e0c 100644 --- a/test/test_shape_contract.jl +++ b/test/test_shape_contract.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test using Random using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT @@ -16,11 +17,11 @@ Random.seed!(42) u3 = rand(3, 8) r2 = SFC.calculate_structure_function( - sf, x2, u2, bins; backend = SFC.SerialBackend(), + sf, x2, u2, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) r3 = SFC.calculate_structure_function( - sf, x3, u3, bins; backend = SFC.SerialBackend(), + sf, x3, u3, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) @@ -32,14 +33,14 @@ Random.seed!(42) x = rand(2, 9) u = rand(2, 9, 3) r = SFC.calculate_structure_function( - sf, x, u, bins; backend = SFC.SerialBackend(), + sf, x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) ref_sums = zeros(eltype(r.sums), n_bins, 3) ref_counts = zeros(eltype(r.counts), n_bins, 3) for t in 1:3 rt = SFC.calculate_structure_function( - sf, x, @view(u[:, :, t]), bins; backend = SFC.SerialBackend(), + sf, x, @view(u[:, :, t]), bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) ref_sums[:, t] .= rt.sums @@ -53,7 +54,7 @@ Random.seed!(42) x = rand(2, 7) u = rand(2, 7, 2, 3) r = SFC.calculate_structure_function( - sf, x, u, bins; backend = SFC.SerialBackend(), + sf, x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) @test size(r.sums) == (n_bins, 2, 3) @@ -64,14 +65,14 @@ Random.seed!(42) x = rand(2, 8, 3) u = rand(2, 8, 3) r = SFC.calculate_structure_function( - sf, x, u, bins; backend = SFC.SerialBackend(), + sf, x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) ref_sums = zeros(eltype(r.sums), n_bins, 3) ref_counts = zeros(eltype(r.counts), n_bins, 3) for t in 1:3 rt = SFC.calculate_structure_function( - sf, @view(x[:, :, t]), @view(u[:, :, t]), bins; backend = SFC.SerialBackend(), + sf, @view(x[:, :, t]), @view(u[:, :, t]), bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, ) ref_sums[:, t] .= rt.sums diff --git a/test/test_single_pass.jl b/test/test_single_pass.jl index 412b0dc..d528b1e 100644 --- a/test/test_single_pass.jl +++ b/test/test_single_pass.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, StructureFunctionTypes as SFT, Calculations as SFC using OhMyThreads: OhMyThreads # load extension for ThreadedBackend / AutoBackend when nthreads() > 1 @@ -36,7 +37,7 @@ Test.@testset "Single-Pass Core Correctness & Helmholtz Parity" begin # 1. Test SerialBackend single-pass execution (raw output for sums/counts comparison) sp = SFC.calculate_structure_functions_single_pass( x, u, distance_bins; - backend = SFC.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, + backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) # Keyed-collection shape: six invariants + a helmholtz entry for point-field input. @@ -81,7 +82,7 @@ Test.@testset "Single-Pass Core Correctness & Helmholtz Parity" begin # 4. Compare AutoBackend against SerialBackend (per invariant, NaN-safe) sp_auto = SFC.calculate_structure_functions_single_pass( x, u, distance_bins; - backend = SFC.AutoBackend(), output_type = SF.StructureFunctionSumsAndCounts, + backend = CB.AutoBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) for k in SP_INV Test.@test _sp_nan_safe(sp_auto[k].sums, sp[k].sums; atol = 1e-12) @@ -99,18 +100,18 @@ Test.@testset "Single-Pass 3D point parity" begin distance_bins = Float32[0.1, 1.0, 2.0] sp = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; backend = SFC.SerialBackend(), + x, u, distance_bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) Test.@test keys(sp) == (SP_INV..., :helmholtz) Test.@test length(sp.S2.sums) == 2 sp_auto = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; backend = SFC.AutoBackend(), + x, u, distance_bins; backend = CB.AutoBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) sp_gpu = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; backend = SF.GPUBackend(KA.CPU()), + x, u, distance_bins; backend = CB.GPUBackend(KA.CPU()), output_type = SF.StructureFunctionSumsAndCounts, ) for k in SP_INV @@ -127,14 +128,14 @@ Test.@testset "Single-Pass 3D auxiliary axes" begin distance_bins = Float32[0.0, 0.75, 1.5, 3.0] batched = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; backend = SFC.SerialBackend(), + x, u, distance_bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) # Batched (auxiliary-axis) input has no Helmholtz entry — just the six invariants. Test.@test keys(batched) == SP_INV for b in 1:2 spb = SFC.calculate_structure_functions_single_pass( - x, @view(u[:, :, b]), distance_bins; backend = SFC.SerialBackend(), + x, @view(u[:, :, b]), distance_bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) for k in SP_INV @@ -144,43 +145,56 @@ Test.@testset "Single-Pass 3D auxiliary axes" begin end end -Test.@testset "Single-Pass with Custom Distance Metric (Cityblock)" begin - using Distances: Distances as DI - x = Float64[0.0 1.0 0.0; - 0.0 0.0 1.0] - u = Float64[0.0 1.0 0.0; - 0.0 0.0 1.0] - - distance_bins = Float64[0.1, 1.0, 2.0] - metric = DI.Cityblock() - - sp = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; - backend = SFC.SerialBackend(), distance_metric = metric, - output_type = SF.StructureFunctionSumsAndCounts, - ) +# `helmholtz_decompose_2d` used to reconstruct bin midpoints from only the first and last edge via +# exp(min_log + (k-0.5)*log_step), i.e. it assumed log-uniform spacing unconditionally. On linear +# edges that placed midpoints outside their own bins (up to ~59% off) and silently returned a wrong +# decomposition. Midpoints now come from the actual edges as sqrt(e[k]*e[k+1]). +Test.@testset "Helmholtz decomposition — bin midpoints from actual edges" begin + FT = Float64 + n_bins = 8 + lin_edges = collect(FT, range(0.5, 8.5; length = n_bins + 1)) + log_edges = collect(FT, 10 .^ range(log10(0.1), log10(10.0); length = n_bins + 1)) + + # Non-constant D_TT - D_LL so the cumulative integral (and hence the midpoints) actually matter. + counts = ones(UInt32, n_bins) + L2 = FT[0.5k for k in 1:n_bins] + T2 = FT[0.5k + 0.25k^2 for k in 1:n_bins] + + function expected(edges) + mids = FT[sqrt(edges[k] * edges[k + 1]) for k in 1:n_bins] + I = zeros(FT, n_bins) + for k in 2:n_bins + f_prev = (T2[k - 1] - L2[k - 1]) / mids[k - 1] + f_curr = (T2[k] - L2[k]) / mids[k] + I[k] = I[k - 1] + 0.5 * (f_prev + f_curr) * (mids[k] - mids[k - 1]) + end + return mids, I + end - distance_bins_ref = Float64[0.1, 1.0, 2.0] - for t in 1:6 - res = SFC.calculate_structure_function( - SP_REF_TYPES[t], x, u, distance_bins_ref; - distance_metric = metric, - verbose = false, show_progress = false, output_type = SF.StructureFunctionSumsAndCounts, - ) - entry = sp[SP_INV[t]] - Test.@test isapprox(entry.sums, res.sums, atol = 1e-12) - Test.@test entry.counts == res.counts + for edges in (lin_edges, log_edges) + h = SFC.helmholtz_decompose_2d(edges, L2, counts, T2, counts) + mids, I = expected(edges) + Test.@test h.rotational_sums ≈ T2 .+ mids .* I + Test.@test h.divergent_sums ≈ L2 .- mids .* I + # The invariant the old closed form violated: each midpoint lies inside its own bin. + for k in 1:n_bins + Test.@test edges[k] <= mids[k] <= edges[k + 1] + end end - # Compare AutoBackend against SerialBackend under Cityblock metric (per invariant, NaN-safe) - sp_auto = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; - backend = SFC.AutoBackend(), distance_metric = metric, - output_type = SF.StructureFunctionSumsAndCounts, + # Empty bins must not enter the cumulative integral as a fabricated zero. + sparse_counts = copy(counts) + sparse_counts[3] = 0 + h_sparse = SFC.helmholtz_decompose_2d(lin_edges, L2, sparse_counts, T2, sparse_counts) + Test.@test isnan(h_sparse.longitudinal_values[3]) + Test.@test isnan(h_sparse.transverse_values[3]) + + # A bin touching r <= 0 has no geometric midpoint and no r^-1 integrand: NaN, never a number. + # The six invariants stay valid, so this must not error — bins starting at 0.0 are legitimate. + h_zero = SFC.helmholtz_decompose_2d( + collect(FT, range(0.0, 8.0; length = n_bins + 1)), L2, counts, T2, counts, ) - for k in SP_INV - Test.@test _sp_nan_safe(sp_auto[k].sums, sp[k].sums; atol = 1e-12) - Test.@test sp_auto[k].counts == sp[k].counts - end + Test.@test all(isnan, h_zero.rotational_sums) + Test.@test all(isnan, h_zero.divergent_sums) end diff --git a/test/test_single_pass_2d.jl b/test/test_single_pass_2d.jl index f8be845..0fd92d1 100644 --- a/test/test_single_pass_2d.jl +++ b/test/test_single_pass_2d.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionObjects as SFO, StructureFunctionTypes as SFT, InfPaddedBinEdges, LinearBinEdges, LogBinEdges @@ -37,7 +38,7 @@ Test.@testset "Single-Pass 2D Core Correctness & Parity" begin counts_2d = zeros(UInt32, 6, n_bins, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_2d, counts_2d, x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) Test.@test size(sums_2d) == (6, n_bins, n_val) Test.@test size(counts_2d) == (6, n_bins, n_val) @@ -46,7 +47,7 @@ Test.@testset "Single-Pass 2D Core Correctness & Parity" begin for (t, k) in enumerate(SP2D_INV) sf2d = SFC.calculate_structure_function( SFC.SINGLE_PASS_OPERATORS[k], x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) Test.@test sf2d isa SFO.StructureFunction2DSumsAndCounts Test.@test sums_2d[t, :, :] ≈ sf2d.sums @@ -56,7 +57,7 @@ Test.@testset "Single-Pass 2D Core Correctness & Parity" begin # 1D single-pass (keyed, raw) for marginalization parity. sp_1d = SFC.calculate_structure_functions_single_pass( x, u, distance_bins; - backend = SFC.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, + backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts, ) for (t, k) in enumerate(SP2D_INV) marg_sums = vec(dropdims(sum(sums_2d[t:t, :, :], dims = 3), dims = 1)) @@ -83,11 +84,11 @@ Test.@testset "Single-Pass 2D Core Correctness & Parity" begin fill!(counts_2d, 0) SFC.calculate_structure_functions_single_pass_2d!( sums_2d, counts_2d, x, u, distance_bins, value_bins; - backend = SFC.AutoBackend(), + backend = CB.AutoBackend(), ) sp2_auto = SFC.calculate_structure_functions_single_pass_2d( x, u, distance_bins, value_bins; - backend = SFC.AutoBackend(), + backend = CB.AutoBackend(), ) for (t, k) in enumerate(SP2D_INV) Test.@test sp2_auto[k].sums ≈ sums_2d[t, :, :] @@ -95,59 +96,6 @@ Test.@testset "Single-Pass 2D Core Correctness & Parity" begin end end -Test.@testset "Single-Pass 2D with Custom Distance Metric (Cityblock)" begin - using Distances: Distances as DI - - Random.seed!(42) - n_points = 40 - x = rand(n_points, 2)' .* 50000.0 - u = randn(2, n_points) .* 0.5 - - distance_bins = LogBinEdges(collect(exp.(range(log(1000.0), log(50000.0), length = 6)))) - value_bins = _synthetic_value_bins(10; pad_infinite = true) - n_val = length(value_bins) - 1 - n_bins = length(distance_bins) - 1 - metric = DI.Cityblock() - - sums_2d = zeros(Float64, 6, n_bins, n_val) - counts_2d = zeros(UInt32, 6, n_bins, n_val) - SFC.calculate_structure_functions_single_pass_2d!( - sums_2d, counts_2d, x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), distance_metric = metric, - ) - - for (t, k) in enumerate(SP2D_INV) - sf2d = SFC.calculate_structure_function( - SFC.SINGLE_PASS_OPERATORS[k], x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), distance_metric = metric, - verbose = false, show_progress = false, - ) - Test.@test sums_2d[t, :, :] ≈ sf2d.sums - Test.@test counts_2d[t, :, :] ≈ sf2d.counts - end - - sp_1d = SFC.calculate_structure_functions_single_pass( - x, u, distance_bins; - backend = SFC.SerialBackend(), distance_metric = metric, - output_type = SF.StructureFunctionSumsAndCounts, - ) - for (t, k) in enumerate(SP2D_INV) - marg_sums = vec(dropdims(sum(sums_2d[t:t, :, :], dims = 3), dims = 1)) - marg_counts = vec(dropdims(sum(counts_2d[t:t, :, :], dims = 3), dims = 1)) - Test.@test marg_sums ≈ sp_1d[k].sums - Test.@test marg_counts == sp_1d[k].counts - end - - # Compare AutoBackend with SerialBackend - sp2_auto = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, value_bins; - backend = SFC.AutoBackend(), distance_metric = metric, - ) - for (t, k) in enumerate(SP2D_INV) - Test.@test sp2_auto[k].sums ≈ sums_2d[t, :, :] - Test.@test sp2_auto[k].counts == counts_2d[t, :, :] - end -end Test.@testset "Single-Pass 2D value-bin accepted shapes" begin Random.seed!(15) @@ -158,7 +106,7 @@ Test.@testset "Single-Pass 2D value-bin accepted shapes" begin shared_range_bins = range(-2.0, 3.0; length = 9) s_shared = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, shared_range_bins; backend = SFC.SerialBackend(), + x, u, distance_bins, shared_range_bins; backend = CB.SerialBackend(), ) Test.@test keys(s_shared) == SP2D_INV Test.@test size(s_shared.S2.sums) == (nd, length(shared_range_bins) - 1) @@ -169,14 +117,14 @@ Test.@testset "Single-Pass 2D value-bin accepted shapes" begin LinearBinEdges(range(-2.0, 3.0; length = 9)) end s_mixed = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, mixed_bins; backend = SFC.SerialBackend(), + x, u, distance_bins, mixed_bins; backend = CB.SerialBackend(), ) for k in SP2D_INV Test.@test size(s_mixed[k].sums) == size(s_shared[k].sums) end s_gpu = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, mixed_bins; backend = SF.GPUBackend(KA.CPU()), + x, u, distance_bins, mixed_bins; backend = CB.GPUBackend(KA.CPU()), ) for k in SP2D_INV Test.@test s_gpu[k].sums ≈ s_mixed[k].sums @@ -195,10 +143,10 @@ Test.@testset "Single-Pass 2D value bins with 3D point fields" begin value_bins = range(-2.0f0, 2.0f0; length = 9) sp_ref = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, value_bins; backend = SFC.SerialBackend(), + x, u, distance_bins, value_bins; backend = CB.SerialBackend(), ) sp_gpu = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, value_bins; backend = SF.GPUBackend(KA.CPU()), + x, u, distance_bins, value_bins; backend = CB.GPUBackend(KA.CPU()), ) for k in SP2D_INV Test.@test isapprox(sp_gpu[k].sums, sp_ref[k].sums; atol = 1.0f-4) @@ -221,12 +169,12 @@ Test.@testset "Single-Pass 2D GPU (KA.CPU) parity vs Serial" begin counts_ref = zeros(UInt32, 6, n_bins, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_ref, counts_ref, x, u, distance_bins, value_bins; - backend = SFC.SerialBackend(), + backend = CB.SerialBackend(), ) sp_gpu = SFC.calculate_structure_functions_single_pass_2d( x, u, distance_bins, value_bins; - backend = SF.GPUBackend(KA.CPU()), + backend = CB.GPUBackend(KA.CPU()), ) for (t, k) in enumerate(SP2D_INV) Test.@test sp_gpu[k].sums ≈ sums_ref[t, :, :] @@ -238,8 +186,49 @@ Test.@testset "Single-Pass 2D GPU (KA.CPU) parity vs Serial" begin counts_gpu2 = zeros(UInt32, 6, n_bins, n_val) SFC.calculate_structure_functions_single_pass_2d!( sums_gpu2, counts_gpu2, x, u, distance_bins, value_bins; - backend = SF.GPUBackend(KA.CPU()), + backend = CB.GPUBackend(KA.CPU()), ) Test.@test sums_gpu2 ≈ sums_ref Test.@test counts_gpu2 == counts_ref end + +# `value_bins` may be a heterogeneous NTuple{6} — log bins for the three non-negative invariants and +# linear/raw-vector bins for the three signed ones is the natural choice. The scatter is unrolled so +# each `vb` stays concretely typed; indexing the tuple with a runtime `t` would make it a `Union` and +# box a `digitize` dispatch on every pair x invariant. +Test.@testset "Single-Pass 2D heterogeneous value-bin tuple" begin + FT = Float64 + N, nv = 60, 6 + Random.seed!(99) + x, u = rand(FT, 2, N), randn(FT, 2, N) + db = collect(FT, range(0.0, 2.0; length = 7)) + nd = length(db) - 1 + + lin = LinearBinEdges(range(FT(-10), FT(10); length = nv + 1)) + lg = LogBinEdges(collect(FT, 10 .^ range(-4, 1; length = nv + 1))) + raw = collect(FT, range(FT(-10), FT(10); length = nv + 1)) + het = (lg, lg, lg, lin, raw, lin) + + Test.@test !isconcretetype(eltype(het)) # the case the unroll exists for + + # Correct: each invariant must match a run with that invariant's bins used uniformly. + got = SFC.calculate_structure_functions_single_pass_2d( + x, u, db, het; backend = CB.SerialBackend(), verbose = false, show_progress = false, + ) + for (t, k) in enumerate(SP2D_INV) + ref = SFC.calculate_structure_functions_single_pass_2d( + x, u, db, ntuple(_ -> het[t], 6); + backend = CB.SerialBackend(), verbose = false, show_progress = false, + ) + Test.@test got[k].sums ≈ ref[k].sums + Test.@test got[k].counts == ref[k].counts + end + + # Type-stability proxy: a boxed Union `vb` allocates per pair x invariant. At N=60 that is + # 10_620 * 6 scatters, so per-op boxing would cost megabytes; the unrolled form costs ~nothing. + sums = zeros(FT, 6, nd, nv) + counts = zeros(UInt32, 6, nd, nv) + f() = SFC.serial_calculate_structure_functions_single_pass_2d!(sums, counts, x, u, db, het) + f() + Test.@test (@allocated f()) < 100_000 +end diff --git a/test/test_spherical_geometry.jl b/test/test_spherical_geometry.jl new file mode 100644 index 0000000..bfcc59f --- /dev/null +++ b/test/test_spherical_geometry.jl @@ -0,0 +1,237 @@ +using ComputationalBackends: ComputationalBackends as CB +using StructureFunctions: + StructureFunctions as SF, Calculations as SFC, HelperFunctions as SFH, + StructureFunctionObjects as SFO, StructureFunctionTypes as SFT +using OhMyThreads: OhMyThreads +using Distances: Distances as DI +using StaticArrays: StaticArrays as SA +using LinearAlgebra: LinearAlgebra as LA +using Random: Random +using Test: Test + +Random.seed!(20260817) + +const EARTH_R = 6.371e6 + +_sp(x, u, bins, m; be = CB.SerialBackend()) = SFC.calculate_structure_functions_single_pass( + x, u, bins; backend = be, distance_metric = m, + output_type = SFO.StructureFunctionSumsAndCounts, +) + +Test.@testset "Pair geometry: selection and coordinate width" begin + Test.@test SFH.pair_geometry_for(DI.Euclidean(), Val(2)) === SFH.FlatGeometry{2}() + Test.@test SFH.pair_geometry_for(DI.Euclidean(), Val(3)) === SFH.FlatGeometry{3}() + Test.@test SFH.pair_geometry_for(DI.Haversine(EARTH_R), Val(2)) isa SFH.SphericalGeometry{2} + Test.@test SFH.pair_geometry_for(DI.SphericalAngle(), Val(3)) isa SFH.SphericalGeometry{3} + + # A point on a shell takes two coordinates whether or not the velocity carries a radial third. + Test.@test SFH.coordinate_width(SFH.FlatGeometry{2}()) === Val(2) + Test.@test SFH.coordinate_width(SFH.FlatGeometry{3}()) === Val(3) + Test.@test SFH.coordinate_width(SFH.pair_geometry_for(DI.Haversine(EARTH_R), Val(2))) === Val(2) + Test.@test SFH.coordinate_width(SFH.pair_geometry_for(DI.Haversine(EARTH_R), Val(3))) === Val(2) + + # A distance function does not define a direction or a transport rule, so a metric with no + # geometry is refused rather than assumed flat. + Test.@test_throws ArgumentError SFH.pair_geometry_for(DI.Cityblock(), Val(2)) + msg = try + SFH.pair_geometry_for(DI.Cityblock(), Val(2)) + catch e + sprint(showerror, e) + end + Test.@test occursin("pair_geometry_for", msg) +end + +Test.@testset "Spherical separation matches the metric, in both angle conventions" begin + hav = DI.Haversine(EARTH_R) + sph = DI.SphericalAngle() + for (lo1, la1, lo2, la2) in ((10.0, 45.0, 13.0, 47.0), (-170.0, -33.0, 175.0, 12.0), + (0.0, 0.0, 0.0, 90.0), (100.0, 60.0, 100.0, 60.5)) + p1 = SA.SVector(lo1, la1); p2 = SA.SVector(lo2, la2) + ok_h, r_h, f_h = SFH.pair_frame(SFH.pair_geometry_for(hav, Val(2)), p1, p2) + q1 = SA.SVector(deg2rad(lo1), deg2rad(la1)); q2 = SA.SVector(deg2rad(lo2), deg2rad(la2)) + ok_s, r_s, f_s = SFH.pair_frame(SFH.pair_geometry_for(sph, Val(2)), q1, q2) + + Test.@test ok_h && ok_s + Test.@test isapprox(r_h, hav(p1, p2); rtol = 1e-12) + Test.@test isapprox(r_s, sph(q1, q2); rtol = 1e-12) + # Degrees and radians describe the same physical pair: same arc, same local frame. + Test.@test isapprox(r_h, EARTH_R * r_s; rtol = 1e-12) + Test.@test isapprox(f_h[1], f_s[1]; atol = 1e-12) + Test.@test isapprox(f_h[2], f_s[2]; atol = 1e-12) + end +end + +# A rigid rotation preserves every geodesic distance, so d(σ)/dt = δu_L / R vanishes for EVERY +# pair at every separation. This is the sharpest single test of the parallel transport: it holds +# under transport and fails badly for a frame that is not transported. +Test.@testset "Solid-body rotation has no longitudinal increment" begin + N = 250 + Ω = 7.292e-5 + lon = 360 .* rand(N) .- 180 + lat = 120 .* rand(N) .- 60 + x = permutedims(hcat(lon, lat)) + u = permutedims(hcat(Ω * EARTH_R .* cosd.(lat), zeros(N))) + bins = collect(range(0.0, 8.0e6; length = 21)) + + r = _sp(x, u, bins, DI.Haversine(EARTH_R)) + occ = r.L2.counts .> 0 + Test.@test any(occ) + # L2 is a square of δu_L, so machine-zero here is ~eps^2 relative to S2. + Test.@test sum(r.L2.sums[occ]) / sum(r.S2.sums[occ]) < 1e-24 + + # Control: the identical field with a non-transported (flat lon/lat) frame puts a large + # fraction of the energy into a quantity whose true value is zero. + flat = SFC.calculate_structure_functions_single_pass( + x, u, collect(range(0.0, 80.0; length = 21)); backend = CB.SerialBackend(), + distance_metric = DI.Euclidean(), output_type = SFO.StructureFunctionSumsAndCounts, + ) + occf = flat.L2.counts .> 0 + Test.@test sum(flat.L2.sums[occf]) / sum(flat.S2.sums[occf]) > 0.01 +end + +Test.@testset "Thin shell: radial component is carried but never transported" begin + N = 200 + Ω = 7.292e-5 + lon = 300 .* rand(N) .- 150 + lat = 100 .* rand(N) .- 50 + x = permutedims(hcat(lon, lat)) # (2, N) + ue = Ω * EARTH_R .* cosd.(lat) + u2 = permutedims(hcat(ue, zeros(N))) # (2, N) + u3 = permutedims(hcat(ue, zeros(N), 3.0 .* sind.(2 .* lat))) # (3, N) + vertical + bins = collect(range(0.0, 8.0e6; length = 21)) + m = DI.Haversine(EARTH_R) + + r2 = _sp(x, u2, bins, m) + r3 = _sp(x, u3, bins, m) + + # The geodesic frame is tangent to the shell, so the radial component is orthogonal to both + # t̂ and m̂ and cannot enter δu_L at all. + Test.@test r3.L2.sums == r2.L2.sums + Test.@test r3.L2.counts == r2.L2.counts + # It does contribute to the total, and the six invariants stay consistent. + Test.@test sum(r3.S2.sums) > sum(r2.S2.sums) + Test.@test r3.S2.sums ≈ r3.L2.sums .+ r3.T2.sums +end + +Test.@testset "Spherical geometry: backend agreement" begin + N = 120 + lon = 300 .* rand(N) .- 150 + lat = 100 .* rand(N) .- 50 + x = permutedims(hcat(lon, lat)) + u = permutedims(hcat(randn(N), randn(N), randn(N))) + bins = collect(range(0.0, 9.0e6; length = 13)) + m = DI.Haversine(EARTH_R) + + ref = _sp(x, u, bins, m) + for be in (CB.AutoBackend(), CB.ThreadedBackend()) + got = _sp(x, u, bins, m; be = be) + for k in (:S2, :L2, :T2, :S3, :L3, :L1T2) + Test.@test got[k].counts == ref[k].counts + Test.@test got[k].sums ≈ ref[k].sums + end + end + + # Single operators must agree with the single-pass invariants under the same geometry. + for (sft, key) in ((SFT.LongitudinalSecondOrderStructureFunctionType(), :L2), + (SFT.TransverseSecondOrderStructureFunctionType(), :T2), + (SFT.SecondOrderStructureFunctionType(), :S2)) + one = SFC.calculate_structure_function( + sft, x, u, bins; backend = CB.SerialBackend(), distance_metric = m, + output_type = SFO.StructureFunctionSumsAndCounts, verbose = false, show_progress = false, + ) + Test.@test one.counts == ref[key].counts + Test.@test one.sums ≈ ref[key].sums + end +end + +# On a patch of angular size ε the transported frame and a flat tangent-plane frame differ by +# O(ε) (the meridian convergence). Shrinking the patch must shrink the discrepancy proportionally +# — "the difference is small" is not the claim; the scaling is. +Test.@testset "Flat limit: spherical converges to Cartesian like r/R" begin + N = 90 + lat0 = 35.0 + function deviation(halfwidth_deg) + Random.seed!(4242) + dlon = halfwidth_deg .* (2 .* rand(N) .- 1) + dlat = halfwidth_deg .* (2 .* rand(N) .- 1) + lon = dlon + lat = lat0 .+ dlat + uu = permutedims(hcat(randn(N), randn(N))) + x_sph = permutedims(hcat(lon, lat)) + # Local tangent plane at (0, lat0), in metres. + x_flat = permutedims(hcat( + EARTH_R .* deg2rad.(dlon) .* cosd(lat0), EARTH_R .* deg2rad.(dlat), + )) + rmax = 2.2 * EARTH_R * deg2rad(halfwidth_deg) + bins = collect(range(0.0, rmax; length = 9)) + a = _sp(x_sph, uu, bins, DI.Haversine(EARTH_R)) + b = _sp(x_flat, uu, bins, DI.Euclidean()) + occ = (a.L2.counts .> 0) .& (b.L2.counts .> 0) + return maximum(abs.(a.L2.sums[occ] .- b.L2.sums[occ])) / maximum(abs.(b.L2.sums[occ])) + end + + d_big = deviation(4.0) + d_small = deviation(1.0) + Test.@test d_small < d_big + # A 4x smaller patch must cut the O(r/R) discrepancy by at least ~2.5x (allowing slack for + # the pair set changing with the patch and for the O((r/R)^2) term). + Test.@test d_big / d_small > 2.5 +end + +# The geometry interface is the extension point: a user's own manifold works by adding methods, +# with no special-casing anywhere in the package. Demonstrated, not asserted in prose. +struct DoubledFlatMetric <: DI.PreMetric end +(::DoubledFlatMetric)(a, b) = 2 * sqrt(sum(abs2, a .- b)) + +struct DoubledFlatGeometry{D} end +SFH.coordinate_width(::DoubledFlatGeometry{D}) where {D} = Val(D) +SFH.pair_geometry_for(::DoubledFlatMetric, ::Val{D}) where {D} = DoubledFlatGeometry{D}() +@inline function SFH.pair_frame(::DoubledFlatGeometry, x1, x2) + dx = x2 - x1 + return true, 2 * sqrt(LA.dot(dx, dx)), dx +end +@inline SFH.pair_direction(::DoubledFlatGeometry, frame, r) = frame / (r / 2) +@inline SFH.pair_delta(::DoubledFlatGeometry, frame, x1, x2, u1, u2) = u2 - u1 + +Test.@testset "User-defined geometry works end to end on every backend" begin + N = 100 + x = rand(2, N) + u = randn(2, N) + bins = collect(range(0.05, 1.4; length = 11)) + + # Every separation is doubled, so doubled bins must reproduce the Euclidean histogram exactly. + euc = _sp(x, u, bins, DI.Euclidean()) + for be in (CB.SerialBackend(), CB.AutoBackend()) + got = _sp(x, u, 2 .* bins, DoubledFlatMetric(); be = be) + for k in (:S2, :L2, :T2, :S3, :L3, :L1T2) + Test.@test got[k].counts == euc[k].counts + Test.@test got[k].sums ≈ euc[k].sums + end + end + + # And through a different entry point (2D joint) to show nothing is special-cased per-path. + vb = collect(range(-3.0, 3.0; length = 9)) + j_euc = SFC.calculate_structure_function( + SFT.L2SFType(), x, u, bins, vb; backend = CB.SerialBackend(), verbose = false, + show_progress = false, + ) + j_got = SFC.calculate_structure_function( + SFT.L2SFType(), x, u, 2 .* bins, vb; backend = CB.SerialBackend(), + distance_metric = DoubledFlatMetric(), verbose = false, show_progress = false, + ) + Test.@test j_got.counts == j_euc.counts + Test.@test j_got.sums ≈ j_euc.sums +end + +Test.@testset "Shape contract is geometry-aware" begin + bins = collect(range(0.0, 5.0e6; length = 9)) + # Flat space: the coordinate count is the velocity dimension. + Test.@test_throws DimensionMismatch _sp(rand(2, 8), randn(3, 8), bins, DI.Euclidean()) + Test.@test_throws DimensionMismatch _sp(rand(3, 8), randn(2, 8), bins, DI.Euclidean()) + # A shell locates a point with two coordinates, for both D = 2 and D = 3. + m = DI.Haversine(EARTH_R) + Test.@test_throws DimensionMismatch _sp(rand(3, 8), randn(3, 8), bins, m) + lonlat = permutedims(hcat(20 .* rand(8), 20 .* rand(8))) + Test.@test _sp(lonlat, randn(2, 8), bins, m) isa NamedTuple + Test.@test _sp(lonlat, randn(3, 8), bins, m) isa NamedTuple +end diff --git a/test/test_stability.jl b/test/test_stability.jl index 8a1ec3c..ee6d5ad 100644 --- a/test/test_stability.jl +++ b/test/test_stability.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test, @inferred using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT, StructureFunctionObjects as SFO @@ -13,25 +14,23 @@ Test.@testset "Stability Verification" begin # 1. Default (averaged) output path must infer concretely. This exercises the full backend # compute (which produces the raw accumulator) plus `_finalize`, so any backend - # type-instability would surface here. (Passing a non-default `output_type` explicitly - # incurs a single dynamic-dispatch barrier — negligible, and analogous to the old - # `return_sums_and_counts` convenience form — so it is exercised for correctness below, - # not inferred.) + # type-instability would surface here. A non-default `output_type` incurs one + # dynamic-dispatch barrier, so it is checked for correctness below rather than inferred. println("Checking type stability for Array variant (default output-type)...") - @inferred SFC.calculate_structure_function(sft, x, u, bins; backend = SFC.SerialBackend(), count_eltype = UInt32) + @inferred SFC.calculate_structure_function(sft, x, u, bins, UInt32; backend = CB.SerialBackend()) - res_false = SFC.calculate_structure_function(sft, x, u, bins; backend = SFC.SerialBackend(), count_eltype = UInt32) + res_false = SFC.calculate_structure_function(sft, x, u, bins, UInt32; backend = CB.SerialBackend()) Test.@test res_false isa SFO.StructureFunction - res_true = SFC.calculate_structure_function(sft, x, u, bins; backend = SFC.SerialBackend(), output_type = SFO.StructureFunctionSumsAndCounts, count_eltype = UInt32) + res_true = SFC.calculate_structure_function(sft, x, u, bins, UInt32; backend = CB.SerialBackend(), output_type = SFO.StructureFunctionSumsAndCounts) Test.@test res_true isa SFO.StructureFunctionSumsAndCounts # 1b. Single-pass default (averaged) path must infer concretely too — for point-field and # batched (auxiliary-axis) input. The keyed result is a single concrete NamedTuple per rank. println("Checking type stability for single-pass (point-field + batched)...") - @inferred SFC.calculate_structure_functions_single_pass(x, u, bins; backend = SFC.SerialBackend()) + @inferred SFC.calculate_structure_functions_single_pass(x, u, bins; backend = CB.SerialBackend()) u_batched = rand(FT, 2, N, 2) - @inferred SFC.calculate_structure_functions_single_pass(x, u_batched, bins; backend = SFC.SerialBackend()) + @inferred SFC.calculate_structure_functions_single_pass(x, u_batched, bins; backend = CB.SerialBackend()) # 2. Distributed Stability Check (if DistributedExt is loaded) # We'll just check if the method exists for now, or skip if not tested here. diff --git a/test/test_tensor_khm.jl b/test/test_tensor_khm.jl index e8e83f4..7288c5c 100644 --- a/test/test_tensor_khm.jl +++ b/test/test_tensor_khm.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using StructureFunctions: StructureFunctions as SF, Calculations as SFC, StructureFunctionTypes as SFT using Test: Test @@ -8,7 +9,7 @@ Test.@testset "Tensor Structure Functions" begin bins = [0.0, 1.1, 2.0] t2 = SFC.calculate_structure_function_tensor( - Val(2), x, u, bins; backend = SFC.SerialBackend(), + Val(2), x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionTensorSumsAndCounts, ) Test.@test t2 isa SF.StructureFunctionTensorSumsAndCounts{2} @@ -25,20 +26,20 @@ Test.@testset "Tensor Structure Functions" begin Test.@test t2.sums[:, :, 2] ≈ expected_bin2 # Default output is the averaged mean tensor D_ij(r) = sums ./ counts (per distance bin). - t2_mean = SFC.calculate_structure_function_tensor(Val(2), x, u, bins; backend = SFC.SerialBackend()) + t2_mean = SFC.calculate_structure_function_tensor(Val(2), x, u, bins; backend = CB.SerialBackend()) Test.@test t2_mean isa SF.StructureFunctionTensor{2} Test.@test t2_mean.values[:, :, 1] ≈ expected_bin1 ./ 2 Test.@test t2_mean.values[:, :, 2] ≈ expected_bin2 ./ 1 s2 = SFC.calculate_structure_function( - SFT.S2SF, x, u, bins; backend = SFC.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts + SFT.S2SF, x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionSumsAndCounts ) trace_sums = [sum(t2.sums[a, a, bin] for a in 1:2) for bin in axes(t2.sums, 3)] Test.@test trace_sums ≈ s2.sums Test.@test t2.counts == s2.counts t3 = SFC.calculate_structure_function_tensor( - Val(3), x, u, bins; backend = SFC.SerialBackend(), + Val(3), x, u, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionTensorSumsAndCounts, ) Test.@test t3 isa SF.StructureFunctionTensorSumsAndCounts{3} @@ -49,7 +50,7 @@ Test.@testset "Tensor Structure Functions" begin u_aux = cat(u, 2u; dims = 3) t2_aux = SFC.calculate_structure_function_tensor( - Val(2), x, u_aux, bins; backend = SFC.SerialBackend(), + Val(2), x, u_aux, bins; backend = CB.SerialBackend(), output_type = SF.StructureFunctionTensorSumsAndCounts, ) Test.@test size(t2_aux.sums) == (2, 2, 2, 2) diff --git a/test/test_triangle_outer_chunks.jl b/test/test_triangle_outer_chunks.jl index 0f28329..b5972e2 100644 --- a/test/test_triangle_outer_chunks.jl +++ b/test/test_triangle_outer_chunks.jl @@ -1,4 +1,5 @@ # Partition balance for O(N²) triangle pair loops (OhMyThreads outer chunks). +using ComputationalBackends: ComputationalBackends as CB using Test: Test using Random: Random using OhMyThreads: OhMyThreads as OMT @@ -48,10 +49,10 @@ Test.@testset "Triangle outer chunks (OMT RoundRobin)" begin inv = (:S2, :L2, :T2, :S3, :L3, :L1T2) sp_ref = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, value_bins; backend = SFC.SerialBackend(), + x, u, distance_bins, value_bins; backend = CB.SerialBackend(), ) sp_thr = SFC.calculate_structure_functions_single_pass_2d( - x, u, distance_bins, value_bins; backend = SFC.ThreadedBackend(), + x, u, distance_bins, value_bins; backend = CB.ThreadedBackend(), ) for k in inv Test.@test sp_thr[k].counts == sp_ref[k].counts @@ -61,12 +62,12 @@ Test.@testset "Triangle outer chunks (OMT RoundRobin)" begin sf_type = SFT.LongitudinalSecondOrderStructureFunctionType() r1 = SFC.calculate_structure_function( sf_type, x, u, distance_bins; - backend = SFC.SerialBackend(), verbose = false, show_progress = false, + backend = CB.SerialBackend(), verbose = false, show_progress = false, output_type = SFO.StructureFunctionSumsAndCounts, ) r2 = SFC.calculate_structure_function( sf_type, x, u, distance_bins; - backend = SFC.ThreadedBackend(), verbose = false, show_progress = false, + backend = CB.ThreadedBackend(), verbose = false, show_progress = false, output_type = SFO.StructureFunctionSumsAndCounts, ) Test.@test r2.counts == r1.counts diff --git a/test/threads_subprocess_smoke.jl b/test/threads_subprocess_smoke.jl index ca45074..bf530db 100644 --- a/test/threads_subprocess_smoke.jl +++ b/test/threads_subprocess_smoke.jl @@ -1,3 +1,4 @@ +using ComputationalBackends: ComputationalBackends as CB using Test: Test using OhMyThreads: OhMyThreads using StructureFunctions: StructureFunctions as SF @@ -11,7 +12,7 @@ serial = SF.calculate_structure_function( x, u, bins; - backend = SF.SerialBackend(), + backend = CB.SerialBackend(), verbose = false, show_progress = false, ) @@ -21,7 +22,7 @@ threaded = SF.calculate_structure_function( x, u, bins; - backend = SF.ThreadedBackend(), + backend = CB.ThreadedBackend(), verbose = false, show_progress = false, ) @@ -31,7 +32,7 @@ auto_backend = SF.calculate_structure_function( x, u, bins; - backend = SF.AutoThreadingBackend(), + backend = CB.AutoBackend(), verbose = false, show_progress = false, )