MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / Softmax

Function Softmax

tensorflow/lite/delegates/gpu/metal/kernels/softmax.cc:99–170  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

97} // namespace
98
99std::vector<ComputeTaskDescriptorPtr> Softmax(int id, ValueId input_id,
100 ValueId output_id,
101 int channels_count) {
102 auto desc = std::make_shared<ComputeTaskDescriptor>();
103 desc->id = id;
104 desc->is_linkable = false;
105 desc->shader_source = R"(
106 #include <metal_stdlib>
107 using namespace metal;
108 constant int src_channels = )";
109 desc->shader_source += std::to_string(channels_count);
110 desc->shader_source += R"(;
111 $0
112 kernel void ComputeFunction(
113 $1
114 uint3 gid[[thread_position_in_grid]]) {
115 if (int(gid.x) >= size.x || int(gid.y) >= size.y) {
116 return;
117 }
118 float shift = 0.0f;
119 int remaining_channels = src_channels % 4;
120
121 float sum = 0.0f;
122 for (int d = 0; d < src_channels / 4; ++d) {
123 int buffer_index = (d * size.y + gid.y) * size.x + gid.x;
124 sum += dot(float4(1.0f), exp(float4(input_buffer[buffer_index]) - shift));
125 }
126 if (remaining_channels > 0) {
127 int buffer_index = ((src_channels / 4) * size.y + gid.y) * size.x + gid.x;
128 float4 last_element = float4(input_buffer[buffer_index]);
129 sum += exp(last_element.x - shift);
130 if (remaining_channels > 1) sum += exp(last_element.y - shift);
131 if (remaining_channels == 3) sum += exp(last_element.z - shift);
132 }
133
134 for (int d = 0; d < (src_channels + 3) / 4; ++d) {
135 const int linear_index = (d * size.y + gid.y) * size.x + gid.x;
136 FLT4 value = FLT4(exp(float4(input_buffer[linear_index]) - shift) / sum);
137 $2
138 output_buffer[linear_index] = value;
139 }
140 }
141 )";
142
143 desc->input_buffers = {
144 {input_id, "device FLT4* const input_buffer"},
145 };
146
147 desc->output_buffer = {output_id, "device FLT4* output_buffer",
148 [input_id](const std::map<ValueId, BHWC>& buffers) {
149 return buffers.find(input_id)->second;
150 }};
151
152 desc->uniform_buffers = {
153 {"constant int2& size",
154 [output_id](const std::map<ValueId, BHWC>& buffers) {
155 const auto& dimension = buffers.find(output_id)->second;
156 std::vector<int> sizes{dimension.w, dimension.h};

Callers 1

SelectSoftmaxFunction · 0.50

Calls 4

to_stringFunction · 0.85
VectorToUint8VectorFunction · 0.85
IntegralDivideRoundUpFunction · 0.50
findMethod · 0.45

Tested by

no test coverage detected