2 * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "Quantizer.h"
19 #include <luci/ImporterEx.h>
20 #include <luci/CircleQuantizer.h>
21 #include <luci/CircleExporter.h>
22 #include <luci/CircleFileExpContract.h>
26 extern "C" onert::odc::IQuantizer *create_quantizer() { return new onert::odc::Quantizer(); }
27 extern "C" void destroy_quantizer(onert::odc::IQuantizer *quantizer) { delete quantizer; }
34 int Quantizer::quantize(const char *in, const char *out, bool is_q16)
36 // Load model from the file
37 luci::ImporterEx importerex;
38 auto module = importerex.importVerifyModule(std::string(in));
39 if (module.get() == nullptr)
42 luci::CircleQuantizer quantizer;
43 auto options = quantizer.options();
45 options->enable(luci::CircleQuantizer::Options::Algorithm::QuantizeWeights);
47 using AlgorithmParameters = luci::CircleQuantizer::Options::AlgorithmParameters;
48 options->param(AlgorithmParameters::Quantize_input_model_dtype, "float32");
49 options->param(AlgorithmParameters::Quantize_output_model_dtype, is_q16 ? "int16" : "int8");
50 options->param(AlgorithmParameters::Quantize_granularity, "channel");
53 for (size_t idx = 0; idx < module->size(); ++idx)
55 auto graph = module->graph(idx);
58 quantizer.quantize(graph);
61 // TODO Validate if needed
63 if (!luci::validate(graph))
65 std::cerr << "ERROR: Quantized graph is invalid" << std::endl;
71 // Export to output Circle file
72 luci::CircleExporter exporter;
73 luci::CircleFileExpContract contract(module.get(), std::string(out));
75 if (!exporter.invoke(&contract))
78 // Return 0 when luci::CircleQuantizer::Options::Algorithm::QuantizeWeights is ready