diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000000..9c3f6daa4eb71 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,209 @@ +--- +Checks: ' +-bugprone-argument-comment, +-bugprone-assert-side-effect, +-bugprone-bad-signal-to-kill-thread, +-bugprone-bool-pointer-implicit-conversion, +-bugprone-branch-clone, +-bugprone-copy-constructor-init, +-bugprone-dangling-handle, +-bugprone-dynamic-static-initializers, +-bugprone-exception-escape, +-bugprone-fold-init-type, +-bugprone-forwarding-reference-overload, +-bugprone-inaccurate-erase, +-bugprone-incorrect-roundings, +-bugprone-infinite-loop, +-bugprone-integer-division, +-bugprone-macro-repeated-side-effects, +-bugprone-misplaced-operator-in-strlen-in-alloc, +-bugprone-misplaced-widening-cast, +-bugprone-move-forwarding-reference, +-bugprone-multiple-statement-macro, +-bugprone-narrowing-conversions, +-bugprone-not-null-terminated-result, +-bugprone-parent-virtual-call, +-bugprone-posix-return, +-bugprone-signed-char-misuse, +-bugprone-sizeof-container, +-bugprone-sizeof-expression, +-bugprone-string-constructor, +-bugprone-string-integer-assignment, +-bugprone-string-literal-with-embedded-nul, +-bugprone-suspicious-enum-usage, +-bugprone-suspicious-memset-usage, +-bugprone-suspicious-missing-comma, +-bugprone-suspicious-semicolon, +-bugprone-suspicious-string-compare, +-bugprone-terminating-continue, +-bugprone-throw-keyword-missing, +-bugprone-too-small-loop-variable, +-bugprone-undefined-memory-manipulation, +-bugprone-undelegated-constructor, +-bugprone-unhandled-self-assignment, +-bugprone-unused-raii, +-bugprone-unused-return-value, +-bugprone-use-after-move, +-bugprone-virtual-near-miss, +-clang-analyzer-apiModeling.StdCLibraryFunctions, +-clang-analyzer-apiModeling.TrustNonnull, +-clang-analyzer-apiModeling.google.GTest, +-clang-analyzer-apiModeling.llvm.CastValue, +-clang-analyzer-apiModeling.llvm.ReturnValue, +-clang-analyzer-core.CallAndMessage, +-clang-analyzer-core.DivideZero, +-clang-analyzer-core.DynamicTypePropagation, +-clang-analyzer-core.NonNullParamChecker, +-clang-analyzer-core.NonnilStringConstants, +-clang-analyzer-core.NullDereference, +-clang-analyzer-core.StackAddrEscapeBase, +-clang-analyzer-core.StackAddressEscape, +-clang-analyzer-core.UndefinedBinaryOperatorResult, +-clang-analyzer-core.VLASize, +-clang-analyzer-core.builtin.BuiltinFunctions, +-clang-analyzer-core.builtin.NoReturnFunctions, +-clang-analyzer-core.uninitialized.ArraySubscript, +-clang-analyzer-core.uninitialized.Assign, +-clang-analyzer-core.uninitialized.Branch, +-clang-analyzer-core.uninitialized.CapturedBlockVariable, +-clang-analyzer-core.uninitialized.UndefReturn, +-clang-analyzer-cplusplus.InnerPointer, +-clang-analyzer-cplusplus.Move, +-clang-analyzer-cplusplus.NewDelete, +-clang-analyzer-cplusplus.NewDeleteLeaks, +-clang-analyzer-cplusplus.PureVirtualCall, +-clang-analyzer-cplusplus.SelfAssignment, +-clang-analyzer-cplusplus.SmartPtr, +-clang-analyzer-cplusplus.VirtualCallModeling, +-clang-analyzer-deadcode.DeadStores, +-clang-analyzer-fuchsia.HandleChecker, +-clang-analyzer-nullability.NullPassedToNonnull, +-clang-analyzer-nullability.NullReturnedFromNonnull, +-clang-analyzer-nullability.NullabilityBase, +-clang-analyzer-nullability.NullableDereferenced, +-clang-analyzer-nullability.NullablePassedToNonnull, +-clang-analyzer-nullability.NullableReturnedFromNonnull, +-clang-analyzer-optin.cplusplus.UninitializedObject, +-clang-analyzer-optin.cplusplus.VirtualCall, +-clang-analyzer-optin.mpi.MPI-Checker, +-clang-analyzer-optin.osx.OSObjectCStyleCast, +-clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker, +-clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker, +-clang-analyzer-optin.performance.GCDAntipattern, +-clang-analyzer-optin.performance.Padding, +-clang-analyzer-optin.portability.UnixAPI, +-clang-analyzer-osx.API, +-clang-analyzer-osx.MIG, +-clang-analyzer-osx.NSOrCFErrorDerefChecker, +-clang-analyzer-osx.NumberObjectConversion, +-clang-analyzer-osx.OSObjectRetainCount, +-clang-analyzer-osx.ObjCProperty, +-clang-analyzer-osx.SecKeychainAPI, +-clang-analyzer-osx.cocoa.AtSync, +-clang-analyzer-osx.cocoa.AutoreleaseWrite, +-clang-analyzer-osx.cocoa.ClassRelease, +-clang-analyzer-osx.cocoa.Dealloc, +-clang-analyzer-osx.cocoa.IncompatibleMethodTypes, +-clang-analyzer-osx.cocoa.Loops, +-clang-analyzer-osx.cocoa.MissingSuperCall, +-clang-analyzer-osx.cocoa.NSAutoreleasePool, +-clang-analyzer-osx.cocoa.NSError, +-clang-analyzer-osx.cocoa.NilArg, +-clang-analyzer-osx.cocoa.NonNilReturnValue, +-clang-analyzer-osx.cocoa.ObjCGenerics, +-clang-analyzer-osx.cocoa.RetainCount, +-clang-analyzer-osx.cocoa.RetainCountBase, +-clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak, +-clang-analyzer-osx.cocoa.SelfInit, +-clang-analyzer-osx.cocoa.SuperDealloc, +-clang-analyzer-osx.cocoa.UnusedIvars, +-clang-analyzer-osx.cocoa.VariadicMethodTypes, +-clang-analyzer-osx.coreFoundation.CFError, +-clang-analyzer-osx.coreFoundation.CFNumber, +-clang-analyzer-osx.coreFoundation.CFRetainRelease, +-clang-analyzer-osx.coreFoundation.containers.OutOfBounds, +-clang-analyzer-osx.coreFoundation.containers.PointerSizedValues, +-clang-analyzer-security.FloatLoopCounter, +-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, +-clang-analyzer-security.insecureAPI.SecuritySyntaxChecker, +-clang-analyzer-security.insecureAPI.UncheckedReturn, +-clang-analyzer-security.insecureAPI.bcmp, +-clang-analyzer-security.insecureAPI.bcopy, +-clang-analyzer-security.insecureAPI.bzero, +-clang-analyzer-security.insecureAPI.decodeValueOfObjCType, +-clang-analyzer-security.insecureAPI.getpw, +-clang-analyzer-security.insecureAPI.gets, +-clang-analyzer-security.insecureAPI.mkstemp, +-clang-analyzer-security.insecureAPI.mktemp, +-clang-analyzer-security.insecureAPI.rand, +-clang-analyzer-security.insecureAPI.strcpy, +-clang-analyzer-security.insecureAPI.vfork, +-clang-analyzer-unix.API, +-clang-analyzer-unix.DynamicMemoryModeling, +-clang-analyzer-unix.Malloc, +-clang-analyzer-unix.MallocSizeof, +-clang-analyzer-unix.MismatchedDeallocator, +-clang-analyzer-unix.Vfork, +-clang-analyzer-unix.cstring.BadSizeArg, +-clang-analyzer-unix.cstring.CStringModeling, +-clang-analyzer-unix.cstring.NullArg, +-clang-analyzer-valist.CopyToSelf, +-clang-analyzer-valist.Uninitialized, +-clang-analyzer-valist.Unterminated, +-clang-analyzer-valist.ValistBase, +-cppcoreguidelines-avoid-c-arrays, +-cppcoreguidelines-avoid-goto, +-cppcoreguidelines-c-copy-assignment-signature, +-cppcoreguidelines-explicit-virtual-functions, +-cppcoreguidelines-init-variables, +-cppcoreguidelines-narrowing-conversions, +-cppcoreguidelines-no-malloc, +-cppcoreguidelines-pro-type-const-cast, +-cppcoreguidelines-pro-type-member-init, +-cppcoreguidelines-slicing, +-hicpp-avoid-goto, +-hicpp-exception-baseclass, +-misc-unused-alias-decls, +-misc-unused-using-decls, +-modernize-avoid-bind, +-modernize-avoid-c-arrays, +-modernize-deprecated-headers, +-modernize-deprecated-ios-base-aliases, +-modernize-loop-convert, +-modernize-make-shared, +-modernize-make-unique, +-modernize-pass-by-value, +-modernize-raw-string-literal, +-modernize-redundant-void-arg, +-modernize-replace-auto-ptr, +-modernize-replace-random-shuffle, +-modernize-shrink-to-fit, +-modernize-unary-static-assert, +-modernize-use-bool-literals, +-modernize-use-emplace, +-modernize-use-equals-default, +-modernize-use-equals-delete, +-modernize-use-noexcept, +-modernize-use-nullptr, +-modernize-use-override, +-modernize-use-transparent-functors, +-modernize-use-uncaught-exceptions, +-performance-faster-string-find, +-performance-for-range-copy, +-performance-implicit-conversion-in-loop, +-performance-inefficient-algorithm, +-performance-inefficient-string-concatenation, +-performance-inefficient-vector-operation, +-performance-move-const-arg, +-performance-move-constructor-init, +-performance-no-automatic-move, +-performance-noexcept-move-constructor, +-performance-trivially-destructible, +-performance-type-promotion-in-math-fn, +-performance-unnecessary-copy-initialization, +readability-container-size-empty, +' +HeaderFilterRegex: '^(paddle/(?!cinn)).*$' +AnalyzeTemporaryDtors: false +WarningsAsErrors: '*' +... diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d66288ac48580..c3162f1839b98 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -104,6 +104,39 @@ repos: (?x)^( paddle/utils/flat_hash_map\.h )$ +- repo: local + hooks: + - id: clang-tidy + name: clang-tidy + description: Parallel clang-tidy runner. + entry: python ./tools/codestyle/clang-tidy.py + language: system + files: \.(c|cc|cxx|cpp|h|hpp|hxx)$ + args: + - -p=build/ + - -extra-arg=-Wno-unknown-warning-option + - -extra-arg=-Wno-pessimizing-move + - -extra-arg=-Wno-braced-scalar-init + - -extra-arg=-Wno-dangling-gsl + - -extra-arg=-Wno-deprecated-copy + - -extra-arg=-Wno-final-dtor-non-final-class + - -extra-arg=-Wno-implicit-int-float-conversion + - -extra-arg=-Wno-inconsistent-missing-override + - -extra-arg=-Wno-infinite-recursion + - -extra-arg=-Wno-mismatched-tags + - -extra-arg=-Wno-self-assign + - -extra-arg=-Wno-sign-compare + - -extra-arg=-Wno-sometimes-uninitialized + - -extra-arg=-Wno-tautological-overlap-compare + - -extra-arg=-Wno-unused-const-variable + - -extra-arg=-Wno-unused-lambda-capture + - -extra-arg=-Wno-unused-private-field + - -extra-arg=-Wno-unused-value + - -extra-arg=-Wno-unused-variable + - -extra-arg=-Wno-overloaded-virtual + - -extra-arg=-Wno-defaulted-function-deleted + - -extra-arg=-Wno-delete-non-abstract-non-virtual-dtor + - -extra-arg=-Wno-return-type-c-linkage # For CMake files - repo: local hooks: diff --git a/paddle/fluid/distributed/collective/process_group_nccl.cc b/paddle/fluid/distributed/collective/process_group_nccl.cc index 58c1ae247d7c5..1bbad05aef001 100644 --- a/paddle/fluid/distributed/collective/process_group_nccl.cc +++ b/paddle/fluid/distributed/collective/process_group_nccl.cc @@ -490,7 +490,7 @@ void ProcessGroupNCCL::BroadcastUniqueNCCLID(ncclUniqueId* nccl_id) { void ProcessGroupNCCL::CreateNCCLEnvCache(const Place& place, const std::string& place_key) { - if (place_to_comm_ctx_.size() > 0) { + if (!place_to_comm_ctx_.empty()) { VLOG(3) << "Warning: Tensors from multiple devices are not supported yet."; } @@ -795,7 +795,7 @@ std::shared_ptr ProcessGroupNCCL::Broadcast( void CheckTensorsInDifferentDevices( const std::vector& tensors, const size_t num_devices) { PADDLE_ENFORCE_EQ( - tensors.size() == 0, + tensors.empty(), false, phi::errors::InvalidArgument("Tensor list must be nonempty.")); PADDLE_ENFORCE_LE( diff --git a/paddle/fluid/distributed/fleet_executor/dist_model.cc b/paddle/fluid/distributed/fleet_executor/dist_model.cc index 4836d656d180f..9ceea0de746ee 100644 --- a/paddle/fluid/distributed/fleet_executor/dist_model.cc +++ b/paddle/fluid/distributed/fleet_executor/dist_model.cc @@ -541,11 +541,11 @@ bool DistModel::PrepareFeedAndFetch() { } } - if (feeds_.size() == 0) { + if (feeds_.empty()) { LOG(ERROR) << "No feed ops in the inf program, please check the program."; return false; } - if (fetches_.size() == 0) { + if (fetches_.empty()) { LOG(ERROR) << "No fetch op in the inf program, please check the program."; return false; } diff --git a/paddle/fluid/distributed/fleet_executor/fleet_executor.cc b/paddle/fluid/distributed/fleet_executor/fleet_executor.cc index 915b1f8280408..712ae8cf4435e 100644 --- a/paddle/fluid/distributed/fleet_executor/fleet_executor.cc +++ b/paddle/fluid/distributed/fleet_executor/fleet_executor.cc @@ -261,7 +261,7 @@ void FleetExecutor::InitMessageBus() { addr = ip_port; } } - if (addr == "") { + if (addr.empty()) { PADDLE_ENFORCE_EQ( rank_to_addr.size(), 1, @@ -273,9 +273,9 @@ void FleetExecutor::InitMessageBus() { platform::errors::NotFound("Address is empty but cur rank is not 0.")); } VLOG(3) << "Current rank is " << cur_rank << " and the ip_port is " - << (addr == "" ? "empty" : addr) << "."; + << (addr.empty() ? "empty" : addr) << "."; VLOG(3) << "The number of ranks are " - << (rank_to_addr.size() == 0 ? 1 : rank_to_addr.size()) << "."; + << (rank_to_addr.empty() ? 1 : rank_to_addr.size()) << "."; VLOG(5) << ss.str(); GlobalVal::Get()->Init(cur_rank, rank_to_addr, addr); } diff --git a/paddle/fluid/distributed/fleet_executor/message_bus.cc b/paddle/fluid/distributed/fleet_executor/message_bus.cc index adc8ee16e5784..b5786e2393393 100644 --- a/paddle/fluid/distributed/fleet_executor/message_bus.cc +++ b/paddle/fluid/distributed/fleet_executor/message_bus.cc @@ -39,7 +39,7 @@ void MessageBus::Init( rank_to_addr_ = rank_to_addr; addr_ = addr; - if (addr_ != "") { + if (!addr_.empty()) { const auto& addr = GetAddr(rank_); PADDLE_ENFORCE_EQ(addr, addr_, @@ -55,7 +55,7 @@ void MessageBus::Init( defined(PADDLE_WITH_XPU_BKCL) || defined(PADDLE_WITH_CUSTOM_DEVICE) // NOTE: To make the brpc is compatible with collective, // need release the handler holding the ip address. - if (addr_ != "") { + if (!addr_.empty()) { VLOG(3) << "Message bus is releasing the fd held by gen_comm_id."; paddle::platform::SocketServer& socket_server = paddle::platform::SocketServer::GetInstance(addr_); @@ -174,7 +174,7 @@ bool MessageBus::DispatchMsgToCarrier( } void MessageBus::ListenPort() { - if (addr_ == "") { + if (addr_.empty()) { LOG(INFO) << "No need listen to port since training on single card."; return; } diff --git a/paddle/fluid/distributed/ps/service/brpc_ps_server.cc b/paddle/fluid/distributed/ps/service/brpc_ps_server.cc index c965496c68ba6..84784c32f3b2d 100644 --- a/paddle/fluid/distributed/ps/service/brpc_ps_server.cc +++ b/paddle/fluid/distributed/ps/service/brpc_ps_server.cc @@ -428,7 +428,7 @@ int32_t BrpcPsService::PushSparseParam(Table *table, 1); CHECK_TABLE_EXIST(table, request, response) auto &push_data = request.data(); - if (push_data.size() < 1) { + if (push_data.empty()) { // set_response_code(response, 0, "push sparse data is empty"); return 0; } @@ -557,7 +557,7 @@ int32_t BrpcPsService::PushSparse(Table *table, "PsService->PushSparse", platform::TracerEventType::Communication, 1); CHECK_TABLE_EXIST(table, request, response) auto &push_data = request.data(); - if (push_data.size() < 1) { + if (push_data.empty()) { // set_response_code(response, 0, "push sparse data is empty"); return 0; } diff --git a/paddle/fluid/distributed/ps/service/brpc_utils.cc b/paddle/fluid/distributed/ps/service/brpc_utils.cc index f1493ece37b4b..715d1bbf954f0 100644 --- a/paddle/fluid/distributed/ps/service/brpc_utils.cc +++ b/paddle/fluid/distributed/ps/service/brpc_utils.cc @@ -95,7 +95,7 @@ void SerializeLodTensor(framework::Variable* var, auto* tensor = var->GetMutable(); var_msg->set_type(::paddle::distributed::LOD_TENSOR); const framework::LoD lod = tensor->lod(); - if (lod.size() > 0) { + if (!lod.empty()) { var_msg->set_lod_level(lod.size()); for (auto& each : lod) { VarMsg::LodData* lod_inner = var_msg->add_lod(); diff --git a/paddle/fluid/distributed/ps/service/communicator/communicator.cc b/paddle/fluid/distributed/ps/service/communicator/communicator.cc index b3cf5159c2610..66840845604fe 100644 --- a/paddle/fluid/distributed/ps/service/communicator/communicator.cc +++ b/paddle/fluid/distributed/ps/service/communicator/communicator.cc @@ -43,7 +43,7 @@ Communicator::Communicator() {} void Communicator::InitGFlag(const std::string &gflags) { VLOG(3) << "Init With Gflags:" << gflags; std::vector flags = paddle::string::split_string(gflags); - if (flags.size() < 1) { + if (flags.empty()) { flags.push_back("-max_body_size=314217728"); flags.push_back("-bthread_concurrency=40"); flags.push_back("-socket_max_unwritten_bytes=2048000000"); @@ -654,7 +654,7 @@ void AsyncCommunicator::PushSparseFromTensorAsync( bool batch_size_consist = true; for (auto *input : *inputs) { int cur_batch_size = - input->lod().size() ? input->lod()[0].size() - 1 : input->dims()[0]; + !input->lod().empty() ? input->lod()[0].size() - 1 : input->dims()[0]; if (batch_size == -1) { batch_size = cur_batch_size; } else if (batch_size != cur_batch_size) { @@ -666,10 +666,10 @@ void AsyncCommunicator::PushSparseFromTensorAsync( CHECK(batch_size > 0); // NOLINT int show_size = - shows->lod().size() ? shows->lod()[0].size() - 1 : shows->dims()[0]; + !shows->lod().empty() ? shows->lod()[0].size() - 1 : shows->dims()[0]; CHECK(show_size == batch_size || show_size == 1); int clk_size = - clks->lod().size() ? clks->lod()[0].size() - 1 : clks->dims()[0]; + !clks->lod().empty() ? clks->lod()[0].size() - 1 : clks->dims()[0]; CHECK(clk_size == batch_size || clk_size == 1); CHECK(outputs->size() == inputs->size()); @@ -705,7 +705,7 @@ void AsyncCommunicator::PushSparseFromTensorAsync( size_t len = tensor->numel(); output_len = 0; - if (tensor->lod().size() > 0) { + if (!tensor->lod().empty()) { for (size_t i = 0; i < tensor->lod()[0].size() - 1; ++i) { for (size_t j = tensor->lod()[0][i]; j < tensor->lod()[0][i + 1]; ++j, output_len += fea_dim) { @@ -1326,7 +1326,7 @@ void GeoCommunicator::SendSparse(const std::string &varname, platform::RecordEvent record_event("GeoCommunicator->SendSparse", platform::TracerEventType::Communication, 1); - if (sparse_ids.size() == 0) { + if (sparse_ids.empty()) { return; } std::string param_name = SplitedGradToParam(varname); diff --git a/paddle/fluid/distributed/ps/service/graph_brpc_client.cc b/paddle/fluid/distributed/ps/service/graph_brpc_client.cc index 7b0afc47a4483..fb2e6d7b3a22f 100644 --- a/paddle/fluid/distributed/ps/service/graph_brpc_client.cc +++ b/paddle/fluid/distributed/ps/service/graph_brpc_client.cc @@ -200,7 +200,7 @@ std::future GraphBrpcClient::add_graph_node( std::vector &is_weighted_list) { std::vector> request_bucket; std::vector> is_weighted_bucket; - bool add_weight = is_weighted_list.size() > 0; + bool add_weight = !is_weighted_list.empty(); std::vector server_index_arr; std::vector index_mapping(server_size, -1); for (size_t query_idx = 0; query_idx < node_id_list.size(); ++query_idx) { @@ -638,7 +638,7 @@ std::future GraphBrpcClient::set_node_feat( int request_idx = server2request[server_index]; node_id_buckets[request_idx].push_back(node_ids[query_idx]); query_idx_buckets[request_idx].push_back(query_idx); - if (features_idx_buckets[request_idx].size() == 0) { + if (features_idx_buckets[request_idx].empty()) { features_idx_buckets[request_idx].resize(feature_names.size()); } for (size_t feat_idx = 0; feat_idx < feature_names.size(); ++feat_idx) { diff --git a/paddle/fluid/distributed/ps/service/graph_brpc_server.cc b/paddle/fluid/distributed/ps/service/graph_brpc_server.cc index 0bd6a0a220d40..945e758daeeb7 100644 --- a/paddle/fluid/distributed/ps/service/graph_brpc_server.cc +++ b/paddle/fluid/distributed/ps/service/graph_brpc_server.cc @@ -548,7 +548,7 @@ int32_t GraphBrpcService::sample_neighbors_across_multi_servers( seq.push_back(request_idx); } size_t remote_call_num = request_call_num; - if (request2server.size() != 0 && + if (!request2server.empty() && static_cast(request2server.back()) == rank) { remote_call_num--; local_buffers.resize(node_id_buckets.back().size()); diff --git a/paddle/fluid/distributed/ps/service/ps_service/service.cc b/paddle/fluid/distributed/ps/service/ps_service/service.cc index 2fa98e65156b8..d62cdb4c133ed 100644 --- a/paddle/fluid/distributed/ps/service/ps_service/service.cc +++ b/paddle/fluid/distributed/ps/service/ps_service/service.cc @@ -51,7 +51,7 @@ paddle::distributed::PSParameter load_from_prototxt( void PSCore::InitGFlag(const std::string& gflags) { VLOG(3) << "Init With Gflags:" << gflags; std::vector flags = paddle::string::split_string(gflags); - if (flags.size() < 1) { + if (flags.empty()) { flags.push_back("-max_body_size=314217728"); flags.push_back("-socket_max_unwritten_bytes=2048000000"); flags.push_back("-max_connection_pool_size=1950"); diff --git a/paddle/fluid/distributed/ps/table/barrier_table.cc b/paddle/fluid/distributed/ps/table/barrier_table.cc index adb2a6847cab5..f665a024a78af 100644 --- a/paddle/fluid/distributed/ps/table/barrier_table.cc +++ b/paddle/fluid/distributed/ps/table/barrier_table.cc @@ -53,7 +53,7 @@ int32_t BarrierTable::Barrier(const uint32_t trainer_id, auto diff = to_string(diffs); VLOG(1) << "still need trainers: " << diff; - trainer_wait_.wait(lock, [&] { return trainer_ids_.size() == 0; }); + trainer_wait_.wait(lock, [&] { return trainer_ids_.empty(); }); } else { VLOG(1) << "barrier table optimize begin"; for (auto& x : *table_map_) { diff --git a/paddle/fluid/distributed/ps/table/common_graph_table.cc b/paddle/fluid/distributed/ps/table/common_graph_table.cc index 13b44d409fad7..8eba1f192715f 100644 --- a/paddle/fluid/distributed/ps/table/common_graph_table.cc +++ b/paddle/fluid/distributed/ps/table/common_graph_table.cc @@ -1105,7 +1105,7 @@ int32_t GraphTable::add_graph_node(int idx, } std::vector> tasks; for (size_t i = 0; i < batch.size(); ++i) { - if (!batch[i].size()) continue; + if (batch[i].empty()) continue; tasks.push_back( _shards_task_pool[i]->enqueue([&shards, &batch, i, this]() -> int { for (auto &p : batch[i]) { @@ -1130,7 +1130,7 @@ int32_t GraphTable::remove_graph_node(int idx, std::vector &id_list) { auto &shards = edge_shards[idx]; std::vector> tasks; for (size_t i = 0; i < batch.size(); ++i) { - if (!batch[i].size()) continue; + if (batch[i].empty()) continue; tasks.push_back( _shards_task_pool[i]->enqueue([&shards, &batch, i, this]() -> int { for (auto &p : batch[i]) { @@ -1254,7 +1254,7 @@ int32_t GraphTable::parse_type_to_typepath( std::unordered_map &res_type2path) { auto type2files_split = paddle::string::split_string(type2files, ","); - if (type2files_split.size() == 0) { + if (type2files_split.empty()) { return -1; } for (auto one_type2file : type2files_split) { @@ -1355,7 +1355,7 @@ int32_t GraphTable::parse_node_and_load(std::string ntype2files, npath_str = paddle::string::join_strings(npath_list, delim); } - if (ntypes.size() == 0) { + if (ntypes.empty()) { VLOG(0) << "node_type not specified, nothing will be loaded "; return 0; } @@ -1459,7 +1459,7 @@ int32_t GraphTable::load_node_and_edge_file( npath_str = paddle::string::join_strings(npath_list, delim); } - if (ntypes.size() == 0) { + if (ntypes.empty()) { VLOG(0) << "node_type not specified, nothing will be loaded "; return 0; } @@ -1659,7 +1659,7 @@ int32_t GraphTable::load_nodes(const std::string &path, std::string node_type) { uint64_t valid_count = 0; int idx = 0; if (FLAGS_graph_load_in_parallel) { - if (node_type == "") { + if (node_type.empty()) { VLOG(0) << "Begin GraphTable::load_nodes(), will load all node_type once"; } std::vector>> tasks; @@ -1676,7 +1676,7 @@ int32_t GraphTable::load_nodes(const std::string &path, std::string node_type) { } } else { VLOG(0) << "Begin GraphTable::load_nodes() node_type[" << node_type << "]"; - if (node_type == "") { + if (node_type.empty()) { VLOG(0) << "node_type not specified, loading edges to " << id_to_feature[0] << " part"; } else { @@ -1781,7 +1781,7 @@ int32_t GraphTable::load_edges(const std::string &path, if (search_level == 2) total_memory_cost = 0; #endif int idx = 0; - if (edge_type == "") { + if (edge_type.empty()) { VLOG(0) << "edge_type not specified, loading edges to " << id_to_edge[0] << " part"; } else { @@ -1999,7 +1999,7 @@ int32_t GraphTable::random_sample_neighbors( } for (size_t i = 0; i < seq_id.size(); i++) { - if (seq_id[i].size() == 0) continue; + if (seq_id[i].empty()) continue; tasks.push_back(_shards_task_pool[i]->enqueue([&, i, this]() -> int { uint64_t node_id; std::vector> r; @@ -2069,7 +2069,7 @@ int32_t GraphTable::random_sample_neighbors( } } } - if (sample_res.size()) { + if (!sample_res.empty()) { scaled_lru->insert( i, sample_keys.data(), sample_res.data(), sample_keys.size()); } diff --git a/paddle/fluid/distributed/ps/table/graph/graph_node.h b/paddle/fluid/distributed/ps/table/graph/graph_node.h index ee12644019b42..4650c5a6bd5b0 100644 --- a/paddle/fluid/distributed/ps/table/graph/graph_node.h +++ b/paddle/fluid/distributed/ps/table/graph/graph_node.h @@ -234,7 +234,8 @@ class FeatureNode : public Node { T v; size_t feat_str_size = feat_str_end - feat_str_begin; size_t Tsize = sizeof(T) * feat_str_size; - char buffer[Tsize] = {'\0'}; + char buffer[Tsize]; + memset(buffer, 0, Tsize * sizeof(char)); for (size_t i = 0; i < feat_str_size; i++) { std::stringstream ss(*(feat_str_begin + i)); ss >> v; diff --git a/paddle/fluid/distributed/ps/table/memory_sparse_table.cc b/paddle/fluid/distributed/ps/table/memory_sparse_table.cc index 975067d300ecb..7233f0b331dd7 100644 --- a/paddle/fluid/distributed/ps/table/memory_sparse_table.cc +++ b/paddle/fluid/distributed/ps/table/memory_sparse_table.cc @@ -119,7 +119,7 @@ int32_t MemorySparseTable::Load(const std::string &path, << " not equal to expect_shard_num:" << expect_shard_num; return -1; } - if (file_list.size() == 0) { + if (file_list.empty()) { LOG(WARNING) << "MemorySparseTable load file is empty, path:" << path; return -1; } diff --git a/paddle/fluid/distributed/ps/table/ssd_sparse_table.cc b/paddle/fluid/distributed/ps/table/ssd_sparse_table.cc index fbc6af49870d5..2f24f303f2eb0 100644 --- a/paddle/fluid/distributed/ps/table/ssd_sparse_table.cc +++ b/paddle/fluid/distributed/ps/table/ssd_sparse_table.cc @@ -263,7 +263,7 @@ int32_t SSDSparseTable::PullSparsePtr(int shard_id, pull_values[i] = reinterpret_cast(ret); } } - if (cur_ctx->batch_keys.size() != 0) { + if (!cur_ctx->batch_keys.empty()) { cur_ctx->batch_values.resize(cur_ctx->batch_keys.size()); cur_ctx->status.resize(cur_ctx->batch_keys.size()); auto fut = @@ -1541,7 +1541,7 @@ int32_t SSDSparseTable::Load(const std::string& path, << " not equal to expect_shard_num:" << expect_shard_num; return -1; } - if (file_list.size() == 0) { + if (file_list.empty()) { LOG(WARNING) << "SSDSparseTable load file is empty, path:" << path; return -1; } @@ -1692,7 +1692,7 @@ int32_t SSDSparseTable::LoadWithString( } } // last batch - if (ssd_keys.size() > 0) { + if (!ssd_keys.empty()) { _db->put_batch(local_shard_id, ssd_keys, ssd_values, ssd_keys.size()); } @@ -1928,7 +1928,7 @@ int32_t SSDSparseTable::LoadWithBinary(const std::string& path, int param) { for (int shard_idx = 0; shard_idx < _real_local_shard_num; shard_idx++) { auto sst_filelist = _afs_client.list(paddle::string::format_string( "%s_%d/part-*", FLAGS_rocksdb_path.c_str(), shard_idx)); - if (sst_filelist.size() > 0) { + if (!sst_filelist.empty()) { int ret = _db->ingest_externel_file(shard_idx, sst_filelist); if (ret) { VLOG(0) << "ingest file failed"; @@ -2032,7 +2032,7 @@ int32_t SSDSparseTable::CacheTable(uint16_t pass_id) { } // 必须做空判断,否则sst_writer.Finish会core掉 - if (datas.size() != 0) { + if (!datas.empty()) { rocksdb::SstFileWriter sst_writer(rocksdb::EnvOptions(), options); std::string filename = paddle::string::format_string("%s_%d/cache-%05d.sst", diff --git a/paddle/fluid/distributed/ps/wrapper/fleet.cc b/paddle/fluid/distributed/ps/wrapper/fleet.cc index 7086f4ce95be8..d25ad89d504fa 100644 --- a/paddle/fluid/distributed/ps/wrapper/fleet.cc +++ b/paddle/fluid/distributed/ps/wrapper/fleet.cc @@ -93,7 +93,7 @@ void FleetWrapper::InitServer( void FleetWrapper::InitGFlag(const std::string& gflags) { VLOG(3) << "Init With Gflags:" << gflags; std::vector flags = paddle::string::split_string(gflags); - if (flags.size() < 1) { + if (flags.empty()) { flags.push_back("-max_body_size=314217728"); flags.push_back("-bthread_concurrency=40"); flags.push_back("-socket_max_unwritten_bytes=2048000000"); @@ -558,7 +558,7 @@ void FleetWrapper::PushSparseFromTensorAsync( bool batch_size_consist = true; for (auto* input : *inputs) { size_t cur_batch_size = - input->lod().size() ? input->lod()[0].size() - 1 : input->dims()[0]; + !input->lod().empty() ? input->lod()[0].size() - 1 : input->dims()[0]; if (batch_size == -1) { batch_size = static_cast(cur_batch_size); } else if (batch_size != static_cast(cur_batch_size)) { @@ -570,10 +570,10 @@ void FleetWrapper::PushSparseFromTensorAsync( CHECK(batch_size > 0); // NOLINT size_t show_size = - shows->lod().size() ? shows->lod()[0].size() - 1 : shows->dims()[0]; + !shows->lod().empty() ? shows->lod()[0].size() - 1 : shows->dims()[0]; CHECK(show_size == size_t(batch_size) || show_size == 1); size_t clk_size = - clks->lod().size() ? clks->lod()[0].size() - 1 : clks->dims()[0]; + !clks->lod().empty() ? clks->lod()[0].size() - 1 : clks->dims()[0]; CHECK(clk_size == size_t(batch_size) || clk_size == 1); CHECK(outputs->size() == inputs->size()); @@ -613,7 +613,7 @@ void FleetWrapper::PushSparseFromTensorAsync( size_t len = tensor->numel(); output_len = 0; - if (tensor->lod().size() > 0) { + if (!tensor->lod().empty()) { for (size_t i = 0; i < tensor->lod()[0].size() - 1; ++i) { for (size_t j = tensor->lod()[0][i]; j < tensor->lod()[0][i + 1]; ++j, output_len += fea_dim) { diff --git a/paddle/fluid/eager/api/manual/eager_manual/nodes/add_n_node.cc b/paddle/fluid/eager/api/manual/eager_manual/nodes/add_n_node.cc index d63c9e0161f2b..424d71a4cec89 100644 --- a/paddle/fluid/eager/api/manual/eager_manual/nodes/add_n_node.cc +++ b/paddle/fluid/eager/api/manual/eager_manual/nodes/add_n_node.cc @@ -46,8 +46,8 @@ AddNGradNodeFinal::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(1); for (int i = 0; i < 1; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } std::vector api_output_0; diff --git a/paddle/fluid/eager/api/manual/eager_manual/nodes/conv2d_nodes.cc b/paddle/fluid/eager/api/manual/eager_manual/nodes/conv2d_nodes.cc index 0d9862b7b2f2d..a7d00f8df1802 100644 --- a/paddle/fluid/eager/api/manual/eager_manual/nodes/conv2d_nodes.cc +++ b/paddle/fluid/eager/api/manual/eager_manual/nodes/conv2d_nodes.cc @@ -57,8 +57,8 @@ Conv2dGradNodeFinal::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(2); for (int i = 0; i < 2; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = @@ -213,8 +213,8 @@ Conv2dDoubleGradNodeFinal::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(3); for (int i = 0; i < 3; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = diff --git a/paddle/fluid/eager/api/manual/eager_manual/nodes/multiply_node.cc b/paddle/fluid/eager/api/manual/eager_manual/nodes/multiply_node.cc index ea849f7e4846a..f7a90c43e7d93 100644 --- a/paddle/fluid/eager/api/manual/eager_manual/nodes/multiply_node.cc +++ b/paddle/fluid/eager/api/manual/eager_manual/nodes/multiply_node.cc @@ -59,8 +59,8 @@ MultiplyGradNode::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(2); for (int i = 0; i < 2; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = @@ -269,8 +269,8 @@ MultiplyDoubleGradNode::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(3); for (int i = 0; i < 3; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = @@ -485,8 +485,8 @@ MultiplyGradNode::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(2); for (int i = 0; i < 2; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = diff --git a/paddle/fluid/eager/api/manual/eager_manual/nodes/sync_batch_norm_node.cc b/paddle/fluid/eager/api/manual/eager_manual/nodes/sync_batch_norm_node.cc index 4242f74c81c08..f10d724eaa210 100644 --- a/paddle/fluid/eager/api/manual/eager_manual/nodes/sync_batch_norm_node.cc +++ b/paddle/fluid/eager/api/manual/eager_manual/nodes/sync_batch_norm_node.cc @@ -70,8 +70,8 @@ SyncBatchNormGradNode::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(5); for (int i = 0; i < 5; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = @@ -289,8 +289,8 @@ SyncBatchNormGradNode::operator()( paddle::small_vector, egr::kSlotSmallVectorSize> returns(5); for (int i = 0; i < 5; ++i) { - out_metas[i].size() == 0 ? returns[i].resize(1) - : returns[i].resize(out_metas[i].size()); + out_metas[i].empty() ? returns[i].resize(1) + : returns[i].resize(out_metas[i].size()); } auto* api_output_0 = diff --git a/paddle/fluid/eager/auto_code_generator/eager_generator.cc b/paddle/fluid/eager/auto_code_generator/eager_generator.cc index e4159500dca95..70c2c141ccb68 100644 --- a/paddle/fluid/eager/auto_code_generator/eager_generator.cc +++ b/paddle/fluid/eager/auto_code_generator/eager_generator.cc @@ -1545,23 +1545,22 @@ static std::pair GenerateForwardFunctionContents( op_type); } } - if (ins_contents_str.size() > 0) + if (!ins_contents_str.empty()) ins_contents_str.pop_back(); // // Remove trailing "," - if (amp_tensors_vector_str.size() > 0) amp_tensors_vector_str.pop_back(); + if (!amp_tensors_vector_str.empty()) amp_tensors_vector_str.pop_back(); for (const std::string& arg : input_args_str_list) { dygraph_function_args_str += arg; dygraph_function_args_str += ","; } - if (dygraph_function_args_str.size() > 0) - dygraph_function_args_str.pop_back(); + if (!dygraph_function_args_str.empty()) dygraph_function_args_str.pop_back(); for (const std::string& arg : amp_function_call_args_str_list) { amp_function_call_args_str += arg; amp_function_call_args_str += ","; } - if (amp_function_call_args_str.size() > 0) + if (!amp_function_call_args_str.empty()) amp_function_call_args_str.pop_back(); // Handle Dispensable Inputs @@ -1725,9 +1724,9 @@ static std::pair GenerateForwardFunctionContents( } } } - if (outs_contents_str.size() > 0) + if (!outs_contents_str.empty()) outs_contents_str.pop_back(); // Remove trailing "," - if (inplace_mapping_str.size() > 0) + if (!inplace_mapping_str.empty()) inplace_mapping_str.pop_back(); // Remove trailing "," if ((op_type != "cast") && (forward_inplace_map.empty())) { @@ -1740,7 +1739,7 @@ static std::pair GenerateForwardFunctionContents( "%s\n" " }\n"; std::string amp_logic_str = ""; - if (in_vars.size() != 0) { + if (!in_vars.empty()) { const char* AMP_TENSORS_VECTOR_TEMPLATE = " paddle::small_vector, " "egr::kSlotSmallVectorSize> " @@ -1770,7 +1769,7 @@ static std::pair GenerateForwardFunctionContents( " return %s_dygraph_function(%s);\n" " }"; amp_function_call_args_str += ", attr_map "; - if (amp_function_call_args_str.size() > 0) { + if (!amp_function_call_args_str.empty()) { auto iter = amp_function_call_args_str.begin(); if ((*iter) == ',') amp_function_call_args_str.erase(iter); } @@ -2078,7 +2077,7 @@ static std::pair GenerateForwardFunctionContents( function_name = op_type + "__dygraph_function"; } - if (dygraph_function_args_str.size() > 0) { + if (!dygraph_function_args_str.empty()) { auto iter = dygraph_function_args_str.begin(); if ((*iter) == ',') dygraph_function_args_str.erase(iter); } @@ -2284,7 +2283,7 @@ static std::string GenerateSingleOpBase( grad_input_name)); } } - if (ins_contents_str.size() > 0) + if (!ins_contents_str.empty()) ins_contents_str.pop_back(); // // Remove trailing "," const char* BWD_INS_MAP_TEMPLATE = @@ -3070,14 +3069,14 @@ static std::string ConvertCoreOpsInfosToString( } // Remove trailing ',' - if (returns_str.size() > 0) returns_str.pop_back(); + if (!returns_str.empty()) returns_str.pop_back(); std::string op_type_init_str = paddle::string::Sprintf( Core_Ops_Returns_TEMPLATE, op_type, returns_str); core_ops_legacy_returns_info_init_str += op_type_init_str; } // Remove trailing ',' - if (core_ops_legacy_returns_info_init_str.size() > 0) + if (!core_ops_legacy_returns_info_init_str.empty()) core_ops_legacy_returns_info_init_str.pop_back(); return core_ops_legacy_returns_info_init_str; diff --git a/paddle/fluid/eager/backward.cc b/paddle/fluid/eager/backward.cc index dd310757956c0..c8bc59b577ce7 100644 --- a/paddle/fluid/eager/backward.cc +++ b/paddle/fluid/eager/backward.cc @@ -191,7 +191,7 @@ std::vector RunBackward( // copy grad tensor since we should totally run grad without affect forward // value - if (grad_tensors.size() > 0 && grad_tensors[i].initialized()) { + if (!grad_tensors.empty() && grad_tensors[i].initialized()) { PADDLE_ENFORCE( grad_tensors.size() == tensors.size(), paddle::platform::errors::Fatal( diff --git a/paddle/fluid/eager/grad_node_info.cc b/paddle/fluid/eager/grad_node_info.cc index 875ae1407bf09..1fe6aba3c7bb3 100644 --- a/paddle/fluid/eager/grad_node_info.cc +++ b/paddle/fluid/eager/grad_node_info.cc @@ -93,7 +93,7 @@ void GradNodeBase::SetGradInMeta(const paddle::Tensor& fwd_out, "bwd_in_meta_ is designed to hold as same num as backward " "inputs.")); auto& metas = bwd_in_meta_.at(slot_rank); - if (metas.size() == 0) { + if (metas.empty()) { metas.resize(1); } @@ -218,7 +218,7 @@ void GradNodeBase::SetGradOutMeta(const paddle::Tensor& fwd_in, "backward outputs.")); auto& metas = bwd_out_meta_.at(slot_rank); // Init stop gradient vector before use to avoid push back - if (metas.size() == 0) { + if (metas.empty()) { metas.resize(1); } auto& meta = metas[0]; @@ -281,7 +281,7 @@ void GradNodeBase::SetGradOutMeta(const paddle::Tensor& fwd_in, "backward outputs.")); auto& metas = bwd_out_meta_.at(slot_rank); // Init stop gradient vector before use to avoid push back - if (metas.size() == 0) { + if (metas.empty()) { metas.resize(1); } auto& meta = metas[0]; diff --git a/paddle/fluid/eager/nan_inf_utils.cc b/paddle/fluid/eager/nan_inf_utils.cc index a66bc211d513c..29922e37beb43 100644 --- a/paddle/fluid/eager/nan_inf_utils.cc +++ b/paddle/fluid/eager/nan_inf_utils.cc @@ -37,7 +37,7 @@ static std::unordered_set& nan_inf_skip_op_list() { void SetCheckOpList(const std::string& check_op_list = "") { nan_inf_check_op_list(); - if (check_op_list.size() != 0) { + if (!check_op_list.empty()) { std::stringstream ss(check_op_list); std::string op_type; LOG(INFO) << "Please set op's name according to the " @@ -51,7 +51,7 @@ void SetCheckOpList(const std::string& check_op_list = "") { void SetSkipOpList(const std::string& skip_op_list = "") { nan_inf_skip_op_list(); - if (skip_op_list.size() != 0) { + if (!skip_op_list.empty()) { std::stringstream ss(skip_op_list); std::string op_type; LOG(INFO) << "Please set op's name according to the " @@ -70,7 +70,7 @@ bool CheckOp(const std::string& api_name) { return false; } - if (nan_inf_check_op_list().size() != 0 && + if (!nan_inf_check_op_list().empty() && (!nan_inf_check_op_list().count(api_name))) { VLOG(4) << "Current op isn't in checked_op_list : " << api_name; return false; diff --git a/paddle/fluid/framework/data_feed.cc b/paddle/fluid/framework/data_feed.cc index 32c4845bd0d57..b102f3714eeab 100644 --- a/paddle/fluid/framework/data_feed.cc +++ b/paddle/fluid/framework/data_feed.cc @@ -375,7 +375,7 @@ bool InMemoryDataFeed::Start() { output_channel_->Write(std::move(data)); } #endif - if (batch_offsets_.size() > 0) { + if (!batch_offsets_.empty()) { VLOG(3) << "batch_size offsets: " << batch_offsets_.size(); enable_heterps_ = true; this->offset_index_ = 0; @@ -1536,13 +1536,13 @@ void PrivateInstantDataFeed::PutToFeedVec() { if (type[0] == 'f') { // float const auto& feasign = ins_vec_[i].GetFloatData(); - float* tensor_ptr = - feed_vec_[i]->mutable_data({total_instance, 1}, this->place_); + float* tensor_ptr = feed_vec_[i]->template mutable_data( + {total_instance, 1}, this->place_); CopyToFeedTensor(tensor_ptr, &feasign[0], total_instance * sizeof(float)); } else if (type[0] == 'u') { // uint64 // no uint64_t type in paddlepaddle const auto& feasign = ins_vec_[i].GetUint64Data(); - int64_t* tensor_ptr = feed_vec_[i]->mutable_data( + int64_t* tensor_ptr = feed_vec_[i]->template mutable_data( {total_instance, 1}, this->place_); CopyToFeedTensor( tensor_ptr, &feasign[0], total_instance * sizeof(int64_t)); @@ -2690,7 +2690,7 @@ bool SlotRecordInMemoryDataFeed::Start() { input_channel_->Read(data); } #endif - if (batch_offsets_.size() > 0) { + if (!batch_offsets_.empty()) { VLOG(3) << "batch_size offsets: " << batch_offsets_.size(); enable_heterps_ = true; this->offset_index_ = 0; diff --git a/paddle/fluid/framework/data_set.cc b/paddle/fluid/framework/data_set.cc index 3dc440b1d1c69..3d53f979ac553 100644 --- a/paddle/fluid/framework/data_set.cc +++ b/paddle/fluid/framework/data_set.cc @@ -227,13 +227,13 @@ void DatasetImpl::CreateChannel() { if (input_channel_ == nullptr) { input_channel_ = paddle::framework::MakeChannel(); } - if (multi_output_channel_.size() == 0) { + if (multi_output_channel_.empty()) { multi_output_channel_.reserve(channel_num_); for (int i = 0; i < channel_num_; ++i) { multi_output_channel_.push_back(paddle::framework::MakeChannel()); } } - if (multi_consume_channel_.size() == 0) { + if (multi_consume_channel_.empty()) { multi_consume_channel_.reserve(channel_num_); for (int i = 0; i < channel_num_; ++i) { multi_consume_channel_.push_back(paddle::framework::MakeChannel()); @@ -242,13 +242,13 @@ void DatasetImpl::CreateChannel() { if (input_pv_channel_ == nullptr) { input_pv_channel_ = paddle::framework::MakeChannel(); } - if (multi_pv_output_.size() == 0) { + if (multi_pv_output_.empty()) { multi_pv_output_.reserve(channel_num_); for (int i = 0; i < channel_num_; ++i) { multi_pv_output_.push_back(paddle::framework::MakeChannel()); } } - if (multi_pv_consume_.size() == 0) { + if (multi_pv_consume_.empty()) { multi_pv_consume_.reserve(channel_num_); for (int i = 0; i < channel_num_; ++i) { multi_pv_consume_.push_back(paddle::framework::MakeChannel()); @@ -413,7 +413,7 @@ static int compute_thread_batch_nccl( void MultiSlotDataset::PrepareTrain() { #ifdef PADDLE_WITH_GLOO if (enable_heterps_) { - if (input_records_.size() == 0 && input_channel_ != nullptr && + if (input_records_.empty() && input_channel_ != nullptr && input_channel_->Size() != 0) { input_channel_->ReadAll(input_records_); VLOG(3) << "read from channel to records with records size: " @@ -1009,7 +1009,7 @@ void DatasetImpl::CreateReaders() { CHECK(channel_num_ > 0) << "channel num should > 0"; CHECK(channel_num_ <= thread_num_) << "channel num should <= thread num"; VLOG(3) << "readers size: " << readers_.size(); - if (readers_.size() != 0) { + if (!readers_.empty()) { VLOG(3) << "readers_.size() = " << readers_.size() << ", will not create again"; return; @@ -1646,7 +1646,7 @@ void MultiSlotDataset::PreprocessChannel( << " output channel size: " << out_channel_size; if ((!input_channel_ || input_channel_->Size() == 0) && - slots_shuffle_original_data_.size() == 0 && out_channel_size == 0) { + slots_shuffle_original_data_.empty() && out_channel_size == 0) { VLOG(3) << "DatasetImpl::SlotsShuffle() end, no data to slots shuffle"; return; } @@ -1658,7 +1658,7 @@ void MultiSlotDataset::PreprocessChannel( index_slots.insert(i); } } - if (slots_shuffle_original_data_.size() == 0) { + if (slots_shuffle_original_data_.empty()) { // before first slots shuffle, instances could be in // input_channel, oupput_channel or consume_channel if (input_channel_ && input_channel_->Size() != 0) { @@ -1782,7 +1782,7 @@ void SlotRecordDataset::CreateReaders() { CHECK(channel_num_ > 0) << "channel num should > 0"; CHECK(channel_num_ <= thread_num_) << "channel num should <= thread num"; VLOG(3) << "readers size: " << readers_.size(); - if (readers_.size() != 0) { + if (!readers_.empty()) { VLOG(3) << "readers_.size() = " << readers_.size() << ", will not create again"; return; @@ -1870,7 +1870,7 @@ void SlotRecordDataset::DynamicAdjustChannelNum(int channel_num, void SlotRecordDataset::PrepareTrain() { #ifdef PADDLE_WITH_GLOO if (enable_heterps_) { - if (input_records_.size() == 0 && input_channel_ != nullptr && + if (input_records_.empty() && input_channel_ != nullptr && input_channel_->Size() != 0) { input_channel_->ReadAll(input_records_); VLOG(3) << "read from channel to records with records size: " diff --git a/paddle/fluid/framework/details/async_ssa_graph_executor.cc b/paddle/fluid/framework/details/async_ssa_graph_executor.cc index e17ea867bf71d..855db2e8a8e52 100644 --- a/paddle/fluid/framework/details/async_ssa_graph_executor.cc +++ b/paddle/fluid/framework/details/async_ssa_graph_executor.cc @@ -148,7 +148,7 @@ FetchResultType AsyncSSAGraphExecutor::Run( "AsyncSSAGraphExecutor does not support unmerged " "results to be fetched!")); // init once - if (run_futures_.size() == 0 && places_.size() > 1) { + if (run_futures_.empty() && places_.size() > 1) { #if defined PADDLE_WITH_PSCORE if (strategy_.thread_barrier_) { paddle::distributed::Communicator::GetInstance()->BarrierTriggerReset( diff --git a/paddle/fluid/framework/details/build_strategy.cc b/paddle/fluid/framework/details/build_strategy.cc index 69f7a49ce55fd..070fb7bafbcd2 100644 --- a/paddle/fluid/framework/details/build_strategy.cc +++ b/paddle/fluid/framework/details/build_strategy.cc @@ -232,7 +232,7 @@ class ParallelExecutorPassBuilder : public ir::PassBuilder { "but received strategy_.trainer_id_ = %d.", strategy_.trainer_id_)); - if (strategy_.trainer_id_ > 0 && strategy_.trainers_endpoints_.size() > 0) { + if (strategy_.trainer_id_ > 0 && !strategy_.trainers_endpoints_.empty()) { PADDLE_ENFORCE_LT( static_cast(strategy_.trainer_id_), strategy_.trainers_endpoints_.size(), diff --git a/paddle/fluid/framework/details/op_handle_base.cc b/paddle/fluid/framework/details/op_handle_base.cc index 82f09f51c23e1..6a5f0a38204e5 100644 --- a/paddle/fluid/framework/details/op_handle_base.cc +++ b/paddle/fluid/framework/details/op_handle_base.cc @@ -57,7 +57,7 @@ void OpHandleBase::InitCUDA() { cudaEventCreateWithFlags(&events_[dev_id], cudaEventDisableTiming)); #endif } - if (IsMultiDeviceTransfer() && dev_ctxes_.size() > 0) { + if (IsMultiDeviceTransfer() && !dev_ctxes_.empty()) { for (auto &out_var : outputs_) { auto *out_var_handle = dynamic_cast(out_var); if (out_var_handle) { @@ -137,7 +137,7 @@ void OpHandleBase::InitXPU() { void OpHandleBase::Run(DeviceType use_device) { #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) - if (events_.empty() && use_device == p::kCUDA && dev_ctxes_.size() > 0) { + if (events_.empty() && use_device == p::kCUDA && !dev_ctxes_.empty()) { InitCUDA(); } #else @@ -149,7 +149,7 @@ void OpHandleBase::Run(DeviceType use_device) { "compiled with CUDA.")); #endif - if (use_device == p::kXPU && dev_ctxes_.size() > 0) { + if (use_device == p::kXPU && !dev_ctxes_.empty()) { #ifdef PADDLE_WITH_XPU InitXPU(); #else diff --git a/paddle/fluid/framework/details/parallel_ssa_graph_executor.cc b/paddle/fluid/framework/details/parallel_ssa_graph_executor.cc index a2dd00c008e87..10d6bc873b2cc 100644 --- a/paddle/fluid/framework/details/parallel_ssa_graph_executor.cc +++ b/paddle/fluid/framework/details/parallel_ssa_graph_executor.cc @@ -288,7 +288,7 @@ FetchResultType ParallelSSAGraphExecutor::Run( &(PADDLE_GET_CONST(LoDTensorArray, fetch_list[fetch_idx]))); } } - if (lodtensor_ptrs.size() != 0) { + if (!lodtensor_ptrs.empty()) { phi::DenseTensor var; MergeLoDTensor(&var, lodtensor_ptrs, platform::CPUPlace()); ret.emplace_back(var); diff --git a/paddle/fluid/framework/details/scope_buffered_monitor.cc b/paddle/fluid/framework/details/scope_buffered_monitor.cc index a84fb8eec9eb6..ebe020a19e2ba 100644 --- a/paddle/fluid/framework/details/scope_buffered_monitor.cc +++ b/paddle/fluid/framework/details/scope_buffered_monitor.cc @@ -133,7 +133,7 @@ void ScopeBufferedMonitor::Apply(const std::function &callback, } if (VLOG_IS_ON(10)) { - if (incr_local_exec_scopes.at(scope_id).size() && + if (!incr_local_exec_scopes.at(scope_id).empty() && FLAGS_local_exe_sub_scope_limit > 0) { VLOG(10) << "FLAGS_local_exe_sub_scope_limit is " diff --git a/paddle/fluid/framework/details/scope_buffered_ssa_graph_executor.cc b/paddle/fluid/framework/details/scope_buffered_ssa_graph_executor.cc index 8e1a9670209f7..aa8b1718bbfeb 100644 --- a/paddle/fluid/framework/details/scope_buffered_ssa_graph_executor.cc +++ b/paddle/fluid/framework/details/scope_buffered_ssa_graph_executor.cc @@ -98,7 +98,7 @@ FetchResultType ScopeBufferedSSAGraphExecutor::Run( if (strategy_.num_iteration_per_drop_scope_ == 1) { exe_run_func(); } else { - scope_monitor_.Apply(exe_run_func, fetch_tensors.size() > 0); + scope_monitor_.Apply(exe_run_func, !fetch_tensors.empty()); } if (VLOG_IS_ON(5)) { diff --git a/paddle/fluid/framework/device_worker.cc b/paddle/fluid/framework/device_worker.cc index 0fccdf265d279..055f3940334fb 100644 --- a/paddle/fluid/framework/device_worker.cc +++ b/paddle/fluid/framework/device_worker.cc @@ -208,7 +208,7 @@ void PrintLodTensor(phi::DenseTensor* tensor, std::pair GetTensorBound(phi::DenseTensor* tensor, int index) { auto& dims = tensor->dims(); - if (tensor->lod().size() != 0) { + if (!tensor->lod().empty()) { auto& lod = tensor->lod()[0]; return {lod[index] * dims[1], lod[index + 1] * dims[1]}; } else { @@ -219,7 +219,7 @@ std::pair GetTensorBound(phi::DenseTensor* tensor, bool CheckValidOutput(phi::DenseTensor* tensor, size_t batch_size) { auto& dims = tensor->dims(); if (dims.size() != 2) return false; - if (tensor->lod().size() != 0) { + if (!tensor->lod().empty()) { auto& lod = tensor->lod()[0]; if (lod.size() != batch_size + 1) { return false; @@ -308,12 +308,12 @@ void DeviceWorker::DumpField(const Scope& scope, } } if (!has_valid_batch) return; - } else if (ins_id_vec.size() > 0) { + } else if (!ins_id_vec.empty()) { batch_size = ins_id_vec.size(); } std::vector ars(batch_size); if (dump_mode_ == 3) { - if (dump_fields_ == NULL || (*dump_fields_).size() == 0) { + if (dump_fields_ == NULL || (*dump_fields_).empty()) { return; } auto set_output_str = [&, this](size_t begin, @@ -325,7 +325,7 @@ void DeviceWorker::DumpField(const Scope& scope, bound = {i * dims[1], (i + 1) * dims[1]}; // auto bound = GetTensorBound(tensor, i); - if (ars[i].size() > 0) ars[i] += "\t"; + if (!ars[i].empty()) ars[i] += "\t"; // ars[i] += '['; PrintLodTensor(tensor, bound.first, bound.second, ars[i], ' ', false); // ars[i] += ']'; @@ -388,10 +388,10 @@ void DeviceWorker::DumpField(const Scope& scope, size_t end = begin + average_size + (i < batch_size % acutal_thread_num ? 1 : 0); for (size_t j = begin + 1; j < end; j++) { - if (ars[begin].size() > 0 && ars[j].size() > 0) ars[begin] += "\n"; + if (!ars[begin].empty() && !ars[j].empty()) ars[begin] += "\n"; ars[begin] += ars[j]; } - if (ars[begin].size() > 0) writer_ << ars[begin]; + if (!ars[begin].empty()) writer_ << ars[begin]; } return; } diff --git a/paddle/fluid/framework/downpour_lite_worker.cc b/paddle/fluid/framework/downpour_lite_worker.cc index 4c60d6b5b95a3..b22328e4b5b22 100644 --- a/paddle/fluid/framework/downpour_lite_worker.cc +++ b/paddle/fluid/framework/downpour_lite_worker.cc @@ -137,7 +137,7 @@ void DownpourLiteWorker::CopySparseTable() { } else if (!copy_table_config_.sparse_copy_by_feasign()) { if (feasign_set_.find(src_table) == feasign_set_.end()) { continue; - } else if (feasign_set_[src_table].size() == 0) { + } else if (feasign_set_[src_table].empty()) { continue; } feanum = fleet_ptr_->CopyTable(src_table, dest_table); @@ -474,7 +474,7 @@ void DownpourLiteWorker::TrainFiles() { size_t batch_size = device_reader_->GetCurBatchSize(); std::string s = ""; for (auto& ins_id : ins_id_vec) { - if (s != "") s += ","; + if (!s.empty()) s += ","; s += ins_id; } fprintf(stderr, diff --git a/paddle/fluid/framework/downpour_worker.cc b/paddle/fluid/framework/downpour_worker.cc index 01f6abb59dba4..86a1343157844 100644 --- a/paddle/fluid/framework/downpour_worker.cc +++ b/paddle/fluid/framework/downpour_worker.cc @@ -362,7 +362,7 @@ void DownpourWorker::CopySparseTable() { } else if (!copy_table_config_.sparse_copy_by_feasign()) { if (feasign_set_.find(src_table) == feasign_set_.end()) { continue; - } else if (feasign_set_[src_table].size() == 0) { + } else if (feasign_set_[src_table].empty()) { continue; } feanum = fleet_ptr_->CopyTable(src_table, dest_table); diff --git a/paddle/fluid/framework/heter_pipeline_trainer.cc b/paddle/fluid/framework/heter_pipeline_trainer.cc index c5d5dd219a94d..b62caec249694 100644 --- a/paddle/fluid/framework/heter_pipeline_trainer.cc +++ b/paddle/fluid/framework/heter_pipeline_trainer.cc @@ -307,7 +307,7 @@ void HeterPipelineTrainer::Run() { for (auto& th : threads_) { th.join(); } - if (threads_.size() > 0) { + if (!threads_.empty()) { threads_.clear(); } VLOG(3) << "Epoch Training done"; diff --git a/paddle/fluid/framework/heter_section_worker.cc b/paddle/fluid/framework/heter_section_worker.cc index 6321fe9c5388f..510d397bbb74c 100644 --- a/paddle/fluid/framework/heter_section_worker.cc +++ b/paddle/fluid/framework/heter_section_worker.cc @@ -391,7 +391,7 @@ void HeterSectionWorker::Run() { micro_ids_.push_back(i); } // backward - if (micro_ids_.size() > 0) { + if (!micro_ids_.empty()) { MiniBatchBarrier(); } VLOG(0) << "one batch run over! micro_ids_size: " << micro_ids_.size(); diff --git a/paddle/fluid/framework/io/fs.cc b/paddle/fluid/framework/io/fs.cc index aa909136f40dc..3bc36a81482ea 100644 --- a/paddle/fluid/framework/io/fs.cc +++ b/paddle/fluid/framework/io/fs.cc @@ -27,7 +27,7 @@ namespace framework { static void fs_add_read_converter_internal(std::string& path, // NOLINT bool& is_pipe, // NOLINT const std::string& converter) { - if (converter == "") { + if (converter.empty()) { return; } @@ -43,7 +43,7 @@ static void fs_add_read_converter_internal(std::string& path, // NOLINT static void fs_add_write_converter_internal(std::string& path, // NOLINT bool& is_pipe, // NOLINT const std::string& converter) { - if (converter == "") { + if (converter.empty()) { return; } @@ -157,7 +157,7 @@ int64_t localfs_file_size(const std::string& path) { } void localfs_remove(const std::string& path) { - if (path == "") { + if (path.empty()) { return; } @@ -165,7 +165,7 @@ void localfs_remove(const std::string& path) { } std::vector localfs_list(const std::string& path) { - if (path == "") { + if (path.empty()) { return {}; } @@ -186,7 +186,7 @@ std::vector localfs_list(const std::string& path) { } std::string localfs_tail(const std::string& path) { - if (path == "") { + if (path.empty()) { return ""; } @@ -213,7 +213,7 @@ bool localfs_exists(const std::string& path) { } void localfs_mkdir(const std::string& path) { - if (path == "") { + if (path.empty()) { return; } @@ -221,7 +221,7 @@ void localfs_mkdir(const std::string& path) { } void localfs_mv(const std::string& src, const std::string& dest) { - if (src == "" || dest == "") { + if (src.empty() || dest.empty()) { return; } shell_execute(string::format_string("mv %s %s", src.c_str(), dest.c_str())); @@ -274,7 +274,7 @@ std::shared_ptr hdfs_open_read(std::string path, int* err_no, const std::string& converter, bool read_data) { - if (download_cmd() != "") { // use customized download command + if (!download_cmd().empty()) { // use customized download command path = string::format_string( "%s \"%s\"", download_cmd().c_str(), path.c_str()); } else { @@ -318,7 +318,7 @@ std::shared_ptr hdfs_open_write(std::string path, } void hdfs_remove(const std::string& path) { - if (path == "") { + if (path.empty()) { return; } @@ -327,7 +327,7 @@ void hdfs_remove(const std::string& path) { } std::vector hdfs_list(const std::string& path) { - if (path == "") { + if (path.empty()) { return {}; } @@ -362,7 +362,7 @@ std::vector hdfs_list(const std::string& path) { } std::string hdfs_tail(const std::string& path) { - if (path == "") { + if (path.empty()) { return ""; } @@ -382,7 +382,7 @@ bool hdfs_exists(const std::string& path) { } void hdfs_mkdir(const std::string& path) { - if (path == "") { + if (path.empty()) { return; } @@ -391,7 +391,7 @@ void hdfs_mkdir(const std::string& path) { } void hdfs_mv(const std::string& src, const std::string& dest) { - if (src == "" || dest == "") { + if (src.empty() || dest.empty()) { return; } shell_execute(string::format_string( diff --git a/paddle/fluid/framework/ir/add_support_int8_pass.cc b/paddle/fluid/framework/ir/add_support_int8_pass.cc index d38853bb96489..21b45d1b1fa38 100644 --- a/paddle/fluid/framework/ir/add_support_int8_pass.cc +++ b/paddle/fluid/framework/ir/add_support_int8_pass.cc @@ -42,7 +42,7 @@ void AddSupportInt8Pass::ApplyImpl(ir::Graph* graph) const { // OP'Attr hasn't std::vector>. To do: Support multi-tensor // scale for one input for (size_t i = 0; i < quanted_op_desc->InputNames().size(); i++) { - if (quanted_op_desc->Input(quanted_op_desc->InputNames()[i]).size() > 0 && + if (!quanted_op_desc->Input(quanted_op_desc->InputNames()[i]).empty() && quanted_op_desc->HasAttr( "Input_scale_" + quanted_op_desc->Input(quanted_op_desc->InputNames()[i])[0])) { @@ -66,8 +66,8 @@ void AddSupportInt8Pass::ApplyImpl(ir::Graph* graph) const { if (out_op_node->Op()->HasAttr("Input_scale_" + input_name)) { for (size_t i = 0; i < quanted_op_desc->OutputNames().size(); i++) { - if (quanted_op_desc->Output(quanted_op_desc->OutputNames()[i]) - .size() > 0 && + if (!quanted_op_desc->Output(quanted_op_desc->OutputNames()[i]) + .empty() && input_name == quanted_op_desc->Output( quanted_op_desc->OutputNames()[i])[0]) { outscale_flag = true; diff --git a/paddle/fluid/framework/ir/coalesce_grad_tensor_pass.cc b/paddle/fluid/framework/ir/coalesce_grad_tensor_pass.cc index cede39503b367..4aabf3453423a 100644 --- a/paddle/fluid/framework/ir/coalesce_grad_tensor_pass.cc +++ b/paddle/fluid/framework/ir/coalesce_grad_tensor_pass.cc @@ -87,7 +87,7 @@ class CoalesceGradTensorPass : public ir::Pass { details::kGroupParamsAndDenseGrads, &result); VLOG(10) << "The number of params and grads is:" << params_grads.size(); - if (params_grads.size() == 0) { + if (params_grads.empty()) { return; } @@ -107,7 +107,7 @@ class CoalesceGradTensorPass : public ir::Pass { VLOG(10) << "Dense grads: " << p_g_dense_grad.size() << ", Sparse grads: " << p_g_sparse_grad.size(); - if (p_g_dense_grad.size() == 0) { + if (p_g_dense_grad.empty()) { return; } diff --git a/paddle/fluid/framework/ir/constant_folding_pass.cc b/paddle/fluid/framework/ir/constant_folding_pass.cc index 468d74478c8bf..b365e11397429 100644 --- a/paddle/fluid/framework/ir/constant_folding_pass.cc +++ b/paddle/fluid/framework/ir/constant_folding_pass.cc @@ -128,13 +128,13 @@ void ConstantFoldingPass::ApplyImpl(ir::Graph *graph) const { local_scope->FindVar(out_node->Var()->Name()) ->GetMutable(); // useless out_node can be removed, not need set it persistable ! - if (out_node->outputs.size() == 0L) remove_nodes.emplace(out_node); + if (out_node->outputs.empty()) remove_nodes.emplace(out_node); } op->Run(*local_scope, platform::CPUPlace()); folded_op_num++; for (auto out_node : op_node->outputs) { // this out_node is useless, do not set it persistable - if (out_node->outputs.size() == 0L) continue; + if (out_node->outputs.empty()) continue; auto out_desc = out_node->Var(); auto out_name = out_desc->Name(); auto *local_out_tensor = diff --git a/paddle/fluid/framework/ir/conv_bn_fuse_pass.cc b/paddle/fluid/framework/ir/conv_bn_fuse_pass.cc index 0392a8cfba0be..de1374073c389 100644 --- a/paddle/fluid/framework/ir/conv_bn_fuse_pass.cc +++ b/paddle/fluid/framework/ir/conv_bn_fuse_pass.cc @@ -367,7 +367,7 @@ void ConvBNFusePass::ApplyImpl(ir::Graph* graph) const { auto input_names = conv->Op()->InputNames(); bool has_bias = std::find(input_names.begin(), input_names.end(), "Bias") != input_names.end() && - conv->Op()->Input("Bias").size() > 0; + !conv->Op()->Input("Bias").empty(); bool mkldnn_with_bias = is_mkldnn && has_bias; // Create eltwise_y (conv bias) variable diff --git a/paddle/fluid/framework/ir/fc_elementwise_layernorm_fuse_pass.cc b/paddle/fluid/framework/ir/fc_elementwise_layernorm_fuse_pass.cc index 417d79972806f..cd8312214af8d 100644 --- a/paddle/fluid/framework/ir/fc_elementwise_layernorm_fuse_pass.cc +++ b/paddle/fluid/framework/ir/fc_elementwise_layernorm_fuse_pass.cc @@ -126,7 +126,7 @@ PDNode *FCElementwiseLayerNorm::operator()(PDNode *x) { template static bool IsEqual(const std::vector &x, const std::vector &y) { - if (!(x.size() > 0U && y.size() > 0U) || x.size() != y.size()) { + if (!(!x.empty() && !y.empty()) || x.size() != y.size()) { return false; } for (size_t i = 0; i < x.size(); ++i) { @@ -283,13 +283,13 @@ void FCElementwiseLayerNormFusePass::ApplyImpl(ir::Graph *graph) const { // outputs new_desc.SetOutput("Out", {layer_norm_out->Name()}); - bool lnm_has_output = layer_norm_mean->outputs.size() > 0U; + bool lnm_has_output = !layer_norm_mean->outputs.empty(); if (lnm_has_output) { new_desc.SetOutput("Mean", {layer_norm_mean->Name()}); } else { del_node_set.insert(layer_norm_mean); } - bool lnv_has_output = layer_norm_variance->outputs.size() > 0U; + bool lnv_has_output = !layer_norm_variance->outputs.empty(); if (lnv_has_output) { new_desc.SetOutput("Variance", {layer_norm_variance->Name()}); } else { diff --git a/paddle/fluid/framework/ir/fuse_adamw_op_pass.cc b/paddle/fluid/framework/ir/fuse_adamw_op_pass.cc index edceedd546be7..c2d16d182cb9c 100644 --- a/paddle/fluid/framework/ir/fuse_adamw_op_pass.cc +++ b/paddle/fluid/framework/ir/fuse_adamw_op_pass.cc @@ -91,7 +91,7 @@ void InsertOpToGraph(const std::vector> &inout_node_vectors, weight_decay = config.first_coeff; use_adamw = true; } - if (inout_node_vectors[0].size() > 0 && config.replace_adamw) { + if (!inout_node_vectors[0].empty() && config.replace_adamw) { OpDesc fuse_adamw_op_desc(config.block); fuse_adamw_op_desc.SetType("fused_adam"); @@ -297,7 +297,7 @@ ir::Graph *FuseAdamWPass::FuseAdamWFun(ir::Graph *graph, } // Remove old op - if (config.replace_adamw && (inout_node_vectors[0].size() > 0)) { + if (config.replace_adamw && !inout_node_vectors[0].empty()) { GraphSafeRemoveNodes(graph, adamw_op_del_set); } diff --git a/paddle/fluid/framework/ir/fuse_elewise_add_act_pass.cc b/paddle/fluid/framework/ir/fuse_elewise_add_act_pass.cc index b6faf76f11d10..60267177b7a2b 100644 --- a/paddle/fluid/framework/ir/fuse_elewise_add_act_pass.cc +++ b/paddle/fluid/framework/ir/fuse_elewise_add_act_pass.cc @@ -350,7 +350,7 @@ void FuseElewiseAddActPass::RemoveIntermediateOut(Graph *graph) const { auto cur_node_outputs = cur_node->outputs; for (auto &out : cur_node_outputs) { if (out->Name() == intermediate_out_args[0]) { - if (out->outputs.size() == 0) { + if (out->outputs.empty()) { cur_node->outputs = this->RemoveNode(out, cur_node->outputs); need_removed_nodes.insert(std::move(out)); cur_node->Op()->SetAttr("save_intermediate_out", false); diff --git a/paddle/fluid/framework/ir/fuse_optimizer_ops_pass/fuse_optimizer_op_pass.cc b/paddle/fluid/framework/ir/fuse_optimizer_ops_pass/fuse_optimizer_op_pass.cc index 35f6544a3255e..cb1901108bb34 100644 --- a/paddle/fluid/framework/ir/fuse_optimizer_ops_pass/fuse_optimizer_op_pass.cc +++ b/paddle/fluid/framework/ir/fuse_optimizer_ops_pass/fuse_optimizer_op_pass.cc @@ -143,7 +143,7 @@ void FuseOptimizerOpPass::ApplyImpl(ir::Graph *graph) const { // with the kGrad. The gradients of kParamsAndDenseGrads is // collected during backward stage, but in optimization state, the // some gradient's name maybe changed. - if (new_grad_idx.size() == 0) { + if (new_grad_idx.empty()) { if (!result.Has(details::kFusedGrads)) { PADDLE_THROW(platform::errors::PreconditionNotMet( "The coalesce_grad_tensor_pass should " @@ -287,7 +287,7 @@ bool FuseOptimizerOpPass::OpWithKernelSupportCPUAndGPU( auto &kernel_factory = phi::KernelFactory::Instance(); auto kernel_key_map = kernel_factory.SelectKernelMap(phi::TransToPhiKernelName(op_type)); - bool has_op_kernel = kernel_key_map.size() > 0 ? true : false; + bool has_op_kernel = !kernel_key_map.empty() ? true : false; for (auto &kernel : kernel_key_map) { if (platform::is_gpu_place(phi::TransToPhiPlace(kernel.first.backend()))) { support_gpu = true; diff --git a/paddle/fluid/framework/ir/fusion_group/code_generator.cc b/paddle/fluid/framework/ir/fusion_group/code_generator.cc index 4d8565e439edd..24ddaef703b25 100644 --- a/paddle/fluid/framework/ir/fusion_group/code_generator.cc +++ b/paddle/fluid/framework/ir/fusion_group/code_generator.cc @@ -115,7 +115,7 @@ std::vector CodeGenerator::ConvertToExpressions( for (auto& name : input_names) { // Some input vars are not used in grad ops, such as // "elementwise_add_grad", where "X", "Y" and "Out" are not used. - if ((HasInput(node, name) && op->Input(name).size() >= 1U)) { + if ((HasInput(node, name) && !op->Input(name).empty())) { for (size_t i = 0; i < op->Input(name).size(); i++) { Node* input_var = GetInputVar(node, op->Input(name)[i]); PADDLE_ENFORCE_NE( diff --git a/paddle/fluid/framework/ir/fusion_group/elementwise_group_detector.cc b/paddle/fluid/framework/ir/fusion_group/elementwise_group_detector.cc index ad911c8891330..90709dbe5dbaa 100644 --- a/paddle/fluid/framework/ir/fusion_group/elementwise_group_detector.cc +++ b/paddle/fluid/framework/ir/fusion_group/elementwise_group_detector.cc @@ -35,7 +35,7 @@ static std::unordered_set& GetElementwiseOpTypes() { static bool IsSpecifiedOp(const std::unordered_set& op_types, const Node* n) { - if (n && n->IsOp() && n->Op() && n->outputs.size() > 0U) { + if (n && n->IsOp() && n->Op() && !n->outputs.empty()) { auto iter = op_types.find(n->Op()->Type()); if (iter != op_types.end()) { return true; @@ -58,7 +58,7 @@ static bool IsGradOp(const Node* n) { static bool IsEqualAndNotEmpty(const std::vector& l, const std::vector& r) { - return l.size() != 0U && r.size() != 0U && l == r; + return !l.empty() && !r.empty() && l == r; } bool GroupDetector::CheckPrecondition(const Node* n) { @@ -131,7 +131,7 @@ bool ElementwiseGroupDetector::IsElementwiseOp(const Node* n) { std::vector output_names = OperationMap::Instance().Get(op->Type()).output_names; for (auto& name : output_names) { - if (op->Output(name).size() < 1U) { + if (op->Output(name).empty()) { return false; } } diff --git a/paddle/fluid/framework/ir/fusion_group/operation.cc b/paddle/fluid/framework/ir/fusion_group/operation.cc index 12699189fce52..edd4d455df8a6 100644 --- a/paddle/fluid/framework/ir/fusion_group/operation.cc +++ b/paddle/fluid/framework/ir/fusion_group/operation.cc @@ -55,7 +55,7 @@ void OperationMap::Insert(int type, op_type)); operations_[op_type] = op; - if (grad_exprs.size() > 0U) { + if (!grad_exprs.empty()) { std::string grad_op_type = op_type + "_grad"; // grad_inputs = inputs + outputs + grad of outputs std::vector grad_input_names = input_names; diff --git a/paddle/fluid/framework/ir/graph_helper.cc b/paddle/fluid/framework/ir/graph_helper.cc index 04ff8c0190837..163df90e58d05 100644 --- a/paddle/fluid/framework/ir/graph_helper.cc +++ b/paddle/fluid/framework/ir/graph_helper.cc @@ -345,7 +345,7 @@ size_t GraphNum(const Graph &graph) { traverse_nodes(cur_node->outputs); } else { ++graph_count; - if (g_nodes.size()) { + if (!g_nodes.empty()) { graph_nodes.emplace_back(g_nodes); } g_nodes.clear(); @@ -359,11 +359,11 @@ size_t GraphNum(const Graph &graph) { } } - if (g_nodes.size()) { + if (!g_nodes.empty()) { graph_nodes.emplace_back(g_nodes); } - if (FLAGS_print_sub_graph_dir.size()) { + if (!FLAGS_print_sub_graph_dir.empty()) { if (graph_nodes.size() > 1) { std::stringstream out; for (auto &g_n : graph_nodes) { diff --git a/paddle/fluid/framework/ir/graph_pattern_detector.cc b/paddle/fluid/framework/ir/graph_pattern_detector.cc index 319d3e4f027ae..56ce869b42ce3 100644 --- a/paddle/fluid/framework/ir/graph_pattern_detector.cc +++ b/paddle/fluid/framework/ir/graph_pattern_detector.cc @@ -1210,7 +1210,7 @@ PDNode *patterns::FCMKLDNN::operator()(bool with_residual_data) { } else { fc_op->assert_more([&](Node *x) { if (!HasInput(x, "ResidualData") || - x->Op()->Input("ResidualData").size() == 0) + x->Op()->Input("ResidualData").empty()) return true; return false; }); @@ -1741,7 +1741,7 @@ PDNode *patterns::LinearAct::operator()( elementwise_add_grad_op->LinksFrom({matmul_out_var}); } - if (act_types.size() > 0) { + if (!act_types.empty()) { ele_out_var->AsIntermediate()->assert_is_ops_input(act_types); auto *act = pattern->NewNode(act_repr())->assert_is_ops(act_types); @@ -1812,7 +1812,7 @@ PDNode *patterns::ElewiseAddMatmulAct::operator()( matmul_grad->LinksTo({matmul_grad_dx_var, matmul_grad_dw_var}); } - if (!without_x_gradient && act_grad_types.size() > 0) { + if (!without_x_gradient && !act_grad_types.empty()) { matmul_grad_dx_var->AsIntermediate()->assert_is_ops_input( act_grad_types, GradVarName("Out")); @@ -2059,7 +2059,7 @@ PDNode *patterns::FusedMatmul::operator()(bool with_residual) { if (!with_residual) { matmul_op->assert_more([&](Node *x) { return (!HasInput(x, "ResidualData") || - x->Op()->Input("ResidualData").size() == 0); + x->Op()->Input("ResidualData").empty()); }); } @@ -2115,7 +2115,7 @@ PDNode *patterns::ConvResidual::operator()(const std::string &conv_type, if (!with_residual_data) { conv_op->assert_more([&](Node *x) { if (!HasInput(x, "ResidualData") || - x->Op()->Input("ResidualData").size() == 0) + x->Op()->Input("ResidualData").empty()) return true; return false; }); @@ -3799,7 +3799,7 @@ PDNode *patterns::AddSupportInt8::operator()() { auto quant_out = pattern->NewNode(quant_out_repr()) ->assert_is_var() - ->assert_more([&](Node *node) { return node->outputs.size() > 0; }) + ->assert_more([&](Node *node) { return !node->outputs.empty(); }) ->AsOutput(); quant_op->LinksTo({quant_out}); return quant_out; diff --git a/paddle/fluid/framework/ir/lock_free_optimize_pass.cc b/paddle/fluid/framework/ir/lock_free_optimize_pass.cc index d6f4460113f88..794fa151fc796 100644 --- a/paddle/fluid/framework/ir/lock_free_optimize_pass.cc +++ b/paddle/fluid/framework/ir/lock_free_optimize_pass.cc @@ -372,7 +372,7 @@ ir::Node* LockFreeOptimizePass::FindForwardOpViaBackwardOp( for (ir::Node* node : graph->Nodes()) { if (node->Name() == forward_op_name) { - if (node->outputs.size() == 0u) { + if (node->outputs.empty()) { // if forward_node has no output, then it has NO grad op continue; } diff --git a/paddle/fluid/framework/ir/matmul_scale_fuse_pass.cc b/paddle/fluid/framework/ir/matmul_scale_fuse_pass.cc index 64c74ab0f9b18..c9c9a271d439b 100644 --- a/paddle/fluid/framework/ir/matmul_scale_fuse_pass.cc +++ b/paddle/fluid/framework/ir/matmul_scale_fuse_pass.cc @@ -144,7 +144,7 @@ void MatmulScaleFusePass::ApplyImpl(ir::Graph* graph) const { auto const& names = scale_op->Op()->InputNames(); bool has_scale_tensor = std::find(names.begin(), names.end(), "ScaleTensor") != names.end(); - if (has_scale_tensor && scale_op->Op()->Input("ScaleTensor").size() > 0) { + if (has_scale_tensor && !scale_op->Op()->Input("ScaleTensor").empty()) { std::string scale_var_name = scale_op->Op()->Input("ScaleTensor").front(); auto* scale_var = scope->FindVar(scale_var_name); // ScaleTensor must be weight @@ -206,7 +206,7 @@ void MatmulV2ScaleFusePass::ApplyImpl(ir::Graph* graph) const { auto const& names = scale_op->Op()->InputNames(); bool has_scale_tensor = std::find(names.begin(), names.end(), "ScaleTensor") != names.end(); - if (has_scale_tensor && scale_op->Op()->Input("ScaleTensor").size() > 0) { + if (has_scale_tensor && !scale_op->Op()->Input("ScaleTensor").empty()) { std::string scale_var_name = scale_op->Op()->Input("ScaleTensor").front(); auto* scale_var = scope->FindVar(scale_var_name); // ScaleTensor must be weight diff --git a/paddle/fluid/framework/ir/mkldnn/compute_propagate_scales_mkldnn_pass.cc b/paddle/fluid/framework/ir/mkldnn/compute_propagate_scales_mkldnn_pass.cc index 16dc293b06048..e9eea53c94845 100644 --- a/paddle/fluid/framework/ir/mkldnn/compute_propagate_scales_mkldnn_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/compute_propagate_scales_mkldnn_pass.cc @@ -476,7 +476,7 @@ void ComputePropagateScalesMkldnnPass::PropagateScales( auto waiting_for_scale = UpdateScales(graph, var_quant_scales, scale_immutable_ops); std::unordered_set waiting_for_scale_prev{}; - while (waiting_for_scale.size() != 0 && + while (!waiting_for_scale.empty() && waiting_for_scale != waiting_for_scale_prev) { waiting_for_scale_prev.clear(); waiting_for_scale_prev.insert(waiting_for_scale.begin(), diff --git a/paddle/fluid/framework/ir/mkldnn/conv_bias_mkldnn_fuse_pass.cc b/paddle/fluid/framework/ir/mkldnn/conv_bias_mkldnn_fuse_pass.cc index 314991d3479fb..bd61d58a3b2b0 100644 --- a/paddle/fluid/framework/ir/mkldnn/conv_bias_mkldnn_fuse_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/conv_bias_mkldnn_fuse_pass.cc @@ -338,7 +338,7 @@ void ConvBiasFusePass::FuseConvBias(ir::Graph* graph, bool has_bias = std::find(input_names.begin(), input_names.end(), "Bias") != input_names.end(); - if (has_bias && conv->Op()->Input("Bias").size() > 0) { + if (has_bias && !conv->Op()->Input("Bias").empty()) { auto conv_bias_names = conv->Op()->Input("Bias"); // add eltwise bias to existing conv bias PADDLE_ENFORCE_EQ(conv_bias_names.size(), diff --git a/paddle/fluid/framework/ir/mkldnn/cpu_quantize_squash_pass_tester.cc b/paddle/fluid/framework/ir/mkldnn/cpu_quantize_squash_pass_tester.cc index d6277d8d013a0..5b1cd5fe87aed 100644 --- a/paddle/fluid/framework/ir/mkldnn/cpu_quantize_squash_pass_tester.cc +++ b/paddle/fluid/framework/ir/mkldnn/cpu_quantize_squash_pass_tester.cc @@ -44,15 +44,15 @@ void SetOp(ProgramDesc* prog, if (type == "pool2d") { op->SetInput("X", {inputs[0]}); op->SetOutput("Out", {outputs[0]}); - if (scale.size() > 0) op->SetAttr("Scale_in", scale[0]); + if (!scale.empty()) op->SetAttr("Scale_in", scale[0]); if (scale.size() > 1) op->SetAttr("Scale_out", scale[1]); } else if (type == "relu") { op->SetInput("X", {inputs[0]}); op->SetOutput("Out", {outputs[0]}); - if (scale.size() > 0) op->SetAttr("Scale_in", scale[0]); + if (!scale.empty()) op->SetAttr("Scale_in", scale[0]); if (scale.size() > 1) op->SetAttr("Scale_out", scale[1]); } else if (type == "conv2d") { - if (scale.size() > 0) op->SetAttr("Scale_in", scale[0]); + if (!scale.empty()) op->SetAttr("Scale_in", scale[0]); if (scale.size() > 1) op->SetAttr("Scale_out", scale[1]); op->SetInput("Input", {inputs[0]}); if (inputs.size() > 1) op->SetInput("Filter", {inputs[1]}); @@ -91,7 +91,7 @@ void SetOp(ProgramDesc* prog, inputs.size())); op->SetInput("W", {inputs[1]}); op->SetOutput("Out", outputs); - if (scale.size() > 0) op->SetAttr("Scale_in", scale[0]); + if (!scale.empty()) op->SetAttr("Scale_in", scale[0]); if (scale.size() > 1) op->SetAttr("Scale_out", scale[1]); op->SetAttr("force_fp32_output", false); op->SetAttr("mkldnn_data_type", mkldnn_data_type); @@ -105,7 +105,7 @@ void SetOp(ProgramDesc* prog, op->SetInput("X", {inputs[0]}); op->SetInput("Y", {inputs[1]}); op->SetOutput("Out", {outputs[0]}); - if (scale.size() > 0) op->SetAttr("Scale_x", scale[0]); + if (!scale.empty()) op->SetAttr("Scale_x", scale[0]); if (scale.size() > 1) op->SetAttr("Scale_out", scale[1]); op->SetAttr("force_fp32_output", false); op->SetAttr("mkldnn_data_type", mkldnn_data_type); diff --git a/paddle/fluid/framework/ir/mkldnn/int8_scale_calculation_mkldnn_pass.cc b/paddle/fluid/framework/ir/mkldnn/int8_scale_calculation_mkldnn_pass.cc index 43aa86837d988..9160d88824552 100644 --- a/paddle/fluid/framework/ir/mkldnn/int8_scale_calculation_mkldnn_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/int8_scale_calculation_mkldnn_pass.cc @@ -159,7 +159,7 @@ void Int8ScaleCalculationMkldnnPass::Int8ScaleImpl( } } - if (has_bias && conv_op->Op()->Input("Bias").size() > 0) { + if (has_bias && !conv_op->Op()->Input("Bias").empty()) { auto bias_scales = std::vector(count); for (int i = 0; i < count; i++) { bias_scales[i] = scale_in_data * scale_weights_data[i]; diff --git a/paddle/fluid/framework/ir/mkldnn/mkldnn_placement_pass.cc b/paddle/fluid/framework/ir/mkldnn/mkldnn_placement_pass.cc index c966c46e06b16..23e5497b12fde 100644 --- a/paddle/fluid/framework/ir/mkldnn/mkldnn_placement_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/mkldnn_placement_pass.cc @@ -30,7 +30,7 @@ inline bool FoundOneDNNKernelWithCorrectDataType( if (platform::is_cpu_place(kernel_pair.first.place_) && (kernel_pair.first.library_type_ == framework::LibraryType::kMKLDNN)) { - if (op->inputs.size() > 0) { + if (!op->inputs.empty()) { if (op->inputs[0]->IsVar() && op->inputs[0]->Var()->Name() != "feed" && kernel_pair.first.data_type_ == @@ -53,7 +53,7 @@ inline bool FoundPhiOneDNNKernelWithCorrectDataType( for (auto& kernel_pair : phi_kernels) { if (kernel_pair.first.backend() == phi::Backend::ONEDNN) { - if (op->inputs.size() > 0) { + if (!op->inputs.empty()) { if (op->inputs[0]->IsVar() && op->inputs[0]->Var()->Name() != "feed" && kernel_pair.first.dtype() == framework::TransToPhiDataType( diff --git a/paddle/fluid/framework/ir/mkldnn/operator_reshape2_onednn_fuse_pass.cc b/paddle/fluid/framework/ir/mkldnn/operator_reshape2_onednn_fuse_pass.cc index 19e814fbbe14d..94ede72921baa 100644 --- a/paddle/fluid/framework/ir/mkldnn/operator_reshape2_onednn_fuse_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/operator_reshape2_onednn_fuse_pass.cc @@ -99,8 +99,7 @@ void FuseOperatorReshape2OneDNNPass::FuseReshape2(Graph *graph, bool has_shape_tensor_list = std::find(names.begin(), names.end(), "ShapeTensorList") != names.end(); - if (has_shape_tensor && - reshape2_op->Op()->Input("ShapeTensor").size() > 0) { + if (has_shape_tensor && !reshape2_op->Op()->Input("ShapeTensor").empty()) { VLOG(4) << "Cannot fuse " << op_type << " and reshape2 because reshape2 dims are specified by " "ShapeTensor!"; @@ -108,7 +107,7 @@ void FuseOperatorReshape2OneDNNPass::FuseReshape2(Graph *graph, } if (has_shape_tensor_list && - reshape2_op->Op()->Input("ShapeTensorList").size() > 0) { + !reshape2_op->Op()->Input("ShapeTensorList").empty()) { VLOG(4) << "Cannot fuse " << op_type << " and reshape2 because reshape2 dims are specified by " "ShapeTensorList!"; diff --git a/paddle/fluid/framework/ir/mkldnn/operator_scale_onednn_fuse_pass.cc b/paddle/fluid/framework/ir/mkldnn/operator_scale_onednn_fuse_pass.cc index 086de37ab4299..4f6c2bfe0507b 100644 --- a/paddle/fluid/framework/ir/mkldnn/operator_scale_onednn_fuse_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/operator_scale_onednn_fuse_pass.cc @@ -82,7 +82,7 @@ void FuseOperatorScaleOneDNNPass::FuseScale(Graph *graph, bool has_scale_tensor = std::find(names.begin(), names.end(), "ScaleTensor") != names.end(); - if (has_scale_tensor && scale_op->Op()->Input("ScaleTensor").size() > 0) { + if (has_scale_tensor && !scale_op->Op()->Input("ScaleTensor").empty()) { std::string scale_var_name = scale_op->Op()->Input("ScaleTensor").front(); auto *scale_var = scope->FindVar(scale_var_name); // ScaleTensor must be weight diff --git a/paddle/fluid/framework/ir/mkldnn/operator_unsqueeze2_onednn_fuse_pass.cc b/paddle/fluid/framework/ir/mkldnn/operator_unsqueeze2_onednn_fuse_pass.cc index 7726206e84ea4..28b01bc065b37 100644 --- a/paddle/fluid/framework/ir/mkldnn/operator_unsqueeze2_onednn_fuse_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/operator_unsqueeze2_onednn_fuse_pass.cc @@ -76,8 +76,7 @@ void FuseOperatorUnsqueeze2OneDNNPass::FuseUnsqueeze2( bool has_axes_tensor_list = std::find(names.begin(), names.end(), "AxesTensorList") != names.end(); - if (has_axes_tensor && - unsqueeze2_op->Op()->Input("AxesTensor").size() > 0) { + if (has_axes_tensor && !unsqueeze2_op->Op()->Input("AxesTensor").empty()) { VLOG(4) << "Cannot fuse " << op_type << " and unsqueeze2 because unsqueeze2 dims are specified by " "AxesTensor!"; @@ -85,7 +84,7 @@ void FuseOperatorUnsqueeze2OneDNNPass::FuseUnsqueeze2( } if (has_axes_tensor_list && - unsqueeze2_op->Op()->Input("AxesTensorList").size() > 0) { + !unsqueeze2_op->Op()->Input("AxesTensorList").empty()) { VLOG(4) << "Cannot fuse " << op_type << " and unsqueeze2 because unsqueeze2 dims are specified by " "AxesTensorList!"; diff --git a/paddle/fluid/framework/ir/mkldnn/params_quantization_mkldnn_pass.cc b/paddle/fluid/framework/ir/mkldnn/params_quantization_mkldnn_pass.cc index 132b11232433f..093001675ec7f 100644 --- a/paddle/fluid/framework/ir/mkldnn/params_quantization_mkldnn_pass.cc +++ b/paddle/fluid/framework/ir/mkldnn/params_quantization_mkldnn_pass.cc @@ -50,7 +50,7 @@ bool HasBias(ir::Node* conv_op) { auto input_names = conv_op->Op()->InputNames(); return std::find(input_names.begin(), input_names.end(), "Bias") != input_names.end() && - conv_op->Op()->Input("Bias").size() > 0; + !conv_op->Op()->Input("Bias").empty(); } template diff --git a/paddle/fluid/framework/ir/multi_devices_graph_pass/fuse_all_reduce_op_pass.cc b/paddle/fluid/framework/ir/multi_devices_graph_pass/fuse_all_reduce_op_pass.cc index b0ea65948199c..15d36d481ccb7 100644 --- a/paddle/fluid/framework/ir/multi_devices_graph_pass/fuse_all_reduce_op_pass.cc +++ b/paddle/fluid/framework/ir/multi_devices_graph_pass/fuse_all_reduce_op_pass.cc @@ -59,7 +59,7 @@ class FuseAllReduceOpPass : public ir::Pass { GetAllReduceOps(result, places, grads); VLOG(6) << "Find all_reduce_ops: " << all_reduce_ops.size(); - if (all_reduce_ops.size() == 0) { + if (all_reduce_ops.empty()) { return; } diff --git a/paddle/fluid/framework/ir/preln_embedding_eltwise_layernorm_fuse_pass.cc b/paddle/fluid/framework/ir/preln_embedding_eltwise_layernorm_fuse_pass.cc index 5281f27ff1c69..d24cbdff25000 100644 --- a/paddle/fluid/framework/ir/preln_embedding_eltwise_layernorm_fuse_pass.cc +++ b/paddle/fluid/framework/ir/preln_embedding_eltwise_layernorm_fuse_pass.cc @@ -439,8 +439,8 @@ void PrelnEmbeddingEltwiseLayerNormFusePass::ApplyImpl(Graph* graph) const { bool with_dynamic_shape = Get("with_dynamic_shape"); std::string pos_id = Get("tensorrt_transformer_posid"); std::string mask_id = Get("tensorrt_transformer_maskid"); - if (!(enable_int8 && use_varseqlen && with_interleaved && pos_id != "" && - mask_id != "" && with_dynamic_shape)) { + if (!(enable_int8 && use_varseqlen && with_interleaved && !pos_id.empty() && + !mask_id.empty() && with_dynamic_shape)) { VLOG(3) << "preln_embedding_eltwise_layernorm_fuse_pass need: use_trt, " "enable_int8, set pos_id, set mask_id, " "use_varseqlen, with_interleaved, with_dynamic_shape. Stop this " diff --git a/paddle/fluid/framework/ir/preln_skip_layernorm_fuse_pass.cc b/paddle/fluid/framework/ir/preln_skip_layernorm_fuse_pass.cc index 84546c1db6aac..8547fceed0773 100644 --- a/paddle/fluid/framework/ir/preln_skip_layernorm_fuse_pass.cc +++ b/paddle/fluid/framework/ir/preln_skip_layernorm_fuse_pass.cc @@ -116,8 +116,8 @@ void PrelnSkipLayerNormFusePass::ApplyImpl(ir::Graph *graph) const { std::string mask_id = Get("tensorrt_transformer_maskid"); if (!(enable_int8 && use_varseqlen && with_interleaved && graph->Has(framework::ir::kPrelnEmbEltwiseLayernormPass) && - graph->Has(framework::ir::kMultiheadMatmulPass) && pos_id != "" && - mask_id != "" && with_dynamic_shape)) { + graph->Has(framework::ir::kMultiheadMatmulPass) && !pos_id.empty() && + !mask_id.empty() && with_dynamic_shape)) { VLOG(3) << "preln_skip_layernorm_fuse_pass need: use_trt, enable_int8, " "with_interleaved" "use_varseqlen, preln_embedding_eltwise_layernorm_fuse_pass, " diff --git a/paddle/fluid/framework/ir/remove_padding_recover_padding_pass.cc b/paddle/fluid/framework/ir/remove_padding_recover_padding_pass.cc index 429fc12d1df4f..ffbff73183629 100644 --- a/paddle/fluid/framework/ir/remove_padding_recover_padding_pass.cc +++ b/paddle/fluid/framework/ir/remove_padding_recover_padding_pass.cc @@ -168,7 +168,7 @@ void RemovePaddingRecoverPaddingPass::ApplyImpl(ir::Graph* graph) const { std::string pos_id = Get("tensorrt_transformer_posid"); std::string mask_id = Get("tensorrt_transformer_maskid"); - if (use_varseqlen && pos_id != "" && mask_id != "" && + if (use_varseqlen && !pos_id.empty() && !mask_id.empty() && (graph->Has(framework::ir::kEmbEltwiseLayernormPass) || graph->Has(framework::ir::kPrelnEmbEltwiseLayernormPass)) && graph->Has(framework::ir::kMultiheadMatmulPass)) { diff --git a/paddle/fluid/framework/ir/repeated_fc_relu_fuse_pass.cc b/paddle/fluid/framework/ir/repeated_fc_relu_fuse_pass.cc index 6d2241d280be3..6fdab51006865 100644 --- a/paddle/fluid/framework/ir/repeated_fc_relu_fuse_pass.cc +++ b/paddle/fluid/framework/ir/repeated_fc_relu_fuse_pass.cc @@ -221,7 +221,7 @@ void BuildRepeatedFCReluPattern(PDPattern* pattern, if (i == 0) { fc_input_var_0 = pattern->NewNode( [=](Node* x) { - if (x->outputs.size() <= 0 || x->inputs.size() <= 0U) { + if (x->outputs.empty() || x->inputs.empty()) { return false; } if (x->IsVar() && x->Var() && x->Var()->GetShape().size() > 2) { @@ -275,8 +275,8 @@ void BuildRepeatedFCReluPattern(PDPattern* pattern, return false; } x = before_var_of_part(x); - if (i == 0 && x->outputs.size() > 0U) { - if (x->inputs.size() <= 0U) { + if (i == 0 && !x->outputs.empty()) { + if (x->inputs.empty()) { return false; } int fc_idx = FindFCIdx(x); @@ -291,7 +291,7 @@ void BuildRepeatedFCReluPattern(PDPattern* pattern, } } else { return var_next_is_fc_act_repeated_n_times(x, num_fc - i, "relu") && - x->inputs.size() > 0 && + !x->inputs.empty() && var_before_is_fc_act_repeated_n_times(x, i, "relu"); } }, diff --git a/paddle/fluid/framework/ir/seqpool_concat_fuse_pass.cc b/paddle/fluid/framework/ir/seqpool_concat_fuse_pass.cc index be1a4de55d574..fd04e8974db04 100644 --- a/paddle/fluid/framework/ir/seqpool_concat_fuse_pass.cc +++ b/paddle/fluid/framework/ir/seqpool_concat_fuse_pass.cc @@ -61,7 +61,7 @@ PDNode* BuildSeqPoolConcatPattern(PDPattern* pattern, } else { satisfied_all = satisfied_all && is_nth_input_var_of_concat(x->outputs[1], idx) && - x->outputs[0]->IsVar() && x->outputs[0]->outputs.size() == 0; + x->outputs[0]->IsVar() && x->outputs[0]->outputs.empty(); } } return satisfied_all; @@ -99,7 +99,7 @@ PDNode* BuildSeqPoolConcatPattern(PDPattern* pattern, seqpool_ops_output_unused_var[i] = pattern->NewNode( [=](Node* x) { return x && x->IsVar() && x->inputs.size() == 1 && - x->outputs.size() == 0 && + x->outputs.empty() && is_seqpool_op_with_pootype_of_nth_input_of_concat( x->inputs[0], "SUM", i); }, @@ -114,7 +114,7 @@ PDNode* BuildSeqPoolConcatPattern(PDPattern* pattern, seqpool_ops_input_var[i] = pattern->NewNode( [=](Node* x) { - bool basic = x && x->IsVar() && x->outputs.size() >= 1; + bool basic = x && x->IsVar() && !x->outputs.empty(); bool next_is_fine = false; for (auto* o : x->outputs) { if (is_seqpool_op_with_pootype_of_nth_input_of_concat( diff --git a/paddle/fluid/framework/ir/set_transformer_input_convert_pass.cc b/paddle/fluid/framework/ir/set_transformer_input_convert_pass.cc index e2bec6b65f809..0ff7a6bc0ba2d 100644 --- a/paddle/fluid/framework/ir/set_transformer_input_convert_pass.cc +++ b/paddle/fluid/framework/ir/set_transformer_input_convert_pass.cc @@ -56,7 +56,7 @@ void SetTransformerInputConvertPass::ApplyImpl(ir::Graph *graph) const { std::string pos_id = Get("tensorrt_transformer_posid"); if (!(graph->Has(framework::ir::kMultiheadMatmulPass) && with_dynamic_shape && - (pos_id != ""))) { + (!pos_id.empty()))) { VLOG(3) << "Transformer model need MultiheadMatmul, and " "with_dynamic_shape. Stop this pass, " "please reconfig."; diff --git a/paddle/fluid/framework/ir/squared_mat_sub_fuse_pass.cc b/paddle/fluid/framework/ir/squared_mat_sub_fuse_pass.cc index 7b9d6bbe62800..9b3eb12c3eef7 100644 --- a/paddle/fluid/framework/ir/squared_mat_sub_fuse_pass.cc +++ b/paddle/fluid/framework/ir/squared_mat_sub_fuse_pass.cc @@ -250,7 +250,7 @@ PDNode* BuildSquaredMatSubPattern(PDPattern* pattern, return false; } for (auto* in : x->inputs) { - if (in && in->inputs.size() > 0 && in->inputs[0] && + if (in && !in->inputs.empty() && in->inputs[0] && is_fusion_sub_op(in->inputs[0])) { return true; } @@ -273,7 +273,7 @@ PDNode* BuildSquaredMatSubPattern(PDPattern* pattern, auto* constant_op_out = pattern->NewNode( [=](Node* x) { return x && x->IsVar() && var_is_op_input(x, "elementwise_mul") && - x->inputs.size() > 0 && x->inputs[0] && x->inputs[0]->IsOp() && + !x->inputs.empty() && x->inputs[0] && x->inputs[0]->IsOp() && x->inputs[0]->Op()->Type() == "fill_constant" && x->outputs[0] && is_fusion_element_op(x->outputs[0]); }, diff --git a/paddle/fluid/framework/ir/transfer_layout_elim_pass.cc b/paddle/fluid/framework/ir/transfer_layout_elim_pass.cc index a28eca20f760f..b75c3365c0529 100644 --- a/paddle/fluid/framework/ir/transfer_layout_elim_pass.cc +++ b/paddle/fluid/framework/ir/transfer_layout_elim_pass.cc @@ -51,7 +51,7 @@ void TransferLayoutElimPass::PutTranferlayoutAfterOp( int op_node_useful_output = 0; Node *var2; for (auto ele : op_node->outputs) { - if (ele->outputs.size() >= 1) { + if (!ele->outputs.empty()) { op_node_useful_output++; var2 = ele; } @@ -68,7 +68,7 @@ void TransferLayoutElimPass::PutTranferlayoutAfterOp( // } useful_var1s.push_back(var1); } - CHECK_EQ(useful_var1s.size() >= 1L, true); + CHECK_EQ(!useful_var1s.empty(), true); auto transfer_layout_opdesc = *useful_var1s[0]->inputs[0]->Op()->Proto(); auto block = useful_var1s[0]->inputs[0]->Op()->Block(); diff --git a/paddle/fluid/framework/ir/trt_embedding_eltwise_layernorm_fuse_pass.cc b/paddle/fluid/framework/ir/trt_embedding_eltwise_layernorm_fuse_pass.cc index 80d7ade84581b..b471e24d7c1ab 100644 --- a/paddle/fluid/framework/ir/trt_embedding_eltwise_layernorm_fuse_pass.cc +++ b/paddle/fluid/framework/ir/trt_embedding_eltwise_layernorm_fuse_pass.cc @@ -358,7 +358,7 @@ int TrtEmbeddingEltwiseLayerNormFusePass::BuildFusion( new_op_desc.SetType("fused_embedding_eltwise_layernorm"); new_op_desc.SetInput("Ids", ids); new_op_desc.SetInput("Embs", embs); - if (use_varseqlen && pos_id != "" && mask_id != "") { + if (use_varseqlen && !pos_id.empty() && !mask_id.empty()) { new_op_desc.SetInput("PosId", {pos_id}); new_op_desc.SetInput("MaskId", {mask_id}); } @@ -471,8 +471,8 @@ void TrtEmbeddingEltwiseLayerNormFusePass::ApplyImpl(Graph* graph) const { std::string pos_id = Get("tensorrt_transformer_posid"); std::string mask_id = Get("tensorrt_transformer_maskid"); - if ((use_varseqlen && pos_id != "" && mask_id != "") || - (!use_varseqlen && pos_id == "")) { + if ((use_varseqlen && !pos_id.empty() && !mask_id.empty()) || + (!use_varseqlen && pos_id.empty())) { VLOG(3) << "start trt_embedding_eltwise_layernorm_fuse_pass"; } else { PADDLE_THROW( diff --git a/paddle/fluid/framework/ir/trt_multihead_matmul_fuse_pass.cc b/paddle/fluid/framework/ir/trt_multihead_matmul_fuse_pass.cc index 11705c33121b6..db62c5dd3789c 100644 --- a/paddle/fluid/framework/ir/trt_multihead_matmul_fuse_pass.cc +++ b/paddle/fluid/framework/ir/trt_multihead_matmul_fuse_pass.cc @@ -1095,7 +1095,7 @@ void TrtMultiHeadMatmulV2FusePass::ApplyImpl(Graph* graph) const { std::string pos_id = Get("tensorrt_transformer_posid"); std::string mask_id = Get("tensorrt_transformer_maskid"); - if (use_varseqlen && pos_id != "" && mask_id != "") { + if (use_varseqlen && !pos_id.empty() && !mask_id.empty()) { if (graph->Has(framework::ir::kEmbEltwiseLayernormPass) || graph->Has(framework::ir::kPrelnEmbEltwiseLayernormPass)) { if (with_interleaved) { @@ -1111,7 +1111,7 @@ void TrtMultiHeadMatmulV2FusePass::ApplyImpl(Graph* graph) const { "preln_embedding_eltwise_layernorm_fuse_" "pass. please use no_varseqlen")); } - } else if (!use_varseqlen && pos_id == "") { + } else if (!use_varseqlen && pos_id.empty()) { VLOG(3) << "start no_varseqlen_trt_multihead_matmul_fuse_pass"; } else { PADDLE_THROW( @@ -1510,7 +1510,7 @@ void TrtMultiHeadMatmulV3FusePass::ApplyImpl(Graph* graph) const { std::string pos_id = Get("tensorrt_transformer_posid"); std::string mask_id = Get("tensorrt_transformer_maskid"); - if (use_varseqlen && pos_id != "" && mask_id != "") { + if (use_varseqlen && !pos_id.empty() && !mask_id.empty()) { if (graph->Has(framework::ir::kEmbEltwiseLayernormPass) || graph->Has(framework::ir::kPrelnEmbEltwiseLayernormPass)) { if (with_interleaved) { @@ -1526,7 +1526,7 @@ void TrtMultiHeadMatmulV3FusePass::ApplyImpl(Graph* graph) const { "preln_embedding_eltwise_layernorm_fuse_" "pass. please use no_varseqlen")); } - } else if (!use_varseqlen && pos_id == "") { + } else if (!use_varseqlen && pos_id.empty()) { VLOG(3) << "start no_varseqlen_trt_multihead_matmul_fuse_pass"; } else { PADDLE_THROW( diff --git a/paddle/fluid/framework/ir/trt_skip_layernorm_fuse_pass.cc b/paddle/fluid/framework/ir/trt_skip_layernorm_fuse_pass.cc index 02ae3e29595c3..65afdec4c0564 100644 --- a/paddle/fluid/framework/ir/trt_skip_layernorm_fuse_pass.cc +++ b/paddle/fluid/framework/ir/trt_skip_layernorm_fuse_pass.cc @@ -238,7 +238,7 @@ void TrtSkipLayerNormFusePass::ApplyImpl(ir::Graph *graph) const { std::string pos_id = Get("tensorrt_transformer_posid"); std::string mask_id = Get("tensorrt_transformer_maskid"); - if (use_varseqlen && pos_id != "" && mask_id != "") { + if (use_varseqlen && !pos_id.empty() && !mask_id.empty()) { if ((graph->Has(framework::ir::kEmbEltwiseLayernormPass) || graph->Has(framework::ir::kPrelnEmbEltwiseLayernormPass)) && graph->Has(framework::ir::kMultiheadMatmulPass)) { @@ -249,7 +249,7 @@ void TrtSkipLayerNormFusePass::ApplyImpl(ir::Graph *graph) const { "trt_embedding_eltwise_layernorm_fuse_pass, " "trt_multihead_matmul_fuse_pass. please use no_varseqlen")); } - } else if (!use_varseqlen && pos_id == "") { + } else if (!use_varseqlen && pos_id.empty()) { VLOG(3) << "start no_varseqlen trt_skip_layernorm_fuse_pass"; } else { PADDLE_THROW( diff --git a/paddle/fluid/framework/multi_trainer.cc b/paddle/fluid/framework/multi_trainer.cc index 97920952e453b..220b11efb1b8a 100644 --- a/paddle/fluid/framework/multi_trainer.cc +++ b/paddle/fluid/framework/multi_trainer.cc @@ -84,7 +84,7 @@ void MultiTrainer::Initialize(const TrainerDesc& trainer_desc, } std::string MultiTrainer::GetDumpPath(int tid) { - if (user_define_dump_filename_ != "") { + if (!user_define_dump_filename_.empty()) { return string::format_string("%s/part-%s-%05d", dump_fields_path_.c_str(), user_define_dump_filename_.c_str(), diff --git a/paddle/fluid/framework/new_executor/executor_statistics.cc b/paddle/fluid/framework/new_executor/executor_statistics.cc index 0449fa53e1912..311b5994672b7 100644 --- a/paddle/fluid/framework/new_executor/executor_statistics.cc +++ b/paddle/fluid/framework/new_executor/executor_statistics.cc @@ -430,7 +430,7 @@ int StatisticsEngine::Stat(const platform::NodeTrees& trees) { } } } - if (thr_evts.size() == 0) { + if (thr_evts.empty()) { continue; } std::sort(thr_evts.begin(), @@ -440,7 +440,7 @@ int StatisticsEngine::Stat(const platform::NodeTrees& trees) { }); all_evts.push_back(std::move(thr_evts)); } - if (all_evts.size() == 0) { + if (all_evts.empty()) { LOG(WARNING) << "No profiler events"; return -1; } @@ -621,7 +621,7 @@ void StatisticsEngine::Log(const std::string& filepath) { void StaticGraphExecutorPerfStatistics( std::shared_ptr profiling_data) { - if (FLAGS_static_executor_perfstat_filepath.size() == 0) { + if (FLAGS_static_executor_perfstat_filepath.empty()) { VLOG(5) << "StaticGraphExecutorPerfStatistics is disabled"; return; } diff --git a/paddle/fluid/framework/new_executor/interpreter/data_transfer.cc b/paddle/fluid/framework/new_executor/interpreter/data_transfer.cc index 48aeefc553c07..d4606c4bef003 100644 --- a/paddle/fluid/framework/new_executor/interpreter/data_transfer.cc +++ b/paddle/fluid/framework/new_executor/interpreter/data_transfer.cc @@ -513,7 +513,7 @@ void ApplyDataTransform(const OpKernelType& expected_kernel_key, var->IsType()) { tensor_in = GetLoDTensorOrSelectedRowsValueFromVar(*var); } else if (var->IsType()) { - if (var->Get().size() == 0) { + if (var->Get().empty()) { continue; } tensor_in = static_cast( diff --git a/paddle/fluid/framework/new_executor/interpreter/stream_analyzer.cc b/paddle/fluid/framework/new_executor/interpreter/stream_analyzer.cc index acde737e9e02d..bba4e0accc392 100644 --- a/paddle/fluid/framework/new_executor/interpreter/stream_analyzer.cc +++ b/paddle/fluid/framework/new_executor/interpreter/stream_analyzer.cc @@ -357,7 +357,7 @@ void StreamAnalyzer::AnalyseEventInfoForTwoInstructions( // can only add event for it with the help of depend_op. if (HasDataDependency(instructions[cur_instr_id], instructions[next_instr_id]) || - run_type_info[next_instr_id][DownstreamRunType::kEventRun].size() || + !run_type_info[next_instr_id][DownstreamRunType::kEventRun].empty() || instructions[next_instr_id].OpBase()->Type() == "depend") { waiter_instr_ids->insert(next_instr_id); return; diff --git a/paddle/fluid/framework/new_executor/new_ir_interpreter.cc b/paddle/fluid/framework/new_executor/new_ir_interpreter.cc index 63fb46cba0d91..54a0332db98de 100644 --- a/paddle/fluid/framework/new_executor/new_ir_interpreter.cc +++ b/paddle/fluid/framework/new_executor/new_ir_interpreter.cc @@ -777,7 +777,7 @@ void NewIRInterpreter::BuildSkipShareLoDInfo() { for (auto& input : vec_instruction_[i].InnerRuntimeContext()->inputs) { for (auto& var : input.second) { if (var->IsType()) { - if (var->Get().lod().size() != 0) { + if (!var->Get().lod().empty()) { can_skip_lod = false; break; } diff --git a/paddle/fluid/framework/new_executor/program_interpreter.cc b/paddle/fluid/framework/new_executor/program_interpreter.cc index 3035dea85dcb4..cea40f47ffd5d 100644 --- a/paddle/fluid/framework/new_executor/program_interpreter.cc +++ b/paddle/fluid/framework/new_executor/program_interpreter.cc @@ -764,7 +764,7 @@ void ProgramInterpreter::BuildSkipShareLoDInfo() { for (auto& input : vec_instruction_[i].InnerRuntimeContext()->inputs) { for (auto& var : input.second) { if (var->IsType()) { - if (var->Get().lod().size() != 0) { + if (!var->Get().lod().empty()) { can_skip_lod = false; break; } diff --git a/paddle/fluid/framework/new_executor/workqueue/events_waiter.cc b/paddle/fluid/framework/new_executor/workqueue/events_waiter.cc index f949d6783b320..d66b8e9d43443 100644 --- a/paddle/fluid/framework/new_executor/workqueue/events_waiter.cc +++ b/paddle/fluid/framework/new_executor/workqueue/events_waiter.cc @@ -154,7 +154,7 @@ std::string EventsWaiter::WaitEvent() { { triggered = trigger_event_; std::lock_guard guard(events_lock_); - if (deleted_events_.size() > 0) { + if (!deleted_events_.empty()) { for (auto evt : deleted_events_) { if (evt == triggered) { continue; diff --git a/paddle/fluid/framework/op_desc.cc b/paddle/fluid/framework/op_desc.cc index dcdf15c19b7bf..73bcd46161267 100644 --- a/paddle/fluid/framework/op_desc.cc +++ b/paddle/fluid/framework/op_desc.cc @@ -691,7 +691,7 @@ void OpDesc::SetAttr(const std::string &name, const Attribute &v) { // here if we meet this issue proto::AttrType attr_type = static_cast(v.index() - 1); if (attr_type == proto::AttrType::INTS && - PADDLE_GET_CONST(std::vector, v).size() == 0u) { + PADDLE_GET_CONST(std::vector, v).empty()) { // Find current attr via attr name and set the correct attribute value if (is_runtime_attr) { attr_type = diff --git a/paddle/fluid/framework/operator.cc b/paddle/fluid/framework/operator.cc index 74e4b04d0535f..1b55dea874aa0 100644 --- a/paddle/fluid/framework/operator.cc +++ b/paddle/fluid/framework/operator.cc @@ -223,7 +223,7 @@ bool RuntimeInferShapeContext::HasInput(const std::string& name) const { return false; } const auto& in = it->second; - if (in.size() == 0) return false; + if (in.empty()) return false; PADDLE_ENFORCE_EQ( in.size(), 1UL, @@ -240,7 +240,7 @@ bool RuntimeInferShapeContext::HasOutput(const std::string& name) const { return false; } const auto& out = it->second; - if (out.size() == 0) { + if (out.empty()) { return false; } PADDLE_ENFORCE_EQ( @@ -967,7 +967,7 @@ OperatorBase::OperatorBase(const std::string& type, // framework::OpRegistry::CreateOp(type, {}, {}, {}, false). // Inputs, outputs and attrs will be set to empty map // to improve the execution efficiency of dygraph. - if (inputs_.size() > 0 || outputs_.size() > 0) { + if (!inputs_.empty() || !outputs_.empty()) { GenerateTemporaryNames(); CheckAllInputOutputSet(); } @@ -1149,7 +1149,7 @@ ExecutionContext::MultiInput(const std::string& name) const { LogVarUsageIfUnusedVarCheckEnabled(name); auto vars = MultiInputVar(name); - if (vars.size() == 0) { + if (vars.empty()) { return {}; } std::vector res; @@ -1176,7 +1176,7 @@ std::vector ExecutionContext::MultiOutput( const std::string& name) const { auto vars = MultiOutputVar(name); - if (vars.size() == 0) { + if (vars.empty()) { return {}; } std::vector res; @@ -3128,7 +3128,7 @@ void OperatorWithKernel::BuildPhiKernelContext( size_t start_idx = (i == 0 ? 0 : phi_kernel_context->InputRangeAt(i - 1).second); // deal with optional here - if ((it == ctx.inputs.end() || it->second.size() == 0) && + if ((it == ctx.inputs.end() || it->second.empty()) && (input_defs[i].type_index == std::type_index(typeid(paddle::optional)) || input_defs[i].type_index == @@ -3553,7 +3553,7 @@ void OperatorWithKernel::BuildPhiKernelContext( Type()); for (const auto& input_name : extra_input_names) { auto it = ctx.inputs.find(input_name); - if (it == ctx.inputs.end() || it->second.size() == 0) { + if (it == ctx.inputs.end() || it->second.empty()) { one_dnn_ctx->SetDnnInput(input_name, nullptr); } else { auto ins_vector = it->second; diff --git a/paddle/fluid/framework/parallel_executor.cc b/paddle/fluid/framework/parallel_executor.cc index 806b8570108b9..ba35de8dddfa5 100644 --- a/paddle/fluid/framework/parallel_executor.cc +++ b/paddle/fluid/framework/parallel_executor.cc @@ -137,7 +137,7 @@ class ParallelExecutorPrivate { * them. */ inline void SetSkipMemoryReuse(size_t scope_idx, const std::string &name) { - if (mem_opt_var_infos_.size() == 0) { + if (mem_opt_var_infos_.empty()) { VLOG(4) << "The mem_opt_var_infos_ is empty, maybe no memory " "optimization strategy is enabled"; return; @@ -673,7 +673,7 @@ ParallelExecutor::ParallelExecutor(const std::vector &places, const BuildStrategy &build_strategy, ir::Graph *graph) : member_(new ParallelExecutorPrivate(places, scope)) { - PADDLE_ENFORCE_EQ(places.size() > 0, + PADDLE_ENFORCE_EQ(!places.empty(), true, platform::errors::Unavailable( "NPU is not supported in ParallelExecutor.")); diff --git a/paddle/fluid/framework/phi_utils.cc b/paddle/fluid/framework/phi_utils.cc index 9881d479a75a2..01b28e364a5e7 100644 --- a/paddle/fluid/framework/phi_utils.cc +++ b/paddle/fluid/framework/phi_utils.cc @@ -306,7 +306,7 @@ phi::IntArray MakePhiIntArrayFromVar(const framework::Variable& variable) { // TODO(chentianyu03): Inplace with IntArray constructor phi::IntArray MakePhiIntArrayFromVarList( const std::vector& variable_list) { - if (variable_list.size() == 0) { + if (variable_list.empty()) { return phi::IntArray(); } auto expected_place = phi::TransToPhiPlace(phi::Backend::CPU); diff --git a/paddle/fluid/framework/program_converter.cc b/paddle/fluid/framework/program_converter.cc index 3bedde424adb9..b13aab38cbc05 100644 --- a/paddle/fluid/framework/program_converter.cc +++ b/paddle/fluid/framework/program_converter.cc @@ -89,7 +89,7 @@ void ConvertSetValueOp(OpDesc* op) { op->SetAttr("fp16_values", std::vector()); phi::DataType dtype = phi::DataType::FLOAT32; - if (values.size()) { + if (!values.empty()) { dtype = values.at(0).dtype(); } @@ -156,7 +156,7 @@ void ConvertSetValueOp(OpDesc* op) { if (op->HasAttr("bool_values")) { std::vector bool_values = PADDLE_GET_CONST(std::vector, op->GetAttr("bool_values", false)); - if (bool_values.size()) { + if (!bool_values.empty()) { values = WrapAsScalars(bool_values); } op->RemoveAttr("bool_values"); @@ -164,7 +164,7 @@ void ConvertSetValueOp(OpDesc* op) { if (op->HasAttr("fp32_values")) { std::vector fp32_values = PADDLE_GET_CONST(std::vector, op->GetAttr("fp32_values", false)); - if (fp32_values.size()) { + if (!fp32_values.empty()) { values = WrapAsScalars(fp32_values); } op->RemoveAttr("fp32_values"); @@ -172,7 +172,7 @@ void ConvertSetValueOp(OpDesc* op) { if (op->HasAttr("int32_values")) { std::vector int32_values = PADDLE_GET_CONST(std::vector, op->GetAttr("int32_values", false)); - if (int32_values.size()) { + if (!int32_values.empty()) { values = WrapAsScalars(int32_values); } op->RemoveAttr("int32_values"); @@ -180,7 +180,7 @@ void ConvertSetValueOp(OpDesc* op) { if (op->HasAttr("int64_values")) { std::vector int64_values = PADDLE_GET_CONST( std::vector, op->GetAttr("int64_values", false)); - if (int64_values.size()) { + if (!int64_values.empty()) { values = WrapAsScalars(int64_values); } op->RemoveAttr("int64_values"); @@ -188,7 +188,7 @@ void ConvertSetValueOp(OpDesc* op) { if (op->HasAttr("fp64_values")) { std::vector fp64_values = PADDLE_GET_CONST( std::vector, op->GetAttr("fp64_values", false)); - if (fp64_values.size()) { + if (!fp64_values.empty()) { values = WrapAsScalars(fp64_values); } op->RemoveAttr("fp64_values"); @@ -196,7 +196,7 @@ void ConvertSetValueOp(OpDesc* op) { if (op->HasAttr("fp16_values")) { std::vector fp16_values = PADDLE_GET_CONST(std::vector, op->GetAttr("fp16_values", false)); - if (fp16_values.size()) { + if (!fp16_values.empty()) { values = WrapAsScalars(fp16_values); } op->RemoveAttr("fp16_values"); diff --git a/paddle/fluid/framework/program_desc.cc b/paddle/fluid/framework/program_desc.cc index 1d044b9727c29..272ff43e6b299 100644 --- a/paddle/fluid/framework/program_desc.cc +++ b/paddle/fluid/framework/program_desc.cc @@ -263,7 +263,7 @@ void ProgramDesc::SetFetchHolderName(const std::string &fetch_holder_name) { std::string ProgramDesc::CachedHashString() { std::string serialize_str; - if (cached_hash_str_.size() == 0 || NeedUpdate()) { + if (cached_hash_str_.empty() || NeedUpdate()) { Flush(); desc_.SerializePartialToString(&serialize_str); // non-cryptographic is enough diff --git a/paddle/fluid/framework/pull_dense_worker.cc b/paddle/fluid/framework/pull_dense_worker.cc index 7b61052a20151..a46158c59ece1 100644 --- a/paddle/fluid/framework/pull_dense_worker.cc +++ b/paddle/fluid/framework/pull_dense_worker.cc @@ -203,7 +203,7 @@ void PullDenseWorker::PullDense(bool force_update) { ResetThreadVersion(tid); } } - if (pull_dense_status_.size() != 0) { + if (!pull_dense_status_.empty()) { Wait(&pull_dense_status_); } } diff --git a/paddle/fluid/framework/tensor_util.cc b/paddle/fluid/framework/tensor_util.cc index d8224cb0dd72b..6552a14a03fcc 100644 --- a/paddle/fluid/framework/tensor_util.cc +++ b/paddle/fluid/framework/tensor_util.cc @@ -959,7 +959,7 @@ std::ostream& operator<<(std::ostream& os, const LoD& lod) { } std::ostream& operator<<(std::ostream& os, const phi::DenseTensor& t) { - if (t.lod().size() > 0) { + if (!t.lod().empty()) { os << " - lod: " << t.lod() << "\n"; } diff --git a/paddle/fluid/framework/trainer.cc b/paddle/fluid/framework/trainer.cc index 2d8e567b65a7d..96bf42559d117 100644 --- a/paddle/fluid/framework/trainer.cc +++ b/paddle/fluid/framework/trainer.cc @@ -25,12 +25,12 @@ void TrainerBase::ParseDumpConfig(const TrainerDesc& desc) { dump_fields_path_ = desc.dump_fields_path(); need_dump_field_ = false; need_dump_param_ = false; - if (dump_fields_path_ == "") { + if (dump_fields_path_.empty()) { VLOG(2) << "dump_fields_path_ is empty"; return; } auto& file_list = dataset_ptr_->GetFileList(); - if (file_list.size() == 0) { + if (file_list.empty()) { VLOG(2) << "file_list is empty"; return; } diff --git a/paddle/fluid/framework/var_desc.cc b/paddle/fluid/framework/var_desc.cc index d2e8550dae716..b75becf3c5542 100644 --- a/paddle/fluid/framework/var_desc.cc +++ b/paddle/fluid/framework/var_desc.cc @@ -351,7 +351,7 @@ void VarDesc::SetAttr(const std::string &name, const Attribute &v) { // here if we meet this issue proto::AttrType attr_type = static_cast(v.index() - 1); if (attr_type == proto::AttrType::INTS && - PADDLE_GET_CONST(std::vector, v).size() == 0u) { + PADDLE_GET_CONST(std::vector, v).empty()) { // Find current attr via attr name and set the correct attribute value this->attrs_[name] = std::vector(); return; diff --git a/paddle/fluid/imperative/basic_engine.cc b/paddle/fluid/imperative/basic_engine.cc index a2cea4067a0ea..7f682e600232f 100644 --- a/paddle/fluid/imperative/basic_engine.cc +++ b/paddle/fluid/imperative/basic_engine.cc @@ -185,7 +185,7 @@ void BasicEngine::PrepareGradAccumulators( if (!var) continue; bool find_grad_node_of_var = false; - if (grad_pending_nodes.size()) { + if (!grad_pending_nodes.empty()) { // Because Inplace op overwrites the grad_node of the input grad_var. So // only the information of grad_pending_node can be used to find the // grad_node of grad_var. @@ -251,7 +251,7 @@ void BasicEngine::PrepareGradAccumulators( } } - if (!grad_pending_nodes.size() || !find_grad_node_of_var) { + if (grad_pending_nodes.empty() || !find_grad_node_of_var) { auto& accumulator = accumulators_[var.get()]; if (!accumulator) { if (FLAGS_sort_sum_gradient) { @@ -360,7 +360,7 @@ static void PerformBackwardInplace(const std::string& op_type, for (auto& p : ins) { if (p.first == pair.first) { // has at least one var - if (p.second.size() > 0 && p.second[0]) { + if (!p.second.empty() && p.second[0]) { auto& in_var = p.second[0]; VLOG(10) << p.first << " use_count: " << in_var.use_count(); // the refcount of var to be inplaced should be 1 @@ -378,7 +378,7 @@ static void PerformBackwardInplace(const std::string& op_type, } for (auto& p : *outs) { if (p.first == pair.second) { - if (p.second.size() > 0 && p.second[0]) { + if (!p.second.empty() && p.second[0]) { auto& out_var = p.second[0]; if (out_var->Type() == framework::proto::VarType::LOD_TENSOR) { out_tensor = @@ -460,7 +460,7 @@ void BasicEngine::Execute() { std::unique_ptr>::iterator iter; bool flag_find_grad = false; - if (grad_pending_nodes.size()) { + if (!grad_pending_nodes.empty()) { VLOG(10) << "Find gradient of var (" << var->Name() << ") with grad_node."; for (auto& grad_pending_node : grad_pending_nodes) { @@ -479,7 +479,7 @@ void BasicEngine::Execute() { << " in accumulators_with_grad_node_"; } } - if (!grad_pending_nodes.size() || !flag_find_grad) { + if (grad_pending_nodes.empty() || !flag_find_grad) { VLOG(10) << "Find gradient of var (" << var->Name() << ") with no grad_node."; iter = accumulators_.find(var.get()); diff --git a/paddle/fluid/inference/analysis/ir_pass_manager.cc b/paddle/fluid/inference/analysis/ir_pass_manager.cc index af677fc28eb6f..1e5a0fd844e45 100644 --- a/paddle/fluid/inference/analysis/ir_pass_manager.cc +++ b/paddle/fluid/inference/analysis/ir_pass_manager.cc @@ -90,9 +90,9 @@ void IRPassManager::CreatePasses(Argument *argument, // tuned trt dynamic_shape pass->Set("trt_tuned_dynamic_shape", new bool(argument->tensorrt_tuned_dynamic_shape())); - bool with_dynamic_shape = (argument->max_input_shape().size() > 0 && - argument->min_input_shape().size() > 0 && - argument->optim_input_shape().size() > 0) || + bool with_dynamic_shape = (!argument->max_input_shape().empty() && + !argument->min_input_shape().empty() && + !argument->optim_input_shape().empty()) || argument->tensorrt_tuned_dynamic_shape(); pass->Set("with_dynamic_shape", new bool(with_dynamic_shape)); diff --git a/paddle/fluid/inference/analysis/ir_passes/tensorrt_subgraph_pass.cc b/paddle/fluid/inference/analysis/ir_passes/tensorrt_subgraph_pass.cc index b7852c2df5d2b..1c46c048a7ac9 100644 --- a/paddle/fluid/inference/analysis/ir_passes/tensorrt_subgraph_pass.cc +++ b/paddle/fluid/inference/analysis/ir_passes/tensorrt_subgraph_pass.cc @@ -601,14 +601,14 @@ std::string TensorRtSubgraphPass::CreateTensorRTOp( op_desc->Flush(); std::unique_ptr calibrator; - if (enable_int8 && calibration_data.size() != 0) { + if (enable_int8 && !calibration_data.empty()) { calibrator.reset(new tensorrt::TRTInt8Calibrator(calibration_data)); LOG(INFO) << "RUN Paddle TRT int8 calibration mode..."; } // When in int8 mode and calibration_mode, the program just produce the // calibration table data. bool calibration_mode = - (enable_int8 && calibration_data.size() == 0 && use_calib_mode); + (enable_int8 && calibration_data.empty() && use_calib_mode); if (calibration_mode) { // calibraion mode means generate int8 calibration table data process. return calibration_engine_key; @@ -620,7 +620,7 @@ std::string TensorRtSubgraphPass::CreateTensorRTOp( // Check trt version for dynamic shape input. - if (min_input_shape.size() > 0 && TRT_VERSION < 6000) { + if (!min_input_shape.empty() && TRT_VERSION < 6000) { LOG_FIRST_N(WARNING, 1) << "You are using the dynamic size input mode of " "Paddle-TRT, but we found that the version of " "the TensorRT is less than 6.0, so we use the " diff --git a/paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.cc b/paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.cc index 65e149925e742..36398739483f1 100644 --- a/paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.cc +++ b/paddle/fluid/inference/analysis/passes/ir_params_sync_among_devices_pass.cc @@ -65,9 +65,9 @@ void IrParamsSyncAmongDevicesPass::CopyParamsToGpu(Argument *argument) { bool with_dynamic_shape = false; if (argument->Has("max_input_shape") && argument->Has("min_input_shape") && argument->Has("optim_input_shape")) { - with_dynamic_shape = (argument->max_input_shape().size() > 0 && - argument->min_input_shape().size() > 0 && - argument->optim_input_shape().size() > 0); + with_dynamic_shape = (!argument->max_input_shape().empty() && + !argument->min_input_shape().empty() && + !argument->optim_input_shape().empty()); } with_dynamic_shape = with_dynamic_shape || (argument->Has("tensorrt_tuned_dynamic_shape") && diff --git a/paddle/fluid/inference/api/analysis_predictor.cc b/paddle/fluid/inference/api/analysis_predictor.cc index 56652c2f42cb7..ad6ab5a7ef0eb 100644 --- a/paddle/fluid/inference/api/analysis_predictor.cc +++ b/paddle/fluid/inference/api/analysis_predictor.cc @@ -2220,7 +2220,7 @@ void AnalysisPredictor::HookCollectShapeRangeInfo() { framework::DDim dim = tensor.dims(); std::vector shape(dim.size()); for (size_t i = 0; i < shape.size(); ++i) shape[i] = dim[i]; - if (shape.size() >= 1) { + if (!shape.empty()) { shape_info_[input_name].emplace_back(shape); } else if (tensor.numel() > 0) { // This must be a zero dimension tensor. diff --git a/paddle/fluid/inference/lite/engine.cc b/paddle/fluid/inference/lite/engine.cc index d193bff8edde1..e6574da52d583 100644 --- a/paddle/fluid/inference/lite/engine.cc +++ b/paddle/fluid/inference/lite/engine.cc @@ -30,7 +30,7 @@ namespace paddle { namespace inference { namespace lite { -bool EngineManager::Empty() const { return engines_.size() == 0; } +bool EngineManager::Empty() const { return engines_.empty(); } bool EngineManager::Has(const std::string& name) const { if (engines_.count(name) == 0) { diff --git a/paddle/fluid/inference/tensorrt/convert/bilinear_interp_v2_op.cc b/paddle/fluid/inference/tensorrt/convert/bilinear_interp_v2_op.cc index 5501a02355855..bd9e53bd7fd1f 100644 --- a/paddle/fluid/inference/tensorrt/convert/bilinear_interp_v2_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/bilinear_interp_v2_op.cc @@ -60,7 +60,7 @@ class BilinearInterpolateV2OpConverter : public OpConverter { bool has_scale_input_attr = (resize_inputs.find("Scale") != resize_inputs.end()); bool has_scale_input = - has_scale_input_attr && (op_desc.Input("Scale").size() > 0); + has_scale_input_attr && (!op_desc.Input("Scale").empty()); if (has_scale_input) { auto* scale_var = scope.FindVar(op_desc.Input("Scale")[0]); auto* scale_tensor = scale_var->GetMutable(); @@ -90,7 +90,7 @@ class BilinearInterpolateV2OpConverter : public OpConverter { nvinfer1::ITensor* outsize_tensor = nullptr; if (engine_->with_dynamic_shape() && resize_inputs.find("OutSize") != resize_inputs.end()) { - if (op_desc.Input("OutSize").size() >= 1) { + if (!op_desc.Input("OutSize").empty()) { outsize_tensor = engine_->GetITensor(op_desc.Input("OutSize")[0]); } } diff --git a/paddle/fluid/inference/tensorrt/convert/conv2d_op.cc b/paddle/fluid/inference/tensorrt/convert/conv2d_op.cc index d81f7a1b63600..a8387e675984c 100644 --- a/paddle/fluid/inference/tensorrt/convert/conv2d_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/conv2d_op.cc @@ -135,7 +135,7 @@ void ConvertConv2d(TensorRTEngine* engine, layer->setStrideNd(nv_strides); layer->setPrePadding(nv_pre_paddings); - if (output_padding.size() > 0) { + if (!output_padding.empty()) { nv_post_paddings.d[0] -= output_padding[0]; nv_post_paddings.d[1] -= output_padding[1]; } diff --git a/paddle/fluid/inference/tensorrt/convert/conv3d_op.cc b/paddle/fluid/inference/tensorrt/convert/conv3d_op.cc index da9774e172756..1df92f0641040 100644 --- a/paddle/fluid/inference/tensorrt/convert/conv3d_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/conv3d_op.cc @@ -98,7 +98,7 @@ void ConvertConv3d(TensorRTEngine* engine, layer->setStrideNd(nv_strides); layer->setPrePadding(nv_pre_paddings); nvinfer1::Dims3 nv_post_paddings = nv_pre_paddings; - if (output_padding.size() > 0) { + if (!output_padding.empty()) { // Here is consistent with op_teller.cc #if IS_TRT_VERSION_GE(8400) nv_post_paddings.d[0] -= output_padding[0]; diff --git a/paddle/fluid/inference/tensorrt/convert/emb_eltwise_layernorm.cc b/paddle/fluid/inference/tensorrt/convert/emb_eltwise_layernorm.cc index 2eb2c99e7e7ba..dba8086f2952e 100644 --- a/paddle/fluid/inference/tensorrt/convert/emb_eltwise_layernorm.cc +++ b/paddle/fluid/inference/tensorrt/convert/emb_eltwise_layernorm.cc @@ -40,8 +40,8 @@ class EmbEltwiseLayerNormOpConverter : public OpConverter { framework::OpDesc op_desc(op, nullptr); auto pos_id_name = engine_->tensorrt_transformer_posid(); auto mask_id_name = engine_->tensorrt_transformer_maskid(); - bool flag_varseqlen = - engine_->use_varseqlen() && pos_id_name != "" && mask_id_name != ""; + bool flag_varseqlen = engine_->use_varseqlen() && !pos_id_name.empty() && + !mask_id_name.empty(); // bool with_fp16 = engine_->WithFp16() && // !engine_->disable_trt_plugin_fp16(); int hidden = 0; Declare inputs std::vector input_ids; diff --git a/paddle/fluid/inference/tensorrt/convert/expand_v2_op.cc b/paddle/fluid/inference/tensorrt/convert/expand_v2_op.cc index 377df302f4f9f..0efccce390a62 100644 --- a/paddle/fluid/inference/tensorrt/convert/expand_v2_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/expand_v2_op.cc @@ -36,11 +36,11 @@ class ExpandOpConverter : public OpConverter { if (op_type_ == "expand_v2") { if (inputs.find("Shape") != inputs.end() && - op_desc.Input("Shape").size() >= 1) { + !op_desc.Input("Shape").empty()) { shape_tensor = engine_->GetITensor(op_desc.Input("Shape")[0]); shape_rank = shape_tensor->getDimensions().nbDims; } else if (inputs.find("expand_shapes_tensor") != inputs.end() && - op_desc.Input("expand_shapes_tensor").size() >= 1) { + !op_desc.Input("expand_shapes_tensor").empty()) { int shape_size = op_desc.Input("expand_shapes_tensor").size(); std::vector shape_tensors; for (int i = 0; i < shape_size; ++i) { diff --git a/paddle/fluid/inference/tensorrt/convert/fill_constant_batch_size_like_op.cc b/paddle/fluid/inference/tensorrt/convert/fill_constant_batch_size_like_op.cc index 8939e6afc6106..69decf67d1e71 100644 --- a/paddle/fluid/inference/tensorrt/convert/fill_constant_batch_size_like_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/fill_constant_batch_size_like_op.cc @@ -44,7 +44,7 @@ class FillConstantBatchSizeLikeOpConverter : public OpConverter { PADDLE_GET_CONST(std::string, op_desc.GetAttr("str_value")); std::vector shape = PADDLE_GET_CONST(std::vector, op_desc.GetAttr("shape")); - if (str_value == "") { + if (str_value.empty()) { float value = PADDLE_GET_CONST(float, op_desc.GetAttr("value")); str_value = std::to_string(value); } diff --git a/paddle/fluid/inference/tensorrt/convert/fill_constant_op.cc b/paddle/fluid/inference/tensorrt/convert/fill_constant_op.cc index de946d4dcba0e..f6f476dc20485 100644 --- a/paddle/fluid/inference/tensorrt/convert/fill_constant_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/fill_constant_op.cc @@ -31,7 +31,7 @@ class FillConstantOpConverter : public OpConverter { PADDLE_GET_CONST(std::string, op_desc.GetAttr("str_value")); std::vector shape = PADDLE_GET_CONST(std::vector, op_desc.GetAttr("shape")); - if (str_value == "") { + if (str_value.empty()) { float value = PADDLE_GET_CONST(float, op_desc.GetAttr("value")); str_value = std::to_string(value); } diff --git a/paddle/fluid/inference/tensorrt/convert/multihead_matmul_op.cc b/paddle/fluid/inference/tensorrt/convert/multihead_matmul_op.cc index 4d267d923e92f..21095ed29eca6 100644 --- a/paddle/fluid/inference/tensorrt/convert/multihead_matmul_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/multihead_matmul_op.cc @@ -77,10 +77,10 @@ class MultiheadMatMulOpConverter : public OpConverter { nvinfer1::ILayer* layer = nullptr; auto output_name = op_desc.Output("Out")[0]; bool flag_varseqlen = engine_->use_varseqlen() && - engine_->tensorrt_transformer_posid() != "" && - engine_->tensorrt_transformer_maskid() != ""; + !engine_->tensorrt_transformer_posid().empty() && + !engine_->tensorrt_transformer_maskid().empty(); if (engine_->with_dynamic_shape()) { - if (engine_->tensorrt_transformer_maskid() != "" && + if (!engine_->tensorrt_transformer_maskid().empty() && engine_->precision() != phi::DataType::FLOAT32 && platform::GetGPUComputeCapability(platform::GetCurrentDeviceId()) >= 75) { diff --git a/paddle/fluid/inference/tensorrt/convert/multihead_matmul_roformer_op.cc b/paddle/fluid/inference/tensorrt/convert/multihead_matmul_roformer_op.cc index 5f019d9a12197..ea72e6941d47c 100644 --- a/paddle/fluid/inference/tensorrt/convert/multihead_matmul_roformer_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/multihead_matmul_roformer_op.cc @@ -81,8 +81,8 @@ class MultiheadMatMulRoformerOpConverter : public OpConverter { nvinfer1::ILayer* layer = nullptr; auto output_name = op_desc.Output("Out")[0]; bool flag_varseqlen = engine_->use_varseqlen() && - engine_->tensorrt_transformer_posid() != "" && - engine_->tensorrt_transformer_maskid() != ""; + !engine_->tensorrt_transformer_posid().empty() && + !engine_->tensorrt_transformer_maskid().empty(); if (engine_->with_dynamic_shape()) { if (flag_varseqlen) { diff --git a/paddle/fluid/inference/tensorrt/convert/one_hot_op.cc b/paddle/fluid/inference/tensorrt/convert/one_hot_op.cc index 0627be308e9b0..3ab318de2df4d 100644 --- a/paddle/fluid/inference/tensorrt/convert/one_hot_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/one_hot_op.cc @@ -61,7 +61,7 @@ class OneHotOpConverter : public OpConverter { } auto depth_name = op_desc.Input("depth_tensor"); - if (depth_name.size() == 0) { + if (depth_name.empty()) { const int depth = PADDLE_GET_CONST(int, op_desc.GetAttr("depth")); depth_tensor = Add1DConstantLayer(depth, "depth_tensor", true); } else { diff --git a/paddle/fluid/inference/tensorrt/convert/pad3d_op.cc b/paddle/fluid/inference/tensorrt/convert/pad3d_op.cc index efb4012b00ab0..a8a7a91e49a14 100644 --- a/paddle/fluid/inference/tensorrt/convert/pad3d_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/pad3d_op.cc @@ -35,7 +35,7 @@ class Pad3dOpConverter : public OpConverter { auto* input = engine_->GetITensor(op_desc.Input("X")[0]); nvinfer1::ITensor* paddings; - if (op_desc.HasInput("Paddings") && op_desc.Input("Paddings").size() > 0) { + if (op_desc.HasInput("Paddings") && !op_desc.Input("Paddings").empty()) { paddings = engine_->GetITensor(op_desc.Input("Paddings")[0]); } else { std::vector paddings_v = diff --git a/paddle/fluid/inference/tensorrt/convert/preln_emb_eltwise_layernorm.cc b/paddle/fluid/inference/tensorrt/convert/preln_emb_eltwise_layernorm.cc index fa98a208b4a82..afeacd5cd6b98 100644 --- a/paddle/fluid/inference/tensorrt/convert/preln_emb_eltwise_layernorm.cc +++ b/paddle/fluid/inference/tensorrt/convert/preln_emb_eltwise_layernorm.cc @@ -38,8 +38,8 @@ class PrelnEmbEltwiseLayerNormOpConverter : public OpConverter { auto pos_id_name = engine_->tensorrt_transformer_posid(); auto mask_id_name = engine_->tensorrt_transformer_maskid(); bool flag_prelayernorm = engine_->with_interleaved() && - engine_->use_varseqlen() && pos_id_name != "" && - mask_id_name != ""; + engine_->use_varseqlen() && !pos_id_name.empty() && + !mask_id_name.empty(); if (!flag_prelayernorm) { PADDLE_THROW(platform::errors::Fatal( diff --git a/paddle/fluid/inference/tensorrt/convert/reshape_op.cc b/paddle/fluid/inference/tensorrt/convert/reshape_op.cc index 9dba7aa26b5a5..92c592ee03212 100644 --- a/paddle/fluid/inference/tensorrt/convert/reshape_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/reshape_op.cc @@ -37,12 +37,12 @@ class ReshapeOpConverter : public OpConverter { bool one_input = false; if (engine_->with_dynamic_shape()) { if (op_desc.Inputs().find("ShapeTensor") != op_desc.Inputs().end() && - op_desc.Input("ShapeTensor").size() > 0) { + !op_desc.Input("ShapeTensor").empty()) { for (auto name : op_desc.Input("ShapeTensor")) concat_inputs.push_back(engine_->GetITensor(name)); real_shape_tensor = Concat(concat_inputs); } else if (op_desc.Inputs().find("Shape") != op_desc.Inputs().end() && - op_desc.Input("Shape").size() > 0) { + !op_desc.Input("Shape").empty()) { real_shape_tensor = engine_->GetITensor(op_desc.Input("Shape")[0]); } else { reshape_dim.nbDims = nbDims_num; diff --git a/paddle/fluid/inference/tensorrt/convert/scale_op.cc b/paddle/fluid/inference/tensorrt/convert/scale_op.cc index d75eb4128b2e5..0df7894929f8c 100644 --- a/paddle/fluid/inference/tensorrt/convert/scale_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/scale_op.cc @@ -60,7 +60,7 @@ class ScaleOpConverter : public OpConverter { auto scale_inputs = op_desc.Inputs(); if (scale_inputs.find("ScaleTensor") != scale_inputs.end() && - op_desc.Input("ScaleTensor").size()) { // has EndsTensor input + !op_desc.Input("ScaleTensor").empty()) { // has EndsTensor input has_scale_tensor = true; scale_tensor = engine_->GetITensor(op_desc.Input("ScaleTensor")[0]); is_scale_1 = false; diff --git a/paddle/fluid/inference/tensorrt/convert/set_value_op.cc b/paddle/fluid/inference/tensorrt/convert/set_value_op.cc index 9ba5a7a4d531f..3292df6b4a772 100644 --- a/paddle/fluid/inference/tensorrt/convert/set_value_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/set_value_op.cc @@ -14,14 +14,14 @@ limitations under the License. */ #include "paddle/fluid/inference/tensorrt/convert/op_converter.h" -#define GET_ATTR_FROM_VECTOR(attr_name__) \ - do { \ - std::vector vec_##attr_name__; \ - if (op_desc.HasAttr(#attr_name__)) { \ - vec_##attr_name__ = PADDLE_GET_CONST(std::vector, \ - op_desc.GetAttr(#attr_name__)); \ - if (vec_##attr_name__.size() > 0) attr_name__ = vec_##attr_name__[0]; \ - } \ +#define GET_ATTR_FROM_VECTOR(attr_name__) \ + do { \ + std::vector vec_##attr_name__; \ + if (op_desc.HasAttr(#attr_name__)) { \ + vec_##attr_name__ = PADDLE_GET_CONST(std::vector, \ + op_desc.GetAttr(#attr_name__)); \ + if (!vec_##attr_name__.empty()) attr_name__ = vec_##attr_name__[0]; \ + } \ } while (0) namespace paddle { @@ -50,7 +50,7 @@ class SetValueConverter : public OpConverter { std::vector decr_axes{decrease_axes.begin(), decrease_axes.end()}; auto value_rank = updates->getDimensions().nbDims; auto input_rank = inputs->getDimensions().nbDims; - if (decrease_axes.size() > 0 && value_rank != input_rank) { + if (!decrease_axes.empty() && value_rank != input_rank) { updates = Unsqueeze(updates, decr_axes); } diff --git a/paddle/fluid/inference/tensorrt/convert/skip_layernorm.cc b/paddle/fluid/inference/tensorrt/convert/skip_layernorm.cc index c3a78cdb9a83d..0cdb6088f3096 100644 --- a/paddle/fluid/inference/tensorrt/convert/skip_layernorm.cc +++ b/paddle/fluid/inference/tensorrt/convert/skip_layernorm.cc @@ -121,8 +121,8 @@ class SkipLayerNormOpConverter : public OpConverter { auto scale_weight = GetWeight("Scale").get(); nvinfer1::ILayer* layer = nullptr; bool flag_varseqlen = engine_->use_varseqlen() && - engine_->tensorrt_transformer_posid() != "" && - engine_->tensorrt_transformer_maskid() != ""; + !engine_->tensorrt_transformer_posid().empty() && + !engine_->tensorrt_transformer_maskid().empty(); if (flag_varseqlen && engine_->with_interleaved()) { VLOG(4) << "fused skip_layernorm op: use_varseqlen and with_interleaved"; if (!enable_int8) { diff --git a/paddle/fluid/inference/tensorrt/convert/slice_op.cc b/paddle/fluid/inference/tensorrt/convert/slice_op.cc index 07cd71e6d3679..9154fe61533a7 100644 --- a/paddle/fluid/inference/tensorrt/convert/slice_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/slice_op.cc @@ -63,13 +63,13 @@ class SliceOpConverter : public OpConverter { } auto slice_inputs = op_desc.Inputs(); if (slice_inputs.find("StartsTensor") != slice_inputs.end() && - op_desc.Input("StartsTensor").size()) { // has StartsTensor input + !op_desc.Input("StartsTensor").empty()) { // has StartsTensor input for (size_t i = 0; i < axes.size(); ++i) { starts_tensor[axes[i]] = GetEleTensorOfShape( engine_->GetITensor(op_desc.Input("StartsTensor")[0]), i); } } else if (slice_inputs.find("StartsTensorList") != slice_inputs.end() && - op_desc.Input("StartsTensorList").size()) { + !op_desc.Input("StartsTensorList").empty()) { for (size_t i = 0; i < axes.size(); ++i) { starts_tensor[axes[i]] = engine_->GetITensor(op_desc.Input("StartsTensorList")[i]); @@ -98,13 +98,13 @@ class SliceOpConverter : public OpConverter { start_tensor = Concat(starts_tensor); if (slice_inputs.find("EndsTensor") != slice_inputs.end() && - op_desc.Input("EndsTensor").size()) { // has EndsTensor input + !op_desc.Input("EndsTensor").empty()) { // has EndsTensor input for (size_t i = 0; i < axes.size(); ++i) { ends_tensor[axes[i]] = GetEleTensorOfShape( engine_->GetITensor(op_desc.Input("EndsTensor")[0]), i); } } else if (slice_inputs.find("EndsTensorList") != slice_inputs.end() && - op_desc.Input("EndsTensorList").size()) { + !op_desc.Input("EndsTensorList").empty()) { for (size_t i = 0; i < axes.size(); ++i) { ends_tensor[axes[i]] = engine_->GetITensor(op_desc.Input("EndsTensorList")[i]); @@ -138,7 +138,7 @@ class SliceOpConverter : public OpConverter { layer->setInput(1, *start_tensor); layer->setInput(2, *size_tensor); - if (decrease_axises.size() > 0) { + if (!decrease_axises.empty()) { std::vector gather_indices; for (int i = 0; i < trt_size_dims.nbDims; i++) { if (decrease_axises.end() != @@ -196,7 +196,7 @@ class SliceOpConverter : public OpConverter { nvinfer1::Dims real_trt_size_dims; real_trt_size_dims.nbDims = 0; - if (decrease_axises.size() > 0) { + if (!decrease_axises.empty()) { for (size_t i = 0; i < decrease_axises.size(); i++) { decrease_axises[i]--; } diff --git a/paddle/fluid/inference/tensorrt/convert/split_op.cc b/paddle/fluid/inference/tensorrt/convert/split_op.cc index e0ead88ad5b67..b12e58a536ef9 100644 --- a/paddle/fluid/inference/tensorrt/convert/split_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/split_op.cc @@ -55,7 +55,7 @@ class SplitOpConverter : public OpConverter { // need infer output_lengths if (inputs.find("SectionsTensorList") != inputs.end() && - op_desc.Input("SectionsTensorList").size() >= 1) { + !op_desc.Input("SectionsTensorList").empty()) { int32_t sections_size = op_desc.Input("SectionsTensorList").size(); std::vector sections_tensors; for (int32_t i = 0; i < sections_size; ++i) { diff --git a/paddle/fluid/inference/tensorrt/convert/squeeze2_op.cc b/paddle/fluid/inference/tensorrt/convert/squeeze2_op.cc index 3ec25c6919a41..0134b62aec229 100644 --- a/paddle/fluid/inference/tensorrt/convert/squeeze2_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/squeeze2_op.cc @@ -36,7 +36,7 @@ class Squeeze2OpConverter : public OpConverter { if (op_desc.HasAttr("axes")) { axes = PADDLE_GET_CONST(std::vector, op_desc.GetAttr("axes")); } - if (axes.size() == 0) { + if (axes.empty()) { for (int i = 0; i < input_dims.nbDims; i++) { if (input_dims.d[i] == -1) { PADDLE_THROW(platform::errors::InvalidArgument( diff --git a/paddle/fluid/inference/tensorrt/convert/strided_slice_op.cc b/paddle/fluid/inference/tensorrt/convert/strided_slice_op.cc index deecb913891b1..8b671e53c6673 100644 --- a/paddle/fluid/inference/tensorrt/convert/strided_slice_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/strided_slice_op.cc @@ -122,7 +122,7 @@ class StridedSliceOpConverter : public OpConverter { layer->setInput(2, *size_tensor); layer->setInput(3, *step_tensor); - if (decrease_axises.size() > 0) { + if (!decrease_axises.empty()) { std::vector gather_indices; for (int i = 0; i < trt_size_dims.nbDims; i++) { if (decrease_axises.end() != @@ -159,7 +159,7 @@ class StridedSliceOpConverter : public OpConverter { nvinfer1::Dims real_trt_size_dims; real_trt_size_dims.nbDims = 0; - if (decrease_axises.size() > 0) { + if (!decrease_axises.empty()) { for (size_t i = 0; i < decrease_axises.size(); i++) { decrease_axises[i]--; } diff --git a/paddle/fluid/inference/tensorrt/convert/tile_op.cc b/paddle/fluid/inference/tensorrt/convert/tile_op.cc index 5dd373e69d949..6b77fb1aae344 100644 --- a/paddle/fluid/inference/tensorrt/convert/tile_op.cc +++ b/paddle/fluid/inference/tensorrt/convert/tile_op.cc @@ -46,11 +46,11 @@ class TileOpConverter : public OpConverter { nvinfer1::ITensor* repeat_tensor = nullptr; int32_t repeat_rank = 0; if (inputs.find("RepeatTimes") != inputs.end() && - op_desc.Input("RepeatTimes").size() >= 1) { + !op_desc.Input("RepeatTimes").empty()) { repeat_tensor = engine_->GetITensor(op_desc.Input("RepeatTimes")[0]); repeat_rank = repeat_tensor->getDimensions().d[0]; } else if (inputs.find("repeat_times_tensor") != inputs.end() && - op_desc.Input("repeat_times_tensor").size() >= 1) { + !op_desc.Input("repeat_times_tensor").empty()) { int32_t repeat_size = op_desc.Input("repeat_times_tensor").size(); std::vector repeat_tensors; for (int32_t i = 0; i < repeat_size; ++i) { diff --git a/paddle/fluid/inference/tensorrt/dynamic_shape_infermeta.cc b/paddle/fluid/inference/tensorrt/dynamic_shape_infermeta.cc index a6f58a10086c7..11a909cfb3bc3 100644 --- a/paddle/fluid/inference/tensorrt/dynamic_shape_infermeta.cc +++ b/paddle/fluid/inference/tensorrt/dynamic_shape_infermeta.cc @@ -490,7 +490,7 @@ nvinfer1::DimsExprs PNormInferMeta( for (int i = 0; i < x_dim.nbDims; ++i) { if (i != axis) reduce_dims.emplace_back(x_dim.d[i]); } - if (reduce_dims.size() == 0) { + if (reduce_dims.empty()) { reduce_dims.emplace_back(expr_builder.constant(1)); } } @@ -728,11 +728,11 @@ nvinfer1::DimsExprs Conv2dTransposeInferMeta( CHECK_EQ(padding_algorithm == "EXPLICIT", true); CHECK_EQ(data_format == "NCHW", true); - CHECK_EQ(output_size.size() == 0, true); + CHECK_EQ(output_size.empty(), true); CHECK_EQ(paddings.size() == 2, true); CHECK_EQ(x_dims.nbDims == 4, true); CHECK_EQ(x_dims.nbDims == filter_dims.nbDims, true); - CHECK_EQ(output_padding.size() == 0, true); + CHECK_EQ(output_padding.empty(), true); int stride_size = strides.size(); for (int i = 0; i < stride_size; ++i) { @@ -742,11 +742,11 @@ nvinfer1::DimsExprs Conv2dTransposeInferMeta( int in_sub_stride_size = x_dims.nbDims - stride_size; CHECK_EQ(in_sub_stride_size == 2, true); - if (output_size.size()) { + if (!output_size.empty()) { CHECK_EQ(output_size.size() == strides.size(), true); } - if (output_padding.size()) { + if (!output_padding.empty()) { CHECK_EQ(strides.size() == output_padding.size(), true); } diff --git a/paddle/fluid/inference/tensorrt/op_teller.cc b/paddle/fluid/inference/tensorrt/op_teller.cc index ff6b49e79c9c1..ee20184c86194 100644 --- a/paddle/fluid/inference/tensorrt/op_teller.cc +++ b/paddle/fluid/inference/tensorrt/op_teller.cc @@ -171,7 +171,7 @@ struct SimpleOpTypeSetTeller : public Teller { // Can't get feed op's TensorDesc if (op_type != "feed" && var_desc && !var_desc->Persistable()) { const auto shape = var_desc->GetShape(); - if (shape.size() == 1 || shape.size() == 0) return false; + if (shape.size() == 1 || shape.empty()) return false; } } } @@ -196,7 +196,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto x_var_name = desc.Input("X")[0]; auto* x_var_desc = block->FindVar(x_var_name); const auto x_shape = x_var_desc->GetShape(); - if (x_shape.size() == 0 && unary_list.find(op_type) != unary_list.end()) { + if (x_shape.empty() && unary_list.find(op_type) != unary_list.end()) { VLOG(3) << op_type << " op does not support 0 dim input when TensorRT < 8.6."; return false; @@ -462,7 +462,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto* x_var_desc = block->FindVar(x_var_name); const auto x_shape = x_var_desc->GetShape(); - if (with_dynamic_shape && (x_shape.size() == 1 || x_shape.size() == 0)) { + if (with_dynamic_shape && (x_shape.size() == 1 || x_shape.empty())) { int axis = desc.HasAttr("axis") ? PADDLE_GET_CONST(int, desc.GetAttr("axis")) : -1; @@ -497,7 +497,7 @@ struct SimpleOpTypeSetTeller : public Teller { } auto concat_inputs = desc.Inputs(); if (concat_inputs.find("AxisTensor") != concat_inputs.end()) { - if (desc.Input("AxisTensor").size() >= 1) { + if (!desc.Input("AxisTensor").empty()) { return false; } } @@ -601,7 +601,7 @@ struct SimpleOpTypeSetTeller : public Teller { if (op_type == "gather") { auto gather_inputs = desc.Inputs(); if (gather_inputs.find("Axis") != gather_inputs.end()) { - if (desc.Input("Axis").size() >= 1) { + if (!desc.Input("Axis").empty()) { return false; } } @@ -802,7 +802,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto multiclass_nms_inputs = desc.Inputs(); if (multiclass_nms_inputs.find("RoisNum") != multiclass_nms_inputs.end()) { - if (desc.Input("RoisNum").size() >= 1) { + if (!desc.Input("RoisNum").empty()) { return false; } } @@ -944,7 +944,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto resize_inputs = desc.Inputs(); if (resize_inputs.find("SizeTensor") != resize_inputs.end()) { - if (desc.Input("SizeTensor").size() >= 1) { + if (!desc.Input("SizeTensor").empty()) { VLOG(3) << "The Paddle-TRT doesn't support the SizeTensor for op_type " << op_type; @@ -1036,7 +1036,7 @@ struct SimpleOpTypeSetTeller : public Teller { if (desc.HasAttr("axes")) { axes = PADDLE_GET_CONST(std::vector, desc.GetAttr("axes")); } - if (axes.size() == 0) { + if (axes.empty()) { auto* block = desc.Block(); if (block) { auto input_var_name = desc.Input("X")[0]; @@ -1053,7 +1053,7 @@ struct SimpleOpTypeSetTeller : public Teller { } } } - if (axes.size() == 0) { + if (axes.empty()) { VLOG(3) << "The necessary attributes of the squeeze2 operator axes is " "missing."; @@ -1074,7 +1074,7 @@ struct SimpleOpTypeSetTeller : public Teller { if (desc.HasAttr("axes")) { axes = PADDLE_GET_CONST(std::vector, desc.GetAttr("axes")); } - if (axes.size() == 0) { + if (axes.empty()) { VLOG(3) << "The necessary attributes of the squeeze2 operator axes is " "missing."; return false; @@ -1102,7 +1102,7 @@ struct SimpleOpTypeSetTeller : public Teller { } auto batch_norm_inputs = desc.Inputs(); if (batch_norm_inputs.find("MomentumTensor") != batch_norm_inputs.end()) { - if (desc.Input("MomentumTensor").size() >= 1) { + if (!desc.Input("MomentumTensor").empty()) { return false; } } @@ -1133,12 +1133,12 @@ struct SimpleOpTypeSetTeller : public Teller { } auto split_inputs = desc.Inputs(); if (split_inputs.find("AxisTensor") != split_inputs.end()) { - if (desc.Input("AxisTensor").size() >= 1) { + if (!desc.Input("AxisTensor").empty()) { return false; } } if (split_inputs.find("SectionsTensorList") != split_inputs.end()) { - if (desc.Input("SectionsTensorList").size() >= 1) { + if (!desc.Input("SectionsTensorList").empty()) { if (!with_dynamic_shape) { return false; } @@ -1174,7 +1174,7 @@ struct SimpleOpTypeSetTeller : public Teller { output_lengths = PADDLE_GET_CONST(std::vector, desc.GetAttr("sections")); } - if (output_lengths.size() == 0 && num == 0) { + if (output_lengths.empty() && num == 0) { VLOG(3) << "sections and num cannot be equal to 0 at the same time"; return false; } @@ -1192,7 +1192,7 @@ struct SimpleOpTypeSetTeller : public Teller { VLOG(3) << "The (" << axis << ") dim of input should not be -1"; return false; } - if (output_lengths.size() == 0) { + if (output_lengths.empty()) { if (num > 0) { int64_t in_axis_dim = x_shape[axis]; if (in_axis_dim % num != 0) { @@ -1216,7 +1216,7 @@ struct SimpleOpTypeSetTeller : public Teller { if (op_type == "scale") { auto scale_inputs = desc.Inputs(); if (scale_inputs.find("ScaleTensor") != scale_inputs.end()) { - if (desc.Input("ScaleTensor").size() >= 1) { + if (!desc.Input("ScaleTensor").empty()) { return false; } } @@ -1289,7 +1289,7 @@ struct SimpleOpTypeSetTeller : public Teller { // not support following four inputs for rnn in paddle-trt auto rnn_inputs = desc.Inputs(); if (rnn_inputs.find("SequenceLength") != rnn_inputs.end()) { - if (desc.Input("SequenceLength").size()) { + if (!desc.Input("SequenceLength").empty()) { return false; } } @@ -1388,7 +1388,7 @@ struct SimpleOpTypeSetTeller : public Teller { // not support following four inputs for slice in paddle-trt auto slice_inputs = desc.Inputs(); // its size == 5 if (slice_inputs.find("StartsTensor") != slice_inputs.end() && - desc.Input("StartsTensor").size()) { + !desc.Input("StartsTensor").empty()) { VLOG(3) << "The Slice has StartsTensor input."; } else { if (!desc.HasAttr("starts")) { @@ -1407,7 +1407,7 @@ struct SimpleOpTypeSetTeller : public Teller { } } if (slice_inputs.find("EndsTensor") != slice_inputs.end() && - desc.Input("EndsTensor").size()) { + !desc.Input("EndsTensor").empty()) { VLOG(3) << "The Slice has EndsTensor input."; } else { if (!desc.HasAttr("ends")) { @@ -1690,15 +1690,15 @@ struct SimpleOpTypeSetTeller : public Teller { auto fill_constant_inputs = desc.Inputs(); if (fill_constant_inputs.find("ValueTensor") != fill_constant_inputs.end()) { - if (desc.Input("ValueTensor").size()) return false; + if (!desc.Input("ValueTensor").empty()) return false; } if (fill_constant_inputs.find("ShapeTensor") != fill_constant_inputs.end()) { - if (desc.Input("ShapeTensor").size()) return false; + if (!desc.Input("ShapeTensor").empty()) return false; } if (fill_constant_inputs.find("ShapeTensorList") != fill_constant_inputs.end()) { - if (desc.Input("ShapeTensorList").size()) return false; + if (!desc.Input("ShapeTensorList").empty()) return false; } int dtype = desc.HasAttr("dtype") ? PADDLE_GET_CONST(int, desc.GetAttr("dtype")) @@ -1844,7 +1844,7 @@ struct SimpleOpTypeSetTeller : public Teller { return false; } auto alpha_shape = alpha_var->GetShape(); - if (!with_dynamic_shape && alpha_shape.size() == 0) { + if (!with_dynamic_shape && alpha_shape.empty()) { VLOG(3) << op_type << " op does not support alpha's dim is 0 in tensorrt " "static shape mode."; @@ -1897,7 +1897,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto roi_align_inputs = desc.Inputs(); if (roi_align_inputs.find("RoisNum") != roi_align_inputs.end()) { - if (desc.Input("RoisNum").size() >= 1) { + if (!desc.Input("RoisNum").empty()) { return false; } } @@ -1941,7 +1941,7 @@ struct SimpleOpTypeSetTeller : public Teller { return false; #elif !IS_TRT_VERSION_GE(8600) const auto x_shape = x_var_desc->GetShape(); - if (x_shape.size() == 0) { + if (x_shape.empty()) { VLOG(3) << "BOOL type does not support 0 dim input when TensorRT < 8.6."; return false; @@ -1975,7 +1975,7 @@ struct SimpleOpTypeSetTeller : public Teller { } auto one_hot_inputs = desc.Inputs(); if (one_hot_inputs.find("depth_tensor") != one_hot_inputs.end()) { - if (desc.Input("depth_tensor").size() != 0) { + if (!desc.Input("depth_tensor").empty()) { return true; } } @@ -2127,12 +2127,12 @@ struct SimpleOpTypeSetTeller : public Teller { // Static shape does not support the input tensors: Shape and ShapeTensor auto reshape_inputs = desc.Inputs(); if (reshape_inputs.find("Shape") != reshape_inputs.end()) { - if (desc.Input("Shape").size() >= 1) { + if (!desc.Input("Shape").empty()) { return false; } } if (reshape_inputs.find("ShapeTensor") != reshape_inputs.end()) { - if (desc.Input("ShapeTensor").size() >= 1) { + if (!desc.Input("ShapeTensor").empty()) { return false; } } @@ -2166,12 +2166,12 @@ struct SimpleOpTypeSetTeller : public Teller { // Paddle-TRT does not support the input tensors: Min and Max auto clip_inputs = desc.Inputs(); if (clip_inputs.find("Min") != clip_inputs.end()) { - if (desc.Input("Min").size() >= 1) { + if (!desc.Input("Min").empty()) { return false; } } if (clip_inputs.find("Max") != clip_inputs.end()) { - if (desc.Input("Max").size() >= 1) { + if (!desc.Input("Max").empty()) { return false; } } @@ -2186,7 +2186,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto x_var_name = desc.Input("X")[0]; auto* x_var_desc = block->FindVar(x_var_name); const auto x_shape = x_var_desc->GetShape(); - if (!with_dynamic_shape && (x_shape.size() == 1 || x_shape.size() == 0)) { + if (!with_dynamic_shape && (x_shape.size() == 1 || x_shape.empty())) { VLOG(3) << op_type << " op does not support input's dim is 1 or 0 in tensorrt " "static shape mode."; @@ -2267,12 +2267,12 @@ struct SimpleOpTypeSetTeller : public Teller { auto tile_inputs = desc.Inputs(); if (!with_dynamic_shape) { if (tile_inputs.find("repeat_times_tensor") != tile_inputs.end()) { - if (desc.Input("repeat_times_tensor").size() >= 1) { + if (!desc.Input("repeat_times_tensor").empty()) { return false; } } if (tile_inputs.find("RepeatTimes") != tile_inputs.end()) { - if (desc.Input("RepeatTimes").size() >= 1) { + if (!desc.Input("RepeatTimes").empty()) { return false; } } @@ -2392,7 +2392,7 @@ struct SimpleOpTypeSetTeller : public Teller { auto x_var_name = desc.Input("X")[0]; auto* x_var_desc = block->FindVar(x_var_name); const auto x_shape = x_var_desc->GetShape(); - if (!with_dynamic_shape && (x_shape.size() == 1 || x_shape.size() == 0)) { + if (!with_dynamic_shape && (x_shape.size() == 1 || x_shape.empty())) { VLOG(3) << op_type << " op does not support input's dim is 1 or 0 in tensorrt " "static shape mode."; @@ -2406,17 +2406,17 @@ struct SimpleOpTypeSetTeller : public Teller { #endif auto inputs = desc.Inputs(); if (inputs.find("StartsTensorList") != inputs.end()) { - if (desc.Input("StartsTensorList").size() >= 1) { + if (!desc.Input("StartsTensorList").empty()) { return false; } } if (inputs.find("EndsTensorList") != inputs.end()) { - if (desc.Input("EndsTensorList").size() >= 1) { + if (!desc.Input("EndsTensorList").empty()) { return false; } } if (inputs.find("StepsTensorList") != inputs.end()) { - if (desc.Input("StepsTensorList").size() >= 1) { + if (!desc.Input("StepsTensorList").empty()) { return false; } } diff --git a/paddle/fluid/ir/transforms/pd_op_to_kernel_pass.cc b/paddle/fluid/ir/transforms/pd_op_to_kernel_pass.cc index d31d316ac222c..17ed6dd381c06 100644 --- a/paddle/fluid/ir/transforms/pd_op_to_kernel_pass.cc +++ b/paddle/fluid/ir/transforms/pd_op_to_kernel_pass.cc @@ -62,7 +62,7 @@ phi::KernelKey GetKernelKey( auto attr_map = op->attributes(); auto& data_type_info = op_info_parser->OpRuntimeInfo().kernel_key_dtype; - if (data_type_info.size() > 0 && data_type_info[0] != "") { + if (!data_type_info.empty() && !data_type_info[0].empty()) { // only support single input and attribute auto slot_name = data_type_info[0]; auto& input_map = op_info_parser->InputName2Id(); diff --git a/paddle/fluid/ir_adaptor/translator/op_translator.cc b/paddle/fluid/ir_adaptor/translator/op_translator.cc index ddd8feac29af0..4b3a242394cbd 100644 --- a/paddle/fluid/ir_adaptor/translator/op_translator.cc +++ b/paddle/fluid/ir_adaptor/translator/op_translator.cc @@ -90,7 +90,7 @@ inline bool IsInplace(const OpDesc& op_desc) { bool inplace = false; auto input_names = op_desc.InputArgumentNames(); auto output_names = op_desc.OutputArgumentNames(); - if (input_names.size() == 0 || output_names.size() == 0) { + if (input_names.empty() || output_names.empty()) { return inplace; } @@ -103,7 +103,7 @@ inline bool IsInplace(const OpDesc& op_desc) { output_names.end(), std::back_inserter(name_intersection)); - if (name_intersection.size() > 0) { + if (!name_intersection.empty()) { std::string redundant_variables = std::accumulate( std::next(name_intersection.begin()), name_intersection.end(), @@ -381,7 +381,7 @@ std::vector OpTranscriber::GenerateOperationInput( legacy_input_vars = op_desc.Input(legacy_input_name, true); } - if (legacy_input_vars.size() == 0) { + if (legacy_input_vars.empty()) { if (info.optional) { op_inputs.push_back(ir::OpResult(nullptr)); continue; @@ -390,7 +390,7 @@ std::vector OpTranscriber::GenerateOperationInput( VLOG(10) << "[op:" << op_desc.Type() << "][input]" << info.name << " " << legacy_input_name << " " << legacy_input_vars.size(); - if (legacy_input_vars.size() == 0 && mutable_attributes != nullptr && + if (legacy_input_vars.empty() && mutable_attributes != nullptr && mutable_attributes->count(info.name) != 0) { const auto& candidate_var_names = op_normalizer.GetMutableAttributeInfos(op_desc.Type(), info.name); @@ -400,7 +400,7 @@ std::vector OpTranscriber::GenerateOperationInput( << var_name << "]"; if (op_desc.HasInput(var_name)) { legacy_input_vars = op_desc.Input(var_name, true); - if (legacy_input_vars.size() == 0) continue; + if (legacy_input_vars.empty()) continue; found_candidate_var = true; break; } @@ -511,7 +511,7 @@ OpTranscriber::GenerateOperationOutput(ir::IrContext* ctx, << "[" << op_desc.Type() << "]" << info.name << " :" << info.type_name << " " << legacy_output_name << " " << legacy_output_vars.size(); - if (legacy_output_vars.size() == 0) { + if (legacy_output_vars.empty()) { op_output_types.push_back(ir::Type(nullptr)); continue; } @@ -855,7 +855,7 @@ ir::OpResult TranslateDropOutStateIn(ir::IrContext* ctx, legacy_output_vars = op_desc.Output(legacy_output_name); } - if (legacy_output_vars.size() == 0) { + if (legacy_output_vars.empty()) { VLOG(3) << "[input translating] not find output variable: DropoutState"; return ir::OpResult(nullptr); } diff --git a/paddle/fluid/memory/allocation/mmap_allocator.cc b/paddle/fluid/memory/allocation/mmap_allocator.cc index 1467d4b81081d..ceda4ee578cee 100644 --- a/paddle/fluid/memory/allocation/mmap_allocator.cc +++ b/paddle/fluid/memory/allocation/mmap_allocator.cc @@ -348,7 +348,7 @@ int MemoryMapAllocationPool::FindFromCache(const int &flag, for (size_t idx = 0; idx < memory_map_allocations_.size(); idx++) { if (memory_map_allocations_.at(idx).flags_ == flag && memory_map_allocations_.at(idx).data_size_ == data_size) { - if (file_name == "" || + if (file_name.empty() || memory_map_allocations_.at(idx).file_name_ == file_name) { if (!check_refcount || reinterpret_cast( memory_map_allocations_.at(idx).mmap_ptr_) diff --git a/paddle/fluid/operators/collective/send_v2_op.cc b/paddle/fluid/operators/collective/send_v2_op.cc index 5f1f766316c6d..9a52b9996aea0 100644 --- a/paddle/fluid/operators/collective/send_v2_op.cc +++ b/paddle/fluid/operators/collective/send_v2_op.cc @@ -45,7 +45,7 @@ class SendOpV2 : public framework::OperatorWithKernel { auto t_arr = var->Get(); // NOTE(sandyhouse): Support an empty tensor array as Input. // And set the kernel type is float. - if (t_arr.size() == 0) { + if (t_arr.empty()) { return phi::KernelKey(framework::proto::VarType::FP32, ctx.GetPlace()); } } diff --git a/paddle/fluid/operators/controlflow/conditional_block_op.cc b/paddle/fluid/operators/controlflow/conditional_block_op.cc index 156ba70467380..f3e847aa15ff2 100644 --- a/paddle/fluid/operators/controlflow/conditional_block_op.cc +++ b/paddle/fluid/operators/controlflow/conditional_block_op.cc @@ -308,7 +308,7 @@ class ConditionalBlockGradOp : public ConditionalOp { const auto &input_tensors = input_var->Get(); auto *outside_tensors = outside_var->GetMutable(); - if (outside_tensors->size() == 0U) { + if (outside_tensors->empty()) { outside_tensors->resize(input_tensors.size()); } PADDLE_ENFORCE_EQ(input_tensors.size(), diff --git a/paddle/fluid/operators/detection/bipartite_match_op.cc b/paddle/fluid/operators/detection/bipartite_match_op.cc index 29b732536437d..28fb53c2bd261 100644 --- a/paddle/fluid/operators/detection/bipartite_match_op.cc +++ b/paddle/fluid/operators/detection/bipartite_match_op.cc @@ -113,7 +113,7 @@ class BipartiteMatchKernel : public framework::OpKernel { for (int i = 0; i < row; ++i) { row_pool.push_back(i); } - while (row_pool.size() > 0) { + while (!row_pool.empty()) { int max_idx = -1; int max_row_idx = -1; T max_dist = -1; @@ -202,10 +202,10 @@ class BipartiteMatchKernel : public framework::OpKernel { auto col = dist_mat->dims()[1]; - int64_t n = dist_mat->lod().size() == 0UL + int64_t n = dist_mat->lod().empty() ? 1 : static_cast(dist_mat->lod().back().size() - 1); - if (dist_mat->lod().size()) { + if (!dist_mat->lod().empty()) { PADDLE_ENFORCE_EQ( dist_mat->lod().size(), 1UL, diff --git a/paddle/fluid/operators/detection/locality_aware_nms_op.cc b/paddle/fluid/operators/detection/locality_aware_nms_op.cc index dc512c9f8394d..8412f154f3726 100644 --- a/paddle/fluid/operators/detection/locality_aware_nms_op.cc +++ b/paddle/fluid/operators/detection/locality_aware_nms_op.cc @@ -195,7 +195,7 @@ class LocalityAwareNMSKernel : public framework::OpKernel { selected_indices->clear(); - while (sorted_indices.size() != 0) { + while (!sorted_indices.empty()) { const int idx = sorted_indices.front().second; bool keep = true; for (size_t k = 0; k < selected_indices->size(); ++k) { diff --git a/paddle/fluid/operators/detection/multiclass_nms_op.cc b/paddle/fluid/operators/detection/multiclass_nms_op.cc index c2a967fff9f9f..e263c418f9956 100644 --- a/paddle/fluid/operators/detection/multiclass_nms_op.cc +++ b/paddle/fluid/operators/detection/multiclass_nms_op.cc @@ -171,7 +171,7 @@ class MultiClassNMSKernel : public framework::OpKernel { T adaptive_threshold = nms_threshold; const T* bbox_data = bbox.data(); - while (sorted_indices.size() != 0) { + while (!sorted_indices.empty()) { const int idx = sorted_indices.front().second; bool keep = true; for (size_t k = 0; k < selected_indices->size(); ++k) { diff --git a/paddle/fluid/operators/detection/retinanet_detection_output_op.cc b/paddle/fluid/operators/detection/retinanet_detection_output_op.cc index 1e42809fa5909..3cb44444e8d2a 100644 --- a/paddle/fluid/operators/detection/retinanet_detection_output_op.cc +++ b/paddle/fluid/operators/detection/retinanet_detection_output_op.cc @@ -267,7 +267,7 @@ class RetinanetDetectionOutputKernel : public framework::OpKernel { selected_indices->clear(); T adaptive_threshold = nms_threshold; - while (sorted_indices.size() != 0) { + while (!sorted_indices.empty()) { const int idx = sorted_indices.front().second; bool keep = true; for (size_t k = 0; k < selected_indices->size(); ++k) { diff --git a/paddle/fluid/operators/fused/conv_fusion_op.cc b/paddle/fluid/operators/fused/conv_fusion_op.cc index 8f9cc4be69938..d5f718d82ec75 100644 --- a/paddle/fluid/operators/fused/conv_fusion_op.cc +++ b/paddle/fluid/operators/fused/conv_fusion_op.cc @@ -151,7 +151,7 @@ class Conv2DFusionOp : public framework::OperatorWithKernel { std::vector split_channels = ctx->Attrs().Get>("split_channels"); - if (split_channels.size()) { + if (!split_channels.empty()) { OP_INOUT_CHECK( ctx->HasOutputs("Outputs"), "Output", "Outputs", "Conv2DFusion"); PADDLE_ENFORCE_EQ( diff --git a/paddle/fluid/operators/fused/fused_seqpool_cvm_op.cc b/paddle/fluid/operators/fused/fused_seqpool_cvm_op.cc index aa31af5c58427..3b086dfd98cf1 100644 --- a/paddle/fluid/operators/fused/fused_seqpool_cvm_op.cc +++ b/paddle/fluid/operators/fused/fused_seqpool_cvm_op.cc @@ -78,7 +78,7 @@ class FusedSeqpoolCVMOp : public framework::OperatorWithKernel { PADDLE_GET(framework::Variable*, inputs_tensor[i]); const auto& x_tensor = x_var->Get(); const auto& x_lod = x_tensor.lod(); - if (x_lod.size() > 0) { + if (!x_lod.empty()) { cur_batch_size = x_lod[0].size() - 1; } else { cur_batch_size = x_tensor.dims()[0]; diff --git a/paddle/fluid/operators/generator/get_expected_kernel_func.cc b/paddle/fluid/operators/generator/get_expected_kernel_func.cc index aef9434ef0a27..0ce3688e717e0 100644 --- a/paddle/fluid/operators/generator/get_expected_kernel_func.cc +++ b/paddle/fluid/operators/generator/get_expected_kernel_func.cc @@ -79,7 +79,7 @@ phi::KernelKey GetCheckFiniteAndUnscaleExpectedKernelType( const framework::ExecutionContext& ctx, const framework::OperatorWithKernel* op_ptr) { auto dtype = framework::proto::VarType::FP32; - if (ctx.MultiInputVar("X").size() >= 1) { + if (!ctx.MultiInputVar("X").empty()) { dtype = op_ptr->IndicateVarDataType(ctx, "X"); } return phi::KernelKey(dtype, ctx.GetPlace()); @@ -161,7 +161,7 @@ phi::KernelKey GetAssignExpectedKernelType( auto t_arr = var->Get(); // NOTE(liym27): Support an empty tensor array as Input. // And set the kernel type is float. - if (t_arr.size() == 0) { + if (t_arr.empty()) { return phi::KernelKey(framework::proto::VarType::FP32, ctx.device_context().GetPlace()); } @@ -302,7 +302,7 @@ phi::KernelKey GetUpdateLossScalingExpectedKernelType( const framework::ExecutionContext& ctx, const framework::OperatorWithKernel* op_ptr) { auto dtype = framework::proto::VarType::FP32; - if (ctx.MultiInputVar("X").size() >= 1) { + if (!ctx.MultiInputVar("X").empty()) { dtype = op_ptr->IndicateVarDataType(ctx, "X"); } return phi::KernelKey(dtype, ctx.GetPlace()); diff --git a/paddle/fluid/operators/mkldnn/reshape_mkldnn_op.cc b/paddle/fluid/operators/mkldnn/reshape_mkldnn_op.cc index e2fc1c19f8e39..b7a33edb82a00 100644 --- a/paddle/fluid/operators/mkldnn/reshape_mkldnn_op.cc +++ b/paddle/fluid/operators/mkldnn/reshape_mkldnn_op.cc @@ -134,7 +134,7 @@ class ReshapeMKLDNNKernel : public framework::OpKernel { framework::DDim& out_dims) const { // NOLINT auto list_new_shape_tensor = ctx.MultiInput("ShapeTensor"); - if (list_new_shape_tensor.size() > 0) { + if (!list_new_shape_tensor.empty()) { auto new_shape = extract_shape(list_new_shape_tensor); out_dims = ValidateShape(new_shape, x_dims); } else if (ctx.HasInput("Shape")) { diff --git a/paddle/fluid/operators/pscore/send_op.cc b/paddle/fluid/operators/pscore/send_op.cc index e504d975b6a7b..f32f50937906b 100644 --- a/paddle/fluid/operators/pscore/send_op.cc +++ b/paddle/fluid/operators/pscore/send_op.cc @@ -50,7 +50,7 @@ class SendOp : public framework::OperatorBase { // for memory_dense_table, distributed_push_sparse op for push sparse in // async - if (is_sparse == 0 && send_varnames.size() >= 1 && + if (is_sparse == 0 && !send_varnames.empty() && send_varnames[0] != "@PS_STEP_COUNTER@") { auto fleet = paddle::distributed::FleetWrapper::GetInstance(); std::vector<::std::future> status; diff --git a/paddle/fluid/pybind/eager_legacy_op_function_generator.cc b/paddle/fluid/pybind/eager_legacy_op_function_generator.cc index c1ebc1b998b5a..ece79bd33b719 100644 --- a/paddle/fluid/pybind/eager_legacy_op_function_generator.cc +++ b/paddle/fluid/pybind/eager_legacy_op_function_generator.cc @@ -224,7 +224,7 @@ std::string GenerateOpFunctionsBody( output.duplicable() ? OUT_VAR_LIST_TYPE : OUT_VAR_TYPE; if (FindPassingOutsMap(op_type, out_name)) { - if (input_args != "") { + if (!input_args.empty()) { input_args += ","; } input_args += out_type; @@ -262,7 +262,7 @@ std::string GenerateOpFunctionsBody( // split op. We need to specify the number of variables for the // duplicable output, as the argument OutNum; if (output.duplicable()) { - if (input_args != "") { + if (!input_args.empty()) { input_args += ","; } auto out_num_str = @@ -335,7 +335,7 @@ std::string GenerateOpFunctionsBody( } std::string function_args = ""; - if (input_args == "") { + if (!input_args.empty()) { function_args = FUNCTION_ARGS_NO_INPUT; } else { function_args = paddle::string::Sprintf(FUNCTION_ARGS, input_args); diff --git a/paddle/fluid/pybind/eager_method.cc b/paddle/fluid/pybind/eager_method.cc index eb0e895cf575c..5f497c3f14066 100644 --- a/paddle/fluid/pybind/eager_method.cc +++ b/paddle/fluid/pybind/eager_method.cc @@ -175,7 +175,7 @@ static PyObject* tensor_method_numpy(TensorObject* self, nullptr); if (!self->tensor.impl()->initialized()) { - if (tensor_dims.size() == 0) { + if (tensor_dims.empty()) { py_dims[0] = 0; py_strides[0] = 0; PyObject* array = api.PyArray_NewFromDescr_( diff --git a/paddle/fluid/pybind/eager_py_layer.cc b/paddle/fluid/pybind/eager_py_layer.cc index 23796bb97264b..cf899aa0ab19a 100644 --- a/paddle/fluid/pybind/eager_py_layer.cc +++ b/paddle/fluid/pybind/eager_py_layer.cc @@ -374,7 +374,7 @@ PyObject* pylayer_method_apply(PyObject* cls, } } - if (outputs_tensor.size() == 0) { + if (outputs_tensor.empty()) { PADDLE_THROW(platform::errors::InvalidArgument( "At least one output of `PyLayer.forward` is a `Tensor`.")); } diff --git a/paddle/fluid/pybind/imperative.cc b/paddle/fluid/pybind/imperative.cc index f6776a3f1826a..761cde9153c08 100644 --- a/paddle/fluid/pybind/imperative.cc +++ b/paddle/fluid/pybind/imperative.cc @@ -164,9 +164,10 @@ static void InitVarBaseOnly(imperative::VarBase *self, const std::string &name, bool persistable = false, int stop_gradient = -1) { - auto name_ = name == "" ? imperative::GetCurrentTracer()->GenerateUniqueName( - "generated_tensor") - : name; + auto name_ = name.empty() + ? imperative::GetCurrentTracer()->GenerateUniqueName( + "generated_tensor") + : name; VLOG(5) << "Init Tensor as: / name: " << name_ << " / persistable: " << persistable @@ -250,7 +251,7 @@ static void InitVarBaseFromNumpyWithArg(imperative::VarBase *self, VLOG(4) << "Init VarBase from Arg: "; // 0: self, 1: value, 2: place, 3: persistable, 4: zero_copy, 5: name , 6: // stop_gradient - if (name == "") { + if (name.empty()) { name = imperative::GetCurrentTracer()->GenerateUniqueName("generated_tensor"); } @@ -280,9 +281,10 @@ static void InitVarBaseFromTensorWithArgDefault(imperative::VarBase *self, const std::string &name) { VLOG(4) << "Init VarBase"; auto place = imperative::GetCurrentTracer()->ExpectedPlace(); - auto name_ = name == "" ? imperative::GetCurrentTracer()->GenerateUniqueName( - "generated_tensor") - : name; + auto name_ = name.empty() + ? imperative::GetCurrentTracer()->GenerateUniqueName( + "generated_tensor") + : name; new (self) imperative::VarBase(name_); self->SetPersistable(false); self->SetType(framework::proto::VarType::LOD_TENSOR); @@ -304,9 +306,10 @@ static void InitVarBaseFromTensorWithArg(imperative::VarBase *self, const P &place, const std::string &name) { VLOG(4) << "Init VarBase"; - auto name_ = name == "" ? imperative::GetCurrentTracer()->GenerateUniqueName( - "generated_tensor") - : name; + auto name_ = name.empty() + ? imperative::GetCurrentTracer()->GenerateUniqueName( + "generated_tensor") + : name; new (self) imperative::VarBase(name_); self->SetPersistable(false); self->SetType(framework::proto::VarType::LOD_TENSOR); diff --git a/paddle/fluid/pybind/kernel_signature_generator.cc b/paddle/fluid/pybind/kernel_signature_generator.cc index 1156fd0b52c25..f1dd4b8466386 100644 --- a/paddle/fluid/pybind/kernel_signature_generator.cc +++ b/paddle/fluid/pybind/kernel_signature_generator.cc @@ -66,7 +66,7 @@ int main(int argc, char **argv) { kernel_signature_map_str = kernel_signature_map_str + "\"" + inputs_[i] + "\","; } - if (inputs_.size()) kernel_signature_map_str.pop_back(); + if (!inputs_.empty()) kernel_signature_map_str.pop_back(); kernel_signature_map_str += "],\"attrs\":["; auto attrs_ = args.attr_names; @@ -74,7 +74,7 @@ int main(int argc, char **argv) { kernel_signature_map_str = kernel_signature_map_str + "\"" + attrs_[i] + "\","; } - if (attrs_.size()) kernel_signature_map_str.pop_back(); + if (!attrs_.empty()) kernel_signature_map_str.pop_back(); kernel_signature_map_str += "],\"outputs\":["; auto outputs_ = args.output_names; for (size_t i = 0; i < outputs_.size(); i++) { @@ -82,7 +82,7 @@ int main(int argc, char **argv) { kernel_signature_map_str + "\"" + outputs_[i] + "\","; } - if (outputs_.size()) kernel_signature_map_str.pop_back(); + if (!outputs_.empty()) kernel_signature_map_str.pop_back(); kernel_signature_map_str += "]},"; } } diff --git a/paddle/fluid/pybind/reader_py.cc b/paddle/fluid/pybind/reader_py.cc index f8154e4de8cce..a90b10262388d 100644 --- a/paddle/fluid/pybind/reader_py.cc +++ b/paddle/fluid/pybind/reader_py.cc @@ -58,7 +58,7 @@ static paddle::optional> DiffTensorShapeWithVarDesc( int64_t rank = tensor_shape.size(); if (UNLIKELY(rank == 0)) { - if (desc_shape.size() != 0) { // Tensor rank = 0 but desc does not match + if (!desc_shape.empty()) { // Tensor rank = 0 but desc does not match return phi::vectorize(tensor_shape); } else { return paddle::none; diff --git a/paddle/phi/backends/onednn/onednn_context.cc b/paddle/phi/backends/onednn/onednn_context.cc index 9ad73795da400..bbb52962bc481 100644 --- a/paddle/phi/backends/onednn/onednn_context.cc +++ b/paddle/phi/backends/onednn/onednn_context.cc @@ -208,7 +208,7 @@ struct OneDNNContext::Impl { // max pblob capacity if ((static_cast(sid) == OneDNNContextThreadLocals::kMKLDNNSessionID_CacheClearing) && - sBlob->size() && + !sBlob->empty() && (sBlob->size() >= static_cast( OneDNNContext::tls().cur_input_shape_cache_capacity))) { diff --git a/paddle/phi/core/custom_kernel.cc b/paddle/phi/core/custom_kernel.cc index 75c651c5402c7..58c1a736725b5 100644 --- a/paddle/phi/core/custom_kernel.cc +++ b/paddle/phi/core/custom_kernel.cc @@ -38,7 +38,7 @@ void CustomKernelMap::RegisterCustomKernel(const std::string& name, void CustomKernelMap::RegisterCustomKernels() { VLOG(3) << "Size of custom_kernel_map: " << kernels_.size(); - if (kernels_.size() <= 0) { + if (kernels_.empty()) { LOG(INFO) << "No custom kernel info found in loaded lib(s)."; return; } diff --git a/paddle/phi/core/distributed/auto_parallel/dist_attr.cc b/paddle/phi/core/distributed/auto_parallel/dist_attr.cc index 875edad3fb730..6896d2c96c52f 100644 --- a/paddle/phi/core/distributed/auto_parallel/dist_attr.cc +++ b/paddle/phi/core/distributed/auto_parallel/dist_attr.cc @@ -79,14 +79,14 @@ void TensorDistAttr::set_annotated( void TensorDistAttr::set_default_dims_mapping( const std::vector& tensor_shape) { - if (tensor_shape.size() != 0) { + if (!tensor_shape.empty()) { dims_mapping_ = std::vector(tensor_shape.size(), -1); } } void TensorDistAttr::set_default_dynamic_dims( const std::vector& tensor_shape) { - if (tensor_shape.size() != 0) { + if (!tensor_shape.empty()) { dynamic_dims_ = std::vector(tensor_shape.size(), false); } } @@ -160,7 +160,7 @@ bool TensorDistAttr::verify_dynamic_dims( const std::vector& dynamic_dims, const std::vector& tensor_shape) const { VLOG(4) << "[TensorDistAttr verify_dynamic_dims] " << str_join(dynamic_dims); - if (dynamic_dims.size() > 0 && dynamic_dims.size() != tensor_shape.size()) { + if (!dynamic_dims.empty() && dynamic_dims.size() != tensor_shape.size()) { return false; } return true; diff --git a/paddle/phi/core/lod_utils.cc b/paddle/phi/core/lod_utils.cc index dac1059182c5b..0fab1dbf1d27f 100644 --- a/paddle/phi/core/lod_utils.cc +++ b/paddle/phi/core/lod_utils.cc @@ -59,7 +59,7 @@ LoD ConvertToLengthBasedLoD(const LoD &offset_lod) { length_lod.reserve(offset_lod.size()); for (size_t lvl = 0; lvl < offset_lod.size(); ++lvl) { std::vector level; - if (offset_lod[lvl].size() > 0) { + if (!offset_lod[lvl].empty()) { level.reserve(offset_lod[lvl].size() - 1); } for (size_t idx = 0; idx < offset_lod[lvl].size() - 1; ++idx) { diff --git a/paddle/phi/core/meta_tensor.cc b/paddle/phi/core/meta_tensor.cc index 534efcdc79efb..55a62b7a619bb 100644 --- a/paddle/phi/core/meta_tensor.cc +++ b/paddle/phi/core/meta_tensor.cc @@ -132,7 +132,7 @@ void MetaTensor::share_lod(const MetaTensor& meta_tensor) { phi::SparseCsrTensor::classof(tensor_)) { return; } - if (meta_tensor.lod().size() == 0) { + if (meta_tensor.lod().empty()) { // no need share return; } diff --git a/paddle/phi/infermeta/backward.cc b/paddle/phi/infermeta/backward.cc index 1812ead33480c..2e33d9fbf23c2 100644 --- a/paddle/phi/infermeta/backward.cc +++ b/paddle/phi/infermeta/backward.cc @@ -968,10 +968,10 @@ void RnnGradInferMeta(const MetaTensor& x, if (x_grad) { UnchangedInferMeta(x, x_grad); } - if (pre_state_grad.size()) { + if (!pre_state_grad.empty()) { UnchangedMultiInferMeta(pre_state, pre_state_grad); } - if (weight_grad_list.size()) { + if (!weight_grad_list.empty()) { UnchangedMultiInferMeta(weight_list, weight_grad_list); } } diff --git a/paddle/phi/infermeta/binary.cc b/paddle/phi/infermeta/binary.cc index 2698563eacc77..de0794ada9772 100644 --- a/paddle/phi/infermeta/binary.cc +++ b/paddle/phi/infermeta/binary.cc @@ -684,14 +684,14 @@ void ConvTransposeInferMeta(const MetaTensor& x, x_dims.size(), x_dims, strides.size())); - if (output_size.size()) + if (!output_size.empty()) PADDLE_ENFORCE_EQ( output_size.size(), strides.size(), errors::InvalidArgument( "The Attr(output_size) and Attr(stride) of Op(conv_transpose) " "should be the same.")); - if (output_padding.size()) + if (!output_padding.empty()) PADDLE_ENFORCE_EQ( output_padding.size(), strides.size(), @@ -740,7 +740,7 @@ void ConvTransposeInferMeta(const MetaTensor& x, paddings_[2 * i] - paddings_[2 * i + 1] + filter_extent : -1; - if (output_size.size()) { + if (!output_size.empty()) { if (config.is_runtime) { PADDLE_ENFORCE_GE( output_size[i], @@ -767,7 +767,7 @@ void ConvTransposeInferMeta(const MetaTensor& x, infer_shape + strides[i])); } output_shape.push_back(output_size[i]); - } else if (output_padding.size()) { + } else if (!output_padding.empty()) { if (config.is_runtime) { PADDLE_ENFORCE_GE( output_padding[i], @@ -2473,7 +2473,7 @@ void PriorBoxInferMeta(const MetaTensor& input, ExpandAspectRatios(aspect_ratios, flip, &aspect_ratios_vec); size_t num_priors = aspect_ratios_vec.size() * min_sizes.size(); - if (max_sizes.size() > 0) { + if (!max_sizes.empty()) { PADDLE_ENFORCE_EQ( max_sizes.size(), min_sizes.size(), diff --git a/paddle/phi/infermeta/fusion.cc b/paddle/phi/infermeta/fusion.cc index 97702d513e442..d9b1b08aead80 100644 --- a/paddle/phi/infermeta/fusion.cc +++ b/paddle/phi/infermeta/fusion.cc @@ -425,7 +425,7 @@ void FusedMultiTransformerXpuInferMeta( "shape of input x = [%s], and the shape of input qkv_weight = [%s]", x_dim, y_dim)); - if (cache_kv.size() > 0) { + if (!cache_kv.empty()) { const auto& c_dim = cache_kv[0]->dims(); PADDLE_ENFORCE_EQ( c_dim.size(), @@ -614,14 +614,14 @@ void ConvTransposeXPUInferMeta(const MetaTensor& x, x_dims.size(), x_dims, strides.size())); - if (output_size.size()) + if (!output_size.empty()) PADDLE_ENFORCE_EQ( output_size.size(), strides.size(), errors::InvalidArgument( "The Attr(output_size) and Attr(stride) of Op(conv_transpose) " "should be the same.")); - if (output_padding.size()) + if (!output_padding.empty()) PADDLE_ENFORCE_EQ( output_padding.size(), strides.size(), @@ -669,9 +669,9 @@ void ConvTransposeXPUInferMeta(const MetaTensor& x, paddings_[2 * i] - paddings_[2 * i + 1] + filter_extent : -1; - if (output_size.size()) { + if (!output_size.empty()) { output_shape.push_back(output_size[i]); - } else if (output_padding.size()) { + } else if (!output_padding.empty()) { output_shape.push_back((infer_shape + output_padding[i])); } else { output_shape.push_back(infer_shape); diff --git a/paddle/phi/infermeta/multiary.cc b/paddle/phi/infermeta/multiary.cc index 956432bb3076c..7514520cb6840 100644 --- a/paddle/phi/infermeta/multiary.cc +++ b/paddle/phi/infermeta/multiary.cc @@ -1636,7 +1636,7 @@ static void Interpolate1DInferShapeCheck( i, dim_x[i])); } - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // top prority size auto inputs_name = size_tensor.get(); PADDLE_ENFORCE_EQ( @@ -1677,7 +1677,7 @@ static void Interpolate1DInferShapeCheck( } out_w_tmp = -1; } else { - if (scale.size() > 0) { + if (!scale.empty()) { float scale_w = -1; scale_w = scale[0]; PADDLE_ENFORCE_EQ( @@ -1768,7 +1768,7 @@ static void Interpolate2DInferShapeCheck( dim_x[i])); } - if (size_tensor && size_tensor->size()) { + if (size_tensor && !size_tensor->empty()) { // top prority size auto inputs_name = size_tensor.get(); PADDLE_ENFORCE_EQ( @@ -1814,7 +1814,7 @@ static void Interpolate2DInferShapeCheck( out_h_tmp = -1; out_w_tmp = -1; } else { - if (scale.size() > 0) { + if (!scale.empty()) { float scale_h = -1; float scale_w = -1; scale_h = scale[0]; @@ -1919,7 +1919,7 @@ static void Interpolate3DInferShapeCheck( dim_x[i])); } - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // top prority size auto inputs_name = size_tensor.get(); PADDLE_ENFORCE_EQ( @@ -1959,7 +1959,7 @@ static void Interpolate3DInferShapeCheck( out_h_tmp = -1; out_w_tmp = -1; } else { - if (scale.size() > 0) { + if (!scale.empty()) { float scale_d = -1; float scale_h = -1; float scale_w = -1; diff --git a/paddle/phi/infermeta/unary.cc b/paddle/phi/infermeta/unary.cc index 2b6b5cc0e1673..aaea2e8094ba1 100644 --- a/paddle/phi/infermeta/unary.cc +++ b/paddle/phi/infermeta/unary.cc @@ -1055,7 +1055,7 @@ void ExpandInferMeta(const MetaTensor& x, auto x_dims = x.dims(); auto expand_shape = shape.GetData(); - if (expand_shape.size() == 0) { + if (expand_shape.empty()) { expand_shape = std::vector(x_dims.size(), -1); } @@ -3173,7 +3173,7 @@ void ReduceInferMeta(const MetaTensor& x, bool keep_dim, MetaTensor* out) { bool reduce_all = false; - if (axis.size() == 0) { + if (axis.empty()) { reduce_all = true; } ReduceInferMetaBase(x, axis, keep_dim, reduce_all, out); @@ -3396,7 +3396,7 @@ void RollInferMeta(const MetaTensor& x, MetaTensor* out) { auto shifts_data = shifts.GetData(); - if (axis.size() != 0) { + if (!axis.empty()) { PADDLE_ENFORCE_EQ( axis.size(), shifts_data.size(), @@ -3581,7 +3581,7 @@ void SliceRawInferMeta(const MetaTensor& input, } out->set_dims(out_dims); - if (new_axes.size() > 0 && new_axes[0] != 0) { + if (!new_axes.empty() && new_axes[0] != 0) { out->share_lod(input); } } @@ -3993,7 +3993,7 @@ void StridedSliceRawInferMeta(const MetaTensor& x, } DDim out_dims(phi::make_ddim(out_dims_vector)); // generate new shape - if (decrease_axis.size() > 0) { + if (!decrease_axis.empty()) { std::vector new_out_shape; for (size_t i = 0; i < decrease_axis.size(); ++i) { if (config.is_runtime && infer_flags[i] != -1) { @@ -4181,7 +4181,7 @@ void TileInferMeta(const MetaTensor& x, auto repeat_times_data = repeat_times.GetData(); auto x_dims = x.dims(); - if (repeat_times_data.size() == 0) { + if (repeat_times_data.empty()) { repeat_times_data = std::vector(x_dims.size(), 1); } diff --git a/paddle/phi/kernels/cpu/add_n_kernel.cc b/paddle/phi/kernels/cpu/add_n_kernel.cc index e165f1cc7f24b..137f4e513e461 100644 --- a/paddle/phi/kernels/cpu/add_n_kernel.cc +++ b/paddle/phi/kernels/cpu/add_n_kernel.cc @@ -26,7 +26,7 @@ void AddNKernel(const Context& dev_ctx, dev_ctx.template Alloc(out); bool in_place = false; - if (x.size() > 0 && x[0]->initialized() && DenseTensor::classof(x[0])) { + if (!x.empty() && x[0]->initialized() && DenseTensor::classof(x[0])) { if ((static_cast(x[0]))->Holder() == out->Holder()) { in_place = true; } diff --git a/paddle/phi/kernels/cpu/box_coder_kernel.cc b/paddle/phi/kernels/cpu/box_coder_kernel.cc index 81380e97d9899..a8bd1c5b0bf70 100644 --- a/paddle/phi/kernels/cpu/box_coder_kernel.cc +++ b/paddle/phi/kernels/cpu/box_coder_kernel.cc @@ -178,7 +178,7 @@ void BoxCoderKernel(const Context &dev_ctx, int axis, const std::vector &variance, DenseTensor *output_box) { - if (target_box.lod().size()) { + if (!target_box.lod().empty()) { PADDLE_ENFORCE_EQ(target_box.lod().size(), 1UL, phi::errors::InvalidArgument( diff --git a/paddle/phi/kernels/cpu/broadcast_tensors_grad_kernel.cc b/paddle/phi/kernels/cpu/broadcast_tensors_grad_kernel.cc index 8235abb3209d8..943dd37c82dd3 100644 --- a/paddle/phi/kernels/cpu/broadcast_tensors_grad_kernel.cc +++ b/paddle/phi/kernels/cpu/broadcast_tensors_grad_kernel.cc @@ -116,7 +116,7 @@ void BroadcastTensorsGradKernel(const Context& ctx, size_t reduce_size = reduce_dims_vec.size(); size_t reshape_size = reshape_dims_vec.size(); - bool just_copy = (reduce_dims_vec.size() == 0); + bool just_copy = (reduce_dims_vec.empty()); ctx.template Alloc(output_tensor); if (just_copy) { // If this turns out to be a No-Op, simply perform a tensor copy diff --git a/paddle/phi/kernels/cpu/concat_kernel.cc b/paddle/phi/kernels/cpu/concat_kernel.cc index 58cb1d9566612..2731716afb6a4 100644 --- a/paddle/phi/kernels/cpu/concat_kernel.cc +++ b/paddle/phi/kernels/cpu/concat_kernel.cc @@ -47,11 +47,11 @@ void ConcatKernel(const Context& dev_ctx, dev_ctx.template Alloc(out); // If axis is 0, the lod of the output is not the same as inputs. - if (axis == 0 && x[0]->lod().size() > 0) { + if (axis == 0 && !x[0]->lod().empty()) { size_t lod_size_0 = x[0]->lod().size(); size_t lod_size = lod_size_0; for (size_t i = 1; i < x.size(); ++i) { - if (x[i]->lod().size() > 0) { + if (!x[i]->lod().empty()) { PADDLE_ENFORCE_EQ( x[i]->lod().size(), lod_size_0, diff --git a/paddle/phi/kernels/cpu/distribute_fpn_proposals_kernel.cc b/paddle/phi/kernels/cpu/distribute_fpn_proposals_kernel.cc index 5922597ae3186..5ca3ee0949f8c 100644 --- a/paddle/phi/kernels/cpu/distribute_fpn_proposals_kernel.cc +++ b/paddle/phi/kernels/cpu/distribute_fpn_proposals_kernel.cc @@ -116,7 +116,7 @@ void DistributeFpnProposalsKernel( restore_index_data[restore_index_inter[i]] = i; } - if (multi_level_rois_num.size() > 0) { + if (!multi_level_rois_num.empty()) { int batch_size = fpn_rois_lod.size() - 1; for (int i = 0; i < num_level; ++i) { multi_level_rois_num[i]->Resize({batch_size}); diff --git a/paddle/phi/kernels/cpu/interpolate_grad_kernel.cc b/paddle/phi/kernels/cpu/interpolate_grad_kernel.cc index 83f1a452fe43a..6361680f2baaf 100644 --- a/paddle/phi/kernels/cpu/interpolate_grad_kernel.cc +++ b/paddle/phi/kernels/cpu/interpolate_grad_kernel.cc @@ -395,7 +395,7 @@ static void Interpolate1DCPUBwd( "should be greater than 0, but received value is %d.", scale_w)); } else { - if (scale.size() > 0) { + if (!scale.empty()) { scale_w = scale[0]; PADDLE_ENFORCE_EQ( scale_w > 0, @@ -414,7 +414,7 @@ static void Interpolate1DCPUBwd( funcs::get_new_data_from_tensor(out_size.get_ptr()); out_w = out_size_data[0]; } - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // have size tensor auto new_size = funcs::get_new_shape(size_tensor.get()); out_w = new_size[0]; @@ -536,7 +536,7 @@ static void Interpolate2DCPUBwd( out_h = out_size_data[0]; out_w = out_size_data[1]; } - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // have size tensor auto new_size = funcs::get_new_shape(size_tensor.get()); out_h = new_size[0]; @@ -716,7 +716,7 @@ static void Interpolate3DCPUBwd( out_h = out_size_data[1]; out_w = out_size_data[2]; } - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // have size tensor auto new_size = funcs::get_new_shape(size_tensor.get()); out_d = new_size[0]; diff --git a/paddle/phi/kernels/cpu/interpolate_kernel.cc b/paddle/phi/kernels/cpu/interpolate_kernel.cc index 35f4ae31cfed3..3cd02f67fb21a 100644 --- a/paddle/phi/kernels/cpu/interpolate_kernel.cc +++ b/paddle/phi/kernels/cpu/interpolate_kernel.cc @@ -541,7 +541,7 @@ static void Interpolate1DCPUFwd( funcs::ExtractNCDWH(x.dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); float scale_w = -1.; - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // have size tensor auto new_size = funcs::get_new_shape(size_tensor.get()); out_w = new_size[0]; @@ -558,7 +558,7 @@ static void Interpolate1DCPUFwd( "should be greater than 0, but received value is %d.", scale_w)); } else { - if (scale.size() > 0) { + if (!scale.empty()) { scale_w = scale[0]; PADDLE_ENFORCE_EQ( @@ -642,7 +642,7 @@ static void Interpolate2DCPUFwd( float scale_h = -1; float scale_w = -1; - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // have size tensor auto new_size = funcs::get_new_shape(size_tensor.get()); out_h = new_size[0]; @@ -810,7 +810,7 @@ static void Interpolate3DCPUFwd( float scale_h = -1; float scale_w = -1; - if (size_tensor && size_tensor->size() > 0) { + if (size_tensor && !size_tensor->empty()) { // have size tensor auto new_size = funcs::get_new_shape(size_tensor.get()); out_d = new_size[0]; diff --git a/paddle/phi/kernels/cpu/multiclass_nms3_kernel.cc b/paddle/phi/kernels/cpu/multiclass_nms3_kernel.cc index 381587dd4f6e1..c0728874ebe90 100644 --- a/paddle/phi/kernels/cpu/multiclass_nms3_kernel.cc +++ b/paddle/phi/kernels/cpu/multiclass_nms3_kernel.cc @@ -295,7 +295,7 @@ void NMSFast(const DenseTensor& bbox, T adaptive_threshold = nms_threshold; const T* bbox_data = bbox.data(); - while (sorted_indices.size() != 0) { + while (!sorted_indices.empty()) { const int idx = sorted_indices.front().second; bool keep = true; for (size_t k = 0; k < selected_indices->size(); ++k) { diff --git a/paddle/phi/kernels/cpu/prior_box_kernel.cc b/paddle/phi/kernels/cpu/prior_box_kernel.cc index 5f6b7826dc6fe..f328e6ccc3d4c 100644 --- a/paddle/phi/kernels/cpu/prior_box_kernel.cc +++ b/paddle/phi/kernels/cpu/prior_box_kernel.cc @@ -58,7 +58,7 @@ void PriorBoxKernel(const Context& ctx, } int num_priors = new_aspect_ratios.size() * min_sizes.size(); - if (max_sizes.size() > 0) { + if (!max_sizes.empty()) { num_priors += max_sizes.size(); } @@ -80,7 +80,7 @@ void PriorBoxKernel(const Context& ctx, b_t[2] = (center_x + box_width) / img_width; b_t[3] = (center_y + box_height) / img_height; b_t += 4; - if (max_sizes.size() > 0) { + if (!max_sizes.empty()) { auto max_size = max_sizes[s]; // square prior with size sqrt(minSize * maxSize) box_width = box_height = sqrt(min_size * max_size) / 2.; @@ -116,7 +116,7 @@ void PriorBoxKernel(const Context& ctx, b_t[3] = (center_y + box_height) / img_height; b_t += 4; } - if (max_sizes.size() > 0) { + if (!max_sizes.empty()) { auto max_size = max_sizes[s]; // square prior with size sqrt(minSize * maxSize) box_width = box_height = sqrt(min_size * max_size) / 2.; diff --git a/paddle/phi/kernels/cpu/rnn_grad_kernel.cc b/paddle/phi/kernels/cpu/rnn_grad_kernel.cc index 4b3bbbf5d5c1b..2feec58764baa 100644 --- a/paddle/phi/kernels/cpu/rnn_grad_kernel.cc +++ b/paddle/phi/kernels/cpu/rnn_grad_kernel.cc @@ -410,7 +410,7 @@ struct GradLayer { dev_ctx.GetPlace(), false, dynamic_grad_last_h); - if (last_c_grad_unbind.size() > 0) { + if (!last_c_grad_unbind.empty()) { dynamic_grad_last_c->Resize(last_c_grad_unbind[current_layer_idx].dims()); dev_ctx.Alloc(dynamic_grad_last_c); Copy(dev_ctx, @@ -426,7 +426,7 @@ struct GradLayer { DenseTensor* dynamic_grad_pre_h = &c; DenseTensor* dynamic_grad_pre_c = &d; phi::funcs::SetConstant zero; - if (init_h_grad_unbind->size() > 0) { + if (!init_h_grad_unbind->empty()) { dynamic_grad_pre_h->ShareDataWith( (*init_h_grad_unbind)[current_layer_idx]); } else { @@ -434,7 +434,7 @@ struct GradLayer { dev_ctx.Alloc(dynamic_grad_pre_h); zero(dev_ctx, dynamic_grad_pre_h, static_cast(0.0)); } - if (init_c_grad_unbind->size() > 0) { + if (!init_c_grad_unbind->empty()) { dynamic_grad_pre_c->ShareDataWith( (*init_c_grad_unbind)[current_layer_idx]); } else { @@ -495,12 +495,12 @@ struct GradLayer { hidden = &(*output_tensor_unbind)[i]; if (i == 0) { pre_hidden = &(*init_h_unbind)[current_layer_idx]; - if (init_c_unbind->size() > 0) { + if (!init_c_unbind->empty()) { pre_state = &(*init_c_unbind)[current_layer_idx]; } } else { pre_hidden = &(*output_tensor_unbind)[i - 1]; - if (layer_state_tensor_unbind->size() > 0) { + if (!layer_state_tensor_unbind->empty()) { pre_state = &(*layer_state_tensor_unbind)[begin_idx + i - 1]; } } @@ -536,14 +536,14 @@ struct GradLayer { mode); // copy the gradient to init_c init_h - if ((*init_h_grad_unbind).size() > 0 && time_step % 2 == 0) { + if (!(*init_h_grad_unbind).empty() && time_step % 2 == 0) { Copy(dev_ctx, *dynamic_grad_last_h, dev_ctx.GetPlace(), false, &((*init_h_grad_unbind)[current_layer_idx])); } - if ((*init_c_grad_unbind).size() > 0 && time_step % 2 == 0) { + if (!(*init_c_grad_unbind).empty() && time_step % 2 == 0) { Copy(dev_ctx, *dynamic_grad_last_c, dev_ctx.GetPlace(), @@ -736,7 +736,7 @@ struct SingleGradLayer : GradLayer { DenseTensor layer_state_tensor; std::vector layer_state_tensor_unbind; - if (state_tensor_unbind.size() > 0) { + if (!state_tensor_unbind.empty()) { layer_state_tensor = state_tensor_unbind[layer_idx]; layer_state_tensor.Resize( {time_step * direction_num, batch_size, hidden_size}); @@ -745,7 +745,7 @@ struct SingleGradLayer : GradLayer { DenseTensor layer_act_state_tensor; std::vector layer_act_state_tensor_unbind; - if (act_state_tensor_unbind.size() > 0) { + if (!act_state_tensor_unbind.empty()) { layer_act_state_tensor = act_state_tensor_unbind[layer_idx]; layer_act_state_tensor.Resize( {time_step * direction_num, batch_size, hidden_size}); @@ -881,7 +881,7 @@ struct BidirGradLayer : GradLayer { DenseTensor layer_state_tensor; std::vector layer_state_tensor_unbind; - if (state_tensor_unbind.size() > 0) { + if (!state_tensor_unbind.empty()) { layer_state_tensor = state_tensor_unbind[layer_idx]; layer_state_tensor.Resize( {time_step * direction_num, batch_size, hidden_size}); @@ -890,7 +890,7 @@ struct BidirGradLayer : GradLayer { DenseTensor layer_act_state_tensor; std::vector layer_act_state_tensor_unbind; - if (act_state_tensor_unbind.size() > 0) { + if (!act_state_tensor_unbind.empty()) { layer_act_state_tensor = act_state_tensor_unbind[layer_idx]; layer_act_state_tensor.Resize( {time_step * direction_num, batch_size, hidden_size}); diff --git a/paddle/phi/kernels/cpu/roll_grad_kernel.cc b/paddle/phi/kernels/cpu/roll_grad_kernel.cc index bee30ad8e49de..367851ef4d268 100644 --- a/paddle/phi/kernels/cpu/roll_grad_kernel.cc +++ b/paddle/phi/kernels/cpu/roll_grad_kernel.cc @@ -36,7 +36,7 @@ void RollGradKernel(const Context& dev_ctx, auto dims = axis; // axis = none, reshape to 1-D tensor - if (dims.size() == 0) { + if (dims.empty()) { dims.push_back(0l); input_dim = phi::Dim<1>(out_vec.size()); } diff --git a/paddle/phi/kernels/cpu/roll_kernel.cc b/paddle/phi/kernels/cpu/roll_kernel.cc index a1c4b241171dd..71a8953802eb4 100644 --- a/paddle/phi/kernels/cpu/roll_kernel.cc +++ b/paddle/phi/kernels/cpu/roll_kernel.cc @@ -37,7 +37,7 @@ void RollKernel(const Context& dev_ctx, auto dims = axis; // axis = none, reshape to 1-D tensor - if (dims.size() == 0) { + if (dims.empty()) { dims.push_back(0l); input_dim = phi::Dim<1>(out_vec.size()); } diff --git a/paddle/phi/kernels/cpu/send_u_recv_kernel.cc b/paddle/phi/kernels/cpu/send_u_recv_kernel.cc index 037acbac46b0d..73d4fc72af857 100644 --- a/paddle/phi/kernels/cpu/send_u_recv_kernel.cc +++ b/paddle/phi/kernels/cpu/send_u_recv_kernel.cc @@ -98,7 +98,7 @@ void GraphSendRecvOpKernelLaunchHelper(const Context& ctx, } else { // Set out dim following out_size. std::vector dims_ = phi::vectorize(src_dims); - if (dims_.size() > 0) { + if (!dims_.empty()) { dims_[0] = out_size; } out->Resize(phi::make_ddim(dims_)); diff --git a/paddle/phi/kernels/cpu/sgd_kernel.cc b/paddle/phi/kernels/cpu/sgd_kernel.cc index 30a3a13a50d69..cad34aed06225 100644 --- a/paddle/phi/kernels/cpu/sgd_kernel.cc +++ b/paddle/phi/kernels/cpu/sgd_kernel.cc @@ -151,7 +151,7 @@ void SGDSparseParamSparseGradKernel( SelectedRows* master_param_out UNUSED) { // for distributed training, a sparse var may be empty, // just skip updating. - if (grad.rows().size() == 0) { + if (grad.rows().empty()) { return; } diff --git a/paddle/phi/kernels/full_kernel.cc b/paddle/phi/kernels/full_kernel.cc index 38beafbfa51b9..31bcbc2eeea94 100644 --- a/paddle/phi/kernels/full_kernel.cc +++ b/paddle/phi/kernels/full_kernel.cc @@ -27,7 +27,7 @@ void FullBatchSizeLikeKernel(const Context& dev_ctx, int x_batch_size_dim, int out_batch_size_dim, DenseTensor* out) { - if (x.lod().size() && x_batch_size_dim == 0) { + if (!x.lod().empty() && x_batch_size_dim == 0) { // set the correct batch size for the LoDTensor. auto odims = out->dims(); odims[out_batch_size_dim] = static_cast(x.lod().back().size()) - 1; diff --git a/paddle/phi/kernels/funcs/data_layout_transform.cc b/paddle/phi/kernels/funcs/data_layout_transform.cc index eddb137733937..3edf92a3fd080 100644 --- a/paddle/phi/kernels/funcs/data_layout_transform.cc +++ b/paddle/phi/kernels/funcs/data_layout_transform.cc @@ -65,7 +65,7 @@ dnnl::memory::desc make_memory_desc(const phi::DenseTensor& ref_tensor, "Ref tensor type (%s) is not supported by oneDNN.", ref_tensor.dtype())); - auto md_dims = ref_dims.size() != 0 ? ref_dims : std::vector{1}; + auto md_dims = !ref_dims.empty() ? ref_dims : std::vector{1}; auto md_format = OneDNNFormatForSize(md_dims.size(), ToOneDNNFormat(target_layout)); dnnl::memory::desc md(md_dims, ref_type, md_format); diff --git a/paddle/phi/kernels/funcs/jit/helper.cc b/paddle/phi/kernels/funcs/jit/helper.cc index eb171a6aaebc4..b85a825e35712 100644 --- a/paddle/phi/kernels/funcs/jit/helper.cc +++ b/paddle/phi/kernels/funcs/jit/helper.cc @@ -88,7 +88,7 @@ KernelType to_kerneltype(const std::string& act) { std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (lower == "relu" || lower == "vrelu") { return kVRelu; - } else if (lower == "identity" || lower == "videntity" || lower == "") { + } else if (lower == "identity" || lower == "videntity" || lower.empty()) { return kVIdentity; } else if (lower == "exp" || lower == "vexp") { return kVExp; diff --git a/paddle/phi/kernels/funcs/selected_rows_functor.cc b/paddle/phi/kernels/funcs/selected_rows_functor.cc index 1ec6f0a6ba09c..3716273b4104e 100644 --- a/paddle/phi/kernels/funcs/selected_rows_functor.cc +++ b/paddle/phi/kernels/funcs/selected_rows_functor.cc @@ -291,7 +291,7 @@ struct SelectedRowsAddToTensor { void operator()(const phi::CPUContext& context UNUSED, const phi::SelectedRows& input1, phi::DenseTensor* input2) { - if (UNLIKELY(input1.rows().size() == 0)) { + if (UNLIKELY(input1.rows().empty())) { LOG(WARNING) << "input selected rows is empty!"; return; } @@ -440,7 +440,7 @@ add_sparse_inputs(const std::vector& inputs, auto blas = phi::funcs::GetBlas(context); #endif for (auto* input : inputs) { - if (input->rows().size() == 0) { + if (input->rows().empty()) { continue; } auto* input_data = input->value().data(); @@ -477,7 +477,7 @@ add_sparse_inputs(const std::vector& inputs, VLOG(4) << "[CPU] add_sparse_inputs <" << typeid(T).name(); auto blas = phi::funcs::GetBlas(context); for (auto* input : inputs) { - if (input->rows().size() == 0) { + if (input->rows().empty()) { continue; } auto* input_data = input->value().data(); @@ -516,13 +516,13 @@ struct MergeAddImpl { const std::vector& inputs, phi::SelectedRows* output, const bool sorted_result = false) { - if (inputs.size() == 0) { + if (inputs.empty()) { VLOG(3) << "no input! return"; return; } const phi::SelectedRows* has_value_input = nullptr; for (auto* in : inputs) { - if (in->rows().size() > 0) { + if (!in->rows().empty()) { has_value_input = in; break; } @@ -537,7 +537,7 @@ struct MergeAddImpl { std::set merged_row_set; size_t row_num = 0; for (auto* input : inputs) { - if (input->rows().size() == 0) { + if (input->rows().empty()) { continue; } PADDLE_ENFORCE_EQ( @@ -831,13 +831,13 @@ struct MergeAverage { void operator()(const phi::CPUContext& context, const std::vector& inputs, phi::SelectedRows* output) { - if (inputs.size() == 0) { + if (inputs.empty()) { VLOG(3) << "no input! return"; return; } const phi::SelectedRows* has_value_input = nullptr; for (auto* in : inputs) { - if (in->rows().size() > 0) { + if (!in->rows().empty()) { has_value_input = in; break; } @@ -852,7 +852,7 @@ struct MergeAverage { std::set merged_row_set; size_t row_num = 0; for (auto* input : inputs) { - if (input->rows().size() == 0) { + if (input->rows().empty()) { continue; } PADDLE_ENFORCE_EQ( @@ -891,7 +891,7 @@ struct MergeAverage { auto blas = phi::funcs::GetBlas(context); for (auto* input : inputs) { - if (input->rows().size() == 0) { + if (input->rows().empty()) { continue; } auto* input_data = input->value().data(); diff --git a/paddle/phi/kernels/gpu/rnn_grad_kernel.cu.cc b/paddle/phi/kernels/gpu/rnn_grad_kernel.cu.cc index 910c8e8b6a57a..7e92bde02e08e 100644 --- a/paddle/phi/kernels/gpu/rnn_grad_kernel.cu.cc +++ b/paddle/phi/kernels/gpu/rnn_grad_kernel.cu.cc @@ -189,7 +189,7 @@ void RnnGradKernel(const Context &dev_ctx, const T *init_c_data = nullptr; // const T *last_c_data = nullptr; const T *last_c_grad_data = nullptr; - T *init_h_grad_data = pre_state_grad.size() != 0 && pre_state_grad[0] + T *init_h_grad_data = !pre_state_grad.empty() && pre_state_grad[0] ? dev_ctx.template Alloc(pre_state_grad[0]) : nullptr; T *init_c_grad_data = nullptr; diff --git a/paddle/phi/kernels/onednn/interpolate_kernel.cc b/paddle/phi/kernels/onednn/interpolate_kernel.cc index 0481453a91cbd..082e21bafa0e2 100644 --- a/paddle/phi/kernels/onednn/interpolate_kernel.cc +++ b/paddle/phi/kernels/onednn/interpolate_kernel.cc @@ -97,7 +97,7 @@ std::vector ComputeOutputShape( out_dims.push_back(out_w); } - if (size_tensor && size_tensor.get().size() > 0) { + if (size_tensor && !size_tensor.get().empty()) { auto new_size = funcs::get_new_shape(size_tensor.get()); if (new_size.size() == out_dims.size()) { out_dims = new_size; @@ -117,7 +117,7 @@ std::vector ComputeOutputShape( scale.resize(3, scale_data[0]); std::copy(scale_data.begin(), scale_data.end(), scale.begin()); } else { - if (scale_attr.size() > 0) { + if (!scale_attr.empty()) { scale.resize(3, scale_attr[0]); std::copy(scale_attr.begin(), scale_attr.end(), scale.begin()); } diff --git a/paddle/phi/kernels/onednn/slice_kernel.cc b/paddle/phi/kernels/onednn/slice_kernel.cc index dfda78de77c06..9b098a3f14119 100644 --- a/paddle/phi/kernels/onednn/slice_kernel.cc +++ b/paddle/phi/kernels/onednn/slice_kernel.cc @@ -79,7 +79,7 @@ void SliceKernel(const Context& dev_ctx, std::vector new_out_dims(slice_dims.size() - decrease_axis.size()); - if (new_out_dims.size() == 0) { + if (new_out_dims.empty()) { new_out_dims.emplace_back(1); } else { for (const auto& axis : decrease_axis) { diff --git a/paddle/phi/kernels/onednn/transpose_grad_kernel.cc b/paddle/phi/kernels/onednn/transpose_grad_kernel.cc index e63faf2600964..ca969b5625b5a 100644 --- a/paddle/phi/kernels/onednn/transpose_grad_kernel.cc +++ b/paddle/phi/kernels/onednn/transpose_grad_kernel.cc @@ -30,7 +30,7 @@ void TransposeGradKernel(const Context& dev_ctx, const auto& onednn_engine = dev_ctx.GetEngine(); - if (axis.size() == 1 || axis.size() == 0) { + if (axis.size() == 1 || axis.empty()) { Copy(dev_ctx, out_grad, out_grad.place(), false, x_grad); x_grad->set_mem_desc(out_grad.mem_desc()); return; diff --git a/paddle/phi/kernels/onednn/transpose_kernel.cc b/paddle/phi/kernels/onednn/transpose_kernel.cc index e76d33fc786f5..d382572aa0c6a 100644 --- a/paddle/phi/kernels/onednn/transpose_kernel.cc +++ b/paddle/phi/kernels/onednn/transpose_kernel.cc @@ -59,7 +59,7 @@ void TransposeKernel(const Context& dev_ctx, AllocationType::CPU, errors::PreconditionNotMet("oneDNN Transpose kernel must use CPUPlace")); - if (axis.size() == 1 || axis.size() == 0) { + if (axis.size() == 1 || axis.empty()) { Copy(dev_ctx, x, x.place(), false, out); out->set_mem_desc(x.mem_desc()); return; diff --git a/paddle/phi/kernels/selected_rows/cpu/adam_kernel.cc b/paddle/phi/kernels/selected_rows/cpu/adam_kernel.cc index 98c49da01da7a..960a6e52ebd10 100644 --- a/paddle/phi/kernels/selected_rows/cpu/adam_kernel.cc +++ b/paddle/phi/kernels/selected_rows/cpu/adam_kernel.cc @@ -103,7 +103,7 @@ void AdamDenseParamSparseGradKernel( "value is:%d.", beta2_pow_out->numel())); - if (grad.rows().size() == 0) { + if (grad.rows().empty()) { VLOG(3) << "grad row size is 0!!"; return; } diff --git a/paddle/phi/ops/compat/slice_sig.cc b/paddle/phi/ops/compat/slice_sig.cc index beb5e4c959afe..bb1dbb3af0960 100644 --- a/paddle/phi/ops/compat/slice_sig.cc +++ b/paddle/phi/ops/compat/slice_sig.cc @@ -32,8 +32,8 @@ KernelSignature SliceOpArgumentMapping(const ArgumentMappingContext& ctx) { ends_name = "EndsTensorList"; } - if (paddle::any_cast>(ctx.Attr("decrease_axis")).size() > - 0) { + if (!paddle::any_cast>(ctx.Attr("decrease_axis")) + .empty()) { return KernelSignature( "slice_array_dense", {"Input"}, {starts_name}, {"Out"}); } else { @@ -131,8 +131,8 @@ KernelSignature SliceGradOpArgumentMapping(const ArgumentMappingContext& ctx) { } else if (ctx.InputSize("EndsTensorList") > 0) { ends_name = "EndsTensorList"; } - if (paddle::any_cast>(ctx.Attr("decrease_axis")).size() > - 0) { + if (!paddle::any_cast>(ctx.Attr("decrease_axis")) + .empty()) { return KernelSignature("slice_array_dense_grad", {"Input", "Out@GRAD"}, {starts_name}, diff --git a/paddle/testing/paddle_gtest_main.cc b/paddle/testing/paddle_gtest_main.cc index 7295e86182734..259782e2ab994 100644 --- a/paddle/testing/paddle_gtest_main.cc +++ b/paddle/testing/paddle_gtest_main.cc @@ -61,7 +61,7 @@ int main(int argc, char** argv) { } char* env_str = nullptr; - if (envs.size() > 0) { + if (!envs.empty()) { std::string env_string = "--tryfromenv="; for (auto t : envs) { env_string += t + ","; @@ -73,7 +73,7 @@ int main(int argc, char** argv) { } char* undefok_str = nullptr; - if (undefok.size() > 0) { + if (!undefok.empty()) { std::string undefok_string = "--undefok="; for (auto t : undefok) { undefok_string += t + ","; diff --git a/paddle/utils/span_test.cc b/paddle/utils/span_test.cc index 0dfbaafda2223..9ca34b7fefb9d 100644 --- a/paddle/utils/span_test.cc +++ b/paddle/utils/span_test.cc @@ -33,7 +33,7 @@ TEST(default_ctor, span) { // dynamic size { constexpr span s{}; - static_assert(s.size() == 0, ""); + static_assert(s.empty(), ""); static_assert(s.data() == nullptr, ""); #ifndef _MSC_VER static_assert(s.begin() == s.end(), ""); @@ -45,7 +45,7 @@ TEST(default_ctor, span) { // fixed size { constexpr span s{}; - static_assert(s.size() == 0, ""); + static_assert(s.empty(), ""); static_assert(s.data() == nullptr, ""); #ifndef _MSC_VER static_assert(s.begin() == s.end(), ""); @@ -480,7 +480,7 @@ TEST(ctor_from_spans, span) { constexpr zero_const_span s0{}; constexpr dynamic_const_span d{s0}; - static_assert(d.size() == 0, ""); + static_assert(d.empty(), ""); static_assert(d.data() == nullptr, ""); #ifndef _MSC_VER static_assert(d.begin() == d.end(), ""); @@ -574,7 +574,7 @@ TEST(subview, span) { TEST(observers, span) { // We already use this everywhere, but whatever constexpr span empty{}; - static_assert(empty.size() == 0, ""); + static_assert(empty.size() == 0, ""); // NOLINT static_assert(empty.empty(), ""); constexpr int arr[] = {1, 2, 3}; diff --git a/test/cpp/fluid/fused/fusion_group_op_test.cc b/test/cpp/fluid/fused/fusion_group_op_test.cc index 17128a1add492..9be43b0d9719e 100644 --- a/test/cpp/fluid/fused/fusion_group_op_test.cc +++ b/test/cpp/fluid/fused/fusion_group_op_test.cc @@ -32,7 +32,7 @@ phi::DenseTensor* CreateTensor(framework::Scope* scope, const std::vector& shape) { auto* var = scope->Var(name); auto* tensor = var->GetMutable(); - if (shape.size() > 0) { + if (!shape.empty()) { tensor->mutable_data(phi::make_ddim(shape), place); } return tensor; diff --git a/test/cpp/fluid/prim_ops/prim_op_test.cc b/test/cpp/fluid/prim_ops/prim_op_test.cc index 87ec25d2f8cf3..0d3c1f8a0cf1c 100644 --- a/test/cpp/fluid/prim_ops/prim_op_test.cc +++ b/test/cpp/fluid/prim_ops/prim_op_test.cc @@ -49,7 +49,7 @@ static void NewVar(BlockDesc *block, const std::string &name, const std::vector &shape) { auto *var_desc = block->Var(name); - if (shape.size() > 0) { + if (!shape.empty()) { var_desc->SetShape(shape); var_desc->SetType(proto::VarType::LOD_TENSOR); var_desc->SetDataType(proto::VarType_Type_FP32); diff --git a/test/cpp/inference/api/analyzer_lac_tester.cc b/test/cpp/inference/api/analyzer_lac_tester.cc index c4ef9389bd4ab..fb82bbc3b2d94 100644 --- a/test/cpp/inference/api/analyzer_lac_tester.cc +++ b/test/cpp/inference/api/analyzer_lac_tester.cc @@ -72,7 +72,7 @@ struct DataRecord { lod.push_back(0); } } - if (one_batch.size() != 0) { + if (!one_batch.empty()) { batched_datas.push_back(one_batch); batched_lods.push_back(lod); } diff --git a/test/cpp/ir/core/ir_program_test.cc b/test/cpp/ir/core/ir_program_test.cc index a6345829d07df..d94fb6026c1c5 100644 --- a/test/cpp/ir/core/ir_program_test.cc +++ b/test/cpp/ir/core/ir_program_test.cc @@ -203,7 +203,7 @@ TEST(program_test, slice_combine_test) { // (2) Create an empty program object ir::Program program(ctx); // ir::Program *program = new ir::Program(); - EXPECT_EQ(program.block()->size() == 0, true); + EXPECT_EQ(program.block()->empty(), true); // (3) Create a float32 DenseTensor Parameter and save into Program ir::Type fp32_dtype = ir::Float32Type::get(ctx); diff --git a/test/cpp/phi/core/test_custom_kernel.cc b/test/cpp/phi/core/test_custom_kernel.cc index a8dcd89c87c95..38f59589f7247 100644 --- a/test/cpp/phi/core/test_custom_kernel.cc +++ b/test/cpp/phi/core/test_custom_kernel.cc @@ -75,8 +75,8 @@ void FakeDot(const Context& dev_ctx, assert(fake_attr_double == 3); assert(fake_attr_int64 == 4); assert(fake_attr_dtype == phi::DataType::UINT32); - assert(fake_attr_int64_vec.size() == 0); - assert(fake_attr_int_vec.size() == 0); + assert(fake_attr_int64_vec.empty()); + assert(fake_attr_int_vec.empty()); assert(fake_out_vec.size() == 2); auto const *x_ptr = x.data(), *x_ptr_ = &x_ptr[0]; diff --git a/tools/codestyle/clang-tidy.py b/tools/codestyle/clang-tidy.py new file mode 100644 index 0000000000000..c1437873c7609 --- /dev/null +++ b/tools/codestyle/clang-tidy.py @@ -0,0 +1,415 @@ +#!/usr/bin/env python3 + +# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# +# ===- run-clang-tidy.py - Parallel clang-tidy runner ---------*- python -*--===# +# +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# ===------------------------------------------------------------------------===# +# FIXME: Integrate with clang-tidy-diff.py + +""" +Parallel clang-tidy runner +========================== + +Runs clang-tidy over all files in a compilation database. Requires clang-tidy +and clang-apply-replacements in $PATH. + +Example invocations. +- Run clang-tidy on all files in the current working directory with a default + set of checks and show warnings in the cpp files and all project headers. + run-clang-tidy.py $PWD + +- Fix all header guards. + run-clang-tidy.py -fix -checks=-*,llvm-header-guard + +- Fix all header guards included from clang-tidy and header guards + for clang-tidy headers. + run-clang-tidy.py -fix -checks=-*,llvm-header-guard extra/clang-tidy \ + -header-filter=extra/clang-tidy + +Compilation database setup: +http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html +""" + + +import argparse +import glob +import json +import multiprocessing +import os +import re +import shutil +import subprocess +import sys +import tempfile +import threading +import traceback + +try: + import yaml +except ImportError: + yaml = None + +is_py2 = sys.version[0] == '2' + +if is_py2: + import Queue as queue +else: + import queue + + +def find_compilation_database(path): + """Adjusts the directory until a compilation database is found.""" + result = './' + while not os.path.isfile(os.path.join(result, path)): + if os.path.realpath(result) == '/': + print('Error: could not find compilation database.') + sys.exit(1) + result += '../' + return os.path.realpath(result) + + +def make_absolute(f, directory): + if os.path.isabs(f): + return f + return os.path.normpath(os.path.join(directory, f)) + + +def get_tidy_invocation( + f, + clang_tidy_binary, + checks, + tmpdir, + build_path, + header_filter, + extra_arg, + extra_arg_before, + quiet, + config, +): + """Gets a command line for clang-tidy.""" + start = [clang_tidy_binary] + if header_filter is not None: + start.append('-header-filter=' + header_filter) + if checks: + start.append('-checks=' + checks) + if tmpdir is not None: + start.append('-export-fixes') + # Get a temporary file. We immediately close the handle so clang-tidy can + # overwrite it. + (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir) + os.close(handle) + start.append(name) + for arg in extra_arg: + start.append('-extra-arg=%s' % arg) + for arg in extra_arg_before: + start.append('-extra-arg-before=%s' % arg) + start.append('-p=' + build_path) + if quiet: + start.append('-quiet') + if config: + start.append('-config=' + config) + start.append(f) + return start + + +def merge_replacement_files(tmpdir, mergefile): + """Merge all replacement files in a directory into a single file""" + # The fixes suggested by clang-tidy >= 4.0.0 are given under + # the top level key 'Diagnostics' in the output yaml files + mergekey = "Diagnostics" + merged = [] + for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')): + content = yaml.safe_load(open(replacefile, 'r')) + if not content: + continue # Skip empty files. + merged.extend(content.get(mergekey, [])) + + if merged: + # MainSourceFile: The key is required by the definition inside + # include/clang/Tooling/ReplacementsYaml.h, but the value + # is actually never used inside clang-apply-replacements, + # so we set it to '' here. + output = {'MainSourceFile': '', mergekey: merged} + with open(mergefile, 'w') as out: + yaml.safe_dump(output, out) + else: + # Empty the file: + open(mergefile, 'w').close() + + +def check_clang_apply_replacements_binary(args): + """Checks if invoking supplied clang-apply-replacements binary works.""" + try: + subprocess.check_call( + [args.clang_apply_replacements_binary, '--version'] + ) + except: + print( + 'Unable to run clang-apply-replacements. Is clang-apply-replacements ' + 'binary correctly specified?', + file=sys.stderr, + ) + traceback.print_exc() + sys.exit(1) + + +def apply_fixes(args, tmpdir): + """Calls clang-apply-fixes on a given directory.""" + invocation = [args.clang_apply_replacements_binary] + if args.format: + invocation.append('-format') + if args.style: + invocation.append('-style=' + args.style) + invocation.append(tmpdir) + subprocess.call(invocation) + + +def run_tidy(args, tmpdir, build_path, queue, lock, failed_files): + """Takes filenames out of queue and runs clang-tidy on them.""" + while True: + name = queue.get() + invocation = get_tidy_invocation( + name, + args.clang_tidy_binary, + args.checks, + tmpdir, + build_path, + args.header_filter, + args.extra_arg, + args.extra_arg_before, + args.quiet, + args.config, + ) + + proc = subprocess.Popen( + invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + output, err = proc.communicate() + if proc.returncode != 0: + failed_files.append(name) + with lock: + sys.stdout.write( + ' '.join(invocation) + '\n' + output.decode('utf-8') + ) + if len(err) > 0: + sys.stdout.flush() + sys.stderr.write(err.decode('utf-8')) + queue.task_done() + + +def main(): + parser = argparse.ArgumentParser( + description='Runs clang-tidy over all files ' + 'in a compilation database. Requires ' + 'clang-tidy and clang-apply-replacements in ' + '$PATH.' + ) + parser.add_argument( + '-clang-tidy-binary', + metavar='PATH', + default='clang-tidy-10', + help='path to clang-tidy binary', + ) + parser.add_argument( + '-clang-apply-replacements-binary', + metavar='PATH', + default='clang-apply-replacements-10', + help='path to clang-apply-replacements binary', + ) + parser.add_argument( + '-checks', + default=None, + help='checks filter, when not specified, use clang-tidy ' 'default', + ) + parser.add_argument( + '-config', + default=None, + help='Specifies a configuration in YAML/JSON format: ' + ' -config="{Checks: \'*\', ' + ' CheckOptions: [{key: x, ' + ' value: y}]}" ' + 'When the value is empty, clang-tidy will ' + 'attempt to find a file named .clang-tidy for ' + 'each source file in its parent directories.', + ) + parser.add_argument( + '-header-filter', + default=None, + help='regular expression matching the names of the ' + 'headers to output diagnostics from. Diagnostics from ' + 'the main file of each translation unit are always ' + 'displayed.', + ) + if yaml: + parser.add_argument( + '-export-fixes', + metavar='filename', + dest='export_fixes', + help='Create a yaml file to store suggested fixes in, ' + 'which can be applied with clang-apply-replacements.', + ) + parser.add_argument( + '-j', + type=int, + default=0, + help='number of tidy instances to be run in parallel.', + ) + parser.add_argument( + 'files', + nargs='*', + default=['.*'], + help='files to be processed (regex on path)', + ) + parser.add_argument('-fix', action='store_true', help='apply fix-its') + parser.add_argument( + '-format', + action='store_true', + help='Reformat code ' 'after applying fixes', + ) + parser.add_argument( + '-style', + default='file', + help='The style of reformat ' 'code after applying fixes', + ) + parser.add_argument( + '-p', + dest='build_path', + help='Path used to read a compile command database.', + ) + parser.add_argument( + '-extra-arg', + dest='extra_arg', + action='append', + default=[], + help='Additional argument to append to the compiler ' 'command line.', + ) + parser.add_argument( + '-extra-arg-before', + dest='extra_arg_before', + action='append', + default=[], + help='Additional argument to prepend to the compiler ' 'command line.', + ) + parser.add_argument( + '-quiet', action='store_true', help='Run clang-tidy in quiet mode' + ) + args = parser.parse_args() + + db_path = 'compile_commands.json' + + if args.build_path is not None: + build_path = args.build_path + else: + # Find our database + build_path = find_compilation_database(db_path) + + try: + invocation = [args.clang_tidy_binary, '-list-checks'] + invocation.append('-p=' + build_path) + if args.checks: + invocation.append('-checks=' + args.checks) + invocation.append('-') + if args.quiet: + # Even with -quiet we still want to check if we can call clang-tidy. + with open(os.devnull, 'w') as dev_null: + subprocess.check_call(invocation, stdout=dev_null) + else: + subprocess.check_call(invocation) + except: + print("Unable to run clang-tidy.", file=sys.stderr) + sys.exit(0) + + # Load the database and extract all files. + database = json.load(open(os.path.join(build_path, db_path))) + files = [ + make_absolute(entry['file'], entry['directory']) for entry in database + ] + + max_task = args.j + if max_task == 0: + max_task = multiprocessing.cpu_count() + + tmpdir = None + if args.fix or (yaml and args.export_fixes): + check_clang_apply_replacements_binary(args) + tmpdir = tempfile.mkdtemp() + + # Build up a big regexy filter from all command line arguments. + file_name_re = re.compile('|'.join(args.files)) + + return_code = 0 + try: + # Spin up a bunch of tidy-launching threads. + task_queue = queue.Queue(max_task) + # List of files with a non-zero return code. + failed_files = [] + lock = threading.Lock() + for _ in range(max_task): + t = threading.Thread( + target=run_tidy, + args=(args, tmpdir, build_path, task_queue, lock, failed_files), + ) + t.daemon = True + t.start() + + # Fill the queue with files. + for name in files: + if file_name_re.search(name): + task_queue.put(name) + + # Wait for all threads to be done. + task_queue.join() + if len(failed_files): + return_code = 1 + + except KeyboardInterrupt: + # This is a sad hack. Unfortunately subprocess goes + # bonkers with ctrl-c and we start forking merrily. + print('\nCtrl-C detected, goodbye.') + if tmpdir: + shutil.rmtree(tmpdir) + os.kill(0, 9) + + if yaml and args.export_fixes: + print('Writing fixes to ' + args.export_fixes + ' ...') + try: + merge_replacement_files(tmpdir, args.export_fixes) + except: + print('Error exporting fixes.\n', file=sys.stderr) + traceback.print_exc() + return_code = 1 + + if args.fix: + print('Applying fixes ...') + try: + apply_fixes(args, tmpdir) + except: + print('Error applying fixes.\n', file=sys.stderr) + traceback.print_exc() + return_code = 1 + + if tmpdir: + shutil.rmtree(tmpdir) + sys.exit(return_code) + + +if __name__ == '__main__': + main()