reduce_blockwise_impl.hpp 13.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2022, Advanced Micro Devices, Inc. All rights reserved.

#pragma once

#include <iostream>

#include "ck/ck.hpp"
#include "ck/utility/reduction_enums.hpp"
#include "ck/tensor_operation/gpu/device/device_reduce_multiblock.hpp"
11
#include "ck/tensor_operation/gpu/device/reduction_operator_mapping.hpp"
12

13
#include "ck/library/utility/algorithm.hpp"
14
15
16
17
18
19
#include "ck/library/utility/check_err.hpp"
#include "ck/library/utility/device_memory.hpp"
#include "ck/library/utility/host_tensor.hpp"
#include "ck/library/utility/host_tensor_generator.hpp"
#include "ck/library/utility/host_common_util.hpp"
#include "ck/library/utility/host_reduction.hpp"
20
#include "ck/library/utility/ranges.hpp"
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

#include "reduce_example_common.hpp"

template <typename InOutDataType,
          typename AccDataType,
          ck::ReduceTensorOp ReduceOpId,
          ck::index_t Rank,
          ck::index_t NumReduceDim,
          bool PropagateNan,
          bool OutputIndex>
int reduce_blockwise_impl(bool do_verification,
                          int init_method,
                          bool time_kernel,
                          const std::vector<size_t>& inLengths,
                          const std::vector<int>& reduceDims,
                          float alpha,
                          float beta)

{
    using namespace ck;
    using namespace ck::tensor_operation::device;

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

    constexpr bool invalid_reduce_1 = OutputIndex && !op_support_indices;

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

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

Qianfeng's avatar
Qianfeng committed
63
64
65
    // 1) If InOutDataType is int8_t or int4_t, must use int8_t as AccDataType for indexable
    // reduction operations 2) If InOutDataType is int8_t or int4_t, must use int32_t as AccDataType
    // for non-indexable reduction operations
66
67
68
69
70
    constexpr bool invalid_reduce_4 =
        std::is_same<InOutDataType, int8_t>::value &&
        ((!op_support_indices && !std::is_same<AccDataType, int32_t>::value) ||
         (op_support_indices && !std::is_same<AccDataType, int8_t>::value));

Qianfeng's avatar
Qianfeng committed
71
72
73
74
75
76
77
78
79
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
    constexpr bool invalid_reduce_4_2 =
        std::is_same<InOutDataType, int4_t>::value &&
        ((!op_support_indices && !std::is_same<AccDataType, int32_t>::value) ||
         (op_support_indices && !std::is_same<AccDataType, int8_t>::value));
#endif

    // 1) If InOutDataType is int8_t or int4_t, the supported operation must be either indexable
    // operations or ADD/AVG
80
81
82
83
    constexpr bool invalid_reduce_5 = std::is_same<InOutDataType, int8_t>::value &&
                                      (!op_support_indices && ReduceOpId != ReduceTensorOp::ADD &&
                                       ReduceOpId != ReduceTensorOp::AVG);

Qianfeng's avatar
Qianfeng committed
84
85
86
87
88
89
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
    constexpr bool invalid_reduce_5_2 = std::is_same<InOutDataType, int4_t>::value &&
                                        (!op_support_indices && ReduceOpId != ReduceTensorOp::ADD &&
                                         ReduceOpId != ReduceTensorOp::AVG);
#endif

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

Qianfeng's avatar
Qianfeng committed
94
95
96
97
98
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
    constexpr bool invalid_reduce =
        (invalid_reduce_1 || invalid_reduce_2 || invalid_reduce_3 || invalid_reduce_4 ||
         invalid_reduce_5 || invalid_reduce_6 || invalid_reduce_4_2 || invalid_reduce_5_2);
#else
99
100
    constexpr bool invalid_reduce = (invalid_reduce_1 || invalid_reduce_2 || invalid_reduce_3 ||
                                     invalid_reduce_4 || invalid_reduce_5 || invalid_reduce_6);
Qianfeng's avatar
Qianfeng committed
101
#endif
102

Qianfeng's avatar
Qianfeng committed
103
    if constexpr(invalid_reduce)
104
105
106
107
108
109
110
111
112
113
114
    {
        std::cerr << "The reduction setting is invalid, exiting!" << std::endl;
        return (-1);
    };

    using ReduceOperation = typename reduce_binary_operator<ReduceOpId>::opType;
    using InElementwiseOperation =
        typename reduce_unary_operator<ReduceOpId, true, true>::InElementwiseOperation;
    using AccElementwiseOperation =
        typename reduce_unary_operator<ReduceOpId, true, true>::AccElementwiseOperation;

Qianfeng's avatar
Qianfeng committed
115
116
117
118
119
120
121
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
    using InOutDataTypeInDevice = typename std::
        conditional<std::is_same<InOutDataType, int4_t>::value, int8_t, InOutDataType>::type;
#else
    using InOutDataTypeInDevice   = InOutDataType;
#endif

122
    using DeviceReduceInstance =
Qianfeng's avatar
Qianfeng committed
123
        ck::tensor_operation::device::DeviceReduceMultiBlock<InOutDataTypeInDevice,
124
                                                             AccDataType,
Qianfeng's avatar
Qianfeng committed
125
                                                             InOutDataTypeInDevice,
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
                                                             Rank,
                                                             NumReduceDim,
                                                             ReduceOperation,
                                                             InElementwiseOperation,
                                                             AccElementwiseOperation,
                                                             InMemoryDataOperationEnum::Set,
                                                             PropagateNan,
                                                             OutputIndex,
                                                             false, // HaveIndexInputIfOutputIndex
                                                             256,   // BlockSize
                                                             4,     // MThreadClusterSize
                                                             64,    // KThreadClusterSize
                                                             1,     // MThreadSliceSize
                                                             1,     // KThreadSliceSize
                                                             0,     // InSrcVectorDim
                                                             1,     // InSrceVectorSize
                                                             1>;    // OutDstVectorSize

    Tensor<InOutDataType> in(inLengths);

    std::vector<size_t> outLengths;

    std::vector<int> invariantDims = get_invariant_dims<Rank, NumReduceDim>(reduceDims);

    if(invariantDims.empty())
        outLengths.push_back(1);
    else
        for(auto dim : invariantDims)
            outLengths.push_back(inLengths[dim]);

    Tensor<InOutDataType> out_ref(outLengths);
    Tensor<InOutDataType> out(outLengths);
    Tensor<int> out_indices_ref(outLengths);
    Tensor<int> out_indices(outLengths);

161
162
    auto inStrides  = in.GetStrides();
    auto outStrides = out.GetStrides();
163

164
165
    size_t invariant_total_length = out.GetElementSize();
    size_t reduce_total_length    = in.GetElementSize() / invariant_total_length;
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

    std::size_t num_thread = 1;

    if(do_verification)
    {
        switch(init_method)
        {
        case 0: break;
        case 1:
            in.GenerateTensorValue(GeneratorTensor_1<InOutDataType>{1}, num_thread);
            if(beta != 0.0f)
                out_ref.GenerateTensorValue(GeneratorTensor_1<InOutDataType>{1}, num_thread);
            break;
        case 2:
            in.GenerateTensorValue(GeneratorTensor_2<InOutDataType>{-5, 5}, num_thread);
            if(beta != 0.0f)
                out_ref.GenerateTensorValue(GeneratorTensor_2<InOutDataType>{-5, 5}, num_thread);
            break;
        default:
            in.GenerateTensorValue(GeneratorTensor_3<InOutDataType>{-5.0, 5.0}, num_thread);
            if(beta != 0.0f)
                out_ref.GenerateTensorValue(GeneratorTensor_3<InOutDataType>{-5.0, 5.0},
                                            num_thread);
        }

        if(beta != 0.0f)
192
193
194
        {
            ck::ranges::copy(out_ref, out.begin());
        }
195
196
197
    };

    // these buffers are usually provided by the user application
198
199
    DeviceMem in_dev(in.GetMemorySize());
    DeviceMem out_dev(out.GetMemorySize());
200

Qianfeng's avatar
Qianfeng committed
201
202
203
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
    if(std::is_same<InOutDataType, int4_t>::value)
    {
204
        std::vector<InOutDataTypeInDevice> tmp_buf(in.size());
Qianfeng's avatar
Qianfeng committed
205

206
        std::copy_n(in.data(), in.size(), tmp_buf.data());
Qianfeng's avatar
Qianfeng committed
207
208
209
210
        in_dev.ToDevice(tmp_buf.data());
    }
    else
#endif
211
        in_dev.ToDevice(in.data());
212
213

    if(beta != 0.0f)
Qianfeng's avatar
Qianfeng committed
214
215
216
217
    {
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
        if(std::is_same<InOutDataType, int4_t>::value)
        {
218
            std::vector<InOutDataTypeInDevice> tmp_buf(in.size());
Qianfeng's avatar
Qianfeng committed
219

220
            std::copy_n(out.data(), out.size(), tmp_buf.data());
Qianfeng's avatar
Qianfeng committed
221
222
223
224
            out_dev.ToDevice(tmp_buf.data());
        }
        else
#endif
225
            out_dev.ToDevice(out.data());
Qianfeng's avatar
Qianfeng committed
226
    };
227

228
    size_t indicesSizeInBytes = OutputIndex ? out.GetElementSize() * sizeof(int32_t) : 0;
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

    DeviceMem out_index_dev(indicesSizeInBytes);

    InElementwiseOperation in_elementwise_op;
    AccElementwiseOperation acc_elementwise_op;

    std::tie(in_elementwise_op, acc_elementwise_op) =
        reduce_unary_operator<ReduceOpId, true, true>::GetElementwiseOperator(
            static_cast<int32_t>(reduce_total_length));

    if(do_verification)
    {
        ReductionHost<InOutDataType,
                      AccDataType,
                      InOutDataType,
                      ReduceOperation,
                      InElementwiseOperation,
                      AccElementwiseOperation,
                      Rank,
                      NumReduceDim,
                      PropagateNan,
                      OutputIndex>
251
            hostReduce(in.GetDesc(), out_ref.GetDesc(), invariantDims, reduceDims);
252
253

        hostReduce.Run(alpha,
254
                       in.data(),
255
                       beta,
256
257
                       out_ref.data(),
                       out_indices_ref.data(),
258
259
260
261
                       in_elementwise_op,
                       acc_elementwise_op);
    };

262
    using Indices = std::vector<ck::index_t>;
263
264
265

    auto reduce = DeviceReduceInstance{};

266
267
268
269
    auto argument_ptr = reduce.MakeArgumentPointer(ck::ranges::to<Indices>(inLengths),
                                                   ck::ranges::to<Indices>(inStrides),
                                                   ck::ranges::to<Indices>(outLengths),
                                                   ck::ranges::to<Indices>(outStrides),
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
                                                   reduceDims,
                                                   alpha,
                                                   beta,
                                                   in_dev.GetDeviceBuffer(),
                                                   nullptr,
                                                   out_dev.GetDeviceBuffer(),
                                                   out_index_dev.GetDeviceBuffer(),
                                                   in_elementwise_op,
                                                   acc_elementwise_op);

    if(!reduce.IsSupportedArgument(argument_ptr.get()))
    {
        std::cerr
            << "The runtime parameters seems not supported by the DeviceReduce instance, exiting!"
            << std::endl;

        return (-2);
    };

    std::string reduce_name = reduce.GetTypeString();

    auto invoker_ptr = reduce.MakeInvokerPointer();

    float avg_time = invoker_ptr->Run(argument_ptr.get(), StreamConfig{nullptr, time_kernel});

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

    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;

    bool pass = true;

    if(do_verification)
    {
Qianfeng's avatar
Qianfeng committed
307
308
309
#ifdef CK_EXPERIMENTAL_BIT_INT_EXTENSION_INT4
        if(std::is_same<InOutDataType, int4_t>::value)
        {
310
            std::vector<InOutDataTypeInDevice> tmp_buf(out.size());
Qianfeng's avatar
Qianfeng committed
311
312
313

            out_dev.FromDevice(tmp_buf.data());

314
            std::copy_n(tmp_buf.data(), out.size(), out.data());
Qianfeng's avatar
Qianfeng committed
315
316
317
        }
        else
#endif
318
            out_dev.FromDevice(out.data());
Qianfeng's avatar
Qianfeng committed
319

320
        pass = pass && ck::utils::check_err(out, out_ref);
321
322
323

        if(OutputIndex)
        {
324
325
            out_index_dev.FromDevice(out_indices.data());
            pass = pass && ck::utils::check_err(out_indices, out_indices_ref);
326
327
328
329
330
        };
    };

    return (pass ? 0 : 1);
}