-
Notifications
You must be signed in to change notification settings - Fork 38
/
vectorspace.py
1077 lines (913 loc) · 47.1 KB
/
vectorspace.py
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
import copy
from time import time
import numpy as np
from . import parallel
from . import util
from .py2to3 import print_msg, range
class VectorSpaceArrays(object):
"""Implements inner products and linear combinations using data stored in
arrays.
Kwargs:
``inner_product_weights``: 1D array of inner product weights.
Corresponds to :math:`W` in inner product :math:`v_1^* W v_2`.
"""
def __init__(self, weights=None):
self.weights = weights
if self.weights is not None:
self.weights = np.array(self.weights).squeeze()
if self.weights is None:
self.compute_inner_product_array = self._IP_no_weights
elif self.weights.ndim == 1:
self.compute_inner_product_array = self._IP_1D_weights
elif self.weights.ndim == 2:
self.compute_inner_product_array = self._IP_2D_weights
else:
raise ValueError('Weights must be None, 1D, or 2D')
def _IP_no_weights(self, vecs1, vecs2):
return np.dot(vecs1.conj().T, vecs2)
def _IP_1D_weights(self, vecs1, vecs2):
return np.dot(vecs1.conj().T * self.weights, vecs2)
def _IP_2D_weights(self, vecs1, vecs2):
return vecs1.conj().T.dot(self.weights.dot(vecs2))
def compute_symm_inner_product_array(self, vecs):
return self.compute_inner_product_array(vecs, vecs)
def lin_combine(
self, basis_vecs, coeff_array, coeff_array_col_indices=None):
coeff_array = np.array(coeff_array)
if coeff_array_col_indices is not None:
coeff_array = coeff_array[:, coeff_array_col_indices]
return basis_vecs.dot(coeff_array)
def __eq__(self, other):
if type(other) == type(self):
return np.array_equal(self.weights, other.weights)
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
class VectorSpaceHandles(object):
"""Provides efficient, parallel implementations of vector space operations,
using handles.
Kwargs:
``inner_product``: Function that computes inner product of two vector
objects.
``max_vecs_per_node``: Maximum number of vectors that can be stored in
memory, per node.
``verbosity``: 1 prints progress and warnings, 0 prints almost nothing.
``print_interval``: Minimum time (in seconds) between printed progress
messages.
This class implements low-level functions for computing large numbers of
vector sums and inner products. These functions are used by high-level
classes in :py:mod:`pod`, :py:mod:`bpod`, :py:mod:`dmd` and
:py:mod:`ltigalerkinproj`.
Note: Computations are often sped up by using all available processors,
even if this lowers ``max_vecs_per_node`` proportionally.
However, this depends on the computer and the nature of the functions
supplied, and sometimes loading from file is slower with more processors.
"""
def __init__(
self, inner_product=None, max_vecs_per_node=None, verbosity=1,
print_interval=10):
"""Constructor."""
self.inner_product = inner_product
self.verbosity = verbosity
self.print_interval = print_interval
self.prev_print_time = 0.
if max_vecs_per_node is None:
self.max_vecs_per_node = 10000 # different default?
self.print_msg((
'Warning: max_vecs_per_node was not specified. Assuming %d '
'vecs can be in memory per node. Decrease max_vecs_per_node '
'if memory errors.') % self.max_vecs_per_node)
else:
self.max_vecs_per_node = max_vecs_per_node
if (
self.max_vecs_per_node <
3 * parallel.get_num_procs() / parallel.get_num_nodes()):
self.max_vecs_per_proc = 3
self.max_vecs_per_node = int(np.ceil(
3 * parallel.get_num_procs() / parallel.get_num_nodes()))
self.print_msg(
'Warning: max_vecs_per_node too small for given number of '
'nodes and procs. Assuming three vecs can be in memory per '
'processor. If possible, increase max_vecs_per_node for a '
'speedup.')
else:
self.max_vecs_per_proc = (
self.max_vecs_per_node *
parallel.get_num_nodes() // parallel.get_num_procs())
def _check_inner_product(self):
"""Check that ``inner_product`` is defined"""
if self.inner_product is None:
raise RuntimeError('inner product function is not defined')
def print_msg(self, msg, output_channel='stdout'):
"""Print a message from rank zero MPI worker/processor."""
if self.verbosity > 0 and parallel.is_rank_zero():
print_msg(msg, output_channel=output_channel)
def sanity_check(self, test_vec_handle):
"""Checks that user-supplied vector handle and vector satisfy
requirements.
Args:
``test_vec_handle``: A vector handle to test.
The add and multiply functions are tested for the vector object.
This is not a complete testing, but catches some common mistakes.
An error is raised if a check fails.
"""
# TODO: Other things which could be tested:
# ``get``/``put`` doesn't affect other vecs (memory problems)
# Set tolerance
tol = 1e-12
# Check inner product properties
self._check_inner_product()
# Generate some data
test_vec = test_vec_handle.get()
# Copy vector for comparisons before doing anything else, to later check
# if other operations change the internal data.
vec_copy = copy.deepcopy(test_vec)
vec_copy_mag_sq = self.inner_product(vec_copy, vec_copy)
# Check that inner product of scaled vector is correct
scale_factor = 2.
vec_mult = test_vec * scale_factor
if abs(
self.inner_product(vec_mult, vec_mult) -
vec_copy_mag_sq * scale_factor ** 2) > tol:
raise ValueError(
'Inner product of vector with itself is incorrect after scalar '
'multiplication.')
# Check that inner product of original vector hasn't changed due to
# scalar multiplication.
if abs(
self.inner_product(test_vec, test_vec) - vec_copy_mag_sq) > tol:
raise ValueError(
'Inner product of original test vector with itself has changed '
'value after scalar multiplication.')
# Check that the inner product of a summed vector is correct
vec_add = test_vec + test_vec
if abs(
self.inner_product(vec_add, vec_add) - vec_copy_mag_sq * 4) > tol:
raise ValueError(
'Inner product of vector with itself is incorrect after '
'vector addition.')
# Check that inner product of original vector hasn't changed due to
# vector addition.
if abs(self.inner_product(test_vec, test_vec) - vec_copy_mag_sq) > tol:
raise ValueError(
'Inner product of original test vector with itself has changed '
'value after vector addition.')
# Check that the inner product of a vector is correct after scalar
# multiplication and vector addition.
vec_add_mult = test_vec * scale_factor + test_vec
if abs(
self.inner_product(vec_add_mult, vec_add_mult) -
vec_copy_mag_sq * (scale_factor + 1) ** 2) > tol:
raise ValueError(
'Inner product of vector is incorrect after scalar '
'multiplication and vector addition.')
# Check that inner product of original vector hasn't changed due to
# scalar multiplication and vector addition.
if abs(self.inner_product(test_vec, test_vec) - vec_copy_mag_sq) > tol:
raise ValueError(
'Inner product of original test vector with itself has changed '
'value after scalar multiplication and vector addition.')
# Report results to user
self.print_msg('Passed the sanity check.')
def compute_inner_product_array(self, row_vec_handles, col_vec_handles):
"""Computes array whose elements are inner products of the vector
objects in ``row_vec_handles`` and ``col_vec_handles``.
Args:
``row_vec_handles``: List of handles for vector objects
corresponding to rows of the inner product array. For example, in
BPOD this is the adjoint snapshot array :math:`Y`.
``col_vec_handles``: List of handles for vector objects
corresponding to columns of the inner product array. For example,
in BPOD this is the direct snapshot array :math:`X`.
Returns:
``IP_array``: 2D array of inner products.
The vectors are retrieved in memory-efficient chunks and are not all in
memory at once. The row vectors and column vectors are assumed to be
different. When they are the same, use
:py:meth:`compute_symm_inner_product` for a 2x speedup.
Each MPI worker (processor) is responsible for retrieving a subset of
the rows and columns. The processors then send/receive columns via MPI
so they can be used to compute all inner products for the rows on each
MPI worker. This is repeated until all MPI workers are done with all
of their row chunks. If there are 2 processors::
| x o |
rank0 | x o |
| x o |
-
| o x |
rank1 | o x |
| o x |
In the next step, rank 0 sends column 0 to rank 1 and rank 1 sends
column 1 to rank 0. The remaining inner products are filled in::
| x x |
rank0 | x x |
| x x |
-
| x x |
rank1 | x x |
| x x |
When the number of columns and rows is not divisible by the number of
processors, the processors are assigned unequal numbers of tasks.
However, all processors are always part of the passing cycle.
The scaling is:
- num gets / processor ~ :math:`(n_r*n_c/((max-2)*n_p*n_p)) + n_r/n_p`
- num MPI sends / processor ~
:math:`(n_p-1)*(n_r/((max-2)*n_p))*n_c/n_p`
- num inner products / processor ~ :math:`n_r*n_c/n_p`
where :math:`n_r` is number of rows, :math:`n_c` number of columns,
:math:`max` is
``max_vecs_per_proc = max_vecs_per_node/num_procs_per_node``,
and :math:`n_p` is the number of MPI workers (processors).
If there are more rows than columns, then an internal transpose and
un-transpose is performed to improve efficiency (since :math:`n_c` only
appears in the scaling in the quadratic term).
"""
self._check_inner_product()
row_vec_handles = util.make_iterable(row_vec_handles)
col_vec_handles = util.make_iterable(col_vec_handles)
num_cols = len(col_vec_handles)
num_rows = len(row_vec_handles)
if num_rows > num_cols:
transpose = True
tmp = row_vec_handles
row_vec_handles = col_vec_handles
col_vec_handles = tmp
tmp = num_rows
num_rows = num_cols
num_cols = tmp
else:
transpose = False
# convenience
rank = parallel.get_rank()
## Old way that worked
# num_cols_per_proc_chunk is the number of cols each proc gets at once
num_cols_per_proc_chunk = 1
num_rows_per_proc_chunk = (
self.max_vecs_per_proc - num_cols_per_proc_chunk)
## New way
#if self.max_vecs_per_node > max_num_row_tasks:
# num_cols_per_proc_chunk =
#num_rows_per_proc_chunk = self.max_vecs_per_proc - \
# num_cols_per_proc_chunk
# Determine how the retrieving and inner products will be split up.
row_tasks = parallel.find_assignments(list(range(num_rows)))
col_tasks = parallel.find_assignments(list(range(num_cols)))
# Find max number of col tasks among all processors
max_num_row_tasks = max([len(tasks) for tasks in row_tasks])
max_num_col_tasks = max([len(tasks) for tasks in col_tasks])
# These variables are the number of iters through loops that retrieve
# ("get") row and column vecs.
num_row_get_loops = \
int(np.ceil(max_num_row_tasks*1./num_rows_per_proc_chunk))
num_col_get_loops = \
int(np.ceil(max_num_col_tasks*1./num_cols_per_proc_chunk))
if num_row_get_loops > 1:
self.print_msg((
'Warning: The column vecs, of which '
'there are %d, will be retrieved %d times each. Increase '
'number of nodes or max_vecs_per_node to reduce redundant '
'gets for a speedup.') % (num_cols, num_row_get_loops))
# Burn the first inner product, it sometimes contains slow imports
row_vec = row_vec_handles[0].get()
col_vec = col_vec_handles[0].get()
IP_burn = self.inner_product(row_vec, col_vec)
# Time the get method
start_time = time()
row_vec = row_vec_handles[0].get()
get_time = time() - start_time
# Time the inner product method and get inner product type (real or
# complex)
start_time = time()
IP = self.inner_product(row_vec, col_vec)
IP_time = time() - start_time
IP_type = type(IP)
# Estimate time to compute entire inner product array
total_IP_time = (
num_rows * num_cols * IP_time / parallel.get_num_procs())
vecs_per_proc = (
self.max_vecs_per_node * parallel.get_num_nodes() /
parallel.get_num_procs())
num_gets = (
num_rows * num_cols /
((vecs_per_proc - 2) * parallel.get_num_procs() ** 2) +
num_rows / parallel.get_num_procs())
total_get_time = num_gets * get_time
self.print_msg((
'Computing the inner product array will take at least %.1f '
'minutes.') % ((total_IP_time + total_get_time) / 60.))
del row_vec, col_vec
# To find all of the inner product array chunks, each
# processor has a full IP_array with size
# num_rows x num_cols even though each processor is not responsible for
# filling in all of these entries. After each proc fills in what it is
# responsible for, the other entries remain 0's. Then, an allreduce
# is done and all the IP_arrays are summed. This is simpler than
# concatenating chunks of the IP_arrays.
# The efficiency is not an issue; the size of the arrays
# are small compared to the size of the vecs for large data.
IP_array = np.zeros((num_rows, num_cols), dtype=IP_type)
for row_get_index in range(num_row_get_loops):
if len(row_tasks[rank]) > 0:
start_row_index = min(
row_tasks[rank][0] + (
row_get_index * num_rows_per_proc_chunk),
row_tasks[rank][-1] + 1)
end_row_index = min(
row_tasks[rank][-1] + 1,
start_row_index + num_rows_per_proc_chunk)
row_vecs = [
row_vec_handle.get() for row_vec_handle in
row_vec_handles[start_row_index:end_row_index]]
else:
row_vecs = []
for col_get_index in range(num_col_get_loops):
if len(col_tasks[rank]) > 0:
start_col_index = min(
col_tasks[rank][0] + (
col_get_index * num_cols_per_proc_chunk),
col_tasks[rank][-1] + 1)
end_col_index = min(
col_tasks[rank][-1] + 1,
start_col_index + num_cols_per_proc_chunk)
else:
start_col_index = 0
end_col_index = 0
# Cycle the col vecs to proc with rank -> mod(rank+1,num_procs)
# Must do this for each processor, until data makes a circle
col_vecs_recv = (None, None)
col_indices = list(range(start_col_index, end_col_index))
for pass_index in range(parallel.get_num_procs()):
# If on the first pass, get the col vecs, no send/recv
# This is all that is called when in serial, loop iterates
# once.
if pass_index == 0:
col_vecs = [
col_handle.get() for col_handle in
col_vec_handles[start_col_index:end_col_index]]
else:
# Determine with whom to communicate
dest = (rank + 1) % parallel.get_num_procs()
source = (rank - 1) % parallel.get_num_procs()
# Create unique tag based on send/recv ranks
send_tag = (
rank * (parallel.get_num_procs() + 1) + dest)
recv_tag = (
source * (parallel.get_num_procs() + 1) + rank)
# Collect data and send/receive
col_vecs_send = (col_vecs, col_indices)
request = parallel.comm.isend(
col_vecs_send, dest=dest, tag=send_tag)
col_vecs_recv = parallel.comm.recv(
source=source, tag=recv_tag)
request.Wait()
parallel.barrier()
col_indices = col_vecs_recv[1]
col_vecs = col_vecs_recv[0]
# Compute the IPs for this set of data col_indices stores
# the indices of the IP_array columns to be filled in.
if len(row_vecs) > 0:
for row_index in range(start_row_index, end_row_index):
for col_vec_index, col_vec in enumerate(col_vecs):
IP_array[
row_index,
col_indices[col_vec_index]
] = self.inner_product(
row_vecs[row_index - start_row_index],
col_vec)
if (
(time() - self.prev_print_time) >
self.print_interval):
num_completed_IPs = (np.abs(IP_array) > 0.).sum()
percent_completed_IPs = (
num_completed_IPs *
parallel.get_num_MPI_workers() /
(num_cols * num_rows)) * 100.
self.print_msg(
'Completed %.1f%% of inner products' %
percent_completed_IPs,
output_channel='stderr')
self.prev_print_time = time()
# Clear the retrieved column vecs after done this pass cycle
del col_vecs
# Completed a chunk of rows and all columns on all processors.
del row_vecs
# Assign these chunks into IP_array.
if parallel.is_distributed():
IP_array = parallel.custom_comm.allreduce(IP_array)
if transpose:
IP_array = IP_array.conj().T
percent_completed_IPs = 100.
self.print_msg(
'Completed 100% of inner products', output_channel='stderr')
self.prev_print_time = time()
parallel.barrier()
return IP_array
def compute_symm_inner_product_array(self, vec_handles):
"""Computes symmetric array whose elements are inner products of the
vector objects in ``vec_handles`` with each other.
Args:
``vec_handles``: List of handles for vector objects corresponding
to both rows and columns. For example, in POD this is the snapshot
array :math:`X`.
Returns:
``IP_array``: 2D array of inner products.
See the documentation for :py:meth:`compute_inner_product_array` for an
idea how this works. Efficiency is achieved by only computing the
upper-triangular elements, since the array is symmetric. Within the
upper-triangular portion, there are rectangular chunks and triangular
chunks. The rectangular chunks are divided up among MPI workers
(processors) as weighted tasks. Once those have been computed, the
triangular chunks are dealt with.
"""
# TODO: JON, write detailed documentation similar to
# :py:meth:`compute_inner_product_array`.
self._check_inner_product()
vec_handles = util.make_iterable(vec_handles)
num_vecs = len(vec_handles)
total_num_IPs = num_vecs * (num_vecs + 1) / 2.
# num_cols_per_chunk is the number of cols each proc gets at once.
# Columns are retrieved if the array must be broken up into sets of
# chunks. Then symmetric upper triangular portions will be computed,
# followed by a rectangular piece that uses columns not already in
# memory.
num_cols_per_proc_chunk = 1
num_rows_per_proc_chunk = (
self.max_vecs_per_proc - num_cols_per_proc_chunk)
# <nprocs> chunks are computed simulaneously, making up a set.
num_cols_per_chunk = num_cols_per_proc_chunk * parallel.get_num_procs()
num_rows_per_chunk = num_rows_per_proc_chunk * parallel.get_num_procs()
# <num_row_chunks> is the number of sets that must be computed.
num_row_chunks = int(np.ceil(num_vecs * 1. / num_rows_per_chunk))
if num_row_chunks > 1:
self.print_msg((
'Warning: The vecs, of which there are %d, will be retrieved '
'%d times each. Increase number of nodes or max_vecs_per_node '
'to reduce redundant gets for a speedup.') %
(num_vecs,num_row_chunks))
# Burn the first inner product, as it sometimes contains slow imports
test_vec = vec_handles[0].get()
IP_burn = self.inner_product(test_vec, test_vec)
# Time the get method
start_time = time()
test_vec = vec_handles[0].get()
get_time = time() - start_time
# Time the inner product method and determine the inner product type
# (real or complex)
start_time = time()
IP = self.inner_product(test_vec, test_vec)
IP_time = time() - start_time
IP_type = type(IP)
# Estimate the time to compute the total inner product array
total_IP_time = (
num_vecs ** 2 * IP_time / 2. / parallel.get_num_procs())
vecs_per_proc = (
self.max_vecs_per_node * parallel.get_num_nodes() /
parallel.get_num_procs())
num_gets = (
(num_vecs ** 2 / 2.) / ((vecs_per_proc - 2) *
parallel.get_num_procs() ** 2) +
num_vecs / parallel.get_num_procs() / 2.)
total_get_time = num_gets * get_time
self.print_msg((
'Computing the inner product array will take at least %.1f '
'minutes' % ((total_IP_time + total_get_time) / 60.)))
del test_vec
# Use the same trick as in compute_IP_array, having each proc
# fill in elements of a num_rows x num_rows sized array, rather than
# assembling small chunks. This is done for the triangular portions.
# For the rectangular portions, the inner product array is filled
# in directly.
IP_array = np.zeros((num_vecs, num_vecs), dtype=IP_type)
for start_row_index in range(0, num_vecs, num_rows_per_chunk):
end_row_index = min(num_vecs, start_row_index + num_rows_per_chunk)
proc_row_tasks_all = parallel.find_assignments(list(range(
start_row_index, end_row_index)))
num_active_procs = len([
task for task in proc_row_tasks_all if task != []])
proc_row_tasks = proc_row_tasks_all[parallel.get_rank()]
if len(proc_row_tasks)!=0:
row_vecs = [
vec_handle.get() for vec_handle in
vec_handles[proc_row_tasks[0]:proc_row_tasks[-1] + 1]]
else:
row_vecs = []
# Triangular chunks
if len(proc_row_tasks) > 0:
# Test that indices are consecutive
if proc_row_tasks[0:] != list(range(
proc_row_tasks[0], proc_row_tasks[-1] + 1)):
raise ValueError('Indices are not consecutive.')
# Per-processor triangles (using only vecs in memory)
for row_index in range(proc_row_tasks[0],
proc_row_tasks[-1] + 1):
# Diagonal term
IP_array[row_index, row_index] = self.inner_product(
row_vecs[row_index - proc_row_tasks[0]],
row_vecs[row_index - proc_row_tasks[0]])
# Off-diagonal terms
for col_index in range(
row_index + 1, proc_row_tasks[-1] + 1):
IP_array[row_index, col_index] = self.inner_product(
row_vecs[row_index - proc_row_tasks[0]],
row_vecs[col_index - proc_row_tasks[0]])
# Number of square chunks to fill in is n * (n-1) / 2. At each
# iteration we fill in n of them, so we need (n-1) / 2
# iterations (round up).
for set_index in range(int(np.ceil((num_active_procs - 1.) / 2))):
# The current proc is "sender"
my_rank = parallel.get_rank()
my_row_indices = proc_row_tasks
my_num_rows = len(my_row_indices)
# The proc to send to is "destination"
dest_rank = (my_rank + set_index + 1) % num_active_procs
# The proc that data is received from is the "source"
source_rank = (my_rank - set_index - 1) % num_active_procs
# Find the maximum number of sends/recv to be done by any proc
max_num_to_send = int(np.ceil(1. * max([len(tasks) for \
tasks in proc_row_tasks_all]) /\
num_cols_per_proc_chunk))
'''
# Pad tasks with nan so that everyone has the same
# number of things to send. Same for list of vecs with None.
# The empty lists will not do anything when enumerated, so no
# inner products will be taken. nan is inserted into the
# indices because then min/max of the indices can be taken.
if my_num_rows != len(row_vecs):
raise ValueError('Number of rows assigned does not ' +\
'match number of vecs in memory.')
if my_num_rows > 0 and my_num_rows < max_num_to_send:
my_row_indices += [np.nan] * (max_num_to_send - my_num_rows)
row_vecs += [[]] * (max_num_to_send - my_num_rows)
'''
for send_index in range(max_num_to_send):
# Only processors responsible for rows communicate
if my_num_rows > 0:
# Send row vecs, in groups of num_cols_per_proc_chunk
# These become columns in the ensuing computation
start_col_index = send_index * num_cols_per_proc_chunk
end_col_index = min(
start_col_index + num_cols_per_proc_chunk,
my_num_rows)
col_vecs_send = (
row_vecs[start_col_index:end_col_index],
my_row_indices[start_col_index:end_col_index])
# Create unique tags based on ranks
send_tag = my_rank * (
parallel.get_num_procs() + 1) + dest_rank
recv_tag = source_rank * (
parallel.get_num_procs() + 1) + my_rank
# Send and receieve data. The Wait() command after the
# receive prevents a race condition not fixed by sync().
# The Wait() is very important for the non-
# blocking send (though we are unsure why).
request = parallel.comm.isend(
col_vecs_send, dest=dest_rank, tag=send_tag)
col_vecs_recv = parallel.comm.recv(
source=source_rank, tag=recv_tag)
request.Wait()
col_vecs = col_vecs_recv[0]
my_col_indices = col_vecs_recv[1]
for row_index in range(
my_row_indices[0], my_row_indices[-1] + 1):
for col_vec_index, col_vec in enumerate(col_vecs):
IP_array[
row_index,
my_col_indices[col_vec_index]
] = self.inner_product(
row_vecs[row_index - my_row_indices[0]],
col_vec)
if (
(time() - self.prev_print_time) >
self.print_interval):
num_completed_IPs = np.sum(
np.abs(np.triu(IP_array)) > 0.)
percent_completed_IPs = (
num_completed_IPs *
parallel.get_num_MPI_workers() /
total_num_IPs) * 100.
self.print_msg(
'Completed %.1f%% of inner products' %
percent_completed_IPs,
output_channel='stderr')
self.prev_print_time = time()
# Sync after send/receive
parallel.barrier()
# Fill in the rectangular portion next to each triangle (if nec.).
# Start at index after last row, continue to last column. This part
# of the code is the same as in compute_IP_array, as of
# revision 141.
for start_col_index in range(
end_row_index, num_vecs, num_cols_per_chunk):
end_col_index = min(
start_col_index + num_cols_per_chunk, num_vecs)
proc_col_tasks = parallel.find_assignments(list(range(
start_col_index, end_col_index)))[parallel.get_rank()]
# Pass the col vecs to proc with rank -> mod(rank+1,numProcs)
# Must do this for each processor, until data makes a circle
col_vecs_recv = (None, None)
if len(proc_col_tasks) > 0:
col_indices = list(range(
proc_col_tasks[0], proc_col_tasks[-1] + 1))
else:
col_indices = []
for num_passes in range(parallel.get_num_procs()):
# If on the first pass, get the col vecs, no send/recv
# This is all that is called when in serial, loop iterates
# once.
if num_passes == 0:
if len(col_indices) > 0:
col_vecs = [
col_handle.get() for col_handle in
vec_handles[col_indices[0]:col_indices[-1] + 1]]
else:
col_vecs = []
else:
# Determine whom to communicate with
dest = (
(parallel.get_rank() + 1) %
parallel.get_num_procs())
source = (
(parallel.get_rank() - 1) %
parallel.get_num_procs())
# Create unique tag based on ranks
send_tag = parallel.get_rank() * (
parallel.get_num_procs() + 1) + dest
recv_tag = source * (
parallel.get_num_procs() + 1) + parallel.get_rank()
# Collect data and send/receive
col_vecs_send = (col_vecs, col_indices)
request = parallel.comm.isend(
col_vecs_send, dest=dest, tag=send_tag)
col_vecs_recv = parallel.comm.recv(
source=source, tag=recv_tag)
request.Wait()
parallel.barrier()
col_indices = col_vecs_recv[1]
col_vecs = col_vecs_recv[0]
# Compute the IPs for this set of data col_indices stores
# the indices of the IP_array columns to be
# filled in.
if len(proc_row_tasks) > 0:
for row_index in range(
proc_row_tasks[0], proc_row_tasks[-1] + 1):
for col_vec_index, col_vec in enumerate(col_vecs):
IP_array[
row_index,
col_indices[col_vec_index]
] = self.inner_product(
row_vecs[row_index - proc_row_tasks[0]],
col_vec)
if (
(time() - self.prev_print_time) >
self.print_interval):
num_completed_IPs = np.sum(
np.abs(np.triu(IP_array)) > 0.)
percent_completed_IPs = (
num_completed_IPs *
parallel.get_num_MPI_workers() /
total_num_IPs) * 100.
self.print_msg(
'Completed %.1f%% of inner products' %
percent_completed_IPs,
output_channel='stderr')
self.prev_print_time = time()
# Completed a chunk of rows and all columns on all processors.
# Finished row_vecs loop, delete memory used
del row_vecs
# Assign the triangular portion chunks into IP_array.
if parallel.is_distributed():
IP_array = parallel.custom_comm.allreduce(IP_array)
# Create a mask for the repeated values. Select values that are zero
# in the upper triangular portion (not computed there) but nonzero in
# the lower triangular portion (computed there). For the case where
# the inner product is not perfectly symmetric, this will select the
# computation done in the upper triangular portion.
mask = np.multiply(IP_array == 0., IP_array.conj().T != 0)
# Collect values below diagonal
IP_array += np.multiply(np.triu(IP_array.conj().T, 1), mask)
# Symmetrize array
IP_array = np.triu(IP_array) + np.triu(IP_array, 1).conj().T
# Print progress
self.print_msg(
'Completed 100% of inner products', output_channel='stderr')
self.prev_print_time = time()
# Return inner product array
parallel.barrier()
return IP_array
def lin_combine(
self, sum_vec_handles, basis_vec_handles, coeff_array,
coeff_array_col_indices=None):
"""Computes linear combination(s) of basis vector objects and calls
``put`` on result(s), using handles.
Args:
``sum_vec_handles``: List of handles for the sum vector objects.
``basis_vec_handles``: List of handles for the basis vector objects.
``coeff_array``: Array whose rows correspond to basis vectors and
whose columns correspond to sum vectors. The rows and columns
correspond, by index, to the lists ``basis_vec_handles`` and
``sum_vec_handles``. In matrix notation, we can write ``sums =
basis * coeff_array``
Kwargs:
``coeff_array_col_indices``: List of column indices. Only the
``sum_vecs`` corresponding to these columns of the coefficient
array are computed. If no column indices are specified, then all
columns will be used.
Each MPI worker (processor) retrieves a subset of the basis vectors to
compute as many outputs as an MPI worker (processor) can have in memory
at once. Each MPI worker (processor) computes the "layers" from the
basis it is responsible for, and for as many modes as it can fit in
memory. The layers from all MPI workers (processors) are summed
together to form the ``sum_vecs`` and ``put`` is called on each.
Scaling is:
num gets/worker = :math:`n_s/(n_p*(max-2)) * n_b/n_p`
passes/worker = :math:`(n_p-1) * n_s/(n_p*(max-2)) * (n_b/n_p)`
scalar multiplies/worker = :math:`n_s*n_b/n_p`
where :math:`n_s` is number of sum vecs, :math:`n_b` is
number of basis vecs,
:math:`n_p` is number of processors,
:math:`max` = ``max_vecs_per_node``.
"""
sum_vec_handles = util.make_iterable(sum_vec_handles)
basis_vec_handles = util.make_iterable(basis_vec_handles)
num_bases = len(basis_vec_handles)
num_sums = len(sum_vec_handles)
# Force coefficients to be array
coeff_array = np.array(coeff_array)
# Check for 1d coefficient arrays
if coeff_array.ndim < 2:
# If there is only one basis vector, then force the coefficient
# array to be a row vector.
if num_bases == 1:
coeff_array = util.atleast_2d_row(coeff_array)
# Otherwise, force it to be a column vector.
else:
coeff_array = util.atleast_2d_col(coeff_array)
# Slice coeff array. If only one column of the array is chosen, slicing
# will produce a 1d array, which we do not want for matrix
# multiplication. So use atleast_2d_col method to force it to be a
# column vector.
if coeff_array_col_indices is not None:
coeff_array = util.atleast_2d_col(
coeff_array[:, coeff_array_col_indices])
# Check dimensions of coeff array
if num_bases != coeff_array.shape[0]:
raise ValueError((
'Number of coeff_array rows (%d) does not equal number of '
'basis handles (%d)') % (coeff_array.shape[0], num_bases))
if num_sums != coeff_array.shape[1]:
raise ValueError((
'Number of coeff_array cols (%d) does not equal number of '
'output handles (%d)') % (coeff_array.shape[1], num_sums))
# Burn the first operations to allow for slow imports
test_vec_burn = basis_vec_handles[0].get()
test_vec_burn_3 = test_vec_burn + 2. * test_vec_burn
del test_vec_burn, test_vec_burn_3
# Time get method
start_time = time()
test_vec = basis_vec_handles[0].get()
get_time = time() - start_time
# Time vector space operations
start_time = time()
test_vec_3 = test_vec + 2.*test_vec
add_scale_time = time() - start_time
del test_vec, test_vec_3
# Estimate time for all linear combinations
vecs_per_worker = (
self.max_vecs_per_node * parallel.get_num_nodes() /
parallel.get_num_MPI_workers())
num_gets = (
num_sums /
(parallel.get_num_MPI_workers()* (vecs_per_worker - 2)) +
num_bases / parallel.get_num_MPI_workers())
num_add_scales = num_sums * num_bases / parallel.get_num_MPI_workers()
self.print_msg(
'Linear combinations will take at least %.1f minutes' %
(num_gets * get_time / 60. + num_add_scales * add_scale_time / 60.))
# Convenience variable
rank = parallel.get_rank()
# num_bases_per_proc_chunk is the num of bases each proc gets at once.
num_bases_per_proc_chunk = 1
num_sums_per_proc_chunk = (
self.max_vecs_per_proc - num_bases_per_proc_chunk)
# Divide up tasks
basis_tasks = parallel.find_assignments(list(range(num_bases)))
sum_tasks = parallel.find_assignments(list(range(num_sums)))
# Find max number tasks among all processors
max_num_basis_tasks = max([len(tasks) for tasks in basis_tasks])
max_num_sum_tasks = max([len(tasks) for tasks in sum_tasks])
# These variables are the number of iters through loops that get and put
# basis and sum vecs.
num_basis_get_iters = int(np.ceil(
max_num_basis_tasks*1./num_bases_per_proc_chunk))
num_sum_put_iters = int(np.ceil(
max_num_sum_tasks*1./num_sums_per_proc_chunk))
if num_sum_put_iters > 1:
self.print_msg((
'Warning: The basis vecs, of which there are %d, will be '
'retrieved %d times each. If possible, increase number of '
'nodes or max_vecs_per_node to reduce redundant retrieves and '
'get a big speedup.') % (num_bases, num_sum_put_iters))
for sum_put_index in range(num_sum_put_iters):
if len(sum_tasks[rank]) > 0:
start_sum_index = min(
sum_tasks[rank][0] + (
sum_put_index * num_sums_per_proc_chunk),
sum_tasks[rank][-1] + 1)
end_sum_index = min(
start_sum_index + num_sums_per_proc_chunk,
sum_tasks[rank][-1] + 1)
# Create empty list on each processor
sum_layers = [None] * (end_sum_index - start_sum_index)
else:
start_sum_index = 0
end_sum_index = 0
sum_layers = []
for basis_get_index in range(num_basis_get_iters):
if len(basis_tasks[rank]) > 0:
start_basis_index = min(
basis_tasks[rank][0] +(
basis_get_index*num_bases_per_proc_chunk),
basis_tasks[rank][-1] + 1)
end_basis_index = min(
start_basis_index + num_bases_per_proc_chunk,
basis_tasks[rank][-1] + 1)
basis_indices = list(range(
start_basis_index, end_basis_index))
else:
basis_indices = []
# Pass the basis vecs to proc with rank -> mod(rank+1,num_procs)
# Must do this for each processor, until data makes a circle
basis_vecs_recv = (None, None)
for pass_index in range(parallel.get_num_procs()):
# If on the first pass, retrieve the basis vecs,
# no send/recv.
# This is all that is called when in serial,