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. std::string Predict(const std::string &type) {
  202. // Data we are sending to the server.
  203. PredictRequest request;
  204. if (type == "add") {
  205. Tensor data;
  206. TensorShape shape;
  207. shape.add_dims(1);
  208. shape.add_dims(1);
  209. shape.add_dims(2);
  210. shape.add_dims(2);
  211. *data.mutable_tensor_shape() = shape;
  212. data.set_tensor_type(ms_serving::MS_FLOAT32);
  213. std::vector<float> input_data{1.1, 2.1, 3.1, 4.1};
  214. data.set_data(input_data.data(), input_data.size());
  215. *request.add_data() = data;
  216. *request.add_data() = data;
  217. } else if (type == "bert") {
  218. request = ReadBertInput();
  219. } else {
  220. std::cout << "type only support bert or add, but input is " << type << std::endl;
  221. }
  222. std::cout << "intput tensor size is " << request.data_size() << std::endl;
  223. // Container for the data we expect from the server.
  224. PredictReply reply;
  225. // Context for the client. It could be used to convey extra information to
  226. // the server and/or tweak certain RPC behaviors.
  227. ClientContext context;
  228. // The actual RPC.
  229. Status status = stub_->Predict(&context, request, &reply);
  230. for (int i = 0; i < reply.result_size(); i++) {
  231. WriteFile(reply.result(i).data().data(), reply.result(i).data().size());
  232. }
  233. std::cout << "the return result size is " << reply.result_size() << std::endl;
  234. // Act upon its status.
  235. if (status.ok()) {
  236. return "RPC OK";
  237. } else {
  238. std::cout << status.error_code() << ": " << status.error_message() << std::endl;
  239. return "RPC failed";
  240. }
  241. }
  242. private:
  243. std::unique_ptr<MSService::Stub> stub_;
  244. };
  245. int main(int argc, char **argv) {
  246. // Instantiate the client. It requires a channel, out of which the actual RPCs
  247. // are created. This channel models a connection to an endpoint specified by
  248. // the argument "--target=" which is the only expected argument.
  249. // We indicate that the channel isn't authenticated (use of
  250. // InsecureChannelCredentials()).
  251. std::string target_str;
  252. std::string arg_target_str("--target");
  253. std::string type;
  254. std::string arg_type_str("--type");
  255. if (argc > 2) {
  256. {
  257. // parse target
  258. std::string arg_val = argv[1];
  259. size_t start_pos = arg_val.find(arg_target_str);
  260. if (start_pos != std::string::npos) {
  261. start_pos += arg_target_str.size();
  262. if (arg_val[start_pos] == '=') {
  263. target_str = arg_val.substr(start_pos + 1);
  264. } else {
  265. std::cout << "The only correct argument syntax is --target=" << std::endl;
  266. return 0;
  267. }
  268. } else {
  269. target_str = "localhost:5500";
  270. }
  271. }
  272. {
  273. // parse type
  274. std::string arg_val2 = argv[2];
  275. size_t start_pos = arg_val2.find(arg_type_str);
  276. if (start_pos != std::string::npos) {
  277. start_pos += arg_type_str.size();
  278. if (arg_val2[start_pos] == '=') {
  279. type = arg_val2.substr(start_pos + 1);
  280. } else {
  281. std::cout << "The only correct argument syntax is --target=" << std::endl;
  282. return 0;
  283. }
  284. } else {
  285. type = "add";
  286. }
  287. }
  288. } else {
  289. target_str = "localhost:5500";
  290. type = "add";
  291. }
  292. MSClient client(grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
  293. std::string reply = client.Predict(type);
  294. std::cout << "client received: " << reply << std::endl;
  295. return 0;
  296. }