TensorFlow Serving (TF Serving) 是一種工具,可使用 RPC 或 REST API 在大型生產環境中線上執行 TensorFlow 模型。TF Serving >=2.11 原生支援 TensorFlow 決策樹森林 (TF-DF)。
TF-DF 模型與 TF Serving 直接相容。Yggdrasil 模型可以先轉換後,再與 TF Serving 一起使用。
限制
TensorFlow 增加了大量的運算 overhead。對於小型、延遲敏感模型(例如,模型推論時間約 1 微秒),此 overhead 可能比模型本身所需的時間大一個數量級。在這種情況下,建議使用 Yggdrasil 決策樹森林執行 TF-DF 模型。
使用範例
以下範例示範如何在 TF Serving 中執行 TF-DF 模型
首先,安裝 TF Serving。在本範例中,我們將使用 TF-Serving + TF-DF 的預先編譯版本。
# Download TF Serving
wget https://github.com/tensorflow/decision-forests/releases/download/serving-1.0.1/tensorflow_model_server_linux.zip
unzip tensorflow_model_server_linux.zip
# Check that TF Serving works.
./tensorflow_model_server --version
在本範例中,我們使用已訓練的 TF-DF 模型。
# Get a TF-DF model
git clone https://github.com/tensorflow/decision-forests.git
MODEL_PATH=$(pwd)/decision-forests/tensorflow_decision_forests/test_data/model/saved_model_adult_rf
echo "The TF-DF model is available at: ${MODEL_PATH}"
注意: TF-Serving 需要模型的完整路徑。這就是我們使用 $(pwd)
的原因。
TF-Serving 支援模型版本控制。模型應包含在一個目錄中,該目錄的名稱是模型的版本。模型版本是一個整數,例如「1」。以下是 TF-Serving 的典型目錄。
/path/to/model
1
:模型版本 15
:模型版本 56
:模型版本 6
對於此範例,我們只需要將模型放在名為「1」的目錄中。
mkdir -p /tmp/tf_serving_model
cp -R "${MODEL_PATH}" /tmp/tf_serving_model/1
現在,我們可以在模型上啟動 TF-Serving。
./tensorflow_model_server \
--rest_api_port=8502 \
--model_name=my_model \
--model_base_path=/tmp/tf_serving_model
最後,您可以使用 Rest API 將請求傳送至 TF Serving。提供兩種格式:predict+instances API 和 predict+inputs API。以下是它們各自的範例
# Predictions with the predict+instances API.
curl https://127.0.0.1:8502/v1/models/my_model:predict -X POST \
-d '{"instances": [{"age":39,"workclass":"State-gov","fnlwgt":77516,"education":"Bachelors","education_num":13,"marital_status":"Never-married","occupation":"Adm-clerical","relationship":"Not-in-family","race":"White","sex":"Male","capital_gain":2174,"capital_loss":0,"hours_per_week":40,"native_country":"United-States"}]}'
# Predictions with the predict+inputs API
curl https://127.0.0.1:8502/v1/models/my_model:predict -X POST \
-d '{"inputs": {"age":[39],"workclass":["State-gov"],"fnlwgt":[77516],"education":["Bachelors"],"education_num":[13],"marital_status":["Never-married"],"occupation":["Adm-clerical"],"relationship":["Not-in-family"],"race":["White"],"sex":["Male"],"capital_gain":[2174],"capital_loss":[0],"hours_per_week":[40],"native_country":["United-States"]} }'