Repository navigation
Pack Rgba32 with a native conversion and one byte shuffle - #3288
Open
sebastienros wants to merge 2 commits into
Open
sebastienros wants to merge 2 commits into
sebastienros wants to merge 2 commits into
Conversation
Rgba32.Pack clamps the scaled vector to [0, 255] before the conversion, so the saturating Vector128.ConvertToInt32 and the four GetElement reads can be replaced by ConvertToInt32Native and one shuffle of the low bytes with the same result. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
Without hardware acceleration Vector128.Shuffle runs a software loop that is slower than four element reads (9% to 18% in a Stopwatch loop with DOTNET_EnableHWIntrinsic=0). Pack now uses the shuffle only when Vector128 is accelerated, and the Pack test runs with and without intrinsics so that both paths are checked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
|
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prerequisites
Description
The per-pixel conversions
Rgba32.FromUnassociatedScaledVector4(alsoFromScaledVector4andFromVector4) andRgba32.FromAssociatedScaledVector4end inRgba32.Pack.Packclamps the scaled vector to [0, 255] and then converted it withVector128.ConvertToInt32(the saturating conversion, which needs extra instructions on x64 for out-of-range lanes) and fourGetElementreads. After the clamp, every lane is finite and in [0, 255] (NaN maps to 0), soVector128.ConvertToInt32Nativegives the same integers, and one shuffle of the low byte of each lane gives the same pixel.The investigation, the prototype and the benchmark code are in the collapsed section at the end.
Change (
src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs,Pack): whenVector128is hardware accelerated,ConvertToInt32Native, thenVector128.Shufflewith the constant indices 0, 4, 8, 12 (the other indices are out of range and give 0),ToScalar()of theuint, reinterpreted asRgba32(its field order is R, G, B, A). Without acceleration,Packkeeps the previous conversion and fourGetElementreads: the software shuffle is slower there (9% to 18% in a Stopwatch loop withDOTNET_EnableHWIntrinsic=0). The scale, the half, and the clamp are unchanged.Test (
tests/ImageSharp.Tests/PixelFormats/Rgba32Tests.cs):Rgba32_FromVector4_RoundsClampsAndMapsNaNToZeroconverts 20,000 vectors (half of the components NaN, infinities, signed zeros, ±1e30, epsilon, and values next to the rounding midpoints and to 1) and compares each byte with the rule ofPack: scale by 255, add one half, clamp to [0, 255] with NaN as 0, truncate. It runs throughFeatureTestRunnerwith all intrinsics and with intrinsics disabled, so both paths are checked. With the clamp replaced byVector4.Max(vector, Vector4.Zero)(a temporary change), the test fails; with a wrong element index in the fallback (a temporary change), it fails too.Test run (macOS 15.8.3 arm64, .NET 10, with the PNG test inputs from Git LFS):
dotnet testoftests/ImageSharp.Testswith the filterRgba32|PixelOperations|PixelBlender|PorterDuff|SimdUtils, in Release and in Debug: 44,644 passed, 12 failed, 1 skipped.main(c6d486d) gives 44,643 passed and the same 12 failures in Release; the extra test is the new one. The 12 failures arePorterDuffOutputIsCorrect, whose reference images (Git LFS objects) were not fetched for this run.Measured (BenchmarkDotNet 0.15.8, .NET 10.0.15, Intel Xeon 2.30 GHz with AVX-512, shared cloud container; 5 warmup and 15 measured iterations of 100 ms; mean ± half of the 99.9% interval; both runs in one session). 4,096 random vectors converted in a loop (per pixel) or with one bulk call, the released package against this branch (Release build of
src/ImageSharp, referenced as an assembly by the same benchmark project; measured before the fallback change, which does not change the accelerated path):FromUnassociatedScaledVector4, per pixelFromAssociatedScaledVector4, per pixelFromUnassociatedScaledVector4Destructive, bulk (unchanged code)FromAssociatedScaledVector4Destructive, bulk (unchanged code)The standalone prototype of the investigation (with
Ssse3.Shuffleinstead ofVector128.Shuffle) took 4.36 ± 0.17 µs and 15.65 ± 0.23 µs in the same run, a little faster than this branch; the portableVector128.Shufflewas kept so that ARM64 is covered by the same code. The equality check of the benchmark project (2,000,000 vectors, a quarter of them NaN, infinities, signed zeros, out-of-range and tiny values) gives 0 differences between this branch and the prototype, which gives 0 against the released package.To measure this branch with the benchmark at the end, replace the
SixLabors.ImageSharppackage reference with<Reference Include="SixLabors.ImageSharp" HintPath="<Release build of src/ImageSharp>/SixLabors.ImageSharp.dll" />and remove the Fonts and PolygonClipper package references.The same saturating conversion and four
GetElementreads are in thePackofAbgr32,Abgr32P,Argb32,Argb32P,Bgra32,Bgra32P,L8, andLa16; they are not changed here.Not verified: AVX2-only machines, and the tests on ARM64 (the ARM64 timing is below); the real-workload gain (a profile of the SVG work in ImageSharp.Drawing puts
Packat 7.37% of the samples of a per-pixel caller).Measured on ARM64 (local, BenchmarkDotNet ShortRun)
BenchmarkDotNet 0.15.8,
Job.ShortRun(3 warmup and 3 measured iterations, 1 launch), .NET 10.0.15 (Arm64 RyuJIT), Apple M4 Pro (14 cores, 48 GB; 128-bit AdvSIMD, no 256- or 512-bit vectors), macOS 15.8.3; mean ± half of the 99.9% interval; two rounds,mainthen this branch, one benchmark process at a time. Both sides are Release builds ofsrc/ImageSharpfrom source, referenced as assemblies by thePerPixelPackbenchmark at the end (library methods only; the prototype uses x86 intrinsics):mainatc6d486d, this branch at4abf05c. "Ratio" is the faster branch round over the fastermainround. A round whose Error is larger than about half of its mean was disturbed (the M4 Pro mixes performance and efficiency cores, and 3 iterations give a wide interval); read those cells with care.main, round 1 / 2FromUnassociatedScaledVector4, per pixelFromAssociatedScaledVector4, per pixelFromUnassociatedScaledVector4Destructive, bulk (unchanged code)FromAssociatedScaledVector4Destructive, bulk (unchanged code)On ARM64 the portable
Vector128.Shufflepath makes the per-pixel conversions 23% (unassociated) and 14% (associated) faster; the bulk methods, which do not callPack, are unchanged (1.00). The second branch round of the table was disturbed (its Errors are as large as its means), so a check ran with 3 launches per round (Job.ShortRun.WithLaunchCount(3), two rounds, 6 launches per side): unassociated per pixel 3.03 to 3.13 µs onmainagainst 2.33 to 2.38 µs on this branch in every launch (0.77), associated per pixel 7.92 to 7.96 against 6.86 to 7.09 µs (0.87), and the bulk methods 1.00 and 1.01 (fastest launches). This covers the timing on ARM64 only: the tests were not run on this machine.Investigation and benchmark code
Investigation
Source:
PixelFormats/PixelImplementations/Rgba32.cs,Pack(Vector4):FromAssociatedScaledVector4callsPixelOperations<Rgba32>.FromAssociatedScaledVector4, which appliesPixelOperations.UnassociateOperator.Apply(an alpha clamp, a division,ClampToPixelRange) and thenFromUnassociatedScaledVector4, that isPack.Measurement in the SVG work in ImageSharp.Drawing (SVG_DESIGN.md section 20.1, "Texture brush",
perf, FilterShadows at 1000 px, one thread, ImageSharp 5.0.0-alpha.0.38): the per-pixelTPixel.FromAssociatedScaledVector4inside the generic texture brush showedUnassociateOperator.ApplyandRgba32.Packas two calls that were not inlined, 8.75% and 7.37% of the samples. In a small loop (the benchmark below) the JIT inlines both, so the "not inlined" part depends on the caller; the cost ofPackitself shows in both.Measured in isolation (below): per million pixels, the library per-pixel unassociated form takes 2.7 to 3.8 ms (two runs), the associated form 6.3 to 6.4 ms, the bulk forms 0.33 ms and 1.8 to 2.1 ms; the prototype per-pixel forms 1.05 ms and 3.8 to 3.9 ms.
Benchmark to validate
Machine: Intel Xeon 2.30 GHz, 4 cores (shared cloud container, AVX-512: x86-64-v4), Ubuntu 24.04, .NET 10.0.15 (SDK 10.0.404), BenchmarkDotNet 0.15.8. Job: 5 warmup and 15 measured iterations of 100 ms, 1 launch. Error is half of the 99.9% confidence interval.
4,096 random vectors (alpha in [0, 1]; the associated input is the straight input times its alpha), converted in a loop with the library method, with the prototype, and with the bulk method:
A first run gave 15.66 ± 0.10 µs for the library unassociated loop (prototype 4.34 µs), 26.35 µs for the associated loop (prototype 16.07 µs), and the same bulk times; the library unassociated loop is the one cell that moved between the runs.
The equality check converts 2,000,000 vectors with both the library and the prototype, for both the associated and the unassociated method: a quarter of them are made of NaN, infinities, signed zeros, out-of-range and tiny values, the others random associated colours (some 1.2 times out of range). Result: 0 differences.
What result means the fix works: the patched
Rgba32.FromUnassociatedScaledVector4andFromAssociatedScaledVector4take the prototype times (within the error), and the equality check passes against the patched library.How to build and run:
Bench.csproj,NuGet.config,Program.cs, and the.csfiles).dotnet build -c Debug(the project sets<Optimize>true</Optimize>; see the note on the license check).dotnet bin/Debug/net10.0/Bench.dll check.dotnet bin/Debug/net10.0/Bench.dll --filter '*.PerPixelPack.*'.Note on the build: the Six Labors packages run a license check in every build whose configuration does not start with
Debug; without a license key, a Release build fails. The project therefore builds theDebugconfiguration with<Optimize>true</Optimize>, and the job usesWithCustomBuildConfiguration("Debug"), so BenchmarkDotNet builds its generated project the same way and accepts it as optimized. With a license key set (SixLaborsLicenseKey), a Release build and the default job work too.Bench.csproj:NuGet.config(the prerelease packages are on the Six Labors feed):Program.cs:ProtoPack.cs:PackChecks.cs:PackBenchmarks.cs: