"git@developer.sourcefind.cn:modelzoo/resnet50_tensorflow.git" did not exist on "0d9f9b22bfc51d664e47378c681b8e7167651687"
softmax_blockwise.cpp 9.17 KB
Newer Older
Chao Liu's avatar
Chao Liu committed
1
2
3
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2022, Advanced Micro Devices, Inc. All rights reserved.

4
5
#include <cstdlib>
#include <initializer_list>
6
7
#include <iostream>
#include <numeric>
8

9
10
#include <getopt.h>

Chao Liu's avatar
Chao Liu committed
11
12
#include "ck/ck.hpp"
#include "ck/utility/reduction_enums.hpp"
Adam Osewski's avatar
Adam Osewski committed
13
#include "ck/tensor_operation/gpu/device/impl/device_softmax_impl.hpp"
Chao Liu's avatar
Chao Liu committed
14
#include "ck/tensor_operation/gpu/device/reduction_operator_mapping.hpp"
Adam Osewski's avatar
Adam Osewski committed
15
#include "ck/tensor_operation/gpu/element/element_wise_operation.hpp"
16

17
18
#include "ck/library/reference_tensor_operation/cpu/reference_softmax.hpp"
#include "ck/library/utility/algorithm.hpp"
Chao Liu's avatar
Chao Liu committed
19
#include "ck/library/utility/check_err.hpp"
20
21
#include "ck/library/utility/device_memory.hpp"
#include "ck/library/utility/host_common_util.hpp"
22
#include "ck/library/utility/ranges.hpp"
23
24
25
26
27
28
29

using namespace ck::tensor_operation::device;

using InDataType  = ck::half_t;
using OutDataType = ck::half_t;
using AccDataType = float;

Adam Osewski's avatar
Adam Osewski committed
30
31
using PassThrough = ck::tensor_operation::element_wise::PassThrough;

32
33
34
constexpr int Rank         = 3;
constexpr int NumReduceDim = 1;

Adam Osewski's avatar
Adam Osewski committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using DeviceInstance = DeviceSoftmaxImpl<InDataType,
                                         AccDataType,
                                         OutDataType,
                                         PassThrough, // InElementwiseOperation
                                         PassThrough, // AccElementwiseOperation
                                         Rank,
                                         NumReduceDim,
                                         256, // BlockSize
                                         8,   // ClusterM
                                         32,  // ClusterK
                                         1,   // SliceM
                                         8,   // SliceK
                                         1,   // SrcVecDim (0=M, 1=K)
                                         8,   // SrcScalarPerVector
                                         8>;  // OutScalarPerVector
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

static struct option long_options[] = {{"inLengths", required_argument, nullptr, 'D'},
                                       {"verify", required_argument, nullptr, 'v'},
                                       {"help", no_argument, nullptr, '?'},
                                       {nullptr, 0, nullptr, 0}};

class SimpleAppArgs
{
    private:
    int option_index = 0;

    public:
    std::vector<size_t> inLengths   = {8, 128, 2048};
    std::vector<AccDataType> scales = {2.0f, 2.0f};

    bool do_verification = true;
    int init_method      = 2;
    bool time_kernel     = true;

    public:
    void show_usage(const char* cmd)
    {
        std::cout << "Usage of " << cmd << std::endl;
        std::cout << "--inLengths or -D, comma separated list of input tensor dimension lengths"
                  << std::endl;
        std::cout << "--verify or -v, 1/0 to indicate whether to verify the reduction result by "
                     "comparing with the host-based reduction"
                  << std::endl;
        std::cout << "Arg1 -- init method (0=no init, 1=single integer value, 2=scope integer "
                     "value, 3=decimal value)"
                  << std::endl;
        std::cout << "Arg2 -- time kernel (0=no, 1=yes)" << std::endl;
    };

    int processArgs(int argc, char* argv[])
    {
        using ck::host_common::getTypeValuesFromString;

        int ch;

        while(1)
        {
            ch = getopt_long(argc, argv, "D:v:l:", long_options, &option_index);
            if(ch == -1)
                break;
            switch(ch)
            {
            case 'D':
                if(!optarg)
                    throw std::runtime_error("Invalid option format!");

                inLengths = getTypeValuesFromString<size_t>(optarg);
                break;
            case 'v':
                if(!optarg)
                    throw std::runtime_error("Invalid option format!");

                do_verification = static_cast<bool>(std::atoi(optarg));
                break;
            case '?':
                if(std::string(long_options[option_index].name) == "help")
                {
                    show_usage(argv[0]);
                    return (-1);
                };
                break;
            default: show_usage(argv[0]); return (-1);
            };
        };

        if(optind + 2 > argc)
            throw std::runtime_error("Invalid cmd-line arguments, more argumetns are needed!");

        init_method = std::atoi(argv[optind++]);
        time_kernel = static_cast<bool>(std::atoi(argv[optind]));

        if(scales.empty())
        {
            scales.push_back(1.0f);
            scales.push_back(0.0f);
        };

        return (0);
    };
};

int main(int argc, char* argv[])
{
    // Example: batched gemm C[G, M, N] applies max/sum reduction along N internally
    const std::vector<int> invariantDims{0, 1};
    const std::vector<int> reduceDims{2};

    SimpleAppArgs args;

    if(argc > 1)
    {
        if(args.processArgs(argc, argv) < 0)
            return (-1);
    };

    Tensor<InDataType> in(args.inLengths);
    Tensor<OutDataType> out_ref(args.inLengths);
    Tensor<OutDataType> out(args.inLengths);

154
    auto inStrides = in.GetStrides();
155
156
157
158

    AccDataType alpha = args.scales[0];
    AccDataType beta  = args.scales[1];

159
160
    std::cout << "in: " << in.GetDesc() << std::endl;
    std::cout << "out: " << out.GetDesc() << std::endl;
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
    std::size_t num_thread = 1;

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

        if(beta != 0.0f)
186
187
188
        {
            ck::ranges::copy(out_ref, out.begin());
        }
189
190
    };
    // std::cout << "beta = " << beta << std::endl;
191
192
    // LogRangeAsType<float>(std::cout << "tensor in: " , in, ",") << std::endl;
    // LogRangeAsType<float>(std::cout << "tensor prior out: " , out, ",") << std::endl;
193
194

    // these buffers are usually provided by the user application
195
196
    DeviceMem in_dev(in.GetMemorySize());
    DeviceMem out_dev(out.GetMemorySize());
197

198
    in_dev.ToDevice(in.data());
199
200

    if(beta != 0.0f)
201
        out_dev.ToDevice(out.data());
202
203
204
205

    if(args.do_verification)
    {
        using ReferenceInstance =
Adam Osewski's avatar
Adam Osewski committed
206
            ck::tensor_operation::host::ReferenceSoftmax<InDataType, OutDataType, AccDataType>;
207
        ReferenceInstance ref;
208
        auto ref_arg = ref.MakeArgument(in, out_ref, alpha, beta, reduceDims);
209
210
        auto invoker = ref.MakeInvoker();
        invoker.Run(ref_arg);
211
        // LogRangeAsType<float>(std::cout << "tensor out_ref: ", out_ref, ",") << std::endl;
212
213
    };

214
    using Indices = std::vector<ck::index_t>;
215
216
217

    auto device_instance = DeviceInstance{};

218
    std::cout << args.inLengths.size() << ", " << inStrides.size() << std::endl;
rocking5566's avatar
rocking5566 committed
219

220
221
    auto argument_ptr = device_instance.MakeArgumentPointer(ck::ranges::to<Indices>(args.inLengths),
                                                            ck::ranges::to<Indices>(inStrides),
222
                                                            reduceDims,
223
224
                                                            &alpha,
                                                            &beta,
225
                                                            in_dev.GetDeviceBuffer(),
Adam Osewski's avatar
Adam Osewski committed
226
227
228
                                                            out_dev.GetDeviceBuffer(),
                                                            PassThrough{},
                                                            PassThrough{});
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

    if(!device_instance.IsSupportedArgument(argument_ptr.get()))
    {
        std::cout
            << "The runtime parameters seems not supported by the DeviceReduce instance, exiting!"
            << std::endl;
        return 1;
    };

    std::string instance_name = device_instance.GetTypeString();

    auto invoker_ptr = device_instance.MakeInvokerPointer();

    bool pass = true;
    if(args.do_verification)
    {
        invoker_ptr->Run(argument_ptr.get(), StreamConfig{nullptr, false});
246
247
248
        out_dev.FromDevice(out.data());
        // LogRangeAsType<float>(std::cout << "tensor out: " , out, ",") << std::endl;
        pass = pass && ck::utils::check_err(out, out_ref);
249
250
251
252
    };

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

253
254
    std::size_t num_bytes = in.GetElementSize() * sizeof(InDataType) +
                            (beta == 0.0f ? 1 : 2) * out.GetElementSize() * sizeof(OutDataType);
255
256
257
258
259
260
261
262

    float gb_per_sec = num_bytes / 1.E6 / avg_time;

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

    return (pass ? 0 : 1);
}