profile_reduce_impl.hpp 20 KB
Newer Older
1
#pragma once
2
3

#include "check_err.hpp"
4
5
6
#include "device_reduce.hpp"
#include "device_reduce_instance.hpp"
#include "reduction_enums.hpp"
7
#include "host_reduction.hpp"
8
9
#include "host_common_util.hpp"
#include "host_tensor_generator.hpp"
10
11
12
13
14
15

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

16
template <int Rank, int NumReduceDim, int ReduceOpId, bool PropagateNan, bool UseIndex>
17
18
struct ReduceDescription
{
Qianfeng's avatar
Qianfeng committed
19
20
21
    static constexpr int Rank_         = Rank;
    static constexpr int NumReduceDim_ = NumReduceDim;
    static constexpr int ReduceOpId_   = ReduceOpId;
22
23
    static constexpr int PropagateNan_ = PropagateNan;
    static constexpr int UseIndex_     = UseIndex;
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
using reduce_description_instances =
    std::tuple<ReduceDescription<4, 3, 0, false, false>, // for ADD
               ReduceDescription<4, 4, 0, false, false>,
               ReduceDescription<4, 1, 0, false, false>,
               ReduceDescription<2, 1, 0, false, false>,

               ReduceDescription<4, 3, 5, false, false>, // for AVG
               ReduceDescription<4, 4, 5, false, false>,
               ReduceDescription<4, 1, 5, false, false>,
               ReduceDescription<2, 1, 5, false, false>,

               ReduceDescription<4, 3, 7, false, false>, // for NORM2
               ReduceDescription<4, 4, 7, false, false>,
               ReduceDescription<4, 1, 7, false, false>,
               ReduceDescription<2, 1, 7, false, false>,

               ReduceDescription<4, 3, 2, false, false>, // for MIN
               ReduceDescription<4, 4, 2, false, false>,
               ReduceDescription<4, 1, 2, false, false>,
               ReduceDescription<2, 1, 2, false, false>,
               ReduceDescription<4, 3, 3, false, false>, // for MAX
               ReduceDescription<4, 4, 3, false, false>,
               ReduceDescription<4, 1, 3, false, false>,
               ReduceDescription<2, 1, 3, false, false>,
               ReduceDescription<4, 3, 4, false, false>, // for AMAX
               ReduceDescription<4, 4, 4, false, false>,
               ReduceDescription<4, 1, 4, false, false>,
               ReduceDescription<2, 1, 4, false, false>,

               ReduceDescription<4, 3, 2, false, true>, // for MIN
               ReduceDescription<4, 4, 2, false, true>,
               ReduceDescription<4, 1, 2, false, true>,
               ReduceDescription<2, 1, 2, false, true>,
               ReduceDescription<4, 3, 3, false, true>, // for MAX
               ReduceDescription<4, 4, 3, false, true>,
               ReduceDescription<4, 1, 3, false, true>,
               ReduceDescription<2, 1, 3, false, true>,
               ReduceDescription<4, 3, 4, false, true>, // for AMAX
               ReduceDescription<4, 4, 4, false, true>,
               ReduceDescription<4, 1, 4, false, true>,
               ReduceDescription<2, 1, 4, false, true>>;
67
68
69
70

template <typename DescriptionType>
bool description_match(const DescriptionType& description,
                       int Rank,
Qianfeng's avatar
Qianfeng committed
71
                       const std::vector<int>& reduceDims,
72
                       ReduceTensorOp ReduceOpId,
73
74
                       bool PropagateNan,
                       bool UseIndex)
75
76
{
    if(description.Rank_ != Rank || description.ReduceOpId_ != static_cast<int>(ReduceOpId) ||
77
78
       description.PropagateNan_ != static_cast<int>(PropagateNan) ||
       description.UseIndex_ != static_cast<int>(UseIndex))
79
80
        return (false);

Qianfeng's avatar
Qianfeng committed
81
    if(DescriptionType::NumReduceDim_ != reduceDims.size())
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        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
97
98
template <index_t Rank, index_t NumReduceDim>
static inline std::vector<int> get_invariant_dims(const std::vector<int>& reduceDims)
99
{
Qianfeng's avatar
Qianfeng committed
100
    assert(NumReduceDim == reduceDims.size());
101

Qianfeng's avatar
Qianfeng committed
102
    int reduceFlag = 0;
103

Qianfeng's avatar
Qianfeng committed
104
105
    // flag the bits for the reduceDims
    for(int i = 0; i < NumReduceDim; i++)
106
    {
Qianfeng's avatar
Qianfeng committed
107
        reduceFlag |= 1 << reduceDims[i];
108
109
    };

Qianfeng's avatar
Qianfeng committed
110
111
112
113
114
115
116
117
118
119
    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;
120
121
122
123
124
125
};

template <typename InDataType,
          typename AccDataType,
          typename OutDataType,
          int Rank,
Qianfeng's avatar
Qianfeng committed
126
          int NumReduceDim,
127
          ReduceTensorOp ReduceOpId,
128
129
130
          bool PropagateNan,
          bool UseIndex>
bool profile_reduce_impl_impl(bool do_verification,
131
132
                              int init_method,
                              bool do_dumpout,
JD's avatar
JD committed
133
                              bool time_kernel,
134
                              const std::vector<size_t>& inLengths,
Qianfeng's avatar
Qianfeng committed
135
                              const std::vector<int>& reduceDims,
136
137
138
139
140
                              float alpha,
                              float beta)
{
    using namespace ck::tensor_operation::device;
    using namespace ck::tensor_operation::device::device_reduce_instance;
141
    using ck::host_common::dumpBufferToFile;
142
143

    constexpr bool op_support_indices =
144
145
        (ReduceOpId == ReduceTensorOp::MIN || ReduceOpId == ReduceTensorOp::MAX ||
         ReduceOpId == ReduceTensorOp::AMAX);
146

147
    constexpr bool OutputIndex = (op_support_indices && UseIndex);
148
149
150

    constexpr bool out_support_atomic_add = std::is_same<OutDataType, float>::value;
    constexpr bool op_support_atomic_add =
151
        !op_support_indices && ReduceOpId != ReduceTensorOp::NORM2;
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    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
168
    constexpr bool invalid_reduce_3 = (!op_support_indices && UseIndex);
169

170
171
172
173
174
175
176
177
178
179
180
    // 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 &&
181
182
                                      (!op_support_indices && ReduceOpId != ReduceTensorOp::ADD &&
                                       ReduceOpId != ReduceTensorOp::AVG);
183
184
185
186
187
188
189

    // 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);
190

191
192
    bool pass = true;

193
194
195
196
197
198
    if constexpr(!invalid_reduce)
    {
        Tensor<InDataType> in(inLengths);

        std::vector<size_t> outLengths;

Qianfeng's avatar
Qianfeng committed
199
200
201
        const auto invariantDims = get_invariant_dims<Rank, NumReduceDim>(reduceDims);

        if(reduceDims.size() == Rank)
202
203
            outLengths.push_back(1);
        else
Qianfeng's avatar
Qianfeng committed
204
            for(auto dim : invariantDims)
205
206
207
208
                outLengths.push_back(inLengths[dim]);

        Tensor<OutDataType> out_ref(outLengths);
        Tensor<OutDataType> out(outLengths);
209
210
        Tensor<int32_t> out_indices_ref(outLengths);
        Tensor<int32_t> out_indices(outLengths);
211
212
213
214
215
216
217

        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;

218
        std::size_t num_thread = 1;
219
220
221
222
223

        if(do_verification)
        {
            switch(init_method)
            {
224
225
226
            case 0: break;
            case 1:
                in.GenerateTensorValue(GeneratorTensor_1<InDataType>{1}, num_thread);
227
                if(beta != 0.0f)
228
                    out_ref.GenerateTensorValue(GeneratorTensor_1<InDataType>{1}, num_thread);
229
                break;
230
            case 2:
231
232
233
234
235
                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:
236
                in.GenerateTensorValue(GeneratorTensor_3<InDataType>{-5.0, 5.0}, num_thread);
237
                if(beta != 0.0f)
238
239
                    out_ref.GenerateTensorValue(GeneratorTensor_3<InDataType>{-5.0, 5.0},
                                                num_thread);
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
            }

            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());

256
        size_t indicesSizeInBytes = OutputIndex ? out.mDesc.GetElementSize() * sizeof(int) : 0;
257
258
259
260
261
262

        DeviceMem out_indices_dev(indicesSizeInBytes);

        float best_avg_time   = 0;
        float best_gb_per_sec = 0;

263
        using InElementwiseOperation =
264
265
            typename reduce_unary_operator<AccDataType, ReduceOpId, true, true>::
                InElementwiseOperation;
266
        using AccElementwiseOperation =
267
268
269
            typename reduce_unary_operator<AccDataType, ReduceOpId, true, true>::
                AccElementwiseOperation;

270
271
        using ReduceOperation = typename reduce_binary_operator<AccDataType, ReduceOpId>::opType;

272
        using DeviceReduceInstPtr0 =
273
            DeviceReducePtr<InElementwiseOperation, AccElementwiseOperation>;
274
275
276
277
278
279
280

        std::vector<DeviceReduceInstPtr0> reduce0_ptrs;

        add_device_reduce_instance_threadwise<InDataType,
                                              AccDataType,
                                              OutDataType,
                                              Rank,
Qianfeng's avatar
Qianfeng committed
281
                                              NumReduceDim,
282
                                              ReduceOpId,
283
284
                                              PropagateNan,
                                              UseIndex>(reduce0_ptrs);
285
286
287
288
289

        add_device_reduce_instance_blockwise<InDataType,
                                             AccDataType,
                                             OutDataType,
                                             Rank,
Qianfeng's avatar
Qianfeng committed
290
                                             NumReduceDim,
291
                                             ReduceOpId,
292
293
                                             PropagateNan,
                                             UseIndex>(reduce0_ptrs);
294
295

        if constexpr(use_atomic_add)
296
        {
297
298
299
300
            add_device_reduce_instance_multiblock_atomic_add<InDataType,
                                                             AccDataType,
                                                             OutDataType,
                                                             Rank,
Qianfeng's avatar
Qianfeng committed
301
                                                             NumReduceDim,
302
                                                             ReduceOpId,
303
304
                                                             PropagateNan,
                                                             UseIndex>(reduce0_ptrs);
305
        }
306

307
        if(reduce0_ptrs.empty())
308
309
310
311
312
313
        {
            throw std::runtime_error("Wrong! No device REDUCE instance found");
        };

        if(do_verification)
        {
314
315
316
            ReductionHost<InDataType,
                          AccDataType,
                          OutDataType,
317
318
319
                          ReduceOperation,
                          InElementwiseOperation,
                          AccElementwiseOperation,
320
321
322
                          Rank,
                          NumReduceDim,
                          PropagateNan,
323
                          OutputIndex>
Qianfeng's avatar
Qianfeng committed
324
                hostReduce(in.mDesc, out_ref.mDesc, invariantDims, reduceDims);
325

326
327
            hostReduce.Run(
                alpha, in.mData.data(), beta, out_ref.mData.data(), out_indices_ref.mData.data());
328
329
        };

330
331
332
333
334
335
336
337
338
        std::vector<ck::index_t> i_inLengths;
        std::vector<ck::index_t> i_inStrides;
        std::vector<ck::index_t> i_outLengths;
        std::vector<ck::index_t> i_outStrides;

        i_inLengths.assign(inLengths.begin(), inLengths.end());
        i_inStrides.assign(inStrides.begin(), inStrides.end());
        i_outLengths.assign(outLengths.begin(), outLengths.end());
        i_outStrides.assign(outStrides.begin(), outStrides.end());
339
340
341
342

        for(auto& reduce_ptr : reduce0_ptrs)
        {

343
344
            InElementwiseOperation in_elementwise_op(static_cast<int32_t>(reduce_total_length));
            AccElementwiseOperation acc_elementwise_op(static_cast<int32_t>(reduce_total_length));
345
346
347
348
349
350
351
352
353

            auto argument_ptr = reduce_ptr->MakeArgumentPointer(i_inLengths,
                                                                i_inStrides,
                                                                i_outLengths,
                                                                i_outStrides,
                                                                reduceDims,
                                                                alpha,
                                                                beta,
                                                                in_dev.GetDeviceBuffer(),
354
                                                                nullptr,
355
356
                                                                out_dev.GetDeviceBuffer(),
                                                                out_indices_dev.GetDeviceBuffer(),
357
358
                                                                in_elementwise_op,
                                                                acc_elementwise_op);
359
360
361
362
363
364
365
366

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

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

            auto invoker_ptr = reduce_ptr->MakeInvokerPointer();

JD's avatar
JD committed
367
368
            float avg_time =
                invoker_ptr->Run(argument_ptr.get(), StreamConfig{nullptr, time_kernel});
369
370
371
372
373
374
375

            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;

376
377
378
            if(time_kernel)
                std::cout << "Perf: " << avg_time << " ms, " << gb_per_sec << " GB/s, "
                          << reduce_name << std::endl;
379
380
381
382
383
384
385
386
387

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

            if(do_verification)
            {
388
389
                bool single_pass;

390
                out_dev.FromDevice(out.mData.data());
391
                single_pass = ck::utils::check_err(out.mData, out_ref.mData);
392

393
                if(OutputIndex)
394
395
                {
                    out_indices_dev.FromDevice(out_indices.mData.data());
396
397
                    single_pass = single_pass &&
                                  ck::utils::check_err(out_indices.mData, out_indices_ref.mData);
398
399
                };

400
                if(!single_pass)
401
                {
402
403
404
405
                    std::cout << "Fail Info: " << reduce_ptr->GetTypeString() << std::endl;
                }

                pass = pass && single_pass;
406
407
408
409
410
411
412
413
            };

            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());
414
                if(OutputIndex)
415
416
417
418
419
420
421
422
423
424
425
                {
                    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());
                };
            };
        };

426
427
428
        if(time_kernel)
            std::cout << "Best Perf: " << best_avg_time << " ms, " << best_gb_per_sec << " GB/s"
                      << std::endl;
429
430
431
432
433
434
    }
    else
    {
        std::cout << "The requested reduction operation is not supported, please check !!!"
                  << std::endl;
    };
435
436

    return pass;
437
438
439
};

template <typename InDataType, typename AccDataType, typename OutDataType>
440
bool profile_reduce_impl(bool do_verification,
441
442
                         int init_method,
                         bool do_dumpout,
JD's avatar
JD committed
443
                         bool time_kernel,
444
                         const std::vector<size_t>& inLengths,
Qianfeng's avatar
Qianfeng committed
445
                         const std::vector<int>& reduceDims,
446
                         ReduceTensorOp ReduceOpId,
447
448
                         bool PropagateNan,
                         bool UseIndex,
449
450
451
452
                         float alpha,
                         float beta)
{
    bool matched = false;
453
    bool pass    = true;
454
455
456
457
458
459
460
461
462
463
464
465
466

    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(
467
               descType{}, inLengths.size(), reduceDims, ReduceOpId, PropagateNan, UseIndex))
468
469
            return;

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
        pass = pass &&
               profile_reduce_impl_impl<InDataType,
                                        AccDataType,
                                        OutDataType,
                                        descType::Rank_,
                                        descType::NumReduceDim_,
                                        static_cast<ReduceTensorOp>(descType::ReduceOpId_),
                                        static_cast<bool>(descType::PropagateNan_),
                                        static_cast<bool>(descType::UseIndex_)>(do_verification,
                                                                                init_method,
                                                                                do_dumpout,
                                                                                time_kernel,
                                                                                inLengths,
                                                                                reduceDims,
                                                                                alpha,
                                                                                beta);
486
487
488

        matched = true;
    });
489
490

    return pass;
491
492
493
494
};

} // namespace profiler
} // namespace ck