作者:TensorFlow 中國團隊,Google 開發技術推廣工程師 Renmin Gu.
最新的中文技術分享視頻來了!本期來自 Google 的工程師 Renmin 為大家帶來 TensorFlow Lite 的深度解析視頻,主要講述 TensorFlow Lite 模型文件格式,並可視化以幫助大家記憶理解,也包含 TensorFlow Lite 的具體加載運行過程,並給出關鍵的數據結構描述,同樣以可視化的形式呈現給大家:
看完視頻,我們不妨一起總結回顧一下:
首先,我們需要在臺式機上設計、訓練出目標模型,並將其轉化成 TensorFlow Lite 的格式。接著,此格式文件在 TensorFlow Lite 中會被內置了 Neon 指令集的解析器加載到內存,並執行相應的計算。由於 TensorFlow Lite 對硬體加速接口良好的支持,開發者可以設計出性能更優的 App 供用戶使用。
模型文件格式Model 結構體:模型的主結構table Model {
version: uint;
operator_codes: [OperatorCode];
subgraphs: [SubGraph];
description: string;
buffers: [Buffer]
}
在上面的 Model 結構體定義中,operator_codes 定義了整個模型的所有算子,subgraphs 定義了所有的子圖。子圖當中,第一個元素是主圖。buffers 屬性則是數據存儲區域,主要存儲的是模型的權重信息。
SubGraph 結構體:Model 中最重要的部分table SubGraph {
tensors: [Tensor];
inputs: [int];
outputs: [int];
operators: [Operator];
name: string;
}
類似的,tensors 屬性定義了子圖的各個 Tensor,而 inputs 和 outputs 用索引的維護著子圖中 Tensor 與輸入輸出之間的對應關係。剩下的operators 定義了子圖當中的算子。
Tensor 結構體:包含維度、數據類型、Buffer 位置等信息table Tensor {
shape: [int];
type: TensorType;
buffer: uint;
name: string;
}
buffer 以索引量的形式,給出了這個 Tensor 需要用到子圖的哪一個 buffer。
Operator 結構體:SubGraph 中最重要的結構體Operator 結構體定義了子圖的結構:
table Operator {
opcode_index: uint;
inputs: [int];
outputs: [int];
...
}
opcode_index 用索引方式指明該 Operator 對應了哪個算子。 inputs 和 outputs 則是 Tensor 的索引值,指明該 Operator 的輸入輸出信息。
解析器概況那麼 TensorFlow Lite 的解析器又是如何工作的呢?
一開始,終端設備會通過 mmap 以內存映射的形式將模型文件載入客戶端內存中,其中包含了所有的 Tensor,Operator 和 Buffer 等信息。出於數據使用的需要,TensorFlow Lite 會同時創建 Buffer 的只讀區域和分配可寫 Buffer 區域。
由於解析器中包含了集體執行計算的代碼,這一部分被稱為 Kernel。模型中的各個 Tensor 會被加載為 TfLiteTensor 的格式併集中存放在 TfLiteContext 中。
每個 Tensor 的指針都指向了內存中的只讀 Buffer 區域或是一開始新分配的可寫入 Buffer 區域。
模型中的 Operator 被重新加載為 TfLiteNode,它包含輸入輸出的 Tensor 索引值。這些 Node 對應的操作符存儲於 TfLiteRegistration 中,它包含了指向 Kernel 的函數指針。OpResolver 負責維護函數指針的對應關係。
TensorFlow Lite 加載模型的過程中會確定執行 Node 的順序,然後依次執行。
大家如果想要更好掌握 TensorFlow Lite 的技術細節,一定要閱讀以下文件:
lite/context.h
lite/model.h
lite/interpreter.h
lite/kernels/register.h
希望我們的分享能讓廣大開發者們對 TensorFlow Lite 的代碼有一個初步認識,期待看到大家精彩的作品!
另外,TensorFlow Lite 的代碼位置:
https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/lite
模型的模式文件位於:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/schema/schema.fbs
更多在 Google 中國 Bilibili 頻道查看本視頻:
https://www.bilibili.com/video/av24219725/
在谷歌開發者中文頻道查看本視頻:
https://www.youtube.com/watch?v=b45xt-tdI7M
在谷歌開發者視頻 Youku 頻道查看本視頻:
http://v.youku.com/v_show/id_XMzYzODc1NDYyOA==.html
還想看到更多中文 TensorFlow 教學視頻嗎,歡迎留下你的評論和想法!