Skip to content

Convert the row tails of SimdUtils byte and float conversions with narrower vectors - #3289

Open
sebastienros wants to merge 3 commits into
SixLabors:mainfrom
sebastienros:perf/simdutils-vector-tails
Open

sebastienros wants to merge 3 commits into
SixLabors:mainfrom
sebastienros:perf/simdutils-vector-tails

Conversation

@sebastienros

Copy link
Copy Markdown

Prerequisites

  • I have written a descriptive pull-request title
  • I have verified that there are no overlapping pull-requests open
  • I have verified that I am following the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules 👮.
  • I have provided test coverage for my change (where applicable)

Description

SimdUtils.ByteToNormalizedFloat and SimdUtils.NormalizedFloatToByteSaturate / FloatToByteSaturate (and their TAlpha forms) converted everything after the last whole step of the widest vector (64 bytes with AVX-512, 32 with AVX2, 16 with SSE) one element at a time; the byte-to-float remainder divided each byte by 255. Every row whose length is not a multiple of 16 Rgba32 pixels (with AVX-512) paid for up to 15 pixels in scalar code, and rows shorter than 16 pixels were converted in scalar code only. The blender converts each row to Vector4 and back, so every short span of a fill or a stroke paid two scalar tails.

The investigation that this change follows (profiles, prototype, equality check, and the full benchmark code) is in the collapsed section at the end.

Change (src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs): ByteToNormalizedFloatReduce<TAlpha> and FloatToByteSaturateReduce<TAlpha> now continue after the main loop with narrower vector steps, in new private methods ByteToNormalizedFloatTail<TAlpha> and FloatToByteSaturateTail<TAlpha>:

  • 16 elements per step with 512-bit vectors, 8 per step with 256-bit vectors, then 4 per step (one RGBA pixel) with 128-bit vectors; the last 0 to 3 elements still go to the existing scalar remainder.
  • Each element uses the arithmetic of the main loop: byte to float is FusedMultiplyAdd(f, high, f * low) with the same reciprocal parts; float to byte is TAlpha.Apply, ClampToFinite to [0, 255 / scale] (NaN to 0), and ConvertToInt32Native(x * scale + 0.5). After the clamp the integers are 0 to 255, so the truncating narrows give the bytes of the saturating narrow. The output is the same for every length and input.
  • Each step is a multiple of 4 elements and starts at a multiple of 4, so TAlpha sees whole RGBA groups. Each step loads before it stores and the steps move forward, which the staging in Rgba32CompatiblePixelOperations<TPixel>.Unpack and the three-byte packing in Pack rely on (the reason for narrower steps instead of one overlapping vector).
  • A row of whole main-loop steps skips the call (the first measurement showed about 1 ns for the call on 16-pixel rows).

Tests (tests/ImageSharp.Tests/Common/SimdUtilsTests.cs): ByteToNormalizedFloat_EveryShortLength_MatchesOracle_AtEveryVectorWidth and FloatToByteSaturate_EveryShortLength_MatchesOracle_AtEveryVectorWidth run every length from 0 to 130 under each width (all features, AVX-512 off, AVX2 off, all intrinsics off) through FeatureTestRunner, against a scalar oracle: byte / 255 in double, and NaN to 0, clamp, truncate(x * 255 + 0.5) for floats with NaN, infinities, signed zeros, and out-of-range values; and the AssociateOperator / UnassociateOperator forms per pixel. With the 4-float step's rounding constant changed to 0.49 (a temporary change), the float test fails.

Test run (macOS 15.8.3 arm64, .NET 10, with the PNG test inputs from Git LFS): dotnet test of tests/ImageSharp.Tests with the filter SimdUtils|PixelOperations|PixelBlender|PorterDuff, in Release and in Debug: 44,132 passed, 12 failed, 1 skipped. The 12 failures are PorterDuffOutputIsCorrect, which fail the same way on main (c6d486d): their 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). The RowConversion benchmark at the end: one row of Rgba32 to Vector4 (PixelOperations<Rgba32>.ToUnassociatedScaledVector4) and back (FromUnassociatedScaledVector4Destructive), the released package against this branch (Release build of src/ImageSharp, referenced as an assembly by the same benchmark project: replace the SixLabors.ImageSharp package reference with <Reference Include="SixLabors.ImageSharp" HintPath="<Release build of src/ImageSharp>/SixLabors.ImageSharp.dll" />):

Pixels Direction Released 5.0.0-alpha.0.38 This branch Ratio
1 to Rgba32 6.8401 ns ± 0.0158 ns 4.2701 ns ± 0.1003 ns 0.62
1 to Vector4 5.4801 ns ± 0.1127 ns 3.2315 ns ± 0.0360 ns 0.59
3 to Rgba32 14.2365 ns ± 0.3128 ns 6.8453 ns ± 0.0607 ns 0.48
3 to Vector4 7.8949 ns ± 0.2029 ns 4.3842 ns ± 0.0713 ns 0.56
4 to Rgba32 19.4592 ns ± 0.1505 ns 5.6972 ns ± 0.2166 ns 0.29
4 to Vector4 10.5934 ns ± 0.3056 ns 3.8712 ns ± 0.1436 ns 0.37
7 to Rgba32 35.0572 ns ± 1.2945 ns 10.4796 ns ± 0.0517 ns 0.30
7 to Vector4 19.9943 ns ± 0.0761 ns 5.3544 ns ± 0.0818 ns 0.27
8 to Rgba32 36.9877 ns ± 0.2330 ns 7.5101 ns ± 0.1910 ns 0.20
8 to Vector4 23.5194 ns ± 0.6406 ns 4.3155 ns ± 0.1447 ns 0.18
15 to Rgba32 75.2601 ns ± 0.1564 ns 12.8729 ns ± 0.2300 ns 0.17
15 to Vector4 45.1609 ns ± 0.0335 ns 6.9546 ns ± 0.0773 ns 0.15
16 to Rgba32 7.1040 ns ± 0.3156 ns 7.0162 ns ± 0.2953 ns 0.99
16 to Vector4 5.9887 ns ± 0.1942 ns 5.9107 ns ± 0.3033 ns 0.99
17 to Rgba32 12.4647 ns ± 0.3378 ns 10.0617 ns ± 0.0936 ns 0.81
17 to Vector4 9.7736 ns ± 0.4941 ns 8.0436 ns ± 0.3911 ns 0.82
31 to Rgba32 88.1424 ns ± 1.8506 ns 17.9230 ns ± 0.4795 ns 0.20
31 to Vector4 46.7196 ns ± 0.8184 ns 11.0418 ns ± 0.3182 ns 0.24
32 to Rgba32 11.5647 ns ± 0.3772 ns 12.0956 ns ± 0.0799 ns 1.05
32 to Vector4 9.2071 ns ± 0.3033 ns 9.1703 ns ± 0.4018 ns 1.00
63 to Rgba32 109.5043 ns ± 4.3971 ns 33.0308 ns ± 1.4367 ns 0.30
63 to Vector4 50.8559 ns ± 1.3195 ns 18.6025 ns ± 0.6122 ns 0.37
64 to Rgba32 21.9123 ns ± 0.3186 ns 22.4120 ns ± 0.5537 ns 1.02
64 to Vector4 18.4415 ns ± 1.8403 ns 14.3202 ns ± 0.5795 ns 0.78
100 to Rgba32 54.6579 ns ± 1.6418 ns 36.9310 ns ± 1.8050 ns 0.68
100 to Vector4 28.5854 ns ± 0.2447 ns 22.9477 ns ± 0.0745 ns 0.80
255 to Rgba32 165.4725 ns ± 5.5673 ns 92.3260 ns ± 0.5878 ns 0.56
255 to Vector4 84.0581 ns ± 1.3073 ns 58.2958 ns ± 0.2810 ns 0.69
256 to Rgba32 82.9484 ns ± 0.5776 ns 82.4494 ns ± 4.1001 ns 0.99
256 to Vector4 54.7725 ns ± 1.1688 ns 56.5368 ns ± 0.9368 ns 1.03

Rows that end with a tail are 1.2 to 6.7 times faster. Rows of whole 16-pixel steps are unchanged within the error, except 32 pixels to Rgba32, 5% slower (11.6 ± 0.4 against 12.1 ± 0.1 ns). The equality check of the benchmark project (every length from 0 to 300 pixels, 20 random rows each, half of the float rows with special values) gives 0 differing bytes and floats between this branch and the prototype, which gives 0 against the released package.

Not verified: AVX2-only and SSE-only machines (only through the feature switches of the tests on this AVX-512 machine), the tests on ARM64 (the ARM64 timing is below), and the effect on a real workload: the profiles of the SVG work in ImageSharp.Drawing put the scalar remainders at 4.6% to 21% of the samples of drawing workloads.

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, main then this branch, one benchmark process at a time. Both sides are Release builds of src/ImageSharp from source, referenced as assemblies by the RowConversion benchmark at the end (library methods only; the prototype uses x86 intrinsics): main at c6d486d, this branch at 7d2378e. "Ratio" is the faster branch round over the faster main round. 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.

With 128-bit vectors only, the main loop converts 16 bytes (4 pixels) per step, so on this machine only rows that are not a multiple of 4 pixels have a tail (1 to 3 pixels); this branch converts it with the 4-element (one pixel) Vector128 step, so for Rgba32 rows the scalar remainder is empty on this machine.

Pixels Direction main, round 1 / 2 This branch, round 1 / 2 Ratio Allocated
1 to Vector4 3.706 ± 0.175 / 3.590 ± 6.983 ns 3.028 ± 0.068 / 3.152 ± 0.749 ns 0.84 0 → 0
1 to Rgba32 3.413 ± 0.414 / 3.529 ± 2.106 ns 2.938 ± 0.162 / 3.103 ± 0.701 ns 0.86 0 → 0
3 to Vector4 5.540 ± 0.142 / 5.608 ± 0.388 ns 5.750 ± 0.640 / 5.798 ± 0.541 ns 1.04 0 → 0
3 to Rgba32 6.254 ± 0.029 / 6.368 ± 0.087 ns 3.407 ± 0.072 / 3.586 ± 1.731 ns 0.54 0 → 0
4 to Vector4 5.138 ± 24.68 / 4.170 ± 0.336 ns 5.028 ± 24.50 / 3.971 ± 0.177 ns 0.95 0 → 0
4 to Rgba32 2.894 ± 0.076 / 2.976 ± 0.006 ns 3.007 ± 0.104 / 3.125 ± 0.242 ns 1.04 0 → 0
7 to Vector4 11.16 ± 87.02 / 8.218 ± 0.282 ns 5.910 ± 0.372 / 8.433 ± 34.68 ns 0.72 0 → 0
7 to Rgba32 8.100 ± 0.751 / 8.203 ± 0.231 ns 8.575 ± 11.22 / 9.155 ± 11.79 ns 1.06 0 → 0
8 to Vector4 4.846 ± 0.313 / 4.848 ± 0.180 ns 7.943 ± 4.697 / 7.233 ± 47.27 ns 1.49 0 → 0
8 to Rgba32 4.147 ± 0.355 / 5.896 ± 24.58 ns 5.533 ± 31.87 / 6.155 ± 19.13 ns 1.33 0 → 0
15 to Vector4 9.617 ± 0.236 / 12.63 ± 13.85 ns 8.204 ± 7.761 / 8.209 ± 2.653 ns 0.85 0 → 0
15 to Rgba32 11.03 ± 0.087 / 11.61 ± 13.47 ns 8.871 ± 3.150 / 8.517 ± 0.786 ns 0.77 0 → 0
16 to Vector4 6.445 ± 0.124 / 11.32 ± 37.14 ns 6.834 ± 0.470 / 6.640 ± 2.159 ns 1.03 0 → 0
16 to Rgba32 8.877 ± 19.85 / 8.333 ± 2.117 ns 8.205 ± 1.443 / 8.150 ± 0.752 ns 0.98 0 → 0
17 to Vector4 8.627 ± 0.146 / 8.994 ± 1.364 ns 8.036 ± 1.716 / 7.762 ± 0.260 ns 0.90 0 → 0
17 to Rgba32 9.809 ± 0.389 / 9.932 ± 1.382 ns 9.087 ± 0.203 / 9.097 ± 0.421 ns 0.93 0 → 0
31 to Vector4 15.36 ± 66.67 / 13.23 ± 0.488 ns 11.44 ± 0.496 / 11.32 ± 0.259 ns 0.86 0 → 0
31 to Rgba32 19.82 ± 1.851 / 20.00 ± 1.025 ns 17.35 ± 0.208 / 17.43 ± 1.621 ns 0.88 0 → 0
32 to Vector4 9.969 ± 5.182 / 9.918 ± 0.634 ns 9.846 ± 2.059 / 9.945 ± 0.885 ns 0.99 0 → 0
32 to Rgba32 17.21 ± 1.085 / 16.91 ± 0.623 ns 26.33 ± 28.60 / 16.98 ± 0.207 ns 1.00 0 → 0
63 to Vector4 21.80 ± 0.587 / 21.61 ± 0.111 ns 29.98 ± 20.29 / 18.98 ± 2.834 ns 0.88 0 → 0
63 to Rgba32 37.84 ± 0.682 / 37.89 ± 0.840 ns 50.76 ± 36.67 / 36.99 ± 57.10 ns 0.98 0 → 0
64 to Vector4 18.08 ± 1.494 / 17.91 ± 3.588 ns 19.09 ± 7.749 / 25.28 ± 57.33 ns 1.07 0 → 0
64 to Rgba32 35.19 ± 6.043 / 46.32 ± 141.8 ns 35.45 ± 22.74 / 37.22 ± 86.13 ns 1.01 0 → 0
100 to Vector4 29.02 ± 0.909 / 42.40 ± 17.18 ns 30.38 ± 25.06 / 42.62 ± 50.03 ns 1.05 0 → 0
100 to Rgba32 54.85 ± 0.831 / 57.00 ± 72.91 ns 54.54 ± 0.038 / 55.07 ± 8.807 ns 0.99 0 → 0
255 to Vector4 80.41 ± 1.679 / 123.7 ± 119.2 ns 74.49 ± 1.294 / 74.50 ± 1.174 ns 0.93 0 → 0
255 to Rgba32 142.7 ± 15.97 / 154.1 ± 244.9 ns 141.0 ± 2.513 / 143.9 ± 29.92 ns 0.99 0 → 0
256 to Vector4 79.29 ± 26.70 / 76.21 ± 3.780 ns 74.62 ± 2.079 / 74.74 ± 1.756 ns 0.98 0 → 0
256 to Rgba32 142.7 ± 53.37 / 140.7 ± 4.116 ns 140.6 ± 0.699 / 140.8 ± 2.232 ns 1.00 0 → 0

Rows with a tail (1, 3, 7, 15, 17, 31, 63, 255 pixels) are mostly faster: 0.54 to 0.93, the most for 3 pixels to Rgba32 (6.25 → 3.41 ns); 3 pixels to Vector4, and 7, 63 and 255 pixels to Rgba32, stay at 0.98 to 1.06. Rows of whole steps (4, 8, 16, 32, 64, 100, 256 pixels) should not change; they are at 0.95 to 1.07, except 8 pixels (1.49 and 1.33), where both branch rounds were disturbed.

Check of the rows of whole steps with 3 launches per round (Job.ShortRun.WithLaunchCount(3), Pixels 4, 8, 16, 64, two rounds), mean ± Error in ns, round 1 / 2:

Pixels Direction main This branch Ratio
4 to Vector4 3.863 ± 0.135 / 4.067 ± 0.147 4.336 ± 0.167 / 4.201 ± 0.623 1.09
4 to Rgba32 2.944 ± 0.073 / 3.151 ± 0.049 4.329 ± 2.534 / 3.294 ± 0.115 1.12
8 to Vector4 4.764 ± 0.111 / 5.631 ± 1.662 5.801 ± 2.224 / 4.947 ± 0.160 1.04
8 to Rgba32 5.420 ± 2.933 / 4.142 ± 0.663 4.620 ± 0.071 / 5.555 ± 1.960 1.12
16 to Vector4 7.488 ± 2.666 / 6.837 ± 0.099 7.022 ± 0.338 / 6.888 ± 0.685 1.01
16 to Rgba32 10.688 ± 3.842 / 8.375 ± 0.276 8.795 ± 0.245 / 8.200 ± 0.056 0.98
64 to Vector4 24.316 ± 12.260 / 18.019 ± 0.111 23.131 ± 8.507 / 18.072 ± 0.039 1.00
64 to Rgba32 35.612 ± 0.182 / 34.936 ± 0.652 42.471 ± 15.486 / 35.078 ± 0.741 1.00

With more launches the 8-pixel rows are at 1.04 and 1.12 instead of 1.49 and 1.33, and 16 and 64 pixels are at 0.98 to 1.01. 4-pixel rows stay slower: 1.09 to Vector4 (3.86 and 4.07 against 4.34 and 4.20 ns) and 1.12 to Rgba32 (2.94 and 3.15 against 3.29 ns in the undisturbed round), about 0.3 ns per call. A 4-pixel row is one main-loop step and skips the tail, so this is the cost of the extra length test or of a change of code layout.

Investigation and benchmark code

Investigation

Source path (one row of Rgba32 to Vector4 and back, as PixelBlender<TPixel> calls it for every blended row):

  • PixelOperations<Rgba32>.ToUnassociatedScaledVector4 → Rgba32.PixelOperations.ToUnassociatedVector4 → SimdUtils.ByteToNormalizedFloat (Common/Helpers/SimdUtils.Convert.cs). HwIntrinsics.ByteToNormalizedFloatReduce (Common/Helpers/SimdUtils.HwIntrinsics.cs) takes length - length % Vector512<byte>.Count bytes; ConvertByteToNormalizedFloatRemainder converts the rest with byte / (float)byte.MaxValue, one byte per iteration ([MethodImpl(MethodImplOptions.NoInlining)]).
  • PixelOperations<Rgba32>.FromUnassociatedScaledVector4Destructive → Rgba32.PixelOperations.FromUnassociatedVector4Destructive → SimdUtils.NormalizedFloatToByteSaturate. HwIntrinsics.FloatToByteSaturateReduce takes whole multiples of 64 floats; ConvertFloatToByteRemainder converts the rest with ConvertToByte, one float per iteration.
  • The TAlpha forms (ByteToNormalizedFloat<TAlpha>, FloatToByteSaturate<TAlpha>) use the same split; their remainders run TAlpha.Apply per pixel and then the same scalar conversion.

Profiles from the SVG work in ImageSharp.Drawing (src/ImageSharp.Drawing/Svg/SVG_DESIGN.md, perf with one thread, shares of all samples):

  • Section 18.5, StreetMap document at 1000 px (roads are rows of 4 to 15 pixels): ConvertFloatToByteRemainder 7.1% and ConvertByteToNormalizedFloatRemainder 4.6% (measured on ImageSharp 4.1.2, which has the same split).
  • Section 19.1, Icons document at 1000 px after the opaque fill change: the scalar remainders were 8.9% and 8.9% of the samples (ImageSharp 4.1.2); section 19.2 after the clear change: ConvertFloatToByteRemainder 9.8%.
  • Section 19.3, replay of the FilterShadows scene (on ImageSharp 5.0.0-alpha.0.38): the scalar remainders of the row conversions of the blender were 21% of the samples, with rows of about 100 pixels.

The isolated benchmark below reproduces the cost: a row of 15 pixels takes 45.2 ns to convert to vectors, a row of 16 pixels 6.2 ns; 63 pixels take 50.9 ns, 64 pixels 18.5 ns.

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.

The benchmark converts one row of Rgba32 (random bytes) to Vector4 with PixelOperations<Rgba32>.Instance.ToUnassociatedScaledVector4, and one row of Vector4 back with FromUnassociatedScaledVector4Destructive, against the prototype ProtoConvert (the main loop of the library plus the narrower steps). Neither allocates.

Measured (mean per call; this run used a build made from the files below in an empty directory; a first run gave the same values within a few percent, for example 45.2 → 3.6 ns at 15 pixels):

Method Pixels Mean Error StdDev Allocated
'ToVector4, library' 1 5.4801 ns 0.1127 ns 0.1054 ns -
'ToVector4, prototype' 1 0.4468 ns 0.0539 ns 0.0421 ns -
'FromVector4, library' 1 6.8401 ns 0.0158 ns 0.0123 ns -
'FromVector4, prototype' 1 1.3769 ns 0.1364 ns 0.1139 ns -
'ToVector4, library' 3 7.8949 ns 0.2029 ns 0.1799 ns -
'ToVector4, prototype' 3 1.6184 ns 0.0322 ns 0.0301 ns -
'FromVector4, library' 3 14.2365 ns 0.3128 ns 0.2773 ns -
'FromVector4, prototype' 3 4.2471 ns 0.0579 ns 0.0542 ns -
'ToVector4, library' 4 10.5934 ns 0.3056 ns 0.2858 ns -
'ToVector4, prototype' 4 0.6590 ns 0.0269 ns 0.0252 ns -
'FromVector4, library' 4 19.4592 ns 0.1505 ns 0.1175 ns -
'FromVector4, prototype' 4 1.3785 ns 0.0494 ns 0.0463 ns -
'ToVector4, library' 7 19.9943 ns 0.0761 ns 0.0711 ns -
'ToVector4, prototype' 7 2.2301 ns 0.1152 ns 0.1021 ns -
'FromVector4, library' 7 35.0572 ns 1.2945 ns 1.2108 ns -
'FromVector4, prototype' 7 6.4401 ns 0.4880 ns 0.4565 ns -
'ToVector4, library' 8 23.5194 ns 0.6406 ns 0.5679 ns -
'ToVector4, prototype' 8 1.3151 ns 0.1061 ns 0.0992 ns -
'FromVector4, library' 8 36.9877 ns 0.2330 ns 0.2066 ns -
'FromVector4, prototype' 8 2.6720 ns 0.0066 ns 0.0062 ns -
'ToVector4, library' 15 45.1609 ns 0.0335 ns 0.0297 ns -
'ToVector4, prototype' 15 3.8040 ns 0.0242 ns 0.0214 ns -
'FromVector4, library' 15 75.2601 ns 0.1564 ns 0.1463 ns -
'FromVector4, prototype' 15 9.7373 ns 0.6177 ns 0.5158 ns -
'ToVector4, library' 16 5.9887 ns 0.1942 ns 0.1817 ns -
'ToVector4, prototype' 16 2.1502 ns 0.1170 ns 0.1094 ns -
'FromVector4, library' 16 7.1040 ns 0.3156 ns 0.2797 ns -
'FromVector4, prototype' 16 5.1745 ns 0.1922 ns 0.1605 ns -
'ToVector4, library' 17 9.7736 ns 0.4941 ns 0.4622 ns -
'ToVector4, prototype' 17 3.2387 ns 0.3582 ns 0.3350 ns -
'FromVector4, library' 17 12.4647 ns 0.3378 ns 0.3160 ns -
'FromVector4, prototype' 17 6.4942 ns 0.1733 ns 0.1353 ns -
'ToVector4, library' 31 46.7196 ns 0.8184 ns 0.7655 ns -
'ToVector4, prototype' 31 6.5655 ns 0.3718 ns 0.3295 ns -
'FromVector4, library' 31 88.1424 ns 1.8506 ns 1.5454 ns -
'FromVector4, prototype' 31 14.8839 ns 0.3320 ns 0.2943 ns -
'ToVector4, library' 32 9.2071 ns 0.3033 ns 0.2837 ns -
'ToVector4, prototype' 32 5.3497 ns 0.1717 ns 0.1607 ns -
'FromVector4, library' 32 11.5647 ns 0.3772 ns 0.2945 ns -
'FromVector4, prototype' 32 9.6834 ns 0.1900 ns 0.1586 ns -
'ToVector4, library' 63 50.8559 ns 1.3195 ns 1.1697 ns -
'ToVector4, prototype' 63 14.0677 ns 0.2426 ns 0.2269 ns -
'FromVector4, library' 63 109.5043 ns 4.3971 ns 3.8979 ns -
'FromVector4, prototype' 63 27.3078 ns 1.0834 ns 0.9604 ns -
'ToVector4, library' 64 18.4415 ns 1.8403 ns 1.7214 ns -
'ToVector4, prototype' 64 10.0954 ns 0.2467 ns 0.2187 ns -
'FromVector4, library' 64 21.9123 ns 0.3186 ns 0.2487 ns -
'FromVector4, prototype' 64 20.2935 ns 0.6165 ns 0.5767 ns -
'ToVector4, library' 100 28.5854 ns 0.2447 ns 0.2289 ns -
'ToVector4, prototype' 100 20.0700 ns 0.3602 ns 0.3193 ns -
'FromVector4, library' 100 54.6579 ns 1.6418 ns 1.3710 ns -
'FromVector4, prototype' 100 31.8859 ns 0.1337 ns 0.1044 ns -
'ToVector4, library' 255 84.0581 ns 1.3073 ns 1.1589 ns -
'ToVector4, prototype' 255 49.5768 ns 1.1112 ns 0.9279 ns -
'FromVector4, library' 255 165.4725 ns 5.5673 ns 4.9353 ns -
'FromVector4, prototype' 255 90.6639 ns 3.6949 ns 3.0854 ns -
'ToVector4, library' 256 54.7725 ns 1.1688 ns 0.9760 ns -
'ToVector4, prototype' 256 46.4157 ns 1.0114 ns 0.9461 ns -
'FromVector4, library' 256 82.9484 ns 0.5776 ns 0.5403 ns -
'FromVector4, prototype' 256 84.1863 ns 0.7159 ns 0.5978 ns -

The equality check compares the prototype with the library for every row length from 0 to 300 pixels, 20 random rows each (903,000 pixels per direction; half of the float rows hold NaN, infinities, signed zeros, and values out of range), plus the exhaustive check of the reciprocal product. Result: 0 differing bytes and floats.

What result means the fix works: the patched library gives the times of the prototype column for the lengths that end with a tail (1 to 15, 17, 31, 63, 100, 255 pixels), the same times as today for multiples of 16 pixels, and the equality check (run against the patched library and a copy of today's scalar reference) shows no difference.

How to build and run:

  1. Put the files below in one directory (Bench.csproj, NuGet.config, Program.cs, and the .cs files).
  2. dotnet build -c Debug (the project sets <Optimize>true</Optimize>; see the note on the license check).
  3. Equality check: dotnet bin/Debug/net10.0/Bench.dll check.
  4. Benchmark: dotnet bin/Debug/net10.0/Bench.dll --filter '*.RowConversion.*'.

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 the Debug configuration with <Optimize>true</Optimize>, and the job uses WithCustomBuildConfiguration("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:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>disable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <ImplicitUsings>enable</ImplicitUsings>
    <Optimize>true</Optimize>
    <DebugType>portable</DebugType>
    <TieredPGO>true</TieredPGO>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
    <PackageReference Include="SixLabors.ImageSharp" Version="5.0.0-alpha.0.38" />
    <PackageReference Include="SixLabors.Fonts" Version="3.2.1" />
    <PackageReference Include="SixLabors.PolygonClipper" Version="2.0.0-alpha.0.2" />
  </ItemGroup>
</Project>

NuGet.config (the prerelease packages are on the Six Labors feed):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="feedz-sixlabors" value="https://f.feedz.io/sixlabors/sixlabors/nuget/index.json" />
  </packageSources>
</configuration>

Program.cs:

using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using Perfolizer.Horology;
using Bench;

if (args.Length > 0 && args[0] == "check")
{
    return ConvertChecks.Run();
}

// The Six Labors packages check for a license in builds whose configuration does not start with "Debug".
// Bench.csproj sets Optimize=true, so the Debug build is optimized; BenchmarkDotNet builds with that configuration.
IConfig config = DefaultConfig.Instance
    .AddJob(Job.Default
        .WithCustomBuildConfiguration("Debug")
        .WithWarmupCount(5)
        .WithIterationCount(15)
        .WithIterationTime(TimeInterval.FromMilliseconds(100))
        .WithLaunchCount(1));

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config);
return 0;

ProtoConvert.cs:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;

namespace Bench;

/// <summary>
/// Prototype of the row conversions of SimdUtils (SixLabors.ImageSharp 5.0.0-alpha.0.38) with a vector tail.
/// The 64-byte main loop is the loop of the library (AVX-512 width). The library converts the rest
/// (up to 63 bytes) one byte at a time with a float division or a scalar clamp; the prototype converts it
/// with 16-byte steps, then 4-byte steps, then single bytes.
/// Every element is computed with the same IEEE operations as the library, so the bytes and floats are equal.
/// </summary>
public static class ProtoConvert
{
    private const float ReciprocalHigh = (float)(1D / byte.MaxValue);
    private const float ReciprocalLow = (float)((1D / byte.MaxValue) - ReciprocalHigh);

    /// <summary>Bytes to floats in [0, 1]. Same contract as SimdUtils.ByteToNormalizedFloat.</summary>
    public static void ByteToNormalizedFloat(ReadOnlySpan<byte> source, Span<float> destination)
    {
        ref byte sourceBase = ref MemoryMarshal.GetReference(source);
        ref float destinationBase = ref MemoryMarshal.GetReference(destination);
        nuint length = (uint)source.Length;
        nuint i = 0;

        Vector512<float> high = Vector512.Create(ReciprocalHigh);
        Vector512<float> low = Vector512.Create(ReciprocalLow);

        // Main loop of the library: 64 bytes per step.
        for (; i + 64 <= length; i += 64)
        {
            Vector512<float> f0 = Vector512.ConvertToSingle(Avx512F.ConvertToVector512Int32(Vector128.LoadUnsafe(ref sourceBase, i)));
            Vector512<float> f1 = Vector512.ConvertToSingle(Avx512F.ConvertToVector512Int32(Vector128.LoadUnsafe(ref sourceBase, i + 16)));
            Vector512<float> f2 = Vector512.ConvertToSingle(Avx512F.ConvertToVector512Int32(Vector128.LoadUnsafe(ref sourceBase, i + 32)));
            Vector512<float> f3 = Vector512.ConvertToSingle(Avx512F.ConvertToVector512Int32(Vector128.LoadUnsafe(ref sourceBase, i + 48)));
            Vector512.FusedMultiplyAdd(f0, high, f0 * low).StoreUnsafe(ref destinationBase, i);
            Vector512.FusedMultiplyAdd(f1, high, f1 * low).StoreUnsafe(ref destinationBase, i + 16);
            Vector512.FusedMultiplyAdd(f2, high, f2 * low).StoreUnsafe(ref destinationBase, i + 32);
            Vector512.FusedMultiplyAdd(f3, high, f3 * low).StoreUnsafe(ref destinationBase, i + 48);
        }

        // Tail, new: one 16-byte group widens to one 512-bit float vector.
        for (; i + 16 <= length; i += 16)
        {
            Vector512<float> f = Vector512.ConvertToSingle(Avx512F.ConvertToVector512Int32(Vector128.LoadUnsafe(ref sourceBase, i)));
            Vector512.FusedMultiplyAdd(f, high, f * low).StoreUnsafe(ref destinationBase, i);
        }

        // Tail, new: one pixel (4 bytes) at a time in a 128-bit vector.
        Vector128<float> high128 = Vector128.Create(ReciprocalHigh);
        Vector128<float> low128 = Vector128.Create(ReciprocalLow);
        for (; i + 4 <= length; i += 4)
        {
            uint packed = Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref sourceBase, i));
            Vector128<float> f = Vector128.ConvertToSingle(Sse41.ConvertToVector128Int32(Vector128.CreateScalarUnsafe(packed).AsByte()));
            Vector128.FusedMultiplyAdd(f, high128, f * low128).StoreUnsafe(ref destinationBase, i);
        }

        // Single bytes: the same two-term product, which equals byte / 255F for every byte (checked exhaustively).
        for (; i < length; i++)
        {
            float f = Unsafe.Add(ref sourceBase, i);
            Unsafe.Add(ref destinationBase, i) = MathF.FusedMultiplyAdd(f, ReciprocalHigh, f * ReciprocalLow);
        }
    }

    /// <summary>Floats in [0, 1] to bytes. Same contract as SimdUtils.NormalizedFloatToByteSaturate.</summary>
    public static void NormalizedFloatToByteSaturate(ReadOnlySpan<float> source, Span<byte> destination)
    {
        ref float sourceBase = ref MemoryMarshal.GetReference(source);
        ref byte destinationBase = ref MemoryMarshal.GetReference(destination);
        nuint length = (uint)source.Length;
        nuint i = 0;

        Vector512<float> scale = Vector512.Create(255F);
        Vector512<float> half = Vector512.Create(.5F);
        Vector512<float> one = Vector512.Create(1F);

        // Main loop of the library: 64 floats per step. Each step loads before it stores, so a destination
        // that starts at the source (the three-byte formats of the library) stays valid.
        for (; i + 64 <= length; i += 64)
        {
            Vector512<float> f0 = Vector512.LoadUnsafe(ref sourceBase, i);
            Vector512<float> f1 = Vector512.LoadUnsafe(ref sourceBase, i + 16);
            Vector512<float> f2 = Vector512.LoadUnsafe(ref sourceBase, i + 32);
            Vector512<float> f3 = Vector512.LoadUnsafe(ref sourceBase, i + 48);
            Vector128<byte> b0 = ToBytes(f0, one, scale, half);
            Vector128<byte> b1 = ToBytes(f1, one, scale, half);
            Vector128<byte> b2 = ToBytes(f2, one, scale, half);
            Vector128<byte> b3 = ToBytes(f3, one, scale, half);
            b0.StoreUnsafe(ref destinationBase, i);
            b1.StoreUnsafe(ref destinationBase, i + 16);
            b2.StoreUnsafe(ref destinationBase, i + 32);
            b3.StoreUnsafe(ref destinationBase, i + 48);
        }

        // Tail, new: 16 floats to 16 bytes.
        for (; i + 16 <= length; i += 16)
        {
            ToBytes(Vector512.LoadUnsafe(ref sourceBase, i), one, scale, half).StoreUnsafe(ref destinationBase, i);
        }

        // Tail, new: 4 floats to 4 bytes.
        Vector128<float> scale128 = Vector128.Create(255F);
        Vector128<float> half128 = Vector128.Create(.5F);
        Vector128<float> one128 = Vector128.Create(1F);
        for (; i + 4 <= length; i += 4)
        {
            Vector128<float> f = Clamp(Vector128.LoadUnsafe(ref sourceBase, i), one128);
            Vector128<int> n = Vector128.ConvertToInt32Native((f * scale128) + half128);

            // Values are 0 to 255, so the truncating narrows keep them.
            Vector128<byte> b = Vector128.Narrow(Vector128.Narrow(n, n), Vector128<short>.Zero).AsByte();
            Unsafe.WriteUnaligned(ref Unsafe.Add(ref destinationBase, i), b.AsUInt32().ToScalar());
        }

        // Single floats: the scalar rule of the library.
        for (; i < length; i++)
        {
            float v = (Unsafe.Add(ref sourceBase, i) * 255F) + .5F;
            float lower = v >= 0F ? v : 0F;
            Unsafe.Add(ref destinationBase, i) = (byte)(v > 255F ? 255F : lower);
        }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static Vector128<byte> ToBytes(Vector512<float> f, Vector512<float> one, Vector512<float> scale, Vector512<float> half)
    {
        // ClampToFinite of the library: NaN to 0, then [0, 1].
        Vector512<float> lower = Vector512.ConditionalSelect(Vector512.GreaterThanOrEqual(f, Vector512<float>.Zero), f, Vector512<float>.Zero);
        f = Vector512.ConditionalSelect(Vector512.GreaterThan(f, one), one, lower);

        // truncate(x * 255 + 0.5) is 0 to 255, so the truncating narrow (vpmovdb) equals the saturating one.
        return Avx512F.ConvertToVector128Byte(Vector512.ConvertToInt32Native((f * scale) + half));
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static Vector128<float> Clamp(Vector128<float> f, Vector128<float> one)
    {
        Vector128<float> lower = Vector128.ConditionalSelect(Vector128.GreaterThanOrEqual(f, Vector128<float>.Zero), f, Vector128<float>.Zero);
        return Vector128.ConditionalSelect(Vector128.GreaterThan(f, one), one, lower);
    }
}

ConvertChecks.cs:

using System.Numerics;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

namespace Bench;

/// <summary>Compares the conversion prototype with the library, bit for bit, on random and edge inputs.</summary>
public static class ConvertChecks
{
    public static int Run()
    {
        int failures = CheckByteReciprocal() + CheckConversions();
        Console.WriteLine(failures == 0 ? "ALL CHECKS PASSED" : $"FAILURES: {failures}");
        return failures;
    }

    public static int CheckByteReciprocal()
    {
        const float high = (float)(1D / 255);
        const float low = (float)((1D / 255) - high);
        int bad = 0;
        for (int b = 0; b < 256; b++)
        {
            float f = b;
            if (BitConverter.SingleToInt32Bits(MathF.FusedMultiplyAdd(f, high, f * low)) != BitConverter.SingleToInt32Bits(f / 255F))
            {
                bad++;
            }
        }

        Console.WriteLine($"byte reciprocal: 256 values, {bad} differ");
        return bad;
    }

    public static int CheckConversions()
    {
        Random random = new(1234);
        Configuration configuration = Configuration.Default;
        int bad = 0;
        long compared = 0;
        float[] specials = [float.NaN, float.PositiveInfinity, float.NegativeInfinity, -0F, 0F, 1F, -1F, 2F, 1e30F, -1e30F, float.Epsilon, 0.5F / 255, 1.5F / 255, 254.5F / 255, 1F + 1e-7F, 1F - 1e-7F];

        for (int length = 0; length <= 300; length++)
        {
            for (int round = 0; round < 20; round++)
            {
                // Bytes to vectors.
                Rgba32[] pixels = new Rgba32[length];
                random.NextBytes(MemoryMarshal.AsBytes(pixels.AsSpan()));
                Vector4[] expected = new Vector4[length];
                Vector4[] actual = new Vector4[length];
                PixelOperations<Rgba32>.Instance.ToUnassociatedScaledVector4(configuration, pixels, expected);
                ProtoConvert.ByteToNormalizedFloat(MemoryMarshal.AsBytes(pixels.AsSpan()), MemoryMarshal.Cast<Vector4, float>(actual.AsSpan()));
                bad += CountDifferent(MemoryMarshal.AsBytes(expected.AsSpan()), MemoryMarshal.AsBytes(actual.AsSpan()));
                compared += length;

                // Vectors to bytes. Random values in [-0.25, 1.25] and, in half of the rounds, special values.
                Vector4[] source = new Vector4[length];
                Span<float> floats = MemoryMarshal.Cast<Vector4, float>(source.AsSpan());
                for (int i = 0; i < floats.Length; i++)
                {
                    floats[i] = (round % 2 == 1 && random.Next(4) == 0)
                        ? specials[random.Next(specials.Length)]
                        : (float)((random.NextDouble() * 1.5) - 0.25);
                }

                Vector4[] copy = (Vector4[])source.Clone();
                Rgba32[] expectedPixels = new Rgba32[length];
                Rgba32[] actualPixels = new Rgba32[length];
                ProtoConvert.NormalizedFloatToByteSaturate(MemoryMarshal.Cast<Vector4, float>(copy.AsSpan()), MemoryMarshal.AsBytes(actualPixels.AsSpan()));
                PixelOperations<Rgba32>.Instance.FromUnassociatedScaledVector4Destructive(configuration, source, expectedPixels);
                bad += CountDifferent(MemoryMarshal.AsBytes(expectedPixels.AsSpan()), MemoryMarshal.AsBytes(actualPixels.AsSpan()));
            }
        }

        Console.WriteLine($"row conversions: lengths 0..300 pixels, 20 rounds each ({compared} pixels per direction), {bad} differing bytes");
        return bad;
    }

    internal static int CountDifferent(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b)
    {
        int d = 0;
        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] != b[i])
            {
                d++;
            }
        }

        return d;
    }

    internal static int FirstDifferent(Rgba32[] a, Rgba32[] b)
    {
        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] != b[i])
            {
                return i;
            }
        }

        return -1;
    }
}

ConvertBenchmarks.cs:

using System.Numerics;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

namespace Bench;

/// <summary>Candidate 2: one row conversion Rgba32 to Vector4 and back, per row length.</summary>
[MemoryDiagnoser]
public class RowConversion
{
    private Rgba32[] pixels;
    private Vector4[] vectors;
    private Vector4[] input;
    private Rgba32[] output;

    [Params(1, 3, 4, 7, 8, 15, 16, 17, 31, 32, 63, 64, 100, 255, 256)]
    public int Pixels { get; set; }

    [GlobalSetup]
    public void Setup()
    {
        Random random = new(1);
        this.pixels = new Rgba32[this.Pixels];
        random.NextBytes(MemoryMarshal.AsBytes(this.pixels.AsSpan()));
        this.vectors = new Vector4[this.Pixels];
        this.input = new Vector4[this.Pixels];
        PixelOperations<Rgba32>.Instance.ToUnassociatedScaledVector4(Configuration.Default, this.pixels, this.input);
        this.output = new Rgba32[this.Pixels];
    }

    [Benchmark(Description = "ToVector4, library")]
    public void ToVector4Library()
        => PixelOperations<Rgba32>.Instance.ToUnassociatedScaledVector4(Configuration.Default, this.pixels, this.vectors);

    [Benchmark(Description = "ToVector4, prototype")]
    public void ToVector4Prototype()
        => ProtoConvert.ByteToNormalizedFloat(MemoryMarshal.AsBytes(this.pixels.AsSpan()), MemoryMarshal.Cast<Vector4, float>(this.vectors.AsSpan()));

    // The library method is destructive by contract; for Rgba32 it reads the source only, so the input is reused.
    [Benchmark(Description = "FromVector4, library")]
    public void FromVector4Library()
        => PixelOperations<Rgba32>.Instance.FromUnassociatedScaledVector4Destructive(Configuration.Default, this.input, this.output);

    [Benchmark(Description = "FromVector4, prototype")]
    public void FromVector4Prototype()
        => ProtoConvert.NormalizedFloatToByteSaturate(MemoryMarshal.Cast<Vector4, float>(this.input.AsSpan()), MemoryMarshal.AsBytes(this.output.AsSpan()));
}

…er vectors

ByteToNormalizedFloat and FloatToByteSaturate converted the bytes after the last
whole step of the widest vector one element at a time. The Reduce methods now
convert whole pixels of that tail with 16-, 8-, or 4-element vector steps, with the
same arithmetic per element, so the output is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
The main byte-to-float loop and its tail each declared the high and low
parts of 1 / 255; the floats are only equal while both copies match, so
they are now one pair of class constants. The 256-bit and 128-bit narrow
steps explain their lane layout like the 512-bit step. The tail test also
checks SimdUtils.FloatToByteSaturate (scale 1, used for associated
pixels), which runs the same tail with another bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants