-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy patharrayDistance.cpp
More file actions
1054 lines (911 loc) · 41.1 KB
/
Copy patharrayDistance.cpp
File metadata and controls
1054 lines (911 loc) · 41.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <Columns/ColumnArray.h>
#include <Columns/IColumn.h>
#include <Common/TargetSpecific.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/IDataType.h>
#include <DataTypes/getLeastSupertype.h>
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionHelpers.h>
#include <Functions/checkLpNormPArgument.h>
#include <cmath>
#if USE_MULTITARGET_CODE
#include <immintrin.h>
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_COLUMN;
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int LOGICAL_ERROR;
extern const int SIZES_OF_ARRAYS_DONT_MATCH;
}
#if USE_MULTITARGET_CODE
/// Widen 16 packed `BFloat16` to `Float32` without AVX512-BF16: a `BFloat16` is the upper 16 bits of the
/// corresponding `Float32`, so zero-extend each 16-bit value to 32 bits and shift it into the high half.
/// Uses only AVX-512F/BW, so it runs on all `x86-64-v4` CPUs (not just AVX512-BF16 ones), and it is faster
/// than the native `dpbf16` / BFloat16->Float32 convert instructions, which are throughput-limited.
X86_64_V4_FUNCTION_SPECIFIC_ATTRIBUTE static inline __m512 loadBFloat16AsFloat32(const BFloat16 * p)
{
const __m256i raw = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(p));
return _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(raw), 16));
}
#endif
struct L1Distance
{
static constexpr auto name = "L1";
struct ConstParams {};
template <typename FloatType>
struct State
{
FloatType sum{};
};
template <typename ResultType>
static void accumulate(State<ResultType> & state, ResultType x, ResultType y, const ConstParams &)
{
state.sum += std::fabs(x - y);
}
template <typename ResultType>
static void combine(State<ResultType> & state, const State<ResultType> & other_state, const ConstParams &)
{
state.sum += other_state.sum;
}
template <typename ResultType>
static ResultType finalize(const State<ResultType> & state, const ConstParams &)
{
return state.sum;
}
};
struct L2Distance
{
static constexpr auto name = "L2";
struct ConstParams {};
template <typename FloatType>
struct State
{
FloatType sum{};
};
template <typename ResultType>
static void accumulate(State<ResultType> & state, ResultType x, ResultType y, const ConstParams &)
{
state.sum += (x - y) * (x - y);
}
template <typename ResultType>
static void combine(State<ResultType> & state, const State<ResultType> & other_state, const ConstParams &)
{
state.sum += other_state.sum;
}
#if USE_MULTITARGET_CODE
template <typename ResultType>
X86_64_V4_FUNCTION_SPECIFIC_ATTRIBUTE static void accumulateCombineF32F64(
const ResultType * __restrict data_x,
const ResultType * __restrict data_y,
size_t i_max,
size_t & i_x,
size_t & i_y,
State<ResultType> & state)
{
static constexpr bool is_float32 = std::is_same_v<ResultType, Float32>;
__m512 sums;
if constexpr (is_float32)
sums = _mm512_setzero_ps();
else
sums = _mm512_setzero_pd();
constexpr size_t n = sizeof(__m512) / sizeof(ResultType);
for (; i_x + n <= i_max; i_x += n, i_y += n)
{
if constexpr (is_float32)
{
__m512 x = _mm512_loadu_ps(data_x + i_x);
__m512 y = _mm512_loadu_ps(data_y + i_y);
__m512 differences = _mm512_sub_ps(x, y);
sums = _mm512_fmadd_ps(differences, differences, sums);
}
else
{
__m512 x = _mm512_loadu_pd(data_x + i_x);
__m512 y = _mm512_loadu_pd(data_y + i_y);
__m512 differences = _mm512_sub_pd(x, y);
sums = _mm512_fmadd_pd(differences, differences, sums);
}
}
if constexpr (is_float32)
state.sum = _mm512_reduce_add_ps(sums);
else
state.sum = _mm512_reduce_add_pd(sums);
}
X86_64_V4_FUNCTION_SPECIFIC_ATTRIBUTE static void accumulateCombineBF16(
const BFloat16 * __restrict data_x,
const BFloat16 * __restrict data_y,
size_t i_max,
size_t & i_x,
size_t & i_y,
State<Float32> & state)
{
__m512 sums = _mm512_setzero_ps();
constexpr size_t n = sizeof(__m512) / sizeof(Float32);
for (; i_x + n <= i_max; i_x += n, i_y += n)
{
__m512 differences = _mm512_sub_ps(loadBFloat16AsFloat32(data_x + i_x), loadBFloat16AsFloat32(data_y + i_y));
sums = _mm512_fmadd_ps(differences, differences, sums);
}
state.sum = _mm512_reduce_add_ps(sums);
}
#endif
template <typename ResultType>
static ResultType finalize(const State<ResultType> & state, const ConstParams &)
{
return std::sqrt(state.sum);
}
};
struct L2SquaredDistance : L2Distance
{
static constexpr auto name = "L2Squared";
template <typename ResultType>
static ResultType finalize(const State<ResultType> & state, const ConstParams &)
{
return state.sum;
}
};
struct LpDistance
{
static constexpr auto name = "Lp";
struct ConstParams
{
Float64 power;
Float64 inverted_power;
};
template <typename FloatType>
struct State
{
FloatType sum{};
};
template <typename ResultType>
static void accumulate(State<ResultType> & state, ResultType x, ResultType y, const ConstParams & params)
{
state.sum += static_cast<ResultType>(std::pow(static_cast<double>(std::fabs(x - y)), params.power));
}
template <typename ResultType>
static void combine(State<ResultType> & state, const State<ResultType> & other_state, const ConstParams &)
{
state.sum += other_state.sum;
}
template <typename ResultType>
static ResultType finalize(const State<ResultType> & state, const ConstParams & params)
{
return static_cast<ResultType>(std::pow(static_cast<double>(state.sum), params.inverted_power));
}
};
struct LinfDistance
{
static constexpr auto name = "Linf";
struct ConstParams {};
template <typename FloatType>
struct State
{
FloatType dist{};
};
template <typename ResultType>
static void accumulate(State<ResultType> & state, ResultType x, ResultType y, const ConstParams &)
{
state.dist = std::fmax(state.dist, std::fabs(x - y));
}
template <typename ResultType>
static void combine(State<ResultType> & state, const State<ResultType> & other_state, const ConstParams &)
{
state.dist = std::fmax(state.dist, other_state.dist);
}
template <typename ResultType>
static ResultType finalize(const State<ResultType> & state, const ConstParams &)
{
return state.dist;
}
};
struct CosineDistance
{
static constexpr auto name = "Cosine";
struct ConstParams {};
template <typename FloatType>
struct State
{
FloatType dot_prod{};
FloatType x_squared{};
FloatType y_squared{};
};
template <typename ResultType>
static void accumulate(State<ResultType> & state, ResultType x, ResultType y, const ConstParams &)
{
state.dot_prod += x * y;
state.x_squared += x * x;
state.y_squared += y * y;
}
template <typename ResultType>
static void combine(State<ResultType> & state, const State<ResultType> & other_state, const ConstParams &)
{
state.dot_prod += other_state.dot_prod;
state.x_squared += other_state.x_squared;
state.y_squared += other_state.y_squared;
}
#if USE_MULTITARGET_CODE
template <typename ResultType>
X86_64_V4_FUNCTION_SPECIFIC_ATTRIBUTE static void accumulateCombineF32F64(
const ResultType * __restrict data_x,
const ResultType * __restrict data_y,
size_t i_max,
size_t & i_x,
size_t & i_y,
State<ResultType> & state)
{
static constexpr bool is_float32 = std::is_same_v<ResultType, Float32>;
__m512 dot_products;
__m512 x_squareds;
__m512 y_squareds;
if constexpr (is_float32)
{
dot_products = _mm512_setzero_ps();
x_squareds = _mm512_setzero_ps();
y_squareds = _mm512_setzero_ps();
}
else
{
dot_products = _mm512_setzero_pd();
x_squareds = _mm512_setzero_pd();
y_squareds = _mm512_setzero_pd();
}
constexpr size_t n = sizeof(__m512) / sizeof(ResultType);
for (; i_x + n <= i_max; i_x += n, i_y += n)
{
if constexpr (is_float32)
{
__m512 x = _mm512_loadu_ps(data_x + i_x);
__m512 y = _mm512_loadu_ps(data_y + i_y);
dot_products = _mm512_fmadd_ps(x, y, dot_products);
x_squareds = _mm512_fmadd_ps(x, x, x_squareds);
y_squareds = _mm512_fmadd_ps(y, y, y_squareds);
}
else
{
__m512 x = _mm512_loadu_pd(data_x + i_x);
__m512 y = _mm512_loadu_pd(data_y + i_y);
dot_products = _mm512_fmadd_pd(x, y, dot_products);
x_squareds = _mm512_fmadd_pd(x, x, x_squareds);
y_squareds = _mm512_fmadd_pd(y, y, y_squareds);
}
}
if constexpr (is_float32)
{
state.dot_prod = _mm512_reduce_add_ps(dot_products);
state.x_squared = _mm512_reduce_add_ps(x_squareds);
state.y_squared = _mm512_reduce_add_ps(y_squareds);
}
else
{
state.dot_prod = _mm512_reduce_add_pd(dot_products);
state.x_squared = _mm512_reduce_add_pd(x_squareds);
state.y_squared = _mm512_reduce_add_pd(y_squareds);
}
}
X86_64_V4_FUNCTION_SPECIFIC_ATTRIBUTE static void accumulateCombineBF16(
const BFloat16 * __restrict data_x,
const BFloat16 * __restrict data_y,
size_t i_max,
size_t & i_x,
size_t & i_y,
State<Float32> & state)
{
__m512 dot_products = _mm512_setzero_ps();
__m512 x_squareds = _mm512_setzero_ps();
__m512 y_squareds = _mm512_setzero_ps();
constexpr size_t n = sizeof(__m512) / sizeof(Float32);
for (; i_x + n <= i_max; i_x += n, i_y += n)
{
__m512 x = loadBFloat16AsFloat32(data_x + i_x);
__m512 y = loadBFloat16AsFloat32(data_y + i_y);
dot_products = _mm512_fmadd_ps(x, y, dot_products);
x_squareds = _mm512_fmadd_ps(x, x, x_squareds);
y_squareds = _mm512_fmadd_ps(y, y, y_squareds);
}
state.dot_prod = _mm512_reduce_add_ps(dot_products);
state.x_squared = _mm512_reduce_add_ps(x_squareds);
state.y_squared = _mm512_reduce_add_ps(y_squareds);
}
#endif
template <typename ResultType>
static ResultType finalize(const State<ResultType> & state, const ConstParams &)
{
return ResultType{1} - state.dot_prod / std::sqrt(state.x_squared * state.y_squared);
}
};
template <typename ResultType, typename LeftType, typename RightType>
constexpr bool is_native_distance_type = std::is_same_v<ResultType, LeftType> && std::is_same_v<ResultType, RightType>;
template <typename LeftType, typename RightType, typename A, typename B>
constexpr bool is_unordered_pair = (std::is_same_v<LeftType, A> && std::is_same_v<RightType, B>)
|| (std::is_same_v<LeftType, B> && std::is_same_v<RightType, A>);
/// Common mixed-type pairs that warrant SIMD specialisation. Selection mirrors
/// real-world vector-search workloads:
/// - UInt8 <-> Float32/Float64: quantised embeddings stored as UInt8 to save
/// space, queried against Float32/Float64 query vectors (typical for ANN).
/// - Float32 <-> Float64: cross-precision lookup (e.g. Float64 client query
/// against Float32 server-side storage).
/// Other mixed pairs fall through to the baseline (non-MULTITARGET) instantiation
/// of executeDistanceMixedImpl. The set is deliberately tiny: extending to the
/// full 11x11 numeric Cartesian product would explode MULTITARGET instantiations
/// to 11*11*6*2*3 = 4356 .text copies and push arrayDistance.o past the 50 MB
/// CI object-size limit.
template <typename LeftType, typename RightType>
constexpr bool is_common_mixed_pair = is_unordered_pair<LeftType, RightType, UInt8, Float32>
|| is_unordered_pair<LeftType, RightType, UInt8, Float64>
|| is_unordered_pair<LeftType, RightType, Float32, Float64>;
/// Per-row accumulator unroll width for the four distance hot loops below.
///
/// Fixed at 8, not the wider `128 / sizeof(ResultType)`. These loops run once
/// per row, so the per-row fixed cost (scalar remainder tail + horizontal
/// reduction over the partial states) grows with the unroll width. For the
/// short vectors typical of vector search (e.g. 150 dims) a width of 32 leaves
/// ~15% of each row in the scalar tail and regresses L1/L2/Linf/cosine on both
/// x86 and ARM; widths >= 16 also overflow the register file for the
/// three-accumulator cosineDistance kernel. 8 was the measured sweet spot over
/// dims 150..1024 on both ISAs, matching the previous hand-tuned const-path
/// value. See PR #101310.
constexpr size_t distance_unroll_count = 8;
/// Multi-target hot loop for the native same-type path (LeftType == RightType == ResultType).
/// The MULTITARGET macro generates _x86_64_v4, _x86_64_v3, and default versions
/// so the compiler can auto-vectorize with the best available ISA.
///
/// Mixed-type pairs do NOT use this kernel; they go through `executeDistanceMixed` which casts
/// per element inside the hot loop instead of pre-converting full columns. Templating only on
/// <Kernel, ResultType> here keeps the LeftType x RightType x arch instantiation explosion bounded.
MULTITARGET_FUNCTION_X86_V4_V3(
MULTITARGET_FUNCTION_HEADER(
template <typename Kernel, typename ResultType>
void NO_INLINE
), executeDistanceImpl, MULTITARGET_FUNCTION_BODY((
const ResultType * __restrict data_x,
const ResultType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
constexpr size_t unroll_count = distance_unroll_count;
ColumnArray::Offset prev = 0;
for (size_t row = 0; row < row_count; ++row)
{
const auto off = offsets[row];
const size_t count = off - prev;
typename Kernel::template State<ResultType> partial[unroll_count];
size_t i = 0;
const size_t unrolled_end = count / unroll_count * unroll_count;
/// Keep this outer loop scalar: `clang-22` otherwise vectorizes it into a slow strided gather instead of letting the unrolled inner loop SLP-vectorize into contiguous loads (worst for `Linf`/`BFloat16`).
_Pragma("clang loop vectorize(disable)")
for (; i < unrolled_end; i += unroll_count)
for (size_t s = 0; s < unroll_count; ++s)
Kernel::template accumulate<ResultType>(
partial[s],
data_x[prev + i + s],
data_y[prev + i + s],
params);
typename Kernel::template State<ResultType> state;
for (const auto & p : partial)
Kernel::template combine<ResultType>(state, p, params);
for (; i < count; ++i)
Kernel::template accumulate<ResultType>(
state,
data_x[prev + i],
data_y[prev + i],
params);
result[row] = Kernel::finalize(state, params);
prev = off;
}
}))
template <typename Kernel, typename ResultType>
void executeDistance(
const ResultType * __restrict data_x,
const ResultType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
#if USE_MULTITARGET_CODE
if (isArchSupported(TargetArch::x86_64_v4))
return executeDistanceImpl_x86_64_v4<Kernel, ResultType>(data_x, data_y, offsets, result, row_count, params);
if (isArchSupported(TargetArch::x86_64_v3))
return executeDistanceImpl_x86_64_v3<Kernel, ResultType>(data_x, data_y, offsets, result, row_count, params);
#endif
executeDistanceImpl<Kernel, ResultType>(data_x, data_y, offsets, result, row_count, params);
}
/// Streaming mixed-type path. It casts individual elements inside the hot loop
/// and never materialises converted full-column buffers.
///
/// One MULTITARGET definition serves both common and uncommon pairs:
/// - Common pairs (see is_common_mixed_pair) call executeDistanceMixedImpl_x86_64_v3/v4
/// for SIMD acceleration.
/// - Other mixed pairs fall back to the baseline (non-MULTITARGET) instantiation
/// of executeDistanceMixedImpl, keeping LeftType x RightType x ISA explosion bounded.
MULTITARGET_FUNCTION_X86_V4_V3(
MULTITARGET_FUNCTION_HEADER(
template <typename Kernel, typename ResultType, typename LeftType, typename RightType>
void NO_INLINE
), executeDistanceMixedImpl, MULTITARGET_FUNCTION_BODY((
const LeftType * __restrict data_x,
const RightType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
constexpr size_t unroll_count = distance_unroll_count;
ColumnArray::Offset prev = 0;
for (size_t row = 0; row < row_count; ++row)
{
const auto off = offsets[row];
const size_t count = off - prev;
typename Kernel::template State<ResultType> partial[unroll_count];
size_t i = 0;
const size_t unrolled_end = count / unroll_count * unroll_count;
_Pragma("clang loop vectorize(disable)")
for (; i < unrolled_end; i += unroll_count)
for (size_t s = 0; s < unroll_count; ++s)
Kernel::template accumulate<ResultType>(
partial[s],
static_cast<ResultType>(data_x[prev + i + s]),
static_cast<ResultType>(data_y[prev + i + s]),
params);
typename Kernel::template State<ResultType> state;
for (const auto & p : partial)
Kernel::template combine<ResultType>(state, p, params);
for (; i < count; ++i)
Kernel::template accumulate<ResultType>(
state,
static_cast<ResultType>(data_x[prev + i]),
static_cast<ResultType>(data_y[prev + i]),
params);
result[row] = Kernel::finalize(state, params);
prev = off;
}
}))
template <typename Kernel, typename ResultType, typename LeftType, typename RightType>
void executeDistanceMixed(
const LeftType * __restrict data_x,
const RightType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
#if USE_MULTITARGET_CODE
if constexpr (is_common_mixed_pair<LeftType, RightType>)
{
if (isArchSupported(TargetArch::x86_64_v4))
return executeDistanceMixedImpl_x86_64_v4<Kernel, ResultType, LeftType, RightType>(
data_x, data_y, offsets, result, row_count, params);
if (isArchSupported(TargetArch::x86_64_v3))
return executeDistanceMixedImpl_x86_64_v3<Kernel, ResultType, LeftType, RightType>(
data_x, data_y, offsets, result, row_count, params);
}
#endif
executeDistanceMixedImpl<Kernel, ResultType, LeftType, RightType>(data_x, data_y, offsets, result, row_count, params);
}
/// Multi-target hot loop for const x non-const path.
/// data_x is the constant array (repeated for every row), data_y varies per row.
MULTITARGET_FUNCTION_X86_V4_V3(
MULTITARGET_FUNCTION_HEADER(
template <typename Kernel, typename ResultType>
void NO_INLINE
), executeDistanceConstImpl, MULTITARGET_FUNCTION_BODY((
const ResultType * __restrict data_x,
size_t array_size,
const ResultType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
constexpr size_t unroll_count = distance_unroll_count;
ColumnArray::Offset prev = 0;
for (size_t row = 0; row < row_count; ++row)
{
const auto off = offsets[row];
const size_t count = off - prev;
chassert(count == array_size);
typename Kernel::template State<ResultType> partial[unroll_count];
size_t i = 0;
const size_t unrolled_end = array_size / unroll_count * unroll_count;
_Pragma("clang loop vectorize(disable)")
for (; i < unrolled_end; i += unroll_count)
for (size_t s = 0; s < unroll_count; ++s)
Kernel::template accumulate<ResultType>(
partial[s],
data_x[i + s],
data_y[prev + i + s],
params);
typename Kernel::template State<ResultType> state;
for (const auto & p : partial)
Kernel::template combine<ResultType>(state, p, params);
for (; i < array_size; ++i)
Kernel::template accumulate<ResultType>(
state,
data_x[i],
data_y[prev + i],
params);
result[row] = Kernel::finalize(state, params);
prev = off;
}
}))
template <typename Kernel, typename ResultType>
void executeDistanceConst(
const ResultType * __restrict data_x,
size_t array_size,
const ResultType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
#if USE_MULTITARGET_CODE
if (isArchSupported(TargetArch::x86_64_v4))
return executeDistanceConstImpl_x86_64_v4<Kernel, ResultType>(data_x, array_size, data_y, offsets, result, row_count, params);
if (isArchSupported(TargetArch::x86_64_v3))
return executeDistanceConstImpl_x86_64_v3<Kernel, ResultType>(data_x, array_size, data_y, offsets, result, row_count, params);
#endif
executeDistanceConstImpl<Kernel, ResultType>(data_x, array_size, data_y, offsets, result, row_count, params);
}
/// const-left mirror of executeDistanceMixedImpl. Same MULTITARGET strategy:
/// common pairs get x86_64_v3/v4 instances, other pairs reuse the baseline.
MULTITARGET_FUNCTION_X86_V4_V3(
MULTITARGET_FUNCTION_HEADER(
template <typename Kernel, typename ResultType, typename LeftType, typename RightType>
void NO_INLINE
), executeDistanceConstMixedImpl, MULTITARGET_FUNCTION_BODY((
const LeftType * __restrict data_x,
size_t array_size,
const RightType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
constexpr size_t unroll_count = distance_unroll_count;
ColumnArray::Offset prev = 0;
for (size_t row = 0; row < row_count; ++row)
{
const auto off = offsets[row];
const size_t count = off - prev;
chassert(count == array_size);
typename Kernel::template State<ResultType> partial[unroll_count];
size_t i = 0;
const size_t unrolled_end = array_size / unroll_count * unroll_count;
_Pragma("clang loop vectorize(disable)")
for (; i < unrolled_end; i += unroll_count)
for (size_t s = 0; s < unroll_count; ++s)
Kernel::template accumulate<ResultType>(
partial[s],
static_cast<ResultType>(data_x[i + s]),
static_cast<ResultType>(data_y[prev + i + s]),
params);
typename Kernel::template State<ResultType> state;
for (const auto & p : partial)
Kernel::template combine<ResultType>(state, p, params);
for (; i < array_size; ++i)
Kernel::template accumulate<ResultType>(
state,
static_cast<ResultType>(data_x[i]),
static_cast<ResultType>(data_y[prev + i]),
params);
result[row] = Kernel::finalize(state, params);
prev = off;
}
}))
template <typename Kernel, typename ResultType, typename LeftType, typename RightType>
void executeDistanceConstMixed(
const LeftType * __restrict data_x,
size_t array_size,
const RightType * __restrict data_y,
const ColumnArray::Offset * __restrict offsets,
ResultType * __restrict result,
size_t row_count,
const typename Kernel::ConstParams & params)
{
#if USE_MULTITARGET_CODE
if constexpr (is_common_mixed_pair<LeftType, RightType>)
{
if (isArchSupported(TargetArch::x86_64_v4))
return executeDistanceConstMixedImpl_x86_64_v4<Kernel, ResultType, LeftType, RightType>(
data_x, array_size, data_y, offsets, result, row_count, params);
if (isArchSupported(TargetArch::x86_64_v3))
return executeDistanceConstMixedImpl_x86_64_v3<Kernel, ResultType, LeftType, RightType>(
data_x, array_size, data_y, offsets, result, row_count, params);
}
#endif
executeDistanceConstMixedImpl<Kernel, ResultType, LeftType, RightType>(
data_x, array_size, data_y, offsets, result, row_count, params);
}
template <typename Kernel>
class FunctionArrayDistance : public IFunction
{
public:
String getName() const override
{
static auto name = String("array") + Kernel::name + "Distance";
return name;
}
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionArrayDistance<Kernel>>(); }
size_t getNumberOfArguments() const override { return 2; }
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {}; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
bool useDefaultImplementationForConstants() const override { return true; }
DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
{
DataTypes types;
for (size_t i = 0; i < 2; ++i)
{
const auto * array_type = checkAndGetDataType<DataTypeArray>(arguments[i].type.get());
if (!array_type)
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Argument {} of function {} must be array.", i, getName());
types.push_back(array_type->getNestedType());
}
if constexpr (std::is_same_v<Kernel, LpDistance>)
checkLpNormPArgumentForAnalysis(arguments[2], getName());
const DataTypePtr & common_type = getLeastSupertype(types);
switch (common_type->getTypeId())
{
case TypeIndex::BFloat16: /// (*)
case TypeIndex::Float32:
return std::make_shared<DataTypeFloat32>();
case TypeIndex::UInt8:
case TypeIndex::UInt16:
case TypeIndex::UInt32:
case TypeIndex::UInt64:
case TypeIndex::Int8:
case TypeIndex::Int16:
case TypeIndex::Int32:
case TypeIndex::Int64:
case TypeIndex::Float64:
return std::make_shared<DataTypeFloat64>();
default:
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Arguments of function {} has nested type {}. "
"Supported types: UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, BFloat16, Float32, Float64.",
getName(),
common_type->getName());
/// (*) You may ask why we return Float32 instead of BFloat16 for Array(BFloat16) arguments.
/// The reason is that Intels' SIMD support for BFloat16 that is extremely limited at the moment, see
/// https://en.wikichip.org/wiki/x86/avx512_bf16 for AVX-512 BF16. To calculate the common L2 and cosine distances with
/// SIMD, we need to cast up or relinquish SIMD support. (Interestingly, FP16 (IEEE 754 binary16) is well supported by
/// AVX-512 but nobody seems to likes FP16 these days ...)
}
}
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
{
switch (result_type->getTypeId())
{
case TypeIndex::Float32:
return executeWithResultType<Float32>(arguments, input_rows_count);
case TypeIndex::Float64:
return executeWithResultType<Float64>(arguments, input_rows_count);
default:
throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected result type {}", result_type->getName());
}
}
#define SUPPORTED_TYPES(ACTION) \
ACTION(UInt8) \
ACTION(UInt16) \
ACTION(UInt32) \
ACTION(UInt64) \
ACTION(Int8) \
ACTION(Int16) \
ACTION(Int32) \
ACTION(Int64) \
ACTION(BFloat16) \
ACTION(Float32) \
ACTION(Float64)
private:
/// Mirror of the getLeastSupertype-based mapping in getReturnTypeImpl: the result is Float32
/// iff both operand types are representable in Float32 (small ints, BFloat16, Float32) and at
/// least one of them is a small float (otherwise the supertype is an integer type, which maps
/// to Float64). For every (left, right) pair exactly one ResultType is reachable, so guarding
/// the kernel instantiations with this predicate halves the number of instantiations.
template <typename T>
static constexpr bool is_small_float = std::is_same_v<T, BFloat16> || std::is_same_v<T, Float32>;
template <typename T>
static constexpr bool fits_float32 = is_small_float<T>
|| std::is_same_v<T, UInt8> || std::is_same_v<T, UInt16> || std::is_same_v<T, Int8> || std::is_same_v<T, Int16>;
template <typename ResultType, typename FirstArgType, typename SecondArgType>
static constexpr bool isReachableResultType()
{
constexpr bool is_float32_result = fits_float32<FirstArgType> && fits_float32<SecondArgType>
&& (is_small_float<FirstArgType> || is_small_float<SecondArgType>);
return std::is_same_v<ResultType, Float32> == is_float32_result;
}
template <typename ResultType>
ColumnPtr executeWithResultType(const ColumnsWithTypeAndName & arguments, size_t input_rows_count) const
{
DataTypePtr type_x = typeid_cast<const DataTypeArray *>(arguments[0].type.get())->getNestedType();
switch (type_x->getTypeId())
{
#define ON_TYPE(type) \
case TypeIndex::type: \
return executeWithResultTypeAndLeftType<ResultType, type>(arguments, input_rows_count); \
break;
SUPPORTED_TYPES(ON_TYPE)
#undef ON_TYPE
default:
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Arguments of function {} have nested type {}. "
"Supported types: UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, BFloat16, Float32, Float64.",
getName(),
type_x->getName());
}
}
template <typename ResultType, typename LeftType>
ColumnPtr executeWithResultTypeAndLeftType(const ColumnsWithTypeAndName & arguments, size_t input_rows_count) const
{
DataTypePtr type_y = typeid_cast<const DataTypeArray *>(arguments[1].type.get())->getNestedType();
switch (type_y->getTypeId())
{
#define ON_TYPE(type) \
case TypeIndex::type: \
if constexpr (isReachableResultType<ResultType, LeftType, type>()) \
return executeWithResultTypeAndLeftTypeAndRightType<ResultType, LeftType, type>(arguments[0].column, arguments[1].column, input_rows_count, arguments); \
else \
throw Exception( \
ErrorCodes::LOGICAL_ERROR, \
"Result type {} of function {} is impossible for operand types {} and {}", \
TypeName<ResultType>, getName(), TypeName<LeftType>, TypeName<type>); \
break;
SUPPORTED_TYPES(ON_TYPE)
#undef ON_TYPE
default:
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Arguments of function {} have nested type {}. "
"Supported types: UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, BFloat16, Float32, Float64.",
getName(),
type_y->getName());
}
}
template <typename ResultType, typename LeftType, typename RightType>
ColumnPtr executeWithResultTypeAndLeftTypeAndRightType(ColumnPtr col_x, ColumnPtr col_y, size_t input_rows_count, const ColumnsWithTypeAndName & arguments) const
{
if (col_x->isConst())
return executeWithLeftArgConst<ResultType, LeftType, RightType>(col_x, col_y, input_rows_count, arguments);
if (col_y->isConst())
return executeWithLeftArgConst<ResultType, RightType, LeftType>(col_y, col_x, input_rows_count, arguments);
const auto & array_x = *assert_cast<const ColumnArray *>(col_x.get());
const auto & array_y = *assert_cast<const ColumnArray *>(col_y.get());
const auto & data_x = typeid_cast<const ColumnVector<LeftType> &>(array_x.getData()).getData();
const auto & data_y = typeid_cast<const ColumnVector<RightType> &>(array_y.getData()).getData();
const auto & offsets_x = array_x.getOffsets();
if (!array_x.hasEqualOffsets(array_y))
throw Exception(ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH, "Array arguments for function {} must have equal sizes", getName());
const typename Kernel::ConstParams kernel_params = initConstParams(arguments);
auto col_res = ColumnVector<ResultType>::create(input_rows_count);
auto & result_data = col_res->getData();
if constexpr (is_native_distance_type<ResultType, LeftType, RightType>)
executeDistance<Kernel, ResultType>(
data_x.data(), data_y.data(), offsets_x.data(), result_data.data(), input_rows_count, kernel_params);
else
executeDistanceMixed<Kernel, ResultType, LeftType, RightType>(
data_x.data(), data_y.data(), offsets_x.data(), result_data.data(), input_rows_count, kernel_params);
return col_res;
}
/// Special case when the 1st parameter is Const
template <typename ResultType, typename LeftType, typename RightType>
ColumnPtr executeWithLeftArgConst(ColumnPtr col_x, ColumnPtr col_y, size_t input_rows_count, const ColumnsWithTypeAndName & arguments) const
{
col_x = assert_cast<const ColumnConst *>(col_x.get())->getDataColumnPtr();
col_y = col_y->convertToFullColumnIfConst();
const auto & array_x = *assert_cast<const ColumnArray *>(col_x.get());
const auto & array_y = *assert_cast<const ColumnArray *>(col_y.get());
const auto & data_x = typeid_cast<const ColumnVector<LeftType> &>(array_x.getData()).getData();
const auto & data_y = typeid_cast<const ColumnVector<RightType> &>(array_y.getData()).getData();
const auto & offsets_x = array_x.getOffsets();
const auto & offsets_y = array_y.getOffsets();
ColumnArray::Offset prev_offset = 0;
for (auto offset_y : offsets_y)
{
if (offsets_x[0] != offset_y - prev_offset)
throw Exception(ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH, "Array arguments for function {} must have equal sizes", getName());
prev_offset = offset_y;
}
const typename Kernel::ConstParams kernel_params = initConstParams(arguments);
auto result = ColumnVector<ResultType>::create(input_rows_count);
auto & result_data = result->getData();
/// Hand-written AVX-512 intrinsics for L2/Cosine with Float32/Float64/BFloat16.
/// These outperform compiler auto-vectorization for these specific kernels.
#if USE_MULTITARGET_CODE
if constexpr (std::is_same_v<Kernel, L2Distance> || std::is_same_v<Kernel, CosineDistance>)
{
if constexpr ((std::is_same_v<ResultType, Float32> && std::is_same_v<LeftType, Float32> && std::is_same_v<RightType, Float32>)
|| (std::is_same_v<ResultType, Float64> && std::is_same_v<LeftType, Float64> && std::is_same_v<RightType, Float64>))
{
if (isArchSupported(TargetArch::x86_64_v4))
{
size_t prev = 0;
for (size_t row = 0; row < input_rows_count; ++row)
{
const auto off = offsets_y[row];
size_t i = 0;
size_t j = prev;
typename Kernel::template State<ResultType> state;
Kernel::template accumulateCombineF32F64<ResultType>(data_x.data(), data_y.data(), i + offsets_x[0], i, j, state);
for (; j < off; ++i, ++j)
Kernel::template accumulate<ResultType>(
state, data_x[i], data_y[j], kernel_params);
result_data[row] = Kernel::finalize(state, kernel_params);
prev = off;
}
return result;
}
}
else if constexpr (std::is_same_v<ResultType, Float32> && std::is_same_v<LeftType, BFloat16> && std::is_same_v<RightType, BFloat16>)
{
if (isArchSupported(TargetArch::x86_64_v4))
{
size_t prev = 0;
for (size_t row = 0; row < input_rows_count; ++row)
{
const auto off = offsets_y[row];
size_t i = 0;
size_t j = prev;
typename Kernel::template State<Float32> state;
Kernel::accumulateCombineBF16(data_x.data(), data_y.data(), i + offsets_x[0], i, j, state);
for (; j < off; ++i, ++j)
Kernel::template accumulate<Float32>(
state, static_cast<Float32>(data_x[i]), static_cast<Float32>(data_y[j]), kernel_params);
result_data[row] = Kernel::finalize(state, kernel_params);
prev = off;
}
return result;
}
}
}
#endif
if constexpr (is_native_distance_type<ResultType, LeftType, RightType>)