-
Notifications
You must be signed in to change notification settings - Fork 3.6k
[CoreML EP] Add support of BatchNormalization/Reshape/Global[Average/Max]Pool #6625
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
onnxruntime/core/providers/coreml/builders/impl/batch_norm_op_builder.cc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| #include "core/providers/common.h" | ||
| #include "core/providers/shared/utils/utils.h" | ||
| #include "core/providers/coreml/builders/helper.h" | ||
| #include "core/providers/coreml/builders/model_builder.h" | ||
| #include "core/providers/coreml/builders/op_builder_factory.h" | ||
|
|
||
| #include "base_op_builder.h" | ||
| #include "builder_utils.h" | ||
|
|
||
| namespace onnxruntime { | ||
| namespace coreml { | ||
|
|
||
| class BatchNormalizationOpBuilder : public BaseOpBuilder { | ||
| // Add operator related | ||
| public: | ||
| void AddInitializersToSkip(ModelBuilder& model_builder, const Node& node) const override; | ||
|
|
||
| private: | ||
| Status AddToModelBuilderImpl(ModelBuilder& model_builder, const Node& node, | ||
| const logging::Logger& logger) const override ORT_MUST_USE_RESULT; | ||
|
|
||
| // Operator support related | ||
| private: | ||
| bool IsOpSupportedImpl(const InitializedTensorSet& initializers, const Node& node, | ||
| const logging::Logger& logger) const override; | ||
|
|
||
| // BatchNormalization opset 6- has unsupported attributes | ||
| int GetMinSupportedOpSet(const Node& /* node */) const override { return 7; } | ||
| }; | ||
|
|
||
| // Add operator related | ||
|
|
||
| void BatchNormalizationOpBuilder::AddInitializersToSkip(ModelBuilder& model_builder, const Node& node) const { | ||
| // skip everything except input0 for BatchNormalization | ||
| const auto& input_defs = node.InputDefs(); | ||
| model_builder.AddInitializerToSkip(input_defs[1]->Name()); // scale | ||
| model_builder.AddInitializerToSkip(input_defs[2]->Name()); // B | ||
| model_builder.AddInitializerToSkip(input_defs[3]->Name()); // mean | ||
| model_builder.AddInitializerToSkip(input_defs[4]->Name()); // var | ||
| } | ||
|
|
||
| Status BatchNormalizationOpBuilder::AddToModelBuilderImpl(ModelBuilder& model_builder, | ||
| const Node& node, | ||
| const logging::Logger& /* logger */) const { | ||
| std::unique_ptr<COREML_SPEC::NeuralNetworkLayer> layer = CreateNNLayer(node); | ||
|
|
||
| const auto& input_defs = node.InputDefs(); | ||
| const auto& initializers(model_builder.GetInitializerTensors()); | ||
| NodeAttrHelper helper(node); | ||
|
|
||
| const auto& scale_tensor = *initializers.at(input_defs[1]->Name()); | ||
| const auto& bias_tensor = *initializers.at(input_defs[2]->Name()); | ||
| const auto& mean_tensor = *initializers.at(input_defs[3]->Name()); | ||
| const auto& var_tensor = *initializers.at(input_defs[4]->Name()); | ||
| const auto eps = helper.Get("epsilon", 1e-5f); | ||
| const auto channels = scale_tensor.dims()[0]; | ||
|
|
||
| auto* coreml_batch_norm = layer->mutable_batchnorm(); | ||
| coreml_batch_norm->set_channels(channels); | ||
| coreml_batch_norm->set_epsilon(eps); | ||
| coreml_batch_norm->set_computemeanvar(false); | ||
| coreml_batch_norm->set_instancenormalization(false); | ||
|
|
||
| CreateCoreMLWeight(*coreml_batch_norm->mutable_gamma(), scale_tensor); // scale | ||
| CreateCoreMLWeight(*coreml_batch_norm->mutable_beta(), bias_tensor); // B | ||
| CreateCoreMLWeight(*coreml_batch_norm->mutable_mean(), mean_tensor); // mean | ||
| CreateCoreMLWeight(*coreml_batch_norm->mutable_variance(), var_tensor); // var | ||
|
|
||
| *layer->mutable_input()->Add() = node.InputDefs()[0]->Name(); | ||
| *layer->mutable_output()->Add() = node.OutputDefs()[0]->Name(); | ||
|
|
||
| model_builder.AddLayer(std::move(layer)); | ||
| return Status::OK(); | ||
| } | ||
|
|
||
| // Operator support related | ||
|
|
||
| bool BatchNormalizationOpBuilder::IsOpSupportedImpl(const InitializedTensorSet& initializers, const Node& node, | ||
| const logging::Logger& logger) const { | ||
| if (node.OutputDefs().size() != 1) { | ||
| LOGS(logger, VERBOSE) << "Your onnx model may be in training mode, please export " | ||
| "it in test mode."; | ||
| return false; | ||
| } | ||
|
|
||
| const auto& input_defs = node.InputDefs(); | ||
| std::vector<int64_t> input_shape; | ||
| if (!GetShape(*input_defs[0], input_shape, logger)) | ||
| return false; | ||
|
|
||
| const auto input_size = input_shape.size(); | ||
| // TODO, support 1d batch normalization (input is 3d) | ||
| // To map 1d input {N,C,H} to 2d {N,C,H,1} first and then squeeze back after | ||
| if (input_size != 4) { | ||
| LOGS(logger, VERBOSE) << "BN only support 4d shape for now, input is " | ||
| << input_size << "d shape"; | ||
| return false; | ||
| } | ||
|
|
||
| NodeAttrHelper helper(node); | ||
| const auto spatial = helper.Get("spatial", 1); | ||
| if (spatial != 1) { | ||
| LOGS(logger, VERBOSE) << "Non-spatial BN is not supported"; | ||
| return false; | ||
| } | ||
|
|
||
| const auto& scale_name = input_defs[1]->Name(); | ||
| const auto& b_name = input_defs[2]->Name(); | ||
| const auto& mean_name = input_defs[3]->Name(); | ||
| const auto& var_name = input_defs[4]->Name(); | ||
| if (!Contains(initializers, scale_name)) { | ||
| LOGS(logger, VERBOSE) << "Scale of BN must be a constant initializer"; | ||
| return false; | ||
| } | ||
| if (!Contains(initializers, b_name)) { | ||
| LOGS(logger, VERBOSE) << "B of BN must be a constant initializer"; | ||
| return false; | ||
| } | ||
| if (!Contains(initializers, mean_name)) { | ||
| LOGS(logger, VERBOSE) << "Mean of BN must be a constant initializer"; | ||
| return false; | ||
| } | ||
| if (!Contains(initializers, var_name)) { | ||
| LOGS(logger, VERBOSE) << "Var of BN must be a constant initializer"; | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| void CreateBatchNormalizationOpBuilder(const std::string& op_type, OpBuilderRegistrations& op_registrations) { | ||
| op_registrations.builders.push_back(onnxruntime::make_unique<BatchNormalizationOpBuilder>()); | ||
| op_registrations.op_builder_map.emplace(op_type, op_registrations.builders.back().get()); | ||
| } | ||
|
|
||
| } // namespace coreml | ||
| } // namespace onnxruntime | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
94 changes: 94 additions & 0 deletions
94
onnxruntime/core/providers/coreml/builders/impl/pool_op_builder.cc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| #include "core/providers/shared/utils/utils.h" | ||
| #include "core/providers/coreml/builders/helper.h" | ||
| #include "core/providers/coreml/builders/model_builder.h" | ||
| #include "core/providers/coreml/builders/op_builder_factory.h" | ||
|
|
||
| #include "base_op_builder.h" | ||
|
|
||
| namespace onnxruntime { | ||
| namespace coreml { | ||
|
|
||
| class PoolOpBuilder : public BaseOpBuilder { | ||
| // Add operator related | ||
| private: | ||
| Status AddToModelBuilderImpl(ModelBuilder& model_builder, const Node& node, | ||
| const logging::Logger& logger) const override ORT_MUST_USE_RESULT; | ||
|
|
||
| // Operator support related | ||
| private: | ||
| bool IsOpSupportedImpl(const InitializedTensorSet& initializers, const Node& node, | ||
| const logging::Logger& logger) const override; | ||
| }; | ||
|
|
||
| // Add operator related | ||
|
|
||
| Status PoolOpBuilder::AddToModelBuilderImpl(ModelBuilder& model_builder, | ||
| const Node& node, | ||
| const logging::Logger& /* logger */) const { | ||
| std::unique_ptr<COREML_SPEC::NeuralNetworkLayer> layer = CreateNNLayer(node); | ||
|
|
||
| auto* coreml_pool = layer->mutable_pooling(); | ||
| const auto& op_type = node.OpType(); | ||
|
|
||
| // We only support global pool now | ||
| coreml_pool->set_globalpooling(true); | ||
| coreml_pool->mutable_valid(); | ||
|
|
||
| if (op_type == "GlobalAveragePool") { | ||
| coreml_pool->set_type(COREML_SPEC::PoolingLayerParams_PoolingType_AVERAGE); | ||
| } else if (op_type == "GlobalMaxPool") { | ||
| coreml_pool->set_type(COREML_SPEC::PoolingLayerParams_PoolingType_MAX); | ||
| } | ||
|
|
||
guoyu-wang marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| *layer->mutable_input()->Add() = node.InputDefs()[0]->Name(); | ||
| *layer->mutable_output()->Add() = node.OutputDefs()[0]->Name(); | ||
|
|
||
| model_builder.AddLayer(std::move(layer)); | ||
| return Status::OK(); | ||
| } | ||
|
|
||
| // Operator support related | ||
| bool PoolOpBuilder::IsOpSupportedImpl(const InitializedTensorSet& /* initializers */, const Node& node, | ||
| const logging::Logger& logger) const { | ||
| const auto& op_type = node.OpType(); | ||
| if (op_type != "GlobalAveragePool" && op_type != "GlobalMaxPool") { | ||
| LOGS(logger, VERBOSE) << "[" << op_type << "] is not supported"; | ||
| return false; | ||
| } | ||
|
|
||
| std::vector<int64_t> input_shape; | ||
| if (!GetShape(*node.InputDefs()[0], input_shape, logger)) | ||
| return false; | ||
|
|
||
| const auto input_size = input_shape.size(); | ||
| if (input_size != 4) { | ||
| LOGS(logger, VERBOSE) | ||
| << op_type << " only supports rank-4 tensor, input [" | ||
| << node.InputDefs()[0]->Name() << "] has actual dim count " << input_size; | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| void CreatePoolOpBuilder(const std::string& op_type, OpBuilderRegistrations& op_registrations) { | ||
| if (op_registrations.op_builder_map.find(op_type) != op_registrations.op_builder_map.cend()) | ||
| return; | ||
|
|
||
| static std::vector<std::string> op_types = | ||
| { | ||
| "GlobalAveragePool", | ||
| "GlobalMaxPool", | ||
| }; | ||
|
|
||
| op_registrations.builders.push_back(onnxruntime::make_unique<PoolOpBuilder>()); | ||
| for (const auto& op_type : op_types) { | ||
| op_registrations.op_builder_map.emplace(op_type, op_registrations.builders.back().get()); | ||
| } | ||
| } | ||
|
|
||
| } // namespace coreml | ||
| } // namespace onnxruntime | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we infer the batch size to be 1 and treat it as 4d if input_size == 3? #Pending
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will be handled in a future PR, will need to add 1 to the end of the shape and make this a 2d batch norm, such as {N,C,H} -> {N,C,H,1}
Will need to add a ExpandDimsLayer (unsqueeze) before bn and a SqueezeLayer after
This may also be required by other ops since CoreML has weird shape for some layers
Updated comments
In reply to: 573438207 [](ancestors = 573438207)