/
arraysinterface.py
1256 lines (1025 loc) · 41.4 KB
/
arraysinterface.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
"""
Implements the ArraysInterface object and supporting functionality.
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import numpy as _np
from pygsti.tools import sharedmemtools as _smt
class ArraysInterface(object):
"""
An interface between pyGSTi's optimization methods and data storage arrays.
This class provides an abstract interface to algorithms (particularly the Levenberg-Marquardt
nonlinear least-squares algorithm) for creating an manipulating potentially distributed data
arrays with types such as "jtj" (Jacobian^T * Jacobian), "jtf" (Jacobian^T * objectivefn_vector),
and "x" (model parameter vector). The class encapsulates all the operations on these arrays so
that the algorithm doesn't need to worry about how the arrays are actually stored in memory,
e.g. whether shared memory is used or not.
"""
pass # just a base class - maybe make an abc abtract class in FUTURE?
class UndistributedArraysInterface(ArraysInterface):
"""
An arrays interface for the case when the arrays are not actually distributed.
Parameters
----------
num_global_elements : int
The total number of objective function "elements", i.e. the size of the
objective function array `f`.
num_global_params : int
The total number of (model) parameters, i.e. the size of the `x` array.
"""
def __init__(self, num_global_elements, num_global_params):
self.num_global_elements = num_global_elements
self.num_global_params = num_global_params
def allocate_jtf(self):
"""
Allocate an array for holding a `'jtf'`-type value.
Returns
-------
numpy.ndarray or LocalNumpyArray
"""
return _np.empty(self.num_global_params, 'd')
def allocate_jtj(self):
"""
Allocate an array for holding an approximated Hessian (type `'jtj'`).
Returns
-------
numpy.ndarray or LocalNumpyArray
"""
return _np.empty((self.num_global_params, self.num_global_params), 'd')
def allocate_jac(self):
"""
Allocate an array for holding a Jacobian matrix (type `'ep'`).
Returns
-------
numpy.ndarray or LocalNumpyArray
"""
return _np.empty((self.num_global_elements, self.num_global_params), 'd')
def deallocate_jtf(self, jtf):
"""
Free an array for holding an objective function value (type `'jtf'`).
Returns
-------
None
"""
pass
def deallocate_jtj(self, jtj):
"""
Free an array for holding an approximated Hessian (type `'jtj'`).
Returns
-------
None
"""
pass
def deallocate_jac(self, jac):
"""
Free an array for holding a Jacobian matrix (type `'ep'`).
Returns
-------
None
"""
pass
def global_num_elements(self):
"""
The total number of objective function "elements".
This is the size/length of the objective function `f` vector.
Returns
-------
int
"""
return self.num_global_elements
def jac_param_slice(self, only_if_leader=False):
"""
The slice into a Jacobian's columns that belong to this processor.
Parameters
----------
only_if_leader : bool, optional
If `True`, the current processor's parameter slice is ony returned if
the processor is the "leader" (i.e. the first) of the processors that
calculate the same parameter slice. All non-leader processors return
the zero-slice `slice(0,0)`.
Returns
-------
slice
"""
return slice(0, self.num_global_params)
def jtf_param_slice(self):
"""
The slice into a `'jtf'` vector giving the rows of owned by this processor.
Returns
-------
slice
"""
return slice(0, self.num_global_params)
def param_fine_info(self):
"""
Returns information regarding how model parameters are distributed among hosts and processors.
This information relates to the "fine" distribution used in distributed layouts,
and is needed by some algorithms which utilize shared-memory communication between
processors on the same host.
Returns
-------
param_fine_slices_by_host : list
A list with one entry per host. Each entry is itself a list of
`(rank, (global_param_slice, host_param_slice))` elements where `rank` is the top-level
overall rank of a processor, `global_param_slice` is the parameter slice that processor owns
and `host_param_slice` is the same slice relative to the parameters owned by the host.
owner_host_and_rank_of_global_fine_param_index : dict
A mapping between parameter indices (keys) and the owning processor rank and host index.
Values are `(host_index, processor_rank)` tuples.
"""
all_params = slice(0, self.num_global_params)
ranks_and_pslices_for_host0 = [(0, (all_params, all_params))]
param_fine_slices_by_host = [ranks_and_pslices_for_host0]
owner_host_and_rank_of_global_fine_param_index = {i: (0, 0) for i in range(self.num_global_params)}
return param_fine_slices_by_host, \
owner_host_and_rank_of_global_fine_param_index
def allgather_x(self, x, global_x):
"""
Gather a parameter (`x`) vector onto all the processors.
Parameters
----------
x : numpy.array or LocalNumpyArray
The input vector.
global_x : numpy.array or LocalNumpyArray
The output (gathered) vector.
Returns
-------
None
"""
global_x[:] = x
def allscatter_x(self, global_x, x):
"""
Pare down an already-scattered global parameter (`x`) vector to be just a local `x` vector.
Parameters
----------
global_x : numpy.array or LocalNumpyArray
The input vector. This global vector is already present on all the processors,
so there's no need to do any MPI communication.
x : numpy.array or LocalNumpyArray
The output vector, typically a slice of `global_x`..
Returns
-------
None
"""
x[:] = global_x
def scatter_x(self, global_x, x):
"""
Scatter a global parameter (`x`) vector onto all the processors.
Parameters
----------
global_x : numpy.array or LocalNumpyArray
The input vector.
x : numpy.array or LocalNumpyArray
The output (scattered) vector.
Returns
-------
None
"""
x[:] = global_x
def allgather_f(self, f, global_f):
"""
Gather an objective funtion (`f`) vector onto all the processors.
Parameters
----------
f : numpy.array or LocalNumpyArray
The input vector.
global_f : numpy.array or LocalNumpyArray
The output (gathered) vector.
Returns
-------
None
"""
global_f[:] = f
def gather_jtj(self, jtj, return_shared=False):
"""
Gather a Hessian (`jtj`) matrix onto the root processor.
Parameters
----------
jtj : numpy.array or LocalNumpyArray
The (local) input matrix to gather.
return_shared : bool, optional
Whether the returned array is allowed to be a shared-memory array, which results
in a small performance gain because the array used internally to gather the results
can be returned directly. When `True` a shared memory handle is also returned, and
the caller assumes responsibilty for freeing the memory via
:function:`pygsti.tools.sharedmemtools.cleanup_shared_ndarray`.
Returns
-------
gathered_array : numpy.ndarray or None
The full (global) output array on the root (rank=0) processor and
`None` on all other processors.
shared_memory_handle : multiprocessing.shared_memory.SharedMemory or None
Returned only when `return_shared == True`. The shared memory handle
associated with `gathered_array`, which is needed to free the memory.
"""
return (jtj, None) if return_shared else jtj # gathers just onto the root proc
def scatter_jtj(self, global_jtj, jtj):
"""
Scatter a Hessian (`jtj`) matrix onto all the processors.
Parameters
----------
global_jtj : numpy.ndarray
The global Hessian matrix to scatter.
jtj : numpy.ndarray or LocalNumpyArray
The local destination array.
Returns
-------
None
"""
jtj[:, :] = global_jtj
def gather_jtf(self, jtf, return_shared=False):
"""
Gather a `jtf` vector onto the root processor.
Parameters
----------
jtf : numpy.array or LocalNumpyArray
The local input vector to gather.
return_shared : bool, optional
Whether the returned array is allowed to be a shared-memory array, which results
in a small performance gain because the array used internally to gather the results
can be returned directly. When `True` a shared memory handle is also returned, and
the caller assumes responsibilty for freeing the memory via
:function:`pygsti.tools.sharedmemtools.cleanup_shared_ndarray`.
Returns
-------
gathered_array : numpy.ndarray or None
The full (global) output array on the root (rank=0) processor and
`None` on all other processors.
shared_memory_handle : multiprocessing.shared_memory.SharedMemory or None
Returned only when `return_shared == True`. The shared memory handle
associated with `gathered_array`, which is needed to free the memory.
"""
return (jtf, None) if return_shared else jtf
def scatter_jtf(self, global_jtf, jtf):
"""
Scatter a `jtf` vector onto all the processors.
Parameters
----------
global_jtf : numpy.ndarray
The global vector to scatter.
jtf : numpy.ndarray or LocalNumpyArray
The local destination array.
Returns
-------
None
"""
jtf[:] = global_jtf
def global_svd_dot(self, jac_v, minus_jtf):
"""
Gathers the dot product between a `jtj`-type matrix and a `jtf`-type vector into a global result array.
This is typically used within SVD-defined basis calculations, where `jac_v` is the "V"
matrix of the SVD of a jacobian, and `minus_jtf` is the negative dot product between the Jacobian
matrix and objective function vector.
Parameters
----------
jac_v : numpy.ndarray or LocalNumpyArray
An array of `jtj`-type.
minus_jtf : numpy.ndarray or LocalNumpyArray
An array of `jtf`-type.
Returns
-------
numpy.ndarray
The global (gathered) parameter vector `dot(jac_v.T, minus_jtf)`.
"""
return _np.dot(jac_v.T, minus_jtf)
def fill_dx_svd(self, jac_v, global_vec, dx):
"""
Computes the dot product of a `jtj`-type array with a global parameter array.
The result (`dx`) is a `jtf`-type array. This is typically used for
computing the x-update vector in the LM method when using a SVD-defined basis.
Parameters
----------
jac_v : numpy.ndarray or LocalNumpyArray
An array of `jtj`-type.
global_vec : numpy.ndarray
A global parameter vector.
dx : numpy.ndarray or LocalNumpyArray
An array of `jtf`-type. Filled with `dot(jac_v, global_vec)`
values.
Returns
-------
None
"""
dx[:] = _np.dot(jac_v, global_vec)
def dot_x(self, x1, x2):
"""
Take the dot product of two `x`-type vectors.
Parameters
----------
x1, x2 : numpy.ndarray or LocalNumpyArray
The vectors to operate on.
Returns
-------
float
"""
return _np.dot(x1, x2)
def norm2_x(self, x):
"""
Compute the Frobenius norm squared of an `x`-type vector.
Parameters
----------
x : numpy.ndarray or LocalNumpyArray
The vector to operate on.
Returns
-------
float
"""
return _np.dot(x, x)
def infnorm_x(self, x):
"""
Compute the infinity-norm of an `x`-type vector.
Parameters
----------
x : numpy.ndarray or LocalNumpyArray
The vector to operate on.
Returns
-------
float
"""
return _np.linalg.norm(x, ord=_np.inf) # (max(sum(abs(x), axis=1))) = max(abs(x))
def max_x(self, x):
"""
Compute the maximum of an `x`-type vector.
Parameters
----------
x : numpy.ndarray or LocalNumpyArray
The vector to operate on.
Returns
-------
float
"""
return _np.max(x)
def norm2_f(self, f):
"""
Compute the Frobenius norm squared of an `f`-type vector.
Parameters
----------
f : numpy.ndarray or LocalNumpyArray
The vector to operate on.
Returns
-------
float
"""
return _np.dot(f, f)
def norm2_jtj(self, jtj):
"""
Compute the Frobenius norm squared of an `jtj`-type matrix.
Parameters
----------
jtj : numpy.ndarray or LocalNumpyArray
The array to operate on.
Returns
-------
float
"""
return _np.linalg.norm(jtj)**2
def norm2_jac(self, j):
"""
Compute the Frobenius norm squared of an Jacobian matrix (`ep`-type).
Parameters
----------
j : numpy.ndarray or LocalNumpyArray
The Jacobian to operate on.
Returns
-------
float
"""
return _np.linalg.norm(j)
def fill_jtf(self, j, f, jtf):
"""
Compute dot(Jacobian.T, f) in supplied memory.
Parameters
----------
j : numpy.ndarray or LocalNumpyArray
Jacobian matrix (type `ep`).
f : numpy.ndarray or LocalNumpyArray
Objective function vector (type `e`).
jtf : numpy.ndarray or LocalNumpyArray
Output array, type `jtf`. Filled with `dot(j.T, f)` values.
Returns
-------
None
"""
jtf[:] = _np.dot(j.T, f)
def fill_jtj(self, j, jtj, shared_mem_buf=None):
"""
Compute dot(Jacobian.T, Jacobian) in supplied memory.
Parameters
----------
j : numpy.ndarray or LocalNumpyArray
Jacobian matrix (type `ep`).
jtf : numpy.ndarray or LocalNumpyArray
Output array, type `jtj`. Filled with `dot(j.T, j)` values.
shared_mem_buf : tuple or None
Scratch space of shared memory used to speed up repeated calls to `fill_jtj`.
If not none, the value returned from :method:`allocate_jtj_shared_mem_buf`.
Returns
-------
None
"""
jtj[:, :] = _np.dot(j.T, j)
def allocate_jtj_shared_mem_buf(self):
"""
Allocate scratch space to be used for repeated calls to :method:`fill_jtj`.
Returns
-------
scratch : numpy.ndarray or None
The scratch array.
shared_memory_handle : multiprocessing.shared_memory.SharedMemory or None
The shared memory handle associated with `scratch`, which is needed to
free the memory.
"""
return None, None
def deallocate_jtj_shared_mem_buf(self, jtj_buf):
"""
Frees the scratch memory allocated by :method:`allocate_jtj_shared_mem_buf`.
Parameters
----------
jtj_buf : tuple or None
The value returned from :method:`allocate_jtj_shared_mem_buf`
"""
pass
def jtj_diag_indices(self, jtj):
"""
The indices into a `jtj`-type array that correspond to diagonal elements of the global matrix.
If `jtj` were a global quantity, then this would just be `numpy.diag_indices_from(jtj)`,
however, it may be more complicated in actuality when different processors hold different
sections of the global matrix.
Parameters
----------
jtj : numpy.ndarray or None
The `jtj`-type array to get the indices with respect to.
Returns
-------
tuple
A tuple of 1D arrays that can be used to index the elements of `jtj` that
correspond to diagonal elements of the global jtj matrix.
"""
return _np.diag_indices_from(jtj)
class DistributedArraysInterface(ArraysInterface):
"""
An arrays interface where the arrays are distributed according to a distributed layout.
Parameters
----------
dist_layout : DistributableCOPALayout
The layout giving the distribution of the arrays.
extra_elements : int, optional
The number of additional objective function "elements" beyond those
specified by `dist_layout`. These are often used for penalty terms.
"""
def __init__(self, dist_layout, extra_elements=0):
from ..layouts.distlayout import DistributableCOPALayout as _DL
assert(isinstance(dist_layout, _DL))
self.layout = dist_layout
self.resource_alloc = self.layout.resource_alloc()
self.extra_elements = extra_elements
def allocate_jtf(self):
"""
Allocate an array for holding a `'jtf'`-type value.
Returns
-------
numpy.ndarray or LocalNumpyArray
"""
return self.layout.allocate_local_array('jtf', 'd', extra_elements=self.extra_elements)
def allocate_jtj(self):
"""
Allocate an array for holding an approximated Hessian (type `'jtj'`).
Returns
-------
numpy.ndarray or LocalNumpyArray
"""
return self.layout.allocate_local_array('jtj', 'd', extra_elements=self.extra_elements)
def allocate_jac(self):
"""
Allocate an array for holding a Jacobian matrix (type `'ep'`).
Returns
-------
numpy.ndarray or LocalNumpyArray
"""
return self.layout.allocate_local_array('ep', 'd', extra_elements=self.extra_elements)
def deallocate_jtf(self, jtf):
"""
Free an array for holding an objective function value (type `'jtf'`).
Returns
-------
None
"""
self.layout.free_local_array(jtf) # cleaup shared memory, if it was used
def deallocate_jtj(self, jtj):
"""
Free an array for holding an approximated Hessian (type `'jtj'`).
Returns
-------
None
"""
self.layout.free_local_array(jtj) # cleaup shared memory, if it was used
def deallocate_jac(self, jac):
"""
Free an array for holding a Jacobian matrix (type `'ep'`).
Returns
-------
None
"""
self.layout.free_local_array(jac) # cleaup shared memory, if it was used
def global_num_elements(self):
"""
The total number of objective function "elements".
This is the size/length of the objective function `f` vector.
Returns
-------
int
"""
return self.layout.global_num_elements + self.extra_elements
def jac_param_slice(self, only_if_leader=False):
"""
The slice into a Jacobian's columns that belong to this processor.
Parameters
----------
only_if_leader : bool, optional
If `True`, the current processor's parameter slice is ony returned if
the processor is the "leader" (i.e. the first) of the processors that
calculate the same parameter slice. All non-leader processors return
the zero-slice `slice(0,0)`.
Returns
-------
slice
"""
if only_if_leader and not self.layout.resource_alloc('param-processing').is_host_leader:
return slice(0, 0) # not the leader of the group of procs computing this same jac portion
return self.layout.global_param_slice
def jtf_param_slice(self):
"""
The slice into a `'jtf'` vector giving the rows of owned by this processor.
Returns
-------
slice
"""
return self.layout.global_param_fine_slice
def param_fine_info(self):
"""
Returns information regarding how model parameters are distributed among hosts and processors.
This information relates to the "fine" distribution used in distributed layouts,
and is needed by some algorithms which utilize shared-memory communication between
processors on the same host.
Returns
-------
param_fine_slices_by_host : list
A list with one entry per host. Each entry is itself a list of
`(rank, (global_param_slice, host_param_slice))` elements where `rank` is the top-level
overall rank of a processor, `global_param_slice` is the parameter slice that processor owns
and `host_param_slice` is the same slice relative to the parameters owned by the host.
owner_host_and_rank_of_global_fine_param_index : dict
A mapping between parameter indices (keys) and the owning processor rank and host index.
Values are `(host_index, processor_rank)` tuples.
"""
return self.layout.param_fine_slices_by_host, \
self.layout.owner_host_and_rank_of_global_fine_param_index
def allgather_x(self, x, global_x):
"""
Gather a parameter (`x`) vector onto all the processors.
Parameters
----------
x : numpy.array or LocalNumpyArray
The input vector.
global_x : numpy.array or LocalNumpyArray
The output (gathered) vector.
Returns
-------
None
"""
#TODO: do this more efficiently in future:
global_x_on_root = self.layout.gather_local_array('jtf', x)
if self.resource_alloc.comm is not None:
global_x[:] = self.resource_alloc.comm.bcast(
global_x_on_root if self.resource_alloc.comm.rank == 0 else None, root=0)
else:
global_x[:] = global_x_on_root
def allscatter_x(self, global_x, x):
"""
Pare down an already-scattered global parameter (`x`) vector to be just a local `x` vector.
Parameters
----------
global_x : numpy.array or LocalNumpyArray
The input vector. This global vector is already present on all the processors,
so there's no need to do any MPI communication.
x : numpy.array or LocalNumpyArray
The output vector, typically a slice of `global_x`..
Returns
-------
None
"""
x[:] = global_x[self.layout.global_param_fine_slice]
def scatter_x(self, global_x, x):
"""
Scatter a global parameter (`x`) vector onto all the processors.
Parameters
----------
global_x : numpy.array or LocalNumpyArray
The input vector.
x : numpy.array or LocalNumpyArray
The output (scattered) vector.
Returns
-------
None
"""
self.scatter_jtf(global_x, x)
def allgather_f(self, f, global_f):
"""
Gather an objective funtion (`f`) vector onto all the processors.
Parameters
----------
f : numpy.array or LocalNumpyArray
The input vector.
global_f : numpy.array or LocalNumpyArray
The output (gathered) vector.
Returns
-------
None
"""
#TODO: do this more efficiently in future:
global_f_on_root = self.layout.gather_local_array('e', f, extra_elements=self.extra_elements)
if self.resource_alloc.comm is not None:
global_f[:] = self.resource_alloc.comm.bcast(
global_f_on_root if self.resource_alloc.comm.rank == 0 else None, root=0)
else:
global_f[:] = global_f_on_root
def gather_jtj(self, jtj, return_shared=False):
"""
Gather a Hessian (`jtj`) matrix onto the root processor.
Parameters
----------
jtj : numpy.array or LocalNumpyArray
The (local) input matrix to gather.
return_shared : bool, optional
Whether the returned array is allowed to be a shared-memory array, which results
in a small performance gain because the array used internally to gather the results
can be returned directly. When `True` a shared memory handle is also returned, and
the caller assumes responsibilty for freeing the memory via
:function:`pygsti.tools.sharedmemtools.cleanup_shared_ndarray`.
Returns
-------
gathered_array : numpy.ndarray or None
The full (global) output array on the root (rank=0) processor and
`None` on all other processors.
shared_memory_handle : multiprocessing.shared_memory.SharedMemory or None
Returned only when `return_shared == True`. The shared memory handle
associated with `gathered_array`, which is needed to free the memory.
"""
# gathers just onto the root proc
return self.layout.gather_local_array('jtj', jtj, return_shared=return_shared)
def scatter_jtj(self, global_jtj, jtj):
"""
Scatter a Hessian (`jtj`) matrix onto all the processors.
Parameters
----------
global_jtj : numpy.ndarray
The global Hessian matrix to scatter.
jtj : numpy.ndarray or LocalNumpyArray
The local destination array.
Returns
-------
None
"""
# Don't bother trying to be fancy with shared mem here - we need to send the
# entire global_jtj from the (single) root proc anyway.
comm = self.resource_alloc.comm
if comm is not None:
jtj[:, :] = comm.scatter([global_jtj[pslc, :] for pslc in self.layout.param_fine_slices_by_rank]
if comm.rank == 0 else None, root=0)
else:
jtj[:, :] = global_jtj
def gather_jtf(self, jtf, return_shared=False):
"""
Gather a `jtf` vector onto the root processor.
Parameters
----------
jtf : numpy.array or LocalNumpyArray
The local input vector to gather.
return_shared : bool, optional
Whether the returned array is allowed to be a shared-memory array, which results
in a small performance gain because the array used internally to gather the results
can be returned directly. When `True` a shared memory handle is also returned, and
the caller assumes responsibilty for freeing the memory via
:function:`pygsti.tools.sharedmemtools.cleanup_shared_ndarray`.
Returns
-------
gathered_array : numpy.ndarray or None
The full (global) output array on the root (rank=0) processor and
`None` on all other processors.
shared_memory_handle : multiprocessing.shared_memory.SharedMemory or None
Returned only when `return_shared == True`. The shared memory handle
associated with `gathered_array`, which is needed to free the memory.
"""
# gathers just onto the root proc
return self.layout.gather_local_array('jtf', jtf, return_shared=return_shared)
def scatter_jtf(self, global_jtf, jtf):
"""
Scatter a `jtf` vector onto all the processors.
Parameters
----------
global_jtf : numpy.ndarray
The global vector to scatter.
jtf : numpy.ndarray or LocalNumpyArray
The local destination array.
Returns
-------
None
"""
# Don't bother trying to be fancy with shared mem here - we need to send the
# entire global_jtj from the (single) root proc anyway.
comm = self.resource_alloc.comm
if comm is not None:
to_scatter = [global_jtf[pslc] for pslc in self.layout.param_fine_slices_by_rank] \
if (comm.rank == 0) else None
jtf[:] = comm.scatter(to_scatter, root=0)
else:
jtf[:] = global_jtf
def global_svd_dot(self, jac_v, minus_jtf):
"""
Gathers the dot product between a `jtj`-type matrix and a `jtf`-type vector into a global result array.
This is typically used within SVD-defined basis calculations, where `jac_v` is the "V"
matrix of the SVD of a jacobian, and `minus_jtf` is the negative dot product between the Jacobian
matrix and objective function vector.
Parameters
----------
jac_v : numpy.ndarray or LocalNumpyArray
An array of `jtj`-type.
minus_jtf : numpy.ndarray or LocalNumpyArray
An array of `jtf`-type.
Returns
-------
numpy.ndarray
The global (gathered) parameter vector `dot(jac_v.T, minus_jtf)`.
"""
# Assumes jac_v is 'jtj' type and minus_jtf is 'jtf' type.
# Returns a *global* parameter array that is dot(jac_v.T, minus_jtf)
local_dot = _np.dot(jac_v.T, minus_jtf) # (nP, nP_fine) * (nP_fine) = (nP,)
#Note: Could make this more efficient by being given a shared array like this as the destination
result, result_shm = _smt.create_shared_ndarray(self.resource_alloc, (jac_v.shape[1],), 'd')
self.resource_alloc.allreduce_sum(result, local_dot,
unit_ralloc=self.layout.resource_alloc('param-fine'))
ret = result.copy()
self.resource_alloc.host_comm_barrier() # make sure we don't cleanup too quickly
_smt.cleanup_shared_ndarray(result_shm)
return ret
def fill_dx_svd(self, jac_v, global_vec, dx):
"""
Computes the dot product of a `jtj`-type array with a global parameter array.
The result (`dx`) is a `jtf`-type array. This is typically used for
computing the x-update vector in the LM method when using a SVD-defined basis.
Parameters
----------
jac_v : numpy.ndarray or LocalNumpyArray
An array of `jtj`-type.
global_vec : numpy.ndarray
A global parameter vector.
dx : numpy.ndarray or LocalNumpyArray
An array of `jtf`-type. Filled with `dot(jac_v, global_vec)`
values.
Returns
-------
None
"""
# Assumes dx is of type 'jtf' (only locally holds fine param slice)
# Assumes jac_v is of type 'jtj' (locally hosts fine param slice rows)
# Assumes global_vec is a global parameter vector
# fills dx = dot(jac, global_vec
dx[:] = _np.dot(jac_v, global_vec) # everything is local in this case!
def dot_x(self, x1, x2):
"""
Take the dot product of two `x`-type vectors.
Parameters
----------
x1, x2 : numpy.ndarray or LocalNumpyArray
The vectors to operate on.
Returns
-------
float
"""
# assumes x's are in "fine" mode
local_dot = _np.array(_np.dot(x1, x2))
local_dot.shape = (1,) # for compatibility with allreduce_sum
result, result_shm = _smt.create_shared_ndarray(self.resource_alloc, (1,), 'd')