-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathcontraction_eval.h
More file actions
2021 lines (1743 loc) · 81 KB
/
Copy pathcontraction_eval.h
File metadata and controls
2021 lines (1743 loc) · 81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is a part of TiledArray.
* Copyright (C) 2013 Virginia Tech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef TILEDARRAY_DIST_EVAL_CONTRACTION_EVAL_H__INCLUDED
#define TILEDARRAY_DIST_EVAL_CONTRACTION_EVAL_H__INCLUDED
#include <vector>
#include <TiledArray/config.h>
#include <TiledArray/dist_eval/dist_eval.h>
#include <TiledArray/proc_grid.h>
#include <TiledArray/reduce_task.h>
#include <TiledArray/shape.h>
#include <TiledArray/type_traits.h>
#include <TiledArray/tensor/type_traits.h>
// #define TILEDARRAY_ENABLE_SUMMA_TRACE_EVAL 1
// #define TILEDARRAY_ENABLE_SUMMA_TRACE_INITIALIZE 1
// #define TILEDARRAY_ENABLE_SUMMA_TRACE_STEP 1
// #define TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST 1
// #define TILEDARRAY_ENABLE_SUMMA_TRACE_FINALIZE 1
namespace TiledArray {
namespace detail {
/// \brief Distributed contraction evaluator implementation
/// \tparam Left The left-hand argument evaluator type
/// \tparam Right The right-hand argument evaluator type
/// \tparam Op The contraction/reduction operation type
/// \tparam Policy The tensor policy class
/// \note The algorithms in this class assume that the arguments have a two-
/// dimensional cyclic distribution, and that the row phase of the left-hand
/// argument and the column phase of the right-hand argument are equal to
/// the number of rows and columns, respectively, in the \c ProcGrid object
/// passed to the constructor.
template <typename Left, typename Right, typename Op, typename Policy>
class Summa
: public DistEvalImpl<typename Op::result_type, Policy>,
public std::enable_shared_from_this<Summa<Left, Right, Op, Policy>> {
public:
typedef Summa<Left, Right, Op, Policy> Summa_; ///< This object type
typedef DistEvalImpl<typename Op::result_type, Policy>
DistEvalImpl_; ///< The base class type
typedef typename DistEvalImpl_::TensorImpl_
TensorImpl_; ///< The base, base class type
typedef Left left_type; ///< The left-hand argument type
typedef Right right_type; ///< The right-hand argument type
typedef typename DistEvalImpl_::ordinal_type ordinal_type; ///< Ordinal type
typedef typename DistEvalImpl_::range_type range_type; ///< Range type
typedef typename DistEvalImpl_::shape_type shape_type; ///< Shape type
typedef typename DistEvalImpl_::pmap_interface
pmap_interface; ///< Process map interface type
typedef
typename DistEvalImpl_::trange_type trange_type; ///< Tiled range type
typedef typename DistEvalImpl_::value_type value_type; ///< Tile type
typedef
typename DistEvalImpl_::eval_type eval_type; ///< Tile evaluation type
typedef Op op_type; ///< Tile evaluation operator type
private:
static ordinal_type max_memory_; ///< Maximum memory used per node
static ordinal_type
max_depth_; ///< Maximum number of concurrent SUMMA iterations
// Arguments and operation
left_type left_; ///< The left-hand argument
right_type right_; /// < The right-hand argument
op_type op_; /// < The operation used to evaluate tile-tile contractions
// Broadcast groups for dense arguments (empty for non-dense arguments)
madness::Group row_group_; ///< The row process group for this rank
madness::Group col_group_; ///< The column process group for this rank
// Dimension information
const ordinal_type k_; ///< Number of tiles in the inner dimension
const ProcGrid proc_grid_; ///< Process grid for this contraction
// Batched (fused/Hadamard-index) dimension information. A batched
// contraction C(h,i,j) = sum_k A(h,i,k) B(h,k,j) is evaluated as nh_
// independent SUMMA "slabs" sharing one process grid and one task graph:
// the iteration space is steps s = h*k_ + k, and every tile ordinal is
// offset by its slab base (h * {left,right,result}_slab_size_). For the
// ordinary contraction nh_ == 1 and all of this reduces to the unbatched
// arithmetic.
const ordinal_type nh_; ///< Number of fused (Hadamard) slabs
const ordinal_type nsteps_; ///< Total SUMMA steps = nh_ * k_
const ordinal_type
left_slab_size_; ///< # of left tiles per slab (= rows*k tiles)
const ordinal_type
right_slab_size_; ///< # of right tiles per slab (= k*cols tiles)
const ordinal_type
result_slab_size_; ///< # of result tiles per slab (= rows*cols tiles)
// Contraction results
ReducePairTask<op_type>* reduce_tasks_; ///< A pointer to the reduction tasks
// Constants used to iterate over columns and rows of left_ and right_,
// respectively. N.B. all are *slab-local* (slab h adds
// h * {left,right}_slab_size_ at the use sites).
const ordinal_type
left_start_local_; ///< The starting point of left column iterator ranges
///< (just add k for specific columns)
const ordinal_type left_end_; ///< The end of the left column iterator ranges
///< within a slab
const ordinal_type left_stride_; ///< Stride for left column iterators
const ordinal_type
left_stride_local_; ///< Stride for local left column iterators
const ordinal_type right_stride_; ///< Stride for right row iterators
const ordinal_type
right_stride_local_; ///< stride for local right row iterators
// 3-d (h-grouped) grid information. The world's first
// proc_h_ * proc_h_stride ranks are partitioned into proc_h_ contiguous
// groups; slab h belongs to group h % proc_h_, and each group runs its
// own 2-d SUMMA grid (proc_grid_ is this rank's GROUP-LOCAL grid,
// constructed over the group's rank interval). proc_h_ == 1 is the
// ordinary shared-grid batched contraction.
const ordinal_type proc_h_; ///< Number of slab (h) groups
const ordinal_type
proc_h_stride_; ///< World ranks per slab group (the
///< group of slab h spans world ranks
///< [(h % proc_h_) * proc_h_stride_, ...))
const ordinal_type first_slab_; ///< This rank's group's first slab (== its
///< group index), or nh_ if this rank is
///< in no group (idle for this eval)
const ordinal_type my_slabs_; ///< Number of slabs of this rank's group
/// \return the world rank that owns result tile \p i: the within-group
/// owner (from the group-local process grid) shifted by the world-rank
/// offset of the group that owns \p i's slab. For proc_h_ == 1 the offset
/// is 0 and this is the ordinary cyclic owner.
ProcessID result_tile_owner(const ordinal_type i) const {
const ordinal_type source_index = DistEvalImpl_::perm_index_to_source(i);
// owner is independent of slab index *within a group*
const ordinal_type slab_index = source_index % result_slab_size_;
const ordinal_type tile_row = slab_index / proc_grid_.cols();
const ordinal_type tile_col = slab_index % proc_grid_.cols();
const ordinal_type proc_row = tile_row % proc_grid_.proc_rows();
const ordinal_type proc_col = tile_col % proc_grid_.proc_cols();
const ProcessID within_group = proc_row * proc_grid_.proc_cols() + proc_col;
// shift by the offset of the group that owns this tile's slab
const ordinal_type slab = source_index / result_slab_size_;
const ordinal_type group = (proc_h_ > 1ul) ? (slab % proc_h_) : 0ul;
return ProcessID(group * proc_h_stride_) + within_group;
}
/// \return the slab index of SUMMA step \p s
ordinal_type step_h(const ordinal_type s) const { return s / k_; }
/// \return the within-slab inner-dimension index of SUMMA step \p s
ordinal_type step_k(const ordinal_type s) const { return s % k_; }
/// \return the smallest SUMMA step >= \p s that belongs to one of this
/// rank's group's slabs, or nsteps_ if there is none
ordinal_type next_step(ordinal_type s) const {
if (proc_h_ == 1ul) return std::min(s, nsteps_);
if (first_slab_ >= nh_) return nsteps_; // not in any group
while (s < nsteps_ && (step_h(s) % proc_h_) != first_slab_)
s = (step_h(s) + 1ul) * k_; // jump to the start of the next slab
return std::min(s, nsteps_);
}
/// \return this rank's group-local ordinal of slab \p h (which must
/// belong to this rank's group)
ordinal_type slab_ord(const ordinal_type h) const {
return (h - first_slab_) / proc_h_;
}
/// \return the number of SUMMA steps of this rank's group's slabs
ordinal_type my_steps() const { return my_slabs_ * k_; }
typedef Future<typename right_type::eval_type>
right_future; ///< Future to a right-hand argument tile
typedef Future<typename left_type::eval_type>
left_future; ///< Future to a left-hand argument tile
typedef std::pair<ordinal_type, right_future>
row_datum; ///< Datum element type for a right-hand argument row
typedef std::pair<ordinal_type, left_future>
col_datum; ///< Datum element type for a left-hand argument column
// various tracing/debugging artifacts
static constexpr const bool trace_tasks =
#ifdef TILEDARRAY_ENABLE_TASK_DEBUG_TRACE
true
#else
false
#endif
;
#ifdef TILEDARRAY_ENABLE_GLOBAL_COMM_STATS_TRACE
mutable std::atomic<ordinal_type>
left_ntiles_used_; // # of tiles used from left_
mutable std::atomic<ordinal_type>
right_ntiles_used_; // # of tiles used from right_
mutable std::atomic<ordinal_type>
left_ntiles_discarded_; // # of tiles discarded from left_
mutable std::atomic<ordinal_type>
right_ntiles_discarded_; // # of tiles discarded from right_
#endif
protected:
// Import base class functions
using std::enable_shared_from_this<Summa_>::shared_from_this;
private:
// Static variable initialization ----------------------------------------
/// Initialize max_memory_ limit for SUMMA
static ordinal_type init_max_memory() {
const char* max_memory = getenv("TA_SUMMA_MAX_MEMORY");
if (max_memory) {
// Convert the string into bytes
std::stringstream ss(max_memory);
double memory = 0.0;
if (ss >> memory) {
if (memory > 0.0) {
std::string unit;
if (ss >> unit) { // Failure == assume bytes
if (unit == "KB" || unit == "kB") {
memory *= 1000.0;
} else if (unit == "KiB" || unit == "kiB") {
memory *= 1024.0;
} else if (unit == "MB") {
memory *= 1000000.0;
} else if (unit == "MiB") {
memory *= 1048576.0;
} else if (unit == "GB") {
memory *= 1000000000.0;
} else if (unit == "GiB") {
memory *= 1073741824.0;
}
}
}
}
memory = std::max(memory, 104857600.0); // Minimum 100 MiB
return memory;
}
return 0ul;
}
static ordinal_type init_max_depth() {
const char* max_depth = getenv("TA_SUMMA_MAX_DEPTH");
if (max_depth) return std::stoul(max_depth);
return 0ul;
}
// Process groups --------------------------------------------------------
/// Process group factory function
/// This function generates a sparse process group.
/// \tparam Shape The shape type
/// \tparam ProcMap The process map operation type
/// \param shape The shape that will be used to select processes that are
/// included in the process group
/// \param process_mask the process mask, if
/// \code process_mask[p] == true \endcode,
/// process \c p will not be included in the result (p is row/col index
/// in this process's row/column)
/// \param index The first index of the row or column range
/// \param end The end of the row or column range
/// \param stride The row or column index stride
/// \param k The broadcast group index
/// \param max_proc_h_stride The maximum number of processes in the result
/// group, which is equal to the number of process in this process row or
/// column as defined by \c proc_grid_.
/// \param key_offset The key that will be used to identify the process group
/// \param proc_map The operator that will convert a process row/column
/// index into the absolute process index (ProcessID)
/// \return A sparse process group that includes process in the row or
/// column of this process as defined by \c proc_grid_.
template <typename Shape, typename ProcMap>
madness::Group make_group(const Shape& shape,
const std::vector<bool>& process_mask,
ordinal_type index, const ordinal_type end,
const ordinal_type stride,
const ordinal_type max_proc_h_stride,
const ordinal_type k, const ordinal_type key_offset,
const ProcMap& proc_map) const {
// Generate the list of processes in rank_row
std::vector<ProcessID> proc_list(max_proc_h_stride, -1);
// Flag the root processes of the broadcast, which may not be included
// by shape.
ordinal_type p = k % max_proc_h_stride;
proc_list[p] = proc_map(p);
ordinal_type count = 1ul;
// Flag all processes that have non-zero tiles
for (p = 0ul; (index < end) && (count < max_proc_h_stride);
index += stride, p = (p + 1u) % max_proc_h_stride) {
if ((proc_list[p] != -1) || (shape.is_zero(index)) || !process_mask.at(p))
continue;
proc_list[p] = proc_map(p);
++count;
}
// Remove processes from the list that will not be in the group
for (ordinal_type x = 0ul, p = 0ul; x < count; ++p) {
if (proc_list[p] == -1) continue;
proc_list[x++] = proc_list[p];
}
// Truncate invalid process id's
proc_list.resize(count);
return madness::Group(
TensorImpl_::world(), proc_list,
madness::DistributedID(DistEvalImpl_::id(), k + key_offset));
}
/// Row process group factory function
/// \param s The SUMMA step (= slab index * k_ + broadcast group index)
/// \return A row process group
madness::Group make_row_group(const ordinal_type s) const {
const ordinal_type h = step_h(s);
const ordinal_type k = step_k(s);
// Construct the sparse broadcast group
const ordinal_type right_begin_k =
h * right_slab_size_ + k * proc_grid_.cols();
const ordinal_type right_end_k = right_begin_k + proc_grid_.cols();
// make the row mask; using the same mask for all tiles avoids having to
// compute mask for every tile and use of masked broadcasts
auto result_row_mask_k = make_row_mask(h, k);
// return empty group if I am not in this group, otherwise make a group
// N.B. group key = s + nsteps_ (unique across (h,k) and distinct from the
// column groups' keys), root flag = k (the within-slab cyclic owner)
if (result_row_mask_k[proc_grid_.rank_col()])
return make_group(right_.shape(), result_row_mask_k, right_begin_k,
right_end_k, right_stride_, proc_grid_.proc_cols(), k,
s - k + nsteps_, [&](const ProcGrid::size_type col) {
return proc_grid_.map_col(col);
});
else
return madness::Group();
}
/// Column process group factory function
/// \param s The SUMMA step (= slab index * k_ + broadcast group index)
/// \return A column process group
madness::Group make_col_group(const ordinal_type s) const {
const ordinal_type h = step_h(s);
const ordinal_type k = step_k(s);
// make the column mask; using the same mask for all tiles avoids having to
// compute mask for every tile and use of masked broadcasts
auto result_col_mask_k = make_col_mask(h, k);
// return empty group if I am not in this group, otherwise make a group
// N.B. group key = s (unique across (h,k)), root flag = k
if (result_col_mask_k[proc_grid_.rank_row()])
return make_group(
left_.shape(), result_col_mask_k, h * left_slab_size_ + k,
h * left_slab_size_ + left_end_, left_stride_, proc_grid_.proc_rows(),
k, s - k,
[&](const ordinal_type row) { return proc_grid_.map_row(row); });
else
return madness::Group();
}
/// Makes the row result mask
/// \param k The SUMMA iteration (i.e. contraction tile) index
/// \return a set object, if \code result[p] == true \endcode the process
/// in column \c p of this row has at least 1 result tile for this \c
/// k
std::vector<bool> make_row_mask(const ordinal_type h,
const ordinal_type k) const {
// "local" A[i][k] (i.e. for all i assigned to my row of processes) will
// produce C[i][*] for each process in my row of the process grid determine
// whether there are any nonzero C[i][*] located on that node
const auto nproc_cols = proc_grid_.proc_cols();
const auto my_proc_row = proc_grid_.rank_row();
// result shape
const auto& result_shape = TensorImpl_::shape();
// if result is dense, include all processors
if (result_shape.is_dense()) return std::vector<bool>(nproc_cols, true);
// initialize the mask
std::vector<bool> mask(nproc_cols, false);
// number of tiles in the col dimension of the result
const auto nj = proc_grid_.cols();
// number of tiles in contraction dim
const auto nk = k_;
// slab bases
const auto left_base = h * left_slab_size_;
const auto result_base = h * result_slab_size_;
// for each i assigned to my row of processes ...
ordinal_type i_start, i_fence, i_stride;
std::tie(i_start, i_fence, i_stride) = result_row_range(my_proc_row);
const auto ik_stride = i_stride * nk;
for (ordinal_type i = i_start, ik = left_base + i_start * nk + k;
i < i_fence; i += i_stride, ik += ik_stride) {
// ... such that A[i][k] exists ...
if (!left_.shape().is_zero(ik)) {
// ... the owner of А[i][k] is always in the group ...
const auto k_proc_col = k % nproc_cols;
mask[k_proc_col] = true;
// ... loop over processes in my row ...
for (ordinal_type proc_col = 0; proc_col != nproc_cols; ++proc_col) {
// ... that are not the owner of A[i][k] ...
if (proc_col != k_proc_col) {
// ... loop over all C[i][j] tiles that belong to this process ...
ordinal_type j_start, j_fence, j_stride;
std::tie(j_start, j_fence, j_stride) = result_col_range(proc_col);
const auto ij_stride = j_stride;
for (ordinal_type j = j_start, ij = result_base + i * nj + j_start;
j < j_fence; j += j_stride, ij += ij_stride) {
// ... if any such C[i][j] exists, update the mask, and move
// on to next process
if (!result_shape.is_zero(
DistEvalImpl_::perm_index_to_target(ij))) {
mask[proc_col] = true;
break;
}
}
}
}
}
}
return mask;
}
/// Makes the column result mask
/// \param k The SUMMA iteration (i.e. contraction tile) index
/// \return a set object, if \code result[p] == true \endcode the process
/// in row \c p of this column has at least 1 result tile for this
/// \c k
std::vector<bool> make_col_mask(const ordinal_type h,
const ordinal_type k) const {
// "local" B[k][j] (i.e. for all j assigned to my column of processes)
// will produce C[*][j]
// for each process in my column of the process grid determine whether
// there are any
// nonzero C[*][j] located on that node
const auto nproc_rows = proc_grid_.proc_rows();
const auto my_proc_col = proc_grid_.rank_col();
// result shape
const auto& result_shape = TensorImpl_::shape();
// if result is dense, include all processors
if (result_shape.is_dense()) return std::vector<bool>(nproc_rows, true);
// initialize the mask
std::vector<bool> mask(nproc_rows, false);
// number of tiles in col dim of the result
const auto nj = proc_grid_.cols();
// slab bases
const auto right_base = h * right_slab_size_;
const auto result_base = h * result_slab_size_;
// for each j assigned to my column of processes ...
ordinal_type j_start, j_fence, j_stride;
std::tie(j_start, j_fence, j_stride) = result_col_range(my_proc_col);
const auto kj_stride = j_stride;
for (ordinal_type j = j_start, kj = right_base + k * nj + j_start;
j < j_fence; j += j_stride, kj += kj_stride) {
// ... such that B[k][j] exists ...
if (!right_.shape().is_zero(kj)) {
// ... the owner of B[k][j] is always in the group ...
auto k_proc_row = k % nproc_rows;
mask[k_proc_row] = true;
// ... loop over processes in my col ...
for (ordinal_type proc_row = 0; proc_row != nproc_rows; ++proc_row) {
// ... that are not the owner of B[k][j] ...
if (proc_row != k_proc_row) {
// ... loop over all C[i][j] tiles that belong to this process
ordinal_type i_start, i_fence, i_stride;
std::tie(i_start, i_fence, i_stride) = result_row_range(proc_row);
const auto ij_stride = i_stride * nj;
for (ordinal_type i = i_start, ij = result_base + i_start * nj + j;
i < i_fence; i += i_stride, ij += ij_stride) {
// ... if any such C[i][j] exists, update the mask, and move
// on to next process
if (!result_shape.is_zero(
DistEvalImpl_::perm_index_to_target(ij))) {
mask[proc_row] = true;
break;
}
}
}
}
}
}
return mask;
}
/// computes the result row iteration range for a particular processor
/// \param proc_row the process row in \c this->proc_grid_
/// \return the {start,fence,stride} tuple which defines the iteration
/// range for the row indices of the result tiles residing on
/// process in row \c proc_row
inline std::tuple<ordinal_type, ordinal_type, ordinal_type> result_row_range(
ordinal_type proc_row) const {
const ordinal_type start = proc_row;
const ordinal_type fence = proc_grid_.rows();
const ordinal_type stride = proc_grid_.proc_rows();
return std::make_tuple(start, fence, stride);
}
/// computes the result column iteration range for a particular processor
/// \param proc_col the process column in \c this->proc_grid_
/// \return the {start,fence,stride} tuple which defines the iteration
/// range for the column indices of the result tiles residing on
/// process in column \c proc_col
std::tuple<ordinal_type, ordinal_type, ordinal_type> result_col_range(
ordinal_type proc_col) const {
const ordinal_type start = proc_col;
const ordinal_type fence = proc_grid_.cols();
const ordinal_type stride = proc_grid_.proc_cols();
return std::make_tuple(start, fence, stride);
}
// Broadcast kernels -----------------------------------------------------
/// Tile conversion task function
/// \tparam Tile The input tile type
/// \param tile The input tile
/// \return The evaluated version of the lazy tile
template <typename Tile>
static auto convert_tile(const Tile& tile) {
TiledArray::Cast<typename eval_trait<Tile>::type, Tile> cast;
return cast(tile);
}
/// Conversion function
/// This function does nothing since tile is not a lazy tile.
/// \tparam Arg The type of the argument that holds the input tiles
/// \param arg The argument that holds the tiles
/// \param index The tile index of arg
/// \return \c tile
template <typename Arg>
static typename std::enable_if<!is_lazy_tile<typename Arg::value_type>::value,
Future<typename Arg::eval_type>>::type
get_tile(Arg& arg, const typename Arg::ordinal_type index) {
return arg.get(index);
}
/// Conversion function
/// This function spawns a task that will convert a lazy tile from the
/// tile type to the evaluated tile type.
/// \tparam Arg The type of the argument that holds the input tiles
/// \param arg The argument that holds the tiles
/// \param index The tile index of arg
/// \return A future to the evaluated tile
template <typename Arg>
static typename std::enable_if<
is_lazy_tile<typename Arg::value_type>::value
#ifdef TILEDARRAY_HAS_DEVICE
&& !detail::is_device_tile_v<typename Arg::value_type>
#endif
,
Future<typename Arg::eval_type>>::type
get_tile(Arg& arg, const typename Arg::ordinal_type index) {
auto convert_tile_fn =
&Summa_::template convert_tile<typename Arg::value_type>;
return arg.world().taskq.add(convert_tile_fn, arg.get(index),
madness::TaskAttributes::hipri());
}
#ifdef TILEDARRAY_HAS_DEVICE
/// Conversion function
/// This function spawns a task that will convert a lazy tile from the
/// tile type to the evaluated tile type.
/// \tparam Arg The type of the argument that holds the input tiles
/// \param arg The argument that holds the tiles
/// \param index The tile index of arg
/// \return A future to the evaluated tile
template <typename Arg>
static typename std::enable_if<
is_lazy_tile<typename Arg::value_type>::value &&
detail::is_device_tile_v<typename Arg::value_type>,
Future<typename Arg::eval_type>>::type
get_tile(Arg& arg, const typename Arg::ordinal_type index) {
auto convert_tile_fn =
&Summa_::template convert_tile<typename Arg::value_type>;
return madness::add_device_task(arg.world(), convert_tile_fn,
arg.get(index),
madness::TaskAttributes::hipri());
}
#endif
/// Collect non-zero tiles from \c arg
/// \tparam Arg The argument type
/// \tparam Datum The vector datum type
/// \param[in] arg The owner of the input tiles
/// \param[in] index The index of the first tile to be broadcast
/// \param[in] end The end of the range of tiles to be broadcast
/// \param[in] stride The stride between tile indices to be broadcast
/// \param[out] vec The vector that will hold broadcast tiles
template <typename Arg, typename Datum>
void get_vector(Arg& arg, ordinal_type index, const ordinal_type end,
const ordinal_type stride, std::vector<Datum>& vec) const {
TA_ASSERT(vec.size() == 0ul);
// Iterate over vector of tiles
if (arg.is_local(index)) {
for (ordinal_type i = 0ul; index < end; ++i, index += stride) {
if (arg.shape().is_zero(index)) continue;
vec.emplace_back(i, get_tile(arg, index));
}
} else {
for (ordinal_type i = 0ul; index < end; ++i, index += stride) {
if (arg.shape().is_zero(index)) continue;
vec.emplace_back(i, Future<typename Arg::eval_type>());
}
}
TA_ASSERT(vec.size() > 0ul);
}
/// Collect non-zero tiles from column \c k of slab \c h of \c left_
/// \param[in] s The SUMMA step (slab * k_ + column index)
/// \param[out] col The column vector that will hold the tiles
void get_col(const ordinal_type s, std::vector<col_datum>& col) const {
const ordinal_type base = step_h(s) * left_slab_size_;
col.reserve(proc_grid_.local_rows());
get_vector(left_, base + left_start_local_ + step_k(s), base + left_end_,
left_stride_local_, col);
}
/// Collect non-zero tiles from row \c k of slab \c h of \c right_
/// \param[in] s The SUMMA step (slab * k_ + row index)
/// \param[out] row The row vector that will hold the tiles
void get_row(const ordinal_type s, std::vector<row_datum>& row) const {
row.reserve(proc_grid_.local_cols());
// Compute local iteration limits for row k of slab h of right_.
ordinal_type begin =
step_h(s) * right_slab_size_ + step_k(s) * proc_grid_.cols();
const ordinal_type end = begin + proc_grid_.cols();
begin += proc_grid_.rank_col();
get_vector(right_, begin, end, right_stride_local_, row);
}
/// Broadcast tiles from \c arg
/// \param[in] start The index of the first tile to be broadcast
/// \param[in] stride The stride between tile indices to be broadcast
/// \param[in] group The process group where the tiles will be broadcast
/// \param[in] group_root The root process of the broadcast
/// \param[in] key_offset The broadcast key offset value
/// \param[out] vec The vector that will hold broadcast tiles
template <typename Datum>
void bcast(const ordinal_type start, const ordinal_type stride,
const madness::Group& group, const ProcessID group_root,
const ordinal_type key_offset, std::vector<Datum>& vec) const {
TA_ASSERT(vec.size() != 0ul);
TA_ASSERT(group.size() > 0);
TA_ASSERT(group_root < group.size());
#ifdef TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST
std::stringstream ss;
ss << "bcast: rank=" << TensorImpl_::world().rank()
<< " root=" << group.world_rank(group_root) << " groupid=("
<< group.id().first << "," << group.id().second
<< ") keyoffset=" << key_offset << " group={ ";
for (ProcessID group_proc = 0; group_proc < group.size(); ++group_proc)
ss << group.world_rank(group_proc) << " ";
ss << "} tiles={ ";
#endif // TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST
// Iterate over tiles to be broadcast
for (typename std::vector<Datum>::iterator it = vec.begin();
it != vec.end(); ++it) {
const ordinal_type index = it->first * stride + start;
// Broadcast the tile
const madness::DistributedID key(DistEvalImpl_::id(), index + key_offset);
TensorImpl_::world().gop.bcast(key, it->second, group_root, group);
#ifdef TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST
ss << index << " ";
#endif // TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST
}
TA_ASSERT(vec.size() > 0ul);
#ifdef TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST
ss << "}\n";
printf(ss.str().c_str());
#endif // TILEDARRAY_ENABLE_SUMMA_TRACE_BCAST
}
// Broadcast specialization for left and right arguments -----------------
ProcessID get_row_group_root(const ordinal_type k,
const madness::Group& row_group) const {
ProcessID group_root = k % proc_grid_.proc_cols();
if (!right_.shape().is_dense() &&
row_group.size() < static_cast<ProcessID>(proc_grid_.proc_cols())) {
const ProcessID world_root =
proc_grid_.rank_row() * proc_grid_.proc_cols() + group_root;
group_root = row_group.rank(world_root);
}
return group_root;
}
ProcessID get_col_group_root(const ordinal_type k,
const madness::Group& col_group) const {
ProcessID group_root = k % proc_grid_.proc_rows();
if (!left_.shape().is_dense() &&
col_group.size() < static_cast<ProcessID>(proc_grid_.proc_rows())) {
const ProcessID world_root =
group_root * proc_grid_.proc_cols() + proc_grid_.rank_col();
group_root = col_group.rank(world_root);
}
return group_root;
}
/// Broadcast column \c k of slab \c h of \c left_
/// \param[in] s The SUMMA step (slab * k_ + column index)
/// \param[out] col The vector that will hold the results of the broadcast
void bcast_col(const ordinal_type s, std::vector<col_datum>& col,
const madness::Group& row_group) const {
// broadcast if I'm part of the broadcast group
if (!row_group.empty()) {
// Broadcast column k of slab h of left_.
ProcessID group_root = get_row_group_root(step_k(s), row_group);
bcast(step_h(s) * left_slab_size_ + left_start_local_ + step_k(s),
left_stride_local_, row_group, group_root, 0ul, col);
}
}
/// Broadcast row \c k of slab \c h of \c right_
/// \param[in] s The SUMMA step (slab * k_ + row index)
/// \param[out] row The vector that will hold the results of the broadcast
void bcast_row(const ordinal_type s, std::vector<row_datum>& row,
const madness::Group& col_group) const {
// broadcast if I'm part of the broadcast group
if (!col_group.empty()) {
// Compute the group root process.
ProcessID group_root = get_col_group_root(step_k(s), col_group);
// Broadcast row k of slab h of right_.
bcast(step_h(s) * right_slab_size_ + step_k(s) * proc_grid_.cols() +
proc_grid_.rank_col(),
right_stride_local_, col_group, group_root, left_.size(), row);
}
}
void bcast_col_range_task(ordinal_type s, const ordinal_type end) const {
// Iterate over the skipped steps for which this process column owns the
// broadcast root (i.e. within-slab k congruent to rank_col mod Pcols)
const ordinal_type Pcols = proc_grid_.proc_cols();
for (s = next_step(s); s < end; s = next_step(s + 1ul)) {
const ordinal_type k = step_k(s);
if (k % Pcols != static_cast<ordinal_type>(proc_grid_.rank_col()))
continue;
const ordinal_type left_base = step_h(s) * left_slab_size_;
// Compute local iteration limits for column k of slab h of left_.
ordinal_type index = left_base + left_start_local_ + k;
const ordinal_type col_end = left_base + left_end_;
// will create broadcast group only if needed
bool have_group = false;
madness::Group row_group;
ProcessID group_root;
bool do_broadcast;
// Search column k of left for non-zero tiles
for (; index < col_end; index += left_stride_local_) {
if (left_.shape().is_zero(index)) continue;
// Construct broadcast group, if needed
if (!have_group) {
have_group = true;
row_group = make_row_group(s);
// broadcast if I am in this group and this group has others
do_broadcast = !row_group.empty() && row_group.size() > 1;
if (do_broadcast) group_root = get_row_group_root(k, row_group);
}
if (do_broadcast) {
// Broadcast the tile
#ifdef TILEDARRAY_ENABLE_GLOBAL_COMM_STATS_TRACE
++left_ntiles_used_;
#endif
const madness::DistributedID key(DistEvalImpl_::id(), index);
auto tile = get_tile(left_, index);
TensorImpl_::world().gop.bcast(key, tile, group_root, row_group);
} else {
// Discard the tile
#ifdef TILEDARRAY_ENABLE_GLOBAL_COMM_STATS_TRACE
++left_ntiles_discarded_;
#endif
left_.discard(index);
}
}
}
}
void bcast_row_range_task(ordinal_type s, const ordinal_type end) const {
// Iterate over the skipped steps for which this process row owns the
// broadcast root (i.e. within-slab k congruent to rank_row mod Prows)
const ordinal_type Prows = proc_grid_.proc_rows();
for (s = next_step(s); s < end; s = next_step(s + 1ul)) {
const ordinal_type k = step_k(s);
if (k % Prows != static_cast<ordinal_type>(proc_grid_.rank_row()))
continue;
// Compute local iteration limits for row k of slab h of right_.
ordinal_type index = step_h(s) * right_slab_size_ + k * proc_grid_.cols();
const ordinal_type row_end = index + proc_grid_.cols();
index += proc_grid_.rank_col();
// will create broadcast group only if needed
bool have_group = false;
madness::Group col_group;
ProcessID group_root;
bool do_broadcast;
// Search for and broadcast non-zero row
for (; index < row_end; index += right_stride_local_) {
if (right_.shape().is_zero(index)) continue;
// Construct broadcast group
if (!have_group) {
have_group = true;
col_group = make_col_group(s);
// broadcast if I am in this group and this group has others
do_broadcast = !col_group.empty() && col_group.size() > 1;
if (do_broadcast) group_root = get_col_group_root(k, col_group);
}
if (do_broadcast) {
// Broadcast the tile
#ifdef TILEDARRAY_ENABLE_GLOBAL_COMM_STATS_TRACE
++right_ntiles_used_;
#endif
const madness::DistributedID key(DistEvalImpl_::id(),
index + left_.size());
auto tile = get_tile(right_, index);
TensorImpl_::world().gop.bcast(key, tile, group_root, col_group);
} else {
// Discard the tile
#ifdef TILEDARRAY_ENABLE_GLOBAL_COMM_STATS_TRACE
++right_ntiles_discarded_;
#endif
right_.discard(index);
}
}
}
}
// Row and column iteration functions ------------------------------------
/// Find next non-zero row of \c right_ for a sparse shape
/// Starting at SUMMA step \c s, find the next step whose right-hand row
/// contains at least one non-zero tile. This search only checks for
/// non-zero tiles in this processes column.
/// \param s The first step to search
/// \return The first step, greater than or equal to \c s with non-zero
/// tiles, or \c nsteps_ if none is found.
ordinal_type iterate_row(ordinal_type s) const {
// Iterate over this rank's group's steps until a non-zero tile is found
// or the end of the matrix is reached.
for (s = next_step(s); s < nsteps_; s = next_step(s + 1ul)) {
// Search for non-zero tiles in row k of slab h of right
ordinal_type i =
step_h(s) * right_slab_size_ + step_k(s) * proc_grid_.cols();
const ordinal_type end = i + proc_grid_.cols();
i += proc_grid_.rank_col();
for (; i < end; i += right_stride_local_)
if (!right_.shape().is_zero(i)) return s;
}
return s;
}
/// Find the next non-zero column of \c left_ for an arbitrary shape type
/// Starting at SUMMA step \c s, find the next step whose left-hand column
/// contains at least one non-zero tile. This search only
/// checks for non-zero tiles in this process's row.
/// \param s The first step to test for non-zero tiles
/// \return The first step, greater than or equal to \c s, that contains
/// a non-zero tile. If no non-zero tile is not found, return \c nsteps_.
ordinal_type iterate_col(ordinal_type s) const {
// Iterate over this rank's group's steps until a non-zero tile is found
// or the end of the matrix is reached.
for (s = next_step(s); s < nsteps_; s = next_step(s + 1ul)) {
// Search column k of slab h for non-zero tiles
const ordinal_type base = step_h(s) * left_slab_size_;
for (ordinal_type i = base + left_start_local_ + step_k(s);
i < base + left_end_; i += left_stride_local_)
if (!left_.shape().is_zero(i)) return s;
}
return s;
}
/// Find the next k where the left- and right-hand argument have non-zero
/// tiles
/// Search for the next k-th column and row of the left- and right-hand
/// arguments, respectively, that both contain non-zero tiles. This search
/// only checks for non-zero tiles in this process's row or column. If a
/// non-zero, local tile is found that does not contribute to local
/// contractions, the tiles will be immediately broadcast.
/// \param k The first row/column to check
/// \return The next k-th column and row of the left- and right-hand
/// arguments, respectively, that both have non-zero tiles
ordinal_type iterate_sparse(const ordinal_type s) const {
// Initial step for k_col and k_row.
ordinal_type k_col = iterate_col(s);
ordinal_type k_row = iterate_row(k_col);
// Search for a row and column that both have non-zero tiles
while (k_col != k_row) {
if (k_col < k_row) {
k_col = iterate_col(k_row);
} else {
k_row = iterate_row(k_col);
}
}
if (s < k_row) {
// Spawn a task to broadcast any local columns of left that were skipped
TensorImpl_::world().taskq.add(shared_from_this(),
&Summa_::bcast_col_range_task, s, k_row,
madness::TaskAttributes::hipri());
// Spawn a task to broadcast any local rows of right that were skipped
TensorImpl_::world().taskq.add(shared_from_this(),
&Summa_::bcast_row_range_task, s, k_col,
madness::TaskAttributes::hipri());
}
return k_col;
}
/// Find the next k where the left- and right-hand argument have non-zero
/// tiles
/// Search for the next k-th column and row of the left- and right-hand
/// arguments, respectively, that both contain non-zero tiles. This search
/// only checks for non-zero tiles in this process's row or column. If a
/// non-zero, local tile is found that does not contribute to local
/// contractions, the tiles will be immediately broadcast.
/// \param k The first row/column to check
/// \return The next k-th column and row of the left- and right-hand
/// arguments, respectively, that both have non-zero tiles
ordinal_type iterate(const ordinal_type k) const {
return (left_.shape().is_dense() && right_.shape().is_dense()
? k
: iterate_sparse(k));
}
// Initialization functions ----------------------------------------------
/// Initialize reduce tasks and construct broadcast groups