logsoftmax.cpp 2.06 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,
Paul's avatar
Paul committed
15
16
                    argument result,
                    argument arg,
Shucai Xiao's avatar
Shucai Xiao committed
17
                    int axis)
18
19
{

Paul's avatar
Paul committed
20
    auto lens         = result.get_shape().lens();
21
    auto num_in_batch = lens[axis];
Shucai Xiao's avatar
Shucai Xiao committed
22
23
    auto batch_lens   = lens;
    batch_lens[axis]  = 1;
Paul's avatar
Paul committed
24
    shape batch_shape{result.get_shape().type(), batch_lens};
25

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

Paul's avatar
Paul committed
28
29
30
31
        // 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;
32

Paul's avatar
Paul committed
33
34
35
36
37
38
39
            // 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]));
            }
40

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

Paul's avatar
Paul committed
47
48
49
50
51
52
53
            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));
54

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

Paul's avatar
Paul committed
63
    return result;
64
65
66
67
68
69
}

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