xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/mlir/lite/python/graphdef_to_tfl_flatbuffer.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/compiler/mlir/lite/python/graphdef_to_tfl_flatbuffer.h"
17 
18 #include <ostream>
19 #include <string>
20 #include <utility>
21 
22 #include "llvm/ADT/None.h"
23 #include "llvm/Support/ToolOutputFile.h"
24 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
25 #include "mlir/IR/BuiltinOps.h"  // from @llvm-project
26 #include "mlir/IR/MLIRContext.h"  // from @llvm-project
27 #include "mlir/Pass/Pass.h"  // from @llvm-project
28 #include "mlir/Support/FileUtilities.h"  // from @llvm-project
29 #include "mlir/Transforms/ViewOpGraph.h"  // from @llvm-project
30 #include "tensorflow/compiler/mlir/lite/common/tfl_pass_config.h"
31 #include "tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.h"
32 #include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h"
33 #include "tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h"
34 #include "tensorflow/compiler/mlir/lite/transforms/passes.h"
35 #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
36 #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
37 #include "tensorflow/core/framework/graph.pb.h"
38 #include "tensorflow/core/framework/types.pb.h"
39 #include "tensorflow/core/lib/core/errors.h"
40 #include "tensorflow/core/platform/status.h"
41 #include "tensorflow/core/protobuf/graph_debug_info.pb.h"
42 #include "tensorflow/lite/toco/model_flags.pb.h"
43 #include "tensorflow/lite/toco/toco_flags.pb.h"
44 #include "tensorflow/lite/toco/types.pb.h"
45 #include "tensorflow/stream_executor/lib/statusor.h"
46 
47 namespace tensorflow {
ConvertGraphDefToTFLiteFlatBuffer(const toco::ModelFlags & model_flags,const toco::TocoFlags & toco_flags,const GraphDebugInfo & debug_info,const GraphDef & input,string * result)48 Status ConvertGraphDefToTFLiteFlatBuffer(const toco::ModelFlags& model_flags,
49                                          const toco::TocoFlags& toco_flags,
50                                          const GraphDebugInfo& debug_info,
51                                          const GraphDef& input,
52                                          string* result) {
53   using ::tflite::optimize::ReducedPrecisionSupport;
54   mlir::MLIRContext context;
55   GraphImportConfig specs;
56   mlir::quant::QuantizationSpecs quant_specs;
57 
58   // Parse input arrays.
59   std::vector<string> node_names;
60   std::vector<string> node_dtypes;
61   std::vector<llvm::Optional<std::vector<int>>> node_shapes;
62   std::vector<llvm::Optional<double>> node_mins;
63   std::vector<llvm::Optional<double>> node_maxs;
64 
65   // Populate quantization specs.
66   TF_RETURN_IF_ERROR(internal::PopulateQuantizationSpecs(
67       model_flags, toco_flags, &quant_specs, &node_names, &node_dtypes,
68       &node_shapes, &node_mins, &node_maxs));
69 
70   TF_RETURN_IF_ERROR(tensorflow::ParseInputArrayInfo(
71       node_names, node_dtypes, node_shapes, &specs.inputs));
72 
73   // Parse output arrays.
74   std::vector<string> output_arrays(model_flags.output_arrays().begin(),
75                                     model_flags.output_arrays().end());
76   TF_RETURN_IF_ERROR(
77       tensorflow::ParseOutputArrayInfo(output_arrays, &specs.outputs));
78 
79   // Parse control output arrays.
80   std::vector<string> control_output_arrays(
81       model_flags.control_output_arrays().begin(),
82       model_flags.control_output_arrays().end());
83   TF_RETURN_IF_ERROR(tensorflow::ParseOutputArrayInfo(control_output_arrays,
84                                                       &specs.control_outputs));
85 
86   specs.prune_unused_nodes = true;
87   specs.convert_legacy_fed_inputs = true;
88   specs.graph_as_function = false;
89   specs.upgrade_legacy = true;
90   specs.unconditionally_use_set_output_shapes = true;
91   internal::WarningUnusedFlags(model_flags, toco_flags);
92 
93   // Register all custom ops, including user-specified custom ops.
94   TF_RETURN_IF_ERROR(internal::RegisterAllCustomOps(toco_flags));
95 
96   TF_ASSIGN_OR_RETURN(
97       auto module, ConvertGraphdefToMlir(input, debug_info, specs, &context));
98 
99   mlir::TFL::PassConfig pass_config(quant_specs);
100   bool emit_builtin_tflite_ops = !toco_flags.force_select_tf_ops();
101   pass_config.emit_builtin_tflite_ops = emit_builtin_tflite_ops;
102   pass_config.unfold_batch_matmul = toco_flags.unfold_batchmatmul();
103   pass_config.lower_tensor_list_ops = toco_flags.lower_tensor_list_ops();
104   // Disable the unfolding of the 16x16 TF::BatchMatMulOp to avoid the
105   // conversion to an unsupported 16x16 TFL::FullyConnectedOp.
106   if (toco_flags.inference_type() == toco::IODataType::QUANTIZED_INT16) {
107     pass_config.unfold_batch_matmul = false;
108   }
109   pass_config.unfold_large_splat_constant =
110       toco_flags.unfold_large_splat_constant();
111   pass_config.enable_dynamic_update_slice =
112       toco_flags.enable_dynamic_update_slice();
113   pass_config.preserve_assert_op = toco_flags.preserve_assert_op();
114   pass_config.guarantee_all_funcs_one_use =
115       toco_flags.guarantee_all_funcs_one_use();
116 
117   return internal::ConvertMLIRToTFLiteFlatBuffer(
118       model_flags, toco_flags, std::move(module), pass_config,
119       /*saved_model_tags=*/{}, result,
120       /*session=*/llvm::None);
121 }
122 
123 }  // namespace tensorflow
124