logsoftmax.cpp 2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
#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 {

Paul's avatar
Paul committed
14
argument logsoftmax(hipStream_t stream, argument result, argument arg, int axis)
15
16
{

Paul's avatar
Paul committed
17
    auto lens         = result.get_shape().lens();
18
    auto num_in_batch = lens[axis];
Shucai Xiao's avatar
Shucai Xiao committed
19
20
    auto batch_lens   = lens;
    batch_lens[axis]  = 1;
Paul's avatar
Paul committed
21
    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

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;
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 < num_in_batch; ++j)
            {
                data_idx[axis] = j;
                batch_max      = std::max(to_hip_type(batch_max), to_hip_type(input[data_idx]));
            }
37

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

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

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

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

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