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

argument logsoftmax(hipStream_t stream,
Shucai Xiao's avatar
Shucai Xiao committed
15
16
17
                    const migraphx::shape& output_shape,
                    std::vector<migraphx::argument> args,
                    int axis)
18
19
20
21
22
23
24
25
26
27
{

    auto lens              = output_shape.lens();
    std::size_t batch_size = std::accumulate(
        lens.begin(), lens.begin() + axis, std::size_t{1}, std::multiplies<std::size_t>());
    std::size_t n_dims = std::accumulate(
        lens.begin() + axis, lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
    migraphx::shape comp_shape{output_shape.type(), {batch_size, n_dims}};

    visit_all(args.back(), args.front())([&](auto output, auto input) {
Shucai Xiao's avatar
Shucai Xiao committed
28
29
        const auto* input_ptr = device_cast(input.data());
        auto* output_ptr      = device_cast(output.data());
30
31
32
33
34
35

        // each thread is for one item in the batch
        gs_launch(stream, batch_size)([=](auto i) {
            std::size_t row_start = i * n_dims;
            // get max
            auto batch_max = input_ptr[row_start];
Shucai Xiao's avatar
Shucai Xiao committed
36
            for(std::size_t j = 1; j < n_dims; ++j)
37
            {
Shucai Xiao's avatar
Shucai Xiao committed
38
                auto ind  = row_start + j;
39
40
41
                batch_max = std::max(to_hip_type(batch_max), to_hip_type(input_ptr[ind]));
            }

Shucai Xiao's avatar
Shucai Xiao committed
42
            for(std::size_t j = 0; j < n_dims; ++j)
43
            {
Shucai Xiao's avatar
Shucai Xiao committed
44
                auto ind        = row_start + j;
45
46
47
                output_ptr[ind] = input_ptr[ind] - batch_max;
            }

48
            auto batch_sum = ::exp(to_hip_type(output_ptr[row_start]));
Shucai Xiao's avatar
Shucai Xiao committed
49
            for(std::size_t j = 1; j < n_dims; ++j)
50
51
52
53
54
55
            {
                auto ind = row_start + j;
                batch_sum += ::exp(to_hip_type(output_ptr[ind]));
            }
            batch_sum = ::log(to_hip_type(batch_sum));

Shucai Xiao's avatar
Shucai Xiao committed
56
            for(std::size_t j = 0; j < n_dims; ++j)
57
58
59
60
61
62
63
64
65
66
67
68
69
70
            {
                auto ind = row_start + j;
                output_ptr[ind] -= batch_sum;
            }
        });
    });

    return args.back();
}

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