Ron_617 2024-04-04 15:31 采纳率: 0%
浏览 21
已结题

模型转换中遇到的问题.ckpt转trt格式

我首先利用train.py程序训练得到.model.ckpt格式的模型文件;
然后利用GraphDef.py程序将.model.ckpt格式的模型文件转换成.pb格式的模型文件;
然后再利用指将文件转换成onnx格式;
最后在jetson开发板中转换得到trt格式。
但是二者推理得到结果不一致,利用tensorflow的.model.ckp模型进行下属下述推理

def test(infrareds, images, global_layers, local_layers, scaling_factor, is_training):
    with tf.Graph().as_default():
        logits = model.inference(infrareds, images, global_layers,local_layers,scaling_factor,is_training)
        
    # dim = logits.get_shape()[3].value
        true_labels = tf.reshape(depthtest, [-1])
        true_labels = tf.cast(true_labels, tf.float32)
        #true_labels = tf.identity(true_labels)

        mask = (true_labels < 192) & (true_labels > 0)
        mask = tf.cast(mask, tf.float32)
        #mask = tf.identity(mask)

        pre_dep = tf.reshape(logits , [-1])
        pre_dep = tf.cast(pre_dep, tf.float32)

        cross_entropy = tf.reduce_mean(mask * tf.square(true_labels - pre_dep))

        saver = tf.compat.v1.train.Saver()
        with tf.Session() as sess:
            saver.restore(sess, 'saver/4.3/model.ckpt-83999')
            labels = sess.run(logits)
            loss = sess.run(cross_entropy)

得到的输出格式是(8, 448, 512, 1)
但是利用trt推理,利用下述代码:

def main():
    trt_model = "/home/nvidia/zza/IVFuseNet/IVFusion_model_fp16.trt"
    device = torch.device("cuda:0")

    left_images = sorted(glob.glob('/home/nvidia/zza/04-20_IGEV-main/IGEV-Stereo/kaist_test/thermal/*.jpg', recursive=True))
    #right_images = sorted(glob.glob('/home/nvidia/zza/04-20_IGEV-main/IGEV-Stereo/kaist_test/right/*.jpg', recursive=True))
    #print(f"Found {len(left_images)} images.")

    #print('deserializing trt engine')
    engine = None
    logger = trt.Logger(trt.Logger.INFO)
    
    # 这是一个上下文管理器,它同时打开一个文件和一个 TensorRT 运行时对象。trt_model 是序列化的 TensorRT 引擎文件的路径。
    # "rb" 指定以二进制只读模式打开文件。
    # f 是文件对象,runtime 是 TensorRT 运行时对象。
    # logger 是一个用于记录日志的 trt.Logger 对象,它在之前的代码中已经被定义了。
    with open(trt_model, "rb") as f, trt.Runtime(logger) as runtime:
        engine = runtime.deserialize_cuda_engine(f.read())

    model_all_names = []
    #print("engine bindings message: ")
    # 这段代码的作用是遍历 TensorRT 引擎中的所有绑定,对于每个绑定,获取其是否为输入、名称、数据类型和形状,并将名称添加到名为 model_all_names 的列表中
    for idx in range(engine.num_bindings):
        is_input = engine.binding_is_input(idx)
        name = engine.get_binding_name(idx)
        op_type = engine.get_binding_dtype(idx)
        model_all_names.append(name)
        shape = engine.get_binding_shape(idx)
        # 检查当前绑定是否为输入绑定且其形状是否为动态形状
        if is_input and is_dynamic(shape):
            profile_shapes = engine.get_profile_shape(0, idx)
            # print(profile_shapes)
     #   print('input id:', idx, '   is input: ', is_input, '  binding name:', name, '  shape:', shape, 'type: ', op_type)

    output_directory = Path("./output_trt_fp16/")
    output_directory.mkdir(exist_ok=True)
    # 设置模型 输入输出名称
    trt_model = TRTModule(engine, [model_all_names[0], model_all_names[1]], model_all_names[2:])

    start_time = time.time()
    batch_size = 1
    num_batches = len(left_images) // batch_size
    print(num_batches)
    j = 0
    
    for batch_idx in tqdm(range(num_batches)):
    
        batch_left_images = infrareds[batch_idx * batch_size: (batch_idx + 1) * batch_size]
        batch_right_images = images[batch_idx * batch_size: (batch_idx + 1) * batch_size]
        
        print(batch_left_images.shape)
        print(batch_right_images.shape)
        
        batch_left_images_torch = torch.from_numpy(batch_left_images).float().to("cuda:0")
        batch_right_images_torch = torch.from_numpy(batch_right_images).float().to("cuda:0")
    
        print(batch_left_images_torch.shape)
        print(batch_right_images_torch.shape)
        
        #images1 = load_image1(batch_left_images)
        #mages2 = load_image2(batch_right_images)

        # 处理整个批次的图像
        #padder = InputPadder(images1.shape[1:], divis_by=32)
        #images1_padded, images2_padded = padder.pad(images1, images2)
        trt_results = trt_model(batch_left_images_torch, batch_right_images_torch)
        print("************************")
        print("trt_results.shape:", trt_results.shape)

得到的结果是torch([1834208]),即 将8448512相乘得到,并且reshape后图片显示不正确,
和直接使用.ckpt模型得到的输出不同,应该说直接是错的怎么办

  • 写回答

17条回答 默认 最新

  • 关注

    下午好🌅🌅🌅
    本答案参考ChatGPT-3.5

    根据你提供的信息,你在模型转换过程中遇到了推理结果不一致的问题。推理结果不一致可能是由于多个原因造成的,下面是一些可能的解决方案:

    1. 确保模型转换的每个阶段都正确无误:

      • 确保训练过程中得到的 .model.ckpt 格式的模型文件是正确的。
      • 确保使用 GraphDef.py 将 .model.ckpt 格式的模型文件转换成 .pb 格式的模型文件时没有出错。
      • 确保使用指令将 .pb 格式的模型文件转换成 .onnx 格式时没有出错。
      • 确保在 jetson 开发板中将 .onnx 格式的模型文件转换成 trt 格式时没有出错。
    2. 检查推理过程中的代码逻辑:

      • 确保在 TensorFlow 中加载模型时采用了正确的代码逻辑,如加载模型和运行推理的顺序。
      • 确保输入数据的维度、类型和范围与模型要求的一致。
    3. 比较推理结果的差异:

      • 使用相同的输入数据在 TensorFlow 和 TensorRT 中运行推理,并比较输出结果的差异。可以通过打印输出结果或计算差异度量值来进行比较。
    4. 检查模型转换过程中的参数设置:

      • 确保模型转换过程中的参数设置和配置文件的正确性。例如,TensorRT 中的精度模式(fp16或int8)是否与 TensorFlow 中的模型一致。
    5. 调试和日志记录:

      • 在转换和推理过程中添加适当的调试和日志记录语句,以便更详细地了解问题所在。可以输出中间结果、打印变量的值等。

    修改后的代码:

    • 请提供 train.py 程序的代码,以便更好地理解模型训练过程。
    • 请提供 GraphDef.py 和模型转换为 .pb 文件的代码,以便更好地理解模型转换过程。
    • 请提供将 .pb 文件转换为 .onnx 文件的代码,以便更好地理解模型转换过程。
    • 请提供将 .onnx 文件转换为 trt 文件的代码,以便更好地理解模型转换过程。
    • 请提供 TensorRT 推理部分的完整代码,以便更好地理解问题所在。
    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 4月7日
  • 创建了问题 4月4日

悬赏问题

  • ¥15 非科班怎么跑代码?如何导数据和调参
  • ¥15 福州市的全人群死因监测点死亡原因报表
  • ¥15 打开powerpont询问是否安装officeplus不小心点了不安装以后再也不提示是否安装了
  • ¥15 Altair EDEM中生成一个颗粒,并且各个方向没有初始速度
  • ¥15 系统2008r2 装机配置推荐一下
  • ¥500 服务器搭建cisco AnyConnect vpn
  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊
  • ¥15 快速扫描算法求解Eikonal方程咨询
  • ¥20 我的是道格手机,重置后屏幕右上角出现红色字的未写入tee key 和未写入google key请问怎么去掉啊