エッジAI

TensorFlow Lite (Micro)

組み込み向けの軽量推論ライブラリ。

概要

TensorFlow Lite(TFLite)は、Googleが開発したモバイルおよびエッジデバイス向けの軽量な機械学習推論フレームワークです。クラウドや大規模サーバー向けのTensorFlowから派生し、スマートフォン・IoTデバイス・マイクロコントローラ上での推論実行に特化して設計されています。

TensorFlow Liteには主に二つのバリアントがあります。

バリアント対象動作環境最小RAM
TensorFlow Liteスマートフォン・Linux SBCAndroid / iOS / Linux数十MB
TensorFlow Lite Micro (TFLM)マイコンベアメタル / RTOS16KB〜

TFLite Microは動的メモリ確保(malloc/free)を使用せず、C++11のみで実装されており、OSなしのベアメタル環境でも動作します。標準ライブラリへの依存も最小限に抑えられているため、リソース制約の厳しいARM Cortex-Mシリーズのマイコンに最適です。

歴史・背景

TensorFlow Liteの開発はGoogleが2017年にTensorFlow 1.0系の「TensorFlow Mobile」を発展させる形で開始され、2017年末に公式発表されました。

主な発展の経緯:

  • 2017年:TensorFlow Lite v1.0発表(Android/iOS対応)
  • 2018年:デリゲートAPI導入(GPU・DSP・NPUへのオフロード機構)
  • 2019年:TensorFlow Lite for Microcontrollers(TFLite Micro)発表
    • Pete Warden(Google Research)が主導
    • ARM Cortex-Mでの動作を初めて実現
  • 2020年:CMSIS-NNを通じたARM Cortex-M最適化統合
  • 2021年:TFLite Microがリポジトリを独立(tflite-micro)
  • 2022年:Ethos NPUデリゲート対応
  • 2023年:LiteRT(TFLiteの新ブランド名)への移行開始を発表

技術仕様

TFLiteモデルフォーマット(.tflite)

TFLiteモデルはFlatBuffers形式でシリアライズされたバイナリファイルです。JSONと異なりスキーマコンパイルにより高速なパース(読み込み)が可能で、ゼロコピーアクセスに対応します。

.tfliteファイルの内部構造(FlatBuffers)
├── subgraphs[]
│   ├── tensors[](テンソル定義)
│   │   ├── name
│   │   ├── shape
│   │   ├── type(FLOAT32/INT8/etc)
│   │   └── quantization(スケール・ゼロ点)
│   ├── operators[](演算子リスト)
│   │   ├── opcode_index
│   │   ├── inputs[]
│   │   └── outputs[]
│   ├── inputs[](入力テンソルインデックス)
│   └── outputs[](出力テンソルインデックス)
├── buffers[](重みデータ)
└── operator_codes[](使用する演算子種別)

量子化パラメータ

INT8量子化モデルでは各テンソルにスケールとゼロ点が付与されます。

実数値 = スケール × (量子化値 - ゼロ点)
量子化値 = round(実数値 / スケール) + ゼロ点

サポートされる主要演算子

カテゴリ          演算子
──────────────────────────────────────────
たたみ込み系      Conv2D, DepthwiseConv2D,
                  TransposeConv
プーリング系      MaxPool2D, AveragePool2D,
                  MeanPool
正規化系          BatchNormalization, LayerNorm
活性化関数        ReLU, ReLU6, Sigmoid, Tanh,
                  LeakyReLU, PReLU
全結合            FullyConnected, MatMul
変形系            Reshape, Squeeze, ExpandDims,
                  Transpose, Gather, Slice
演算系            Add, Mul, Sub, Div, Concat,
                  Split, Pack, Unpack
リカレント        LSTM, GRU, RNN
その他            Softmax, Logistic, Dequantize

デリゲートAPI

デリゲートはTFLiteの最も強力な機能の一つで、特定の演算をハードウェアアクセラレータにオフロードします。

┌──────────────────────────────────────────┐
│  TFLite Interpreter                       │
│  ┌────────────┐    ┌────────────────────┐│
│  │ CPUカーネル │    │    デリゲート      ││
│  │(非対応演算)│    │  ┌─────────────┐ ││
│  └────────────┘    │  │ GPU Delegate │ ││
│                    │  │ NNAPI        │ ││
│                    │  │ Hexagon      │ ││
│                    │  │ Core ML      │ ││
│                    │  │ Ethos-U NPU  │ ││
│                    │  └─────────────┘ ││
│                    └────────────────────┘│
└──────────────────────────────────────────┘

動作原理

モデル変換パイプライン

import tensorflow as tf

# 学習済みKerasモデルの変換
model = tf.keras.models.load_model('my_model.h5')

# TFLiteConverter作成
converter = tf.lite.TFLiteConverter.from_keras_model(model)

# 最適化オプション設定
converter.optimizations = [tf.lite.Optimize.DEFAULT]

# INT8量子化(代表データセットが必要)
def representative_dataset():
    for data in calibration_dataset:
        yield [data.astype('float32')]

converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [
    tf.lite.OpsSet.TFLITE_BUILTINS_INT8
]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8

# 変換実行
tflite_model = converter.convert()

# 保存
with open('model_int8.tflite', 'wb') as f:
    f.write(tflite_model)
print(f"モデルサイズ: {len(tflite_model) / 1024:.1f}KB")

TFLite Microでのマイコン実装(完全例)

// main.cc(Cortex-M向けTFLite Micro実装例)
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/system_setup.h"
#include "tensorflow/lite/schema/schema_generated.h"

// Cmakeで別途生成されたモデルデータ
#include "model_data.h"

// テンソルアリーナ(スタック or グローバル)
namespace {
constexpr int kTensorArenaSize = 64 * 1024;  // 64KB
alignas(16) uint8_t tensor_arena[kTensorArenaSize];

tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* input = nullptr;
TfLiteTensor* output = nullptr;
}  // namespace

void setup_tflite() {
    tflite::InitializeTarget();

    // オペレータ登録(必要なものだけ選択)
    static tflite::MicroMutableOpResolver<6> resolver;
    resolver.AddConv2D();
    resolver.AddDepthwiseConv2D();
    resolver.AddFullyConnected();
    resolver.AddSoftmax();
    resolver.AddReshape();
    resolver.AddMaxPool2D();

    // モデルをFlatBufferから取得
    const tflite::Model* model = 
        tflite::GetModel(g_model_data);
    
    if (model->version() != TFLITE_SCHEMA_VERSION) {
        // スキーマバージョン不一致エラー処理
        return;
    }

    // インタープリタ初期化
    static tflite::MicroInterpreter static_interpreter(
        model, resolver, tensor_arena, kTensorArenaSize);
    interpreter = &static_interpreter;

    // テンソルメモリ確保
    TfLiteStatus allocate_status = 
        interpreter->AllocateTensors();
    if (allocate_status != kTfLiteOk) {
        // メモリ不足エラー処理
        return;
    }

    // 入出力テンソル参照
    input = interpreter->input(0);
    output = interpreter->output(0);
}

void run_inference(const int8_t* sensor_data, int data_len) {
    // 入力テンソルにデータをコピー
    memcpy(input->data.int8, sensor_data, 
           data_len * sizeof(int8_t));

    // 推論実行
    TfLiteStatus invoke_status = interpreter->Invoke();
    if (invoke_status != kTfLiteOk) {
        return;
    }

    // 結果読み取り(INT8 → 実数値への逆量子化)
    float scale = output->params.scale;
    int zero_point = output->params.zero_point;
    
    for (int i = 0; i < output->dims->data[1]; i++) {
        float value = (output->data.int8[i] - zero_point) * scale;
        printf("Class %d: %.4f\n", i, value);
    }
}

CMSIS-NNによる最適化

ARM CMSIS-NNはARM Cortex-M用のニューラルネットワーク演算最適化ライブラリです。TFLite MicroはCMSIS-NNを自動的に利用します。

// CMSIS-NNが内部で使うSIMD命令の例(Cortex-M4以降)
// __SMLAD: 符号付き乗算加算(2x並列)
result = __SMLAD(packed_input, packed_weight, result);

Cortex-M4/M7では__SMLAD命令でINT8積和演算を2倍並列化、Cortex-M55のM-Profileベクター拡張(MVE)では最大16倍の並列化が可能です。

用途・ユースケース

Android / iOSアプリ(TFLite)

// Android (Kotlin) でのTFLite使用例
val model = MyModel.newInstance(context)
val inputFeature = TensorBuffer.createFixedSize(
    intArrayOf(1, 224, 224, 3), DataType.FLOAT32
)
inputFeature.loadBuffer(bitmapToByteBuffer(bitmap))
val outputs = model.process(inputFeature)
val outputFeature = outputs.outputFeature0AsTensorBuffer
model.close()

Linux組み込みボード(TFLite)

# Raspberry PiなどLinux環境での利用
import tflite_runtime.interpreter as tflite
import numpy as np

interpreter = tflite.Interpreter(
    model_path='model.tflite',
    num_threads=4  # マルチスレッド推論
)
interpreter.allocate_tensors()

# 推論実行
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_data = np.expand_dims(preprocessed_image, axis=0)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
result = interpreter.get_tensor(output_details[0]['index'])

マイコン(TFLite Micro)対応デバイス

  • Arduino Nano 33 BLE Sense(音声・ジェスチャー認識)
  • STM32 Nucleo(産業用センサー解析)
  • Nordic nRF52840(Bluetooth + AI)
  • ESP32-S3(Wi-Fi + AI、組み込みカメラ)
  • Raspberry Pi Pico(低コストAIエッジ)

実装・開発のポイント

モデルサイズとRAM使用量の最適化

# モデル情報を詳細に確認するスクリプト
import tensorflow as tf
import os

def analyze_tflite_model(model_path):
    file_size = os.path.getsize(model_path)
    print(f"モデルファイルサイズ: {file_size / 1024:.2f}KB")
    
    interpreter = tf.lite.Interpreter(model_path)
    interpreter.allocate_tensors()
    
    # 各レイヤーのメモリ使用量
    total_params = 0
    for detail in interpreter.get_tensor_details():
        shape = detail['shape']
        params = 1
        for s in shape:
            params *= s
        total_params += params
        
    print(f"総パラメータ数: {total_params:,}")
    print(f"推定モデルRAM: ~{total_params // 1024}KB (INT8)")

デリゲートの選択指針

デリゲート対応OS対応ハードウェア効果
NNAPIAndroid 8.1+NPU/DSP2〜10x
GPU (OpenCL)Android/LinuxGPU2〜5x
GPU (Metal)iOSApple GPU2〜5x
Core MLiOSNeural Engine5〜20x
HexagonAndroidQualcomm DSP3〜8x
Ethos-UベアメタルArm NPU5〜20x

他技術との比較

比較軸TFLite / TFLMONNX RuntimeTensorRTPyTorch Mobile
開発元GoogleMicrosoftNVIDIAMeta
MCU対応TFLM ○△(実験的)××
Android最適化最高良好×良好
GPU対応デリゲート最高CUDA
モデル形式.tflite独自.onnx共通.engine.ptl
変換ツールTFLite Converter多数TensorRTtorch.jit
エコシステム最大広いNVIDIA限定PyTorchユーザー向け

TFLiteはTinyMLの標準的な実装基盤であり、ONNXと組み合わせることで多様なフレームワークのモデルを変換・展開できます。量子化機能との統合も強力で、NPUARM Cortex-M向け最適化も充実しています。

関連用語

参考リンク