| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2023 THL A29 Limited, a Tencent company. All rights reserved. |
| 4 | // |
| 5 | // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except |
| 6 | // in compliance with the License. You may obtain a copy of the License at |
| 7 | // |
| 8 | // https://opensource.org/licenses/BSD-3-Clause |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software distributed |
| 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | // specific language governing permissions and limitations under the License. |
| 14 | |
| 15 | #include "insert_reshape_global_pooling.h" |
| 16 | |
| 17 | #include <algorithm> |
| 18 | #include <set> |
| 19 | |
| 20 | namespace pnnx { |
| 21 | |
| 22 | namespace ncnn { |
| 23 | |
| 24 | static bool is_known_operator_handle_flatten_0(const Operator* op) |
| 25 | { |
| 26 | // opeartors that have similar behavior for (1,c,1,1,1)/(1,c,1,1)/(1,c,1) and (1,c) |
| 27 | |
| 28 | static const char* operator_handle_flatten_0[] = { |
| 29 | "F.batch_norm", |
| 30 | "F.celu", |
| 31 | "F.conv1d", |
| 32 | "F.conv2d", |
| 33 | "F.conv3d", |
| 34 | "F.elu", |
| 35 | "F.gelu", |
| 36 | "F.glu", |
| 37 | "F.hardshrink", |
| 38 | "F.hardsigmoid", |
| 39 | "F.hardswish", |
| 40 | "F.hardtanh", |
| 41 | "F.leaky_relu", |
| 42 | "F.linear", |
| 43 | "F.log_softmax", |
| 44 | "F.logsigmoid", |
| 45 | "F.prelu", |
| 46 | "F.relu", |
| 47 | "F.relu6", |
| 48 | "F.rrelu", |
| 49 | "F.selu", |
| 50 | "F.sigmoid", |
| 51 | "F.silu", |
| 52 | "F.softmax", |
| 53 | "F.softmin", |
| 54 | "F.softplus", |
| 55 | "F.softshrink", |
| 56 | "F.softsign", |
| 57 | "F.tanh", |
| 58 | "F.tanhshrink", |
| 59 | "F.threshold", |
| 60 | |
| 61 | "nn.BatchNorm1d", |
| 62 | "nn.BatchNorm2d", |
| 63 | "nn.BatchNorm3d", |
| 64 | "nn.CELU", |
| 65 | "nn.Conv1d", |
| 66 | "nn.Conv2d", |
| 67 | "nn.Conv3d", |
| 68 | "nn.ELU", |
| 69 | "nn.GELU", |
| 70 | "nn.GLU", |
| 71 | "nn.Hardshrink", |
| 72 | "nn.Hardsigmoid", |
| 73 | "nn.Hardswish", |
| 74 | "nn.Hardtanh", |
| 75 | "nn.LeakyReLU", |
| 76 | "nn.Linear", |
| 77 | "nn.LogSigmoid", |
| 78 | "nn.LogSoftmax", |
| 79 | "nn.PReLU", |
| 80 | "nn.ReLU", |
| 81 | "nn.ReLU6", |
| 82 | "nn.RReLU", |
| 83 | "nn.SELU", |
| 84 | "nn.Sigmoid", |
| 85 | "nn.SiLU", |
| 86 | "nn.Softmax", |
| 87 | "nn.Softmin", |
| 88 | "nn.Softplus", |
| 89 | "nn.Softshrink", |
| 90 | "nn.Softsign", |
| 91 | "nn.Tanh", |
| 92 | "nn.Tanhshrink", |
| 93 | "nn.Threshold", |
| 94 | |
| 95 | "torch.abs", |
| 96 | "torch.acos", |
| 97 | "torch.acosh", |
| 98 | "torch.asin", |
| 99 | "torch.asinh", |
| 100 | "torch.atan", |
| 101 | "torch.atanh", |
| 102 | "torch.atan2", |
| 103 | "torch.ceil", |
| 104 | "torch.clamp", |
| 105 | "torch.cos", |
| 106 | "torch.cosh", |
| 107 | "torch.exp", |
| 108 | "torch.floor", |
| 109 | "torch.imag", |
| 110 | "torch.log", |
| 111 | "torch.log10", |
| 112 | "torch.neg", |
| 113 | "torch.pow", |
| 114 | "torch.real", |
| 115 | "torch.reciprocal", |
| 116 | "torch.rsqrt", |
| 117 | "torch.sign", |
| 118 | "torch.sin", |
| 119 | "torch.sinh", |
| 120 | "torch.sqrt", |
| 121 | "torch.square", |
| 122 | "torch.tan", |
| 123 | "torch.tanh", |
| 124 | "torch.trunc", |
| 125 | }; |
| 126 | |
| 127 | const size_t operator_handle_flatten_0_count = sizeof(operator_handle_flatten_0) / sizeof(const char*); |
| 128 | for (size_t i = 0; i < operator_handle_flatten_0_count; i++) |
| 129 | { |
| 130 | if (op->type == operator_handle_flatten_0[i]) |
| 131 | return true; |
| 132 | } |
| 133 | |
| 134 | return false; |
| 135 | } |
| 136 | |
| 137 | static int is_global_pooling(const Operator* op) |
| 138 | { |
| 139 | static const char* operator_with_flatten_state_0[] = { |
| 140 | "F.adaptive_avg_pool2d", |
| 141 | "F.adaptive_avg_pool3d", |
| 142 | "F.adaptive_max_pool2d", |
| 143 | "F.adaptive_max_pool3d", |
| 144 | "nn.AdaptiveAvgPool2d", |
| 145 | "nn.AdaptiveAvgPool3d", |
| 146 | "nn.AdaptiveMaxPool2d", |
| 147 | "nn.AdaptiveMaxPool3d", |
| 148 | }; |
| 149 | |
| 150 | const size_t operator_with_flatten_state_0_count = sizeof(operator_with_flatten_state_0) / sizeof(const char*); |
| 151 | for (size_t i = 0; i < operator_with_flatten_state_0_count; i++) |
| 152 | { |
| 153 | if (op->type == operator_with_flatten_state_0[i]) |
| 154 | { |
| 155 | // output_size=(1,1) |
| 156 | // output_size=(1,1,1) |
| 157 | const std::vector<int>& output_size = op->params.at("output_size").ai; |
| 158 | if (output_size == std::vector<int> {1, 1}) |
| 159 | return 3; |
| 160 | if (output_size == std::vector<int> {1, 1, 1}) |
| 161 | return 4; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | return 0; |
| 166 | } |
| 167 | |
| 168 | static int insert_reshape_global_pooling_forward(Operand* operand, int pooled_rank, Graph& graph) |
| 169 | { |
| 170 | for (size_t i = 0; i < operand->consumers.size(); i++) |
| 171 | { |
| 172 | Operator* op = operand->consumers[i]; |
| 173 | |
| 174 | if (op->type == "Tensor.reshape" || op->type == "Tensor.view") |
| 175 | { |
| 176 | // reshape discard flatten state |
| 177 | break; |
| 178 | } |
| 179 | |
| 180 | if (is_known_operator_handle_flatten_0(op)) |
| 181 | { |
| 182 | for (Operand* r : op->outputs) |
| 183 | { |
| 184 | int ret = insert_reshape_global_pooling_forward(r, pooled_rank, graph); |
| 185 | if (ret) |
| 186 | return ret; |
| 187 | } |
| 188 | continue; |
| 189 | } |
| 190 | |
| 191 | if (op->type == "pnnx.Expression") |
| 192 | { |
| 193 | // if it can be auto-broadcast |
| 194 | // (1,c) with (1,c,d,h,w)/(1,c,h,w)/(1,c,w)/(1,c) |
| 195 | if (operand->shape.size() == 4 && op->outputs[0]->shape.size() >= 2) |
| 196 | { |
| 197 | if (operand->shape[1] == op->outputs[0]->shape[1]) |
| 198 | break; |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | fprintf(stderr, "insert_reshape_global_pooling_forward %s %s\n", op->name.c_str(), operand->name.c_str()); |
| 203 | |
| 204 | // insert reshape (1,c,1,1) before op |
| 205 | Operator* reshape0 = graph.new_operator_before("Tensor.reshape", op->name + "_ncnnreshape0", op); |
| 206 | |
| 207 | Operand* reshape0_out = graph.new_operand(op->name + "_ncnnreshape0_out"); |
| 208 | |
| 209 | reshape0->inputs.push_back(operand); |
| 210 | reshape0->outputs.push_back(reshape0_out); |
| 211 | |
| 212 | operand->consumers[i] = reshape0; |
| 213 | |
| 214 | for (size_t j = 0; j < op->inputs.size(); j++) |
| 215 | { |
| 216 | if (op->inputs[j] == operand) |
| 217 | { |
| 218 | op->inputs[j] = reshape0_out; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | reshape0_out->producer = reshape0; |
| 223 | reshape0_out->consumers.push_back(op); |
| 224 | |
| 225 | reshape0_out->params["__batch_index"] = 0; |
| 226 | |
| 227 | if (pooled_rank == 3) |
| 228 | reshape0->params["shape"] = std::vector<int> {1, -1, 1, 1}; |
| 229 | if (pooled_rank == 4) |
| 230 | reshape0->params["shape"] = std::vector<int> {1, -1, 1, 1, 1}; |
| 231 | |
| 232 | return 1; |
| 233 | } |
| 234 | |
| 235 | return 0; |
| 236 | } |
| 237 | |
| 238 | void insert_reshape_global_pooling(Graph& graph) |
| 239 | { |
| 240 | int inserted = 0; |
| 241 | |
| 242 | while (1) |
| 243 | { |
| 244 | inserted = 0; |
| 245 | |
| 246 | for (Operator* op : graph.ops) |
| 247 | { |
| 248 | int pooled_rank = is_global_pooling(op); |
| 249 | if (pooled_rank == 0) |
| 250 | continue; |
| 251 | |
| 252 | // look for all output consumers |
| 253 | // insert reshape (1,c,1,1) if it cannot handle flatten |
| 254 | inserted = insert_reshape_global_pooling_forward(op->outputs[0], pooled_rank, graph); |
| 255 | if (inserted) |
| 256 | { |
| 257 | break; |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | if (inserted == 0) |
| 262 | break; |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | } // namespace ncnn |
| 267 | |
| 268 | } // namespace pnnx |