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.

client_example.py 4.8 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. import random
  16. import json
  17. import requests
  18. import grpc
  19. import numpy as np
  20. import ms_service_pb2
  21. import ms_service_pb2_grpc
  22. import mindspore.dataset as de
  23. from mindspore import Tensor, context
  24. from mindspore import log as logger
  25. from tests.st.networks.models.bert.src.bert_model import BertModel
  26. from .generate_model import AddNet, bert_net_cfg
  27. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  28. random.seed(1)
  29. np.random.seed(1)
  30. de.config.set_seed(1)
  31. def test_add():
  32. channel = grpc.insecure_channel('localhost:5500')
  33. stub = ms_service_pb2_grpc.MSServiceStub(channel)
  34. request = ms_service_pb2.PredictRequest()
  35. x = request.data.add()
  36. x.tensor_shape.dims.extend([4])
  37. x.tensor_type = ms_service_pb2.MS_FLOAT32
  38. x.data = (np.ones([4]).astype(np.float32)).tobytes()
  39. y = request.data.add()
  40. y.tensor_shape.dims.extend([4])
  41. y.tensor_type = ms_service_pb2.MS_FLOAT32
  42. y.data = (np.ones([4]).astype(np.float32)).tobytes()
  43. result = stub.Predict(request)
  44. result_np = np.frombuffer(result.result[0].data, dtype=np.float32).reshape(result.result[0].tensor_shape.dims)
  45. print("ms client received: ")
  46. print(result_np)
  47. net = AddNet()
  48. net_out = net(Tensor(np.ones([4]).astype(np.float32)), Tensor(np.ones([4]).astype(np.float32)))
  49. print("add net out: ")
  50. print(net_out)
  51. assert np.allclose(net_out.asnumpy(), result_np, 0.001, 0.001, equal_nan=True)
  52. def test_bert():
  53. MAX_MESSAGE_LENGTH = 0x7fffffff
  54. input_ids = np.random.randint(0, 1000, size=(2, 32), dtype=np.int32)
  55. segment_ids = np.zeros((2, 32), dtype=np.int32)
  56. input_mask = np.zeros((2, 32), dtype=np.int32)
  57. # grpc visit
  58. channel = grpc.insecure_channel('localhost:5500', options=[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),
  59. ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)])
  60. stub = ms_service_pb2_grpc.MSServiceStub(channel)
  61. request = ms_service_pb2.PredictRequest()
  62. x = request.data.add()
  63. x.tensor_shape.dims.extend([2, 32])
  64. x.tensor_type = ms_service_pb2.MS_INT32
  65. x.data = input_ids.tobytes()
  66. y = request.data.add()
  67. y.tensor_shape.dims.extend([2, 32])
  68. y.tensor_type = ms_service_pb2.MS_INT32
  69. y.data = segment_ids.tobytes()
  70. z = request.data.add()
  71. z.tensor_shape.dims.extend([2, 32])
  72. z.tensor_type = ms_service_pb2.MS_INT32
  73. z.data = input_mask.tobytes()
  74. result = stub.Predict(request)
  75. grpc_result = np.frombuffer(result.result[0].data, dtype=np.float32).reshape(result.result[0].tensor_shape.dims)
  76. print("ms grpc client received: ")
  77. print(grpc_result)
  78. # ms result
  79. net = BertModel(bert_net_cfg, False)
  80. bert_out = net(Tensor(input_ids), Tensor(segment_ids), Tensor(input_mask))
  81. print("bert out: ")
  82. print(bert_out[0])
  83. bert_out_size = len(bert_out)
  84. # compare grpc result
  85. for i in range(bert_out_size):
  86. grpc_result = np.frombuffer(result.result[i].data, dtype=np.float32).reshape(result.result[i].tensor_shape.dims)
  87. logger.info("i:{}, grpc_result:{}, bert_out:{}".
  88. format(i, result.result[i].tensor_shape.dims, bert_out[i].asnumpy().shape))
  89. assert np.allclose(bert_out[i].asnumpy(), grpc_result, 0.001, 0.001, equal_nan=True)
  90. # http visit
  91. data = {"tensor": [input_ids.tolist(), segment_ids.tolist(), input_mask.tolist()]}
  92. url = "http://127.0.0.1:5501"
  93. input_json = json.dumps(data)
  94. headers = {'Content-type': 'application/json'}
  95. response = requests.post(url, data=input_json, headers=headers)
  96. result = response.text
  97. result = result.replace('\r', '\\r').replace('\n', '\\n')
  98. result_json = json.loads(result, strict=False)
  99. http_result = np.array(result_json['tensor'])
  100. print("ms http client received: ")
  101. print(http_result[0][:200])
  102. # compare http result
  103. for i in range(bert_out_size):
  104. logger.info("i:{}, http_result:{}, bert_out:{}".
  105. format(i, np.shape(http_result[i]), bert_out[i].asnumpy().shape))
  106. assert np.allclose(bert_out[i].asnumpy(), http_result[i], 0.001, 0.001, equal_nan=True)