MADNESS 0.10.1
cloud.h
Go to the documentation of this file.
1
2/**
3 \file cloud.h
4 \brief Declares the \c Cloud class for storing data and transfering them between worlds
5 \ingroup world
6
7*/
8
9/**
10 * TODO: - delete container record upon caching if container is replicated
11 */
12
13#ifndef SRC_MADNESS_WORLD_CLOUD_H_
14#define SRC_MADNESS_WORLD_CLOUD_H_
15
16
18#include<algorithm>
19#include<any>
20#include<atomic>
21#include<iomanip>
22#include<limits>
23#include<list>
24#include<mutex>
25
26
27/*!
28 \file cloud.h
29 \brief Defines and implements most of madness cloud storage
30
31 TODO: check use of preprocessor directives
32 TODO: clear cache in destructor won't work because no subworld is present -> must be explicitly called, error prone/
33*/
34
35namespace madness {
36
37 /// \brief A utility to get the name of a type as a string from chatGPT
38 template<typename T>
39 struct type_name {
40 static const char* value() { return typeid(T).name();}
41 };
42
43 template<>
44 struct type_name<Function<double,1>> { static const char* value() { return "Function<double,1>"; } };
45 template<>
46 struct type_name<Function<double,2>> { static const char* value() { return "Function<double,2>"; } };
47 template<>
48 struct type_name<Function<double,3>> { static const char* value() { return "Function<double,3>"; } };
49 template<>
50 struct type_name<Function<double,4>> { static const char* value() { return "Function<double,4>"; } };
51 template<>
52 struct type_name<Function<double,5>> { static const char* value() { return "Function<double,5>"; } };
53 template<>
54 struct type_name<Function<double,6>> { static const char* value() { return "Function<double,6>"; } };
55
56 template<>
57 struct type_name<std::vector<Function<double,1>>> { static const char* value() { return "std::vector<Function<double,1>>"; } };
58 template<>
59 struct type_name<std::vector<Function<double,2>>> { static const char* value() { return "std::vector<Function<double,2>>"; } };
60 template<>
61 struct type_name<std::vector<Function<double,3>>> { static const char* value() { return "std::vector<Function<double,3>>"; } };
62 template<>
63 struct type_name<std::vector<Function<double,4>>> { static const char* value() { return "std::vector<Function<double,4>>"; } };
64 template<>
65 struct type_name<std::vector<Function<double,5>>> { static const char* value() { return "std::vector<Function<double,5>>"; } };
66 template<>
67 struct type_name<std::vector<Function<double,6>>> { static const char* value() { return "std::vector<Function<double,6>>"; } };
68
69template<typename keyT>
70struct Recordlist {
71 std::list<keyT> list;
72
73 Recordlist() : list() {};
74
75 explicit Recordlist(const keyT &key) : list{key} {};
76
77 Recordlist(const Recordlist &other) : list(other.list) {};
78
80 for (auto &l2 : list2.list) list.push_back(l2);
81 return *this;
82 }
83
84 Recordlist &operator+=(const keyT &key) {
85 list.push_back(key);
86 return *this;
87 }
88
90 keyT key = list.front();
91 list.pop_front();
92 return key;
93 }
94
95 std::size_t size() const {
96 return list.size();
97 }
98
99 // if type provides id() member function (i.e. WorldObject) use that for hashing, otherwise use hash_value() for
100 // fundamental types (see worldhash.h)
101 template <typename T>
102 using member_id_t = decltype(std::declval<T>().id());
103
104 template <typename T>
106
107 // if type provides a hashing function use that, intrusive hashing, see worldhash.h
108 template <typename T>
109 using member_hash_t = decltype(std::declval<T>().hash());
110
111 template <typename T>
113
114 template<typename T, std::size_t NDIM>
115 static keyT compute_record(const Function<T,NDIM>& arg) {return hash_value(arg.get_impl()->id());}
116
117 template<typename T, std::size_t NDIM>
119
120 template<typename keyQ, typename valueT>
122
123 template<typename keyQ, typename valueT>
124 static keyT compute_record(const std::shared_ptr<WorldContainer<keyQ,valueT>>& arg) {return hash_value(arg->id());}
125
126 template<typename T, std::size_t NDIM>
127 static keyT compute_record(const std::shared_ptr<madness::FunctionImpl<T, NDIM>>& arg) {return hash_value(arg->id());}
128
129 template<typename T>
130 static keyT compute_record(const std::vector<T>& arg) {return hash_range(arg.begin(), arg.end());}
131
132 template<typename T>
133 static keyT compute_record(const Tensor<T>& arg) {return hash_value(arg.normf());}
134
135 template<typename T>
136 static keyT compute_record(const std::shared_ptr<T>& arg) {return compute_record(*arg);}
137
138 template<typename T>
139 static keyT compute_record(const T& arg) {
140 if constexpr (has_member_id<T>::value) {
141 return hash_value(arg.id());
142 } else if constexpr (std::is_pointer_v<T> && has_member_id<std::remove_pointer_t<T>>::value) {
143 return hash_value(arg->id());
144 } else {
145 // compute hash_code for fundamental types
146 std::size_t hashtype = typeid(T).hash_code();
148 return hashtype;
149 }
150 }
151
152
153 friend std::ostream &operator<<(std::ostream &os, const Recordlist &arg) {
154 using namespace madness::operators;
155 os << arg.list;
156 return os;
157 }
158
159};
160
161/// Process map for the cloud's batch container
162
163/// Routes a record to an explicitly assigned owner, falling back to a hash for any
164/// record that was never registered. `set_owner` is collective, so all ranks agree on
165/// routing without further communication. Unlike the default cloud container this map
166/// is never reset to local, which is what keeps owner pinning stable.
167template <typename keyT, typename hashfunT = Hash<keyT>>
169private:
170 const int nproc;
172 std::shared_ptr<std::map<keyT, ProcessID>> table;
173
174public:
175 CloudOwnerPmap(World& world, const hashfunT& hf = hashfunT())
176 : nproc(world.mpi.nproc()), hashfun(hf), table(new std::map<keyT, ProcessID>()) {}
177
178 /// collective: every rank must register the same (key, owner) pair
179 void set_owner(const keyT& key, const ProcessID owner) { (*table)[key] = owner; }
180
181 ProcessID owner(const keyT& key) const override {
182 auto it = table->find(key);
183 if (it != table->end()) return it->second;
184 if (nproc == 1) return 0;
185 return hashfun(key) % nproc;
186 }
187
188 void print_table(const std::string& tag = "") const {
189 print("CloudOwnerPmap::table", tag, "size=", table->size(), "(nproc=", nproc, ")");
190 for (const auto& kv : *table) {
191 std::ostringstream os;
192 os << " key=0x" << std::hex << kv.first << std::dec << " owner=" << kv.second;
193 print(os.str());
194 }
195 }
196};
197
198/// BatchTransport holds a back-reference to its Cloud; its bodies are defined below the class
199class Cloud;
200
202/// the serialized batch travels by value through a Future, so it must be
203/// archive-serializable: a plain vector is, a shared_ptr is not
204using batch_bytesT = std::vector<unsigned char>;
205
206/// Point-to-point transfer of serialized function batches between universe ranks
207
208/// The bytes stream straight from the owner's local batch store to the requester by
209/// MPI point-to-point; they never ride inside an active-message payload, so there is
210/// no eager-buffer limit and no extra copy on the wire.
211///
212/// Both endpoints are posted from **comm-thread AM handlers** (`WorldObject::send` runs
213/// the member inline on the RMI receiver thread), never from worker tasks. That is what
214/// buys overlap under worker saturation: at a tight protocol every worker sits in the
215/// exchange kernel for a long time, so an endpoint posted as a *task* would queue behind
216/// it and the MPI op would not be posted until compute ended. On the comm thread the RMI
217/// loop's Testsome drives the rendezvous to completion during compute instead, leaving
218/// only the final await for the worker.
219///
220/// Wire protocol:
221/// 1. requester (worker): record a pending slot keyed by `tag`, send `on_trigger`
222/// 2. owner `on_trigger` (comm thread): Isend the local bytes, reply `on_reply` with the size
223/// 3. requester `on_reply` (comm thread): size the buffer, post the Irecv, enqueue `finish_recv`
224/// 4. requester `finish_recv` (worker): await the Irecv and set the future
225///
226/// The size travels in the reply of step 2 rather than a separate Isend so that step 3 can
227/// post the payload Irecv *during* compute; posting it at consume time would move the data
228/// transfer to post-compute and lose the overlap.
229class BatchTransport : public WorldObject<BatchTransport> {
230public:
231 /// tags live in the range MADNESS does not manage (safempi.h); 32767 is the
232 /// conservative MPI_TAG_UB floor
233 static constexpr int BATCH_TAG_BASE = 8192;
234 static constexpr int BATCH_TAG_CAP = 32767;
235
236 /// reply size meaning "the owner does not hold this record"; see on_trigger
237 static constexpr std::size_t BATCH_NOT_FOUND = ~std::size_t(0);
238
239 /// bytes per MPI message in a batch transfer; a larger payload is split into several
240
241 /// MPI byte counts are `int`, and batches do exceed 2 GiB: a 161-orbital run at k=10
242 /// measured 3.03 GiB, whose count narrowed to a negative int. MPI rejects that and
243 /// SafeMPI throws it on the comm thread, where nothing catches it.
244 static std::size_t batch_chunk_bytes() { return batch_chunk_bytes_; }
245
246 /// Set the chunk size, for tests only.
247
248 /// Collective and not thread-safe: call it on every rank before any transfer. It exists so
249 /// a unit test can reach the multi-chunk path with an affordable payload.
250 static void set_batch_chunk_bytes(const std::size_t n) {
251 MADNESS_CHECK_THROW(n > 0 and n <= std::size_t(std::numeric_limits<int>::max()),
252 "batch chunk size must be positive and fit an MPI count");
254 }
255
256 /// @param[in] universe the world the cloud lives in (collective construction)
257 /// @param[in] cloud back-reference used to read owner-local batch bytes
258 BatchTransport(World& universe, Cloud* cloud)
259 : WorldObject<BatchTransport>(universe), cloud_(cloud), next_tag_(0) {
260 this->process_pending();
261 }
262
263 /// Future to the serialized bytes of `record`, fetched from its owner
264
265 /// Resolves locally without MPI when this rank owns the record. The trigger is in
266 /// flight on return, so the round trip overlaps work until the future is consumed.
268
269private:
270 Cloud* cloud_; ///< back-reference (not owned)
271 std::atomic<int> next_tag_;
272
273 /// requester-side state for one outstanding receive. Held by shared_ptr so the buffer
274 /// address is stable for the Irecv and the entry can leave pending_ while finish_recv
275 /// still owns its reference.
276 struct PendingRecv {
278 int tag = -1;
279 bool not_found = false; ///< owner reported it does not hold the record
280 batch_bytesT buf; ///< sized in on_reply
281 std::vector<SafeMPI::Request> reqs; ///< one per chunk, posted in on_reply
282 Future<batch_bytesT> fut; ///< set by finish_recv
283 };
284 std::mutex pending_mtx_;
285 std::map<int, std::shared_ptr<PendingRecv>> pending_;
286
287 /// owner-side in-flight Isends, reaped lazily. Their buffers live in the cloud's
288 /// batch container and stay valid for the duration, so an un-reaped Isend is harmless.
289 std::mutex sends_mtx_;
290 std::list<SafeMPI::Request> sends_;
291
292 int alloc_tag() {
293 const int span = BATCH_TAG_CAP - BATCH_TAG_BASE + 1;
294 const int t = next_tag_.fetch_add(1);
295 return BATCH_TAG_BASE + ((t % span) + span) % span;
296 }
297
298 static inline std::size_t batch_chunk_bytes_ = std::size_t(1) << 30; ///< 1 GiB
299
300 void reap_sends();
301
302 /// owner side, comm thread: Isend the record's bytes, then reply with the count.
303 /// Must not throw: an exception here escapes every task-level handler.
305
306 /// requester side, comm thread: size the buffer, post the Irecvs, enqueue finish_recv
307
308 /// \param chunk the chunking the *owner* used, echoed back so the receiver never has to
309 /// infer it. See on_trigger.
310 void on_reply(int tag, std::size_t size, std::size_t chunk);
311
312 /// requester side, worker task: await the background-progressed Irecv and set the future
313 void finish_recv(int tag);
314};
315
316/// cloud class
317
318/// store and load data to/from the cloud into arbitrary worlds
319///
320/// Distributed data is always bound to a certain world. If it needs to be
321/// present in another world it can be serialized to the cloud and deserialized
322/// from there again. For an example see test_cloud.cc
323///
324/// Data is stored into a distributed container living in the universe.
325/// During storing a (replicated) list of records is returned that can be used to find the data
326/// in the container. If a combined object (a vector, tuple, etc) is stored a list of records
327/// will be generated. When loading the data from the world the record list will be used to
328/// deserialize all stored objects.
329///
330/// Note that there must be a fence after the destruction of subworld containers, as in:
331///
332/// create subworlds
333/// {
334/// dcT(subworld)
335/// do work
336/// }
337/// subworld.gop.fence();
338class Cloud {
339
340 bool debug = false; ///< prints debug output
341 bool is_replicated=false; ///< if contents of the container are replicated
342 bool dofence = true; ///< fences after load/store
343 bool force_load_from_cache = false; ///< forces load from cache (mainly for debugging)
344 bool use_cache=true;
345
346public:
347
348 typedef std::any cached_objT;
350 using valueT = std::vector<unsigned char>;
351 typedef std::map<keyT, cached_objT> cacheT;
353
355 StoreFunction, ///< store a madness function in the cloud -- can have a large memory impact
356 ///< equivalent to a deep copy
357 StoreFunctionPointer, ///< store the pointer to the function in the cloud.
358 ///< Return type still is a Function<T,NDIM> with a pointer to the universe function impl.
359 ///< equivalent to a shallow copy
360 };
361
362
363 friend std::ostream& operator<<(std::ostream& os, const StoragePolicy& sp) {
364 switch(sp) {
365 case StoreFunction: os << "Function"; break;
366 case StoreFunctionPointer: os << "FunctionPointer"; break;
367 default: os << "UnknownStoragePolicy"; break;
368 }
369 return os;
370 }
371
372 friend std::string to_string(const StoragePolicy sp) {
373 std::ostringstream os;
374 os << sp;
375 return os.str();
376 }
377
378private:
379 /// are the functions (WorldObjects) stored in the cloud or only pointers to them
381
382 /// cloud is a container: replication policy for the cloud container: distributed, node-replicated, rank-replicated
384
386 /// dedicated container for owner-pinned function batches; see store_batch / fetch_batch_p2p.
387 /// Uses CloudOwnerPmap so each batch record lives on an explicitly chosen rank.
388 std::shared_ptr<CloudOwnerPmap<keyT>> batch_pmap;
390 /// constructed after batch_container so it is destroyed first, as WorldObject lifetimes require
391 std::unique_ptr<BatchTransport> batch_transport_;
393 recordlistT local_list_of_container_keys; // a world-local list of keys occupied in container
394
395public:
396 std::list<WorldObjectBase*> world_object_base_list; // list of world objects stored in the cloud
397
398 template <typename T>
399 using member_cloud_serialize_t = decltype(std::declval<T>().cloud_store(std::declval<World&>(), std::declval<Cloud&>()));
400
401 template <typename T>
403
404public:
405
406 /// @param[in] universe the universe world
407 Cloud(madness::World &universe) : container(universe),
408 batch_pmap(new CloudOwnerPmap<keyT>(universe)),
409 batch_container(universe, batch_pmap),
411 reading_time(0l), copy_time(0l), writing_time(0l),
412 cache_reads(0l), cache_stores(0l) {
413 }
414
416 if ((not cached_objects.empty()) or (not local_list_of_container_keys.list.empty())) {
417 print("\nCloud::~Cloud(): cached_objects not empty, size=", cached_objects.size());
418 print("You need to call clear_cache(subworld) before destroying the cloud");
419 print("\n------------------------------\n");
420 std::string msg="deferred destruction of cloud with non-empty cache";
421 std::cerr << msg << std::endl;
422 }
423 }
424
425 void set_debug(bool value) {
426 debug = value;
427 }
428
429 /// dump the record->owner table on rank 0; pair with the caller's own task-to-rank
430 /// print to check that task assignment and batch routing agree
431 void print_batch_owner_map(World& universe, const std::string& tag = "") const {
432 if (universe.rank() != 0) return;
433 batch_pmap->print_table(tag);
434 }
435
436 void set_fence(bool value) {
437 dofence = value;
438 }
439
440 void set_force_load_from_cache(bool value) {
441 force_load_from_cache = value;
442 }
443
444 /// is the cloud container replicated: per rank, per node, or distributed
447 use_cache=false;
448 if (value == RankReplicated) use_cache=true;
449 }
450
451 /// is the cloud container replicated: per rank, per node, or distributed
455
459 std::cout << "Cloud::validate_distribution(): distribution type mismatch, container is " << disttype
460 << " but cloud_replication_policy is " << cloud_replication_policy << std::endl;
461 return false;
462 }
463 return true;
464 }
465
466
467 /// storing policy refers to storing functions or pointers to functions
469 storage_policy = value;
470 }
471
472 /// storing policy refers to storing functions or pointers to functions
476
477 void print_size(World& universe) {
478 nlohmann::json stats=gather_memory_statistics(universe);
479 double byte2gbyte=1.0/(1024*1024*1024);
480 double global_memsize=stats["memory_global_GB"].template get<double>();
481 double max_record_size=stats["max_record_size"].template get<double>();
482 double min_memsize=stats["memory_min_GB"].template get<double>();
483 double max_memsize=stats["memory_max_GB"].template get<double>();
484 double global_size=stats["container_size_global"].template get<double>();
485
486 if (universe.rank()==0) {
487 print("Cloud memory:");
488 print(" replicated:",is_replicated);
489 print("size of cloud (total)");
490 print(" number of records: ",global_size);
491 print(" memory in GBytes: ",global_memsize);
492 print("size of cloud (average per node)");
493 print(" number of records: ",double(global_size)/universe.size());
494 print(" memory in GBytes: ",global_memsize/universe.size());
495 print("min/max of node");
496 print(" memory in GBytes: ",min_memsize,max_memsize);
497 print(" max record size in GBytes:",max_record_size*byte2gbyte);
498
499 }
500 }
501
502 /// return a json object with the cloud settings and statistics
503 nlohmann::json get_statistics(World& world) const {
504 nlohmann::json j;
505 { // settings
506 j["storage_policy"]=to_string(storage_policy);
507 j["cloud_replication_policy"]=to_string(cloud_replication_policy);
508 j["is_replicated"]=is_replicated;
509 j["local_cached_objects_size"]=cached_objects.size();
510 }
511 // timings
512 j.update(gather_timings(world));
513 j.update(gather_memory_statistics(world));
514 return j;
515
516 }
517
518 /// get size of the cloud container
519 nlohmann::json gather_memory_statistics(World &universe) const {
520
521 std::size_t memsize=0;
522 std::size_t max_record_size=0;
523 for (auto& item : container) {
524 memsize+=item.second.size();
525 max_record_size=std::max(max_record_size,item.second.size());
526 }
527 // batch records are held separately, and for a caller that stores batches they are
528 // the larger half; leaving them out would understate the cloud's footprint
529 std::size_t batch_memsize=0;
530 for (auto& item : batch_container) {
531 batch_memsize+=item.second.size();
532 max_record_size=std::max(max_record_size,item.second.size());
533 }
535 std::size_t global_memsize=memsize;
536 std::size_t max_memsize=memsize;
537 std::size_t min_memsize=memsize;
539 double rss_av=rss;
540 universe.gop.sum(global_memsize);
541 universe.gop.max(max_memsize);
542 universe.gop.max(max_record_size);
543 universe.gop.min(min_memsize);
544 universe.gop.max(rss);
545 universe.gop.sum(rss_av);
546 double byte2gbyte=1.0/(1024*1024*1024);
547
548 // convert type(container item).second to GB, i.e. number of bytes in the container to GB
549 double uchar2gbyte=byte2gbyte*sizeof(unsigned char);
550
551
552 auto local_size=container.size();
553 auto global_size=local_size;
554 universe.gop.sum(global_size);
556 universe.gop.sum(batch_global_size);
558 universe.gop.sum(batch_global_memsize);
559 nlohmann::json j;
560 j["container_size_global"] = global_size;
561 j["batch_container_size_global"] = batch_global_size;
562 j["batch_memory_global_GB"] = batch_global_memsize*uchar2gbyte;
563 j["memory_global_GB"] = global_memsize*uchar2gbyte;
564 j["memory_min_GB"] = min_memsize*uchar2gbyte;
565 j["memory_max_GB"] = max_memsize*uchar2gbyte;
566 j["memory_rss_GB_max"] = rss;
567 j["memory_rss_GB_av"] = rss_av/universe.size();
568 j["max_record_size"] = max_record_size;
569 return j;
570 }
571
572 nlohmann::json gather_timings(World &universe) const {
573 double rtime_max = double(reading_time)*1.e-6;
574 double rtime_acc = double(reading_time)*1.e-6;
575 double rtime_av = double(reading_time)*1.e-6;
576 double ctime_max = double(copy_time)*1.e-6;
577 double ctime_acc = double(copy_time)*1.e-6;
578 double ctime_av = double(copy_time)*1.e-6;
579 double wtime = double(writing_time)*1.e-6;
580 double ptime = double(replication_time)*1.e-6;
581 double tptime = double(target_replication_time)*1.e-6;
582 universe.gop.max(rtime_max);
583 universe.gop.sum(rtime_acc);
584 rtime_av = rtime_acc/universe.size();
585 universe.gop.max(ctime_max);
586 universe.gop.sum(ctime_acc);
587 ctime_av = ctime_acc/universe.size();
588 universe.gop.max(wtime);
589 universe.gop.max(ptime);
590 universe.gop.max(tptime);
591 long creads = long(cache_reads);
592 long cstores = long(cache_stores);
593 universe.gop.sum(creads);
594 universe.gop.sum(cstores);
595 nlohmann::json j;
596 j["reading_time_max_s"] = rtime_max;
597 j["reading_time_acc_s"] = rtime_acc;
598 j["reading_time_av_s"] = rtime_av;
599 j["copy_time_max_s"] = ctime_max;
600 j["copy_time_acc_s"] = ctime_acc;
601 j["copy_time_av_s"] = ctime_av;
602 j["writing_time_s"] = wtime;
603 j["replication_time_s"] = ptime;
604 j["target_replication_time_s"] = tptime;
605 j["cache_reads"] = creads;
606 j["cache_stores"] = cstores;
607 return j;
608 }
609
610 /// backwards compatibility
611 void print_timings(World& universe) const {
612 print_timings(gather_timings(universe));
613 }
614
615 static void print_timings(const nlohmann::json timings) {
616 double rtime_max=timings["reading_time_max_s"].template get<double>();
617 double rtime_av=timings["reading_time_av_s"].template get<double>();
618 double rtime_acc=timings["reading_time_acc_s"].template get<double>();
619 // double ctime_max=timings["copy_time_max_s"].template get<double>();
620 // double ctime_av=timings["copy_time_av_s"].template get<double>();
621 // double ctime_acc=timings["copy_time_acc_s"].template get<double>();
622 double wtime=timings["writing_time_s"].template get<double>();
623 double ptime=timings["replication_time_s"].template get<double>();
624 double tptime=timings["target_replication_time_s"].template get<double>();
625 long creads=timings["cache_reads"].template get<long>();
626 long cstores=timings["cache_stores"].template get<long>();
627
628 auto precision = std::cout.precision();
629 std::cout << std::fixed << std::setprecision(1);
630 print("cloud storing wall time ", wtime);
631 print("cloud replication wall time ", ptime);
632 print("target replication wall time ", tptime);
633 print("cloud max reading time (all procs) ", rtime_max, std::defaultfloat);
634 print("cloud average reading cpu time (all procs) ", rtime_av, std::defaultfloat);
635 print("cloud accumulated reading cpu time (all procs) ", rtime_acc, std::defaultfloat);
636 std::cout << std::setprecision(precision) << std::scientific;
637 print("cloud cache stores ", long(cstores));
638 print("cloud cache loads ", long(creads));
639 }
640
641 static void print_memory_statistics(const nlohmann::json stats) {
642 double byte2gbyte=1.0/(1024*1024*1024);
643 double global_memsize=stats["memory_global_GB"].template get<double>();
644 double max_record_size=stats["max_record_size"].template get<double>();
645 double min_memsize=stats["memory_min_GB"].template get<double>();
646 double max_memsize=stats["memory_max_GB"].template get<double>();
647 double global_size=stats["container_size_global"].template get<double>();
648
649 print("Cloud memory:");
650 print(" size of cloud (total)");
651 print(" number of records: ",global_size);
652 print(" memory in GBytes: ",global_memsize);
653 // print(" size of cloud (average per node)");
654 // print(" number of records: ",double(global_size)/madness::world().size());
655 // print(" memory in GBytes: ",global_memsize*byte2gbyte/madness::world().size());
656 print(" min/max of node");
657 print(" memory in GBytes: ",min_memsize,max_memsize);
658 print(" max record size in GBytes:",max_record_size*byte2gbyte);
659 // the owner-pinned batches, reported separately because they are a different lifetime and
660 // usually the bulk of it. Zero unless some task stored batches.
661 const double b_size = stats.value("batch_container_size_global", 0.0);
662 if (b_size > 0.0) {
663 print(" owner-pinned batches");
664 print(" number of records: ", b_size);
665 print(" memory in GBytes: ", stats.value("batch_memory_global_GB", 0.0));
666 }
667 }
668
669 void clear_cache(World &subworld) {
670 cached_objects.clear();
672 subworld.gop.fence();
673 }
674
675 void clear() {
676 container.clear();
677 // The owner-pinned batches too. They are not leaked without this -- an SCF run derives the
678 // same record keys each time, so the next application overwrites them -- but they are the
679 // largest thing the cloud holds, and without this they stay resident through everything
680 // that follows the exchange in an iteration, which is where the memory ceiling actually is.
681 batch_container.clear();
682 }
683
685 reading_time=0l;
686 copy_time=0l;
687 writing_time=0l;
688 writing_time1=0l;
691 cache_stores=0l;
692 cache_reads=0l;
693 }
694
695 /// functor to distribute/rank/node-replicate a function, passed in as a pointer to WorldObjectBase
696 template<typename T, std::size_t NDIM>
701 // figure out if wo is a FunctionImpl and do the distribution
702 if (auto fimpl=dynamic_cast<FunctionImpl<T, NDIM>*>(wo)) {
703 // fimpl->get_pmap()->print_data_sizes(world,"before distribution of function in cloud");
704 if (dt==RankReplicated) {
705 fimpl->replicate(false);
706 } else if (dt==NodeReplicated) {
707 // print("replicating function per node",fimpl);;
708 fimpl->replicate_on_hosts(true);
709 } else if (dt==Distributed) {
710 fimpl->undo_replicate(false);
711 } else {
712 MADNESS_EXCEPTION("unknown distribution type",1);
713 }
714 // fimpl->get_pmap()->print_data_sizes(world,"after distribution of function in cloud");
715 }
716 return 0;
717 }
718 };
719
720 /// distribute/node/rank replicate the targets of all world objects stored in the cloud
722 if (world_object_base_list.empty()) return;
723 World& world=world_object_base_list.front()->get_world();
724
725 for (auto wo : world_object_base_list) {
727 // world.gop.fence();
728 }
729 world.gop.fence();
730
731 }
732
733 /// @param[in] world the subworld the objects are loaded to
734 /// @param[in] recordlist the list of records where the objects are stored
735
736 /// load a single object from the cloud, recordlist is kept unchanged
737 template<typename T>
738 T load(madness::World &world, const recordlistT recordlist) const {
739 recordlistT rlist = recordlist;
740 cloudtimer t(world, reading_time);
741
742 // forward_load will consume the recordlist while loading elements
743 return forward_load<T>(world, rlist);
744 }
745
746 /// similar to load, but will consume the recordlist
747
748 /// @param[in] world the subworld the objects are loaded to
749 /// @param[in] recordlist the list of records where the objects are stored
750 template<typename T>
752 cloudtimer t(world, reading_time);
753
754 // forward_load will consume the recordlist while loading elements
755 return forward_load<T>(world, recordlist);
756 }
757
758 /// load a single object from the cloud, recordlist is consumed while loading elements
759 template<typename T>
761 // different objects are stored in different ways
762 // - tuples are split up into their components
763 // - classes with their own cloud serialization are stored using that
764 // - everything else is stored using their usual serialization
765 if constexpr (is_tuple<T>::value) {
766 return load_tuple<T>(world, recordlist);
767 } else if constexpr (has_cloud_serialize<T>::value) {
768 T target = allocator<T>(world);
769 target.cloud_load(world, *this, recordlist);
770 return target;
771 } else {
772 return do_load<T>(world, recordlist);
773 }
774 }
775
776 /// Register the owner of a batch record; local map insert, no communication
777
778 /// Collective in the same sense as store_batch: every rank must call it with an
779 /// identical (record, owner) pair or fetches will route inconsistently. Separating
780 /// registration from the payload lets all ranks replicate the routing while each
781 /// owner stores only its own bytes, over a size-1 subworld.
782 void register_batch_owner(const keyT record, const ProcessID owner) {
783 batch_pmap->set_owner(record, owner);
784 }
785
786 /// Store a batch of functions as one owner-pinned record
787
788 /// The whole vector -- its size and each function -- is serialized into a single
789 /// record in the batch container and routed to `owner`, so one batch is one record
790 /// with one owner. Must be called with identical (owner, record) on every rank of
791 /// `world`.
792 ///
793 /// @param[in] fence false lets a caller storing many batches emit one fence for all
794 /// of them; the collective gather inside the archive self-synchronizes
795 template<typename T, std::size_t NDIM>
796 keyT store_batch(madness::World& world, const std::vector<Function<T, NDIM>>& batch,
797 const ProcessID owner, const keyT record, const bool fence = true) {
798 if (is_replicated) {
799 print("Cloud contents are replicated and read-only!");
800 MADNESS_EXCEPTION("cloud error", 1);
801 }
802 batch_pmap->set_owner(record, owner);
804 {
807 par.set_dofence(false);
808 std::size_t fsize = batch.size();
809 par & fsize;
810 for (std::size_t i = 0; i < fsize; ++i) par & batch[i];
811 }
812 if (dofence and fence) world.gop.fence();
813 return record;
814 }
815
816 /// @param[in] world presumably the universe
817 template<typename T>
819 if (is_replicated) {
820 print("Cloud contents are replicated and read-only!");
821 MADNESS_EXCEPTION("cloud error",1);
822 }
823 cloudtimer t(world,writing_time);
824
825 // different objects are stored in different ways
826 // - tuples are split up into their components
827 // - classes with their own cloud serialization are stored using that
828 // - everything else is stored using their usual serialization
830 if constexpr (is_tuple<T>::value) {
832 } else if constexpr (has_cloud_serialize<T>::value) {
833 recordlist+=source.cloud_store(world,*this);
834 } else {
836 }
837 if (dofence) world.gop.fence();
838 return recordlist;
839 }
840
843 // if (debug and (container.size() > 0)) print("no replication of container");
844 return;
845 }
848 }
851 }
852 else {
853 MADNESS_EXCEPTION("unknown replication policy",1);
854 }
855 container.get_world().gop.fence();
856 }
857
858 void replicate_per_node(const std::size_t chunk_size=INT_MAX) {
859 // this will fail if the container values are larger that 2GB
860 // need to reimplement that at some point
861 try {
862 double cpu0=cpu_time();
863 World& world=container.get_world();
864 world.gop.fence();
866 MADNESS_CHECK_THROW(not is_replicated,"cloud::replicate_per_node: container is already replicated");
867 container.replicate_on_hosts(true);
868 is_replicated=true;
869 world.gop.fence();
870 double cpu1=cpu_time();
871 if (debug and (world.rank()==0)) print("replication_per_node ended after ",cpu1-cpu0," seconds");
872 } catch (...) {
873 MADNESS_EXCEPTION("cloud replication_per_node failed, presumably because some data is larger than 2GB",1);
874 }
875 }
876
877 // replicates the contents of the container
878 void replicate(const std::size_t chunk_size=INT_MAX) {
879 MADNESS_CHECK_THROW(not is_replicated,"cloud::replicate_per_node: container is already replicated");
880
881 double cpu0=cpu_time();
882 World& world=container.get_world();
883 world.gop.fence();
885 container.reset_pmap_to_local();
886 is_replicated=true;
887
888 std::list<keyT> keylist;
889 for (auto it=container.begin(); it!=container.end(); ++it) {
890 keylist.push_back(it->first);
891 }
892
893 for (ProcessID rank=0; rank<world.size(); rank++) {
894 if (rank == world.rank()) {
895 std::size_t keylistsize = keylist.size();
896 world.mpi.Bcast(&keylistsize,sizeof(keylistsize),MPI_BYTE,rank);
897
898 for (auto key : keylist) {
900 bool found=container.find(acc,key);
902 auto data = acc->second;
903 std::size_t sz=data.size();
904
905 world.mpi.Bcast(&key,sizeof(key),MPI_BYTE,rank);
906 world.mpi.Bcast(&sz,sizeof(sz),MPI_BYTE,rank);
907
908 // if data is too large for MPI_INT break it into pieces to avoid integer overflow
909 for (std::size_t start=0; start<sz; start+=chunk_size) {
910 std::size_t remainder = std::min(sz - start, chunk_size);
911 world.mpi.Bcast(&data[start], remainder, MPI_BYTE, rank);
912 }
913
914 }
915 }
916 else {
917 std::size_t keylistsize = 0;
918 world.mpi.Bcast(&keylistsize,sizeof(keylistsize),MPI_BYTE,rank);
919 for (size_t i=0; i<keylistsize; i++) {
920 keyT key;
921 world.mpi.Bcast(&key,sizeof(key),MPI_BYTE,rank);
922 std::size_t sz = 0;
923 world.mpi.Bcast(&sz,sizeof(sz),MPI_BYTE,rank);
924 valueT data(sz);
925// world.mpi.Bcast(&data[0],sz,MPI_BYTE,rank);
926 for (std::size_t start=0; start<sz; start+=chunk_size) {
927 std::size_t remainder=std::min(sz-start,chunk_size);
928 world.mpi.Bcast(&data[start],remainder,MPI_BYTE,rank);
929 }
930
931 container.replace(key,data);
932 }
933 }
934 }
935 world.gop.fence();
936 double cpu1=cpu_time();
937 if (debug and (world.rank()==0)) print("replication ended after ",cpu1-cpu0," seconds");
938 }
939
940private:
941
942 mutable std::atomic<long> reading_time=0l; // in microseconds
943 mutable std::atomic<long> batch_store_time=0l; ///< store_batch wall time, microseconds
944 mutable std::atomic<long> batch_find_time=0l; ///< waiting on the p2p transfer, microseconds
945 mutable std::atomic<long> batch_deserialize_time=0l; ///< deserializing the bytes, microseconds
946public:
947 mutable std::atomic<long> copy_time=0l; // if pointers are stored in cloud, time to copy from universe to subworld
948 mutable std::atomic<long> target_replication_time=0l; // if pointers are stored in cloud, time to replicate targets
949private:
950 mutable std::atomic<long> writing_time=0l; // in microseconds
951 mutable std::atomic<long> writing_time1=0l; // in microseconds
952 mutable std::atomic<long> replication_time=0l; // in microseconds
953 mutable std::atomic<long> cache_reads=0l;
954 mutable std::atomic<long> cache_stores=0l;
955
956 template<typename> struct is_tuple : std::false_type { };
957 template<typename ...T> struct is_tuple<std::tuple<T...>> : std::true_type { };
958
959 template<typename Q> struct is_vector : std::false_type { };
960 template<typename Q> struct is_vector<std::vector<Q>> : std::true_type { };
961
962 template<typename T> using is_parallel_serializable_object = std::is_base_of<archive::ParallelSerializableObject,T>;
963
964 template<typename T> using is_world_constructible = std::is_constructible<T, World &>;
965
966public:
967 struct cloudtimer {
969 double wall0;
970 std::atomic<long> &rtime;
971
973
975 long deltatime=long((wall_time() - wall0) * 1000000l);
976 rtime += deltatime;
977 }
978 };
979private:
980
981 template<typename T>
982 void cache(madness::World &world, const T &obj, const keyT &record) const {
983 const_cast<cacheT &>(cached_objects).insert({record,std::make_any<T>(obj)});
984 }
985
986 /// load an object from the cache, record is unchanged
987 template<typename T>
988 T load_from_cache(madness::World &world, const keyT &record) const {
989 if (world.rank()==0) cache_reads++;
990 if (debug) print("loading", type_name<T>::value(), "from cache record", record, "to world", world.id());
991 if (auto obj = std::any_cast<T>(&cached_objects.find(record)->second)) return *obj;
992 MADNESS_EXCEPTION("failed to load from cloud-cache", 1);
993 T target = allocator<T>(world);
994 return target;
995 }
996
997 bool is_cached(const keyT &key) const {
998 return (cached_objects.count(key) == 1);
999 }
1000
1001public:
1002
1003 /// the owner of a batch record; a pmap lookup, no communication
1005 return batch_pmap->owner(record);
1006 }
1007
1008private:
1009
1010 /// only the transport reads owner-local bytes; callers go through fetch_batch_p2p
1011 friend class BatchTransport;
1012
1013 /// bytes of a batch record held by this rank, empty if it holds none
1014
1015 /// Never throws: the callers are BatchTransport's comm-thread handlers, where an
1016 /// escaping exception bypasses every task-level handler and surfaces as an
1017 /// unattributable abort. A miss is reported to the requester instead, and raised
1018 /// there in task context.
1019 ///
1020 /// Emptiness is a sound "not found" marker because a stored batch always begins with
1021 /// its serialized element count, so a present record is never zero bytes.
1024 if (batch_container.find(acc, record)) return acc->second;
1025 return valueT();
1026 }
1027
1028 /// stable pointer and size of a local batch record, {nullptr,0} if this rank holds none
1029
1030 /// Lets the comm thread Isend without copying the payload. The accessor lock is
1031 /// released on return, but the address stays valid because batch records are neither
1032 /// erased nor mutated between the store and the end of the consuming operation.
1033 /// Never throws, for the reason given on try_get_local_batch_bytes.
1034 std::pair<const unsigned char*, std::size_t> try_get_local_batch_ptr(const keyT record) const {
1036 if (batch_container.find(acc, record))
1037 return {acc->second.data(), acc->second.size()};
1038 return {nullptr, 0};
1039 }
1040
1041public:
1042
1043 /// start fetching `record` from its owner; the trigger is in flight on return
1047
1048 /// turn the bytes of a p2p transfer into the batch of functions
1049
1050 /// Blocks on `fut` only if the transfer has not landed yet. Runs in a task, which is
1051 /// where a missing record is reported so the failure is attributable.
1052 /// @param[in] cache_result default false: the cloud-side cache is not safe to keep
1053 /// across changes of the calling world, so opting in is the
1054 /// caller's decision
1055 template<typename T, std::size_t NDIM>
1056 std::vector<Function<T, NDIM>> deserialize_batch_p2p(madness::World& subworld,
1057 Future<batch_bytesT> fut, const keyT record,
1058 const bool cache_result = false) const {
1059 typedef std::vector<Function<T, NDIM>> vecfuncT;
1060 if (is_cached(record)) return load_from_cache<vecfuncT>(subworld, record);
1061 cloudtimer t(subworld, reading_time);
1062 const double w0 = wall_time();
1063 batch_bytesT bytes = fut.get();
1064 const double w1 = wall_time();
1065 batch_find_time += long((w1 - w0) * 1.e6);
1066 MADNESS_CHECK_THROW(not bytes.empty(),
1067 "deserialize_batch_p2p: the owner does not hold this batch record");
1068 vecfuncT batch;
1069 {
1072 std::size_t fsize = 0;
1073 par & fsize;
1074 batch.resize(fsize);
1075 for (std::size_t i = 0; i < fsize; ++i) par & batch[i];
1076 }
1077 batch_deserialize_time += long((wall_time() - w1) * 1.e6);
1078 if (use_cache and cache_result) cache(subworld, batch, record);
1079 return batch;
1080 }
1081
1082 /// fetch a batch stored by store_batch; resolves without MPI when this rank owns it
1083 template<typename T, std::size_t NDIM>
1084 std::vector<Function<T, NDIM>> fetch_batch_p2p(madness::World& subworld,
1085 const keyT record, const bool cache_result = false) const {
1086 typedef std::vector<Function<T, NDIM>> vecfuncT;
1087 if (is_cached(record)) return load_from_cache<vecfuncT>(subworld, record);
1090 }
1091
1092private:
1093
1094 /// checks if a (universe) container record is used
1095
1096 /// currently implemented with a local copy of the recordlist, might be
1097 /// reimplemented with container.find(), which would include blocking communication.
1098 bool is_in_container(const keyT &key) const {
1099 auto it = std::find(local_list_of_container_keys.list.begin(),
1101 return it!=local_list_of_container_keys.list.end();
1102 }
1103
1104 template<typename T>
1105 T allocator(World &world) const {
1106 if constexpr (is_world_constructible<T>::value) {
1107 return T(world);
1108 } else {
1109 return T();
1110 }
1111 }
1112
1113 template<typename T>
1117 if (debug and world.rank()==0) {
1118 if (is_already_present) std::cout << "skipping ";
1119 if constexpr (Recordlist<keyT>::has_member_id<T>::value) {
1120 std::cout << "storing world object of " << type_name<T>::value() << "id " << source.id()
1121 << " to record " << record << std::endl;
1122 }
1123 std::cout << "storing object of " << type_name<T>::value() << " to record " << record << std::endl;
1124 }
1125 if constexpr (is_madness_function<T>::value) {
1126 if (source.is_compressed() and T::dimT>3) print("WARNING: storing compressed hi-dim `function");
1127 }
1128
1129 // scope is important because of destruction ordering of world objects and fence
1130 if (is_already_present) {
1131 if (world.rank()==0) cache_stores++;
1132 } else {
1133 cloudtimer t(world,writing_time1);
1137 if constexpr (is_madness_function<T>::value) {
1138 // store the pointer to the function, not the function itself
1139 par & source.get_impl();
1140 // store the pointer to the WorldObject in a list for later reference (replication/redistribution)
1141 WorldObjectBase* wobj=source.get_impl().get();
1142 world_object_base_list.push_back(wobj);
1143 } else {
1144 // store everything else
1145 par & source;
1146 }
1147 } else {
1148 // store everything else
1149 par & source;
1150 }
1152 }
1153 if (dofence) world.gop.fence();
1154 return recordlistT{record};
1155 }
1156
1157public:
1158 /// load a vector from the cloud, pop records from recordlist
1159 ///
1160 /// @param[inout] world destination world
1161 /// @param[inout] recordlist list of records to load from (reduced by the first few elements)
1162 template<typename T>
1163 typename std::enable_if<is_vector<T>::value, T>::type
1165 std::size_t sz = do_load<std::size_t>(world, recordlist);
1166 T target(sz);
1167 for (std::size_t i = 0; i < sz; ++i) {
1169 }
1170 return target;
1171 }
1172
1173 /// load a single object from the cloud, pop record from recordlist
1174 ///
1175 /// @param[inout] world destination world
1176 /// @param[inout] recordlist list of records to load from (reduced by the first element)
1177 template<typename T>
1178 typename std::enable_if<!is_vector<T>::value, T>::type
1180 keyT record = recordlist.pop_front_and_return();
1182
1183 if (is_cached(record)) return load_from_cache<T>(world, record);
1184 if (debug) print("loading", type_name<T>::value(), "from container record", record, "to world", world.id());
1185 T target = allocator<T>(world);
1188 if constexpr (is_madness_function<T>::value) {
1190 // load the pointer to the function, not the function itself
1191 // this is important for large functions, as they are not replicated
1192 // and only copied to subworlds when needed
1193 try {
1195 std::shared_ptr<implT> impl;
1196 par & impl;
1197 target.set_impl(impl); // target now points to a universe function impl
1198 } catch (...) {
1199 {
1201 print("failed to load function pointer from cloud, maybe the target is out of scope?");
1202 print("record:", record, "world:", world.id());
1203 print("function type:", type_name<T>::value());
1204 print("\n");
1205 }
1206 MADNESS_EXCEPTION("load/store error of pointers in cloud", 1);
1207 }
1208 } else {
1209 // load everything else
1210 par & target;
1211 }
1212 } else {
1213 // load everything else
1214 par & target;
1215 }
1216
1217 if (use_cache) {
1218 cache(world, target, record);
1219 if (is_replicated) container.erase(record);
1220 }
1221
1222 return target;
1223 }
1224
1225public:
1226
1227 // overloaded
1228 template<typename T>
1229 recordlistT store_other(madness::World& world, const std::vector<T>& source) {
1230 if (debug and world.rank()==0)
1231 std::cout << "storing vector of " << type_name<T>::value() << " of size " << source.size() << std::endl;
1232 recordlistT l = store_other(world, source.size());
1233 for (const auto& s : source) l += store_other(world, s);
1234 if (dofence) world.gop.fence();
1235 if (debug and world.rank()==0) std::cout << "done with vector storing; container size "
1236 << container.size() << std::endl;
1237 return l;
1238 }
1239
1240 /// store a tuple in multiple records
1241 template<typename... Ts>
1242 recordlistT store_tuple(World &world, const std::tuple<Ts...> &input) {
1243 recordlistT v;
1244 auto storeaway = [&](const auto &arg) {
1245 v += this->store(world, arg);
1246 };
1247 auto l = [&](Ts const &... arg) {
1248 ((storeaway(arg)), ...);
1249 };
1250 std::apply(l, input);
1251 return v;
1252 }
1253
1254 /// load a tuple from the cloud, pop records from recordlist
1255 ///
1256 /// @param[inout] world destination world
1257 /// @param[inout] recordlist list of records to load from (reduced by the first few elements)
1258 template<typename T>
1260 if (debug) std::cout << "loading tuple of type " << typeid(T).name() << " to world " << world.id() << std::endl;
1261 T target;
1262 std::apply([&](auto &&... args) {
1263 ((args = forward_load<typename std::remove_reference<decltype(args)>::type>(world, recordlist)), ...);
1264 }, target);
1265 return target;
1266 }
1267};
1268
1269// ---- BatchTransport bodies; they need the complete Cloud ----
1270
1272 World& u = this->get_world();
1273 const ProcessID owner = cloud_->batch_owner(record);
1274 if (owner == u.rank()) {
1275 // local: no MPI. An absent record yields empty bytes, which the consumer
1276 // reports in task context, exactly as for the remote path.
1278 }
1279 const int tag = alloc_tag();
1280 auto p = std::make_shared<PendingRecv>();
1281 p->owner = owner;
1282 p->tag = tag;
1283 {
1284 std::lock_guard<std::mutex> g(pending_mtx_);
1285 pending_[tag] = p;
1286 }
1287 // send, not add: the trigger runs inline on the owner's comm thread, so the owner
1288 // posts its Isend without queueing behind its own saturated workers
1289 this->send(owner, &BatchTransport::on_trigger, record, u.rank(), tag);
1290 return p->fut;
1291}
1292
1294 std::lock_guard<std::mutex> g(sends_mtx_);
1295 for (auto it = sends_.begin(); it != sends_.end(); ) {
1296 if (it->Test()) it = sends_.erase(it);
1297 else ++it;
1298 }
1299}
1300
1302 World& u = this->get_world();
1303 reap_sends();
1304 auto ptr_size = cloud_->try_get_local_batch_ptr(record);
1305 if (ptr_size.first == nullptr) {
1306 // Not held here -- reply with the sentinel and post nothing. Throwing instead
1307 // would escape this comm-thread handler past every task-level handler and abort
1308 // the run with no attribution; the requester raises it in task context.
1309 this->send(requester, &BatchTransport::on_reply, tag, BATCH_NOT_FOUND, std::size_t(0));
1310 return;
1311 }
1312 const std::size_t n = ptr_size.second;
1313 // Sent along rather than read again by the requester: the size is a process-local static, so
1314 // the two ends can disagree, and a receiver that guessed would post Irecvs that do not match
1315 // the messages -- MPI_ERR_TRUNCATE on the comm thread, where nothing catches it.
1316 const std::size_t chunk = batch_chunk_bytes_;
1317 // MPI does not overtake between messages sharing source, tag and communicator, so posting
1318 // the chunks in ascending offset order matches the requester's Irecvs pairwise without a
1319 // per-chunk tag. That does rely on one transfer per tag, which alloc_tag's span makes true.
1320 {
1321 std::lock_guard<std::mutex> g(sends_mtx_);
1322 for (std::size_t off = 0; off < n; off += chunk) {
1323 const std::size_t len = std::min(chunk, n - off);
1324 sends_.push_back(u.mpi.Isend(ptr_size.first + off, int(len), MPI_BYTE, requester, tag));
1325 }
1326 }
1327 // the size rides in the reply so the requester can post its Irecvs now, during its
1328 // own compute, and let the rendezvous finish in the background
1329 this->send(requester, &BatchTransport::on_reply, tag, n, chunk);
1330}
1331
1332inline void BatchTransport::on_reply(int tag, std::size_t size, std::size_t chunk) {
1333 World& u = this->get_world();
1334 std::shared_ptr<PendingRecv> p;
1335 {
1336 std::lock_guard<std::mutex> g(pending_mtx_);
1337 auto it = pending_.find(tag);
1338 MADNESS_CHECK(it != pending_.end());
1339 p = it->second;
1340 }
1341 if (size == BATCH_NOT_FOUND) {
1342 // no Isend was posted, so post no Irecv; empty bytes mark the miss
1343 {
1344 std::lock_guard<std::mutex> g(pending_mtx_);
1345 pending_.erase(tag);
1346 }
1347 p->not_found = true;
1348 p->fut.set(batch_bytesT());
1349 return;
1350 }
1351 p->buf.resize(size);
1352 // the owner's framing, not ours; see on_trigger. Positive whenever the record was found, and
1353 // unguarded because a throw on this thread is what the framing exists to avoid
1354 for (std::size_t off = 0; off < size; off += chunk) {
1355 const std::size_t len = std::min(chunk, size - off);
1356 p->reqs.push_back(u.mpi.Irecv(p->buf.data() + off, int(len), MPI_BYTE, p->owner, tag));
1357 }
1358 u.taskq.add(this, &BatchTransport::finish_recv, tag);
1359}
1360
1361inline void BatchTransport::finish_recv(int tag) {
1362 std::shared_ptr<PendingRecv> p;
1363 {
1364 std::lock_guard<std::mutex> g(pending_mtx_);
1365 auto it = pending_.find(tag);
1366 MADNESS_CHECK(it != pending_.end());
1367 p = it->second;
1368 pending_.erase(it);
1369 }
1370 // the comm thread has been progressing these Irecvs all along, so the awaits are short
1371 for (auto& r : p->reqs) World::await(r, true);
1372 p->fut.set(std::move(p->buf));
1373}
1374
1375} /* namespace madness */
1376
1377#endif /* SRC_MADNESS_WORLD_CLOUD_H_ */
Point-to-point transfer of serialized function batches between universe ranks.
Definition cloud.h:229
static void set_batch_chunk_bytes(const std::size_t n)
Set the chunk size, for tests only.
Definition cloud.h:250
void on_trigger(batch_keyT record, ProcessID requester, int tag)
Definition cloud.h:1301
static std::size_t batch_chunk_bytes_
1 GiB
Definition cloud.h:298
BatchTransport(World &universe, Cloud *cloud)
Definition cloud.h:258
Cloud * cloud_
back-reference (not owned)
Definition cloud.h:270
std::map< int, std::shared_ptr< PendingRecv > > pending_
Definition cloud.h:285
std::mutex sends_mtx_
Definition cloud.h:289
static constexpr int BATCH_TAG_CAP
Definition cloud.h:234
int alloc_tag()
Definition cloud.h:292
void finish_recv(int tag)
requester side, worker task: await the background-progressed Irecv and set the future
Definition cloud.h:1361
static constexpr std::size_t BATCH_NOT_FOUND
reply size meaning "the owner does not hold this record"; see on_trigger
Definition cloud.h:237
std::mutex pending_mtx_
Definition cloud.h:284
void reap_sends()
Definition cloud.h:1293
std::atomic< int > next_tag_
Definition cloud.h:271
void on_reply(int tag, std::size_t size, std::size_t chunk)
requester side, comm thread: size the buffer, post the Irecvs, enqueue finish_recv
Definition cloud.h:1332
static std::size_t batch_chunk_bytes()
bytes per MPI message in a batch transfer; a larger payload is split into several
Definition cloud.h:244
Future< batch_bytesT > request(batch_keyT record)
Future to the serialized bytes of record, fetched from its owner.
Definition cloud.h:1271
std::list< SafeMPI::Request > sends_
Definition cloud.h:290
static constexpr int BATCH_TAG_BASE
Definition cloud.h:233
Process map for the cloud's batch container.
Definition cloud.h:168
CloudOwnerPmap(World &world, const hashfunT &hf=hashfunT())
Definition cloud.h:175
ProcessID owner(const keyT &key) const override
Maps key to processor.
Definition cloud.h:181
void print_table(const std::string &tag="") const
Definition cloud.h:188
void set_owner(const keyT &key, const ProcessID owner)
collective: every rank must register the same (key, owner) pair
Definition cloud.h:179
hashfunT hashfun
Definition cloud.h:171
std::shared_ptr< std::map< keyT, ProcessID > > table
Definition cloud.h:172
const int nproc
Definition cloud.h:170
cloud class
Definition cloud.h:338
bool is_cached(const keyT &key) const
Definition cloud.h:997
void print_batch_owner_map(World &universe, const std::string &tag="") const
Definition cloud.h:431
Future< batch_bytesT > request_batch_bytes_async(const keyT record) const
start fetching record from its owner; the trigger is in flight on return
Definition cloud.h:1044
bool use_cache
Definition cloud.h:344
void clear()
Definition cloud.h:675
void replicate_per_node(const std::size_t chunk_size=INT_MAX)
Definition cloud.h:858
bool is_in_container(const keyT &key) const
checks if a (universe) container record is used
Definition cloud.h:1098
bool force_load_from_cache
forces load from cache (mainly for debugging)
Definition cloud.h:343
bool debug
prints debug output
Definition cloud.h:340
std::atomic< long > writing_time1
Definition cloud.h:951
nlohmann::json get_statistics(World &world) const
return a json object with the cloud settings and statistics
Definition cloud.h:503
std::enable_if< is_vector< T >::value, T >::type do_load(World &world, recordlistT &recordlist) const
Definition cloud.h:1164
std::atomic< long > batch_find_time
waiting on the p2p transfer, microseconds
Definition cloud.h:944
recordlistT store_other(madness::World &world, const std::vector< T > &source)
Definition cloud.h:1229
std::any cached_objT
Definition cloud.h:348
recordlistT store(madness::World &world, const T &source)
Definition cloud.h:818
T load_tuple(madness::World &world, recordlistT &recordlist) const
Definition cloud.h:1259
std::is_base_of< archive::ParallelSerializableObject, T > is_parallel_serializable_object
Definition cloud.h:962
~Cloud()
Definition cloud.h:415
madness::archive::ContainerRecordOutputArchive::keyT keyT
Definition cloud.h:349
std::atomic< long > replication_time
Definition cloud.h:952
Recordlist< keyT > recordlistT
Definition cloud.h:352
StoragePolicy storage_policy
are the functions (WorldObjects) stored in the cloud or only pointers to them
Definition cloud.h:380
std::is_constructible< T, World & > is_world_constructible
Definition cloud.h:964
valueT try_get_local_batch_bytes(const keyT record) const
bytes of a batch record held by this rank, empty if it holds none
Definition cloud.h:1022
std::atomic< long > target_replication_time
Definition cloud.h:948
nlohmann::json gather_timings(World &universe) const
Definition cloud.h:572
friend std::string to_string(const StoragePolicy sp)
Definition cloud.h:372
recordlistT store_other(madness::World &world, const T &source)
Definition cloud.h:1114
bool is_replicated
if contents of the container are replicated
Definition cloud.h:341
void set_force_load_from_cache(bool value)
Definition cloud.h:440
decltype(std::declval< T >().cloud_store(std::declval< World & >(), std::declval< Cloud & >())) member_cloud_serialize_t
Definition cloud.h:399
void replicate(const std::size_t chunk_size=INT_MAX)
Definition cloud.h:878
recordlistT local_list_of_container_keys
Definition cloud.h:393
DistributionType cloud_replication_policy
cloud is a container: replication policy for the cloud container: distributed, node-replicated,...
Definition cloud.h:383
void print_size(World &universe)
Definition cloud.h:477
std::unique_ptr< BatchTransport > batch_transport_
constructed after batch_container so it is destroyed first, as WorldObject lifetimes require
Definition cloud.h:391
std::atomic< long > reading_time
Definition cloud.h:942
ProcessID batch_owner(const keyT record) const
the owner of a batch record; a pmap lookup, no communication
Definition cloud.h:1004
void clear_timings()
Definition cloud.h:684
recordlistT store_tuple(World &world, const std::tuple< Ts... > &input)
store a tuple in multiple records
Definition cloud.h:1242
void set_debug(bool value)
Definition cloud.h:425
void register_batch_owner(const keyT record, const ProcessID owner)
Register the owner of a batch record; local map insert, no communication.
Definition cloud.h:782
nlohmann::json gather_memory_statistics(World &universe) const
get size of the cloud container
Definition cloud.h:519
std::enable_if<!is_vector< T >::value, T >::type do_load(World &world, recordlistT &recordlist) const
Definition cloud.h:1179
T load(madness::World &world, const recordlistT recordlist) const
load a single object from the cloud, recordlist is kept unchanged
Definition cloud.h:738
madness::WorldContainer< keyT, valueT > batch_container
Definition cloud.h:389
std::shared_ptr< CloudOwnerPmap< keyT > > batch_pmap
Definition cloud.h:388
void cache(madness::World &world, const T &obj, const keyT &record) const
Definition cloud.h:982
void set_fence(bool value)
Definition cloud.h:436
std::atomic< long > cache_reads
Definition cloud.h:953
std::pair< const unsigned char *, std::size_t > try_get_local_batch_ptr(const keyT record) const
stable pointer and size of a local batch record, {nullptr,0} if this rank holds none
Definition cloud.h:1034
std::vector< Function< T, NDIM > > fetch_batch_p2p(madness::World &subworld, const keyT record, const bool cache_result=false) const
fetch a batch stored by store_batch; resolves without MPI when this rank owns it
Definition cloud.h:1084
friend std::ostream & operator<<(std::ostream &os, const StoragePolicy &sp)
Definition cloud.h:363
static void print_timings(const nlohmann::json timings)
Definition cloud.h:615
std::list< WorldObjectBase * > world_object_base_list
Definition cloud.h:396
static void print_memory_statistics(const nlohmann::json stats)
Definition cloud.h:641
DistributionType get_replication_policy() const
is the cloud container replicated: per rank, per node, or distributed
Definition cloud.h:452
Cloud(madness::World &universe)
Definition cloud.h:407
cacheT cached_objects
Definition cloud.h:392
void clear_cache(World &subworld)
Definition cloud.h:669
keyT store_batch(madness::World &world, const std::vector< Function< T, NDIM > > &batch, const ProcessID owner, const keyT record, const bool fence=true)
Store a batch of functions as one owner-pinned record.
Definition cloud.h:796
std::atomic< long > copy_time
Definition cloud.h:947
StoragePolicy get_storing_policy() const
storing policy refers to storing functions or pointers to functions
Definition cloud.h:473
std::vector< Function< T, NDIM > > deserialize_batch_p2p(madness::World &subworld, Future< batch_bytesT > fut, const keyT record, const bool cache_result=false) const
turn the bytes of a p2p transfer into the batch of functions
Definition cloud.h:1056
std::atomic< long > batch_deserialize_time
deserializing the bytes, microseconds
Definition cloud.h:945
void replicate_according_to_policy(const std::size_t chunk_size=INT_MAX)
Definition cloud.h:841
T load_from_cache(madness::World &world, const keyT &record) const
load an object from the cache, record is unchanged
Definition cloud.h:988
madness::meta::is_detected< member_cloud_serialize_t, T > has_cloud_serialize
Definition cloud.h:402
std::vector< unsigned char > valueT
Definition cloud.h:350
void set_replication_policy(const DistributionType value)
is the cloud container replicated: per rank, per node, or distributed
Definition cloud.h:445
void distribute_targets(const DistributionType dt=Distributed)
distribute/node/rank replicate the targets of all world objects stored in the cloud
Definition cloud.h:721
bool dofence
fences after load/store
Definition cloud.h:342
void print_timings(World &universe) const
backwards compatibility
Definition cloud.h:611
bool validate_replication_policy() const
Definition cloud.h:456
T allocator(World &world) const
Definition cloud.h:1105
std::atomic< long > writing_time
Definition cloud.h:950
void set_storing_policy(const StoragePolicy value)
storing policy refers to storing functions or pointers to functions
Definition cloud.h:468
madness::WorldContainer< keyT, valueT > container
Definition cloud.h:385
T forward_load(madness::World &world, recordlistT &recordlist) const
load a single object from the cloud, recordlist is consumed while loading elements
Definition cloud.h:760
StoragePolicy
Definition cloud.h:354
@ StoreFunctionPointer
Definition cloud.h:357
@ StoreFunction
Definition cloud.h:355
std::map< keyT, cached_objT > cacheT
Definition cloud.h:351
T consuming_load(madness::World &world, recordlistT &recordlist) const
similar to load, but will consume the recordlist
Definition cloud.h:751
std::atomic< long > batch_store_time
store_batch wall time, microseconds
Definition cloud.h:943
std::atomic< long > cache_stores
Definition cloud.h:954
FunctionImpl holds all Function state to facilitate shallow copy semantics.
Definition funcimpl.h:968
A multiresolution adaptive numerical function.
Definition mra.h:144
A future is a possibly yet unevaluated value.
Definition future.h:370
T & get(bool dowork=true) &
Gets the value, waiting if necessary.
Definition future.h:571
Definition worldhashmap.h:330
A tensor is a multidimensional array.
Definition tensor.h:318
Makes a distributed container with specified attributes.
Definition worlddc.h:1127
bool find(accessor &acc, const keyT &key)
Write access to LOCAL value by key. Returns true if found, false otherwise (always false for remote).
Definition worlddc.h:1274
Interface to be provided by any process map.
Definition worlddc.h:122
virtual void print() const
Definition worlddc.h:139
void max(T *buf, size_t nelem)
Inplace global max while still processing AM & tasks.
Definition worldgop.h:902
void fence(bool debug=false)
Synchronizes all processes in communicator AND globally ensures no pending AM or tasks.
Definition worldgop.cc:176
void min(T *buf, size_t nelem)
Inplace global min while still processing AM & tasks.
Definition worldgop.h:896
void sum(T *buf, size_t nelem)
Inplace global sum while still processing AM & tasks.
Definition worldgop.h:890
void Bcast(T *buffer, int count, int root) const
MPI broadcast an array of count elements.
Definition worldmpi.h:416
Implements most parts of a globally addressable object (via unique ID).
Definition world_object.h:491
void process_pending()
To be called from derived constructor to process pending messages.
Definition world_object.h:787
detail::task_result_type< memfnT >::futureT send(ProcessID dest, memfnT memfn) const
Definition world_object.h:858
A parallel world class.
Definition world.h:134
ProcessID rank() const
Returns the process rank in this World (same as MPI_Comm_rank()).
Definition world.h:344
static void await(SafeMPI::Request &request, bool dowork=true)
Wait for a MPI request to complete.
Definition world.h:558
WorldMpiInterface & mpi
MPI interface.
Definition world.h:213
ProcessID size() const
Returns the number of processes in this World (same as MPI_Comm_size()).
Definition world.h:354
unsigned long id() const
Definition world.h:324
WorldGopInterface & gop
Global operations.
Definition world.h:216
Definition parallel_dc_archive.h:60
Definition parallel_dc_archive.h:14
long keyT
Definition parallel_dc_archive.h:16
An archive for storing local or parallel data, wrapping a BinaryFstreamInputArchive.
Definition parallel_archive.h:366
An archive for storing local or parallel data wrapping a BinaryFstreamOutputArchive.
Definition parallel_archive.h:321
Wraps an archive around an STL vector for input.
Definition vector_archive.h:101
char * p(char *buf, const char *name, int k, int initial_level, double thresh, int order)
Definition derivatives.cc:72
Tensor< typename Tensor< T >::scalar_type > arg(const Tensor< T > &t)
Return a new tensor holding the argument of each element of t (complex types only)
Definition tensor.h:2643
static const double v
Definition hatom_sf_dirac.cc:20
static double u(double r, double c)
Definition he.cc:20
#define MADNESS_CHECK(condition)
Check a condition — even in a release build the condition is always evaluated so it can have side eff...
Definition madness_exception.h:182
#define MADNESS_EXCEPTION(msg, value)
Macro for throwing a MADNESS exception.
Definition madness_exception.h:119
#define MADNESS_CHECK_THROW(condition, msg)
Check a condition — even in a release build the condition is always evaluated so it can have side eff...
Definition madness_exception.h:207
typename detail::detector< nonesuch, void, Op, Args... >::value_t is_detected
Definition meta.h:169
Definition array_addons.h:50
Namespace for all elements and tools of MADNESS.
Definition DFParameters.h:10
void hash_range(hashT &seed, It first, It last)
Definition worldhash.h:280
double get_rss_usage_in_GB()
Definition ranks_and_hosts.cpp:10
static double cpu_time()
Returns the cpu time in seconds relative to an arbitrary origin.
Definition timers.h:128
DistributionType
some introspection of how data is distributed
Definition worlddc.h:81
@ NodeReplicated
even if there are several ranks per node
Definition worlddc.h:84
@ Distributed
no replication of the container, the container is distributed over the world
Definition worlddc.h:82
@ RankReplicated
replicate the container over all world ranks
Definition worlddc.h:83
std::vector< unsigned char > batch_bytesT
Definition cloud.h:204
void hash_combine(hashT &seed, const T &v)
Combine hash values.
Definition worldhash.h:260
static class madness::twoscale_cache_class cache[kmax+1]
DistributionType validate_distribution_type(const dcT &dc)
check distribution type of WorldContainer – global communication
Definition worlddc.h:319
void print(const T &t, const Ts &... ts)
Print items to std::cout (items separated by spaces) and terminate with a new line.
Definition print.h:227
NDIM const Function< R, NDIM > & g
Definition mra.h:2622
double wall_time()
Returns the wall time in seconds relative to an arbitrary origin.
Definition timers.cc:48
std::string type(const PairType &n)
Definition PNOParameters.h:18
vector< functionT > vecfuncT
Definition corepotential.cc:58
static bool print_timings
Definition SCF.cc:106
static XNonlinearSolver< std::vector< Function< T, NDIM > >, T, vector_function_allocator< T, NDIM > > nonlinear_vector_solver(World &world, const long nvec)
Definition nonlinsol.h:371
std::string name(const FuncType &type, const int ex=-1)
Definition ccpairfunction.h:28
madness::hashT hash_value(const std::array< T, N > &a)
Hash std::array with madness hash.
Definition array_addons.h:78
madness::archive::ContainerRecordOutputArchive::keyT batch_keyT
Definition cloud.h:201
Definition mraimpl.h:51
Definition test_dc.cc:47
Definition test_ccpairfunction.cc:22
bool not_found
owner reported it does not hold the record
Definition cloud.h:279
ProcessID owner
Definition cloud.h:277
int tag
Definition cloud.h:278
std::vector< SafeMPI::Request > reqs
one per chunk, posted in on_reply
Definition cloud.h:281
Future< batch_bytesT > fut
set by finish_recv
Definition cloud.h:282
batch_bytesT buf
sized in on_reply
Definition cloud.h:280
functor to distribute/rank/node-replicate a function, passed in as a pointer to WorldObjectBase
Definition cloud.h:697
DistributionType dt
Definition cloud.h:698
int operator()(WorldObjectBase *wo) const
Definition cloud.h:700
DistributeFunctor(const DistributionType dt)
Definition cloud.h:699
Definition cloud.h:967
std::atomic< long > & rtime
Definition cloud.h:970
World & world
Definition cloud.h:968
double wall0
Definition cloud.h:969
~cloudtimer()
Definition cloud.h:974
cloudtimer(World &world, std::atomic< long > &readtime)
Definition cloud.h:972
Definition cloud.h:956
Definition cloud.h:959
Definition cloud.h:70
static keyT compute_record(const std::vector< T > &arg)
Definition cloud.h:130
keyT pop_front_and_return()
Definition cloud.h:89
static keyT compute_record(const Function< T, NDIM > &arg)
Definition cloud.h:115
Recordlist(const Recordlist &other)
Definition cloud.h:77
Recordlist(const keyT &key)
Definition cloud.h:75
static keyT compute_record(const std::shared_ptr< T > &arg)
Definition cloud.h:136
static keyT compute_record(const T &arg)
Definition cloud.h:139
std::size_t size() const
Definition cloud.h:95
madness::meta::is_detected< member_id_t, T > has_member_id
Definition cloud.h:105
decltype(std::declval< T >().id()) member_id_t
Definition cloud.h:102
friend std::ostream & operator<<(std::ostream &os, const Recordlist &arg)
Definition cloud.h:153
Recordlist & operator+=(const Recordlist &list2)
Definition cloud.h:79
static keyT compute_record(const WorldContainer< keyQ, valueT > &arg)
Definition cloud.h:121
decltype(std::declval< T >().hash()) member_hash_t
Definition cloud.h:109
static keyT compute_record(const std::shared_ptr< WorldContainer< keyQ, valueT > > &arg)
Definition cloud.h:124
std::list< keyT > list
Definition cloud.h:71
Recordlist & operator+=(const keyT &key)
Definition cloud.h:84
static keyT compute_record(const FunctionImpl< T, NDIM > *arg)
Definition cloud.h:118
static keyT compute_record(const std::shared_ptr< madness::FunctionImpl< T, NDIM > > &arg)
Definition cloud.h:127
static keyT compute_record(const Tensor< T > &arg)
Definition cloud.h:133
madness::meta::is_detected< member_hash_t, T > has_member_hash
Definition cloud.h:112
Recordlist()
Definition cloud.h:73
Base class for WorldObject.
Definition world_object.h:345
World & get_world() const
Definition world_object.h:446
class to temporarily redirect output to cout
Definition print.h:300
Definition mra.h:2996
static const char * value()
Definition cloud.h:44
static const char * value()
Definition cloud.h:46
static const char * value()
Definition cloud.h:48
static const char * value()
Definition cloud.h:50
static const char * value()
Definition cloud.h:52
static const char * value()
Definition cloud.h:54
static const char * value()
Definition cloud.h:57
static const char * value()
Definition cloud.h:59
static const char * value()
Definition cloud.h:61
static const char * value()
Definition cloud.h:63
static const char * value()
Definition cloud.h:65
static const char * value()
Definition cloud.h:67
A utility to get the name of a type as a string from chatGPT.
Definition cloud.h:39
static const char * value()
Definition cloud.h:40
#define MPI_BYTE
Definition stubmpi.h:77
double source(const coordT &r)
Definition testperiodic.cc:48
static madness::WorldMemInfo stats
Definition worldmem.cc:64
int ProcessID
Used to clearly identify process number/rank.
Definition worldtypes.h:43
FLOAT target(const FLOAT &x)
Definition y.cc:295