You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

example.md 8.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # 实现一个Add网络示例
  2. ## 概述
  3. 以一个简单的Add网络为例,演示MindSpore Serving如何使用。
  4. ### 导出模型
  5. 使用[add_model.py](https://gitee.com/mindspore/serving/blob/master/mindspore_serving/example/add/export_model/add_model.py),构造一个只有Add算子的网络,并导出MindSpore推理部署模型。
  6. ```python
  7. import os
  8. from shutil import copyfile
  9. import numpy as np
  10. import mindspore.context as context
  11. import mindspore.nn as nn
  12. from mindspore.ops import operations as P
  13. from mindspore import Tensor
  14. from mindspore.train.serialization import export
  15. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  16. class Net(nn.Cell):
  17. def __init__(self):
  18. super(Net, self).__init__()
  19. self.add = P.TensorAdd()
  20. def construct(self, x_, y_):
  21. return self.add(x_, y_)
  22. def export_net():
  23. x = np.ones([2, 2]).astype(np.float32)
  24. y = np.ones([2, 2]).astype(np.float32)
  25. add = Net()
  26. output = add(Tensor(x), Tensor(y))
  27. export(add, Tensor(x), Tensor(y), file_name='tensor_add', file_format='MINDIR')
  28. dst_dir = '../add/1'
  29. try:
  30. os.mkdir(dst_dir)
  31. except OSError:
  32. pass
  33. try:
  34. dst_file = os.path.join(dst_dir, 'tensor_add.mindir')
  35. if os.path.exists('tensor_add.mindir'):
  36. copyfile('tensor_add.mindir', dst_file)
  37. print("copy tensor_add.mindir to " + dst_dir + " success")
  38. elif os.path.exists('tensor_add'):
  39. copyfile('tensor_add', dst_file)
  40. print("copy tensor_add to " + dst_dir + " success")
  41. except:
  42. print("copy tensor_add.mindir to " + dst_dir + " failed")
  43. print(x)
  44. print(y)
  45. print(output.asnumpy())
  46. if __name__ == "__main__":
  47. export_net()
  48. ```
  49. 使用MindSpore定义神经网络需要继承mindspore.nn.Cell。Cell是所有神经网络的基类。神经网络的各层需要预先在__init__方法中定义,然后通过定义construct方法来完成神经网络的前向构造。使用mindspore.train.serialization模块的export即可导出模型文件。
  50. 更为详细完整的示例可以参考[实现一个图片分类应用](https://www.mindspore.cn/tutorial/training/zh-CN/master/quick_start/quick_start.html)。
  51. 执行add_model.py脚本,生成`tensor_add.mindir`文件,该模型的输入为两个shape为[2,2]的二维Tensor,输出结果是两个输入Tensor之和。
  52. ### 部署Serving推理服务
  53. 启动Serving服务,当前目录下需要有模型文件夹,如add,文件夹下放置版本模型文件和配置文件,文件目录结果如下图所示:
  54. <pre><font color="#268BD2"><b>test_dir/</b></font>
  55. ├── <font color="#268BD2"><b>add/</b></font>
  56. │   └── servable_config.py
  57. │  └─<font color="#268BD2"><b>1/</b></font>
  58. │   └── tensor_add.mindir
  59. └── master_with_worker.py
  60. </pre>
  61. 其中,模型文件为上一步网络生成的,即`tensor_add.mindir`文件,放置在文件夹1下,1为版本号,不同的版本放置在不同的文件夹下。
  62. 配置文件为[servable_config.py](https://gitee.com/mindspore/serving/blob/master/mindspore_serving/example/add/add/servable_config.py),其定义了模型的处理函数。
  63. ```python
  64. from mindspore_serving.worker import register
  65. import numpy as np
  66. # define preprocess pipeline, the function arg is multi instances, every instance is tuple of inputs
  67. # this example has one input and one output
  68. def add_trans_datatype(instances):
  69. """preprocess python implement"""
  70. for instance in instances:
  71. x1 = instance[0]
  72. x2 = instance[1]
  73. yield x1.astype(np.float32), x2.astype(np.float32)
  74. # when with_batch_dim set to False, only support 2x2 add
  75. # when with_batch_dim set to True(default), support Nx2 add, while N is view as batch
  76. # float32 inputs/outputs
  77. register.declare_servable(servable_file="tensor_add.mindir", model_format="MindIR", with_batch_dim=False)
  78. # register add_common method in add
  79. @register.register_method(output_names=["y"])
  80. def add_common(x1, x2): # only support float32 inputs
  81. """method add_common data flow definition, only call model servable"""
  82. y = register.call_servable(x1, x2)
  83. return y
  84. # register add_cast method in add
  85. @register.register_method(output_names=["y"])
  86. def add_cast(x1, x2):
  87. """method add_cast data flow definition, only call preprocess and model servable"""
  88. x1, x2 = register.call_preprocess(add_trans_datatype, x1, x2) # cast input to float32
  89. y = register.call_servable(x1, x2)
  90. return y
  91. ```
  92. 该文件定义了add_common和add_cast两个方法。
  93. MindSpore Serving提供两种部署方式,轻量级部署和集群部署,用户可根据需要进行选择部署。
  94. **轻量级部署:**
  95. 服务端调用python接口直接启动推理进程(master和worker共进程),客户端直接连接推理服务后下发推理任务。
  96. 执行[master_with_worker.py](https://gitee.com/mindspore/serving/blob/master/mindspore_serving/example/add/master_with_worker.py),完成轻量级部署服务如下:
  97. ```python
  98. import os
  99. from mindspore_serving import master
  100. from mindspore_serving import worker
  101. def start():
  102. servable_dir = os.path.abspath(".")
  103. worker.start_servable_in_master(servable_dir, "add", device_id=0)
  104. master.start_grpc_server("127.0.0.1", 5500)
  105. if __name__ == "__main__":
  106. start()
  107. ```
  108. 当服务端打印日志`Serving gRPC start success, listening on 0.0.0.0:5500`时,表示Serving服务已加载推理模型完毕。
  109. **集群部署:**
  110. 服务端由master进程和worker进程组成,master用来管理集群内所有的worker节点,并进行推理任务的分发。 部署方式如下:
  111. 部署master:
  112. ```python
  113. import os
  114. from mindspore_serving import master
  115. def start():
  116. servable_dir = os.path.abspath(".")
  117. master.start_grpc_server("127.0.0.1", 5500)
  118. master.start_master_server("127.0.0.1", 6500)
  119. if __name__ == "__main__":
  120. start()
  121. ```
  122. 部署worker:
  123. ```python
  124. import os
  125. from mindspore_serving import master
  126. def start():
  127. servable_dir = os.path.abspath(".")
  128. worker.start_servable(servable_dir, "add", device_id=0,
  129. master_ip="127.0.0.1", master_port=6500,
  130. host_ip="127.0.0.1", host_port=6600)
  131. if __name__ == "__main__":
  132. start()
  133. ```
  134. 轻量级部署和集群部署除了master和woker进程是否隔离,worker使用的接口也不同,轻量级部署使用worker的start_servable_in_master接口,集群部署使用worker的start_servable接口。
  135. ### 执行推理
  136. 使用[client.py](https://gitee.com/mindspore/serving/blob/master/mindspore_serving/example/add/client.py),启动Python客户端。
  137. ```python
  138. import numpy as np
  139. from mindspore_serving.client import Client
  140. def run_add_common():
  141. """invoke servable add method add_common"""
  142. client = Client("localhost", 5500, "add", "add_common")
  143. instances = []
  144. # instance 1
  145. x1 = np.asarray([[1, 1], [1, 1]]).astype(np.float32)
  146. x2 = np.asarray([[1, 1], [1, 1]]).astype(np.float32)
  147. instances.append({"x1": x1, "x2": x2})
  148. # instance 2
  149. x1 = np.asarray([[2, 2], [2, 2]]).astype(np.float32)
  150. x2 = np.asarray([[2, 2], [2, 2]]).astype(np.float32)
  151. instances.append({"x1": x1, "x2": x2})
  152. # instance 3
  153. x1 = np.asarray([[3, 3], [3, 3]]).astype(np.float32)
  154. x2 = np.asarray([[3, 3], [3, 3]]).astype(np.float32)
  155. instances.append({"x1": x1, "x2": x2})
  156. result = client.infer(instances)
  157. print(result)
  158. def run_add_cast():
  159. """invoke servable add method add_cast"""
  160. client = Client("localhost", 5500, "add", "add_cast")
  161. instances = []
  162. x1 = np.ones((2, 2), np.int32)
  163. x2 = np.ones((2, 2), np.int32)
  164. instances.append({"x1": x1, "x2": x2})
  165. result = client.infer(instances)
  166. print(result)
  167. if __name__ == '__main__':
  168. run_add_common()
  169. run_add_cast()
  170. ```
  171. 使用mindspore_serving.client定义的Client类,分别调用模型的两个方法,显示如下返回值说明Serving服务已正确执行Add网络的推理。
  172. ```bash
  173. [{'y': array([[2. , 2.],
  174. [2., 2.]], dtype=float32)}]
  175. [{'y': array([[2. , 2.],
  176. [2., 2.]], dtype=float32)}]
  177. ```

A lightweight and high-performance service module that helps MindSpore developers efficiently deploy online inference services in the production environment.