> ## Documentation Index
> Fetch the complete documentation index at: https://dragonwingdocs-staging.qualcomm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 将 TensorFlow 模型导出为 LiteRT

> 将 TensorFlow 或 Keras 模型转换为 LiteRT 格式并进行量化,以便部署到 Qualcomm Dragonwing IoT 平台。

您可以将 TensorFlow 模型转换为 LiteRT 格式,并针对设备端推理进行优化。有关 LiteRT 模型转换的更多信息,请参阅 [Model conversion overview](https://ai.google.dev/edge/litert/models/convert)。

LiteRT 模型转换支持以下输出精度:

* 32 位浮点精度
* 16 位浮点精度
* uint8/int8 精度(量化模型)

下表列出了 TensorFlow 框架中可用的转换方法:

**TensorFlow 模型转换方法**

| 转换方法         | 描述                        |
| ------------ | ------------------------- |
| Python API   | 将模型转换、优化并量化为 LiteRT 格式    |
| 命令行界面(CLI)工具 | 将模型转换为 LiteRT 格式;仅适用于基本转换 |

Python API 提供了更大的灵活性,可根据您的需求对模型进行转换、优化和量化。

## 使用 Python API 转换模型

下表列出了 TensorFlow 提供的用于将 TensorFlow SavedModel 或 Keras 模型转换为 LiteRT 的 Python API:

**用于转换模型的 TensorFlow Python API**

| API                                              | 描述                       |
| ------------------------------------------------ | ------------------------ |
| `tf.lite.TFLiteConverter.from_saved_model()`(推荐) | 转换 TensorFlow SavedModel |
| `tf.lite.TFLiteConverter.from_keras_model()`     | 转换 Keras 模型              |

### 使用 Python API 转换 TensorFlow SavedModel

以下示例将 SavedModel 格式的 TensorFlow 模型转换为 LiteRT:

```python theme={null}
import tensorflow as tf

# Convert the model
saved_model_dir = "/path/to/tf/model/in/saved_model/format"
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()

# Save the model
with open("model.tflite", "wb") as f:
    f.write(tflite_model)
```

<Note>
  转换后的 LiteRT 模型未经量化,其数据为 32 位浮点精度。
</Note>

### 使用 Python API 转换 Keras 模型

以下示例将 Keras 模型转换为 LiteRT:

```python theme={null}
import tensorflow as tf

# Create a model using high-level tf.keras.* APIs
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1]),
    tf.keras.layers.Dense(units=16, activation='relu'),
    tf.keras.layers.Dense(units=1)
])

# Compile and train the model
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x=[-1, 0, 1], y=[-3, -1, 1], epochs=5)

# Convert the model to LiteRT
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

# Save the model
with open('model.tflite', 'wb') as f:
    f.write(tflite_model)
```

<Note>
  转换后的 LiteRT 模型未经量化,其数据为 32 位浮点精度。
</Note>

## 量化模型

使用 Python API 将模型转换为 LiteRT 格式后,您可以对其进行量化。量化通过将高精度值(例如 32 位浮点数)转换为较低精度格式(例如 8 位整数),来减小模型的大小和计算需求。

神经网络模型的量化包括以下步骤:

1. **量化权重和偏置**——它们已经是训练模型的一部分,无需额外的输入数据即可量化。这是一个静态步骤。

2. **量化激活层**——激活层输出的范围取决于前向传播期间的输入数据。需要一组样本输入(称为校准数据集或代表性数据集)来确定最小和最大范围。

要将 TensorFlow 浮点模型量化为量化的 LiteRT 模型,LiteRT 提供了训练后量化技术。有关更多信息,请参阅 [Post-training quantization](https://ai.google.dev/edge/litert/models/post_training_quantization)。

LiteRT 支持以下类型的训练后量化:

* [动态范围量化](#quantize-models-using-dynamic-range-quantization)
* [全整数量化](#quantize-models-using-full-integer-quantization)

<h3 id="quantize-models-using-dynamic-range-quantization">
  使用动态范围量化对模型进行量化
</h3>

在动态范围量化中,权重和偏置会从浮点静态量化为 8 位整数精度。激活层的范围保持为 32 位浮点精度。

为了减少推理期间的延迟,动态范围算子会:

* 根据激活的范围将其量化为 8 位整数精度。
* 使用 8 位权重和激活执行计算。

<Note>
  此步骤仅量化权重,不需要额外的校准数据。
</Note>

以下脚本将 TensorFlow 模型转换为 LiteRT 并应用动态范围量化:

```python theme={null}
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model(exp_model_path)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
converter.optimizations = [tf.lite.Optimize.DEFAULT]

tflite_model = converter.convert()
save_name = 'quantized_model.tflite'

print('Saving Dynamic Quantized LiteRT model')

with open(save_name, 'wb') as f:
    f.write(tflite_model)
```

<h3 id="full-integer-quantization">
  使用全整数量化对模型进行量化
</h3>

在全整数量化中,使用代表性数据集对模型中的激活层进行量化。这会生成更适合定点整数硬件(例如 Qualcomm 开发套件上的 Hexagon Tensor Processor)的模型。

以下脚本将 TensorFlow 模型转换并量化为全整数量化的 LiteRT 模型:

```python theme={null}
import tensorflow as tf

def representative_dataset():
    for data in dataset:
        yield {"image": data.image, "bias": data.bias}

saved_model_dir = "/path/to/saved/model"

# Load the model
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.optimizations = [tf.lite.Optimize.DEFAULT]

# Set the representative dataset for quantization
converter.representative_dataset = representative_dataset

# For full integer quantization, set target_spec to TFLITE_BUILTINS_INT8
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8   # or tf.uint8
converter.inference_output_type = tf.int8  # or tf.uint8

# Convert the model
tflite_quant_model = converter.convert()
save_name = 'quantized_model_int8.tflite'

print('Saving Quantized LiteRT model')

with open(save_name, 'wb') as f:
    f.write(tflite_quant_model)
```

<Note>
  转换器中的 `supported_ops` 会将 `target_spec` 设置为 `tf.lite.OpsSet.TFLITE_BUILTINS_INT8`。
</Note>

## 使用 `tflite_convert` 命令转换模型

对于 TensorFlow v2.x 及更高版本,您可以使用 TensorFlow pip 包中包含的 `tflite_convert` CLI 工具进行离线转换。

<Note>
  `tflite_convert` 命令仅适用于基本转换。对于训练后整数量化,请使用 Python API。
</Note>

`tflite_convert` 命令需要 `--output_file` 标志,以及 `--saved_model_dir` 或 `--keras_model_file` 之一。运行 `tflite_convert --help` 可查看完整的选项列表。

### 转换 SavedModel

要转换 SavedModel 格式的 TensorFlow 模型,请运行:

```shell theme={null}
tflite_convert \
  --saved_model_dir=/tmp/mobilenet_saved_model \
  --output_file=/tmp/mobilenet.tflite
```

### 转换 Keras H5 模型

要转换 Keras H5 模型,请运行:

```shell theme={null}
tflite_convert \
  --keras_model_file=/tmp/mobilenet_keras_model.h5 \
  --output_file=/tmp/mobilenet.tflite
```
