softmax.cpp 1.94 KB
Newer Older
Khalique's avatar
Khalique committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <migraphx/shape.hpp>
#include <migraphx/argument.hpp>
#include <migraphx/dfor.hpp>
#include <migraphx/gpu/device/softmax.hpp>
#include <migraphx/gpu/device/tensor.hpp>
#include <migraphx/gpu/device/launch.hpp>
#include <migraphx/gpu/device/types.hpp>
#include <migraphx/gpu/hip.hpp>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {
namespace device {

Paul's avatar
Paul committed
15
argument softmax(hipStream_t stream, argument result, argument arg, int axis)
Khalique's avatar
Khalique committed
16
{
Paul's avatar
Paul committed
17
    auto lens        = result.get_shape().lens();
Shucai Xiao's avatar
Shucai Xiao committed
18
19
    auto batch_lens  = lens;
    size_t n_dims    = lens[axis];
20
    batch_lens[axis] = 1;
Paul's avatar
Paul committed
21
    shape batch_shape{result.get_shape().type(), batch_lens};
Khalique's avatar
Khalique committed
22

Paul's avatar
Paul committed
23
    hip_visit_all(result, arg, batch_shape)([&](auto output, auto input, auto batch) {
Khalique's avatar
Khalique committed
24

Paul's avatar
Paul committed
25
26
27
28
        // each thread is for one item in the batch
        gs_launch(stream, batch_shape.elements())([=](auto i) {
            auto batch_idx = batch.multi(i);
            auto data_idx  = batch_idx;
Khalique's avatar
Khalique committed
29

Paul's avatar
Paul committed
30
31
32
33
34
35
36
            // get max
            auto batch_max = input[batch_idx];
            for(std::size_t j = 1; j < n_dims; ++j)
            {
                data_idx[axis] = j;
                batch_max      = std::max(to_hip_type(batch_max), to_hip_type(input[data_idx]));
            }
Khalique's avatar
Khalique committed
37

Paul's avatar
Paul committed
38
39
40
41
42
            for(std::size_t j = 0; j < n_dims; ++j)
            {
                data_idx[axis]   = j;
                output[data_idx] = exp(to_hip_type(input[data_idx] - batch_max));
            }
Khalique's avatar
Khalique committed
43

Paul's avatar
Paul committed
44
45
46
47
48
49
            auto batch_sum = output[batch_idx];
            for(std::size_t j = 1; j < n_dims; ++j)
            {
                data_idx[axis] = j;
                batch_sum += output[data_idx];
            }
Khalique's avatar
Khalique committed
50

Paul's avatar
Paul committed
51
52
            for(std::size_t j = 0; j < n_dims; ++j)
            {
Paul's avatar
Paul committed
53
                data_idx[axis]   = j;
Paul's avatar
Paul committed
54
55
                output[data_idx] = output[data_idx] / batch_sum;
            }
Khalique's avatar
Khalique committed
56
57
58
        });
    });

Paul's avatar
Paul committed
59
    return result;
Khalique's avatar
Khalique committed
60
61
62
63
64
65
}

} // namespace device
} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx