profile_reduce_impl.hpp 29.5 KB
Newer Older
1
2
3
4
#pragma once
#include "device_reduce.hpp"
#include "device_reduce_instance.hpp"
#include "reduction_enums.hpp"
5
#include "host_reduction.hpp"
6
7
8
9
10
11

namespace ck {
namespace tensor_operation {
namespace device {
namespace device_reduce_instance {

Qianfeng's avatar
Qianfeng committed
12
template <int Rank, int NumReduceDim, int ReduceOpId, int NanOpt, int IndicesOpt>
13
14
struct ReduceDescription
{
Qianfeng's avatar
Qianfeng committed
15
16
17
18
19
    static constexpr int Rank_         = Rank;
    static constexpr int NumReduceDim_ = NumReduceDim;
    static constexpr int ReduceOpId_   = ReduceOpId;
    static constexpr int NanOpt_       = NanOpt;
    static constexpr int IndicesOpt_   = IndicesOpt;
20
21
};

Qianfeng's avatar
Qianfeng committed
22
using reduce_description_instances = std::tuple<ReduceDescription<4, 3, 0, 0, 0>, // for ADD
23
                                                ReduceDescription<4, 4, 0, 0, 0>,
Qianfeng's avatar
Qianfeng committed
24
25
26
27
                                                ReduceDescription<4, 1, 0, 0, 0>,
                                                ReduceDescription<2, 1, 0, 0, 0>,

                                                ReduceDescription<4, 3, 5, 0, 0>, // for AVG
28
                                                ReduceDescription<4, 4, 5, 0, 0>,
Qianfeng's avatar
Qianfeng committed
29
30
31
32
                                                ReduceDescription<4, 1, 5, 0, 0>,
                                                ReduceDescription<2, 1, 5, 0, 0>,

                                                ReduceDescription<4, 3, 7, 0, 0>, // for NORM2
33
                                                ReduceDescription<4, 4, 7, 0, 0>,
Qianfeng's avatar
Qianfeng committed
34
35
36
37
                                                ReduceDescription<4, 1, 7, 0, 0>,
                                                ReduceDescription<2, 1, 7, 0, 0>,

                                                ReduceDescription<4, 3, 2, 0, 0>, // for MIN
38
                                                ReduceDescription<4, 4, 2, 0, 0>,
Qianfeng's avatar
Qianfeng committed
39
40
41
                                                ReduceDescription<4, 1, 2, 0, 0>,
                                                ReduceDescription<2, 1, 2, 0, 0>,
                                                ReduceDescription<4, 3, 3, 0, 0>, // for MAX
42
                                                ReduceDescription<4, 4, 3, 0, 0>,
Qianfeng's avatar
Qianfeng committed
43
44
45
                                                ReduceDescription<4, 1, 3, 0, 0>,
                                                ReduceDescription<2, 1, 3, 0, 0>,
                                                ReduceDescription<4, 3, 4, 0, 0>, // for AMAX
46
                                                ReduceDescription<4, 4, 4, 0, 0>,
Qianfeng's avatar
Qianfeng committed
47
48
49
50
                                                ReduceDescription<4, 1, 4, 0, 0>,
                                                ReduceDescription<2, 1, 4, 0, 0>,

                                                ReduceDescription<4, 3, 2, 0, 1>, // for MIN
51
                                                ReduceDescription<4, 4, 2, 0, 1>,
Qianfeng's avatar
Qianfeng committed
52
53
54
                                                ReduceDescription<4, 1, 2, 0, 1>,
                                                ReduceDescription<2, 1, 2, 0, 1>,
                                                ReduceDescription<4, 3, 3, 0, 1>, // for MAX
55
                                                ReduceDescription<4, 4, 3, 0, 1>,
Qianfeng's avatar
Qianfeng committed
56
57
58
                                                ReduceDescription<4, 1, 3, 0, 1>,
                                                ReduceDescription<2, 1, 3, 0, 1>,
                                                ReduceDescription<4, 3, 4, 0, 1>, // for AMAX
59
                                                ReduceDescription<4, 4, 4, 0, 1>,
Qianfeng's avatar
Qianfeng committed
60
61
                                                ReduceDescription<4, 1, 4, 0, 1>,
                                                ReduceDescription<2, 1, 4, 0, 1>>;
62
63
64
65

template <typename DescriptionType>
bool description_match(const DescriptionType& description,
                       int Rank,
Qianfeng's avatar
Qianfeng committed
66
                       const std::vector<int>& reduceDims,
67
68
69
70
71
72
73
74
75
                       ReduceTensorOp_t ReduceOpId,
                       NanPropagation_t NanOpt,
                       ReduceTensorIndices_t IndicesOpt)
{
    if(description.Rank_ != Rank || description.ReduceOpId_ != static_cast<int>(ReduceOpId) ||
       description.NanOpt_ != static_cast<int>(NanOpt) ||
       description.IndicesOpt_ != static_cast<int>(IndicesOpt))
        return (false);

Qianfeng's avatar
Qianfeng committed
76
    if(DescriptionType::NumReduceDim_ != reduceDims.size())
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        return (false);

    bool result = true;

    return (result);
};

} // namespace device_reduce_instance
} // namespace device
} // namespace tensor_operation
} // namespace ck

namespace ck {
namespace profiler {

Qianfeng's avatar
Qianfeng committed
92
93
template <index_t Rank, index_t NumReduceDim>
static inline std::vector<int> get_invariant_dims(const std::vector<int>& reduceDims)
94
{
Qianfeng's avatar
Qianfeng committed
95
    assert(NumReduceDim == reduceDims.size());
96

Qianfeng's avatar
Qianfeng committed
97
    int reduceFlag = 0;
98

Qianfeng's avatar
Qianfeng committed
99
100
    // flag the bits for the reduceDims
    for(int i = 0; i < NumReduceDim; i++)
101
    {
Qianfeng's avatar
Qianfeng committed
102
        reduceFlag |= 1 << reduceDims[i];
103
104
    };

Qianfeng's avatar
Qianfeng committed
105
106
107
108
109
110
111
112
113
114
    std::vector<int> invariantDims;

    // collect invariant dimensions
    for(int i = 0; i < Rank; i++)
        if((reduceFlag & (1 << i)) == 0)
        {
            invariantDims.push_back(i);
        };

    return invariantDims;
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
};

template <typename T>
static void dumpBufferToFile(const char* fileName, T* data, size_t dataNumItems)
{
    std::ofstream outFile(fileName, std::ios::binary);
    if(outFile)
    {
        outFile.write(reinterpret_cast<char*>(data), dataNumItems * sizeof(T));
        outFile.close();
        std::cout << "Write output to file " << fileName << std::endl;
    }
    else
    {
        std::cout << "Could not open file " << fileName << " for writing" << std::endl;
    }
};

// map the data type used by the GPU kernels to the corresponding type used by the host codes
134
template <typename InType>
135
136
struct type_mapping
{
137
    using OutType = InType;
138
139
140
141
142
};

template <>
struct type_mapping<ck::half_t>
{
143
    using OutType = half_float::half;
144
145
146
147
148
149
};

template <typename InDataType,
          typename AccDataType,
          typename OutDataType,
          int Rank,
Qianfeng's avatar
Qianfeng committed
150
          int NumReduceDim,
151
152
153
154
155
156
157
158
159
          ReduceTensorOp_t ReduceOpId,
          NanPropagation_t NanOpt,
          ReduceTensorIndices_t IndicesOpt>
void profile_reduce_impl_impl(bool do_verification,
                              int init_method,
                              bool do_log,
                              bool do_dumpout,
                              int nrepeat,
                              const std::vector<size_t>& inLengths,
Qianfeng's avatar
Qianfeng committed
160
                              const std::vector<int>& reduceDims,
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
                              float alpha,
                              float beta)
{
    using namespace ck::tensor_operation::device;
    using namespace ck::tensor_operation::device::device_reduce_instance;
    using namespace ck::host_reduce;

    constexpr bool op_support_indices =
        (ReduceOpId == ReduceTensorOp_t::MIN || ReduceOpId == ReduceTensorOp_t::MAX ||
         ReduceOpId == ReduceTensorOp_t::AMAX);

    constexpr bool NeedIndices =
        (op_support_indices && (IndicesOpt != ReduceTensorIndices_t::NO_INDICES));

    constexpr bool PropagateNan = (NanOpt == NanPropagation_t::PROPAGATE_NAN);

    constexpr bool out_support_atomic_add = std::is_same<OutDataType, float>::value;
    constexpr bool op_support_atomic_add =
        !op_support_indices && ReduceOpId != ReduceTensorOp_t::NORM2;
    constexpr bool use_atomic_add = (out_support_atomic_add && op_support_atomic_add);

    // 1) If InDataType is half_t, must use half_t as AccDataType for indexable reduction operations
    // 2) If InDataType is half_t, must use float as AccDataType for non-indexable reduction
    // operations
    constexpr bool invalid_reduce_1 =
        std::is_same<InDataType, half_t>::value &&
        ((!op_support_indices && !std::is_same<AccDataType, float>::value) ||
         (op_support_indices && !std::is_same<AccDataType, half_t>::value));

    // 1) If InDataType is float, must use float as AccDataType for indexable reduction operations
    constexpr bool invalid_reduce_2 =
        std::is_same<InDataType, float>::value &&
        (op_support_indices && !std::is_same<AccDataType, float>::value);

    // 1) The indices can only be used when the reduction operation is indexable
    constexpr bool invalid_reduce_3 =
        (!op_support_indices && IndicesOpt != ReduceTensorIndices_t::NO_INDICES);

199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    // 1) If InDataType is int8_t, must use int8_t as AccDataType for indexable reduction operations
    // 2) If InDataType is int8_t, must use int32_t as AccDataType for non-indexable reduction
    // operations
    constexpr bool invalid_reduce_4 =
        std::is_same<InDataType, int8_t>::value &&
        ((!op_support_indices && !std::is_same<AccDataType, int32_t>::value) ||
         (op_support_indices && !std::is_same<AccDataType, int8_t>::value));

    // 1) If InDataType is int8_t, the supported operation must be either indexable operations or
    // ADD/AVG
    constexpr bool invalid_reduce_5 = std::is_same<InDataType, int8_t>::value &&
                                      (!op_support_indices && ReduceOpId != ReduceTensorOp_t::ADD &&
                                       ReduceOpId != ReduceTensorOp_t::AVG);

    // 1) If InDataType is bhalf_t, must use float as AccDataType for all reduction operations
    constexpr bool invalid_reduce_6 =
        std::is_same<InDataType, bhalf_t>::value && !std::is_same<AccDataType, float>::value;

    constexpr bool invalid_reduce = (invalid_reduce_1 || invalid_reduce_2 || invalid_reduce_3 ||
                                     invalid_reduce_4 || invalid_reduce_5 || invalid_reduce_6);
219
220
221
222
223
224
225

    if constexpr(!invalid_reduce)
    {
        Tensor<InDataType> in(inLengths);

        std::vector<size_t> outLengths;

Qianfeng's avatar
Qianfeng committed
226
227
228
        const auto invariantDims = get_invariant_dims<Rank, NumReduceDim>(reduceDims);

        if(reduceDims.size() == Rank)
229
230
            outLengths.push_back(1);
        else
Qianfeng's avatar
Qianfeng committed
231
            for(auto dim : invariantDims)
232
233
234
235
                outLengths.push_back(inLengths[dim]);

        Tensor<OutDataType> out_ref(outLengths);
        Tensor<OutDataType> out(outLengths);
236
237
        Tensor<int32_t> out_indices_ref(outLengths);
        Tensor<int32_t> out_indices(outLengths);
238
239
240
241
242
243
244
245
246
247
248
249
250

        auto inStrides  = in.mDesc.GetStrides();
        auto outStrides = out.mDesc.GetStrides();

        size_t invariant_total_length = out.mDesc.GetElementSize();
        size_t reduce_total_length    = in.mDesc.GetElementSize() / invariant_total_length;

        std::size_t num_thread = std::thread::hardware_concurrency();

        if(do_verification)
        {
            switch(init_method)
            {
251
252
253
            case 0: break;
            case 1:
                in.GenerateTensorValue(GeneratorTensor_1<InDataType>{1}, num_thread);
254
                if(beta != 0.0f)
255
                    out_ref.GenerateTensorValue(GeneratorTensor_1<InDataType>{1}, num_thread);
256
                break;
257
            case 2:
258
259
260
261
262
                in.GenerateTensorValue(GeneratorTensor_2<InDataType>{-5, 5}, num_thread);
                if(beta != 0.0f)
                    out_ref.GenerateTensorValue(GeneratorTensor_2<InDataType>{-5, 5}, num_thread);
                break;
            default:
263
                in.GenerateTensorValue(GeneratorTensor_3<InDataType>{-5.0, 5.0}, num_thread);
264
                if(beta != 0.0f)
265
266
                    out_ref.GenerateTensorValue(GeneratorTensor_3<InDataType>{-5.0, 5.0},
                                                num_thread);
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
            }

            if(beta != 0.0f)
                for(size_t i = 0; i < out_ref.mDesc.GetElementSpace(); i++)
                    out.mData[i] = out_ref.mData[i];
        };

        // these buffers are usually provided by the user application
        DeviceMem in_dev(sizeof(InDataType) * in.mDesc.GetElementSpace());
        DeviceMem out_dev(sizeof(OutDataType) * out.mDesc.GetElementSpace());

        in_dev.ToDevice(in.mData.data());

        if(beta != 0.0f)
            out_dev.ToDevice(out.mData.data());

        size_t indicesSizeInBytes = NeedIndices ? out.mDesc.GetElementSize() * sizeof(int) : 0;

        DeviceMem out_indices_dev(indicesSizeInBytes);

        float best_avg_time   = 0;
        float best_gb_per_sec = 0;

        using InElementwiseOperation_0 =
            typename reduce_unary_operator<AccDataType, ReduceOpId, true, true>::
                InElementwiseOperation;
        using AccElementwiseOperation_0 =
            typename reduce_unary_operator<AccDataType, ReduceOpId, true, true>::
                AccElementwiseOperation;
        using InElementwiseOperation_1 =
            typename reduce_unary_operator<AccDataType, ReduceOpId, true, false>::
                InElementwiseOperation;
        using AccElementwiseOperation_1 =
            typename reduce_unary_operator<AccDataType, ReduceOpId, true, false>::
                AccElementwiseOperation;
        using InElementwiseOperation_2 =
            typename reduce_unary_operator<AccDataType, ReduceOpId, false, true>::
                InElementwiseOperation;
        using AccElementwiseOperation_2 =
            typename reduce_unary_operator<AccDataType, ReduceOpId, false, true>::
                AccElementwiseOperation;

        using DeviceReduceInstPtr0 =
            DeviceReducePtr<InElementwiseOperation_0, AccElementwiseOperation_0>;
        using DeviceReduceInstPtr1 =
            DeviceReducePtr<InElementwiseOperation_1, AccElementwiseOperation_1>;
        using DeviceReduceInstPtr2 =
            DeviceReducePtr<InElementwiseOperation_2, AccElementwiseOperation_2>;

        std::vector<DeviceReduceInstPtr0> reduce0_ptrs;
        std::vector<DeviceReduceInstPtr1> reduce1_ptrs;
        std::vector<DeviceReduceInstPtr2> reduce2_ptrs;

        add_device_reduce_instance_threadwise<InDataType,
                                              AccDataType,
                                              OutDataType,
                                              Rank,
Qianfeng's avatar
Qianfeng committed
324
                                              NumReduceDim,
325
326
327
328
329
330
331
332
                                              ReduceOpId,
                                              NanOpt,
                                              IndicesOpt>(reduce0_ptrs);

        add_device_reduce_instance_blockwise<InDataType,
                                             AccDataType,
                                             OutDataType,
                                             Rank,
Qianfeng's avatar
Qianfeng committed
333
                                             NumReduceDim,
334
335
336
337
338
                                             ReduceOpId,
                                             NanOpt,
                                             IndicesOpt>(reduce0_ptrs);

        if constexpr(use_atomic_add)
339
        {
340
341
342
343
            add_device_reduce_instance_multiblock_atomic_add<InDataType,
                                                             AccDataType,
                                                             OutDataType,
                                                             Rank,
Qianfeng's avatar
Qianfeng committed
344
                                                             NumReduceDim,
345
346
347
                                                             ReduceOpId,
                                                             NanOpt,
                                                             IndicesOpt>(reduce0_ptrs);
348
        }
349
        else
350
        {
351
352
353
354
            add_device_reduce_instance_multiblock_partial_reduce<InDataType,
                                                                 AccDataType,
                                                                 OutDataType,
                                                                 Rank,
Qianfeng's avatar
Qianfeng committed
355
                                                                 NumReduceDim,
356
357
358
                                                                 ReduceOpId,
                                                                 NanOpt,
                                                                 IndicesOpt>(reduce1_ptrs);
359
        };
360
361
362

        // used for secondary reduction
        if constexpr(!use_atomic_add)
363
        {
364
365
366
367
            add_device_reduce_instance_blockwise_second_call<AccDataType,
                                                             AccDataType,
                                                             OutDataType,
                                                             Rank,
Qianfeng's avatar
Qianfeng committed
368
                                                             NumReduceDim,
369
370
371
                                                             ReduceOpId,
                                                             NanOpt,
                                                             IndicesOpt>(reduce2_ptrs);
372
        };
373
374
375
376
377
378
379
380

        if(reduce0_ptrs.empty() && reduce1_ptrs.empty())
        {
            throw std::runtime_error("Wrong! No device REDUCE instance found");
        };

        if(do_verification)
        {
381
382
383
384
385
386
387
388
389
390
391
392
            using HostInDataType  = typename type_mapping<InDataType>::OutType;
            using HostOutDataType = typename type_mapping<OutDataType>::OutType;
            using HostAccDataType = typename type_mapping<AccDataType>::OutType;

            ReductionHost<HostInDataType,
                          HostAccDataType,
                          HostOutDataType,
                          ReduceOpId,
                          Rank,
                          NumReduceDim,
                          PropagateNan,
                          NeedIndices>
Qianfeng's avatar
Qianfeng committed
393
                hostReduce(in.mDesc, out_ref.mDesc, invariantDims, reduceDims);
394
395

            hostReduce.Run(alpha,
396
                           reinterpret_cast<const HostInDataType*>(in.mData.data()),
397
                           beta,
398
                           reinterpret_cast<HostOutDataType*>(out_ref.mData.data()),
399
400
401
402
403
404
405
406
407
408
                           out_indices_ref.mData.data());
        };

        const auto i_inLengths  = to_int_vector(inLengths);
        const auto i_inStrides  = to_int_vector(inStrides);
        const auto i_outLengths = to_int_vector(outLengths);
        const auto i_outStrides = to_int_vector(outStrides);

        for(auto& reduce_ptr : reduce0_ptrs)
        {
409
            auto wsSizeInBytes = reduce_ptr->GetWorkspaceSizeInBytes(i_inLengths, reduceDims);
410
411
412

            DeviceMem ws_dev(wsSizeInBytes);

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
            InElementwiseOperation_0 in_elementwise_op_0(static_cast<int32_t>(reduce_total_length));
            AccElementwiseOperation_0 acc_elementwise_op_0(
                static_cast<int32_t>(reduce_total_length));

            auto argument_ptr = reduce_ptr->MakeArgumentPointer(i_inLengths,
                                                                i_inStrides,
                                                                i_outLengths,
                                                                i_outStrides,
                                                                reduceDims,
                                                                alpha,
                                                                beta,
                                                                in_dev.GetDeviceBuffer(),
                                                                out_dev.GetDeviceBuffer(),
                                                                out_indices_dev.GetDeviceBuffer(),
                                                                ws_dev.GetDeviceBuffer(),
                                                                in_elementwise_op_0,
                                                                acc_elementwise_op_0);
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

            if(!reduce_ptr->IsSupportedArgument(argument_ptr.get()))
                continue;

            std::string reduce_name = reduce_ptr->GetTypeString();

            auto invoker_ptr = reduce_ptr->MakeInvokerPointer();

            float avg_time = invoker_ptr->Run(argument_ptr.get(), nrepeat);

            std::size_t num_bytes =
                invariant_total_length * reduce_total_length * sizeof(InDataType) +
                invariant_total_length * sizeof(OutDataType);

            float gb_per_sec = num_bytes / 1.E6 / avg_time;

            std::cout << "Perf: " << avg_time << " ms, " << gb_per_sec << " GB/s, " << reduce_name
                      << std::endl;

            if(gb_per_sec > best_gb_per_sec)
            {
                best_avg_time   = avg_time;
                best_gb_per_sec = gb_per_sec;
            }

            if(do_verification)
            {
                out_dev.FromDevice(out.mData.data());
                check_error(out_ref, out);

                if(NeedIndices)
                {
                    out_indices_dev.FromDevice(out_indices.mData.data());
                    check_indices(out_indices_ref, out_indices);
                };

                if(do_log)
                {
                    LogRangeAsType<float>(std::cout << "out_host  : ", out_ref.mData, ",")
                        << std::endl;
                    LogRangeAsType<float>(std::cout << "out_device: ", out.mData, ",") << std::endl;
                };
            };

            if(do_dumpout)
            {
                dumpBufferToFile("dump_in.bin", in.mData.data(), in.mDesc.GetElementSize());
                dumpBufferToFile("dump_out.bin", out.mData.data(), out.mDesc.GetElementSize());
                dumpBufferToFile(
                    "dump_out_host.bin", out_ref.mData.data(), out_ref.mDesc.GetElementSize());
                if(NeedIndices)
                {
                    dumpBufferToFile("dump_indices.bin",
                                     out_indices.mData.data(),
                                     out_indices.mDesc.GetElementSize());
                    dumpBufferToFile("dump_indices_host.bin",
                                     out_indices_ref.mData.data(),
                                     out_indices_ref.mDesc.GetElementSize());
                };
            };
        };

        for(auto& reduce_ptr : reduce1_ptrs)
        {
494
            auto wsSizeInBytes = reduce_ptr->GetWorkspaceSizeInBytes(i_inLengths, reduceDims);
495
496
497

            DeviceMem ws_dev(wsSizeInBytes);

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
            InElementwiseOperation_1 in_elementwise_op_1(static_cast<int32_t>(reduce_total_length));
            AccElementwiseOperation_1 acc_elementwise_op_1(
                static_cast<int32_t>(reduce_total_length));

            auto argument_ptr = reduce_ptr->MakeArgumentPointer(i_inLengths,
                                                                i_inStrides,
                                                                i_outLengths,
                                                                i_outStrides,
                                                                reduceDims,
                                                                alpha,
                                                                beta,
                                                                in_dev.GetDeviceBuffer(),
                                                                out_dev.GetDeviceBuffer(),
                                                                out_indices_dev.GetDeviceBuffer(),
                                                                ws_dev.GetDeviceBuffer(),
                                                                in_elementwise_op_1,
                                                                acc_elementwise_op_1);
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533

            if(!reduce_ptr->IsSupportedArgument(argument_ptr.get()))
                continue;

            std::string reduce_name = reduce_ptr->GetTypeString();

            auto invoker_ptr = reduce_ptr->MakeInvokerPointer();

            float avg_time = invoker_ptr->Run(argument_ptr.get(), nrepeat);

            std::size_t num_bytes =
                invariant_total_length * reduce_total_length * sizeof(InDataType) +
                invariant_total_length * sizeof(OutDataType);

            std::vector<int> inLengths2 = reduce_ptr->GetWorkspace2dLengths(argument_ptr.get());
            std::vector<int> inStrides2{inLengths2[1], 1};

            for(auto& reduce2_ptr : reduce2_ptrs)
            {
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
                InElementwiseOperation_2 in_elementwise_op_2(
                    static_cast<int32_t>(reduce_total_length));
                AccElementwiseOperation_2 acc_elementwise_op_2(
                    static_cast<int32_t>(reduce_total_length));

                auto argument2_ptr =
                    reduce2_ptr->MakeArgumentPointer(inLengths2,
                                                     inStrides2,
                                                     i_outLengths,
                                                     i_outStrides,
                                                     reduceDims,
                                                     alpha,
                                                     beta,
                                                     ws_dev.GetDeviceBuffer(),
                                                     out_dev.GetDeviceBuffer(),
                                                     out_indices_dev.GetDeviceBuffer(),
                                                     ws_dev.GetDeviceBuffer(),
                                                     in_elementwise_op_2,
                                                     acc_elementwise_op_2);
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

                if(!reduce2_ptr->IsSupportedArgument(argument2_ptr.get()))
                    continue;

                std::string reduce2_name = reduce2_ptr->GetTypeString();

                auto invoker2_ptr = reduce2_ptr->MakeInvokerPointer();

                float avg_time_2 = invoker2_ptr->Run(argument2_ptr.get(), nrepeat);

                std::size_t num_bytes_2 =
                    static_cast<size_t>(inLengths2[0]) * inLengths2[1] * sizeof(AccDataType);

                float gb_per_sec = (num_bytes + num_bytes_2) / 1.E6 / (avg_time + avg_time_2);

                std::cout << "Perf: " << (avg_time + avg_time_2) << " ms, " << gb_per_sec
                          << " GB/s, " << reduce_name << " => " << reduce2_name << std::endl;

                if(gb_per_sec > best_gb_per_sec)
                {
                    best_avg_time   = avg_time + avg_time_2;
                    best_gb_per_sec = gb_per_sec;
                }

                if(do_verification)
                {
                    out_dev.FromDevice(out.mData.data());
                    check_error(out_ref, out);

                    if(NeedIndices)
                    {
                        out_indices_dev.FromDevice(out_indices.mData.data());
                        check_indices(out_indices_ref, out_indices);
                    };

                    if(do_log)
                    {
                        LogRangeAsType<float>(std::cout << "out_host  : ", out_ref.mData, ",")
                            << std::endl;
                        LogRangeAsType<float>(std::cout << "out_device: ", out.mData, ",")
                            << std::endl;
                    }
                }

                if(do_dumpout)
                {
                    dumpBufferToFile("dump_in.bin", in.mData.data(), in.mDesc.GetElementSize());
                    dumpBufferToFile("dump_out.bin", out.mData.data(), out.mDesc.GetElementSize());
                    dumpBufferToFile(
                        "dump_out_host.bin", out_ref.mData.data(), out_ref.mDesc.GetElementSize());
                    if(NeedIndices)
                    {
                        dumpBufferToFile("dump_indices.bin",
                                         out_indices.mData.data(),
                                         out_indices.mDesc.GetElementSize());
                        dumpBufferToFile("dump_indices_host.bin",
                                         out_indices_ref.mData.data(),
                                         out_indices_ref.mDesc.GetElementSize());
                    };
                };
            };
        };

        std::cout << "Best Perf: " << best_avg_time << " ms, " << best_gb_per_sec << " GB/s"
                  << std::endl;
    }
    else
    {
        std::cout << "The requested reduction operation is not supported, please check !!!"
                  << std::endl;
    };
};

template <typename InDataType, typename AccDataType, typename OutDataType>
void profile_reduce_impl(bool do_verification,
                         int init_method,
                         bool do_log,
                         bool do_dumpout,
                         int nrepeat,
                         const std::vector<size_t>& inLengths,
Qianfeng's avatar
Qianfeng committed
633
                         const std::vector<int>& reduceDims,
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
                         ReduceTensorOp_t ReduceOpId,
                         NanPropagation_t NanOpt,
                         ReduceTensorIndices_t IndicesOpt,
                         float alpha,
                         float beta)
{
    bool matched = false;

    using tuple_of_description_instances =
        tensor_operation::device::device_reduce_instance::reduce_description_instances;

    const auto tuple_object = tuple_of_description_instances{};

    static_for<0, std::tuple_size<tuple_of_description_instances>::value, 1>{}([&](auto i) {
        if(matched)
            return;

        using descType = remove_cvref_t<decltype(std::get<i>(tuple_object))>;

        if(!description_match(
Qianfeng's avatar
Qianfeng committed
654
               descType{}, inLengths.size(), reduceDims, ReduceOpId, NanOpt, IndicesOpt))
655
656
657
658
659
660
            return;

        profile_reduce_impl_impl<InDataType,
                                 AccDataType,
                                 OutDataType,
                                 descType::Rank_,
Qianfeng's avatar
Qianfeng committed
661
                                 descType::NumReduceDim_,
662
663
664
                                 static_cast<ReduceTensorOp_t>(descType::ReduceOpId_),
                                 static_cast<NanPropagation_t>(descType::NanOpt_),
                                 static_cast<ReduceTensorIndices_t>(descType::IndicesOpt_)>(
Qianfeng's avatar
Qianfeng committed
665
666
667
668
669
670
671
672
673
            do_verification,
            init_method,
            do_log,
            do_dumpout,
            nrepeat,
            inLengths,
            reduceDims,
            alpha,
            beta);
674
675
676
677
678
679
680

        matched = true;
    });
};

} // namespace profiler
} // namespace ck