Repository navigation
Expand file tree
/
Copy pathDirectILKernelGenerator.Reduction.Boolean.cs
More file actions
226 lines (196 loc) · 9.2 KB
/
Copy pathDirectILKernelGenerator.Reduction.Boolean.cs
File metadata and controls
226 lines (196 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Intrinsics;
// =============================================================================
// DirectILKernelGenerator.Reduction.Boolean.cs - All/Any Boolean Reductions
// =============================================================================
//
// RESPONSIBILITY:
// - All/Any reduction with early-exit SIMD optimization
// - EmitAllAnySimdLoop() - IL emission for All/Any
// - AllSimdHelper<T>() - returns false immediately on first zero
// - AnySimdHelper<T>() - returns true immediately on first non-zero
//
// =============================================================================
namespace NumSharp.Backends.Kernels
{
public static partial class DirectILKernelGenerator
{
#region Boolean Reduction Helpers (All/Any)
/// <summary>
/// Emit All/Any SIMD loop with early-exit.
/// All: returns false immediately when any zero is found
/// Any: returns true immediately when any non-zero is found
/// </summary>
private static void EmitAllAnySimdLoop(ILGenerator il, ElementReductionKernelKey key, int inputSize)
{
// For All/Any, we use a helper method approach because:
// 1. Early-exit logic is complex to emit in IL
// 2. The helper method can be JIT-optimized effectively
// 3. This matches the pattern used elsewhere in the codebase
var genericHelper = GetGenericHelper(
key.Op == ReductionOp.All ? nameof(AllSimdHelper) : nameof(AnySimdHelper),
GetClrType(key.InputType));
// Call helper: AllSimdHelper<T>(input, totalSize) or AnySimdHelper<T>(input, totalSize)
il.Emit(OpCodes.Ldarg_0); // input
il.Emit(OpCodes.Ldarg_S, (byte)4); // totalSize
il.EmitCall(OpCodes.Call, genericHelper, null);
// Result (bool) is already on stack, but we need to convert to TResult (also bool for All/Any)
// Stack has: bool result - convert to byte (0 or 1) for bool return
}
/// <summary>
/// SIMD helper for All reduction with early-exit.
/// Returns true if ALL elements are non-zero.
/// </summary>
[System.Runtime.CompilerServices.MethodImpl(OptimizeAndInline)]
internal static unsafe bool AllSimdHelper<T>(void* input, long totalSize) where T : unmanaged
{
if (totalSize == 0)
return true; // NumPy: all([]) == True (vacuous truth)
// bool / char are NOT JIT-vectorizable (Vector256<bool>/<char>.IsSupported == false),
// so without this redirect they fall through to the scalar per-element loop below.
// Both are bitwise identical to an unsigned integer for a zero/non-zero test
// (bool: 0/1; char: UTF-16 code unit), so reinterpret and run the vectorized path.
if (typeof(T) == typeof(bool))
return AllSimdHelper<byte>(input, totalSize);
if (typeof(T) == typeof(char))
return AllSimdHelper<ushort>(input, totalSize);
T* src = (T*)input;
if (Vector256.IsHardwareAccelerated && Vector256<T>.IsSupported && totalSize >= Vector256<T>.Count)
{
int vectorCount = Vector256<T>.Count;
long vectorEnd = totalSize - vectorCount;
var zero = Vector256<T>.Zero;
long i = 0;
// SIMD loop with early exit
for (; i <= vectorEnd; i += vectorCount)
{
var vec = Vector256.Load(src + i);
var mask = Vector256.Equals(vec, zero);
// If ANY element equals zero, return false
if (Vector256.ExtractMostSignificantBits(mask) != 0)
return false;
}
// Scalar tail
for (; i < totalSize; i++)
{
if (System.Collections.Generic.EqualityComparer<T>.Default.Equals(src[i], default))
return false;
}
return true;
}
else if (Vector128.IsHardwareAccelerated && Vector128<T>.IsSupported && totalSize >= Vector128<T>.Count)
{
int vectorCount = Vector128<T>.Count;
long vectorEnd = totalSize - vectorCount;
var zero = Vector128<T>.Zero;
long i = 0;
for (; i <= vectorEnd; i += vectorCount)
{
var vec = Vector128.Load(src + i);
var mask = Vector128.Equals(vec, zero);
if (Vector128.ExtractMostSignificantBits(mask) != 0)
return false;
}
for (; i < totalSize; i++)
{
if (System.Collections.Generic.EqualityComparer<T>.Default.Equals(src[i], default))
return false;
}
return true;
}
else
{
// Scalar fallback
for (long i = 0; i < totalSize; i++)
{
if (System.Collections.Generic.EqualityComparer<T>.Default.Equals(src[i], default))
return false;
}
return true;
}
}
/// <summary>
/// SIMD helper for Any reduction with early-exit.
/// Returns true if ANY element is non-zero.
/// </summary>
[System.Runtime.CompilerServices.MethodImpl(OptimizeAndInline)]
internal static unsafe bool AnySimdHelper<T>(void* input, long totalSize) where T : unmanaged
{
if (totalSize == 0)
return false; // NumPy: any([]) == False
// bool / char are NOT JIT-vectorizable (Vector256<bool>/<char>.IsSupported == false),
// so without this redirect they fall through to the scalar per-element loop below — the
// any(all-false) cliff (no SIMD → ~10x slower than NumPy at scale). Both are bitwise
// identical to an unsigned integer for a zero/non-zero test (bool: 0/1; char: UTF-16
// code unit), so reinterpret and run the vectorized path.
if (typeof(T) == typeof(bool))
return AnySimdHelper<byte>(input, totalSize);
if (typeof(T) == typeof(char))
return AnySimdHelper<ushort>(input, totalSize);
T* src = (T*)input;
if (Vector256.IsHardwareAccelerated && Vector256<T>.IsSupported && totalSize >= Vector256<T>.Count)
{
int vectorCount = Vector256<T>.Count;
long vectorEnd = totalSize - vectorCount;
var zero = Vector256<T>.Zero;
uint allZeroMask = (uint)((1UL << vectorCount) - 1); // 1u<<32 overflows to 0 for Vector256<byte>/<sbyte> (32 lanes)
long i = 0;
// SIMD loop with early exit
for (; i <= vectorEnd; i += vectorCount)
{
var vec = Vector256.Load(src + i);
var mask = Vector256.Equals(vec, zero);
uint bits = Vector256.ExtractMostSignificantBits(mask);
// If NOT all elements are zero, we found a non-zero
if (bits != allZeroMask)
return true;
}
// Scalar tail
for (; i < totalSize; i++)
{
if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(src[i], default))
return true;
}
return false;
}
else if (Vector128.IsHardwareAccelerated && Vector128<T>.IsSupported && totalSize >= Vector128<T>.Count)
{
int vectorCount = Vector128<T>.Count;
long vectorEnd = totalSize - vectorCount;
var zero = Vector128<T>.Zero;
uint allZeroMask = (uint)((1UL << vectorCount) - 1); // 1u<<32 overflows to 0 for Vector256<byte>/<sbyte> (32 lanes)
long i = 0;
for (; i <= vectorEnd; i += vectorCount)
{
var vec = Vector128.Load(src + i);
var mask = Vector128.Equals(vec, zero);
uint bits = Vector128.ExtractMostSignificantBits(mask);
if (bits != allZeroMask)
return true;
}
for (; i < totalSize; i++)
{
if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(src[i], default))
return true;
}
return false;
}
else
{
// Scalar fallback
for (long i = 0; i < totalSize; i++)
{
if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(src[i], default))
return true;
}
return false;
}
}
#endregion
}
}