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.

worker_proxy.h 30 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. #ifndef MINDSPORE_CCSRC_PS_WORKER_PROXY_H_
  17. #define MINDSPORE_CCSRC_PS_WORKER_PROXY_H_
  18. #include <map>
  19. #include <numeric>
  20. #include <functional>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <algorithm>
  24. #include <utility>
  25. #include <memory>
  26. #include <vector>
  27. #include "ps/ps.h"
  28. #include "ps/util.h"
  29. #include "backend/kernel_compiler/common_utils.h"
  30. #include "ps/ps_context.h"
  31. namespace mindspore {
  32. namespace ps {
  33. template <typename T>
  34. class WorkerProxy : public ::ps::KVWorker<T> {
  35. public:
  36. using Worker = ::ps::KVWorker<T>;
  37. using Callback = std::function<void()>;
  38. using SlicedKVs = std::vector<std::pair<bool, ::ps::KVPairs<T>>>;
  39. using Slicer = std::function<void(int ts, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &ranges,
  40. SlicedKVs *sliced, const std::map<int, int> &attrs)>;
  41. using ::ps::SimpleApp::obj_;
  42. explicit WorkerProxy(int app_id, int customer_id, int lookup_customer_id, int general_customer_id)
  43. : Worker(app_id, customer_id) {
  44. server_num_ = ::ps::NumServers();
  45. PSContext::instance()->SetPSRankId(::ps::MyRank());
  46. using std::placeholders::_1;
  47. using std::placeholders::_2;
  48. using std::placeholders::_3;
  49. using std::placeholders::_4;
  50. using std::placeholders::_5;
  51. lookup_customer_ = std::unique_ptr<::ps::Customer>(
  52. new ::ps::Customer(app_id, lookup_customer_id, std::bind(&WorkerProxy<T>::ProcessLookupResult, this, _1)));
  53. general_customer_ = std::unique_ptr<::ps::Customer>(
  54. new ::ps::Customer(app_id, general_customer_id, std::bind(&WorkerProxy<T>::ProcessResponse, this, _1)));
  55. lookup_slicer_ = std::bind(&WorkerProxy<T>::LookupIdSlicer, this, _1, _2, _3, _4, _5);
  56. sparse_slicer_ = std::bind(&WorkerProxy<T>::SparseSlicer, this, _1, _2, _3, _4, _5);
  57. broadcast_slicer_ = std::bind(&WorkerProxy<T>::BroadcastSlicer, this, _1, _2, _3, _4, _5);
  58. round_robin_slicer_ = std::bind(&WorkerProxy<T>::RoundRobinSlicer, this, _1, _2, _3, _4, _5);
  59. worker_init_embedding_slicer_ = std::bind(&WorkerProxy<T>::WorkerInitEmbeddingSlicer, this, _1, _2, _3, _4, _5);
  60. }
  61. ~WorkerProxy() override = default;
  62. void AddEmbeddingTable(const ::ps::Key &key, const size_t &row_count);
  63. void AddKeyToServerId(const ::ps::Key &key);
  64. void EmbeddingLookup(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids,
  65. const ::ps::SArray<int> &lens, ::ps::SArray<T> *outs, int cmd = 0, const Callback &cb = nullptr,
  66. int priority = 0);
  67. int InitEmbeddingTable(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals,
  68. const ::ps::SArray<int> &lens = {}, const Callback &cb = nullptr, int priority = 0);
  69. bool IsReadyForPush(const Key &key);
  70. bool IsReadyForPull(const Key &key);
  71. void PushData(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals, const ::ps::SArray<int> &lens = {},
  72. int cmd = 0, int priority = 0);
  73. void PushSparseData(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals, const ::ps::SArray<int> &lens,
  74. size_t grad_index, size_t indice_index, size_t first_dim_size, size_t outer_dim_size);
  75. void PullData(const ::ps::SArray<::ps::Key> &keys, ::ps::SArray<T> *vals, ::ps::SArray<int> *lens = nullptr,
  76. int cmd = 0, int priority = 0);
  77. void Finalize();
  78. private:
  79. template <typename C>
  80. int AddLookupCB(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids, C *vals, int cmd,
  81. const Callback &cb);
  82. int AddGeneralRspCB(const ::ps::SArray<::ps::Key> &keys, ::ps::SArray<T> *vals, ::ps::SArray<int> *lens, int cmd,
  83. const Callback &cb);
  84. void LookupIdSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  85. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int, int> &attrs);
  86. void SparseSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  87. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int, int> &attrs);
  88. void BroadcastSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  89. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int, int> &attrs);
  90. void RoundRobinSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  91. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int, int> &attrs);
  92. void WorkerInitEmbeddingSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  93. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  94. const std::map<int, int> &attrs);
  95. void ProcessLookupResult(const ::ps::Message &msg);
  96. void ProcessResponse(const ::ps::Message &msg);
  97. void Send(::ps::Customer *customer, int timestamp, bool push, bool pull, int cmd, const ::ps::KVPairs<T> &kvs,
  98. const Slicer &slicer, std::map<int, int> attrs = {});
  99. void AddKeyByHashMod(const ::ps::Key &key);
  100. void PrepareSparseGradient(const size_t begin, const size_t end, const std::unordered_set<int> &distinct_ids,
  101. const std::vector<std::pair<int, T *>> &indice_to_grad, const int *all_indice,
  102. const size_t segment_size, T *gradient, int *indice);
  103. void BuildSparseValue(const ::ps::SArray<int> &lengths, const size_t grad_index, const size_t indice_index,
  104. const T *original_data, const T *grads, int *indices, ::ps::SArray<T> *reduced_data);
  105. int server_num_;
  106. std::unique_ptr<::ps::Customer> lookup_customer_;
  107. std::unique_ptr<::ps::Customer> general_customer_;
  108. std::unordered_map<::ps::Key, std::shared_ptr<std::vector<::ps::Range>>> embedding_table_ranges_;
  109. std::unordered_map<int, std::vector<::ps::KVPairs<T>>> lookup_results_;
  110. std::unordered_map<int, std::map<int, ::ps::KVPairs<T>>> gathered_response_;
  111. std::mutex mutex_;
  112. Slicer lookup_slicer_;
  113. Slicer sparse_slicer_;
  114. Slicer broadcast_slicer_;
  115. Slicer round_robin_slicer_;
  116. Slicer worker_init_embedding_slicer_;
  117. std::unordered_map<int, Callback> lookup_callbacks_;
  118. std::unordered_map<int, Callback> general_callbacks_;
  119. std::unordered_map<int, int> expected_result_count_;
  120. std::unordered_map<::ps::Key, int> key_to_server_id_;
  121. std::unordered_map<::ps::Key, size_t> embedding_row_cnt_;
  122. };
  123. template <typename T>
  124. void WorkerProxy<T>::AddEmbeddingTable(const ::ps::Key &key, const size_t &row_count) {
  125. uint64_t begin = 0;
  126. uint64_t end = 0;
  127. for (int i = 0; i < server_num_; i++) {
  128. int local_row_cnt = Util::LocalShard(row_count, i, server_num_);
  129. if (i == 0) {
  130. end = local_row_cnt - 1;
  131. } else {
  132. begin = end + 1;
  133. end += local_row_cnt;
  134. }
  135. ::ps::Range range(begin, end);
  136. if (embedding_table_ranges_.count(key) == 0) {
  137. embedding_table_ranges_[key] = std::make_shared<std::vector<::ps::Range>>();
  138. MS_EXCEPTION_IF_NULL(embedding_table_ranges_[key]);
  139. }
  140. embedding_table_ranges_[key]->push_back(range);
  141. }
  142. embedding_row_cnt_[key] = row_count;
  143. }
  144. template <typename T>
  145. void WorkerProxy<T>::AddKeyByHashMod(const ::ps::Key &key) {
  146. if (server_num_ == 0) {
  147. MS_LOG(EXCEPTION) << "Server number is invalid:0";
  148. }
  149. key_to_server_id_[key] = static_cast<int>(key % server_num_);
  150. MS_LOG(INFO) << "The server id of key " << key << " is " << key_to_server_id_[key];
  151. }
  152. template <typename T>
  153. void WorkerProxy<T>::AddKeyToServerId(const ::ps::Key &key) {
  154. AddKeyByHashMod(key);
  155. }
  156. template <typename T>
  157. void WorkerProxy<T>::EmbeddingLookup(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids,
  158. const ::ps::SArray<int> &lens, ::ps::SArray<T> *outs, int cmd, const Callback &cb,
  159. int priority) {
  160. MS_EXCEPTION_IF_NULL(outs);
  161. int ts = AddLookupCB(keys, lookup_ids, outs, cmd, cb);
  162. ::ps::KVPairs<T> kvs;
  163. kvs.keys = keys;
  164. kvs.lens = lookup_ids;
  165. kvs.priority = priority;
  166. expected_result_count_[ts] = 0;
  167. Send(lookup_customer_.get(), ts, true, true, cmd, kvs, lookup_slicer_);
  168. int expect_rt_count = expected_result_count_[ts];
  169. lookup_customer_->AddResponse(ts, server_num_ - expect_rt_count);
  170. lookup_customer_->WaitRequest(ts);
  171. expected_result_count_.erase(ts);
  172. }
  173. template <typename T>
  174. int WorkerProxy<T>::InitEmbeddingTable(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals,
  175. const ::ps::SArray<int> &lens, const Callback &cb, int priority) {
  176. int ts = obj_->NewRequest(::ps::kServerGroup);
  177. ::ps::KVPairs<T> kvs;
  178. kvs.keys = keys;
  179. kvs.vals = vals;
  180. kvs.lens = lens;
  181. kvs.priority = priority;
  182. Send(obj_, ts, true, false, kInitEmbeddingsCmd, kvs, broadcast_slicer_);
  183. return ts;
  184. }
  185. template <typename T>
  186. bool WorkerProxy<T>::IsReadyForPush(const Key &key) {
  187. ::ps::SArray<T> result(1, 0);
  188. PullData({key}, &result, nullptr, kCheckReadyForPushCmd);
  189. if (result[0] > 0) {
  190. return true;
  191. } else {
  192. return false;
  193. }
  194. }
  195. template <typename T>
  196. bool WorkerProxy<T>::IsReadyForPull(const Key &key) {
  197. ::ps::SArray<T> result(1, 0);
  198. PullData({key}, &result, nullptr, kCheckReadyForPullCmd);
  199. if (result[0] > 0) {
  200. return true;
  201. } else {
  202. return false;
  203. }
  204. }
  205. template <typename T>
  206. void WorkerProxy<T>::PushData(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals,
  207. const ::ps::SArray<int> &lens, int cmd, int priority) {
  208. int ts = AddGeneralRspCB(keys, nullptr, nullptr, cmd, nullptr);
  209. ::ps::KVPairs<T> kvs;
  210. kvs.keys = keys;
  211. kvs.vals = vals;
  212. kvs.lens = lens;
  213. kvs.priority = priority;
  214. if (embedding_table_ranges_.count(keys[0])) {
  215. if (cmd == kInitWeightsCmd) {
  216. Send(general_customer_.get(), ts, true, false, cmd, kvs, worker_init_embedding_slicer_);
  217. } else {
  218. Send(general_customer_.get(), ts, true, false, cmd, kvs, broadcast_slicer_);
  219. }
  220. } else {
  221. Send(general_customer_.get(), ts, true, false, cmd, kvs, round_robin_slicer_);
  222. }
  223. if (expected_result_count_[ts] < server_num_) {
  224. general_customer_->AddResponse(ts, server_num_ - expected_result_count_[ts]);
  225. }
  226. general_customer_->WaitRequest(ts);
  227. }
  228. template <typename T>
  229. void WorkerProxy<T>::PushSparseData(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals,
  230. const ::ps::SArray<int> &lens, size_t grad_index, size_t indice_index,
  231. size_t first_dim_size, size_t outer_dim_size) {
  232. int ts = AddGeneralRspCB(keys, nullptr, nullptr, 0, nullptr);
  233. ::ps::KVPairs<T> kvs;
  234. kvs.keys = keys;
  235. kvs.vals = vals;
  236. kvs.lens = lens;
  237. const int cmd = 0;
  238. if (embedding_table_ranges_.count(keys[0])) {
  239. std::map<int, int> attrs{{0, grad_index}, {1, indice_index}, {2, first_dim_size}, {3, outer_dim_size}};
  240. Send(general_customer_.get(), ts, true, false, cmd, kvs, sparse_slicer_, attrs);
  241. } else {
  242. Send(general_customer_.get(), ts, true, false, cmd, kvs, round_robin_slicer_);
  243. }
  244. if (expected_result_count_[ts] < server_num_) {
  245. general_customer_->AddResponse(ts, server_num_ - expected_result_count_[ts]);
  246. }
  247. general_customer_->WaitRequest(ts);
  248. }
  249. template <typename T>
  250. void WorkerProxy<T>::PullData(const ::ps::SArray<::ps::Key> &keys, ::ps::SArray<T> *vals, ::ps::SArray<int> *lens,
  251. int cmd, int priority) {
  252. MS_EXCEPTION_IF_NULL(vals);
  253. int ts = AddGeneralRspCB(keys, vals, lens, cmd, nullptr);
  254. ::ps::KVPairs<T> kvs;
  255. kvs.keys = keys;
  256. kvs.priority = priority;
  257. if (embedding_table_ranges_.count(keys[0])) {
  258. Send(general_customer_.get(), ts, false, true, cmd, kvs, broadcast_slicer_);
  259. } else {
  260. Send(general_customer_.get(), ts, false, true, cmd, kvs, round_robin_slicer_);
  261. }
  262. if (expected_result_count_[ts] < server_num_) {
  263. general_customer_->AddResponse(ts, server_num_ - expected_result_count_[ts]);
  264. }
  265. general_customer_->WaitRequest(ts);
  266. }
  267. template <typename T>
  268. void WorkerProxy<T>::Finalize() {
  269. int ts = obj_->NewRequest(::ps::kServerGroup);
  270. ::ps::KVPairs<T> kvs;
  271. kvs.keys.push_back(0);
  272. kvs.vals.push_back(0.0f);
  273. Send(obj_, ts, true, false, kFinalizeCmd, kvs, broadcast_slicer_);
  274. obj_->WaitRequest(ts);
  275. ::ps::Finalize(0, true);
  276. }
  277. template <typename T>
  278. template <typename C>
  279. int WorkerProxy<T>::AddLookupCB(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids,
  280. C *lookup_result, int cmd, const Callback &cb) {
  281. MS_EXCEPTION_IF_NULL(lookup_result);
  282. int ts = lookup_customer_->NewRequest(::ps::kServerGroup);
  283. const auto &callback = [this, ts, keys, lookup_ids, lookup_result, cb]() mutable {
  284. mutex_.lock();
  285. auto &kvs = lookup_results_[ts];
  286. mutex_.unlock();
  287. std::unordered_map<Key, std::shared_ptr<std::pair<T *, int>>> id_addr_map;
  288. for (const auto &s : kvs) {
  289. int offset = 0;
  290. int len = s.vals.size() / s.keys.size();
  291. for (size_t i = 0; i < s.keys.size(); i++) {
  292. const Key &key = s.keys[i];
  293. T *addr = s.vals.data() + offset;
  294. offset += len;
  295. id_addr_map[key] = std::make_shared<std::pair<T *, int>>(std::make_pair(addr, len));
  296. MS_EXCEPTION_IF_NULL(id_addr_map[key]);
  297. }
  298. }
  299. T *result_addr = lookup_result->data();
  300. MS_EXCEPTION_IF_NULL(result_addr);
  301. int offset = 0;
  302. size_t dst_size = 0;
  303. size_t src_size = 0;
  304. void *dst_data = nullptr;
  305. void *src_data = nullptr;
  306. for (size_t i = 0; i < lookup_ids.size(); i++) {
  307. auto &pair = id_addr_map[static_cast<Key>(lookup_ids[i])];
  308. int size = pair->second * sizeof(T);
  309. dst_size = size;
  310. src_size = size;
  311. dst_data = result_addr + offset;
  312. src_data = pair->first;
  313. MS_EXCEPTION_IF_NULL(dst_data);
  314. MS_EXCEPTION_IF_NULL(src_data);
  315. auto ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  316. if (ret != 0) {
  317. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  318. return;
  319. }
  320. offset += pair->second;
  321. }
  322. mutex_.lock();
  323. lookup_results_.erase(ts);
  324. mutex_.unlock();
  325. if (cb) cb();
  326. };
  327. lookup_callbacks_[ts] = callback;
  328. return ts;
  329. }
  330. template <typename T>
  331. int WorkerProxy<T>::AddGeneralRspCB(const ::ps::SArray<::ps::Key> &keys, ::ps::SArray<T> *vals, ::ps::SArray<int> *lens,
  332. int cmd, const Callback &cb) {
  333. int ts = general_customer_->NewRequest(::ps::kServerGroup);
  334. const auto &callback = [this, ts, keys, vals, lens, cb]() mutable {
  335. mutex_.lock();
  336. std::map<int, ::ps::KVPairs<T>> server_kvs = gathered_response_[ts];
  337. mutex_.unlock();
  338. vals->clear();
  339. for (auto kvs : server_kvs) {
  340. for (auto val : kvs.second.vals) {
  341. vals->push_back(val);
  342. }
  343. if (lens) {
  344. for (auto len : kvs.second.lens) {
  345. lens->push_back(len);
  346. }
  347. }
  348. }
  349. mutex_.lock();
  350. gathered_response_.erase(ts);
  351. mutex_.unlock();
  352. if (cb) {
  353. cb();
  354. }
  355. };
  356. general_callbacks_[ts] = callback;
  357. return ts;
  358. }
  359. template <typename T>
  360. void WorkerProxy<T>::LookupIdSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  361. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  362. const std::map<int, int> &attrs) {
  363. MS_EXCEPTION_IF_NULL(sliced);
  364. int *lookup_ids = send.lens.data();
  365. size_t id_size = send.lens.size();
  366. const Key &key = send.keys[0];
  367. const std::vector<::ps::Range> &ranges = *(embedding_table_ranges_[key]);
  368. sliced->resize(ranges.size());
  369. for (size_t i = 0; i < ranges.size(); i++) {
  370. const ::ps::Range &range = ranges[i];
  371. const auto &begin = range.begin();
  372. const auto &end = range.end();
  373. std::unordered_set<int> unique_ids;
  374. auto &kvs = sliced->at(i).second;
  375. kvs.keys.push_back(key);
  376. kvs.vals.push_back(0.0f);
  377. for (size_t j = 0; j < id_size; j++) {
  378. auto lookup_id = static_cast<uint64_t>(lookup_ids[j]);
  379. if (lookup_id >= begin && lookup_id <= end) {
  380. unique_ids.insert(lookup_id);
  381. }
  382. }
  383. for (const auto &lookup_id : unique_ids) {
  384. kvs.keys.push_back(lookup_id);
  385. kvs.vals.push_back(0.0f);
  386. }
  387. if (kvs.keys.size() <= 1) {
  388. sliced->at(i).first = false;
  389. } else {
  390. sliced->at(i).first = true;
  391. expected_result_count_[timestamp] += 1;
  392. }
  393. }
  394. }
  395. template <typename T>
  396. void WorkerProxy<T>::SparseSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  397. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  398. const std::map<int, int> &attrs) {
  399. MS_EXCEPTION_IF_NULL(sliced);
  400. // Init variables
  401. T *data = send.vals.data();
  402. if (attrs.count(0) == 0 || attrs.count(1) == 0 || attrs.count(2) == 0 || attrs.count(3) == 0) {
  403. MS_LOG(EXCEPTION) << "Invalid attrs keys";
  404. }
  405. auto iter = attrs.find(0);
  406. size_t grad_index = static_cast<size_t>(iter->second);
  407. iter = attrs.find(1);
  408. size_t indice_index = static_cast<size_t>(iter->second);
  409. iter = attrs.find(2);
  410. size_t first_dim_size = static_cast<size_t>(iter->second);
  411. iter = attrs.find(3);
  412. size_t outer_dim_size = static_cast<size_t>(iter->second);
  413. int grad_size = send.lens[grad_index];
  414. int indice_size = send.lens[indice_index];
  415. int segment_size = grad_size / indice_size;
  416. int grad_offset = 0;
  417. int indice_offset = 0;
  418. for (size_t i = 0; i < grad_index; i++) {
  419. grad_offset += send.lens[i];
  420. }
  421. for (size_t j = 0; j < indice_index; j++) {
  422. indice_offset += send.lens[j];
  423. }
  424. T *grad_data = data + grad_offset;
  425. int *indice_data = reinterpret_cast<int *>(data) + indice_offset;
  426. // Build the mappings of indice to gradient
  427. std::vector<std::pair<int, T *>> indice_to_grads;
  428. for (int i = 0; i < indice_size; i++) {
  429. int indice = indice_data[i];
  430. T *grad = grad_data + i * segment_size;
  431. indice_to_grads.push_back(std::make_pair(indice, grad));
  432. }
  433. const Key &key = send.keys[0];
  434. const std::vector<::ps::Range> &ranges = *(embedding_table_ranges_[key]);
  435. sliced->resize(ranges.size());
  436. // Construct reduced sparse data for each server
  437. for (size_t i = 0; i < ranges.size(); i++) {
  438. const ::ps::Range &range = ranges[i];
  439. const auto &begin = range.begin();
  440. const auto &end = range.end();
  441. auto &kvs = sliced->at(i).second;
  442. kvs.keys = send.keys;
  443. kvs.lens = send.lens;
  444. // Prepare the sparse gradient and indice
  445. std::vector<int> indice_ids;
  446. std::unordered_set<int> distinct_ids;
  447. for (int j = 0; j < indice_size; j++) {
  448. size_t indice = static_cast<size_t>(indice_data[j]);
  449. if (indice >= begin && indice <= end) {
  450. indice_ids.push_back(indice);
  451. distinct_ids.insert(indice);
  452. }
  453. }
  454. size_t indices_size = indice_ids.size();
  455. if (indices_size > 0) {
  456. int slice_segment_size = indices_size * segment_size;
  457. std::vector<T> src_grad_data(slice_segment_size);
  458. std::vector<int> src_indice_data(indices_size);
  459. PrepareSparseGradient(begin, end, distinct_ids, indice_to_grads, indice_data, segment_size, src_grad_data.data(),
  460. src_indice_data.data());
  461. // Reduce the sparse gradient and indice
  462. std::vector<T> new_grad(slice_segment_size);
  463. std::vector<int> new_indices(indices_size);
  464. mindspore::kernel::SparseGradient<int> unique_sparse_grad({new_grad.data(), new_indices.data(), indices_size});
  465. Util::ReduceSparseGradient(src_grad_data.data(), src_indice_data.data(), indices_size, segment_size,
  466. first_dim_size, outer_dim_size, &unique_sparse_grad);
  467. // Update the length of reduce sparse gradient and indice
  468. ::ps::SArray<int> reduced_lens;
  469. reduced_lens.CopyFrom(kvs.lens);
  470. reduced_lens[grad_index] = unique_sparse_grad.indices_size_ * segment_size;
  471. reduced_lens[indice_index] = unique_sparse_grad.indices_size_;
  472. // Build the sparse value to be sent
  473. size_t total_size = std::accumulate(reduced_lens.begin(), reduced_lens.end(), 0, std::plus<int>());
  474. ::ps::SArray<T> reduced_data(total_size, 0);
  475. BuildSparseValue(reduced_lens, grad_index, indice_index, data, unique_sparse_grad.value_,
  476. unique_sparse_grad.indices_, &reduced_data);
  477. kvs.lens = reduced_lens;
  478. kvs.vals = reduced_data;
  479. }
  480. if (indices_size <= 0) {
  481. ::ps::SArray<T> no_keys;
  482. ::ps::SArray<T> no_vals;
  483. ::ps::SArray<T> no_lens;
  484. no_keys.push_back(key);
  485. no_vals.push_back(-100);
  486. kvs.vals = no_vals;
  487. kvs.lens = no_lens;
  488. }
  489. sliced->at(i).first = true;
  490. expected_result_count_[timestamp] += 1;
  491. }
  492. }
  493. template <typename T>
  494. void WorkerProxy<T>::PrepareSparseGradient(const size_t begin, const size_t end,
  495. const std::unordered_set<int> &distinct_ids,
  496. const std::vector<std::pair<int, T *>> &indice_to_grads,
  497. const int *all_indice, const size_t segment_size, T *gradient,
  498. int *indices) {
  499. MS_EXCEPTION_IF_NULL(all_indice);
  500. MS_EXCEPTION_IF_NULL(gradient);
  501. MS_EXCEPTION_IF_NULL(indices);
  502. int offset = 0;
  503. int index = 0;
  504. size_t segment_data_size = segment_size * sizeof(T);
  505. size_t dst_size;
  506. size_t src_size;
  507. void *dst_data = nullptr;
  508. void *src_data = nullptr;
  509. for (auto &pair : indice_to_grads) {
  510. if (distinct_ids.count(pair.first) == 0) {
  511. continue;
  512. }
  513. indices[index++] = pair.first;
  514. dst_size = segment_data_size;
  515. src_size = segment_data_size;
  516. dst_data = gradient + offset;
  517. src_data = pair.second;
  518. MS_EXCEPTION_IF_NULL(dst_data);
  519. MS_EXCEPTION_IF_NULL(src_data);
  520. auto ret = memcpy_s(gradient + offset, dst_size, pair.second, src_size);
  521. if (ret != 0) {
  522. MS_LOG(ERROR) << "memcpy_s error, errorno(" << ret << ")";
  523. return;
  524. }
  525. offset += segment_size;
  526. }
  527. }
  528. template <typename T>
  529. void WorkerProxy<T>::BuildSparseValue(const ::ps::SArray<int> &lengths, const size_t grad_index,
  530. const size_t indice_index, const T *original_data, const T *grads, int *indices,
  531. ::ps::SArray<T> *reduced_data) {
  532. MS_EXCEPTION_IF_NULL(original_data);
  533. MS_EXCEPTION_IF_NULL(grads);
  534. MS_EXCEPTION_IF_NULL(indices);
  535. MS_EXCEPTION_IF_NULL(reduced_data);
  536. int offset = 0;
  537. size_t dst_size = 0;
  538. size_t src_size = 0;
  539. void *dst_data = nullptr;
  540. void *src_data = nullptr;
  541. for (size_t i = 0; i < lengths.size(); i++) {
  542. if (i != grad_index && i != indice_index) {
  543. int data_size = lengths[i] * sizeof(T);
  544. dst_size = data_size;
  545. src_size = data_size;
  546. dst_data = reduced_data->data() + offset;
  547. src_data = const_cast<T *>(original_data) + offset;
  548. MS_EXCEPTION_IF_NULL(dst_data);
  549. MS_EXCEPTION_IF_NULL(src_data);
  550. auto ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  551. if (ret != 0) {
  552. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  553. return;
  554. }
  555. }
  556. offset += lengths[i];
  557. }
  558. // Fill the reduced gradient
  559. int grad_offset = 0;
  560. for (size_t i = 0; i < grad_index; i++) {
  561. grad_offset += lengths[i];
  562. }
  563. int data_size = lengths[grad_index] * sizeof(T);
  564. dst_size = data_size;
  565. src_size = data_size;
  566. dst_data = reduced_data->data() + grad_offset;
  567. src_data = const_cast<T *>(grads);
  568. MS_EXCEPTION_IF_NULL(dst_data);
  569. MS_EXCEPTION_IF_NULL(src_data);
  570. auto ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  571. if (ret != 0) {
  572. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  573. return;
  574. }
  575. // Fill the reduced indice
  576. int indice_offset = grad_offset + lengths[grad_index];
  577. data_size = lengths[indice_index] * sizeof(T);
  578. T *indice_data = reduced_data->data() + indice_offset;
  579. dst_size = data_size;
  580. src_size = data_size;
  581. dst_data = indice_data;
  582. src_data = indices;
  583. MS_EXCEPTION_IF_NULL(dst_data);
  584. MS_EXCEPTION_IF_NULL(src_data);
  585. ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  586. if (ret != 0) {
  587. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  588. return;
  589. }
  590. }
  591. template <typename T>
  592. void WorkerProxy<T>::BroadcastSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  593. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  594. const std::map<int, int> &attr) {
  595. MS_EXCEPTION_IF_NULL(sliced);
  596. sliced->resize(server_num_);
  597. for (int i = 0; i < server_num_; i++) {
  598. sliced->at(i).first = true;
  599. sliced->at(i).second = send;
  600. expected_result_count_[timestamp] += 1;
  601. }
  602. }
  603. template <typename T>
  604. void WorkerProxy<T>::RoundRobinSlicer(int timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  605. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  606. const std::map<int, int> &attr) {
  607. MS_EXCEPTION_IF_NULL(sliced);
  608. sliced->resize(server_num_);
  609. auto keys = send.keys;
  610. auto vals = send.vals;
  611. auto lens = send.lens;
  612. int server_id, len;
  613. ::ps::Key param_key;
  614. for (size_t i = 0; i < keys.size(); i++) {
  615. param_key = keys[i];
  616. server_id = key_to_server_id_[param_key];
  617. if (!sliced->at(server_id).first) {
  618. sliced->at(server_id).first = true;
  619. expected_result_count_[timestamp] += 1;
  620. }
  621. ::ps::KVPairs<T> &server_kv_pairs = sliced->at(server_id).second;
  622. server_kv_pairs.keys.push_back(param_key);
  623. if (vals.empty()) {
  624. continue;
  625. }
  626. len = lens[i];
  627. int offset = std::accumulate(lens.begin(), lens.begin() + i, 0);
  628. auto val_begin = vals.begin() + offset;
  629. auto val_end = val_begin + len;
  630. for (auto iter = val_begin; iter != val_end; iter++) {
  631. server_kv_pairs.vals.push_back(*iter);
  632. }
  633. server_kv_pairs.lens.push_back(len);
  634. }
  635. }
  636. template <typename T>
  637. void WorkerProxy<T>::WorkerInitEmbeddingSlicer(int timestamp, const ::ps::KVPairs<T> &send,
  638. const std::vector<::ps::Range> &,
  639. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  640. const std::map<int, int> &attrs) {
  641. MS_EXCEPTION_IF_NULL(sliced);
  642. sliced->resize(server_num_);
  643. auto keys = send.keys;
  644. auto vals = send.vals;
  645. auto lens = send.lens;
  646. size_t col_cnt = lens[0] / embedding_row_cnt_[keys[0]];
  647. const std::vector<::ps::Range> &ranges = *(embedding_table_ranges_[keys[0]]);
  648. for (size_t i = 0; i < ranges.size(); i++) {
  649. size_t offset_begin = ranges[i].begin() * col_cnt;
  650. size_t offset_end = (ranges[i].end() + 1) * col_cnt;
  651. ::ps::KVPairs<T> kvs;
  652. kvs.keys = keys;
  653. kvs.vals = vals.segment(offset_begin, offset_end);
  654. kvs.lens.push_back(offset_end - offset_begin);
  655. sliced->at(i).first = true;
  656. sliced->at(i).second = kvs;
  657. }
  658. }
  659. template <typename T>
  660. void WorkerProxy<T>::ProcessLookupResult(const ::ps::Message &msg) {
  661. int ts = msg.meta.timestamp;
  662. if (msg.meta.pull) {
  663. CHECK_GE(msg.data.size(), (size_t)2);
  664. ::ps::KVPairs<T> kvs;
  665. kvs.keys = msg.data[0];
  666. kvs.vals = msg.data[1];
  667. if (msg.data.size() > (size_t)2) {
  668. kvs.lens = msg.data[2];
  669. }
  670. mutex_.lock();
  671. lookup_results_[ts].push_back(kvs);
  672. mutex_.unlock();
  673. }
  674. if (lookup_customer_->NumResponse(ts) + 1 == server_num_) {
  675. const auto &cb = lookup_callbacks_[ts];
  676. cb();
  677. lookup_callbacks_.erase(ts);
  678. }
  679. }
  680. template <typename T>
  681. void WorkerProxy<T>::ProcessResponse(const ::ps::Message &msg) {
  682. int ts = msg.meta.timestamp;
  683. if (msg.meta.pull) {
  684. CHECK_GE(msg.data.size(), (size_t)2);
  685. ::ps::KVPairs<T> kvs;
  686. kvs.keys = msg.data[0];
  687. kvs.vals = msg.data[1];
  688. if (msg.data.size() > (size_t)2) {
  689. kvs.lens = msg.data[2];
  690. }
  691. mutex_.lock();
  692. int rsp_server_rank = ::ps::Postoffice::Get()->IDtoRank(msg.meta.sender);
  693. gathered_response_[ts][rsp_server_rank] = kvs;
  694. mutex_.unlock();
  695. if (general_customer_->NumResponse(ts) + 1 == server_num_) {
  696. const auto &cb = general_callbacks_[ts];
  697. cb();
  698. general_callbacks_.erase(ts);
  699. }
  700. }
  701. }
  702. template <typename T>
  703. void WorkerProxy<T>::Send(::ps::Customer *customer, int timestamp, bool push, bool pull, int cmd,
  704. const ::ps::KVPairs<T> &kvs, const Slicer &slicer, std::map<int, int> attrs) {
  705. MS_EXCEPTION_IF_NULL(customer);
  706. SlicedKVs sliced;
  707. slicer(timestamp, kvs, ::ps::Postoffice::Get()->GetServerKeyRanges(), &sliced, attrs);
  708. for (size_t i = 0; i < sliced.size(); i++) {
  709. const auto &s = sliced[i];
  710. if (!s.first) continue;
  711. ::ps::Message msg;
  712. msg.meta.app_id = customer->app_id();
  713. msg.meta.customer_id = customer->customer_id();
  714. msg.meta.request = true;
  715. msg.meta.push = push;
  716. msg.meta.pull = pull;
  717. msg.meta.head = cmd;
  718. msg.meta.timestamp = timestamp;
  719. msg.meta.recver = ::ps::Postoffice::Get()->ServerRankToID(i);
  720. msg.meta.priority = kvs.priority;
  721. const auto &kvs = s.second;
  722. if (kvs.keys.size()) {
  723. msg.AddData(kvs.keys);
  724. msg.AddData(kvs.vals);
  725. if (kvs.lens.size()) {
  726. msg.AddData(kvs.lens);
  727. }
  728. }
  729. ::ps::Postoffice::Get()->van()->Send(msg);
  730. }
  731. }
  732. } // namespace ps
  733. } // namespace mindspore
  734. #endif // MINDSPORE_CCSRC_PS_WORKER_PROXY_H_