Skip to content

Commit d506fac

Browse files
authored
Merge pull request #7 from unsafePtr/perf/simd-bitcoin-32-64
SIMD Bitcoin 32/64 byte optimization
2 parents 44f61ac + 4976851 commit d506fac

14 files changed

Lines changed: 1023 additions & 127 deletions

‎README.md‎

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ These optimizations are based on Firedancer's specialized Base58 algorithms and
7070
- Precomputed multiplication tables replace expensive division operations
7171
- Converts binary data to base 58^5 limbs, then to raw base58 digits
7272
- Matrix multiplication approach processes 5 base58 digits simultaneously
73+
- The 32/64-byte encode and decode matrix kernels are SIMD-accelerated with `Vector256`/`Vector128` (widest available width, scalar fallback) — in addition to the vectorized leading-zero count
7374
- Separate encode/decode tables for 32-byte and 64-byte fixed sizes
7475
- Achieves ~2.5x speedup through table-based optimizations vs iterative division
7576

@@ -81,43 +82,43 @@ These optimizations are based on Firedancer's specialized Base58 algorithms and
8182

8283
```
8384
84-
BenchmarkDotNet v0.15.8, Windows 11 (10.0.26200.8246/25H2/2025Update/HudsonValley2)
85+
BenchmarkDotNet v0.15.8, Windows 11 (10.0.26200.8655/25H2/2025Update/HudsonValley2)
8586
13th Gen Intel Core i7-13700KF 3.40GHz, 1 CPU, 24 logical and 16 physical cores
86-
.NET SDK 10.0.203
87-
[Host] : .NET 10.0.7 (10.0.7, 10.0.726.21808), X64 RyuJIT x86-64-v3
88-
DefaultJob : .NET 10.0.7 (10.0.7, 10.0.726.21808), X64 RyuJIT x86-64-v3
87+
.NET SDK 11.0.100-preview.3.26207.106
88+
[Host] : .NET 10.0.10 (10.0.10, 10.0.1026.32716), X64 RyuJIT x86-64-v3
89+
DefaultJob : .NET 10.0.10 (10.0.10, 10.0.1026.32716), X64 RyuJIT x86-64-v3
8990
9091
Job=DefaultJob
9192
9293
```
93-
| Method | VectorType | Mean | Ratio | Gen0 | Allocated | Alloc Ratio |
94-
|--------------------------- |--------------- |------------:|------:|-------:|----------:|------------:|
95-
| **'Our Base58 Encode'** | **BitcoinAddress** | **537.17 ns** | **1.00** | **0.0057** | **96 B** | **1.00** |
96-
| 'SimpleBase Base58 Encode' | BitcoinAddress | 776.69 ns | 1.45 | 0.0057 | 96 B | 1.00 |
97-
| 'Our Base58 Decode' | BitcoinAddress | 160.88 ns | 0.30 | 0.0033 | 56 B | 0.58 |
98-
| 'SimpleBase Base58 Decode' | BitcoinAddress | 353.19 ns | 0.66 | 0.0033 | 56 B | 0.58 |
99-
| | | | | | | |
100-
| **'Our Base58 Encode'** | **SolanaAddress** | **94.07 ns** | **1.00** | **0.0070** | **112 B** | **1.00** |
101-
| 'SimpleBase Base58 Encode' | SolanaAddress | 1,433.92 ns | 15.24 | 0.0057 | 112 B | 1.00 |
102-
| 'Our Base58 Decode' | SolanaAddress | 104.19 ns | 1.11 | 0.0035 | 56 B | 0.50 |
103-
| 'SimpleBase Base58 Decode' | SolanaAddress | 703.66 ns | 7.48 | 0.0029 | 56 B | 0.50 |
104-
| | | | | | | |
105-
| **'Our Base58 Encode'** | **SolanaTx** | **239.21 ns** | **1.00** | **0.0124** | **200 B** | **1.00** |
106-
| 'SimpleBase Base58 Encode' | SolanaTx | 7,166.10 ns | 29.96 | 0.0076 | 200 B | 1.00 |
107-
| 'Our Base58 Decode' | SolanaTx | 180.37 ns | 0.75 | 0.0055 | 88 B | 0.44 |
108-
| 'SimpleBase Base58 Decode' | SolanaTx | 2,957.77 ns | 12.36 | 0.0038 | 88 B | 0.44 |
109-
| | | | | | | |
110-
| **'Our Base58 Encode'** | **IPFSHash** | **1,084.69 ns** | **1.00** | **0.0076** | **120 B** | **1.00** |
111-
| 'SimpleBase Base58 Encode' | IPFSHash | 1,617.11 ns | 1.49 | 0.0076 | 120 B | 1.00 |
112-
| 'Our Base58 Decode' | IPFSHash | 318.15 ns | 0.29 | 0.0038 | 64 B | 0.53 |
113-
| 'SimpleBase Base58 Decode' | IPFSHash | 854.47 ns | 0.79 | 0.0038 | 64 B | 0.53 |
114-
| | | | | | | |
115-
| **'Our Base58 Encode'** | **MoneroAddress** | **4,917.65 ns** | **1.00** | **0.0076** | **216 B** | **1.00** |
116-
| 'SimpleBase Base58 Encode' | MoneroAddress | 8,621.98 ns | 1.75 | - | 216 B | 1.00 |
117-
| 'Our Base58 Decode' | MoneroAddress | 1,198.92 ns | 0.24 | 0.0057 | 96 B | 0.44 |
118-
| 'SimpleBase Base58 Decode' | MoneroAddress | 3,844.43 ns | 0.78 | - | 96 B | 0.44 |
119-
120-
121-
## License
122-
123-
This project is available under the MIT License.
94+
| Method | Categories | VectorType | Mean | Ratio | Gen0 | Allocated | Alloc Ratio |
95+
|--------------------------- |----------- |--------------- |------------:|------:|-------:|----------:|------------:|
96+
| **'Our Base58 Decode'** | **Decode** | **BitcoinAddress** | **178.71 ns** | **1.00** | **0.0033** | **56 B** | **1.00** |
97+
| 'SimpleBase Base58 Decode' | Decode | BitcoinAddress | 364.51 ns | 2.04 | 0.0033 | 56 B | 1.00 |
98+
| | | | | | | | |
99+
| **'Our Base58 Decode'** | **Decode** | **SolanaAddress** | **83.27 ns** | **1.00** | **0.0035** | **56 B** | **1.00** |
100+
| 'SimpleBase Base58 Decode' | Decode | SolanaAddress | 598.64 ns | 7.19 | 0.0029 | 56 B | 1.00 |
101+
| | | | | | | | |
102+
| **'Our Base58 Decode'** | **Decode** | **SolanaTx** | **167.00 ns** | **1.00** | **0.0055** | **88 B** | **1.00** |
103+
| 'SimpleBase Base58 Decode' | Decode | SolanaTx | 4,190.80 ns | 25.10 | 0.0038 | 88 B | 1.00 |
104+
| | | | | | | | |
105+
| **'Our Base58 Decode'** | **Decode** | **IPFSHash** | **339.26 ns** | **1.00** | **0.0038** | **64 B** | **1.00** |
106+
| 'SimpleBase Base58 Decode' | Decode | IPFSHash | 641.17 ns | 1.89 | 0.0038 | 64 B | 1.00 |
107+
| | | | | | | | |
108+
| **'Our Base58 Decode'** | **Decode** | **MoneroAddress** | **1,391.11 ns** | **1.00** | **0.0057** | **96 B** | **1.00** |
109+
| 'SimpleBase Base58 Decode' | Decode | MoneroAddress | 3,882.84 ns | 2.79 | - | 96 B | 1.00 |
110+
| | | | | | | | |
111+
| **'Our Base58 Encode'** | **Encode** | **BitcoinAddress** | **532.69 ns** | **1.00** | **0.0057** | **96 B** | **1.00** |
112+
| 'SimpleBase Base58 Encode' | Encode | BitcoinAddress | 774.83 ns | 1.45 | 0.0057 | 96 B | 1.00 |
113+
| | | | | | | | |
114+
| **'Our Base58 Encode'** | **Encode** | **SolanaAddress** | **95.15 ns** | **1.00** | **0.0070** | **112 B** | **1.00** |
115+
| 'SimpleBase Base58 Encode' | Encode | SolanaAddress | 1,521.61 ns | 15.99 | 0.0057 | 112 B | 1.00 |
116+
| | | | | | | | |
117+
| **'Our Base58 Encode'** | **Encode** | **SolanaTx** | **196.50 ns** | **1.00** | **0.0126** | **200 B** | **1.00** |
118+
| 'SimpleBase Base58 Encode' | Encode | SolanaTx | 7,338.14 ns | 37.34 | 0.0076 | 200 B | 1.00 |
119+
| | | | | | | | |
120+
| **'Our Base58 Encode'** | **Encode** | **IPFSHash** | **1,085.19 ns** | **1.00** | **0.0076** | **120 B** | **1.00** |
121+
| 'SimpleBase Base58 Encode' | Encode | IPFSHash | 1,690.70 ns | 1.56 | 0.0076 | 120 B | 1.00 |
122+
| | | | | | | | |
123+
| **'Our Base58 Encode'** | **Encode** | **MoneroAddress** | **4,959.86 ns** | **1.00** | **0.0076** | **216 B** | **1.00** |
124+
| 'SimpleBase Base58 Encode' | Encode | MoneroAddress | 8,734.32 ns | 1.76 | - | 216 B | 1.00 |

‎src/Base58Encoding.Benchmarks/Base58ComparisonBenchmark.cs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
using Base58Encoding.Benchmarks.Common;
22

33
using BenchmarkDotNet.Attributes;
4+
using BenchmarkDotNet.Configs;
45
using BenchmarkDotNet.Diagnosers;
56

67
namespace Base58Encoding.Benchmarks;
78

89
[MemoryDiagnoser]
10+
[CategoriesColumn]
11+
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
912
[HideColumns("Job", "Error", "StdDev", "Median", "RatioSD")]
1013
public class Base58ComparisonBenchmark
1114
{
@@ -28,25 +31,25 @@ public void Setup()
2831
_base58Encoded = Base58.Bitcoin.Encode(_testData);
2932
}
3033

31-
[Benchmark(Description = "Our Base58 Encode", Baseline = true)]
34+
[BenchmarkCategory("Encode"), Benchmark(Description = "Our Base58 Encode", Baseline = true)]
3235
public string Encode_OurBase58()
3336
{
3437
return Base58.Bitcoin.Encode(_testData);
3538
}
3639

37-
[Benchmark(Description = "SimpleBase Base58 Encode")]
40+
[BenchmarkCategory("Encode"), Benchmark(Description = "SimpleBase Base58 Encode")]
3841
public string Encode_SimpleBase58()
3942
{
4043
return SimpleBase.Base58.Bitcoin.Encode(_testData);
4144
}
4245

43-
[Benchmark(Description = "Our Base58 Decode")]
46+
[BenchmarkCategory("Decode"), Benchmark(Description = "Our Base58 Decode", Baseline = true)]
4447
public byte[] Decode_OurBase58()
4548
{
4649
return Base58.Bitcoin.Decode(_base58Encoded);
4750
}
4851

49-
[Benchmark(Description = "SimpleBase Base58 Decode")]
52+
[BenchmarkCategory("Decode"), Benchmark(Description = "SimpleBase Base58 Decode")]
5053
public byte[] Decode_SimpleBase58()
5154
{
5255
return SimpleBase.Base58.Bitcoin.Decode(_base58Encoded);

‎src/Base58Encoding.Benchmarks/Base58Encoding.Benchmarks.csproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5+
<!-- Emit PDBs even in Release so DisassemblyDiagnoser(printSource: true) can map asm to C#. -->
6+
<DebugType>pdbonly</DebugType>
7+
<DebugSymbols>true</DebugSymbols>
58
</PropertyGroup>
69

710
<ItemGroup>
811
<PackageReference Include="BenchmarkDotNet" />
912
<PackageReference Include="SimpleBase" />
13+
<PackageReference Include="System.Numerics.Tensors" />
1014
</ItemGroup>
1115

1216
<ItemGroup>
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
using System.Buffers.Binary;
2+
using System.Numerics;
3+
using System.Runtime.CompilerServices;
4+
using System.Runtime.InteropServices;
5+
using System.Runtime.Intrinsics;
6+
7+
using BenchmarkDotNet.Attributes;
8+
using BenchmarkDotNet.Jobs;
9+
10+
namespace Base58Encoding.Benchmarks;
11+
12+
// End-to-end 64-byte decode A/B. Both arms run the identical full decode path (validate,
13+
// intermediate build, matmul, carry-reduce, leading-zero check, byte output) and differ ONLY
14+
// in the matmul step (SIMD TensorDot over transposed ulong columns vs jagged scalar). Measured
15+
// in a single run, so the ratio is the real end-to-end effect of the matmul change.
16+
[SimpleJob(RuntimeMoniker.Net10_0)]
17+
[HideColumns("Error", "StdDev", "RatioSD")]
18+
public class EndToEndDecodeBenchmark
19+
{
20+
private string _sig64 = default!;
21+
private ulong[] _transposed64 = default!;
22+
private uint[][] _jagged64 = default!;
23+
24+
[GlobalSetup]
25+
public void Setup()
26+
{
27+
var bytes = new byte[64];
28+
Random.Shared.NextBytes(bytes);
29+
_sig64 = Base58.Bitcoin.Encode(bytes);
30+
31+
// Production tables on this branch are transposed column-major ulong.
32+
_transposed64 = Base58BitcoinTables.DecodeTable64;
33+
34+
// Rebuild the original jagged row-major layout: jagged[i][j] = transposed[j*IntermediateSz64 + i].
35+
int rows = Base58BitcoinTables.IntermediateSz64;
36+
int cols = Base58BitcoinTables.BinarySz64;
37+
_jagged64 = new uint[rows][];
38+
for (int i = 0; i < rows; i++)
39+
{
40+
_jagged64[i] = new uint[cols];
41+
for (int j = 0; j < cols; j++)
42+
{
43+
_jagged64[i][j] = (uint)_transposed64[j * rows + i];
44+
}
45+
}
46+
47+
// Correctness: both matmul variants must reproduce the production decode exactly.
48+
Span<byte> a = stackalloc byte[64];
49+
Span<byte> b = stackalloc byte[64];
50+
DecodeFull64(_sig64, a, useSimd: true);
51+
DecodeFull64(_sig64, b, useSimd: false);
52+
byte[] expected = Base58.Bitcoin.Decode(_sig64);
53+
if (!a.SequenceEqual(expected) || !b.SequenceEqual(expected))
54+
{
55+
throw new InvalidOperationException("DecodeFull64 does not match production Decode");
56+
}
57+
}
58+
59+
[Benchmark(Baseline = true)]
60+
public int Full_Jagged()
61+
{
62+
Span<byte> dest = stackalloc byte[64];
63+
return DecodeFull64(_sig64, dest, useSimd: false);
64+
}
65+
66+
[Benchmark]
67+
public int Full_Simd()
68+
{
69+
Span<byte> dest = stackalloc byte[64];
70+
return DecodeFull64(_sig64, dest, useSimd: true);
71+
}
72+
73+
[SkipLocalsInit]
74+
private int DecodeFull64(ReadOnlySpan<char> encoded, Span<byte> destination, bool useSimd)
75+
{
76+
int charCount = encoded.Length;
77+
78+
Span<byte> rawBase58 = stackalloc byte[Base58BitcoinTables.Raw58Sz64];
79+
ReadOnlySpan<byte> decodeTable = BitcoinAlphabet.DecodeTable;
80+
81+
int prepend0 = Base58BitcoinTables.Raw58Sz64 - charCount;
82+
for (int j = 0; j < Base58BitcoinTables.Raw58Sz64; j++)
83+
{
84+
if (j < prepend0)
85+
{
86+
rawBase58[j] = 0;
87+
}
88+
else
89+
{
90+
int c = encoded[j - prepend0];
91+
if ((uint)c >= 128 || decodeTable[c] == 255)
92+
{
93+
ThrowHelper.ThrowInvalidCharacter((char)c);
94+
}
95+
96+
rawBase58[j] = decodeTable[c];
97+
}
98+
}
99+
100+
Span<ulong> intermediate = stackalloc ulong[Base58BitcoinTables.IntermediateSz64];
101+
for (int i = 0; i < Base58BitcoinTables.IntermediateSz64; i++)
102+
{
103+
intermediate[i] = (ulong)rawBase58[5 * i + 0] * 11316496UL +
104+
(ulong)rawBase58[5 * i + 1] * 195112UL +
105+
(ulong)rawBase58[5 * i + 2] * 3364UL +
106+
(ulong)rawBase58[5 * i + 3] * 58UL +
107+
(ulong)rawBase58[5 * i + 4] * 1UL;
108+
}
109+
110+
Span<ulong> binary = stackalloc ulong[Base58BitcoinTables.BinarySz64];
111+
if (useSimd)
112+
{
113+
var table = _transposed64;
114+
int rows = Base58BitcoinTables.IntermediateSz64;
115+
for (int j = 0; j < Base58BitcoinTables.BinarySz64; j++)
116+
{
117+
binary[j] = TensorDot(intermediate, table.AsSpan(j * rows, rows));
118+
}
119+
}
120+
else
121+
{
122+
var table = _jagged64;
123+
for (int j = 0; j < Base58BitcoinTables.BinarySz64; j++)
124+
{
125+
ulong acc = 0UL;
126+
for (int i = 0; i < Base58BitcoinTables.IntermediateSz64; i++)
127+
{
128+
acc += intermediate[i] * table[i][j];
129+
}
130+
131+
binary[j] = acc;
132+
}
133+
}
134+
135+
for (int i = Base58BitcoinTables.BinarySz64 - 1; i > 0; i--)
136+
{
137+
binary[i - 1] += binary[i] >> 32;
138+
binary[i] &= 0xFFFFFFFFUL;
139+
}
140+
141+
if (binary[0] > 0xFFFFFFFFUL)
142+
{
143+
return -1;
144+
}
145+
146+
int outputLeadingZeros = 0;
147+
for (int i = 0; i < Base58BitcoinTables.BinarySz64; i++)
148+
{
149+
uint v = (uint)binary[i];
150+
if (v != 0)
151+
{
152+
outputLeadingZeros += BitOperations.LeadingZeroCount(v) / 8;
153+
break;
154+
}
155+
outputLeadingZeros += 4;
156+
}
157+
158+
int inputLeadingOnes = Base58.CountLeadingCharacters(encoded, '1');
159+
if (outputLeadingZeros != inputLeadingOnes)
160+
{
161+
return -1;
162+
}
163+
164+
for (int i = 0; i < Base58BitcoinTables.BinarySz64; i++)
165+
{
166+
BinaryPrimitives.WriteUInt32BigEndian(destination.Slice(i * sizeof(uint), sizeof(uint)), (uint)binary[i]);
167+
}
168+
169+
return 64;
170+
}
171+
172+
private static ulong TensorDot(ReadOnlySpan<ulong> x, ReadOnlySpan<ulong> y)
173+
{
174+
ref ulong xr = ref MemoryMarshal.GetReference(x);
175+
ref ulong yr = ref MemoryMarshal.GetReference(y);
176+
int len = x.Length;
177+
int i = 0;
178+
ulong sum = 0UL;
179+
180+
if (Vector256.IsHardwareAccelerated && len >= Vector256<ulong>.Count)
181+
{
182+
Vector256<ulong> acc = Vector256<ulong>.Zero;
183+
int upper = len - Vector256<ulong>.Count;
184+
for (; i <= upper; i += Vector256<ulong>.Count)
185+
{
186+
acc += Vector256.LoadUnsafe(ref xr, (nuint)i) * Vector256.LoadUnsafe(ref yr, (nuint)i);
187+
}
188+
189+
sum += Vector256.Sum(acc);
190+
}
191+
else if (Vector128.IsHardwareAccelerated && len >= Vector128<ulong>.Count)
192+
{
193+
Vector128<ulong> acc = Vector128<ulong>.Zero;
194+
int upper = len - Vector128<ulong>.Count;
195+
for (; i <= upper; i += Vector128<ulong>.Count)
196+
{
197+
acc += Vector128.LoadUnsafe(ref xr, (nuint)i) * Vector128.LoadUnsafe(ref yr, (nuint)i);
198+
}
199+
200+
sum += Vector128.Sum(acc);
201+
}
202+
203+
for (; i < len; i++)
204+
{
205+
sum += Unsafe.Add(ref xr, i) * Unsafe.Add(ref yr, i);
206+
}
207+
208+
return sum;
209+
}
210+
}

0 commit comments

Comments
 (0)