Tensorflow 1.x 迁移到2.x 遇到的问题记录

共计 3806 个字符,预计需要花费 10 分钟才能阅读完成。

背景介绍

最近从tensorflow 1.x迁移到tensorflow 2.x,在迁移过程中遇到了很多坑,最终也顺利迁移。很多迁移资料网上都可以查到,但有些特性是2.x中独有的,网上包括官方给的教程资料也解决不了遇到的问题,所以将此次过程中有价值的信息分享给大家。

主要介绍

  • 1.x到2.x迁移的常规流程
  • 遇到的问题以及解决方法
    • tf.contrib.predictor.from_saved_model(model_path)在2.x中无法使用
    • @tf.function在训练、预测、导出模型的过程中应该怎么使用

1.x到2.x迁移的常规流程

tensorflow官方教程上有写这个步骤,我这里简单说一下。
1、tensorflow中保留了v1的核心模块,在旧代码中加入以下代码,即可使用1.x的模式,继续使用tensorflow

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

2、将其中涉及到的核心模块的api改成1.x版本
例如1.x中的tf.Session改写为tf.compat.v1.Session,旧代码中无法应用的模块首先考虑将tf.xxx改成tf.compat.v1.xxx看是否能成功引用
3、1.x中tf.contrib模块已经被弃用了,改用了扩展包,其中扩展包可查看 TF Addons and TF-Slim,这里面的扩展包需要自己去网上查,例如1.x中tensorflow.contrib.crf变成了tensorflow_addons.text.crf,还有许多方法和模块在2.x中完全弃用了的,比如后面要讲的tf.contrib.predictor.from_saved_model
4、后续按照官方流程说的,还需要将forward passes改成eager模式,也是2.x的独特之处,但是我觉得如果只是为了让老代码能跑的起来,以上三步差不多就结束了,代码还是能按照1.x的模式跑起来。如果非要用eager模式,就不如直接用2.x的方式重写一遍来得简单。

SaveModel

在讲遇到的问题前,首先讲一下SaveModel的模式,tensorflow提供了多种方式保存、加载模型,比如训练阶段的ckpt的方式,模型只保存训练好的参数,模型结构还是需要在代码中定义,但是在生产环境或者用于模型分享,更推荐用SaveModel方式保存pb模型,模型中既保存了模型结构也保存了模型的参数,这样分享给别人,直接加载即可使用。

问题一 tf.contrib.predictor.from_saved_model(model_path)无法使用

使用SaveModel方式保存的模型,在1.x中,可以直接用from_saved_model执行模型,但是2.x中根本找不到这个方法,本来以为这个方法移到了其他扩展包里面,在网上找了很多地方都没有找到有这个方法的替代。
看了下其他网友的解决方案,都没有解决我的问题。我的老代码如下:

class Model(object):
    def __init__(self, model_index, model_path):
        self.model_index = model_index
        self.predict_func = tf.contrib.predictor.from_saved_model(model_path)

    def Run(self, feature):
        prediction = self.predict_func({
            "label_ids": [feature.label_ids][0],
            "input_ids": [feature.input_ids],
            "input_mask": [feature.input_mask],
            "segment_ids": [feature.segment_ids],
        })

        return prediction

在1.x中,加载的代码直接可以进行预测。以下是2.x可以加载模型的代码:

class Model(object):
    def __init__(self, model_index, model_path):
        self.model_index = model_index
        self.predict_func = tf.saved_model.load(model_path)

    def Run(self, feature):
        input_dict = {
            "label_ids": tf.convert_to_tensor([feature.label_ids][0]),
            "input_ids": tf.convert_to_tensor([feature.input_ids]),
            "input_mask": tf.convert_to_tensor([feature.input_mask]),
            "segment_ids": tf.convert_to_tensor([feature.segment_ids]),
        }
        prediction = self.predict_func.signatures['serving_default'](**input_dict)

        return prediction

很多网上找到的代码直接执行self.predict_func(input_dict)是会报错的,pd模型中,会有多个签名,每个签名代表着不同的方法,如果不指定签名,是无法进行调用的。如果在导出时未进行显式地指定signature,则其密钥默认为serving_default

@tf.function在训练、预测、导出模型的过程中应该怎么使用

tf.function这个在2.x中是个非常重要的装饰器函数,可以把Python风格的代码转为效率更好的Tensorflow计算图,这里有篇文章介绍得非常好,解剖tf.function的使用,我这儿着重介绍实际使用过程中应该怎么使用。

tf.funciton既然可以提高计算效率,那么在训练过程中,应该加在call(self, input)函数上面,亲测比不加的时候,训练效率会高很多。
但是如果在预测过程中,也加上的话,会发现多预测几次,控制台会提示一下信息

WARNING:tensorflow:5 out of the last 8 calls to <function NerModel.call at 0x1300295e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.

在在预测过程,输入如果是可变长度,那么会提示这个,看提示信息应该知道,Tracing is expensivetf.function函数的入参尽量符合一下规则:
1、入参尽量是Tensor类型
2、入参的shape在每个step保持一致
3、使用@tf.function(experimental_relax_shapes = True)选项,该选项可放宽参数形状,从而避免不必要的跟踪
那这边推荐在预测过程中,注释掉tf.function
在训练过程中开启

那在导出过程中,如果直接使用tf.saved_model.save(model, configs.model_path)是无法导出模型的,导出的模型为空的模型文件。
在导出模型的过程中,需要指定函数的输入,可以在@tf.function(input_signature=[tf.TensorSpec(shape=[1, None], dtype=tf.int32, name='inputs'])中指定,也可以在导出模型的时候指定。

tf.saved_model.save(model, configs.model_path,
        signatures=model.call.get_concrete_function(
        tf.TensorSpec(shape=[1, None], dtype=tf.int32)))

这里需要说明的是,通常情况下,训练过程的输入是一个batch的输入,因此输入的维度一般是[batchSize, max_length],但是在导出的时候,就得注意输入应该是[1, max_length],不然在加载模型之后,预测过程也需要匹配[batchSize, max_length]才能正确地执行预测过程。

正文完
 
root
版权声明:本站原创文章,由 root 2022-09-09发表,共计3806字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。