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 31 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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(int64_t ts, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &ranges,
  40. SlicedKVs *sliced, const std::map<int64_t, int64_t> &attrs)>;
  41. using ::ps::SimpleApp::obj_;
  42. explicit WorkerProxy(int64_t app_id, int64_t customer_id, int64_t lookup_customer_id, int64_t 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, int64_t cmd = 0,
  66. const Callback &cb = nullptr, int64_t priority = 0);
  67. int64_t InitEmbeddingTable(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals,
  68. const ::ps::SArray<int> &lens = {}, const Callback &cb = nullptr, int64_t 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. int64_t cmd = 0, int64_t 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. int64_t cmd = 0, int64_t priority = 0);
  77. void Finalize();
  78. private:
  79. template <typename C>
  80. int64_t AddLookupCB(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids, C *vals, int64_t cmd,
  81. const Callback &cb);
  82. int64_t AddGeneralRspCB(const ::ps::SArray<::ps::Key> &keys, ::ps::SArray<T> *vals, ::ps::SArray<int> *lens,
  83. int64_t cmd, const Callback &cb);
  84. void LookupIdSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  85. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int64_t, int64_t> &attrs);
  86. void SparseSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  87. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int64_t, int64_t> &attrs);
  88. void BroadcastSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  89. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced, const std::map<int64_t, int64_t> &attrs);
  90. void RoundRobinSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  91. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  92. const std::map<int64_t, int64_t> &attrs);
  93. void WorkerInitEmbeddingSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  94. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  95. const std::map<int64_t, int64_t> &attrs);
  96. void ProcessLookupResult(const ::ps::Message &msg);
  97. void ProcessResponse(const ::ps::Message &msg);
  98. void Send(::ps::Customer *customer, int64_t timestamp, bool push, bool pull, int64_t cmd, const ::ps::KVPairs<T> &kvs,
  99. const Slicer &slicer, std::map<int64_t, int64_t> attrs = {});
  100. void AddKeyByHashMod(const ::ps::Key &key);
  101. void PrepareSparseGradient(const size_t begin, const size_t end, const std::unordered_set<int> &distinct_ids,
  102. const std::vector<std::pair<int, T *>> &indice_to_grad, const int *all_indice,
  103. const size_t segment_size, T *gradient, int *indice);
  104. void BuildSparseValue(const ::ps::SArray<int> &lengths, const size_t grad_index, const size_t indice_index,
  105. const T *original_data, const T *grads, int *indices, ::ps::SArray<T> *reduced_data);
  106. int64_t server_num_;
  107. std::unique_ptr<::ps::Customer> lookup_customer_;
  108. std::unique_ptr<::ps::Customer> general_customer_;
  109. std::unordered_map<::ps::Key, std::shared_ptr<std::vector<::ps::Range>>> embedding_table_ranges_;
  110. std::unordered_map<int64_t, std::vector<::ps::KVPairs<T>>> lookup_results_;
  111. std::unordered_map<int64_t, std::map<int64_t, ::ps::KVPairs<T>>> gathered_response_;
  112. std::mutex mutex_;
  113. Slicer lookup_slicer_;
  114. Slicer sparse_slicer_;
  115. Slicer broadcast_slicer_;
  116. Slicer round_robin_slicer_;
  117. Slicer worker_init_embedding_slicer_;
  118. std::unordered_map<int64_t, Callback> lookup_callbacks_;
  119. std::unordered_map<int64_t, Callback> general_callbacks_;
  120. std::unordered_map<int64_t, int64_t> expected_result_count_;
  121. std::unordered_map<::ps::Key, int64_t> key_to_server_id_;
  122. std::unordered_map<::ps::Key, size_t> embedding_row_cnt_;
  123. };
  124. template <typename T>
  125. void WorkerProxy<T>::AddEmbeddingTable(const ::ps::Key &key, const size_t &row_count) {
  126. uint64_t begin = 0;
  127. uint64_t end = 0;
  128. for (int64_t i = 0; i < server_num_; i++) {
  129. int64_t local_row_cnt = Util::LocalShard(row_count, i, server_num_);
  130. if (i == 0) {
  131. end = local_row_cnt - 1;
  132. } else {
  133. begin = end + 1;
  134. end += local_row_cnt;
  135. }
  136. ::ps::Range range(begin, end);
  137. if (embedding_table_ranges_.count(key) == 0) {
  138. embedding_table_ranges_[key] = std::make_shared<std::vector<::ps::Range>>();
  139. MS_EXCEPTION_IF_NULL(embedding_table_ranges_[key]);
  140. }
  141. embedding_table_ranges_[key]->push_back(range);
  142. }
  143. embedding_row_cnt_[key] = row_count;
  144. }
  145. template <typename T>
  146. void WorkerProxy<T>::AddKeyByHashMod(const ::ps::Key &key) {
  147. if (server_num_ == 0) {
  148. MS_LOG(EXCEPTION) << "Server number is invalid:0";
  149. }
  150. key_to_server_id_[key] = static_cast<int64_t>(key % server_num_);
  151. MS_LOG(INFO) << "The server id of key " << key << " is " << key_to_server_id_[key];
  152. }
  153. template <typename T>
  154. void WorkerProxy<T>::AddKeyToServerId(const ::ps::Key &key) {
  155. AddKeyByHashMod(key);
  156. }
  157. template <typename T>
  158. void WorkerProxy<T>::EmbeddingLookup(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids,
  159. const ::ps::SArray<int> &lens, ::ps::SArray<T> *outs, int64_t cmd,
  160. const Callback &cb, int64_t priority) {
  161. int64_t 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. int64_t 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. int64_t WorkerProxy<T>::InitEmbeddingTable(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<T> &vals,
  175. const ::ps::SArray<int> &lens, const Callback &cb, int64_t priority) {
  176. int64_t 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, int64_t cmd, int64_t priority) {
  208. int64_t 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. int64_t 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 int64_t cmd = 0;
  238. if (embedding_table_ranges_.count(keys[0])) {
  239. std::map<int64_t, int64_t> 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. int64_t cmd, int64_t priority) {
  252. MS_EXCEPTION_IF_NULL(vals);
  253. int64_t 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. int64_t 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. int64_t WorkerProxy<T>::AddLookupCB(const ::ps::SArray<::ps::Key> &keys, const ::ps::SArray<int> &lookup_ids,
  280. C *lookup_result, int64_t cmd, const Callback &cb) {
  281. MS_EXCEPTION_IF_NULL(lookup_result);
  282. int64_t 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. if (lookup_ids.empty()) {
  288. MS_LOG(EXCEPTION) << "Lookup id is empty.";
  289. }
  290. int64_t single_id_len = SizeToLong(lookup_result->size() / lookup_ids.size());
  291. std::unordered_map<Key, std::shared_ptr<std::pair<T *, int64_t>>> id_addr_map;
  292. for (const auto &s : kvs) {
  293. int64_t offset = 0;
  294. for (size_t i = 0; i < s.keys.size(); i++) {
  295. const Key &key = s.keys[i];
  296. T *addr = s.vals.data() + offset;
  297. offset += single_id_len;
  298. id_addr_map[key] = std::make_shared<std::pair<T *, int64_t>>(std::make_pair(addr, single_id_len));
  299. MS_EXCEPTION_IF_NULL(id_addr_map[key]);
  300. }
  301. }
  302. T *result_addr = lookup_result->data();
  303. MS_EXCEPTION_IF_NULL(result_addr);
  304. int64_t offset = 0;
  305. size_t dst_size = 0;
  306. size_t src_size = 0;
  307. void *dst_data = nullptr;
  308. void *src_data = nullptr;
  309. for (size_t i = 0; i < lookup_ids.size(); i++) {
  310. if (id_addr_map.count(lookup_ids[i]) == 0) {
  311. offset += single_id_len;
  312. continue;
  313. }
  314. auto &pair = id_addr_map[static_cast<Key>(lookup_ids[i])];
  315. int64_t size = single_id_len * sizeof(T);
  316. dst_size = size;
  317. src_size = size;
  318. dst_data = result_addr + offset;
  319. src_data = pair->first;
  320. MS_EXCEPTION_IF_NULL(dst_data);
  321. MS_EXCEPTION_IF_NULL(src_data);
  322. auto ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  323. if (ret != 0) {
  324. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  325. return;
  326. }
  327. offset += single_id_len;
  328. }
  329. mutex_.lock();
  330. lookup_results_.erase(ts);
  331. mutex_.unlock();
  332. if (cb) cb();
  333. };
  334. lookup_callbacks_[ts] = callback;
  335. return ts;
  336. }
  337. template <typename T>
  338. int64_t WorkerProxy<T>::AddGeneralRspCB(const ::ps::SArray<::ps::Key> &keys, ::ps::SArray<T> *vals,
  339. ::ps::SArray<int> *lens, int64_t cmd, const Callback &cb) {
  340. int64_t ts = general_customer_->NewRequest(::ps::kServerGroup);
  341. const auto &callback = [this, ts, keys, vals, lens, cb]() mutable {
  342. mutex_.lock();
  343. std::map<int64_t, ::ps::KVPairs<T>> server_kvs = gathered_response_[ts];
  344. mutex_.unlock();
  345. vals->clear();
  346. for (auto kvs : server_kvs) {
  347. for (auto val : kvs.second.vals) {
  348. vals->push_back(val);
  349. }
  350. if (lens) {
  351. for (auto len : kvs.second.lens) {
  352. lens->push_back(len);
  353. }
  354. }
  355. }
  356. mutex_.lock();
  357. gathered_response_.erase(ts);
  358. mutex_.unlock();
  359. if (cb) {
  360. cb();
  361. }
  362. };
  363. general_callbacks_[ts] = callback;
  364. return ts;
  365. }
  366. template <typename T>
  367. void WorkerProxy<T>::LookupIdSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  368. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  369. const std::map<int64_t, int64_t> &attrs) {
  370. MS_EXCEPTION_IF_NULL(sliced);
  371. int32_t *lookup_ids = send.lens.data();
  372. size_t id_size = send.lens.size();
  373. const Key &key = send.keys[0];
  374. const std::vector<::ps::Range> &ranges = *(embedding_table_ranges_[key]);
  375. sliced->resize(ranges.size());
  376. for (size_t i = 0; i < ranges.size(); i++) {
  377. const ::ps::Range &range = ranges[i];
  378. const auto &begin = range.begin();
  379. const auto &end = range.end();
  380. std::unordered_set<int64_t> unique_ids;
  381. auto &kvs = sliced->at(i).second;
  382. kvs.keys.push_back(key);
  383. kvs.vals.push_back(0.0f);
  384. for (size_t j = 0; j < id_size; j++) {
  385. auto lookup_id = static_cast<uint64_t>(lookup_ids[j]);
  386. // If lookup_id is out of range, like negative number, unique_ids will not contain it.
  387. // Servers always get lookup_ids in its embedding table range.
  388. if (lookup_id >= begin && lookup_id <= end) {
  389. unique_ids.insert(lookup_id);
  390. }
  391. }
  392. for (const auto &lookup_id : unique_ids) {
  393. kvs.keys.push_back(lookup_id);
  394. kvs.vals.push_back(0.0f);
  395. }
  396. if (kvs.keys.size() <= 1) {
  397. sliced->at(i).first = false;
  398. } else {
  399. sliced->at(i).first = true;
  400. expected_result_count_[timestamp] += 1;
  401. }
  402. }
  403. }
  404. template <typename T>
  405. void WorkerProxy<T>::SparseSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  406. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  407. const std::map<int64_t, int64_t> &attrs) {
  408. MS_EXCEPTION_IF_NULL(sliced);
  409. // Init variables
  410. T *data = send.vals.data();
  411. if (attrs.count(0) == 0 || attrs.count(1) == 0 || attrs.count(2) == 0 || attrs.count(3) == 0) {
  412. MS_LOG(EXCEPTION) << "Invalid attrs keys";
  413. }
  414. auto iter = attrs.find(0);
  415. size_t grad_index = static_cast<size_t>(iter->second);
  416. iter = attrs.find(1);
  417. size_t indice_index = static_cast<size_t>(iter->second);
  418. iter = attrs.find(2);
  419. size_t first_dim_size = static_cast<size_t>(iter->second);
  420. iter = attrs.find(3);
  421. size_t outer_dim_size = static_cast<size_t>(iter->second);
  422. int grad_size = send.lens[grad_index];
  423. int indice_size = send.lens[indice_index];
  424. int segment_size = grad_size / indice_size;
  425. int64_t grad_offset = 0;
  426. int64_t indice_offset = 0;
  427. for (size_t i = 0; i < grad_index; i++) {
  428. grad_offset += send.lens[i];
  429. }
  430. for (size_t j = 0; j < indice_index; j++) {
  431. indice_offset += send.lens[j];
  432. }
  433. T *grad_data = data + grad_offset;
  434. int *indice_data = reinterpret_cast<int *>(data) + indice_offset;
  435. // Build the mappings of indice to gradient
  436. std::vector<std::pair<int, T *>> indice_to_grads;
  437. for (int i = 0; i < indice_size; i++) {
  438. int indice = indice_data[i];
  439. T *grad = grad_data + i * segment_size;
  440. indice_to_grads.push_back(std::make_pair(indice, grad));
  441. }
  442. const Key &key = send.keys[0];
  443. const std::vector<::ps::Range> &ranges = *(embedding_table_ranges_[key]);
  444. sliced->resize(ranges.size());
  445. // Construct reduced sparse data for each server
  446. for (size_t i = 0; i < ranges.size(); i++) {
  447. const ::ps::Range &range = ranges[i];
  448. const auto &begin = range.begin();
  449. const auto &end = range.end();
  450. auto &kvs = sliced->at(i).second;
  451. kvs.keys = send.keys;
  452. kvs.lens = send.lens;
  453. // Prepare the sparse gradient and indice
  454. std::vector<int> indice_ids;
  455. std::unordered_set<int> distinct_ids;
  456. for (int j = 0; j < indice_size; j++) {
  457. size_t indice = static_cast<size_t>(indice_data[j]);
  458. if (indice >= begin && indice <= end) {
  459. indice_ids.push_back(indice);
  460. distinct_ids.insert(indice);
  461. }
  462. }
  463. size_t indices_size = indice_ids.size();
  464. if (indices_size > 0) {
  465. int slice_segment_size = indices_size * segment_size;
  466. std::vector<T> src_grad_data(slice_segment_size);
  467. std::vector<int> src_indice_data(indices_size);
  468. PrepareSparseGradient(begin, end, distinct_ids, indice_to_grads, indice_data, segment_size, src_grad_data.data(),
  469. src_indice_data.data());
  470. // Reduce the sparse gradient and indice
  471. std::vector<T> new_grad(slice_segment_size);
  472. std::vector<int> new_indices(indices_size);
  473. mindspore::kernel::SparseGradient<int> unique_sparse_grad({new_grad.data(), new_indices.data(), indices_size});
  474. Util::ReduceSparseGradient(src_grad_data.data(), src_indice_data.data(), indices_size, segment_size,
  475. first_dim_size, outer_dim_size, &unique_sparse_grad);
  476. // Update the length of reduce sparse gradient and indice
  477. ::ps::SArray<int> reduced_lens;
  478. reduced_lens.CopyFrom(kvs.lens);
  479. reduced_lens[grad_index] = unique_sparse_grad.indices_size_ * segment_size;
  480. reduced_lens[indice_index] = unique_sparse_grad.indices_size_;
  481. // Build the sparse value to be sent
  482. size_t total_size = std::accumulate(reduced_lens.begin(), reduced_lens.end(), 0, std::plus<int>());
  483. ::ps::SArray<T> reduced_data(total_size, 0);
  484. BuildSparseValue(reduced_lens, grad_index, indice_index, data, unique_sparse_grad.value_,
  485. unique_sparse_grad.indices_, &reduced_data);
  486. kvs.lens = reduced_lens;
  487. kvs.vals = reduced_data;
  488. }
  489. if (indices_size <= 0) {
  490. ::ps::SArray<T> no_keys;
  491. ::ps::SArray<T> no_vals;
  492. ::ps::SArray<T> no_lens;
  493. no_keys.push_back(key);
  494. no_vals.push_back(-100);
  495. kvs.vals = no_vals;
  496. kvs.lens = no_lens;
  497. }
  498. sliced->at(i).first = true;
  499. expected_result_count_[timestamp] += 1;
  500. }
  501. }
  502. template <typename T>
  503. void WorkerProxy<T>::PrepareSparseGradient(const size_t begin, const size_t end,
  504. const std::unordered_set<int> &distinct_ids,
  505. const std::vector<std::pair<int, T *>> &indice_to_grads,
  506. const int *all_indice, const size_t segment_size, T *gradient,
  507. int *indices) {
  508. MS_EXCEPTION_IF_NULL(all_indice);
  509. MS_EXCEPTION_IF_NULL(gradient);
  510. MS_EXCEPTION_IF_NULL(indices);
  511. int64_t offset = 0;
  512. int64_t index = 0;
  513. size_t segment_data_size = segment_size * sizeof(T);
  514. size_t dst_size;
  515. size_t src_size;
  516. void *dst_data = nullptr;
  517. void *src_data = nullptr;
  518. for (auto &pair : indice_to_grads) {
  519. if (distinct_ids.count(pair.first) == 0) {
  520. continue;
  521. }
  522. indices[index++] = pair.first;
  523. dst_size = segment_data_size;
  524. src_size = segment_data_size;
  525. dst_data = gradient + offset;
  526. src_data = pair.second;
  527. MS_EXCEPTION_IF_NULL(dst_data);
  528. MS_EXCEPTION_IF_NULL(src_data);
  529. auto ret = memcpy_s(gradient + offset, dst_size, pair.second, src_size);
  530. if (ret != 0) {
  531. MS_LOG(ERROR) << "memcpy_s error, errorno(" << ret << ")";
  532. return;
  533. }
  534. offset += segment_size;
  535. }
  536. }
  537. template <typename T>
  538. void WorkerProxy<T>::BuildSparseValue(const ::ps::SArray<int> &lengths, const size_t grad_index,
  539. const size_t indice_index, const T *original_data, const T *grads, int *indices,
  540. ::ps::SArray<T> *reduced_data) {
  541. MS_EXCEPTION_IF_NULL(original_data);
  542. MS_EXCEPTION_IF_NULL(grads);
  543. MS_EXCEPTION_IF_NULL(indices);
  544. MS_EXCEPTION_IF_NULL(reduced_data);
  545. int64_t offset = 0;
  546. size_t dst_size = 0;
  547. size_t src_size = 0;
  548. void *dst_data = nullptr;
  549. void *src_data = nullptr;
  550. for (size_t i = 0; i < lengths.size(); i++) {
  551. if (i != grad_index && i != indice_index) {
  552. int data_size = lengths[i] * sizeof(T);
  553. dst_size = data_size;
  554. src_size = data_size;
  555. dst_data = reduced_data->data() + offset;
  556. src_data = const_cast<T *>(original_data) + offset;
  557. MS_EXCEPTION_IF_NULL(dst_data);
  558. MS_EXCEPTION_IF_NULL(src_data);
  559. auto ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  560. if (ret != 0) {
  561. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  562. return;
  563. }
  564. }
  565. offset += lengths[i];
  566. }
  567. // Fill the reduced gradient
  568. int64_t grad_offset = 0;
  569. for (size_t i = 0; i < grad_index; i++) {
  570. grad_offset += lengths[i];
  571. }
  572. int64_t data_size = lengths[grad_index] * sizeof(T);
  573. dst_size = data_size;
  574. src_size = data_size;
  575. dst_data = reduced_data->data() + grad_offset;
  576. src_data = const_cast<T *>(grads);
  577. MS_EXCEPTION_IF_NULL(dst_data);
  578. MS_EXCEPTION_IF_NULL(src_data);
  579. auto ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  580. if (ret != 0) {
  581. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  582. return;
  583. }
  584. // Fill the reduced indice
  585. int64_t indice_offset = grad_offset + lengths[grad_index];
  586. data_size = lengths[indice_index] * sizeof(T);
  587. T *indice_data = reduced_data->data() + indice_offset;
  588. dst_size = data_size;
  589. src_size = data_size;
  590. dst_data = indice_data;
  591. src_data = indices;
  592. MS_EXCEPTION_IF_NULL(dst_data);
  593. MS_EXCEPTION_IF_NULL(src_data);
  594. ret = memcpy_s(dst_data, dst_size, src_data, src_size);
  595. if (ret != 0) {
  596. MS_LOG(EXCEPTION) << "memcpy_s error, errorno(" << ret << ")";
  597. return;
  598. }
  599. }
  600. template <typename T>
  601. void WorkerProxy<T>::BroadcastSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  602. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  603. const std::map<int64_t, int64_t> &attr) {
  604. MS_EXCEPTION_IF_NULL(sliced);
  605. sliced->resize(server_num_);
  606. for (int64_t i = 0; i < server_num_; i++) {
  607. sliced->at(i).first = true;
  608. sliced->at(i).second = send;
  609. expected_result_count_[timestamp] += 1;
  610. }
  611. }
  612. template <typename T>
  613. void WorkerProxy<T>::RoundRobinSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send, const std::vector<::ps::Range> &,
  614. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  615. const std::map<int64_t, int64_t> &attr) {
  616. MS_EXCEPTION_IF_NULL(sliced);
  617. sliced->resize(server_num_);
  618. auto keys = send.keys;
  619. auto vals = send.vals;
  620. auto lens = send.lens;
  621. int64_t server_id, len;
  622. ::ps::Key param_key;
  623. for (size_t i = 0; i < keys.size(); i++) {
  624. param_key = keys[i];
  625. server_id = key_to_server_id_[param_key];
  626. if (!sliced->at(server_id).first) {
  627. sliced->at(server_id).first = true;
  628. expected_result_count_[timestamp] += 1;
  629. }
  630. ::ps::KVPairs<T> &server_kv_pairs = sliced->at(server_id).second;
  631. server_kv_pairs.keys.push_back(param_key);
  632. if (vals.empty()) {
  633. continue;
  634. }
  635. len = lens[i];
  636. int64_t offset = std::accumulate(lens.begin(), lens.begin() + i, 0);
  637. auto val_begin = vals.begin() + offset;
  638. auto val_end = val_begin + len;
  639. for (auto iter = val_begin; iter != val_end; iter++) {
  640. server_kv_pairs.vals.push_back(*iter);
  641. }
  642. server_kv_pairs.lens.push_back(len);
  643. }
  644. }
  645. template <typename T>
  646. void WorkerProxy<T>::WorkerInitEmbeddingSlicer(int64_t timestamp, const ::ps::KVPairs<T> &send,
  647. const std::vector<::ps::Range> &,
  648. std::vector<std::pair<bool, ::ps::KVPairs<T>>> *sliced,
  649. const std::map<int64_t, int64_t> &attrs) {
  650. MS_EXCEPTION_IF_NULL(sliced);
  651. sliced->resize(server_num_);
  652. auto keys = send.keys;
  653. auto vals = send.vals;
  654. auto lens = send.lens;
  655. size_t col_cnt = lens[0] / embedding_row_cnt_[keys[0]];
  656. const std::vector<::ps::Range> &ranges = *(embedding_table_ranges_[keys[0]]);
  657. for (size_t i = 0; i < ranges.size(); i++) {
  658. size_t offset_begin = ranges[i].begin() * col_cnt;
  659. size_t offset_end = (ranges[i].end() + 1) * col_cnt;
  660. ::ps::KVPairs<T> kvs;
  661. kvs.keys = keys;
  662. kvs.vals = vals.segment(offset_begin, offset_end);
  663. kvs.lens.push_back(offset_end - offset_begin);
  664. sliced->at(i).first = true;
  665. sliced->at(i).second = kvs;
  666. }
  667. }
  668. template <typename T>
  669. void WorkerProxy<T>::ProcessLookupResult(const ::ps::Message &msg) {
  670. int64_t ts = msg.meta.timestamp;
  671. if (msg.meta.pull) {
  672. CHECK_GE(msg.data.size(), (size_t)2);
  673. ::ps::KVPairs<T> kvs;
  674. kvs.keys = msg.data[0];
  675. kvs.vals = msg.data[1];
  676. if (msg.data.size() > (size_t)2) {
  677. kvs.lens = msg.data[2];
  678. }
  679. mutex_.lock();
  680. lookup_results_[ts].push_back(kvs);
  681. mutex_.unlock();
  682. }
  683. if (lookup_customer_->NumResponse(ts) + 1 == server_num_) {
  684. const auto &cb = lookup_callbacks_[ts];
  685. cb();
  686. lookup_callbacks_.erase(ts);
  687. }
  688. }
  689. template <typename T>
  690. void WorkerProxy<T>::ProcessResponse(const ::ps::Message &msg) {
  691. int64_t ts = msg.meta.timestamp;
  692. if (msg.meta.pull) {
  693. CHECK_GE(msg.data.size(), (size_t)2);
  694. ::ps::KVPairs<T> kvs;
  695. kvs.keys = msg.data[0];
  696. kvs.vals = msg.data[1];
  697. if (msg.data.size() > (size_t)2) {
  698. kvs.lens = msg.data[2];
  699. }
  700. mutex_.lock();
  701. int rsp_server_rank = ::ps::Postoffice::Get()->IDtoRank(msg.meta.sender);
  702. gathered_response_[ts][rsp_server_rank] = kvs;
  703. mutex_.unlock();
  704. if (general_customer_->NumResponse(ts) + 1 == server_num_) {
  705. const auto &cb = general_callbacks_[ts];
  706. cb();
  707. general_callbacks_.erase(ts);
  708. }
  709. }
  710. }
  711. template <typename T>
  712. void WorkerProxy<T>::Send(::ps::Customer *customer, int64_t timestamp, bool push, bool pull, int64_t cmd,
  713. const ::ps::KVPairs<T> &kvs, const Slicer &slicer, std::map<int64_t, int64_t> attrs) {
  714. MS_EXCEPTION_IF_NULL(customer);
  715. SlicedKVs sliced;
  716. slicer(timestamp, kvs, ::ps::Postoffice::Get()->GetServerKeyRanges(), &sliced, attrs);
  717. for (size_t i = 0; i < sliced.size(); i++) {
  718. const auto &s = sliced[i];
  719. if (!s.first) continue;
  720. ::ps::Message msg;
  721. msg.meta.app_id = customer->app_id();
  722. msg.meta.customer_id = customer->customer_id();
  723. msg.meta.request = true;
  724. msg.meta.push = push;
  725. msg.meta.pull = pull;
  726. msg.meta.head = cmd;
  727. msg.meta.timestamp = timestamp;
  728. msg.meta.recver = ::ps::Postoffice::Get()->ServerRankToID(i);
  729. msg.meta.priority = kvs.priority;
  730. const auto &kvs = s.second;
  731. if (kvs.keys.size()) {
  732. msg.AddData(kvs.keys);
  733. msg.AddData(kvs.vals);
  734. if (kvs.lens.size()) {
  735. msg.AddData(kvs.lens);
  736. }
  737. }
  738. ::ps::Postoffice::Get()->van()->Send(msg);
  739. }
  740. }
  741. } // namespace ps
  742. } // namespace mindspore
  743. #endif // MINDSPORE_CCSRC_PS_WORKER_PROXY_H_