-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathDefault.ClipNDArray.cs
More file actions
562 lines (522 loc) · 25.1 KB
/
Default.ClipNDArray.cs
File metadata and controls
562 lines (522 loc) · 25.1 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
using System;
using System.Linq;
using NumSharp.Backends.Kernels;
using NumSharp.Utilities;
namespace NumSharp.Backends
{
public partial class DefaultEngine
{
// =============================================================================
// ClipNDArray - Clip with array-valued min/max bounds
// =============================================================================
//
// This implements np.clip(a, min_array, max_array) where min and/or max are
// NDArrays (possibly broadcast) rather than scalar values.
//
// NumPy behavior:
// - result[i] = min(max(a[i], min[i]), max[i])
// - When min[i] > max[i] at any position, result is max[i]
// - NaN in bounds array: propagates to result (IEEE comparison semantics)
// - min/max arrays are broadcast to match input shape
//
// Implementation strategy:
// 1. Broadcast min/max arrays to match input shape
// 2. Create output array (copy of input with requested dtype)
// 3. If all arrays are contiguous, use SIMD-optimized IL kernel path
// 4. Otherwise, fall back to iterator-based element-wise processing
//
// =============================================================================
public override NDArray ClipNDArray(NDArray lhs, NDArray min, NDArray max, Type dtype, NDArray @out = null)
=> ClipNDArray(lhs, min, max, dtype?.GetTypeCode(), @out);
public override NDArray ClipNDArray(NDArray lhs, NDArray min, NDArray max, NPTypeCode? typeCode = null, NDArray @out = null)
{
if (lhs.size == 0)
return lhs.Clone();
// If both bounds are null, just return a copy (NumPy behavior)
if (min is null && max is null)
return Cast(lhs, typeCode ?? lhs.typecode, copy: true);
// Broadcast bounds arrays to match input shape
// np.broadcast_arrays ensures they are all broadcastable to each other
var boundsToCheck = new NDArray[] { lhs, min, max }.Where(nd => !(nd is null)).ToArray();
var broadcasted = np.broadcast_arrays(boundsToCheck);
var _min = min is null ? null : np.broadcast_to(min, lhs.Shape);
var _max = max is null ? null : np.broadcast_to(max, lhs.Shape);
// Create or validate output array
if (@out is null)
@out = Cast(lhs, typeCode ?? lhs.typecode, copy: true);
else
{
NumSharpException.ThrowIfNotWriteable(@out.Shape);
if (@out.Shape != lhs.Shape)
throw new ArgumentException($"@out's shape ({@out.Shape}) must match lhs's shape ({lhs.Shape}).'");
// Copy input data into @out - user-provided @out may contain garbage (e.g., np.empty)
np.copyto(@out, lhs);
}
var len = @out.size;
// Check if we can use the fast contiguous SIMD path
// All participating arrays must be contiguous with zero offset
bool canUseFastPath = @out.Shape.IsContiguous && @out.Shape.Offset == 0;
if (!(_min is null) && canUseFastPath)
canUseFastPath = _min.Shape.IsContiguous && _min.Shape.Offset == 0;
if (!(_max is null) && canUseFastPath)
canUseFastPath = _max.Shape.IsContiguous && _max.Shape.Offset == 0;
if (canUseFastPath)
return ClipNDArrayContiguous(@out, _min, _max, len);
else
return ClipNDArrayGeneral(@out, _min, _max, len);
}
/// <summary>
/// Fast path for contiguous arrays - uses IL kernel with SIMD support.
/// </summary>
private unsafe NDArray ClipNDArrayContiguous(NDArray @out, NDArray min, NDArray max, int len)
{
if (!(min is null) && !(max is null))
{
// Both bounds - use ClipArrayBounds
switch (@out.GetTypeCode)
{
case NPTypeCode.Byte:
ILKernelGenerator.ClipArrayBounds((byte*)@out.Address, (byte*)min.Address, (byte*)max.Address, len);
return @out;
case NPTypeCode.Int16:
ILKernelGenerator.ClipArrayBounds((short*)@out.Address, (short*)min.Address, (short*)max.Address, len);
return @out;
case NPTypeCode.UInt16:
ILKernelGenerator.ClipArrayBounds((ushort*)@out.Address, (ushort*)min.Address, (ushort*)max.Address, len);
return @out;
case NPTypeCode.Int32:
ILKernelGenerator.ClipArrayBounds((int*)@out.Address, (int*)min.Address, (int*)max.Address, len);
return @out;
case NPTypeCode.UInt32:
ILKernelGenerator.ClipArrayBounds((uint*)@out.Address, (uint*)min.Address, (uint*)max.Address, len);
return @out;
case NPTypeCode.Int64:
ILKernelGenerator.ClipArrayBounds((long*)@out.Address, (long*)min.Address, (long*)max.Address, len);
return @out;
case NPTypeCode.UInt64:
ILKernelGenerator.ClipArrayBounds((ulong*)@out.Address, (ulong*)min.Address, (ulong*)max.Address, len);
return @out;
case NPTypeCode.Single:
ILKernelGenerator.ClipArrayBounds((float*)@out.Address, (float*)min.Address, (float*)max.Address, len);
return @out;
case NPTypeCode.Double:
ILKernelGenerator.ClipArrayBounds((double*)@out.Address, (double*)min.Address, (double*)max.Address, len);
return @out;
case NPTypeCode.Decimal:
ClipArrayBoundsDecimal((decimal*)@out.Address, (decimal*)min.Address, (decimal*)max.Address, len);
return @out;
case NPTypeCode.Char:
ClipArrayBoundsChar((char*)@out.Address, (char*)min.Address, (char*)max.Address, len);
return @out;
default:
throw new NotSupportedException($"ClipNDArray not supported for dtype {@out.GetTypeCode}");
}
}
else if (!(min is null))
{
// Min only - use ClipArrayMin
switch (@out.GetTypeCode)
{
case NPTypeCode.Byte:
ILKernelGenerator.ClipArrayMin((byte*)@out.Address, (byte*)min.Address, len);
return @out;
case NPTypeCode.Int16:
ILKernelGenerator.ClipArrayMin((short*)@out.Address, (short*)min.Address, len);
return @out;
case NPTypeCode.UInt16:
ILKernelGenerator.ClipArrayMin((ushort*)@out.Address, (ushort*)min.Address, len);
return @out;
case NPTypeCode.Int32:
ILKernelGenerator.ClipArrayMin((int*)@out.Address, (int*)min.Address, len);
return @out;
case NPTypeCode.UInt32:
ILKernelGenerator.ClipArrayMin((uint*)@out.Address, (uint*)min.Address, len);
return @out;
case NPTypeCode.Int64:
ILKernelGenerator.ClipArrayMin((long*)@out.Address, (long*)min.Address, len);
return @out;
case NPTypeCode.UInt64:
ILKernelGenerator.ClipArrayMin((ulong*)@out.Address, (ulong*)min.Address, len);
return @out;
case NPTypeCode.Single:
ILKernelGenerator.ClipArrayMin((float*)@out.Address, (float*)min.Address, len);
return @out;
case NPTypeCode.Double:
ILKernelGenerator.ClipArrayMin((double*)@out.Address, (double*)min.Address, len);
return @out;
case NPTypeCode.Decimal:
ClipArrayMinDecimal((decimal*)@out.Address, (decimal*)min.Address, len);
return @out;
case NPTypeCode.Char:
ClipArrayMinChar((char*)@out.Address, (char*)min.Address, len);
return @out;
default:
throw new NotSupportedException($"ClipNDArray not supported for dtype {@out.GetTypeCode}");
}
}
else // max is not null
{
// Max only - use ClipArrayMax
switch (@out.GetTypeCode)
{
case NPTypeCode.Byte:
ILKernelGenerator.ClipArrayMax((byte*)@out.Address, (byte*)max.Address, len);
return @out;
case NPTypeCode.Int16:
ILKernelGenerator.ClipArrayMax((short*)@out.Address, (short*)max.Address, len);
return @out;
case NPTypeCode.UInt16:
ILKernelGenerator.ClipArrayMax((ushort*)@out.Address, (ushort*)max.Address, len);
return @out;
case NPTypeCode.Int32:
ILKernelGenerator.ClipArrayMax((int*)@out.Address, (int*)max.Address, len);
return @out;
case NPTypeCode.UInt32:
ILKernelGenerator.ClipArrayMax((uint*)@out.Address, (uint*)max.Address, len);
return @out;
case NPTypeCode.Int64:
ILKernelGenerator.ClipArrayMax((long*)@out.Address, (long*)max.Address, len);
return @out;
case NPTypeCode.UInt64:
ILKernelGenerator.ClipArrayMax((ulong*)@out.Address, (ulong*)max.Address, len);
return @out;
case NPTypeCode.Single:
ILKernelGenerator.ClipArrayMax((float*)@out.Address, (float*)max.Address, len);
return @out;
case NPTypeCode.Double:
ILKernelGenerator.ClipArrayMax((double*)@out.Address, (double*)max.Address, len);
return @out;
case NPTypeCode.Decimal:
ClipArrayMaxDecimal((decimal*)@out.Address, (decimal*)max.Address, len);
return @out;
case NPTypeCode.Char:
ClipArrayMaxChar((char*)@out.Address, (char*)max.Address, len);
return @out;
default:
throw new NotSupportedException($"ClipNDArray not supported for dtype {@out.GetTypeCode}");
}
}
}
/// <summary>
/// General path for non-contiguous/broadcast arrays - uses GetAtIndex for element access.
/// </summary>
private unsafe NDArray ClipNDArrayGeneral(NDArray @out, NDArray min, NDArray max, int len)
{
if (!(min is null) && !(max is null))
{
switch (@out.GetTypeCode)
{
case NPTypeCode.Byte:
ClipNDArrayGeneralCore<byte>(@out, min, max, len);
return @out;
case NPTypeCode.Int16:
ClipNDArrayGeneralCore<short>(@out, min, max, len);
return @out;
case NPTypeCode.UInt16:
ClipNDArrayGeneralCore<ushort>(@out, min, max, len);
return @out;
case NPTypeCode.Int32:
ClipNDArrayGeneralCore<int>(@out, min, max, len);
return @out;
case NPTypeCode.UInt32:
ClipNDArrayGeneralCore<uint>(@out, min, max, len);
return @out;
case NPTypeCode.Int64:
ClipNDArrayGeneralCore<long>(@out, min, max, len);
return @out;
case NPTypeCode.UInt64:
ClipNDArrayGeneralCore<ulong>(@out, min, max, len);
return @out;
case NPTypeCode.Single:
ClipNDArrayGeneralCore<float>(@out, min, max, len);
return @out;
case NPTypeCode.Double:
ClipNDArrayGeneralCore<double>(@out, min, max, len);
return @out;
case NPTypeCode.Decimal:
ClipNDArrayGeneralCore<decimal>(@out, min, max, len);
return @out;
case NPTypeCode.Char:
ClipNDArrayGeneralCore<char>(@out, min, max, len);
return @out;
default:
throw new NotSupportedException($"ClipNDArray not supported for dtype {@out.GetTypeCode}");
}
}
else if (!(min is null))
{
switch (@out.GetTypeCode)
{
case NPTypeCode.Byte:
ClipNDArrayMinGeneralCore<byte>(@out, min, len);
return @out;
case NPTypeCode.Int16:
ClipNDArrayMinGeneralCore<short>(@out, min, len);
return @out;
case NPTypeCode.UInt16:
ClipNDArrayMinGeneralCore<ushort>(@out, min, len);
return @out;
case NPTypeCode.Int32:
ClipNDArrayMinGeneralCore<int>(@out, min, len);
return @out;
case NPTypeCode.UInt32:
ClipNDArrayMinGeneralCore<uint>(@out, min, len);
return @out;
case NPTypeCode.Int64:
ClipNDArrayMinGeneralCore<long>(@out, min, len);
return @out;
case NPTypeCode.UInt64:
ClipNDArrayMinGeneralCore<ulong>(@out, min, len);
return @out;
case NPTypeCode.Single:
ClipNDArrayMinGeneralCore<float>(@out, min, len);
return @out;
case NPTypeCode.Double:
ClipNDArrayMinGeneralCore<double>(@out, min, len);
return @out;
case NPTypeCode.Decimal:
ClipNDArrayMinGeneralCore<decimal>(@out, min, len);
return @out;
case NPTypeCode.Char:
ClipNDArrayMinGeneralCore<char>(@out, min, len);
return @out;
default:
throw new NotSupportedException($"ClipNDArray not supported for dtype {@out.GetTypeCode}");
}
}
else // max is not null
{
switch (@out.GetTypeCode)
{
case NPTypeCode.Byte:
ClipNDArrayMaxGeneralCore<byte>(@out, max, len);
return @out;
case NPTypeCode.Int16:
ClipNDArrayMaxGeneralCore<short>(@out, max, len);
return @out;
case NPTypeCode.UInt16:
ClipNDArrayMaxGeneralCore<ushort>(@out, max, len);
return @out;
case NPTypeCode.Int32:
ClipNDArrayMaxGeneralCore<int>(@out, max, len);
return @out;
case NPTypeCode.UInt32:
ClipNDArrayMaxGeneralCore<uint>(@out, max, len);
return @out;
case NPTypeCode.Int64:
ClipNDArrayMaxGeneralCore<long>(@out, max, len);
return @out;
case NPTypeCode.UInt64:
ClipNDArrayMaxGeneralCore<ulong>(@out, max, len);
return @out;
case NPTypeCode.Single:
ClipNDArrayMaxGeneralCore<float>(@out, max, len);
return @out;
case NPTypeCode.Double:
ClipNDArrayMaxGeneralCore<double>(@out, max, len);
return @out;
case NPTypeCode.Decimal:
ClipNDArrayMaxGeneralCore<decimal>(@out, max, len);
return @out;
case NPTypeCode.Char:
ClipNDArrayMaxGeneralCore<char>(@out, max, len);
return @out;
default:
throw new NotSupportedException($"ClipNDArray not supported for dtype {@out.GetTypeCode}");
}
}
}
#region General Path Core Methods
private static unsafe void ClipNDArrayGeneralCore<T>(NDArray @out, NDArray min, NDArray max, int len)
where T : unmanaged, IComparable<T>
{
// Use specialized implementations for float/double to handle NaN correctly
if (typeof(T) == typeof(float))
{
ClipNDArrayGeneralCoreFloat(@out, min, max, len);
return;
}
if (typeof(T) == typeof(double))
{
ClipNDArrayGeneralCoreDouble(@out, min, max, len);
return;
}
var outAddr = (T*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var minVal = Converts.ChangeType<T>(min.GetAtIndex(i));
var maxVal = Converts.ChangeType<T>(max.GetAtIndex(i));
// NumPy semantics: min(max(val, minVal), maxVal)
if (val.CompareTo(minVal) < 0)
val = minVal;
if (val.CompareTo(maxVal) > 0)
val = maxVal;
outAddr[outOffset] = val;
}
}
private static unsafe void ClipNDArrayMinGeneralCore<T>(NDArray @out, NDArray min, int len)
where T : unmanaged, IComparable<T>
{
// Use specialized implementations for float/double to handle NaN correctly
if (typeof(T) == typeof(float))
{
ClipNDArrayMinGeneralCoreFloat(@out, min, len);
return;
}
if (typeof(T) == typeof(double))
{
ClipNDArrayMinGeneralCoreDouble(@out, min, len);
return;
}
var outAddr = (T*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var minVal = Converts.ChangeType<T>(min.GetAtIndex(i));
if (val.CompareTo(minVal) < 0)
outAddr[outOffset] = minVal;
}
}
private static unsafe void ClipNDArrayMaxGeneralCore<T>(NDArray @out, NDArray max, int len)
where T : unmanaged, IComparable<T>
{
// Use specialized implementations for float/double to handle NaN correctly
if (typeof(T) == typeof(float))
{
ClipNDArrayMaxGeneralCoreFloat(@out, max, len);
return;
}
if (typeof(T) == typeof(double))
{
ClipNDArrayMaxGeneralCoreDouble(@out, max, len);
return;
}
var outAddr = (T*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var maxVal = Converts.ChangeType<T>(max.GetAtIndex(i));
if (val.CompareTo(maxVal) > 0)
outAddr[outOffset] = maxVal;
}
}
#region Floating-Point General Path (NaN-aware)
// These use Math.Max/Min which properly propagate NaN per IEEE semantics
private static unsafe void ClipNDArrayGeneralCoreFloat(NDArray @out, NDArray min, NDArray max, int len)
{
var outAddr = (float*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var minVal = Converts.ToSingle(min.GetAtIndex(i));
var maxVal = Converts.ToSingle(max.GetAtIndex(i));
outAddr[outOffset] = Math.Min(Math.Max(val, minVal), maxVal);
}
}
private static unsafe void ClipNDArrayGeneralCoreDouble(NDArray @out, NDArray min, NDArray max, int len)
{
var outAddr = (double*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var minVal = Converts.ToDouble(min.GetAtIndex(i));
var maxVal = Converts.ToDouble(max.GetAtIndex(i));
outAddr[outOffset] = Math.Min(Math.Max(val, minVal), maxVal);
}
}
private static unsafe void ClipNDArrayMinGeneralCoreFloat(NDArray @out, NDArray min, int len)
{
var outAddr = (float*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var minVal = Converts.ToSingle(min.GetAtIndex(i));
outAddr[outOffset] = Math.Max(val, minVal);
}
}
private static unsafe void ClipNDArrayMinGeneralCoreDouble(NDArray @out, NDArray min, int len)
{
var outAddr = (double*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var minVal = Converts.ToDouble(min.GetAtIndex(i));
outAddr[outOffset] = Math.Max(val, minVal);
}
}
private static unsafe void ClipNDArrayMaxGeneralCoreFloat(NDArray @out, NDArray max, int len)
{
var outAddr = (float*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var maxVal = Converts.ToSingle(max.GetAtIndex(i));
outAddr[outOffset] = Math.Min(val, maxVal);
}
}
private static unsafe void ClipNDArrayMaxGeneralCoreDouble(NDArray @out, NDArray max, int len)
{
var outAddr = (double*)@out.Address;
for (int i = 0; i < len; i++)
{
int outOffset = @out.Shape.TransformOffset(i);
var val = outAddr[outOffset];
var maxVal = Converts.ToDouble(max.GetAtIndex(i));
outAddr[outOffset] = Math.Min(val, maxVal);
}
}
#endregion
#endregion
#region Scalar Fallbacks for Non-SIMD Types (Decimal, Char) - Array Bounds
private static unsafe void ClipArrayBoundsDecimal(decimal* output, decimal* minArr, decimal* maxArr, int size)
{
for (int i = 0; i < size; i++)
{
var val = output[i];
if (val < minArr[i]) val = minArr[i];
if (val > maxArr[i]) val = maxArr[i];
output[i] = val;
}
}
private static unsafe void ClipArrayMinDecimal(decimal* output, decimal* minArr, int size)
{
for (int i = 0; i < size; i++)
if (output[i] < minArr[i]) output[i] = minArr[i];
}
private static unsafe void ClipArrayMaxDecimal(decimal* output, decimal* maxArr, int size)
{
for (int i = 0; i < size; i++)
if (output[i] > maxArr[i]) output[i] = maxArr[i];
}
private static unsafe void ClipArrayBoundsChar(char* output, char* minArr, char* maxArr, int size)
{
for (int i = 0; i < size; i++)
{
var val = output[i];
if (val < minArr[i]) val = minArr[i];
if (val > maxArr[i]) val = maxArr[i];
output[i] = val;
}
}
private static unsafe void ClipArrayMinChar(char* output, char* minArr, int size)
{
for (int i = 0; i < size; i++)
if (output[i] < minArr[i]) output[i] = minArr[i];
}
private static unsafe void ClipArrayMaxChar(char* output, char* maxArr, int size)
{
for (int i = 0; i < size; i++)
if (output[i] > maxArr[i]) output[i] = maxArr[i];
}
#endregion
}
}