使用tflite_runtime运行转换后模型时出现Segmentation Fault求助
解决tflite_runtime加载模型时出现Segmentation Fault:11的问题
环境信息
- macOS
- Python 3.8.5
- TensorFlow 2.7.0
- tflite_runtime 2.5.0
模型结构
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dropout (Dropout) (None, 42) 0 dense (Dense) (None, 50) 2150 dropout_1 (Dropout) (None, 50) 0 dense_1 (Dense) (None, 50) 2550 dense_2 (Dense) (None, 5) 255 ================================================================= Total params: 4,955 Trainable params: 4,955 Non-trainable params: 0 _________________________________________________________________
问题描述
Keras手部姿态检测模型转换为TFLite格式成功,使用tf.lite.Interpreter运行推理正常,但切换到tflite_runtime.interpreter时直接触发segmentation fault: 11,无额外错误信息,需要仅依赖tflite_runtime运行模型。
模型转换代码
saved_model_dir = './save_at_500.h5' model = tf.keras.models.load_model(saved_model_dir) df = pd.read_csv('./test_hand_data_2.csv') gt = np.array([]) lmk = np.array([]) gt = np.append(gt, df['pose'].to_numpy()-1) lmk = np.append(lmk, df.loc[:,'lx0':'ly20'].to_numpy()) lmk = np.reshape(lmk,(gt.shape[0],42)) def representative_dataset(): for data in tf.data.Dataset.from_tensor_slices((lmk)).batch(1).take(100): yield [tf.dtypes.cast(data, tf.float32)] converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS] converter.allow_custom_ops=True converter.representative_dataset = representative_dataset tflite_quant_model = converter.convert() open( 'model.tflite' , 'wb' ).write(tflite_quant_model)
推理代码
import cv2 import numpy as np import tflite_runtime.interpreter as tflite #import tensorflow as tf import pandas as pd import os from time import time def main(): model_path = os.path.join(path,'models/6-10/model.tflite') #interpreter = tf.lite.Interpreter(model_path) # 此代码可正常运行 interpreter = tflite.Interpreter(model_path=model_path) # 在此处触发segmentation fault interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() print('INPUT\n', input_details) print('\n OUTPUT\n',output_details) lmk,gt = get_data() input_data = [lmk[0]] print(input_data) interpreter.set_tensor(input_details[0]['index'], input_data) # 执行推理 t1=time() interpreter.invoke() t2=time() output_data = interpreter.get_tensor(output_details[0]['index']) print(output_data) print('Inference time:',t2-t1,'s') if __name__ == "__main__": main()
解决方案
1. 对齐tflite_runtime与TensorFlow版本
当前TensorFlow 2.7.0和tflite_runtime 2.5.0版本不匹配,这是引发Segmentation Fault的核心原因。TFLite模型转换和运行的版本必须一致,否则会因内部API、算子实现差异导致内存错误。
执行以下命令安装对应版本的tflite_runtime:
pip install tflite_runtime==2.7.0 --index-url https://google-coral.github.io/py-repo/
2. 简化模型转换配置
你的模型仅包含标准Dense和Dropout层,无需开启allow_custom_ops=True,可移除该配置避免潜在兼容性问题:
# 移除该行代码 # converter.allow_custom_ops=True
若无需量化优化,可暂时关闭相关配置,先验证基础模型是否能正常运行:
# 注释量化相关配置 # converter.optimizations = [tf.lite.Optimize.DEFAULT] # converter.representative_dataset = representative_dataset
3. 修正输入数据格式
确保输入数据的形状、 dtype与模型要求完全匹配:
- 输入数据需为
float32类型(与转换时的representative_dataset一致) - 输入形状需为
(1,42)(模型输入是(None,42),批量大小为1)
修改推理代码中的输入数据处理部分:
input_data = np.expand_dims(lmk[0], axis=0).astype(np.float32)
4. macOS环境兼容调整
若上述操作无效,可尝试:
- 使用官方Python安装包或Homebrew安装Python,避免conda环境的依赖冲突
- 重启终端或IDE,清除缓存问题
内容的提问来源于stack exchange,提问作者Emil Winzell
相关产品推荐
相关产品推荐

