logsoftmax.cpp 2.09 KB
Newer Older
1
2
3
#include <migraphx/shape.hpp>
#include <migraphx/argument.hpp>
#include <migraphx/gpu/device/logsoftmax.hpp>
4
#include <migraphx/gpu/device/reduce.hpp>
5
6
7
8
9
10
11
12
13
14
#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 {

15
void logsoftmax(hipStream_t stream, const argument& result, const argument& arg, int axis)
16
{
17
18
19
20
    auto lens                  = result.get_shape().lens();
    auto batch_lens            = lens;
    std::size_t batch_item_num = lens[axis];
    batch_lens[axis]           = 1;
21
    migraphx::shape batch_shape{result.get_shape().type(), batch_lens};
22

Paul's avatar
Paul committed
23
    hip_visit_all(result, arg, batch_shape)([&](auto output, auto input, auto batch) {
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
        const std::size_t max_block_size = 256;
        const std::size_t block_size     = compute_block_size(batch_item_num, max_block_size);
        gs_launch(stream, batch_shape.elements() * block_size, block_size)([=](auto i, auto idx) __device__ {
            auto data_idx = batch.multi(i / block_size);
            using type = device_type<std::remove_cv_t<typename decltype(input)::value_type>>;
            type init = lowest();

            auto batch_max = block_reduce<max_block_size>(idx, max{}, init, batch_item_num, [&](auto j) __device__ {
                data_idx[axis] = j;
                return input[data_idx];
            });

            auto batch_sum = block_reduce<max_block_size>(idx, sum{}, 0, batch_item_num, [&](auto j) __device__ {
                data_idx[axis] = j;
                auto val = input[data_idx] - batch_max;
                return ::exp(to_hip_type(val));
            });

            auto log_batch_sum = ::log(to_hip_type(batch_sum)) + batch_max;

            idx.local_stride(batch_item_num, [&](auto j) { 
                data_idx[axis] = j;
Shucai Xiao's avatar
Shucai Xiao committed
46
                output[data_idx] = input[data_idx] - log_batch_sum;
47
            });
48
49
50
51
52
53
54
55
        });
    });
}

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