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.

ms_client.cc 9.2 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <grpcpp/grpcpp.h>
  17. #include <iostream>
  18. #include <vector>
  19. #include <string>
  20. #include <fstream>
  21. #include "./ms_service.grpc.pb.h"
  22. using grpc::Channel;
  23. using grpc::ClientContext;
  24. using grpc::Status;
  25. using ms_serving::MSService;
  26. using ms_serving::PredictReply;
  27. using ms_serving::PredictRequest;
  28. using ms_serving::Tensor;
  29. using ms_serving::TensorShape;
  30. enum TypeId : int {
  31. kTypeUnknown = 0,
  32. kMetaTypeBegin = kTypeUnknown,
  33. kMetaTypeType, // Type
  34. kMetaTypeAnything,
  35. kMetaTypeObject,
  36. kMetaTypeTypeType, // TypeType
  37. kMetaTypeProblem,
  38. kMetaTypeExternal,
  39. kMetaTypeNone,
  40. kMetaTypeNull,
  41. kMetaTypeEllipsis,
  42. kMetaTypeEnd,
  43. //
  44. // Object types
  45. //
  46. kObjectTypeBegin = kMetaTypeEnd,
  47. kObjectTypeNumber,
  48. kObjectTypeString,
  49. kObjectTypeList,
  50. kObjectTypeTuple,
  51. kObjectTypeSlice,
  52. kObjectTypeKeyword,
  53. kObjectTypeTensorType,
  54. kObjectTypeClass,
  55. kObjectTypeDictionary,
  56. kObjectTypeFunction,
  57. kObjectTypeJTagged,
  58. kObjectTypeSymbolicKeyType,
  59. kObjectTypeEnvType,
  60. kObjectTypeRefKey,
  61. kObjectTypeRef,
  62. kObjectTypeEnd,
  63. //
  64. // Number Types
  65. //
  66. kNumberTypeBegin = kObjectTypeEnd,
  67. kNumberTypeBool,
  68. kNumberTypeInt,
  69. kNumberTypeInt8,
  70. kNumberTypeInt16,
  71. kNumberTypeInt32,
  72. kNumberTypeInt64,
  73. kNumberTypeUInt,
  74. kNumberTypeUInt8,
  75. kNumberTypeUInt16,
  76. kNumberTypeUInt32,
  77. kNumberTypeUInt64,
  78. kNumberTypeFloat,
  79. kNumberTypeFloat16,
  80. kNumberTypeFloat32,
  81. kNumberTypeFloat64,
  82. kNumberTypeEnd
  83. };
  84. std::string RealPath(const char *path) {
  85. if (path == nullptr) {
  86. std::cout << "path is nullptr";
  87. return "";
  88. }
  89. if ((strlen(path)) >= PATH_MAX) {
  90. std::cout << "path is too long";
  91. return "";
  92. }
  93. std::shared_ptr<char> resolvedPath(new (std::nothrow) char[PATH_MAX]{0});
  94. if (resolvedPath == nullptr) {
  95. std::cout << "new resolvedPath failed";
  96. return "";
  97. }
  98. auto ret = realpath(path, resolvedPath.get());
  99. if (ret == nullptr) {
  100. std::cout << "realpath failed";
  101. return "";
  102. }
  103. return resolvedPath.get();
  104. }
  105. char *ReadFile(const char *file, size_t *size) {
  106. if (file == nullptr) {
  107. std::cout << "file is nullptr" << std::endl;
  108. return nullptr;
  109. }
  110. if (size == nullptr) {
  111. std::cout << "size should not be nullptr" << std::endl;
  112. return nullptr;
  113. }
  114. std::ifstream ifs(RealPath(file));
  115. if (!ifs.good()) {
  116. std::cout << "file: " << file << "is not exist";
  117. return nullptr;
  118. }
  119. if (!ifs.is_open()) {
  120. std::cout << "file: " << file << "open failed";
  121. return nullptr;
  122. }
  123. ifs.seekg(0, std::ios::end);
  124. *size = ifs.tellg();
  125. std::unique_ptr<char> buf(new (std::nothrow) char[*size]);
  126. if (buf == nullptr) {
  127. std::cout << "malloc buf failed, file: " << file;
  128. ifs.close();
  129. return nullptr;
  130. }
  131. ifs.seekg(0, std::ios::beg);
  132. ifs.read(buf.get(), *size);
  133. ifs.close();
  134. return buf.release();
  135. }
  136. const std::map<TypeId, ms_serving::DataType> id2type_map{
  137. {TypeId::kNumberTypeBegin, ms_serving::MS_UNKNOWN}, {TypeId::kNumberTypeBool, ms_serving::MS_BOOL},
  138. {TypeId::kNumberTypeInt8, ms_serving::MS_INT8}, {TypeId::kNumberTypeUInt8, ms_serving::MS_UINT8},
  139. {TypeId::kNumberTypeInt16, ms_serving::MS_INT16}, {TypeId::kNumberTypeUInt16, ms_serving::MS_UINT16},
  140. {TypeId::kNumberTypeInt32, ms_serving::MS_INT32}, {TypeId::kNumberTypeUInt32, ms_serving::MS_UINT32},
  141. {TypeId::kNumberTypeInt64, ms_serving::MS_INT64}, {TypeId::kNumberTypeUInt64, ms_serving::MS_UINT64},
  142. {TypeId::kNumberTypeFloat16, ms_serving::MS_FLOAT16}, {TypeId::kNumberTypeFloat32, ms_serving::MS_FLOAT32},
  143. {TypeId::kNumberTypeFloat64, ms_serving::MS_FLOAT64},
  144. };
  145. int WriteFile(const void *buf, size_t size) {
  146. auto fd = fopen("output.json", "a+");
  147. if (fd == NULL) {
  148. std::cout << "fd is null and open file fail" << std::endl;
  149. return 0;
  150. }
  151. fwrite(buf, size, 1, fd);
  152. fclose(fd);
  153. return 0;
  154. }
  155. PredictRequest ReadBertInput() {
  156. size_t size;
  157. auto buf = ReadFile("input206.json", &size);
  158. if (buf == nullptr) {
  159. std::cout << "read file failed" << std::endl;
  160. return PredictRequest();
  161. }
  162. PredictRequest request;
  163. auto cur = buf;
  164. while (size > 0) {
  165. if (request.data_size() == 4) {
  166. break;
  167. }
  168. Tensor data;
  169. TensorShape shape;
  170. // set type
  171. int type = *(reinterpret_cast<int *>(cur));
  172. cur = cur + sizeof(int);
  173. size = size - sizeof(int);
  174. ms_serving::DataType dataType = id2type_map.at(TypeId(type));
  175. data.set_tensor_type(dataType);
  176. // set shape
  177. size_t dims = *(reinterpret_cast<size_t *>(cur));
  178. cur = cur + sizeof(size_t);
  179. size = size - sizeof(size_t);
  180. for (size_t i = 0; i < dims; i++) {
  181. int dim = *(reinterpret_cast<int *>(cur));
  182. shape.add_dims(dim);
  183. cur = cur + sizeof(int);
  184. size = size - sizeof(int);
  185. }
  186. *data.mutable_tensor_shape() = shape;
  187. // set data
  188. size_t data_len = *(reinterpret_cast<size_t *>(cur));
  189. cur = cur + sizeof(size_t);
  190. size = size - sizeof(size_t);
  191. data.set_data(cur, data_len);
  192. cur = cur + data_len;
  193. size = size - data_len;
  194. *request.add_data() = data;
  195. }
  196. return request;
  197. }
  198. class MSClient {
  199. public:
  200. explicit MSClient(std::shared_ptr<Channel> channel) : stub_(MSService::NewStub(channel)) {}
  201. ~MSClient() = default;
  202. std::string Predict(const std::string &type) {
  203. // Data we are sending to the server.
  204. PredictRequest request;
  205. if (type == "add") {
  206. Tensor data;
  207. TensorShape shape;
  208. shape.add_dims(1);
  209. shape.add_dims(1);
  210. shape.add_dims(2);
  211. shape.add_dims(2);
  212. *data.mutable_tensor_shape() = shape;
  213. data.set_tensor_type(ms_serving::MS_FLOAT32);
  214. std::vector<float> input_data{1.1, 2.1, 3.1, 4.1};
  215. data.set_data(input_data.data(), input_data.size());
  216. *request.add_data() = data;
  217. *request.add_data() = data;
  218. } else if (type == "bert") {
  219. request = ReadBertInput();
  220. } else {
  221. std::cout << "type only support bert or add, but input is " << type << std::endl;
  222. }
  223. std::cout << "intput tensor size is " << request.data_size() << std::endl;
  224. // Container for the data we expect from the server.
  225. PredictReply reply;
  226. // Context for the client. It could be used to convey extra information to
  227. // the server and/or tweak certain RPC behaviors.
  228. ClientContext context;
  229. // The actual RPC.
  230. Status status = stub_->Predict(&context, request, &reply);
  231. for (int i = 0; i < reply.result_size(); i++) {
  232. WriteFile(reply.result(i).data().data(), reply.result(i).data().size());
  233. }
  234. std::cout << "the return result size is " << reply.result_size() << std::endl;
  235. // Act upon its status.
  236. if (status.ok()) {
  237. return "RPC OK";
  238. } else {
  239. std::cout << status.error_code() << ": " << status.error_message() << std::endl;
  240. return "RPC failed";
  241. }
  242. }
  243. private:
  244. std::unique_ptr<MSService::Stub> stub_;
  245. };
  246. int main(int argc, char **argv) {
  247. // Instantiate the client. It requires a channel, out of which the actual RPCs
  248. // are created. This channel models a connection to an endpoint specified by
  249. // the argument "--target=" which is the only expected argument.
  250. // We indicate that the channel isn't authenticated (use of
  251. // InsecureChannelCredentials()).
  252. std::string target_str;
  253. std::string arg_target_str("--target");
  254. std::string type;
  255. std::string arg_type_str("--type");
  256. if (argc > 2) {
  257. {
  258. // parse target
  259. std::string arg_val = argv[1];
  260. size_t start_pos = arg_val.find(arg_target_str);
  261. if (start_pos != std::string::npos) {
  262. start_pos += arg_target_str.size();
  263. if (arg_val[start_pos] == '=') {
  264. target_str = arg_val.substr(start_pos + 1);
  265. } else {
  266. std::cout << "The only correct argument syntax is --target=" << std::endl;
  267. return 0;
  268. }
  269. } else {
  270. target_str = "localhost:5500";
  271. }
  272. }
  273. {
  274. // parse type
  275. std::string arg_val2 = argv[2];
  276. size_t start_pos = arg_val2.find(arg_type_str);
  277. if (start_pos != std::string::npos) {
  278. start_pos += arg_type_str.size();
  279. if (arg_val2[start_pos] == '=') {
  280. type = arg_val2.substr(start_pos + 1);
  281. } else {
  282. std::cout << "The only correct argument syntax is --target=" << std::endl;
  283. return 0;
  284. }
  285. } else {
  286. type = "add";
  287. }
  288. }
  289. } else {
  290. target_str = "localhost:5500";
  291. type = "add";
  292. }
  293. MSClient client(grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
  294. std::string reply = client.Predict(type);
  295. std::cout << "client received: " << reply << std::endl;
  296. return 0;
  297. }