| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2021 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 "shape_inference.h" |
| 16 | #include <unordered_set> |
| 17 | |
| 18 | #include "storezip.h" |
| 19 | #include "pass_level0/constant_unpooling.h" |
| 20 | #include "pass_level0/convert_half_to_float.h" |
| 21 | #include "pass_level0/flatten_input.h" |
| 22 | #include "pass_level0/inline_block.h" |
| 23 | #include "pass_level0/reset_device.h" |
| 24 | #include "pass_level0/shape_inference.h" |
| 25 | |
| 26 | namespace pnnx { |
| 27 | |
| 28 | static bool is_inplace_op(const std::string& optype) |
| 29 | { |
| 30 | return optype.size() > 2 && optype[optype.size() - 2] != '_' && optype[optype.size() - 1] == '_'; |
| 31 | } |
| 32 | |
| 33 | static bool is_alias_op(const std::string& optype) |
| 34 | { |
| 35 | return optype == "aten::slice" || optype == "aten::select" || optype == "aten::view"; |
| 36 | } |
| 37 | |
| 38 | static bool is_static_shape_foldable(const std::string& optype) |
| 39 | { |
| 40 | return optype == "aten::size" |
| 41 | || optype == "aten::new_empty" |
| 42 | || optype == "aten::new_full" |
| 43 | || optype == "aten::new_ones" |
| 44 | || optype == "aten::new_zeros" |
| 45 | || optype == "aten::empty_like" |
| 46 | || optype == "aten::full_like" |
| 47 | || optype == "aten::ones_like" |
| 48 | || optype == "aten::zeros_like" |
| 49 | || optype == "aten::_shape_as_tensor"; |
| 50 | } |
| 51 | |
| 52 | static void build_value_link_input_map(const torch::jit::Node* node, const std::unordered_map<std::string, torch::jit::Value*>& value_alias_map, std::unordered_map<std::string, int>& value_link_input_map, bool ignore_aten_size) |
| 53 | { |
| 54 | std::string optype = node->kind().toDisplayString(); |
| 55 | |
| 56 | if (ignore_aten_size && is_static_shape_foldable(optype)) |
| 57 | { |
| 58 | return; |
| 59 | } |
| 60 | |
| 61 | for (size_t i = 0; i < node->outputs().size(); i++) |
| 62 | { |
| 63 | auto out2 = node->outputs()[i]; |
| 64 | |
| 65 | std::string os = out2->debugName(); |
| 66 | |
| 67 | if (!os.empty() && value_link_input_map.find(os) != value_link_input_map.end()) |
| 68 | continue; |
| 69 | |
| 70 | auto tensor_type = out2->type()->cast<torch::jit::TensorType>(); |
| 71 | if (tensor_type) |
| 72 | { |
| 73 | value_link_input_map[os] = 1; |
| 74 | } |
| 75 | |
| 76 | for (size_t j = 0; j < out2->uses().size(); j++) |
| 77 | { |
| 78 | auto node2 = out2->uses()[j].user; |
| 79 | |
| 80 | build_value_link_input_map(node2, value_alias_map, value_link_input_map, true); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | if (is_inplace_op(optype) || is_alias_op(optype)) |
| 85 | { |
| 86 | // infect input0 and its alias |
| 87 | while (1) |
| 88 | { |
| 89 | auto in2 = node->inputs()[0]; |
| 90 | |
| 91 | std::string is = in2->debugName(); |
| 92 | |
| 93 | if (is.empty()) |
| 94 | break; |
| 95 | |
| 96 | if (value_alias_map.find(is) == value_alias_map.end()) |
| 97 | break; |
| 98 | |
| 99 | auto in3 = value_alias_map.at(is); |
| 100 | |
| 101 | auto tensor_type = in3->type()->cast<torch::jit::TensorType>(); |
| 102 | if (!tensor_type) |
| 103 | break; |
| 104 | |
| 105 | is = in3->debugName(); |
| 106 | |
| 107 | if (value_link_input_map.find(is) != value_link_input_map.end()) |
| 108 | break; |
| 109 | |
| 110 | for (size_t j = 0; j < in3->uses().size(); j++) |
| 111 | { |
| 112 | auto node2 = in3->uses()[j].user; |
| 113 | |
| 114 | build_value_link_input_map(node2, value_alias_map, value_link_input_map, true); |
| 115 | } |
| 116 | |
| 117 | break; |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | static bool value_link_output(const torch::jit::Value* v, const std::vector<torch::jit::Value*>& outputs) |
| 123 | { |
| 124 | for (auto x : outputs) |
| 125 | { |
| 126 | if (v == x) |
| 127 | return true; |
| 128 | } |
| 129 | |
| 130 | for (size_t i = 0; i < v->uses().size(); i++) |
| 131 | { |
| 132 | auto node = v->uses()[i].user; |
| 133 | for (auto x : node->outputs()) |
| 134 | { |
| 135 | bool link = value_link_output(x, outputs); |
| 136 | if (link) |
| 137 | return true; |
| 138 | } |
| 139 | |
| 140 | std::string op_type = node->kind().toDisplayString(); |
| 141 | if (is_inplace_op(op_type)) |
| 142 | { |
| 143 | // optimize me: track other inplace op inputs |
| 144 | return true; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | return false; |
| 149 | } |
| 150 | |
| 151 | void shape_inference(const torch::jit::Module& mod, std::shared_ptr<torch::jit::Graph>& graph, const std::vector<at::Tensor>& input_tensors, const std::vector<at::Tensor>& input_tensors2, const std::vector<std::string>& module_operators, const std::string& ptpath, const std::string& device, std::set<std::string>& foldable_constants, const std::string& foldable_constants_zippath) |
| 152 | { |
| 153 | // collect all intermediate output tensors |
| 154 | std::vector<std::unordered_set<std::string> > more_value_names; |
| 155 | std::vector<std::vector<torch::jit::Value*> > more_values; |
| 156 | { |
| 157 | std::unordered_set<std::string> value_names; |
| 158 | std::vector<torch::jit::Value*> values; |
| 159 | for (const auto& n : graph->nodes()) |
| 160 | { |
| 161 | for (const auto& v : n->outputs()) |
| 162 | { |
| 163 | auto tensor_type = v->type()->cast<torch::jit::TensorType>(); |
| 164 | if (!tensor_type) |
| 165 | continue; |
| 166 | |
| 167 | value_names.insert(v->debugName()); |
| 168 | values.push_back(v); |
| 169 | } |
| 170 | |
| 171 | // too many intermediate blobs in one inference results oom |
| 172 | if (value_names.size() >= 1000) |
| 173 | { |
| 174 | more_value_names.push_back(value_names); |
| 175 | value_names.clear(); |
| 176 | |
| 177 | more_values.push_back(values); |
| 178 | values.clear(); |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | if (value_names.size() > 0) |
| 183 | { |
| 184 | more_value_names.push_back(value_names); |
| 185 | more_values.push_back(values); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | // collect graph inputs outputs |
| 190 | std::vector<torch::jit::Value*> g_inputs; |
| 191 | for (size_t i = 1; i < graph->inputs().size(); i++) |
| 192 | { |
| 193 | g_inputs.push_back(graph->inputs()[i]); |
| 194 | } |
| 195 | std::vector<torch::jit::Value*> g_outputs; |
| 196 | for (size_t i = 0; i < graph->outputs().size(); i++) |
| 197 | { |
| 198 | g_outputs.push_back(graph->outputs()[i]); |
| 199 | } |
| 200 | |
| 201 | std::vector<torch::jit::IValue> inputs; |
| 202 | for (size_t i = 0; i < input_tensors.size(); i++) |
| 203 | { |
| 204 | const at::Tensor& it = input_tensors[i]; |
| 205 | inputs.push_back(it); |
| 206 | } |
| 207 | |
| 208 | std::vector<torch::jit::IValue> inputs2; |
| 209 | for (size_t i = 0; i < input_tensors2.size(); i++) |
| 210 | { |
| 211 | const at::Tensor& it = input_tensors2[i]; |
| 212 | inputs2.push_back(it); |
| 213 | } |
| 214 | |
| 215 | // bookkeep foldable tensors |
| 216 | std::unordered_map<std::string, int> value_link_input_map; |
| 217 | { |
| 218 | // build value alias map for inplace op |
| 219 | std::unordered_map<std::string, torch::jit::Value*> value_alias_map; |
| 220 | |
| 221 | for (const auto& n : graph->block()->nodes()) |
| 222 | { |
| 223 | if (n->kind() == c10::prim::GetAttr) |
| 224 | continue; |
| 225 | |
| 226 | if (n->kind() == c10::prim::Constant) |
| 227 | continue; |
| 228 | |
| 229 | if (n->kind() == c10::prim::CallMethod) |
| 230 | continue; |
| 231 | |
| 232 | std::string optype = n->kind().toDisplayString(); |
| 233 | |
| 234 | // fprintf(stderr, "optype = %s\n", optype.c_str()); |
| 235 | |
| 236 | if (!is_inplace_op(optype) && !is_alias_op(optype)) |
| 237 | continue; |
| 238 | |
| 239 | if (n->inputs().size() == 0) |
| 240 | continue; |
| 241 | |
| 242 | if (n->outputs().size() == 0) |
| 243 | continue; |
| 244 | |
| 245 | std::string is = n->input(0)->debugName(); |
| 246 | |
| 247 | if (is.empty()) |
| 248 | continue; |
| 249 | |
| 250 | for (size_t i = 0; i < n->outputs().size(); i++) |
| 251 | { |
| 252 | auto out2 = n->output(i); |
| 253 | |
| 254 | auto tensor_type = out2->type()->cast<torch::jit::TensorType>(); |
| 255 | if (!tensor_type) |
| 256 | continue; |
| 257 | |
| 258 | std::string os = out2->debugName(); |
| 259 | |
| 260 | if (os.empty()) |
| 261 | continue; |
| 262 | |
| 263 | if (value_alias_map.find(is) == value_alias_map.end()) |
| 264 | { |
| 265 | value_alias_map[os] = n->input(0); |
| 266 | } |
| 267 | else |
| 268 | { |
| 269 | value_alias_map[os] = value_alias_map[is]; |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // print value_alias_map |
| 275 | // for (const auto& x : value_alias_map) |
| 276 | // { |
| 277 | // fprintf(stderr, "alias %s -> %s\n", x.first.c_str(), x.second->debugName().c_str()); |
| 278 | // } |
| 279 | |
| 280 | bool ignore_aten_size = input_tensors2.empty(); |
| 281 | for (size_t i = 1; i < graph->inputs().size(); i++) |
| 282 | { |
| 283 | auto in0 = graph->inputs()[i]; |
| 284 | |
| 285 | for (size_t j = 0; j < in0->uses().size(); j++) |
| 286 | { |
| 287 | auto node = in0->uses()[j].user; |
| 288 | |
| 289 | build_value_link_input_map(node, value_alias_map, value_link_input_map, ignore_aten_size); |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | // print value_link_input_map |
| 294 | // for (const auto& x : value_link_input_map) |
| 295 | // { |
| 296 | // fprintf(stderr, "link_input %s %d\n", x.first.c_str(), x.second); |
| 297 | // } |
| 298 | } |
| 299 | |
| 300 | StoreZipWriter zip; |
| 301 | zip.open(foldable_constants_zippath); |
| 302 | |
| 303 | for (size_t p = 0; p < more_value_names.size(); p++) |
| 304 | { |
| 305 | std::unordered_set<std::string>& value_names = more_value_names[p]; |
| 306 | std::vector<torch::jit::Value*>& values = more_values[p]; |
| 307 | |
| 308 | // auto mod2 = mod.deepcopy(); |
| 309 | |
| 310 | torch::jit::Module mod2 = torch::jit::load(ptpath, (device == "gpu") ? c10::kCUDA : c10::kCPU); |
| 311 | mod2.eval(); |
| 312 | |
| 313 | convert_half_to_float(mod2); |
| 314 | |
| 315 | auto method = mod2.find_method("forward"); |
| 316 | if (!method) |
| 317 | { |
| 318 | method = mod2.get_methods()[0]; |
| 319 | } |
| 320 | |
| 321 | auto graph2 = method->graph(); |
| 322 | |
| 323 | inline_block(graph2, module_operators); |
| 324 | |
| 325 | reset_device(graph2, device); |
| 326 | |
| 327 | flatten_input(graph2); |
| 328 | |
| 329 | constant_unpooling(graph2); |
| 330 | |
| 331 | std::vector<torch::jit::Value*> values2; |
| 332 | for (auto n : graph2->nodes()) |
| 333 | { |
| 334 | for (const auto& v : n->outputs()) |
| 335 | { |
| 336 | auto tensor_type = v->type()->cast<torch::jit::TensorType>(); |
| 337 | if (!tensor_type) |
| 338 | continue; |
| 339 | |
| 340 | if (value_names.find(v->debugName()) != value_names.end()) |
| 341 | { |
| 342 | values2.push_back(v); |
| 343 | // fprintf(stderr, "%s ", v->debugName().c_str()); |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | fprintf(stderr, "\n----------------\n\n"); |
| 348 | |
| 349 | // set new graph output |
| 350 | torch::jit::Node* new_return_node = graph2->createTuple(at::ArrayRef<torch::jit::Value*>(values2)); |
| 351 | |
| 352 | graph2->appendNode(new_return_node); |
| 353 | |
| 354 | graph2->eraseOutput(0); |
| 355 | graph2->registerOutput(new_return_node->outputs()[0]); |
| 356 | |
| 357 | // construct schema for new inputs and outputs |
| 358 | { |
| 359 | auto oldfs = method->function().getSchema(); |
| 360 | |
| 361 | std::vector<c10::Argument> arguments; |
| 362 | std::vector<c10::Argument> returns; |
| 363 | for (size_t i = 0; i < graph2->inputs().size(); i++) |
| 364 | { |
| 365 | auto v = graph2->inputs()[i]; |
| 366 | arguments.push_back(c10::Argument(v->debugName(), v->type())); |
| 367 | } |
| 368 | for (size_t i = 0; i < graph2->outputs().size(); i++) |
| 369 | { |
| 370 | auto v = graph2->outputs()[i]; |
| 371 | returns.push_back(c10::Argument(v->debugName(), v->type())); |
| 372 | } |
| 373 | |
| 374 | c10::FunctionSchema newfs(oldfs.name(), oldfs.overload_name(), arguments, returns); |
| 375 | method->function().setSchema(newfs); |
| 376 | } |
| 377 | |
| 378 | // inference for all tensors |
| 379 | auto outputs = mod2.copy().get_method(method->name())(inputs).toTuple(); |
| 380 | |
| 381 | if (input_tensors2.empty()) |
| 382 | { |
| 383 | // assign shape info |
| 384 | for (size_t i = 0; i < values2.size(); i++) |
| 385 | { |
| 386 | auto v = values[i]; |
| 387 | auto t = outputs->elements()[i].toTensor(); |
| 388 | |
| 389 | v->setType(c10::TensorType::create(t)); |
| 390 | |
| 391 | // check if value that does not depend on inputs |
| 392 | if (value_link_input_map.find(v->debugName()) == value_link_input_map.end() && value_link_output(v, g_outputs)) |
| 393 | { |
| 394 | // fprintf(stderr, "foldable_constant %s\n", v->debugName().c_str()); |
| 395 | foldable_constants.insert(v->debugName()); |
| 396 | |
| 397 | at::Tensor t2 = t.cpu().contiguous(); |
| 398 | zip.write_file(v->debugName(), (const char*)t2.data_ptr(), t2.nbytes()); |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | else |
| 403 | { |
| 404 | // assign dynamic shape info |
| 405 | auto outputs2 = mod2.copy().get_method(method->name())(inputs2).toTuple(); |
| 406 | |
| 407 | fprintf(stderr, "assign dynamic shape info\n"); |
| 408 | |
| 409 | for (size_t i = 0; i < values2.size(); i++) |
| 410 | { |
| 411 | auto v = values[i]; |
| 412 | auto t = outputs->elements()[i].toTensor(); |
| 413 | auto t2 = outputs2->elements()[i].toTensor(); |
| 414 | |
| 415 | auto type1 = c10::TensorType::create(t); |
| 416 | auto type2 = c10::TensorType::create(t2); |
| 417 | |
| 418 | std::vector<c10::ShapeSymbol> sizes1 = type1->symbolic_sizes().sizes().value(); |
| 419 | std::vector<c10::ShapeSymbol> sizes2 = type2->symbolic_sizes().sizes().value(); |
| 420 | |
| 421 | for (size_t i = 0; i < sizes1.size(); i++) |
| 422 | { |
| 423 | if (sizes1[i] == sizes2[i]) |
| 424 | continue; |
| 425 | |
| 426 | sizes1[i] = c10::ShapeSymbol::fromStaticSize(-1); |
| 427 | } |
| 428 | |
| 429 | auto finaltype = type1->withSymbolicShapes(c10::SymbolicShape(sizes1)); |
| 430 | |
| 431 | v->setType(finaltype); |
| 432 | |
| 433 | // check if value that does not depend on inputs |
| 434 | if (value_link_input_map.find(v->debugName()) == value_link_input_map.end() && value_link_output(v, g_outputs)) |
| 435 | { |
| 436 | // fprintf(stderr, "foldable_constant %s\n", v->debugName().c_str()); |
| 437 | foldable_constants.insert(v->debugName()); |
| 438 | |
| 439 | at::Tensor t2 = t.cpu().contiguous(); |
| 440 | zip.write_file(v->debugName(), (const char*)t2.data_ptr(), t2.nbytes()); |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | zip.close(); |
| 447 | |
| 448 | if (input_tensors2.empty()) |
| 449 | { |
| 450 | for (size_t i = 0; i < input_tensors.size(); i++) |
| 451 | { |
| 452 | auto type = c10::TensorType::create(input_tensors[i]); |
| 453 | |
| 454 | graph->inputs()[1 + i]->setType(type); |
| 455 | } |
| 456 | } |
| 457 | else |
| 458 | { |
| 459 | for (size_t i = 0; i < input_tensors.size(); i++) |
| 460 | { |
| 461 | auto type1 = c10::TensorType::create(input_tensors[i]); |
| 462 | auto type2 = c10::TensorType::create(input_tensors2[i]); |
| 463 | |
| 464 | std::vector<c10::ShapeSymbol> sizes1 = type1->symbolic_sizes().sizes().value(); |
| 465 | std::vector<c10::ShapeSymbol> sizes2 = type2->symbolic_sizes().sizes().value(); |
| 466 | |
| 467 | for (size_t i = 0; i < sizes1.size(); i++) |
| 468 | { |
| 469 | if (sizes1[i] == sizes2[i]) |
| 470 | continue; |
| 471 | |
| 472 | sizes1[i] = c10::ShapeSymbol::fromStaticSize(-1); |
| 473 | } |
| 474 | |
| 475 | auto finaltype = type1->withSymbolicShapes(c10::SymbolicShape(sizes1)); |
| 476 | |
| 477 | graph->inputs()[1 + i]->setType(finaltype); |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | } // namespace pnnx |