MADNESS 0.10.1
exchangeoperator.h
Go to the documentation of this file.
1#ifndef SRC_APPS_CHEM_EXCHANGEOPERATOR_H_
2#define SRC_APPS_CHEM_EXCHANGEOPERATOR_H_
3
4#include<madness.h>
8
9#include <algorithm>
10#include <fstream>
11#include <numeric>
12#include <random>
13#include <list>
14#include <map>
15#include <utility>
16#include <vector>
17
18namespace madness {
19
20// forward declaration
21class SCF;
22class Nemo;
23
24/// Number of batches M for the owner-pinned symmetric exchange algorithm.
25
26/// M = granularity_level * nsubworld, so the level is directly the number of batches per
27/// rank and every level is selectable regardless of nsubworld parity. Clamped to [1, n]:
28/// there cannot be more batches than orbitals, and a caller that hits the clamp is in the
29/// small-problem regime where batches stop being one-per-rank.
30///
31/// Batch k is owned by rank (k mod nsubworld), so away from the clamp every rank owns
32/// exactly `granularity_level` batches.
33inline long exchange_sym_owner_nbatch(const std::size_t n, const long nsubworld,
34 const long granularity_level) {
35 if (n == 0) return 0;
36 const long nsw = std::max<long>(1, nsubworld);
37 const long level = std::max<long>(1, granularity_level);
38 return std::min<long>(level * nsw, long(n));
39}
40
41/// Split a vector of length n into M = exchange_sym_owner_nbatch(...) contiguous batches.
42
43/// Sizes differ by at most 1; the first (n mod M) batches get the extra element, which
44/// avoids a runt batch of 1. Single source of truth for the symmetric owner-pinned batch
45/// boundaries — the task grid, the cloud batch storage and the owner assignment all derive
46/// from it, so they align by construction. Depends only on (n, nsubworld, granularity_level).
47inline std::vector<Batch_1D> exchange_sym_owner_split(const std::size_t n, const long nsubworld,
48 const long granularity_level) {
49 std::vector<Batch_1D> out;
50 if (n == 0) return out;
51 const long nbatch = std::max<long>(1, exchange_sym_owner_nbatch(n, nsubworld, granularity_level));
52 const long bs_floor = long(n) / nbatch;
53 const long rem = long(n) - bs_floor * nbatch;
54 long begin = 0;
55 for (long b = 0; b < nbatch; ++b) {
56 const long sz = bs_floor + (b < rem ? 1 : 0);
57 out.emplace_back(begin, begin + sz);
58 begin += sz;
59 }
60 return out;
61}
62
63/// Batch boundaries for the asymmetric row/column split: one batch per rank.
64
65/// Deliberately the same boundaries as exchange_sym_owner_split at granularity 1, so batches stored
66/// for one dimension align with the partition. Named apart because "sym" reads wrong in the
67/// asymmetric path, and because granularity is not a knob here -- the column-to-rank assignment
68/// relies on there being exactly one batch per rank.
69inline std::vector<Batch_1D> exchange_row_owner_split(const std::size_t n, const long nsubworld) {
70 return exchange_sym_owner_split(n, nsubworld, 1);
71}
72
73/// The asymmetric task grid: every (column, row) pair over two independent splits.
74
75/// The column dimension is the operand that stays put -- vf, whose batch the running rank holds --
76/// and the row dimension is the one that rotates, carrying bra and ket, which share this range
77/// because the operator sums over pairs. There is no symmetry to exploit, so the grid is the full
78/// rectangle rather than a triangle, and the two dimensions are split independently: bra and ket
79/// have the same length as each other but need not match vf's.
80inline std::vector<std::pair<Batch_1D, Batch_1D>>
81exchange_row_owner_grid(const std::size_t ncolumn, const std::size_t nrow, const long nsubworld) {
82 const std::vector<Batch_1D> columns = exchange_row_owner_split(ncolumn, nsubworld);
83 const std::vector<Batch_1D> rows = exchange_row_owner_split(nrow, nsubworld);
84 std::vector<std::pair<Batch_1D, Batch_1D>> out;
85 out.reserve(columns.size() * rows.size());
86 for (const auto& c : columns)
87 for (const auto& r : rows) out.emplace_back(c, r);
88 return out;
89}
90
91/// Are these the same functions, so that one stored record can serve both operand roles?
92
93/// Compares identity, not value: `Function` is a shallow handle, so equal implementation pointers
94/// mean the coefficients are literally shared and storing them twice would duplicate the largest
95/// thing the cloud holds. HF exchange passes the same vector as all three operands, and nemo passes
96/// the same one as ket and vf, so this is the common case rather than a corner.
97template<typename T, std::size_t NDIM>
98inline bool exchange_same_operands(const std::vector<Function<T, NDIM>>& a,
99 const std::vector<Function<T, NDIM>>& b) {
100 if (a.size() != b.size()) return false;
101 for (std::size_t i = 0; i < a.size(); ++i)
102 if (a[i].get_impl().get() != b[i].get_impl().get()) return false;
103 return true;
104}
105
106/// the sup bounds (supbound.h) of a tile's multipliers, one per function
107template <std::size_t NDIM>
108using exchange_sup_bounds_t = std::vector<std::shared_ptr<const SupBoundMap<NDIM>>>;
109
110/// The sup bounds of a tile's multipliers, built once for the tile so that the screens of all its potentials
111/// share them, one task per function. The multipliers must be reconstructed or redundant (sup_bound_map
112/// checks). Their construction time goes to ApplyScreenStats.
113template <typename T, std::size_t NDIM>
115 exchange_sup_bounds_t<NDIM> sup(multipliers.size());
116 if (multipliers.empty()) return sup;
117 const double t0 = cpu_time();
118 typedef Range<int> rangeT;
119 auto build = [&sup, &multipliers](const rangeT::iterator& it) -> bool {
120 sup[it] = std::make_shared<const SupBoundMap<NDIM>>(multipliers[it].get_impl()->sup_bound_map());
121 return true;
122 };
123 // the fan-out is local, so it is awaited with get(), not with a fence
124 MADNESS_CHECK(world.taskq.for_each(rangeT(0, int(multipliers.size())), build).get());
125 ApplyScreenStats::sup_maps += long(multipliers.size());
126 ApplyScreenStats::sup_build_ns += long((cpu_time() - t0) * 1e9);
127 return sup;
128}
129
130/// The destination screen of one exchange potential: a bound on the size, per box, of the function(s) it
131/// will be multiplied with, from their sup bounds (applyscreen.h)
132template <std::size_t NDIM>
136
137/// Owner of every task in the asymmetric grid: all tasks of a column go to one worker.
138
139/// The column operand is the one that stays put, so putting a whole column on one worker means the
140/// batch it holds is never fetched, and that worker computes the *complete* result for those
141/// columns -- there is no cross-rank reduction of results beyond the final gather. Handing columns
142/// out in order is balanced by construction, the grid being a full rectangle, so no cost model is
143/// needed here. Keyed by batch index, like exchange_sym_round_robin_assign.
144inline std::map<std::pair<long,long>,long>
145exchange_row_owner_assign(const long ncolumn, const long nrow, const long nworker) {
146 std::map<std::pair<long,long>,long> owner;
147 if (ncolumn <= 0 or nrow <= 0 or nworker <= 0) return owner;
148 for (long c = 0; c < ncolumn; ++c)
149 for (long r = 0; r < nrow; ++r) owner[{c, r}] = c % nworker;
150 return owner;
151}
152
153/// Triangular index of a batch pair, collapsing (i,j) and (j,i): a*(a+1)/2 + b.
154
155/// The indexing convention of the per-task cost vector, shared by whoever records a
156/// measured cost and by exchange_sym_cost_aware_assign, which consumes it.
157inline long exchange_sym_tri(const long i, const long j) {
158 const long a = std::max(i, j), b = std::min(i, j);
159 return a * (a + 1) / 2 + b;
160}
161
162/// Round-robin owner assignment for the symmetric algorithm's triangular task matrix.
163
164/// Pure function of (n, M): n workers (= nsubworld), M batches, batch k owned by (k mod n).
165/// Task (i,j) with 0 <= j <= i < M is eligible for worker t iff
166/// i==j: (i mod n)==t -- a diagonal task has a single owner
167/// i!=j: (i mod n)==t or (j mod n)==t -- the worker owns at least one operand
168/// Eligibility is what makes the assignment fetch-free: a task always lands on a worker
169/// that already stores one of its two batches. Phase 1 round-robins eligible tasks across
170/// workers; phase 2 then rebalances off-diagonal tasks (diagonals never move) toward a
171/// task-count spread of 1.
172///
173/// Phase 2 is best effort, not a guarantee: it can only move a task to a worker the task
174/// is eligible for, so it stops early when the hottest worker holds nothing the coldest
175/// ones may take. The residual spread is 2 rather than 1 for some (n, M) — measured over
176/// n <= 128 and 1 to 3 batches per rank, never worse than 2.
177///
178/// \return map (i,j) -> owner. Deterministic, so every rank computes the same assignment
179/// without communicating.
180inline std::map<std::pair<long,long>,long>
181exchange_sym_round_robin_assign(const long n, const long M) {
182 std::map<std::pair<long,long>,long> owner;
183 if (n <= 0 or M <= 0) return owner;
184 auto eligible = [n](long i, long j, long t) -> bool {
185 if (i == j) return (i % n) == t;
186 return ((i % n) == t) or ((j % n) == t);
187 };
188 // all tasks, ascending by (i,j)
189 const std::size_t ntask = std::size_t(M) * std::size_t(M + 1) / 2;
190 std::vector<std::pair<long,long>> tasks;
191 tasks.reserve(ntask);
192 for (long i = 0; i < M; ++i)
193 for (long j = 0; j <= i; ++j)
194 tasks.emplace_back(i, j);
195
196 std::vector<std::vector<std::pair<long,long>>> T(n);
197
198 // Phase 1 — round-robin placement. Each worker takes the first task, in ascending
199 // (i,j), that is still free and eligible for it. `cursor[t]` remembers how far worker
200 // t has scanned: everything before it is either taken or permanently ineligible for t,
201 // and neither condition is ever undone, so the cursor only moves forward. That makes
202 // the phase linear in the task count per worker rather than quadratic overall.
203 std::vector<char> taken(ntask, 0);
204 std::vector<std::size_t> cursor(n, 0);
205 std::size_t placed = 0;
206 long t = 0, misses = 0;
207 while (placed < ntask and misses < n) {
208 std::size_t& c = cursor[t];
209 while (c < ntask and (taken[c] or not eligible(tasks[c].first, tasks[c].second, t))) ++c;
210 if (c < ntask) {
211 taken[c] = 1;
212 T[t].push_back(tasks[c]);
213 ++placed;
214 ++c;
215 misses = 0;
216 } else {
217 ++misses;
218 }
219 t = (t + 1) % n;
220 }
221 // any leftovers; every task is eligible for someone, so this should not trigger
222 for (std::size_t idx = 0; idx < ntask; ++idx)
223 if (not taken[idx]) T[tasks[idx].first % n].push_back(tasks[idx]);
224
225 // Phase 2 — rebalance until the spread is <= 1 (the iteration cap is a backstop)
226 for (long iter = 0; iter < 10000; ++iter) {
227 long big = 0, small = 0;
228 for (long p = 1; p < n; ++p) {
229 if (long(T[p].size()) > long(T[big].size())) big = p;
230 if (long(T[p].size()) < long(T[small].size())) small = p;
231 }
232 if (long(T[big].size()) - long(T[small].size()) <= 1) break;
233 bool moved = false;
234 std::vector<long> order(n);
235 for (long p = 0; p < n; ++p) order[p] = p;
236 std::sort(order.begin(), order.end(),
237 [&T](long a, long b){ return T[a].size() > T[b].size(); });
238 for (long bi = 0; bi < n and not moved; ++bi) {
239 for (long si = n - 1; si > bi and not moved; --si) {
240 const long bt = order[bi], st = order[si];
241 if (long(T[bt].size()) - long(T[st].size()) <= 1) continue;
242 for (long idx = 0; idx < long(T[bt].size()); ++idx) {
243 const auto& tk = T[bt][idx];
244 if (tk.first == tk.second) continue; // never move diagonals
245 if (not eligible(tk.first, tk.second, st)) continue;
246 T[st].push_back(tk);
247 T[bt].erase(T[bt].begin() + idx);
248 moved = true;
249 break;
250 }
251 }
252 }
253 if (not moved) break; // accept the residual imbalance
254 }
255
256 for (long p = 0; p < n; ++p)
257 for (const auto& tk : T[p])
258 owner[tk] = p;
259 return owner;
260}
261
262/// Cost-aware owner assignment for the symmetric algorithm's triangular task matrix.
263
264/// Same ownership and eligibility as exchange_sym_round_robin_assign, so the fetch-free
265/// invariant is preserved, but it balances per-worker total COST instead of task COUNT.
266/// Screening makes the tasks strongly inhomogeneous for large molecules, and that is what
267/// a count-based assignment cannot see. `cost` is indexed by exchange_sym_tri and holds a
268/// relative per-task cost, in practice the previous call's measured wall time; entries
269/// past its end count as zero, so an empty or short vector degrades to cost-blind.
270/// Greedy largest-cost-first onto the less loaded eligible worker, then a bounded local
271/// search that relieves the hottest worker.
272///
273/// \return map (i,j) -> owner. Deterministic given the same `cost`.
274inline std::map<std::pair<long,long>,long>
275exchange_sym_cost_aware_assign(const long n, const long M, const std::vector<double>& cost) {
276 std::map<std::pair<long,long>,long> owner;
277 if (n <= 0 or M <= 0) return owner;
278 auto C = [&](long i, long j) -> double {
279 const long t = exchange_sym_tri(i, j); return (t < long(cost.size())) ? cost[t] : 0.0;
280 };
281 std::vector<double> load(n, 0.0);
282 // diagonals first: they have no choice of owner
283 for (long i = 0; i < M; ++i) { const long r = i % n; load[r] += C(i,i); owner[{i,i}] = r; }
284 // off-diagonals, largest cost first, ties broken by (i,j) to stay deterministic
285 std::vector<std::pair<long,long>> off;
286 off.reserve(std::size_t(M) * std::size_t(M > 0 ? M - 1 : 0) / 2);
287 for (long i = 0; i < M; ++i) for (long j = 0; j < i; ++j) off.emplace_back(i, j);
288 std::sort(off.begin(), off.end(), [&](const std::pair<long,long>& A, const std::pair<long,long>& B){
289 const double ca = C(A.first,A.second), cb = C(B.first,B.second);
290 return (ca != cb) ? (ca > cb) : (A < B);
291 });
292 for (const auto& [i,j] : off) {
293 const long ri = i % n, rj = j % n;
294 const long r = (ri == rj) ? ri : (load[ri] <= load[rj] ? ri : rj);
295 owner[{i,j}] = r; load[r] += C(i,j);
296 }
297 // relieve the hottest worker by flipping its off-diagonals to their other eligible owner
298 for (long pass = 0; pass < 50; ++pass) {
299 long hot = 0; for (long p = 1; p < n; ++p) if (load[p] > load[hot]) hot = p;
300 bool improved = false;
301 for (const auto& [i,j] : off) {
302 auto it = owner.find({i,j});
303 if (it->second != hot) continue;
304 const long ri = i % n, rj = j % n;
305 if (ri == rj) continue; // no choice
306 const long other = (hot == ri) ? rj : ri;
307 const double c = C(i,j);
308 if (load[other] + c < load[hot]) { // strictly lowers the hot worker
309 load[hot] -= c; load[other] += c; it->second = other; improved = true;
310 }
311 }
312 if (not improved) break;
313 }
314 return owner;
315}
316
317/// One task's record for the exchange profiler.
318
319/// Written only when MAD_EXCH_TASK_PROFILE is set. What it adds over the aggregate counters is
320/// **attribution**: the counters say how many batches arrived from where, this says which task
321/// waited and for how long, so a straggler can be identified rather than inferred.
322///
323/// It deliberately does not carry a per-stage breakdown of the compute (multiply / apply /
324/// multiply). That would mean timing calls inside the numerical kernels, and the aggregate split
325/// already exists in the operator's own timers.
327 long task_id = -1;
328 long universe_rank = 0; ///< keys the output file: one per process
329 unsigned long subworld_id = 0;
331 double thresh = 0.0; ///< which protocol tier this task ran in
332 long k = 0;
333 bool diagonal = false;
334 long row_begin = 0, row_end = 0, col_begin = 0, col_end = 0;
335 double wall_start = 0.0, wall_end = 0.0;
336 double wait_for_data_wall = 0.0; ///< task entry until its operands are in hand
337 double compute_wall = 0.0, compute_cpu = 0.0;
338 /// wall inside each stage of the tile loop, accumulated over its rows. Honest without adding
339 /// any fence: every stage below runs with fence=true, so each completes before the next is
340 /// timed. What they do not cover -- building the per-row update vector, the compresses and the
341 /// accumulating gaxpys -- shows up as the emitted `other` residual.
342 double mul1_wall = 0.0, apply_wall = 0.0, mul2_wall = 0.0, truncate_wall = 0.0;
343 int operand_source = -1; ///< worst of its fetches: 0 resident, 1 ahead, 2 cold
344 bool waited = false; ///< a cold fetch happened, so this task paid latency
345 double peak_rss_gb = 0.0;
346
347 void reset() { *this = ExchTaskProfile(); }
348 /// keep the worst source, since that is the one that set the task's wait
349 void observe_fetch_tier(const int tier) {
350 if (tier > operand_source) operand_source = tier;
351 if (tier == 2) waited = true;
352 }
353};
354
355/// Is per-task exchange profiling on? Read once per process.
357 static const bool on = (std::getenv("MAD_EXCH_TASK_PROFILE") != nullptr);
358 return on;
359}
360
361/// Send a symmetric application down the general (bra, ket, vf) path? Read once per process.
362
363/// A symmetric application computes the same numbers either way -- the general path just does the
364/// whole rectangle where the symmetric one does a triangle and reuses each intermediate twice. So
365/// with this set, moldft becomes a differential test of the general path on data whose answer is
366/// already known, which is otherwise reachable only from nemo and molresponse. Debug only.
368 static const bool on = (std::getenv("MAD_EXCH_FORCE_GENERAL") != nullptr);
369 return on;
370}
371
372/// Append one record to exch_taskprof.r<rank>.jsonl.
373
374/// The stream stays open for the life of the process: one file per rank appended across every
375/// application, which bounds the file count at the rank count however many iterations run, and
376/// avoids a per-task open/close -- expensive metadata traffic on a parallel filesystem.
378 static std::ofstream os;
379 if (not os.is_open()) {
380 os.open("exch_taskprof.r" + std::to_string(p.universe_rank) + ".jsonl", std::ios::app);
381 if (not os.is_open()) return;
382 }
383 os << "{\"task\":" << p.task_id
384 << ",\"rank\":" << p.universe_rank
385 << ",\"subworld\":" << p.subworld_id
386 << ",\"subworld_nrank\":" << p.subworld_nrank
387 << ",\"thresh\":" << p.thresh
388 << ",\"k\":" << p.k
389 << ",\"diagonal\":" << (p.diagonal ? "true" : "false")
390 << ",\"row\":[" << p.row_begin << "," << p.row_end << "]"
391 << ",\"col\":[" << p.col_begin << "," << p.col_end << "]"
392 << ",\"wall_start\":" << p.wall_start
393 << ",\"wall\":" << (p.wall_end - p.wall_start)
394 << ",\"wait_for_data\":" << p.wait_for_data_wall
395 << ",\"compute_wall\":" << p.compute_wall
396 << ",\"compute_cpu\":" << p.compute_cpu
397 << ",\"compute_components_wall\":{"
398 << "\"mul1\":" << p.mul1_wall << ",\"apply\":" << p.apply_wall
399 << ",\"mul2\":" << p.mul2_wall << ",\"truncate\":" << p.truncate_wall
400 << ",\"other\":" << (p.compute_wall - p.mul1_wall - p.apply_wall
401 - p.mul2_wall - p.truncate_wall)
402 << "}"
403 << ",\"operand_source\":" << p.operand_source
404 << ",\"waited\":" << (p.waited ? "true" : "false")
405 << ",\"peak_rss_gb\":" << p.peak_rss_gb
406 << "}\n";
407 os.flush(); // keep it readable mid-run; there is one write per task, not per node
408}
409
410/// Write the measured per-task cost matrix of one application, for offline inspection.
411
412/// Behind the same flag as the rest of the profiler. One file per application per rank 0:
413/// `Ccall<NNN>_k<K>.csv`, holding `i,j,cost` over the lower-triangular batch grid, with the call
414/// index, wavelet order and batch count in a leading comment so a reader needs no other context.
415/// This is the matrix the next application's placement is derived from, so dumping it is how a
416/// straggler can be traced back to the cost that put it there.
417inline void exch_write_cost_matrix(const long call_index, const long k, const long M,
418 const std::vector<double>& cost) {
419 if (M <= 0 or cost.empty()) return;
420 char name[64];
421 std::snprintf(name, sizeof(name), "Ccall%03ld_k%ld.csv", call_index, k);
422 std::ofstream os(name);
423 if (not os.is_open()) return;
424 os << "# call=" << call_index << " k=" << k << " M=" << M << "\n";
425 os << "i,j,cost\n";
426 for (long i = 0; i < M; ++i)
427 for (long j = 0; j <= i; ++j) {
428 const long t = i * (i + 1) / 2 + j;
429 if (t < long(cost.size())) os << i << "," << j << "," << cost[t] << "\n";
430 }
431}
432
433/// which of the three exchange operand vectors a stored batch belongs to
435
436/// Per-invocation salt for the exchange batch record keys, from the ket identities.
437
438/// Taken from the ket vector because that one is available in full on both sides — where
439/// the batches are stored and where a task fetches them — so both derive the same record
440/// keys without anyone communicating a manifest. Function implementation ids are handed out
441/// in collective creation order, so the salt is identical on every rank and changes when
442/// the operator is applied to freshly built functions.
443///
444/// \warning It keys on identity, not on content: two applications over the same function
445/// objects produce the same salt, so a cache keyed by it must not outlive an
446/// in-place mutation of those functions.
447template<typename T, std::size_t NDIM>
448inline long exchange_batch_salt(const std::vector<Function<T, NDIM>>& ket) {
449 std::size_t k = 0x5a17ull;
450 for (const auto& f : ket) hash_combine(k, hash_value(f.get_impl()->id()));
451 return long(k);
452}
453
454/// Deterministic cloud record key for one stored batch: (salt, dimension, range).
455
456/// Range-keyed, so the storing side and the fetching side agree on the key by construction.
457inline long exchange_batch_record_key(const long salt, const int dim, const Batch_1D& r) {
458 std::size_t k = std::size_t(salt);
459 hash_combine(k, std::size_t(dim));
460 hash_combine(k, std::size_t(r.begin));
461 hash_combine(k, std::size_t(r.end));
462 return long(k);
463}
464
465/// Bounded cache of fetched exchange batches, keyed by cloud record key.
466
467/// A rank reuses the batches it owns across all of its tasks, so those are **pinned** and
468/// never evicted; only the batches fetched from elsewhere are transient and bounded. An
469/// earlier single bound over both let the churning transients evict the reusable owned
470/// batches, which re-fetched them at every owned-batch switch. Pinning the owned ones costs
471/// a fixed share of the data (orbitals per rank) and is independent of batch granularity.
472///
473/// Entries are held in a list, so a reference returned by find() or insert() stays valid
474/// until that entry is evicted — promotion and insertion of other entries do not move it.
475template<typename keyT, typename dataT>
477public:
478 /// how many non-owned entries may be resident; at least one is always allowed
479 void set_transient_capacity(const std::size_t c) { transient_capacity_ = std::max<std::size_t>(1, c); }
480 std::size_t transient_capacity() const { return transient_capacity_; }
481
482 bool contains(const keyT& key) const {
483 for (const auto& s : slots_) if (s.key == key) return true;
484 return false;
485 }
486
487 /// \return the cached batch, promoted to most-recently-used, or nullptr if absent
488 const dataT* find(const keyT& key) {
489 for (auto it = slots_.begin(); it != slots_.end(); ++it) {
490 if (it->key == key) {
491 slots_.splice(slots_.begin(), slots_, it);
492 return &slots_.front().data;
493 }
494 }
495 return nullptr;
496 }
497
498 /// Insert as most-recently-used. `pinned` marks a batch this rank owns.
499 const dataT& insert(const keyT& key, dataT&& data, const bool pinned) {
500 slots_.push_front(Slot{key, std::move(data), pinned});
501 while (n_transient() > transient_capacity_) {
502 // drop the least-recently-used transient entry; pinned ones are skipped
503 for (auto it = slots_.end(); it != slots_.begin(); ) {
504 --it;
505 if (not it->pinned) { slots_.erase(it); break; }
506 }
507 }
508 return slots_.front().data;
509 }
510
511 /// drop every entry; the capacity setting survives
512 void clear() { slots_.clear(); }
513
514 std::size_t size() const { return slots_.size(); }
515
516 std::size_t n_transient() const {
517 std::size_t c = 0;
518 for (const auto& s : slots_) if (not s.pinned) ++c;
519 return c;
520 }
521
522private:
523 struct Slot { keyT key; dataT data; bool pinned; };
524 std::list<Slot> slots_; // front = most recently used
525 std::size_t transient_capacity_ = 2;
526};
527
528
529/// One coefficient node in transit during the exchange finalize.
530
531/// Carries the destination function index, the tree-node key and the whole node, which is
532/// the same content the per-node active message would have sent -- just batched.
533template <typename T, std::size_t NDIM>
535 std::size_t f = 0; ///< index into the destination function vector
536 Key<NDIM> key; ///< tree-node key
537 FunctionNode<T, NDIM> node; ///< the source node
538 template <typename Archive>
539 void serialize(Archive& ar) { ar & f & key & node; }
540};
541
542/// Receiving end of the exchange finalize, living in the world the transfer rides on.
543
544/// Sources push bulk chunks here with task(), so deserializing and accumulating happens on a
545/// worker and never on the communication thread. The arithmetic is the same as
546/// FunctionNode::gaxpy_inplace; the accessor write lock is what serializes two senders that
547/// reach the same key at once.
548template <typename T, std::size_t NDIM>
549class FinalizeReducer : public WorldObject<FinalizeReducer<T, NDIM>> {
550public:
553
556 this->process_pending();
557 }
558
559 /// point at the destinations for the next drain; local, called by every rank
560 void set_targets(std::vector<implT*> dests, T beta) {
561 dests_ = std::move(dests);
562 beta_ = beta;
563 }
564
565 void accumulate_chunk(const std::vector<recT>& recs) {
566 for (const auto& r : recs) {
567 // always on: this guards a raw pointer dereference, so it must not be a check that
568 // release builds compile out. ASSERTION_TYPE=disable is a supported configuration
569 MADNESS_CHECK_THROW(r.f < dests_.size() and dests_[r.f] != nullptr,
570 "exchange finalize: a chunk names a destination this rank has not "
571 "been given, so its reducer targets were never set");
572 typename implT::dcT::accessor acc;
573 dests_[r.f]->get_coeffs().insert(acc, r.key); // get-or-create, locks the key
574 acc->second.template gaxpy_inplace<T, T>(T(1.0), r.node, beta_);
575 }
576 }
577
578private:
579 std::vector<implT*> dests_;
580 T beta_ = T(1.0);
581};
582
583/// Accumulate `src_vec` into `dest_vec` in bulk, one message per destination rank per chunk.
584
585/// Replaces one active message per source tree node. The two vectors may live in different
586/// worlds -- subworld or node into universe, or subworld into node -- so routing uses the
587/// **destination** process map while the transfer rides `transport_world`, which must be the
588/// destination's world. Completion is the caller's own fence.
589///
590/// \warning Collective on `transport_world`: every rank must call it once per finalize. The
591/// fence below is a readiness barrier, so that no chunk can arrive at a rank that
592/// has not yet repointed its reducer. A rank whose `src_vec` is empty still has to
593/// reach it -- **do not add an early return for having nothing to send.**
594template <typename T, std::size_t NDIM>
595void coalesced_gaxpy(World& transport_world,
597 std::vector<Function<T, NDIM>>& dest_vec,
598 std::vector<Function<T, NDIM>>& src_vec,
599 const T beta,
600 const std::size_t chunk_entries) {
601 typedef FunctionImpl<T, NDIM> implT;
602 typedef FinalizeNodeRec<T, NDIM> recT;
603
604 std::vector<implT*> dests(dest_vec.size(), nullptr);
605 for (std::size_t f = 0; f < dest_vec.size(); ++f)
606 dests[f] = dest_vec[f].get_impl().get();
607 reducer.set_targets(dests, beta);
608 transport_world.gop.fence(); // the readiness barrier -- see the warning above
609
610 std::map<ProcessID, std::vector<recT>> buckets;
611 const std::size_t nf = std::min(src_vec.size(), dest_vec.size());
612 for (std::size_t f = 0; f < nf; ++f) {
613 auto simpl = src_vec[f].get_impl();
614 auto dimpl = dest_vec[f].get_impl();
615 if (not simpl or not dimpl) continue;
616 const implT& dref = *dimpl;
617 for (auto it = simpl->get_coeffs().begin(); it != simpl->get_coeffs().end(); ++it) {
618 const ProcessID owner = dref.get_coeffs().owner(it->first);
619 std::vector<recT>& b = buckets[owner];
620 b.push_back(recT{f, it->first, it->second});
621 if (b.size() >= chunk_entries) {
623 b.clear();
624 }
625 }
626 }
627 for (auto& kv : buckets)
628 if (not kv.second.empty())
629 reducer.task(kv.first, &FinalizeReducer<T, NDIM>::accumulate_chunk, kv.second);
630}
631
632
633template<typename T, std::size_t NDIM>
636 typedef std::vector<functionT> vecfuncT;
637
638 static inline std::atomic<long> apply_timer;
639 static inline std::atomic<long> mul2_timer;
640 static inline std::atomic<long> mul1_timer; ///< timing
641 static inline double elapsed_time;
642
643 static void reset_timer() {
644 mul1_timer = 0l;
645 mul2_timer = 0l;
646 apply_timer = 0l;
647 elapsed_time = 0.0;
649 }
650
651public:
652 nlohmann::json gather_timings(World& world) const {
653 double t1 = double(mul1_timer) * 0.001;
654 double t2 = double(apply_timer) * 0.001;
655 double t3 = double(mul2_timer) * 0.001;
656 // the operand batches a task found resident vs had to fetch from their owner. Summed
657 // here rather than read off the local counters, so this reports the whole run like
658 // every other number in this object
659 double resident = double(MacroTaskExchangeSimple::batch_cache_hits());
660 double fetched = double(MacroTaskExchangeSimple::batch_cache_misses());
661 double ahead = double(MacroTaskExchangeSimple::batch_prefetch_hits());
662 world.gop.sum(t1);
663 world.gop.sum(t2);
664 world.gop.sum(t3);
665 world.gop.sum(resident);
666 world.gop.sum(fetched);
667 world.gop.sum(ahead);
668 nlohmann::json j;
669 j["multiply1"] = t1;
670 j["apply"] = t2;
671 j["multiply2"] = t3;
672 j["total"] = elapsed_time;
673 j["batch_cache_hits"] = long(resident);
674 j["batch_cache_misses"] = long(fetched);
675 j["batch_prefetch_hits"] = long(ahead);
676 return j;
677 }
678
679 void print_timer(World& world) const {
680 auto timings= gather_timings(world);
681 if (world.rank() == 0) {
682 printf(" cpu time spent in multiply1 %8.2fs\n", timings["multiply1"].template get<double>());
683 printf(" cpu time spent in apply %8.2fs\n", timings["apply"].template get<double>());
684 printf(" cpu time spent in multiply2 %8.2fs\n", timings["multiply2"].template get<double>());
685 printf(" total wall time %8.2fs\n", timings["total"].template get<double>());
686 // only the owner-pinned path fetches operand batches, so this stays quiet for
687 // every other algorithm; zero fetches would mean that path never ran
688 const long resident = timings["batch_cache_hits"].template get<long>();
689 const long fetched = timings["batch_cache_misses"].template get<long>();
690 const long ahead = timings["batch_prefetch_hits"].template get<long>();
691 if (resident + fetched + ahead > 0)
692 printf(" operand batches resident/ahead/fetched %6ld /%6ld /%6ld\n",
693 resident, ahead, fetched);
694 }
695 }
696
697
701
702 /// default ctor
703 ExchangeImpl(World& world, const double lo, const double thresh) : world(world), lo(lo), thresh(thresh) {}
704
705 /// ctor with a conventional calculation
706 ExchangeImpl(World& world, const SCF *calc, const int ispin) ;
707
708 /// ctor with a nemo calculation
709 ExchangeImpl(World& world, const Nemo *nemo, const int ispin);
710
711 /// ctor with a nemo calculation whose bra R^2 F is already at hand; neither bra nor ket is copied
712 ExchangeImpl(World& world, const Nemo *nemo, const std::vector<Function<double,NDIM>>& R2mo, const int ispin);
713
714 /// set the bra and ket orbital spaces, and the occupation
715
716 /// @param[in] bra bra space, must be provided as complex conjugate
717 /// @param[in] ket ket space
718 void set_bra_and_ket(const vecfuncT& bra, const vecfuncT& ket) {
719 mo_bra = copy(world, bra);
720 mo_ket = copy(world, ket);
721 }
722
723 std::string info() const {return "K";}
724
725 static auto set_poisson(World& world, const double lo, const double econv = FunctionDefaults<3>::get_thresh()) {
726 return std::shared_ptr<real_convolution_3d>(CoulombOperatorPtr(world, lo, econv));
727 }
728
729 /// apply the exchange operator on a vector of functions
730
731 /// note that only one spin is used (either alpha or beta orbitals)
732 /// @param[in] vket the orbitals |i> that the operator is applied on
733 /// @return a vector of orbitals K| i>
734 vecfuncT operator()(const vecfuncT& vket) const;
735
736 bool is_symmetric() const { return symmetric_; }
737
738 ExchangeImpl& set_taskq(std::shared_ptr<MacroTaskQ> taskq1) {
739 this->taskq=taskq1;
740 return *this;
741 }
742
743 ExchangeImpl& symmetric(const bool flag) {
744 symmetric_ = flag;
745 return *this;
746 }
747
750 return *this;
751 }
752
753 ExchangeImpl& set_macro_task_info(const std::vector<std::string>& info) {
754 macro_task_info.from_vector_of_strings(info);
755 if (world.rank() == 0 && printdebug()) {
756 print("set macrotaskinfo to");
758 }
759 return *this;
760 }
761
763 algorithm_ = alg;
764 return *this;
765 }
766
767 ExchangeImpl& set_printlevel(const long& level) {
768 printlevel=level;
769 return *this;
770 }
771
773 MADNESS_CHECK_THROW(level >= 1, "exchange batch granularity must be at least 1");
774 batch_granularity_ = level;
775 return *this;
776 }
777
779 cost_aware_assign_ = flag;
780 return *this;
781 }
782
783 /// The order of the orbitals in the exchange batches (hfexalg=multiworld): as_is, the order given;
784 /// shuffle, a fixed random permutation; balanced, the orbitals dealt into the batches by their
785 /// coefficient count, largest first, each into the batch with the smallest load so far, so that
786 /// every batch carries the same share of the deep core orbitals. The permutation is applied to the
787 /// bra and the ket, with shallow copies, and to the argument on the symmetric path, where the result
788 /// is permuted back; the general path sums over the operator's orbitals for every argument, which
789 /// keeps its order. balanced derives its order from the current node counts at every application,
790 /// while the cost-aware placement reuses the per-tile costs of the previous one, which are
791 /// meaningful only as long as the order did not change in between.
792 ExchangeImpl& set_mo_order(const std::string& order) {
793 MADNESS_CHECK_THROW(order == "as_is" or order == "shuffle" or order == "balanced",
794 "exchange: the orbital order must be as_is, shuffle or balanced");
795 mo_order_ = order;
796 return *this;
797 }
798
799 /// the permutation of the ket for the orbital order, identical on every rank; empty for as_is
800 /// or fewer than two orbitals
801 std::vector<std::size_t> mo_order_permutation() const {
802 const std::size_t n = mo_ket.size();
803 std::vector<std::size_t> perm;
804 if (mo_order_ == "as_is" or n < 2) return perm;
805 perm.resize(n);
806 std::iota(perm.begin(), perm.end(), 0);
807 if (mo_order_ == "shuffle") {
808 // a constant seed on purpose: every rank derives the same order without communicating
809 std::mt19937 rng(42); // NOLINT(cert-msc51-cpp)
810 std::shuffle(perm.begin(), perm.end(), rng);
811 return perm;
812 }
813 // balanced: the global node count per orbital (the local map sizes, one reduction, identical on
814 // every rank; the coefficient count up to k^NDIM for a reconstructed tree, without walking the
815 // nodes), dealt largest first into the batches of the owner split, each into the batch with the
816 // smallest load that still has room, so the batch sizes are those of the split
817 std::vector<double> cost(n, 0.0);
818 for (std::size_t j = 0; j < n; ++j) cost[j] = double(mo_ket[j].get_impl()->get_coeffs().size());
819 world.gop.sum(cost.data(), cost.size());
820 const std::vector<Batch_1D> split = exchange_sym_owner_split(n, world.size(), batch_granularity_);
821 std::vector<std::size_t> order(n);
822 std::iota(order.begin(), order.end(), 0);
823 std::stable_sort(order.begin(), order.end(),
824 [&cost](const std::size_t a, const std::size_t b) { return cost[a] > cost[b]; });
825 std::vector<std::vector<std::size_t>> bins(split.size());
826 std::vector<double> load(split.size(), 0.0);
827 for (const std::size_t i : order) {
828 std::size_t best = split.size();
829 for (std::size_t b = 0; b < split.size(); ++b) {
830 if (long(bins[b].size()) >= split[b].size()) continue;
831 if (best == split.size() or load[b] < load[best]) best = b;
832 }
833 bins[best].push_back(i);
834 load[best] += cost[i];
835 }
836 perm.clear();
837 for (const auto& b : bins) perm.insert(perm.end(), b.begin(), b.end());
838 if (world.rank() == 0 and printlevel >= 4) {
839 // the spread of the per-batch coefficient count, balanced against the order given
840 auto spread = [](const std::vector<double>& v) {
841 double mx = 0.0, sum = 0.0;
842 for (const double x : v) { mx = std::max(mx, x); sum += x; }
843 return v.empty() or sum == 0.0 ? 0.0 : mx / (sum / double(v.size()));
844 };
845 std::vector<double> given(split.size(), 0.0);
846 for (std::size_t b = 0; b < split.size(); ++b)
847 for (long i = split[b].begin; i < split[b].end; ++i) given[b] += cost[i];
848 printf("exchange mo order balanced: %ld batches, per-batch node count max/mean %.2f (as given %.2f)\n",
849 long(split.size()), spread(load), spread(given));
850 }
851 return perm;
852 }
853
854 /// skip the Poisson apply where the multiplier is negligible in the destination box (applyscreen.h);
855 /// read by the multiworld algorithm, ignored by the others (which say so at the first application)
856 ExchangeImpl& set_apply_screen(const bool flag) {
857 apply_screen_ = flag;
858 return *this;
859 }
860
862 MADNESS_CHECK_THROW(mode == 1 or mode == 2, "exchange accumulation mode must be 1 or 2");
863 accumulation_mode_ = mode;
864 return *this;
865 }
866
867 std::shared_ptr<MacroTaskQ> get_taskq() const {return taskq;}
868
869 World& get_world() const {return world;}
870
871 nlohmann::json get_statistics() const {return statistics;}
872
873 /// return some statistics about the current settings
874 nlohmann::json gather_statistics() const {
875 nlohmann::json j;
876 j["symmetric"] = symmetric_;
877 j["lo"] = lo;
878 j["thresh"] = thresh;
879 j["mul_tol"] = mul_tol;
880 j["printlevel"] = printlevel;
881 j["algorithm"] = to_string(algorithm_);
882 j["macro_task_info"] = macro_task_info.to_json();
883 auto timings = gather_timings(world);
884 j.update(timings);
885 return j;
886 }
887
888private:
889
890 /// exchange using macrotasks, i.e. apply K on a function in individual worlds
891 vecfuncT K_macrotask_efficient(const vecfuncT& vket, const double mul_tol = 0.0) const;
892
893 /// the same on the bra and ket given rather than the operator's own
894 vecfuncT K_macrotask_efficient(const vecfuncT& vf, const vecfuncT& bra, const vecfuncT& ket,
895 double mul_tol) const;
896
897 /// exchange using macrotasks, i.e. apply K on a function in individual worlds row-wise
898 vecfuncT K_macrotask_efficient_row(const vecfuncT& vket, const double mul_tol = 0.0) const;
899
900 /// computing the full square of the double sum (over vket and the K orbitals)
901 vecfuncT K_small_memory(const vecfuncT& vket, const double mul_tol = 0.0) const;
902
903 /// computing the upper triangle of the double sum (over vket and the K orbitals)
904 vecfuncT K_large_memory(const vecfuncT& vket, const double mul_tol = 0.0) const;
905
906 /// computing the upper triangle of the double sum (over vket and the K orbitals)
907 static vecfuncT compute_K_tile(World& world, const vecfuncT& mo_bra, const vecfuncT& mo_ket,
908 const vecfuncT& vket, std::shared_ptr<real_convolution_3d> poisson,
909 const bool symmetric, const double mul_tol = 0.0,
910 const bool apply_screen = false);
911
912 inline bool printdebug() const {return printlevel >= 10; }
913 inline bool printprogress() const {return (printlevel>=4) and (not (printdebug()));}
914 inline bool printtimings() const {return printlevel>=3;}
915 inline bool printtimings_detail() const {return printlevel>=4;}
916
918 std::shared_ptr<MacroTaskQ> taskq;
919 bool symmetric_ = false; /// is the exchange matrix symmetric? K phi_i = \sum_k \phi_k \int \phi_k \phi_i
920 vecfuncT mo_bra, mo_ket; ///< MOs for bra and ket
921 double lo = 1.e-4;
923 long printlevel = 0;
925 /// batches per rank in the owner-pinned symmetric partition; 1 is the coarsest split
926 /// and the one with the lowest peak memory
928 /// how the tile results are gathered: 1 = subworld buffer then universe, 2 = also reduce
929 /// within a node first (default; degrades to 1 on a single node)
931 /// place tasks by measured cost instead of by counting them; the first two applications
932 /// still count, having no representative reference to measure against
934 /// the order of the orbitals in the batches: as_is, shuffle or balanced (set_mo_order)
935 std::string mo_order_ = "as_is";
936 /// skip the Poisson apply where the multiplier is negligible in the destination box (applyscreen.h)
937 bool apply_screen_ = false;
938
939 mutable nlohmann::json statistics; ///< statistics of the Cloud (timings, memory) and of the parameters of this run
940
942
944 double lo = 1.e-4;
945 double mul_tol = 1.e-7;
946 bool symmetric = false;
947 /// pin each task to a rank that owns one of its batches, over the owner-pinned split
948 bool owner_pinned = false;
950 /// Per-application salt for the batch record keys, from exchange_batch_salt.
951
952 /// Carried on the task rather than re-derived where it is used: every rank builds the
953 /// same task objects collectively, so a constructor argument already reaches every
954 /// rank, and deriving it instead requires whichever operand vector it is taken from to
955 /// be available in full wherever a key is formed. That is true only while the ket is
956 /// passed unbatched.
957 long batch_salt_ = 0;
958 /// Which role's record actually carries the bra and the vf. Identical operand vectors share
959 /// one stored record instead of duplicating coefficients: HF exchange passes one vector as
960 /// all three operands, nemo passes one as ket and vf. Set on the universe side, where all
961 /// three are in hand; see exchange_same_operands.
962 bool bra_shares_ket_ = true;
963 bool vf_shares_ket_ = true;
964 /// 1 = sum into a subworld buffer and drain that into the universe;
965 /// 2 = additionally reduce within a node first, so only one rank per node scatters
966 /// across nodes. Degrades to 1 automatically when there is a single node.
968 /// place tasks by their measured cost rather than by counting them
969 bool cost_aware_ = true;
970 /// (column batch offset, row batch offset) -> owning rank, filled by
971 /// prepare_owner_assignment and read by owner_hint
972 std::map<std::pair<long,long>,long> owner_map_;
973 /// this process's rank in the universe, to recognise the batches it owns
975 /// screen the Poisson apply by the multipliers' sizes in the destination box (applyscreen.h)
976 bool apply_screen_ = false;
977
978 /// Batches fetched from the cloud, reused across the tasks that run in one subworld.
979
980 /// Static because the tasks of a subworld are separate objects: the cache has to
981 /// outlive any one of them to be reused at all. It is therefore scoped by hand to
982 /// the subworld that filled it -- see ensure_cache_world, which drops it when the
983 /// subworld changes so a batch from one subworld is never read in another.
985 static inline long cache_world_id_ = -1;
986 static inline std::atomic<long> batch_cache_hits_;
987 static inline std::atomic<long> batch_cache_misses_;
988 static inline std::atomic<long> batch_prefetch_hits_;
989
990 /// One batch requested ahead of the task that will read it.
991
992 /// A strict double buffer: `next` is requested while this task computes, and every
993 /// task promotes it to `current` before computing, so **at most two requests are ever
994 /// in flight per rank**. That bound is load-bearing, not a tuning choice: an earlier
995 /// design that allowed several concurrent requests corrupted the transport on large
996 /// replies, because the outstanding replies could outnumber what the receive path was
997 /// prepared for.
999 bool valid = false;
1000 long key = 0;
1001 /// Held by pointer, not by value: a slot is retired by overwriting it, and `Future`'s
1002 /// assignment operator requires an unset target. Overwriting a slot whose reply has
1003 /// already landed -- which is every consumed slot -- trips that assertion. Dropping
1004 /// the pointer releases the future instead of assigning over it.
1005 std::shared_ptr<Future<batch_bytesT>> fut;
1006 };
1007 static inline PrefetchSlot prefetch_current_; ///< promoted from the previous task
1008 static inline PrefetchSlot prefetch_next_; ///< requested during this task
1009
1010 /// What each task cost last time, to place them better this time.
1011
1012 /// Screening makes the tiles strongly uneven for large molecules, and a placement that
1013 /// balances task *counts* cannot see that. The measured wall time of each tile is
1014 /// recorded here, summed across ranks after the call -- each tile ran on exactly one
1015 /// rank, so summing unions the contributions -- and used as the reference for the next
1016 /// call. Kept across calls and across protocol changes on purpose: only the relative
1017 /// cost matters, and its structure barely moves between them.
1018 static inline std::vector<double> cost_reference_; ///< from the previous call
1019 static inline std::vector<double> cost_this_call_; ///< rank-local, summed after the call
1020 static inline std::map<long,long> batch_begin_to_index_; ///< batch offset -> index
1021 static inline long exchange_call_index_ = 0;
1022
1023 /// This task's profile record. NOT static: it belongs to the single operator() call on
1024 /// this object, and the fetch writes into it through `this` during that call.
1026 static inline long prof_task_seq_ = 0; ///< per-process task counter, for identity only
1027
1028 /// Where this subworld's tile results are summed before they leave it, and where a
1029 /// node's subworlds are summed before that leaves the node. Static for the same reason
1030 /// the batch cache is -- each task batch is a separate object -- and so subject to the
1031 /// same two lifetime rules: the world-id guards below stop a stale read, and cleanup()
1032 /// releases them while their world is still alive. Neither alone is enough.
1033 static inline vecfuncT Kf_local_;
1034 static inline bool Kf_local_initialized_ = false;
1035 static inline long Kf_local_world_id_ = -1;
1036 static inline vecfuncT Kf_node_;
1037 static inline bool Kf_node_initialized_ = false;
1038 static inline long Kf_node_world_id_ = -1;
1039 /// Receiving endpoints for the two drains, one per world they transfer within.
1040
1041 /// These are WorldObjects, so they are bound to a world exactly as a Function is, and the
1042 /// same lifetime rule applies: **release them while that world is still alive.** The node
1043 /// world is built per application (the queue owns it and a fresh queue is built per call),
1044 /// so a cached node reducer that survives the application is registered in a world that no
1045 /// longer exists. The world id is kept beside the pointer rather than read back out of it,
1046 /// because comparing `reducer->get_world().id()` is itself a read of the dead world.
1047 static inline std::shared_ptr<FinalizeReducer<T, NDIM>> universe_reducer_;
1048 static inline long universe_reducer_world_id_ = -1;
1049 static inline std::shared_ptr<FinalizeReducer<T, NDIM>> node_reducer_;
1050 static inline long node_reducer_world_id_ = -1;
1051 /// each drain happens once per rank, not once per task object
1052 static inline bool finalize_stage1_done_ = false;
1053 static inline bool finalize_universe_done_ = false;
1054
1055 static void clear_local_caches() {
1056 batch_cache_.clear();
1057 // drop requests issued in a subworld that is no longer the one we are in
1060 }
1061
1062 /// entries per chunk in coalesced_gaxpy, sized so one message stays modest at any k
1063 static std::size_t finalize_chunk_entries() {
1064 const std::size_t k = FunctionDefaults<NDIM>::get_k();
1065 const std::size_t per_node = std::size_t(1) << (2 * NDIM); // (2k)^NDIM / k^NDIM bound
1066 return std::max<std::size_t>(1, (1u << 20) / (per_node * k * k * k * sizeof(T) + 1));
1067 }
1068
1069 /// One reducer per transport world, rebuilt when that world changes. Collective:
1070 /// constructing a WorldObject is, so every rank of `world` reaches this together.
1072 if (not universe_reducer_ or universe_reducer_world_id_ != long(world.id())) {
1073 universe_reducer_ = std::make_shared<FinalizeReducer<T, NDIM>>(world);
1074 universe_reducer_world_id_ = long(world.id());
1075 }
1076 return *universe_reducer_;
1077 }
1078
1080 if (not node_reducer_ or node_reducer_world_id_ != long(world.id())) {
1081 node_reducer_ = std::make_shared<FinalizeReducer<T, NDIM>>(world);
1082 node_reducer_world_id_ = long(world.id());
1083 }
1084 return *node_reducer_;
1085 }
1086
1087 /// drop cached batches when the subworld changes; they belong to the old one
1089 if (cache_world_id_ != long(world.id())) {
1091 cache_world_id_ = long(world.id());
1092 }
1093 }
1094
1095 /// Fetch one owner-pinned batch, from the local cache if it is resident.
1096
1097 /// A miss goes straight to the owning rank over the cloud's point-to-point batch
1098 /// path. Batches this rank owns are pinned, since every one of its tasks needs
1099 /// them; the others are transient and bounded.
1100 ///
1101 /// \return a reference into the cache, valid until that entry is evicted
1102 const vecfuncT& fetch_batch(World& world, Cloud& cloud, const long record) const {
1104 if (const vecfuncT* resident = batch_cache_.find(record)) {
1106 if (profile_active()) prof_.observe_fetch_tier(0);
1107 return *resident;
1108 }
1109 const bool owned = (cloud.batch_owner(record) == universe_rank_);
1110 // requested one task ahead, so the transfer overlapped that task's compute
1111 for (PrefetchSlot* slot : {&prefetch_current_, &prefetch_next_}) {
1112 if (slot->valid and slot->key == record) {
1113 vecfuncT data = cloud.template deserialize_batch_p2p<T, NDIM>(
1114 world, *slot->fut, record, /*cache_result=*/false);
1115 *slot = PrefetchSlot();
1117 if (profile_active()) prof_.observe_fetch_tier(1);
1118 return batch_cache_.insert(record, std::move(data), owned);
1119 }
1120 }
1122 if (profile_active()) prof_.observe_fetch_tier(2);
1123 vecfuncT data = cloud.template fetch_batch_p2p<T, NDIM>(world, record, /*cache_result=*/false);
1124 return batch_cache_.insert(record, std::move(data), owned);
1125 }
1126
1127 /// custom partitioning for the exchange operator in exchangeoperator.h
1128
1129 /// arguments are: result[i] += sum_k vket[k] \int 1/r vbra[k] f[i]
1130 /// with f and vbra being batched, result and vket being passed on as a whole
1132 public:
1139
1140 bool symmetric = false;
1141 /// build the grid from the owner-pinned split instead of the size-driven one,
1142 /// so a task's two batches coincide with batches some rank owns
1143 bool owner_pinned = false;
1145
1146 partitionT do_partitioning(const std::size_t& vsize1, const std::size_t& vsize2,
1147 const std::string policy) const override {
1148
1149 if (owner_pinned and not symmetric) {
1150 // full grid over two independent splits; see exchange_row_owner_grid
1151 partitionT result;
1152 for (const auto& [column, row] : exchange_row_owner_grid(vsize1, vsize2,
1153 long(nsubworld))) {
1154 Batch batch(column, row, _);
1155 result.push_back(std::make_pair(batch, compute_priority(batch)));
1156 }
1157 return result;
1158 }
1159
1160 if (owner_pinned) {
1161 // lower-triangular grid over one granularity-aware split, shared with
1162 // the owner assignment: input[0] = batch i (column), input[1] = batch j
1163 // (row), j <= i. Owners are assigned by prepare_owner_assignment.
1164 const std::vector<Batch_1D> batches =
1166 partitionT result;
1167 for (long i = 0; i < long(batches.size()); ++i) {
1168 for (long j = 0; j <= i; ++j) {
1169 Batch batch(batches[i], batches[j], _);
1170 result.push_back(std::make_pair(batch, compute_priority(batch)));
1171 }
1172 }
1173 return result;
1174 }
1175
1176 partitionT partition1 = do_1d_partition(vsize1, policy);
1177 partitionT partition2 = do_1d_partition(vsize2, policy);
1178 partitionT result;
1179 for (auto i = partition1.begin(); i != partition1.end(); ++i) {
1180 if (symmetric) {
1181 for (auto j = i; j != partition1.end(); ++j) {
1182 Batch batch(i->first.input[0], j->first.input[0], _);
1183 double priority=compute_priority(batch);
1184 result.push_back(std::make_pair(batch,priority));
1185 }
1186 } else {
1187 for (auto j = partition2.begin(); j != partition2.end(); ++j) {
1188 Batch batch(i->first.input[0], j->first.input[0], _);
1189 double priority=compute_priority(batch);
1190 result.push_back(std::make_pair(batch,priority));
1191 }
1192 }
1193 }
1194 return result;
1195 }
1196
1197 /// compute the priority of this task for non-dumb scheduling
1198
1199 /// \return the priority as double number (no limits)
1200 double compute_priority(const Batch& batch) const override {
1201 MADNESS_CHECK(batch.input.size() == 2); // must be quadratic batches
1202 long nrow = batch.input[0].size();
1203 long ncol = batch.input[1].size();
1204 return double(nrow * ncol);
1205 }
1206 };
1207
1208 public:
1209 MacroTaskExchangeSimple(const long nresult, const double lo, const double mul_tol,
1210 const bool symmetric, const bool owner_pinned = false,
1211 const long granularity_level = 1, const long universe_rank = 0,
1212 const int accumulation_mode = 2, const bool cost_aware = true,
1213 const long batch_salt = 0, const bool bra_shares_ket = true,
1214 const bool vf_shares_ket = true, const bool apply_screen = false)
1217 batch_salt_(batch_salt), bra_shares_ket_(bra_shares_ket),
1218 vf_shares_ket_(vf_shares_ket),
1219 accumulation_mode_(accumulation_mode), cost_aware_(cost_aware),
1220 universe_rank_(universe_rank), apply_screen_(apply_screen) {
1222 name="MacroTaskExchangeSimple";
1223 }
1224
1225 /// how often a task's operand batch was already resident, and how often it had to be
1226 /// fetched from the rank owning it. No fetches at all means the path never ran.
1227 static long batch_cache_hits() { return batch_cache_hits_; }
1228 static long batch_cache_misses() { return batch_cache_misses_; }
1230 /// per-task profiling on for this task?
1232 static std::vector<double>& cost_this_call() { return cost_this_call_; }
1234 /// number of batches this application split into, which squares to the cost matrix
1235 static long cost_matrix_dimension() { return long(batch_begin_to_index_.size()); }
1236 /// make this call's measured costs the reference for the next one
1241
1242 /// Assign every task to the rank that will own one of its two batches.
1243
1244 /// Called by the macrotask queue after partitioning and before it asks for each
1245 /// task's owner. The batch boundaries come from the same split the partitioner
1246 /// used, so a task's (column, row) batch offsets identify a pair of batch indices,
1247 /// and exchange_sym_round_robin_assign turns that pair into an owner. Every rank
1248 /// runs this over the same partition and gets the same map without communicating.
1250 const long nsubworld) {
1251 owner_map_.clear();
1252 if (not owner_pinned or nsubworld <= 0) return;
1253
1254 if (not symmetric) {
1255 // Both dimensions are indexed from the partition rather than from nresult, which is
1256 // the column length only: the row dimension carries bra and ket and has its own.
1257 std::map<long,long> column_index, row_index;
1258 for (const auto& [task_batch, priority] : partition) {
1259 MADNESS_CHECK_THROW(task_batch.input.size() >= 2,
1260 "owner-pinned exchange expects two-dimensional task batches");
1261 column_index[task_batch.input[0].begin] = 0; // renumbered below, in order
1262 row_index[task_batch.input[1].begin] = 0;
1263 }
1264 long next = 0;
1265 for (auto& [begin, index] : column_index) index = next++;
1266 next = 0;
1267 for (auto& [begin, index] : row_index) index = next++;
1268
1269 const auto assignment = exchange_row_owner_assign(long(column_index.size()),
1270 long(row_index.size()), nsubworld);
1271 for (const auto& [task_batch, priority] : partition) {
1272 const long c = column_index[task_batch.input[0].begin];
1273 const long r = row_index[task_batch.input[1].begin];
1274 auto it = assignment.find({c, r});
1275 owner_map_[{task_batch.input[0].begin, task_batch.input[1].begin}] =
1276 (it != assignment.end()) ? it->second : (c % nsubworld);
1277 }
1278 // Cost-aware placement stays off here: its vector is indexed by exchange_sym_tri,
1279 // which is meaningless for a rectangle, and a column-per-worker grid is already
1280 // balanced. An empty vector is what stops the tiles recording into it.
1281 cost_this_call_.clear();
1282 batch_begin_to_index_.clear();
1283 return;
1284 }
1285
1286 const std::vector<Batch_1D> split =
1288 const long M = long(split.size());
1289 std::map<long,long> begin_to_index;
1290 for (long k = 0; k < M; ++k) begin_to_index[split[k].begin] = k;
1291
1292 // Cost-aware placement needs a reference from a previous call, and the first call
1293 // is not representative of the ones that follow it -- cold caches and an initial
1294 // guess -- so it takes effect from the third call on, with the second call's
1295 // measurements as its reference.
1297 batch_begin_to_index_ = begin_to_index;
1298 const std::size_t ntask = std::size_t(M) * std::size_t(M + 1) / 2;
1299 cost_this_call_.assign(ntask, 0.0);
1300 const bool use_cost = cost_aware_ and exchange_call_index_ >= 3
1301 and cost_reference_.size() == ntask;
1302 const std::map<std::pair<long,long>,long> assignment =
1303 use_cost ? exchange_sym_cost_aware_assign(nsubworld, M, cost_reference_)
1304 : exchange_sym_round_robin_assign(nsubworld, M);
1305
1306 for (const auto& [task_batch, priority] : partition) {
1307 MADNESS_CHECK_THROW(task_batch.input.size() >= 2,
1308 "owner-pinned exchange expects two-dimensional task batches");
1309 const long column_begin = task_batch.input[0].begin;
1310 const long row_begin = task_batch.input[1].begin;
1311 auto ic = begin_to_index.find(column_begin);
1312 auto jr = begin_to_index.find(row_begin);
1313 MADNESS_CHECK_THROW(ic != begin_to_index.end() and jr != begin_to_index.end(),
1314 "owner-pinned exchange: a task batch is not one of the split batches");
1315 // the assignment is keyed on the lower triangle, so order the pair
1316 const long i = std::max(ic->second, jr->second);
1317 const long j = std::min(ic->second, jr->second);
1318 auto it = assignment.find({i, j});
1319 owner_map_[{column_begin, row_begin}] =
1320 (it != assignment.end()) ? it->second : (i % nsubworld);
1321 }
1322 }
1323
1324 /// the record role carrying the bra, and the one carrying the vf over a *shared* split
1327
1328 /// \return the rank this task is pinned to, or -1 to leave the choice to the queue
1329 long owner_hint(const Batch& task_batch, const long nsubworld) const override {
1330 if (not owner_pinned or nsubworld <= 0 or owner_map_.empty()) return -1;
1331 MADNESS_CHECK_THROW(task_batch.input.size() >= 2,
1332 "owner-pinned exchange expects two-dimensional task batches");
1333 auto it = owner_map_.find({task_batch.input[0].begin, task_batch.input[1].begin});
1334 return (it != owner_map_.end()) ? it->second : -1;
1335 }
1336
1337
1338 // you need to define the exact argument(s) of operator() as tuple
1339 typedef std::tuple<const std::vector<Function<T, NDIM>>&,
1340 const std::vector<Function<T, NDIM>>&,
1341 const std::vector<Function<T, NDIM>>&> argtupleT;
1342
1343 using resultT = std::vector<Function<T, NDIM>>;
1344
1345 // you need to define an empty constructor for the result
1346 // resultT must implement operator+=(const resultT&)
1347 resultT allocator(World& world, const argtupleT& argtuple) const {
1348 std::size_t n = std::get<0>(argtuple).size();
1350 return result;
1351 }
1352
1353 /// Store the orbitals as owner-pinned batches, one record per batch.
1354
1355 /// Called by the macrotask queue on the universe right after the argument tuple is
1356 /// stored. The batch boundaries and the record keys are derived exactly as the task
1357 /// side derives them, so no manifest has to be communicated.
1358 ///
1359 /// Every rank registers the routing for all records, which is local and needs no
1360 /// communication, and then each owner **pulls** the batches it owns into its own
1361 /// size-1 subworld and serializes them there. That is what spreads the ingest across
1362 /// the owners: serializing centrally instead funnels the whole orbital set through
1363 /// one rank's network interface.
1364 ///
1365 /// A record is stored per *distinct* operand vector, not per role: HF exchange passes one
1366 /// vector as all three and still stores a single set, nemo's bra = R^2 * ket makes two, and
1367 /// three only when all three differ. The symmetric grid shares one split; the asymmetric one
1368 /// puts vf on the column boundaries and bra/ket on the row ones, so vf needs its own record
1369 /// there even when it is the ket.
1370 void store_batches(World& world, World& subworld, Cloud& cloud, const argtupleT& argtuple,
1371 const long nsubworld) {
1372 if (not owner_pinned) return;
1373 // Batch k is owned by rank (k mod nsubworld), so a batch index has to name a
1374 // universe rank, and that only holds with one subworld per rank. Anything else
1375 // would register the routing to the wrong ranks and read the wrong coefficients,
1376 // so say so rather than compute something wrong.
1377 MADNESS_CHECK_THROW(nsubworld == world.size(),
1378 "owner-pinned exchange needs one subworld per rank");
1379 const vecfuncT& vf = std::get<0>(argtuple);
1380 const vecfuncT& mo_bra = std::get<1>(argtuple);
1381 const vecfuncT& mo_ket = std::get<2>(argtuple);
1382 // one fence up front, so store_batch does not need one per function
1383 world.gop.fence();
1384
1385 // A cross-world copy picks its process map from the target world, but anything
1386 // on that path reading the process-wide default would route to universe ranks
1387 // that do not exist in a size-1 subworld. Point the default at the subworld for
1388 // the duration and restore it afterwards.
1389 auto saved_pmap = FunctionDefaults<NDIM>::get_pmap();
1391
1392 std::vector<std::pair<long, vecfuncT>> owned;
1393 // register the routing for one operand set, and pull the batches this rank owns. Batch k
1394 // goes to rank k, which is what puts a column batch on the rank running that column.
1395 auto stage = [&](const vecfuncT& v, const int dim, const std::vector<Batch_1D>& split) {
1396 for (long k = 0; k < long(split.size()); ++k) {
1397 const Batch_1D& r = split[k];
1398 const long record = exchange_batch_record_key(batch_salt_, dim, r);
1399 cloud.register_batch_owner(record, ProcessID(k % nsubworld));
1400 if (k % nsubworld == world.rank()) {
1401 vecfuncT local(r.size());
1402 for (long i = r.begin; i < r.end; ++i)
1403 local[i - r.begin] = copy(subworld, v[i], /*fence=*/false);
1404 owned.emplace_back(record, std::move(local));
1405 }
1406 }
1407 };
1408
1409 // bra and ket are indexed together by the operator's sum over pairs, so wherever both
1410 // are stored they share boundaries
1411 MADNESS_CHECK_THROW(mo_bra.size() == mo_ket.size(),
1412 "exchange: bra and ket are a paired set and must have equal length");
1413 if (symmetric) {
1414 // One split serves every role, so a role whose vector is the ket's needs no record of
1415 // its own. HF exchange therefore still stores exactly one set, while nemo -- whose bra
1416 // is R^2 times its ket -- stores two over the same boundaries.
1417 const std::vector<Batch_1D> split =
1421 if (not vf_shares_ket_) stage(vf, EXCHANGE_BATCH_VF, split);
1422 } else {
1423 // Two splits: vf gets the column boundaries, bra and ket the row ones. vf needs its
1424 // own record even when it is the ket, the two splits having different boundaries.
1425 const std::vector<Batch_1D> columns = exchange_row_owner_split(vf.size(), nsubworld);
1426 const std::vector<Batch_1D> rows = exchange_row_owner_split(mo_bra.size(), nsubworld);
1427 stage(vf, EXCHANGE_BATCH_VF, columns);
1428 stage(mo_ket, EXCHANGE_BATCH_KET, rows);
1429 if (not bra_shares_ket_) stage(mo_bra, EXCHANGE_BATCH_BRA, rows);
1430 }
1431 // the source ranks' comm threads serve the pulls, so a fence on the size-1
1432 // subworld drains this owner's copies
1433 subworld.gop.fence();
1434 for (auto& [record, batch] : owned)
1435 cloud.store_batch(subworld, batch, world.rank(), record, /*fence=*/false);
1436 subworld.gop.fence();
1437
1439 world.gop.fence();
1440 }
1441
1442 /// Request the batch the next task will have to fetch, before computing this one.
1443
1444 /// Called by the queue once per task, before the task body, with the batches of the
1445 /// next task this rank will run. Of that task's two batches one is normally owned here
1446 /// and reads locally, so at most one is worth requesting -- and requesting exactly one
1447 /// keeps the in-flight count within the bound PrefetchSlot documents.
1448 ///
1449 /// This is what makes the owner-pinned transport worth its machinery: without it every
1450 /// task pays the full latency of its remote batch with nothing to overlap it against.
1451 /// \param mo_ket unused: the salt it used to be derived from is carried on the task.
1452 /// It stays in the signature because the queue's detection trait matches
1453 /// on it (has_sym_pipeline_advance_v).
1454 void sym_pipeline_advance(World& subworld, const vecfuncT&,
1455 const Batch_1D& next_col, const Batch_1D& next_row,
1456 const bool has_next) const {
1457 if (not owner_pinned) return;
1458 ensure_cache_world(subworld);
1459 // hand the previous task's request to this task, which is the one that reads it.
1460 // Retiring an unconsumed request is safe rather than merely tolerated: the reply
1461 // still lands, fills a result nobody reads, and the transport drops its pending
1462 // entry, so the cost is one wasted transfer and nothing is left dangling.
1465 if (not has_next or cloud_ptr == nullptr) return;
1466 Cloud& cloud = *cloud_ptr;
1467 const long salt = batch_salt_;
1468 // Always the ket's record: it is the one role stored unconditionally, in both grids and on
1469 // whichever split the range belongs to, so requesting it can never name a record nobody
1470 // holds. Symmetric: either of the task's two ranges may be the remote one, so try both.
1471 // Asymmetric: only the row rotates, the column being held on this rank.
1472 const std::vector<Batch_1D> candidates =
1473 symmetric ? std::vector<Batch_1D>{next_col, next_row}
1474 : std::vector<Batch_1D>{next_row};
1475 for (const auto& r : candidates) {
1476 const long record = exchange_batch_record_key(salt, EXCHANGE_BATCH_KET, r);
1477 if (cloud.batch_owner(record) == universe_rank_) continue; // reads locally
1478 if (batch_cache_.contains(record)) continue; // already resident
1479 if (prefetch_current_.valid and prefetch_current_.key == record) continue;
1480 prefetch_next_.key = record;
1481 prefetch_next_.fut = std::make_shared<Future<batch_bytesT>>(
1482 cloud.request_batch_bytes_async(record));
1483 prefetch_next_.valid = true;
1484 break; // one per task
1485 }
1486 }
1487
1488 /// the owner-pinned path fetches its operand batches from the cloud itself
1489 bool handles_own_data_movement() const override { return owner_pinned; }
1490
1491 /// Drop the cached batches while the subworld holding them is still alive.
1492
1493 /// Leaving it to ensure_cache_world to notice a new subworld is too late: by then the
1494 /// cached functions refer to a destroyed world, and merely releasing them walks into
1495 /// it.
1496 void cleanup() override {
1498 cache_world_id_ = -1;
1499 // released here, while the subworld and node world still exist
1500 Kf_local_.clear();
1501 Kf_local_initialized_ = false;
1502 Kf_local_world_id_ = -1;
1503 Kf_node_.clear();
1504 Kf_node_initialized_ = false;
1505 Kf_node_world_id_ = -1;
1506 finalize_stage1_done_ = false;
1508 // Both reducers go too, for the reason given at their declaration. Rebuilding one per
1509 // application costs a WorldObject construction, which is nothing beside an
1510 // application, and it also removes the shutdown hazard of a static outliving its
1511 // world.
1512 universe_reducer_.reset();
1514 node_reducer_.reset();
1516 // cost_reference_ deliberately survives: it is what the next call places against.
1517 // cost_this_call_ survives too, until the caller has summed and committed it.
1518 }
1519
1520 /// true if the task sums its own tile results and drains them in the finalize, rather
1521 /// than the queue moving every tile result into the universe result by itself
1522 bool accumulates_own_output() const override { return owner_pinned; }
1523
1524 /// true if the drain goes subworld -> node -> universe rather than straight to the
1525 /// universe, so only one rank per node scatters across nodes
1526 /// not an override: the queue reaches this through its optional-hook detection, since
1527 /// the virtual it feeds lives on the internal task rather than on this base
1529 return owner_pinned and accumulation_mode_ == 2;
1530 }
1531
1532 /// The result entries this tile actually wrote.
1533
1534 /// operator() scatters into a full-width Kf and leaves everything else zero, so summing all
1535 /// `nresult` entries would gaxpy mostly zeros -- a per-tile cost proportional to the whole
1536 /// result vector. Every tile writes its column range; a symmetric off-diagonal tile also
1537 /// writes its row range, reusing each intermediate for the transposed element, whereas an
1538 /// asymmetric tile contributes to its column alone. A full-size or absent range falls back
1539 /// to all of them.
1540 ///
1541 /// The result must be a *set*: the caller gaxpys one entry per index, so a repeated index is
1542 /// added twice. The two ranges do overlap in the asymmetric case, coming from separate splits
1543 /// of different lengths rather than from one split, where they are always equal or disjoint.
1544 std::vector<long> touched_result_indices() const {
1545 std::vector<long> idx;
1546 auto add_range = [&](const Batch_1D& b) {
1547 const long s = b.is_full_size() ? 0 : b.begin;
1548 const long e = b.is_full_size() ? long(nresult) : b.end;
1549 for (long i = s; i < e and i < long(nresult); ++i) idx.push_back(i);
1550 };
1551 if (batch.input.empty()) {
1552 for (long i = 0; i < long(nresult); ++i) idx.push_back(i);
1553 return idx;
1554 }
1555 add_range(batch.input[0]);
1556 if (symmetric and batch.input.size() > 1 and not (batch.input[1] == batch.input[0]))
1557 add_range(batch.input[1]);
1558 std::sort(idx.begin(), idx.end());
1559 idx.erase(std::unique(idx.begin(), idx.end()), idx.end());
1560 return idx;
1561 }
1562
1563 /// sum one tile's result into this subworld's accumulator
1564 void accumulate_locally(World& subworld, const vecfuncT& result_subworld) const {
1565 const long wid = long(subworld.id());
1566 if (not Kf_local_initialized_ or Kf_local_world_id_ != wid) {
1568 Kf_local_initialized_ = true;
1569 Kf_local_world_id_ = wid;
1570 }
1571 // shallow handles for just the entries this tile wrote; the rest are structurally
1572 // zero, so skipping them is not an approximation
1573 const std::vector<long> touched = touched_result_indices();
1574 vecfuncT rs_sub, kf_sub;
1575 rs_sub.reserve(touched.size());
1576 kf_sub.reserve(touched.size());
1577 for (long i : touched) { rs_sub.push_back(result_subworld[i]); kf_sub.push_back(Kf_local_[i]); }
1578 if (rs_sub.empty()) return;
1579 const TreeState op_state =
1580 rs_sub[0].get_impl()->get_tensor_type() == TT_FULL ? compressed : reconstructed;
1581 change_tree_state(rs_sub, op_state);
1582 gaxpy(1.0, kf_sub, 1.0, rs_sub, false); // mutates kf_sub[k] == Kf_local_[touched[k]]
1583 }
1584
1585 /// Collectively (re)build the node-shared accumulator in the node world.
1586
1587 /// Must be reached by every rank of `nodeworld`, since constructing a Function is
1588 /// collective; the queue drives this uniformly across the replicated task list, so the
1589 /// initialized flag flips in lockstep. The process map is passed explicitly because the
1590 /// process-wide default is the subworld's during the finalize -- inheriting it would map
1591 /// keys to subworld rank indices for functions that live in the node world.
1592 void ensure_node_accumulator(World& nodeworld) const {
1593 const long wid = long(nodeworld.id());
1594 if (Kf_node_initialized_ and Kf_node_world_id_ == wid) return;
1595 auto node_pmap = FunctionDefaults<NDIM>::make_default_pmap(nodeworld);
1596 Kf_node_.resize(nresult);
1597 for (long i = 0; i < nresult; ++i)
1599 .pmap(node_pmap)
1600 .compressed(true)
1601 .fence(false));
1602 nodeworld.gop.fence();
1603 Kf_node_initialized_ = true;
1604 Kf_node_world_id_ = wid;
1605 }
1606
1607 /// reduce this subworld's accumulator into the node-shared one
1608 void finalize_stage1(World& subworld, World* nodeworld) {
1609 if (not nodeworld) return; // one node: stage 2 drains directly
1610 if (finalize_stage1_done_) return;
1611 finalize_stage1_done_ = true;
1612 ensure_node_accumulator(*nodeworld); // collective on the node
1614 vecfuncT empty;
1615 vecfuncT& src = Kf_local_initialized_ ? Kf_local_ : empty;
1616 coalesced_gaxpy<T, NDIM>(*nodeworld, get_node_reducer(*nodeworld),
1617 Kf_node_, src, T(1.0), finalize_chunk_entries());
1618 }
1619
1620 /// drain into the universe result, from the node accumulator if there is one
1621 void finalize_stage2(World& subworld, World* nodeworld, vecfuncT& universe_result) {
1622 if (finalize_universe_done_) return;
1624 if (universe_result.empty()) return;
1625 World& universe = universe_result.front().world();
1626 vecfuncT empty;
1627 vecfuncT* src = &empty;
1628 if (nodeworld) {
1629 if (Kf_node_initialized_) src = &Kf_node_;
1630 } else {
1633 src = &Kf_local_;
1634 }
1635 }
1636 // every rank reaches this, including ones with nothing to send -- coalesced_gaxpy
1637 // is collective on the universe
1639 universe_result, *src, T(1.0), finalize_chunk_entries());
1640 }
1641
1642
1643 std::vector<Function<T, NDIM>>
1644 operator()(const std::vector<Function<T, NDIM>>& vf_batch, // will be batched (column)
1645 const std::vector<Function<T, NDIM>>& bra_batch, // will be batched (row)
1646 const std::vector<Function<T, NDIM>>& vket) { // will not be batched
1647
1648 // the operands are not necessarily this world's: on the owner-pinned path the
1649 // queue leaves them in the universe and the task fetches what it needs
1650 MADNESS_CHECK_THROW(subworld_ptr != nullptr, "MacroTaskExchangeSimple: subworld_ptr is null");
1653
1654 bool diagonal_block = batch.input[0] == batch.input[1];
1655 auto& bra_range = batch.input[1]; // corresponds to vbra
1656 auto& vf_range = batch.input[0]; // corresponds to vf_batch
1657
1658 if (vf_range.is_full_size()) vf_range.end = vf_batch.size();
1659 if (bra_range.is_full_size()) bra_range.end = bra_batch.size();
1660
1661 MADNESS_CHECK(vf_range.end <= nresult);
1662 if (symmetric) MADNESS_CHECK(bra_range.end <= nresult);
1663
1664 const double tile_wall_start = wall_time();
1665 const bool profiling = profile_active();
1666 if (profiling) {
1667 prof_.reset();
1668 prof_.task_id = prof_task_seq_++;
1669 prof_.universe_rank = universe_rank_;
1670 prof_.subworld_id = static_cast<unsigned long>(world.id());
1671 prof_.subworld_nrank = world.size();
1674 prof_.diagonal = diagonal_block;
1675 prof_.row_begin = bra_range.begin; prof_.row_end = bra_range.end;
1676 prof_.col_begin = vf_range.begin; prof_.col_end = vf_range.end;
1677 prof_.wall_start = tile_wall_start;
1678 }
1679
1680 // Owner-pinned: fetch this task's operands from the cloud, one request per role and
1681 // range. Roles that share a record resolve to the same key, so the repeats are cache
1682 // hits rather than transfers.
1683 vecfuncT bra_owned, vf_owned, ket_row_owned, ket_column_owned;
1684 const vecfuncT* bra_work = &bra_batch;
1685 const vecfuncT* vf_work = &vf_batch;
1686 if (owner_pinned) {
1687 MADNESS_CHECK_THROW(cloud_ptr != nullptr, "owner-pinned exchange: cloud_ptr is null");
1688 Cloud& cloud = *cloud_ptr;
1689 const long salt = batch_salt_;
1690 // copy the handles out of the cache: the reference is only good until the
1691 // entry is evicted, and the second fetch may evict the first
1692 if (symmetric) {
1693 // One split, so every role is available over either range. Where the roles alias
1694 // the ket these resolve to the same record and the repeats are cache hits, which
1695 // is why HF exchange pays nothing for the generality.
1696 bra_owned = fetch_batch(world, cloud,
1697 exchange_batch_record_key(salt, bra_role(), bra_range));
1698 vf_owned = fetch_batch(world, cloud,
1699 exchange_batch_record_key(salt, vf_role(), vf_range));
1700 ket_row_owned = fetch_batch(world, cloud,
1702 ket_column_owned = diagonal_block
1703 ? ket_row_owned // one range, so one batch
1704 : fetch_batch(world, cloud,
1706 } else {
1707 // The column batch is held: this task runs on the rank owning it, so the fetch
1708 // is a cache hit and those coefficients never move. The row batch is the one
1709 // that rotates, and it carries bra and ket over the same range.
1710 vf_owned = fetch_batch(world, cloud,
1712 bra_owned = fetch_batch(world, cloud,
1713 exchange_batch_record_key(salt, bra_role(), bra_range));
1714 ket_row_owned = fetch_batch(world, cloud,
1716 }
1717 bra_work = &bra_owned;
1718 vf_work = &vf_owned;
1719 }
1720 // everything up to here was getting the operands in hand; everything after is compute
1721 const double compute_wall_start = wall_time();
1722 const double compute_cpu_start = process_cpu_time();
1723 if (profiling) prof_.wait_for_data_wall = compute_wall_start - tile_wall_start;
1724
1725 // the ket comes from its own record when pinned, and is sliced from the unbatched argument
1726 // otherwise, which is the only form available without the batch store
1727 const vecfuncT ket_rows = owner_pinned ? ket_row_owned : bra_range.copy_batch(vket);
1728
1729 if (symmetric and diagonal_block) {
1730 vecfuncT resultcolumn = compute_diagonal_batch_in_symmetric_matrix(world, ket_rows, *bra_work,
1731 *vf_work);
1732
1733 for (int i = vf_range.begin; i < vf_range.end; ++i){
1734 Kf[i] += resultcolumn[i - vf_range.begin];}
1735
1736 } else if (symmetric and not diagonal_block) {
1737 const vecfuncT ket_columns = owner_pinned ? ket_column_owned
1738 : vf_range.copy_batch(vket);
1739 auto[resultcolumn, resultrow]=compute_offdiagonal_batch_in_symmetric_matrix(world, ket_rows,
1740 ket_columns,
1741 *bra_work, *vf_work);
1742
1743 for (int i = bra_range.begin; i < bra_range.end; ++i){
1744 Kf[i] += resultcolumn[i - bra_range.begin];}
1745 for (int i = vf_range.begin; i < vf_range.end; ++i){
1746 Kf[i] += resultrow[i - vf_range.begin];}
1747 } else {
1748 vecfuncT resultcolumn = compute_batch_in_asymmetric_matrix(world, ket_rows,
1749 *bra_work, *vf_work);
1750 for (int i = vf_range.begin; i < vf_range.end; ++i)
1751 Kf[i] += resultcolumn[i - vf_range.begin];
1752 }
1753
1754 // this tile's cost, for the next call's placement. Keyed by its batch pair, so the
1755 // reference survives a different partition only if the pair count matches -- which
1756 // prepare_owner_assignment checks before using it.
1757 if (profiling) {
1758 prof_.compute_wall = wall_time() - compute_wall_start;
1759 prof_.compute_cpu = process_cpu_time() - compute_cpu_start;
1760 prof_.wall_end = wall_time();
1761 prof_.peak_rss_gb = get_rss_usage_in_GB();
1762 // one record per task, from the rank that ran it
1763 if (world.rank() == 0) exch_write_task_profile(prof_);
1764 }
1765
1766 if (owner_pinned and not cost_this_call_.empty()) {
1767 const auto ic = batch_begin_to_index_.find(vf_range.begin);
1768 const auto jr = batch_begin_to_index_.find(bra_range.begin);
1769 if (ic != batch_begin_to_index_.end() and jr != batch_begin_to_index_.end()) {
1770 const long t = exchange_sym_tri(ic->second, jr->second);
1771 if (t < long(cost_this_call_.size()))
1772 cost_this_call_[t] += wall_time() - tile_wall_start;
1773 }
1774 }
1775 return Kf;
1776 }
1777
1778 /// compute a batch of the exchange matrix, with identical ranges, exploiting the matrix symmetry
1779
1780 /// \param subworld the world we're computing in
1781 /// \param cloud where to store the results
1782 /// \param bra_batch the bra batch of orbitals (including the nuclear correlation factor square)
1783 /// \param ket_batch the ket batch of orbitals, i.e. the orbitals to premultiply with
1784 /// \param vf_batch the argument of the exchange operator
1785 /// Streams the tile one row at a time, so only the intermediates of a single row
1786 /// are live at once where computing the tile in one go holds the whole triangle.
1787 /// Row i builds N_ij = P(bra[i] vf[j]) for j <= i, adds ket[i] N_ij to column j,
1788 /// and adds the mirrored ket[j] N_ij to column i.
1790 const vecfuncT& ket_batch, // is batched
1791 const vecfuncT& bra_batch, // is batched
1792 const vecfuncT& vf_batch // is batched
1793 ) const {
1794 MADNESS_CHECK_THROW(ket_batch.size() == bra_batch.size(),
1795 "symmetric diagonal tile: ket/bra batch size mismatch");
1796 MADNESS_CHECK_THROW(vf_batch.size() == bra_batch.size(),
1797 "symmetric diagonal tile: vf/bra batch size mismatch");
1798
1799 const long n = long(vf_batch.size());
1800 vecfuncT resultcolumn = zero_functions_compressed<T, NDIM>(subworld, n);
1801 auto poisson = Exchange<double, 3>::ExchangeImpl::set_poisson(subworld, lo);
1802 const bool screen = apply_screen_;
1803 // the multipliers' sup bounds, once for the tile
1804 const exchange_sup_bounds_t<NDIM> sup = screen ? exchange_sup_bounds(subworld, ket_batch)
1806
1807 // per-stage wall, for the profiler only; `tick` is a no-op when it is off
1808 const bool prof_on = profile_active();
1809 auto tick = [&](double& acc, const double t0) { if (prof_on) acc += wall_time() - t0; };
1810
1811 for (long i = 0; i < n; ++i) {
1812 double cpu0 = cpu_time();
1813 double w0 = prof_on ? wall_time() : 0.0;
1814 const vecfuncT vf_subset(vf_batch.begin(), vf_batch.begin() + i + 1);
1815 vecfuncT psif = mul_sparse(subworld, bra_batch[i], vf_subset, mul_tol);
1816 tick(prof_.mul1_wall, w0);
1817 w0 = prof_on ? wall_time() : 0.0;
1818 truncate(subworld, psif);
1819 tick(prof_.truncate_wall, w0);
1820 double cpu1 = cpu_time();
1821 mul1_timer += long((cpu1 - cpu0) * 1000l);
1822
1823 cpu0 = cpu_time();
1824 w0 = prof_on ? wall_time() : 0.0;
1825 if (screen) {
1826 // P(bra_i vf_j) is multiplied by ket_i (into column j) and by ket_j (into column i)
1827 std::vector<apply_screen_t<NDIM>> screens(i + 1);
1828 for (long j = 0; j <= i; ++j) screens[j] = exchange_apply_screen<NDIM>({sup[i], sup[j]});
1829 psif = apply(subworld, *poisson.get(), psif, screens);
1830 } else {
1831 psif = apply(subworld, *poisson.get(), psif);
1832 }
1833 tick(prof_.apply_wall, w0);
1834 w0 = prof_on ? wall_time() : 0.0;
1835 truncate(subworld, psif);
1836 tick(prof_.truncate_wall, w0);
1837 cpu1 = cpu_time();
1838 apply_timer += long((cpu1 - cpu0) * 1000l);
1839
1840 // rows overlap in the columns they touch, so this row's contribution is
1841 // assembled on its own and accumulated
1842 cpu0 = cpu_time();
1844 double w1 = prof_on ? wall_time() : 0.0;
1845 vecfuncT row_contrib = mul_sparse(subworld, ket_batch[i], psif, mul_tol);
1846 tick(prof_.mul2_wall, w1);
1847 compress(subworld, row_contrib);
1848 for (long j = 0; j <= i; ++j) update[j] += row_contrib[j];
1849 for (long j = 0; j < i; ++j) {
1850 w1 = prof_on ? wall_time() : 0.0;
1851 vecfuncT mirrored = mul_sparse(subworld, ket_batch[j], vecfuncT(1, psif[j]), mul_tol);
1852 tick(prof_.mul2_wall, w1);
1853 compress(subworld, mirrored);
1854 update[i] += mirrored[0];
1855 }
1856 gaxpy(subworld, 1.0, resultcolumn, 1.0, update);
1857 cpu1 = cpu_time();
1858 mul2_timer += long((cpu1 - cpu0) * 1000l);
1859 }
1860 // !! NO TRUNCATION AT THIS POINT !!
1861 return resultcolumn;
1862 }
1863
1864 /// compute a batch of the exchange matrix, with non-identical ranges
1865
1866 /// \param subworld the world we're computing in
1867 /// \param cloud where to store the results
1868 /// \param bra_batch the bra batch of orbitals (including the nuclear correlation factor square)
1869 /// \param ket_batch the ket batch of orbitals, i.e. the orbitals to premultiply with
1870 /// \param vf_batch the argument of the exchange operator
1872 const vecfuncT& ket_batch,
1873 const vecfuncT& bra_batch,
1874 const vecfuncT& vf_batch) const {
1875 double symmetric = false;
1876 auto poisson = Exchange<double, 3>::ExchangeImpl::set_poisson(subworld, lo);
1877 return Exchange<T, NDIM>::ExchangeImpl::compute_K_tile(subworld, bra_batch, ket_batch, vf_batch, poisson, symmetric,
1879 }
1880
1881 /// compute a batch of the exchange matrix, with non-identical ranges
1882
1883 /// The caller supplies the ket over each of the tile's two ranges: it is the one
1884 /// that knows the ranges, and where those orbitals come from depends on how the
1885 /// operands were supplied, which is not the kernel's concern.
1886 std::pair<vecfuncT, vecfuncT> compute_offdiagonal_batch_in_symmetric_matrix(World& subworld,
1887 const vecfuncT& ket_rows, // ket over the bra/row range
1888 const vecfuncT& ket_columns, // ket over the vf/column range
1889 const vecfuncT& bra_batch, // batched
1890 const vecfuncT& vf_batch) const; // batched
1891
1892 };
1893
1895
1897 double lo = 1.e-4;
1898 double mul_tol = 1.e-7;
1899 bool symmetric = false;
1901
1902 /// custom partitioning for the exchange operator in exchangeoperator.h
1904 public:
1908 };
1909
1910 public:
1911 MacroTaskExchangeRow(const long nresult, const double lo, const double mul_tol, const Algorithm algorithm)
1912 : nresult(nresult), lo(lo), mul_tol(mul_tol), algorithm_(algorithm) {
1914 name="MacroTaskExchangeRow";
1915 }
1916
1917 // you need to define the exact argument(s) of operator() as tuple
1918 typedef std::tuple<const std::vector<Function<T, NDIM>>&,
1919 const std::vector<Function<T, NDIM>>&,
1920 const std::vector<Function<T, NDIM>>&> argtupleT;
1921
1922 using resultT = std::vector<Function<T, NDIM>>;
1923
1924 // you need to define an empty constructor for the result
1925 // resultT must implement operator+=(const resultT&)
1926 resultT allocator(World& world, const argtupleT& argtuple) const {
1927 std::size_t n = std::get<0>(argtuple).size();
1929 return result;
1930 }
1931
1932 /// compute exchange row-wise for a fixed orbital phi_i of vket
1933
1934 /// create 2 worlds: one fetches the function coefficients from the universe, the other
1935 /// does the computation, then swap. The result is copied back to the universe
1936 std::vector<Function<T, NDIM>>
1937 operator()(const std::vector<Function<T, NDIM>>& vket,
1938 const std::vector<Function<T, NDIM>>& mo_bra,
1939 const std::vector<Function<T, NDIM>>& mo_ket) {
1940 std::vector<Function<T,NDIM>> result;
1942 result=row_fetch_compute(vket,mo_bra,mo_ket);
1944 result=row(vket,mo_bra,mo_ket);
1945 } else {
1946 MADNESS_EXCEPTION("unknown algorithm in Exchange::MacroTaskExchangeRow::operator()",1);
1947 }
1948 return result;
1949 }
1950
1951 std::vector<Function<T,NDIM>>
1952 row(const std::vector<Function<T, NDIM>>& vket,
1953 const std::vector<Function<T, NDIM>>& mo_bra,
1954 const std::vector<Function<T, NDIM>>& mo_ket) {
1955
1956 double cpu0, cpu1;
1957 World& world = vket.front().world();
1958
1962
1963 // !! NO !! vket is batched, starts at batch.input[0].begin
1964 // auto& i = batch.input[0].begin;
1965 long i=0;
1966 MADNESS_CHECK_THROW(vket.size()==1,"out-of-bounds error in Exchange::MacroTaskExchangeRow::operator()");
1967 size_t min_tile = 10;
1968 size_t ntile = std::min(mo_bra.size(), min_tile);
1969
1970 for (size_t ilo=0; ilo<mo_bra.size(); ilo+=ntile){
1971 cpu0 = cpu_time();
1972 size_t iend = std::min(ilo+ntile,mo_bra.size());
1973 vecfuncT tmp_mo_bra(mo_bra.begin()+ilo,mo_bra.begin()+iend);
1974 auto tmp_psif = mul_sparse(world, vket[i], tmp_mo_bra, mul_tol);
1975 truncate(world, tmp_psif);
1976 cpu1 = cpu_time();
1977 mul1_timer += long((cpu1 - cpu0) * 1000l);
1978
1979 cpu0 = cpu_time();
1980 tmp_psif = apply(world, *poisson.get(), tmp_psif);
1981 truncate(world, tmp_psif);
1982 cpu1 = cpu_time();
1983 apply_timer += long((cpu1 - cpu0) * 1000l);
1984
1985 cpu0 = cpu_time();
1986 vecfuncT tmp_mo_ket(mo_ket.begin()+ilo,mo_ket.begin()+iend);
1987 // screen the second multiplication too, at the same tolerance as the first
1988 auto tmp_Kf = dot_sparse(world, tmp_mo_ket, tmp_psif, mul_tol, true, true);
1989 cpu1 = cpu_time();
1990 mul2_timer += long((cpu1 - cpu0) * 1000l);
1991
1992 Kf[0] += tmp_Kf;
1993 truncate(world, Kf);
1994 }
1995
1996 return Kf;
1997 }
1998
1999 std::vector<Function<T,NDIM>>
2000 row_fetch_compute(const std::vector<Function<T, NDIM>>& vket,
2001 const std::vector<Function<T, NDIM>>& mo_bra,
2002 const std::vector<Function<T, NDIM>>& mo_ket) {
2003
2005 double total_execution_time=0.0;
2006 double total_fetch_time=0.0;
2007 double total_fetch_spawn_time=0.0;
2008
2010 {
2011 // create the two worlds that will be used for fetching and computing
2012 // std::shared_ptr<World> executing_world(subworld_ptr);
2013 double cpu0=cpu_time();
2014 SafeMPI::Intracomm comm = subworld_ptr->mpi.comm();
2015 std::shared_ptr<World> fetching_world(new World(comm.Clone()));
2016 std::shared_ptr<World> executing_world(new World(comm.Clone()));
2017 double cpu1=cpu_time();
2018 print("time to create two worlds:",cpu1-cpu0,"seconds");
2019 print("executing_world.id()",executing_world->id(),"fetching_world.id()",fetching_world->id(),"in MacroTaskExchangeRow");
2020
2021 {
2022 auto poisson1 = Exchange<double, 3>::ExchangeImpl::set_poisson(*executing_world, lo);
2023 auto poisson2 = Exchange<double, 3>::ExchangeImpl::set_poisson(*fetching_world, lo);
2024
2025 functionT phi1=copy(*executing_world,vket[0]);
2026 functionT phi2=copy(*fetching_world,vket[0]);
2027
2028 // !! NO !! vket is batched, starts at batch.input[0].begin
2029 // auto& i = batch.input[0].begin;
2030 MADNESS_CHECK_THROW(vket.size()==1,"out-of-bounds error in Exchange::MacroTaskExchangeRow::operator()");
2031 size_t min_tile = 10;
2032 size_t ntile = std::min(mo_bra.size(), min_tile);
2033
2034 struct Tile {
2035 size_t ilo;
2036 size_t iend;
2037 };
2038
2039
2040 // copy the data from the universe bra and ket to subworld bra and ket
2041 // returns a pair of vectors in the subworld which are still awaiting the function coefficients
2042 auto fetch_data = [&](World& world, const Tile& tile) {
2043 MADNESS_CHECK_THROW(mo_bra.size()==mo_ket.size(),
2044 "bra and ket size mismatch in Exchange::MacroTaskExchangeRow::execute()");
2045
2046 std::size_t sz=tile.iend-tile.ilo;
2047 vecfuncT subworld_bra(sz);
2048 vecfuncT subworld_ket;
2049 for (size_t i=tile.ilo; i<tile.iend; ++i) {
2050 auto f=copy(world,mo_bra[i],false);
2051 subworld_bra[i-tile.ilo]=f;
2052 subworld_ket.push_back(copy(world, mo_ket[i],false));
2053 }
2054 return std::make_pair(subworld_bra,subworld_ket);
2055 };
2056
2057 // apply the exchange operator on phi for a a tile of mo_bra and mo_ket
2058 auto execute = [&](World& world, auto poisson, const functionT& phi, const vecfuncT& mo_bra, const vecfuncT& mo_ket) {
2059 MADNESS_CHECK_THROW(mo_bra.size()==mo_ket.size(),
2060 "bra and ket size mismatch in Exchange::MacroTaskExchangeRow::execute()");
2061
2062 auto world_id=world.id();
2063 auto phi_id=phi.world().id();
2064 auto bra_id=mo_bra.front().world().id();
2065 auto ket_id=mo_ket.front().world().id();
2066 std::string msg="world mismatch in Exchange::MacroTaskExchangeRow::execute(): ";
2067 msg+="world.id()="+std::to_string(world_id)+", ";
2068 msg+="phi.world().id()="+std::to_string(phi_id)+", ";
2069 msg+="bra.world().id()="+std::to_string(bra_id)+", ";
2070 msg+="ket.world().id()="+std::to_string(ket_id);
2071 if (not (world_id==phi_id && world_id==bra_id && world_id==ket_id)) {
2072 print(msg);
2073 }
2074 MADNESS_CHECK_THROW(world_id==phi_id && world_id==bra_id && world_id==ket_id,msg.c_str());
2075
2076 double cpu0 = cpu_time();
2077 auto tmp_psif = mul_sparse(world, phi, mo_bra, mul_tol);
2078 truncate(world, tmp_psif);
2079 double cpu1 = cpu_time();
2080 mul1_timer += long((cpu1 - cpu0) * 1000l);
2081
2082 cpu0 = cpu_time();
2083 tmp_psif = apply(world, *poisson.get(), tmp_psif);
2084 truncate(world, tmp_psif);
2085 cpu1 = cpu_time();
2086 apply_timer += long((cpu1 - cpu0) * 1000l);
2087
2088 cpu0 = cpu_time();
2089 auto tmp_Kf = dot(world, mo_ket, tmp_psif);
2090 cpu1 = cpu_time();
2091 mul2_timer += long((cpu1 - cpu0) * 1000l);
2092
2093 return tmp_Kf.truncate();
2094
2095 };
2096
2097 std::vector<Tile> tiles;
2098 for (size_t ilo=0; ilo<mo_bra.size(); ilo+=ntile) {
2099 tiles.push_back(Tile{ilo,std::min(ilo+ntile,mo_bra.size())});
2100 }
2101
2102 vecfuncT tmp_mo_bra1,tmp_mo_ket1;
2103 vecfuncT tmp_mo_bra2,tmp_mo_ket2;
2104
2105 for (size_t itile=0; itile<tiles.size(); ++itile) {
2106 Tile& tile = tiles[itile];
2107
2108 if (itile==0) {
2109 double t0=cpu_time();
2110 print("fetching tile",tile.ilo,"into world",executing_world->id());
2111 std::tie(tmp_mo_bra1,tmp_mo_ket1)=fetch_data(*executing_world,tiles[itile]);
2112 fetching_world->gop.set_forbid_fence(false);
2113 double t2=cpu_time();
2114 executing_world->gop.fence();
2115 double t1=cpu_time();
2116 total_fetch_time += (t1 - t0);
2117 total_fetch_spawn_time += (t2 - t0);
2118 }
2119
2120 double t0=cpu_time();
2121 fetching_world->gop.set_forbid_fence(true);
2122 if (itile<tiles.size()-1) {
2123 // fetch data into fetching_world while computing in executing_world
2124 print("fetching tile",tiles[itile+1].ilo,"into world",fetching_world->id()," at time ",wall_time());
2125 std::tie(tmp_mo_bra2,tmp_mo_ket2)=fetch_data(*fetching_world,tiles[itile+1]);
2126 }
2127 fetching_world->gop.set_forbid_fence(false);
2128 double t2=cpu_time();
2129 // uncomment the next line to enforce that fetching is finished before executing
2130 // fetching_world->gop.fence();
2131 double t1=cpu_time();
2132 total_fetch_time += (t1 - t0);
2133 total_fetch_spawn_time += (t2 - t0);
2134
2135 print("executing tile",tile.ilo,"in world",executing_world->id());
2136 double dpu0=cpu_time();
2137 Kf[0]+=execute(*executing_world,poisson1,phi1,tmp_mo_bra1,tmp_mo_ket1);
2138 double dpu1=cpu_time();
2139 print("time to execute tile",tile.ilo,"in world",executing_world->id(),dpu1-dpu0,"seconds");
2140 total_execution_time += dpu1-dpu0;
2141
2142 fetching_world->gop.fence();
2143
2144 // change roles of the two worlds
2145 std::swap(poisson1,poisson2);
2146 std::swap(phi1,phi2);
2147 std::swap(tmp_mo_bra2,tmp_mo_bra1);
2148 std::swap(tmp_mo_ket2,tmp_mo_ket1);
2149 std::swap(executing_world,fetching_world);
2150 }
2151 } // objects living in the two worlds must be destroyed before the worlds are freed
2152
2153 // deferred destruction of WorldObjects happens here
2154 fetching_world->gop.fence();
2155 executing_world->gop.fence();
2156 double cpu2=cpu_time();
2157 print("overall time: ",cpu2-cpu0,"seconds");
2158 print("total execution time:",total_execution_time,"seconds");
2159 print("total fetch time:",total_fetch_time,"seconds");
2160 print("total fetch spawn time:",total_fetch_spawn_time,"seconds");
2161 } // worlds are destroyed here
2162
2163 return Kf;
2164 }
2165 };
2166};
2167
2168} /* namespace madness */
2169
2170#endif /* SRC_APPS_CHEM_EXCHANGEOPERATOR_H_ */
Operators for the molecular HF and DFT code.
static const double small
Definition binaryop.cc:117
Definition test_ar.cc:118
Definition test_ar.cc:141
Definition test_ar.cc:170
Wrapper around MPI_Comm. Has a shallow copy constructor; use Create(Get_group()) for deep copy.
Definition safempi.h:645
Intracomm Clone() const
Definition safempi.h:844
Definition macrotaskpartitioner.h:55
long size() const
Definition macrotaskpartitioner.h:71
long end
first and first past last index [begin,end)
Definition macrotaskpartitioner.h:59
long begin
Definition macrotaskpartitioner.h:59
a batch consists of a 2D-input batch and a 1D-output batch: K-batch <- (I-batch, J-batch)
Definition macrotaskpartitioner.h:124
std::vector< Batch_1D > input
Definition macrotaskpartitioner.h:127
cloud class
Definition cloud.h:338
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:1048
ProcessID batch_owner(const keyT record) const
the owner of a batch record; a pmap lookup, no communication
Definition cloud.h:1008
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:783
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:797
Bounded cache of fetched exchange batches, keyed by cloud record key.
Definition exchangeoperator.h:476
std::list< Slot > slots_
Definition exchangeoperator.h:524
void set_transient_capacity(const std::size_t c)
how many non-owned entries may be resident; at least one is always allowed
Definition exchangeoperator.h:479
std::size_t size() const
Definition exchangeoperator.h:514
std::size_t transient_capacity_
Definition exchangeoperator.h:525
void clear()
drop every entry; the capacity setting survives
Definition exchangeoperator.h:512
std::size_t transient_capacity() const
Definition exchangeoperator.h:480
bool contains(const keyT &key) const
Definition exchangeoperator.h:482
std::size_t n_transient() const
Definition exchangeoperator.h:516
const dataT & insert(const keyT &key, dataT &&data, const bool pinned)
Insert as most-recently-used. pinned marks a batch this rank owns.
Definition exchangeoperator.h:499
const dataT * find(const keyT &key)
Definition exchangeoperator.h:488
custom partitioning for the exchange operator in exchangeoperator.h
Definition exchangeoperator.h:1903
resultT allocator(World &world, const argtupleT &argtuple) const
Definition exchangeoperator.h:1926
std::vector< Function< T, NDIM > > row_fetch_compute(const std::vector< Function< T, NDIM > > &vket, const std::vector< Function< T, NDIM > > &mo_bra, const std::vector< Function< T, NDIM > > &mo_ket)
Definition exchangeoperator.h:2000
std::vector< Function< T, NDIM > > resultT
Definition exchangeoperator.h:1922
std::vector< Function< T, NDIM > > operator()(const std::vector< Function< T, NDIM > > &vket, const std::vector< Function< T, NDIM > > &mo_bra, const std::vector< Function< T, NDIM > > &mo_ket)
compute exchange row-wise for a fixed orbital phi_i of vket
Definition exchangeoperator.h:1937
double lo
Definition exchangeoperator.h:1897
bool symmetric
Definition exchangeoperator.h:1899
long nresult
Definition exchangeoperator.h:1896
std::tuple< const std::vector< Function< T, NDIM > > &, const std::vector< Function< T, NDIM > > &, const std::vector< Function< T, NDIM > > & > argtupleT
Definition exchangeoperator.h:1920
std::vector< Function< T, NDIM > > row(const std::vector< Function< T, NDIM > > &vket, const std::vector< Function< T, NDIM > > &mo_bra, const std::vector< Function< T, NDIM > > &mo_ket)
Definition exchangeoperator.h:1952
Algorithm algorithm_
Definition exchangeoperator.h:1900
MacroTaskExchangeRow(const long nresult, const double lo, const double mul_tol, const Algorithm algorithm)
Definition exchangeoperator.h:1911
double mul_tol
Definition exchangeoperator.h:1898
custom partitioning for the exchange operator in exchangeoperator.h
Definition exchangeoperator.h:1131
double compute_priority(const Batch &batch) const override
compute the priority of this task for non-dumb scheduling
Definition exchangeoperator.h:1200
MacroTaskPartitionerExchange(const bool symmetric, const bool owner_pinned=false, const long granularity_level=1)
Definition exchangeoperator.h:1133
partitionT do_partitioning(const std::size_t &vsize1, const std::size_t &vsize2, const std::string policy) const override
override this if you want your own partitioning
Definition exchangeoperator.h:1146
void ensure_cache_world(World &world) const
drop cached batches when the subworld changes; they belong to the old one
Definition exchangeoperator.h:1088
static std::shared_ptr< FinalizeReducer< T, NDIM > > node_reducer_
Definition exchangeoperator.h:1049
vecfuncT compute_diagonal_batch_in_symmetric_matrix(World &subworld, const vecfuncT &ket_batch, const vecfuncT &bra_batch, const vecfuncT &vf_batch) const
compute a batch of the exchange matrix, with identical ranges, exploiting the matrix symmetry
Definition exchangeoperator.h:1789
static long exchange_call_index()
Definition exchangeoperator.h:1233
static void clear_local_caches()
Definition exchangeoperator.h:1055
void finalize_stage1(World &subworld, World *nodeworld)
reduce this subworld's accumulator into the node-shared one
Definition exchangeoperator.h:1608
static void commit_cost_reference()
make this call's measured costs the reference for the next one
Definition exchangeoperator.h:1237
static long batch_cache_hits()
Definition exchangeoperator.h:1227
void cleanup() override
Drop the cached batches while the subworld holding them is still alive.
Definition exchangeoperator.h:1496
static std::vector< double > cost_reference_
What each task cost last time, to place them better this time.
Definition exchangeoperator.h:1018
bool wants_node_local_reduction() const
Definition exchangeoperator.h:1528
static ExchangeBatchLRU< long, vecfuncT > batch_cache_
Batches fetched from the cloud, reused across the tasks that run in one subworld.
Definition exchangeoperator.h:984
static FinalizeReducer< T, NDIM > & get_universe_reducer(World &world)
Definition exchangeoperator.h:1071
void finalize_stage2(World &subworld, World *nodeworld, vecfuncT &universe_result)
drain into the universe result, from the node accumulator if there is one
Definition exchangeoperator.h:1621
static vecfuncT Kf_local_
Definition exchangeoperator.h:1033
static std::vector< double > & cost_this_call()
Definition exchangeoperator.h:1232
bool profile_active() const
per-task profiling on for this task?
Definition exchangeoperator.h:1231
long nresult
Definition exchangeoperator.h:943
static std::map< long, long > batch_begin_to_index_
batch offset -> index
Definition exchangeoperator.h:1020
double mul_tol
Definition exchangeoperator.h:945
static std::atomic< long > batch_cache_hits_
Definition exchangeoperator.h:986
bool apply_screen_
screen the Poisson apply by the multipliers' sizes in the destination box (applyscreen....
Definition exchangeoperator.h:976
vecfuncT compute_batch_in_asymmetric_matrix(World &subworld, const vecfuncT &ket_batch, const vecfuncT &bra_batch, const vecfuncT &vf_batch) const
compute a batch of the exchange matrix, with non-identical ranges
Definition exchangeoperator.h:1871
void ensure_node_accumulator(World &nodeworld) const
Collectively (re)build the node-shared accumulator in the node world.
Definition exchangeoperator.h:1592
int accumulation_mode_
Definition exchangeoperator.h:967
static FinalizeReducer< T, NDIM > & get_node_reducer(World &world)
Definition exchangeoperator.h:1079
void prepare_owner_assignment(const MacroTaskPartitioner::partitionT &partition, const long nsubworld)
Assign every task to the rank that will own one of its two batches.
Definition exchangeoperator.h:1249
static bool Kf_local_initialized_
Definition exchangeoperator.h:1034
static PrefetchSlot prefetch_next_
requested during this task
Definition exchangeoperator.h:1008
long universe_rank_
this process's rank in the universe, to recognise the batches it owns
Definition exchangeoperator.h:974
bool symmetric
Definition exchangeoperator.h:946
static long universe_reducer_world_id_
Definition exchangeoperator.h:1048
void sym_pipeline_advance(World &subworld, const vecfuncT &, const Batch_1D &next_col, const Batch_1D &next_row, const bool has_next) const
Request the batch the next task will have to fetch, before computing this one.
Definition exchangeoperator.h:1454
static bool finalize_stage1_done_
each drain happens once per rank, not once per task object
Definition exchangeoperator.h:1052
bool accumulates_own_output() const override
Definition exchangeoperator.h:1522
static long batch_cache_misses()
Definition exchangeoperator.h:1228
static long prof_task_seq_
per-process task counter, for identity only
Definition exchangeoperator.h:1026
MacroTaskExchangeSimple(const long nresult, const double lo, const double mul_tol, const bool symmetric, const bool owner_pinned=false, const long granularity_level=1, const long universe_rank=0, const int accumulation_mode=2, const bool cost_aware=true, const long batch_salt=0, const bool bra_shares_ket=true, const bool vf_shares_ket=true, const bool apply_screen=false)
Definition exchangeoperator.h:1209
void accumulate_locally(World &subworld, const vecfuncT &result_subworld) const
sum one tile's result into this subworld's accumulator
Definition exchangeoperator.h:1564
std::vector< long > touched_result_indices() const
The result entries this tile actually wrote.
Definition exchangeoperator.h:1544
ExchTaskProfile prof_
Definition exchangeoperator.h:1025
bool cost_aware_
place tasks by their measured cost rather than by counting them
Definition exchangeoperator.h:969
static long exchange_call_index_
Definition exchangeoperator.h:1021
std::vector< Function< T, NDIM > > operator()(const std::vector< Function< T, NDIM > > &vf_batch, const std::vector< Function< T, NDIM > > &bra_batch, const std::vector< Function< T, NDIM > > &vket)
Definition exchangeoperator.h:1644
bool owner_pinned
pin each task to a rank that owns one of its batches, over the owner-pinned split
Definition exchangeoperator.h:948
long granularity_level
Definition exchangeoperator.h:949
std::tuple< const std::vector< Function< T, NDIM > > &, const std::vector< Function< T, NDIM > > &, const std::vector< Function< T, NDIM > > & > argtupleT
Definition exchangeoperator.h:1341
bool handles_own_data_movement() const override
the owner-pinned path fetches its operand batches from the cloud itself
Definition exchangeoperator.h:1489
resultT allocator(World &world, const argtupleT &argtuple) const
Definition exchangeoperator.h:1347
bool bra_shares_ket_
Definition exchangeoperator.h:962
static void reset_batch_cache_counters()
Definition exchangeoperator.h:1238
static long Kf_node_world_id_
Definition exchangeoperator.h:1038
std::pair< vecfuncT, vecfuncT > compute_offdiagonal_batch_in_symmetric_matrix(World &subworld, const vecfuncT &ket_rows, const vecfuncT &ket_columns, const vecfuncT &bra_batch, const vecfuncT &vf_batch) const
compute a batch of the exchange matrix, with non-identical ranges
Definition exchangeoperator.cc:416
static long Kf_local_world_id_
Definition exchangeoperator.h:1035
std::vector< Function< T, NDIM > > resultT
Definition exchangeoperator.h:1343
static long batch_prefetch_hits()
Definition exchangeoperator.h:1229
double lo
Definition exchangeoperator.h:944
static std::atomic< long > batch_cache_misses_
Definition exchangeoperator.h:987
int bra_role() const
the record role carrying the bra, and the one carrying the vf over a shared split
Definition exchangeoperator.h:1325
static bool finalize_universe_done_
Definition exchangeoperator.h:1053
static std::vector< double > cost_this_call_
rank-local, summed after the call
Definition exchangeoperator.h:1019
std::map< std::pair< long, long >, long > owner_map_
Definition exchangeoperator.h:972
static bool Kf_node_initialized_
Definition exchangeoperator.h:1037
const vecfuncT & fetch_batch(World &world, Cloud &cloud, const long record) const
Fetch one owner-pinned batch, from the local cache if it is resident.
Definition exchangeoperator.h:1102
static long node_reducer_world_id_
Definition exchangeoperator.h:1050
static long cost_matrix_dimension()
number of batches this application split into, which squares to the cost matrix
Definition exchangeoperator.h:1235
void store_batches(World &world, World &subworld, Cloud &cloud, const argtupleT &argtuple, const long nsubworld)
Store the orbitals as owner-pinned batches, one record per batch.
Definition exchangeoperator.h:1370
bool vf_shares_ket_
Definition exchangeoperator.h:963
static PrefetchSlot prefetch_current_
promoted from the previous task
Definition exchangeoperator.h:1007
static std::atomic< long > batch_prefetch_hits_
Definition exchangeoperator.h:988
static long cache_world_id_
Definition exchangeoperator.h:985
static vecfuncT Kf_node_
Definition exchangeoperator.h:1036
static std::size_t finalize_chunk_entries()
entries per chunk in coalesced_gaxpy, sized so one message stays modest at any k
Definition exchangeoperator.h:1063
int vf_role() const
Definition exchangeoperator.h:1326
static std::shared_ptr< FinalizeReducer< T, NDIM > > universe_reducer_
Receiving endpoints for the two drains, one per world they transfer within.
Definition exchangeoperator.h:1047
long batch_salt_
Per-application salt for the batch record keys, from exchange_batch_salt.
Definition exchangeoperator.h:957
long owner_hint(const Batch &task_batch, const long nsubworld) const override
Definition exchangeoperator.h:1329
Definition exchangeoperator.h:634
long batch_granularity_
Definition exchangeoperator.h:927
static std::atomic< long > mul1_timer
timing
Definition exchangeoperator.h:640
Exchange< T, NDIM >::ExchangeAlgorithm Algorithm
Definition exchangeoperator.h:698
bool printtimings() const
Definition exchangeoperator.h:914
MacroTaskInfo macro_task_info
Definition exchangeoperator.h:700
ExchangeImpl & symmetric(const bool flag)
Definition exchangeoperator.h:743
bool cost_aware_assign_
Definition exchangeoperator.h:933
ExchangeImpl & set_printlevel(const long &level)
Definition exchangeoperator.h:767
nlohmann::json statistics
statistics of the Cloud (timings, memory) and of the parameters of this run
Definition exchangeoperator.h:939
static double elapsed_time
Definition exchangeoperator.h:641
void print_timer(World &world) const
Definition exchangeoperator.h:679
ExchangeImpl & set_batch_granularity(const long level)
Definition exchangeoperator.h:772
World & get_world() const
Definition exchangeoperator.h:869
ExchangeImpl & set_macro_task_info(const std::vector< std::string > &info)
Definition exchangeoperator.h:753
double thresh
Definition exchangeoperator.h:922
nlohmann::json get_statistics() const
Definition exchangeoperator.h:871
bool apply_screen_
skip the Poisson apply where the multiplier is negligible in the destination box (applyscreen....
Definition exchangeoperator.h:937
ExchangeImpl & set_macro_task_info(const MacroTaskInfo &info)
Definition exchangeoperator.h:748
long printlevel
Definition exchangeoperator.h:923
static void reset_timer()
Definition exchangeoperator.h:643
vecfuncT mo_bra
is the exchange matrix symmetric? K phi_i = \sum_k \phi_k \int \phi_k \phi_i
Definition exchangeoperator.h:920
double lo
Definition exchangeoperator.h:921
World & world
Definition exchangeoperator.h:917
std::shared_ptr< MacroTaskQ > taskq
Definition exchangeoperator.h:918
Algorithm algorithm_
Definition exchangeoperator.h:699
ExchangeImpl & set_mo_order(const std::string &order)
Definition exchangeoperator.h:792
int accumulation_mode_
Definition exchangeoperator.h:930
Function< T, NDIM > functionT
Definition exchangeoperator.h:635
nlohmann::json gather_statistics() const
return some statistics about the current settings
Definition exchangeoperator.h:874
std::string mo_order_
the order of the orbitals in the batches: as_is, shuffle or balanced (set_mo_order)
Definition exchangeoperator.h:935
bool is_symmetric() const
Definition exchangeoperator.h:736
ExchangeImpl & set_taskq(std::shared_ptr< MacroTaskQ > taskq1)
Definition exchangeoperator.h:738
std::vector< functionT > vecfuncT
Definition exchangeoperator.h:636
double mul_tol
Definition exchangeoperator.h:924
ExchangeImpl & set_cost_aware_assignment(const bool flag)
Definition exchangeoperator.h:778
ExchangeImpl & set_algorithm(const Algorithm &alg)
Definition exchangeoperator.h:762
bool printprogress() const
Definition exchangeoperator.h:913
static std::atomic< long > apply_timer
Definition exchangeoperator.h:638
ExchangeImpl & set_accumulation_mode(const int mode)
Definition exchangeoperator.h:861
ExchangeImpl & set_apply_screen(const bool flag)
Definition exchangeoperator.h:856
vecfuncT mo_ket
MOs for bra and ket.
Definition exchangeoperator.h:920
static vecfuncT compute_K_tile(World &world, const vecfuncT &mo_bra, const vecfuncT &mo_ket, const vecfuncT &vket, std::shared_ptr< real_convolution_3d > poisson, const bool symmetric, const double mul_tol=0.0, const bool apply_screen=false)
computing the upper triangle of the double sum (over vket and the K orbitals)
Definition exchangeoperator.cc:320
ExchangeImpl(World &world, const double lo, const double thresh)
default ctor
Definition exchangeoperator.h:703
std::string info() const
Definition exchangeoperator.h:723
nlohmann::json gather_timings(World &world) const
Definition exchangeoperator.h:652
std::vector< std::size_t > mo_order_permutation() const
Definition exchangeoperator.h:801
bool printtimings_detail() const
Definition exchangeoperator.h:915
bool symmetric_
Definition exchangeoperator.h:919
bool printdebug() const
Definition exchangeoperator.h:912
std::shared_ptr< MacroTaskQ > get_taskq() const
Definition exchangeoperator.h:867
static auto set_poisson(World &world, const double lo, const double econv=FunctionDefaults< 3 >::get_thresh())
Definition exchangeoperator.h:725
static std::atomic< long > mul2_timer
Definition exchangeoperator.h:639
void set_bra_and_ket(const vecfuncT &bra, const vecfuncT &ket)
set the bra and ket orbital spaces, and the occupation
Definition exchangeoperator.h:718
Exchange(World &world, const double lo, const double thresh=FunctionDefaults< NDIM >::get_thresh())
ctor
Definition exchangeoperator.cc:494
static std::string to_string(const ExchangeAlgorithm alg)
Definition SCFOperators.h:145
ExchangeAlgorithm
Definition SCFOperators.h:118
@ fetch_compute
Definition SCFOperators.h:119
@ multiworld_efficient_row
Definition SCFOperators.h:119
Function< T, NDIM > operator()(const Function< T, NDIM > &ket) const
Definition SCFOperators.h:223
std::vector< functionT > vecfuncT
Definition SCFOperators.h:112
Receiving end of the exchange finalize, living in the world the transfer rides on.
Definition exchangeoperator.h:549
T beta_
Definition exchangeoperator.h:580
FinalizeReducer(World &world)
Definition exchangeoperator.h:554
std::vector< implT * > dests_
Definition exchangeoperator.h:579
FinalizeNodeRec< T, NDIM > recT
Definition exchangeoperator.h:552
FunctionImpl< T, NDIM > implT
Definition exchangeoperator.h:551
void accumulate_chunk(const std::vector< recT > &recs)
Definition exchangeoperator.h:565
void set_targets(std::vector< implT * > dests, T beta)
point at the destinations for the next drain; local, called by every rank
Definition exchangeoperator.h:560
static int get_k()
Returns the default wavelet order.
Definition funcdefaults.h:170
static std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > make_default_pmap(World &world)
Makes a default process map for the given world.
Definition mraimpl.h:3840
static const double & get_thresh()
Returns the default threshold.
Definition funcdefaults.h:183
static void set_default_pmap(World &world)
Definition mraimpl.h:3847
static std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > & get_pmap()
Returns the default process map that was last initialized via set_default_pmap().
Definition funcdefaults.h:415
static void set_pmap(const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > &value)
Sets the default process map (does not redistribute existing functions).
Definition funcdefaults.h:446
FunctionFactory implements the named-parameter idiom for Function.
Definition function_factory.h:86
FunctionImpl holds all Function state to facilitate shallow copy semantics.
Definition funcimpl.h:1045
FunctionNode holds the coefficients, etc., at each node of the 2^NDIM-tree.
Definition funcimpl.h:138
A multiresolution adaptive numerical function.
Definition mra.h:141
T & get(bool dowork=true) &
Gets the value, waiting if necessary.
Definition future.h:571
Key is the index for a node of the 2^NDIM-tree.
Definition key.h:71
Cloud * cloud_ptr
Definition macrotaskq.h:1639
MacroTaskOperationBase()
Definition macrotaskq.h:1642
Batch batch
Definition macrotaskq.h:1635
World * subworld_ptr
Definition macrotaskq.h:1636
std::shared_ptr< MacroTaskPartitioner > partitioner
Definition macrotaskq.h:1641
std::string name
Definition macrotaskq.h:1640
std::string policy
how to partition the batches
Definition macrotaskpartitioner.h:190
std::size_t nsubworld
number of worlds (try to have enough batches for all worlds)
Definition macrotaskpartitioner.h:189
std::list< std::pair< Batch, double > > partitionT
Definition macrotaskpartitioner.h:186
friend class Batch
Definition macrotaskpartitioner.h:183
MacroTaskPartitioner()
Definition macrotaskpartitioner.h:193
partitionT do_1d_partition(const std::size_t vsize, const std::string policy) const
Definition macrotaskpartitioner.h:251
std::size_t max_batch_size
maximum batch size (for memory management)
Definition macrotaskpartitioner.h:188
The Nemo class.
Definition nemo.h:377
Range, vaguely a la Intel TBB, to encapsulate a random-access, STL-like start and end iterator with c...
Definition range.h:64
Definition SCF.h:200
Definition applyscreen.h:83
void fence(bool debug=false)
Synchronizes all processes in communicator AND globally ensures no pending AM or tasks.
Definition worldgop.cc:177
WorldObject(const WorldObject &other)
Definition world_object.h:500
void process_pending()
Definition world_object.h:787
detail::task_result_type< memfnT >::futureT task(ProcessID dest, memfnT memfn, const TaskAttributes &attr=TaskAttributes()) const
Sends task to derived class method returnT (this->*memfn)().
Definition world_object.h:1132
Future< bool > for_each(const rangeT &range, const opT &op)
Apply op(item) on all items in range.
Definition world_task_queue.h:572
A parallel world class.
Definition world.h:134
WorldTaskQueue & taskq
Task queue.
Definition world.h:215
unsigned long id() const
Definition world.h:324
WorldGopInterface & gop
Global operations.
Definition world.h:216
Declares the Cloud class for storing data and transfering them between worlds.
char * p(char *buf, const char *name, int k, int initial_level, double thresh, int order)
Definition derivatives.cc:72
std::vector< Spinor > truncate(std::vector< Spinor > arg)
Definition dirac-hatom.cc:503
Fcwf apply(World &world, real_convolution_3d &op, const Fcwf &psi)
Definition fcwf.cc:317
Fcwf mul_sparse(const Fcwf &psi, const madness::real_function_3d &phi, double tol)
Definition fcwf.cc:566
Fcwf copy(Fcwf psi)
Definition fcwf.cc:374
const double beta
Definition gygi_soltion.cc:62
static const double v
Definition hatom_sf_dirac.cc:20
Declares the macrotaskq and MacroTaskBase classes.
General header file for using MADNESS.
#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
Function< double, 3 > functionT
Definition mcpfit.cc:50
vector< functionT > vecfuncT
Definition mcpfit.cc:51
void print(const tensorT &t)
Definition mcpfit.cc:140
Definition madness.h:73
Namespace for all elements and tools of MADNESS.
Definition DFConvergence.h:9
std::vector< std::pair< Batch_1D, Batch_1D > > exchange_row_owner_grid(const std::size_t ncolumn, const std::size_t nrow, const long nsubworld)
The asymmetric task grid: every (column, row) pair over two independent splits.
Definition exchangeoperator.h:81
long exchange_sym_owner_nbatch(const std::size_t n, const long nsubworld, const long granularity_level)
Number of batches M for the owner-pinned symmetric exchange algorithm.
Definition exchangeoperator.h:33
double get_rss_usage_in_GB()
Definition ranks_and_hosts.cpp:18
static double process_cpu_time()
Returns the CPU time consumed by this process, in seconds.
Definition timers.h:152
static double cpu_time()
Returns the cpu time in seconds relative to an arbitrary origin.
Definition timers.h:128
void coalesced_gaxpy(World &transport_world, FinalizeReducer< T, NDIM > &reducer, std::vector< Function< T, NDIM > > &dest_vec, std::vector< Function< T, NDIM > > &src_vec, const T beta, const std::size_t chunk_entries)
Accumulate src_vec into dest_vec in bulk, one message per destination rank per chunk.
Definition exchangeoperator.h:595
std::vector< Batch_1D > exchange_sym_owner_split(const std::size_t n, const long nsubworld, const long granularity_level)
Split a vector of length n into M = exchange_sym_owner_nbatch(...) contiguous batches.
Definition exchangeoperator.h:47
std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > FunctionDefaults< NDIM >::pmap
Definition mraimpl.h:3898
Function< TENSOR_RESULT_TYPE(T, R), NDIM > dot_sparse(World &world, const std::vector< Function< T, NDIM > > &a, const std::vector< Function< R, NDIM > > &b, double tol, bool fence=true, bool do_make_redundant=true)
Multiplies and sums two vectors of functions r = \sum_i a[i] * b[i].
Definition vmra.h:1884
std::map< std::pair< long, long >, long > exchange_sym_cost_aware_assign(const long n, const long M, const std::vector< double > &cost)
Cost-aware owner assignment for the symmetric algorithm's triangular task matrix.
Definition exchangeoperator.h:275
long exchange_batch_record_key(const long salt, const int dim, const Batch_1D &r)
Deterministic cloud record key for one stored batch: (salt, dimension, range).
Definition exchangeoperator.h:457
int FunctionDefaults< NDIM >::k
Definition mraimpl.h:3878
Function< TENSOR_RESULT_TYPE(T, R), NDIM > dot(World &world, const std::vector< Function< T, NDIM > > &a, const std::vector< Function< R, NDIM > > &b, bool fence=true, bool do_make_redundant=true)
Multiplies and sums two vectors of functions r = \sum_i a[i] * b[i]; see dot_sparse for screening.
Definition vmra.h:1897
std::vector< std::shared_ptr< FunctionImpl< T, NDIM > > > get_impl(const std::vector< Function< T, NDIM > > &v)
Definition vmra.h:781
TreeState
Definition funcdefaults.h:60
@ reconstructed
s coeffs at the leaves only
Definition funcdefaults.h:61
@ compressed
d coeffs in internal nodes, s and d coeffs at the root, empty leaves may be present
Definition funcdefaults.h:62
long exchange_sym_tri(const long i, const long j)
Triangular index of a batch pair, collapsing (i,j) and (j,i): a*(a+1)/2 + b.
Definition exchangeoperator.h:157
exchange_sup_bounds_t< NDIM > exchange_sup_bounds(World &world, const std::vector< Function< T, NDIM > > &multipliers)
Definition exchangeoperator.h:114
void compress(World &world, const std::vector< Function< T, NDIM > > &v, bool fence=true)
Compress a vector of functions.
Definition vmra.h:150
std::function< double(const Key< NDIM > &)> apply_screen_t
per destination box, a bound on the size of what the result of the apply will be multiplied with
Definition applyscreen.h:34
void hash_combine(hashT &seed, const T &v)
Combine hash values.
Definition worldhash.h:261
std::map< std::pair< long, long >, long > exchange_row_owner_assign(const long ncolumn, const long nrow, const long nworker)
Owner of every task in the asymmetric grid: all tasks of a column go to one worker.
Definition exchangeoperator.h:145
Function< T, NDIM > sum(World &world, const std::vector< Function< T, NDIM > > &f, bool fence=true)
Returns new function — q = sum_i f[i].
Definition vmra.h:1774
static const Slice _(0,-1, 1)
bool exch_task_profile_enabled()
Is per-task exchange profiling on? Read once per process.
Definition exchangeoperator.h:356
long exchange_batch_salt(const std::vector< Function< T, NDIM > > &ket)
Per-invocation salt for the exchange batch record keys, from the ket identities.
Definition exchangeoperator.h:448
void exch_write_task_profile(const ExchTaskProfile &p)
Append one record to exch_taskprof.r<rank>.jsonl.
Definition exchangeoperator.h:377
std::vector< Batch_1D > exchange_row_owner_split(const std::size_t n, const long nsubworld)
Batch boundaries for the asymmetric row/column split: one batch per rank.
Definition exchangeoperator.h:69
@ TT_FULL
Definition gentensor.h:120
NDIM & f
Definition mra.h:2824
const Function< T, NDIM > & change_tree_state(const Function< T, NDIM > &f, const TreeState finalstate, bool fence=true)
change tree state of a function
Definition mra.h:3150
double wall_time()
Returns the wall time in seconds relative to an arbitrary origin.
Definition timers.cc:48
void print(const T &t, Ts &&... ts)
Print items to std::cout (items separated by spaces) and terminate with a new line.
Definition print.h:232
static SeparatedConvolution< double, 3 > * CoulombOperatorPtr(World &world, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with 1/r in 3D.
Definition operator.h:2039
std::vector< Function< T, NDIM > > zero_functions_compressed(World &world, int n, bool fence=true)
Generates a vector of zero functions (compressed).
Definition vmra.h:450
bool exch_force_general_path()
Send a symmetric application down the general (bra, ket, vf) path? Read once per process.
Definition exchangeoperator.h:367
std::vector< std::shared_ptr< const SupBoundMap< NDIM > > > exchange_sup_bounds_t
the sup bounds (supbound.h) of a tile's multipliers, one per function
Definition exchangeoperator.h:108
void exch_write_cost_matrix(const long call_index, const long k, const long M, const std::vector< double > &cost)
Write the measured per-task cost matrix of one application, for offline inspection.
Definition exchangeoperator.h:417
void load(Function< T, NDIM > &f, const std::string name)
Definition mra.h:3188
const FunctionCommonData< T, NDIM > * FunctionCommonData< T, NDIM >::data[MAXK]
Definition mraimpl.h:3875
bool exchange_same_operands(const std::vector< Function< T, NDIM > > &a, const std::vector< Function< T, NDIM > > &b)
Are these the same functions, so that one stored record can serve both operand roles?
Definition exchangeoperator.h:98
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
std::map< std::pair< long, long >, long > exchange_sym_round_robin_assign(const long n, const long M)
Round-robin owner assignment for the symmetric algorithm's triangular task matrix.
Definition exchangeoperator.h:181
apply_screen_t< NDIM > exchange_apply_screen(exchange_sup_bounds_t< NDIM > sup)
Definition exchangeoperator.h:133
ExchangeBatchDim
which of the three exchange operand vectors a stored batch belongs to
Definition exchangeoperator.h:434
@ EXCHANGE_BATCH_BRA
Definition exchangeoperator.h:434
@ EXCHANGE_BATCH_VF
Definition exchangeoperator.h:434
@ EXCHANGE_BATCH_KET
Definition exchangeoperator.h:434
Function< T, NDIM > copy(const Function< T, NDIM > &f, const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > &pmap, bool fence=true)
Create a new copy of the function with different distribution and optional fence.
Definition mra.h:2239
void gaxpy(const double a, ScalarResult< T > &left, const double b, const T &right, const bool fence=true)
the result type of a macrotask must implement gaxpy
Definition macrotaskq.h:243
@ nemo
nemo's regularized orbitals F = psi/R
Definition Restart.h:60
static const double b
Definition nonlinschro.cc:119
static const double a
Definition nonlinschro.cc:118
double C(double a)
Additional factor when transforming gaussian exponent a from fourier to real space.
Definition relops.cc:25
static const double c
Definition relops.cc:10
static std::atomic< long > sup_build_ns
Definition applyscreen.h:62
static std::atomic< long > sup_maps
Definition applyscreen.h:62
One task's record for the exchange profiler.
Definition exchangeoperator.h:326
double mul1_wall
Definition exchangeoperator.h:342
double compute_cpu
Definition exchangeoperator.h:337
double mul2_wall
Definition exchangeoperator.h:342
double thresh
which protocol tier this task ran in
Definition exchangeoperator.h:331
long k
Definition exchangeoperator.h:332
long task_id
Definition exchangeoperator.h:327
double truncate_wall
Definition exchangeoperator.h:342
long col_end
Definition exchangeoperator.h:334
double apply_wall
Definition exchangeoperator.h:342
unsigned long subworld_id
Definition exchangeoperator.h:329
long row_begin
Definition exchangeoperator.h:334
bool waited
a cold fetch happened, so this task paid latency
Definition exchangeoperator.h:344
double wait_for_data_wall
task entry until its operands are in hand
Definition exchangeoperator.h:336
long col_begin
Definition exchangeoperator.h:334
void reset()
Definition exchangeoperator.h:347
double wall_end
Definition exchangeoperator.h:335
long universe_rank
keys the output file: one per process
Definition exchangeoperator.h:328
int subworld_nrank
Definition exchangeoperator.h:330
double compute_wall
Definition exchangeoperator.h:337
bool diagonal
Definition exchangeoperator.h:333
long row_end
Definition exchangeoperator.h:334
double wall_start
Definition exchangeoperator.h:335
int operand_source
worst of its fetches: 0 resident, 1 ahead, 2 cold
Definition exchangeoperator.h:343
void observe_fetch_tier(const int tier)
keep the worst source, since that is the one that set the task's wait
Definition exchangeoperator.h:349
double peak_rss_gb
Definition exchangeoperator.h:345
Definition exchangeoperator.h:523
dataT data
Definition exchangeoperator.h:523
bool pinned
Definition exchangeoperator.h:523
keyT key
Definition exchangeoperator.h:523
One batch requested ahead of the task that will read it.
Definition exchangeoperator.h:998
std::shared_ptr< Future< batch_bytesT > > fut
Definition exchangeoperator.h:1005
One coefficient node in transit during the exchange finalize.
Definition exchangeoperator.h:534
std::size_t f
index into the destination function vector
Definition exchangeoperator.h:535
Key< NDIM > key
tree-node key
Definition exchangeoperator.h:536
void serialize(Archive &ar)
Definition exchangeoperator.h:539
FunctionNode< T, NDIM > node
the source node
Definition exchangeoperator.h:537
Definition macrotaskq.h:279
static MacroTaskInfo preset(const std::string name)
Definition macrotaskq.h:312
World & world
Memoized reference to the world to which this object belongs.
Definition world_object.h:348
class to temporarily redirect output to cout
Definition print.h:305
void split(const Range< ConcurrentHashMap< int, int >::iterator > &range)
Definition test_hashthreaded.cc:63
double cpu_time()
Definition test_list.cc:43
void e()
Definition test_sig.cc:75
std::complex< double > dataT
Definition testcomplexfunctionsolver.cc:10
vector_complex_function_3d update(World &world, const vector_complex_function_3d &psi, vector_complex_function_3d &vpsi, const tensor_real &e, int iter)
Definition testcosine.cc:210
constexpr std::size_t NDIM
Definition testgconv.cc:54
int ProcessID
Used to clearly identify process number/rank.
Definition worldtypes.h:43
Key< D > keyT
Definition writecoeff2.cc:11