大家好,我是老胡,
許久沒有更新100天搞定機器學習系列了,最近在看一個開源框架,其中有用到 gRPC ,它可以用于機器學習模型的部署,也可用于深度學習框架的開發,本文就當是《100天搞定機器學習》的番外篇吧,

gRPC(Remote Procedure Call)
gRPC 由 Google 開發,是一款語言中立、平臺中立、開源的 RPC 框架,
RPC(Remote Procedure Call)即:遠程程序呼叫,它是一種通過網路從遠程計算機程式上請求服務,而不需要了解底層網路技術的協議,使用的時候,客戶端呼叫server端提供的介面就像是呼叫本地的函式一樣,
比如:有兩臺服務器A,B,一個應用部署在A服務器上,想要呼叫B服務器上應用提供的函式/方法,由于不在一個記憶體空間,不能直接呼叫,需要通過網路來表達呼叫的語意和傳達呼叫的資料,

RPC更像是一種思想或機制,其實作方式有很多,除了gRPC ,還有阿里巴巴的 Dubbo、Facebook 的 Thrift、Twitter 的 Finagle 等,
gRPC 基于以下理念:定義一個服務,指定其能夠被遠程呼叫的方法(包含引數和回傳型別),在服務端實作這個介面,并運行一個 gRPC 服務器來處理客戶端呼叫,在客戶端擁有一個存根能夠像服務端一樣的方法,你可以很容易地用 c++ 創建一個 gRPC 服務端,用 Go、Python、Ruby 來創建客戶端,

上圖中的 Protocbuf 是gRPC的資料序列化工具,使用 Protobuf 將資料序列化成二進制的資料流,即可讓用不同語言(proto3支持C++, Java, Python, Go, Ruby, Objective-C, C#)撰寫并在不同平臺上運行的應用程式交換資料,ps:Protocbuf 也是 Google 開源的,
Protocol Buffer 官方提供了編譯工具來對 proto 檔案進行編譯并生成語言相關的代碼檔案,可以極大地減少編碼的作業量,對于序列化協議來說,使用方只需要關注業務物件本身,即 idl 定義,序列化和反序列化的代碼只需要通過工具生成即可,

gRPC 實體詳解——機器學習模型部署

開始實體之前,需要安裝 gRPC 及相關工具
pip install -U grpcio
pip install -U grpcio-tools
pip install -U protobuf
gRPC的使用通常包括如下幾個步驟:
- 通過protobuf來定義介面和資料型別
- 撰寫gRPC server端代碼
- 撰寫gRPC client端代碼
下面我們就以Iris資料集為例,用 gRPC server端部署一個隨機森林分類器,client 端發起請求預測鳶尾花型別,

0、訓練一個隨機森林分類模型,把訓練好的模型保存為pkl檔案,
# train_model.py
from sklearn import datasets
from sklearn.pipeline import Pipeline
import joblib
from sklearn.ensemble import RandomForestClassifier
def main():
clf = RandomForestClassifier()
p = Pipeline([('clf', clf)])
p.fit(X, y)
filename_p = 'IrisClassifier.pkl'
joblib.dump(p, filename_p)
print('Model saved!')
if __name__ == "__main__":
iris = datasets.load_iris()
X, y = iris.data, iris.target
main()
1、通過protobuf定義介面和資料型別
新建一個iris_demo.proto檔案
syntax = "proto3";
package iris;
message IrisPredictRequest {// 定義引數1
float sepal_length = 1;//引數欄位1
float sepal_width = 2;//引數欄位2
float petal_length = 3;//引數欄位3
float petal_width = 4;//引數欄位4
}
message IrisPredictResponse {// 定義引數1
int32 species = 1;
}
service IrisPredictor{// 定義服務
rpc predict_iris_species(IrisPredictRequest) returns (IrisPredictResponse){}
}
proto檔案格式一般三部分組成,
- 頭部的syntax 注明版本號為 “proto3”,必須寫,沒理由,
- 中間的 message 定義了predict_iris_species方法的引數IrisPredictRequest和IrisPredictResponse,還有引數欄位的型別,
- 尾部的 service 定義一個服務IrisPredictor,其中包括 1 個predict_iris_species的RPC方法,這里可以定義多個RPC方法,在 message 中定義對應的引數即可,
2、使用gRPC protobuf生成Python的庫函式
python -m grpc_tools.protoc -I=. --python_out=. --grpc_python_out=. ./iris_demo.proto
其中:
-I指定了源檔案的路徑
–python_out, 指定 xxx_pb2.py的輸出路徑,如果使用其它語言請使用對應語言的option
–grpc_python_out 指定xxx_pb2_grpc.py檔案的輸出路徑
–*.proto是要編譯的proto檔案,
運行成功后,會自動生成iris_demo_pb2.py(里面有訊息序列化類)和iris_demo_pb2_grpc.py(包含了服務器 Stub 類和客戶端 Stub 類,以及待實作的服務 RPC 介面),我們無需關心這兩個py檔案的細節,只需要直到在服務端和客戶端怎么呼叫即可,
本例中,我們會用到的方法如下:
xxx_pb2.py
├── xxx_pb2.IrisPredictRequest 用于傳入特征資料
├── xxx_pb2.IrisPredictResponse 用于預測
xxxx_pb2_grpc.py
├── xxx_pb2_grpc.IrisPredictorServicer 服務器 Stub 類
├── xxx_pb2_grpc.IrisPredictorStub 客戶端 Stub 類
3、寫一個服務器
這里的重點是定義 IrisPredictor 類的 predict_iris_species 方法,然后用 iris_demo_pb2_grpc.py 中的 add_IrisPredictorServicer_to_server 方法將 IrisPredictor 添加到 server,serve 函式里定義了 gRPC 的運行方式,使用 4 個 worker 的執行緒池,
# iris_prediction_server.py
import grpc
from concurrent import futures
import time
import joblib
import iris_demo_pb2
import iris_demo_pb2_grpc
import predict_iris
from sklearn.ensemble import RandomForestClassifier
class IrisPredictor(iris_demo_pb2_grpc.IrisPredictorServicer):
@classmethod
def get_trained_model(cls):
cls._model = joblib.load('IrisClassifier.pkl')
return cls._model
def predict_iris_species(self, request, context):
model = self.__class__.get_trained_model()
sepal_length = request.sepal_length
sepal_width = request.sepal_width
petal_length = request.petal_length
petal_width = request.petal_width
result = model.predict(
[[sepal_length, sepal_width, petal_length, petal_width]])
response = iris_demo_pb2.IrisPredictResponse(species=result[0])
return response # not sure
def run():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
iris_demo_pb2_grpc.add_IrisPredictorServicer_to_server(
IrisPredictor(), server)
server.add_insecure_port('[::]:50055')
server.start()
print("grpc server start...")
print("Listening on port 50055")
server.wait_for_termination()
if __name__ == '__main__':
run()
4、寫一個客戶端
客戶端的邏輯更加簡單,連上gRPC服務,然后發起呼叫,
# iris_prediction_client.py
import grpc
import iris_demo_pb2
import iris_demo_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50055')
stub = iris_demo_pb2_grpc.IrisPredictorStub(channel)
request = iris_demo_pb2.IrisPredictRequest(
sepal_length=6.7,
sepal_width=3.0,
petal_length=5.2,
petal_width=2.3)
response = stub.predict_iris_species(request)
print('The prediction is :', response.species)
if __name__ == '__main__':
run()
5、呼叫 RPC
先開啟服務端
$ python iris_prediction_server.py

另起一個terminal執行客戶端代碼,呼叫gRPC服務,結果如下:
$ python iris_prediction_client.py

referance
https://grpc.io/
http://doc.oschina.net/
https://zhuanlan.zhihu.com/p/148139089
https://yu-ishikawa.medium.com/machine-learning-as-a-microservice-in-python-16ba4b9ea4ee
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/278084.html
標籤:python
上一篇:第九章:資料結構四兄弟——串列(下),癡月熊學python
下一篇:python多執行緒學習
