/
KokkosGraph_Distance2Color_impl.hpp
1815 lines (1657 loc) · 75.8 KB
/
KokkosGraph_Distance2Color_impl.hpp
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
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) 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.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Brian Kelley (bmkelle@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef _KOKKOSGRAPH_DISTANCE2COLOR_IMPL_HPP
#define _KOKKOSGRAPH_DISTANCE2COLOR_IMPL_HPP
#include <iomanip>
#include <stdexcept>
#include <vector>
#include <type_traits>
#include <Kokkos_Atomic.hpp>
#include <Kokkos_Core.hpp>
#include <Kokkos_MemoryTraits.hpp>
#include <Kokkos_UniqueToken.hpp>
#include <KokkosKernels_Uniform_Initialized_MemoryPool.hpp>
#include <KokkosKernels_HashmapAccumulator.hpp>
#include <KokkosSparse_spgemm.hpp>
#include <KokkosKernels_BitUtils.hpp>
#include <Kokkos_Timer.hpp>
#include "KokkosGraph_Distance1Color.hpp"
#include "KokkosGraph_Distance1ColorHandle.hpp" // todo: remove this (SCAFFOLDING - WCMCLEN)
#include "KokkosGraph_Distance2ColorHandle.hpp"
#include "KokkosKernels_Handle.hpp"
namespace KokkosGraph {
namespace Impl {
#define VB_D2_COLORING_FORBIDDEN_SIZE 64
#define VBBIT_D2_COLORING_FORBIDDEN_SIZE 64
/*!
* \brief Distance-2 Graph Coloring class
*
* This class supports direct methods for distance-2 graph coloring.
*
* doing_bipartite == false: (xadj,adj) is expected to be a
* symmetric graph and the algorithm will always check for distance-1 conflicts.
* (t_xadj,t_adj) should alias (xadj,adj).
*
* doing_bipartite == true: (t_xadj,t_adj) must be the transpose of (xadj,adj).
* Distance-1 conflicts will not be checked.
*
*/
template<typename HandleType,
typename rowmap_t,
typename entries_t,
bool doing_bipartite>
class GraphColorDistance2
{
//Need mutable entries type for edge filtering
using nc_entries_t = typename entries_t::non_const_type;
public:
using execution_space = typename HandleType::HandleExecSpace;
using memory_space = typename HandleType::HandleTempMemorySpace;
using device_type = Kokkos::Device<execution_space, memory_space>;
using color_view_type = typename HandleType::color_view_type;
using color_type = typename HandleType::color_type;
using size_type = typename rowmap_t::non_const_value_type;
using lno_t = typename entries_t::non_const_value_type;
//Temporary view of lno_t
using lno_view_t = typename HandleType::nnz_lno_temp_work_view_type;
//Single-element (0-dim) view of lno_t:
using single_lno_view_t = typename Kokkos::View<lno_t, memory_space>;
using range_policy_type = Kokkos::RangePolicy<execution_space>;
using team_policy_type = Kokkos::TeamPolicy<execution_space>;
using team_member_type = typename team_policy_type::member_type;
using bool_view_t = Kokkos::View<bool*, memory_space>;
using bit_64_forbidden_type = uint64_t;
using bitset_t = Kokkos::Bitset<device_type>;
using forbidden_view = Kokkos::View<uint32_t*, device_type>;
protected:
lno_t nr; // num_rows (also #verts, the objects being colored)
lno_t nc; // num cols
size_type ne; // # edges
rowmap_t xadj; // rowmap, transpose of rowmap
entries_t adj; // entries, transpose of entries (size = # edges)
rowmap_t t_xadj; // transpose rowmap (aliases xadj if !doing_bipartite)
entries_t t_adj; // transpose entries (aliases adj if !doing_bipartite)
HandleType* gc_handle; // pointer to the graph coloring handle
private:
int _chunkSize; // the size of the minimum work unit assigned to threads. Changes the convergence on GPUs
int _max_num_iterations;
bool _ticToc; // if true print info in each step
bool _verbose; // if true, print verbose information
bool using_edge_filtering;
static constexpr color_type UNPROCESSED = 0;
static constexpr color_type UNCOLORABLE = ~UNPROCESSED;
static constexpr color_type CONFLICTED = UNCOLORABLE - 1;
public:
/**
* \brief GraphColorDistance2 constructor.
* \param nr_: number of vertices in the graph
* \param row_map: the xadj array of the graph. Its size is nr_ +1
* \param entries: adjacency array of the graph.
* \param handle: GraphColoringHandle object that holds the specification about the graph coloring,
* including parameters.
*/
GraphColorDistance2(lno_t nr_,
lno_t nc_,
rowmap_t row_map,
entries_t entries,
rowmap_t t_row_map,
entries_t t_entries,
HandleType* handle)
: nr(nr_)
, nc(nc_)
, ne(entries.extent(0))
, xadj(row_map)
, adj(entries)
, t_xadj(t_row_map)
, t_adj(t_entries)
, gc_handle(handle)
, _chunkSize(handle->get_vb_chunk_size())
, _max_num_iterations(handle->get_max_number_of_iterations())
, _ticToc(handle->get_verbose())
, _verbose(handle->get_verbose())
{
//Internal logic check: distance-2 coloring (non-bipartite) requires a square graph
if(!doing_bipartite && nr != nc)
{
throw std::runtime_error("D2 INTERNAL ERROR: requested undirected d2 coloring but input graph is not square (nr_ != nc_)");
}
}
/**
* \brief GraphColor destructor.
*/
virtual ~GraphColorDistance2() {}
// -----------------------------------------------------------------
//
// GraphColorDistance2::execute()
//
// -----------------------------------------------------------------
/**
* \brief Computes the distance-2 graph coloring.
*/
void compute_distance2_color()
{
//Delegate to different coloring functions, depending on algorithm
using_edge_filtering = false;
color_view_type colors_out;
if(gc_handle->get_vertex_colors().use_count() > 0){
colors_out = gc_handle->get_vertex_colors();
} else {
colors_out = color_view_type("Graph Colors", this->nr);
}
switch(this->gc_handle->get_coloring_algo_type())
{
case COLORING_D2_VB_BIT_EF:
using_edge_filtering = true;
case COLORING_D2_VB_BIT:
case COLORING_D2_VB:
compute_d2_coloring_vb(colors_out);
break;
case COLORING_D2_NB_BIT:
compute_d2_coloring_nb(colors_out);
break;
case COLORING_D2_SERIAL:
compute_d2_coloring_serial(colors_out);
break;
default:
throw std::runtime_error(std::string("D2 coloring handle has invalid algorithm: ") +
std::to_string((int) this->gc_handle->get_coloring_algo_type()));
}
}
void compute_d2_coloring_vb(const color_view_type& colors_out)
{
// Data:
// gc_handle = graph coloring handle
// nr = num_rows (scalar)
// nc = num_cols (scalar)
// xadj = row_map (view 1 dimension - [num_verts+1] - entries index into adj )
// adj = entries (view 1 dimension - [num_edges] - adjacency list )
if(this->_ticToc)
{
std::cout << "\tcolor_graph_d2 params:" << std::endl
<< "\t algorithm : " << this->gc_handle->getD2AlgorithmName() << std::endl
<< "\t ticToc : " << this->_ticToc << std::endl
<< "\t max_num_iterations : " << this->_max_num_iterations << std::endl
<< "\t chunkSize : " << this->_chunkSize << std::endl
<< "\t Edge Filtering Pass? : " << (int)using_edge_filtering << std::endl
<< "\tgraph information:" << std::endl
<< "\t nr : " << this->nr << std::endl
<< "\t ne : " << this->ne << std::endl;
/*
// For extra verbosity if debugging...
prettyPrint1DView(this->xadj, ">>> xadj ", 500);
prettyPrint1DView(this->adj, ">>> adj ", 500);
prettyPrint1DView(this->t_xadj, ">>> t_xadj ", 500);
prettyPrint1DView(this->t_adj, ">>> t_adj ", 500);
*/
}
// conflictlist - store conflicts that can happen when we're coloring in parallel.
lno_view_t current_vertexList(
Kokkos::view_alloc(Kokkos::WithoutInitializing, "vertexList"), this->nr);
lno_t current_vertexListLength = this->nr;
if(this->gc_handle->get_use_vtx_list()){
//init conflict list from coloring handle
current_vertexList = this->gc_handle->get_vertex_list();
current_vertexListLength = this->gc_handle->get_vertex_list_size();
} else {
// init conflictlist sequentially.
Kokkos::parallel_for("InitList", range_policy_type(0, this->nr), functorInitList<lno_view_t>(current_vertexList));
}
// Next iteratons's conflictList
lno_view_t next_iteration_recolorList(Kokkos::view_alloc(Kokkos::WithoutInitializing, "recolorList"), this->nr);
// Size the next iteration conflictList
single_lno_view_t next_iteration_recolorListLength("recolorListLength");
lno_t numUncolored = this->nr;
lno_t numUncoloredPreviousIter = this->nr + 1;
double time;
double total_time = 0.0;
Kokkos::Impl::Timer timer;
int iter = 0;
for(; (iter < _max_num_iterations) && (numUncolored > 0); iter++)
{
timer.reset();
// Save the # of uncolored from the previous iteration
numUncoloredPreviousIter = numUncolored;
// ------------------------------------------
// Do greedy color
// ------------------------------------------
if(using_edge_filtering)
{
// Temporary mutable copies of adj array
// * This is required for edge-filtering passes to avoid
// side effects since edge filtering modifies the adj array.
// * Allocate using lno_view_t (managed) but then access as an entries_t,
// so that it has the same type as adj
// * on the other hand, t_adj is not actually modified by EF functor
lno_view_t adj_copy(Kokkos::view_alloc(Kokkos::WithoutInitializing, "adj copy"), this->ne);
Kokkos::deep_copy(adj_copy, this->adj);
this->colorGreedyEF(this->xadj, adj_copy, this->t_xadj, this->t_adj, colors_out);
}
else
{
this->colorGreedy(
this->xadj, this->adj, this->t_xadj, this->t_adj, colors_out, current_vertexList, current_vertexListLength);
}
execution_space().fence();
if(this->_ticToc)
{
time = timer.seconds();
total_time += time;
std::cout << "\tIteration: " << iter << std::endl
<< "\t - Time speculative greedy phase : " << time << std::endl
<< "\t - Num Uncolored (greedy-color) : " << numUncolored << std::endl;
gc_handle->add_to_overall_coloring_time_phase1(time);
timer.reset();
}
// ------------------------------------------
// Find conflicts
// ------------------------------------------
bool swap_work_arrays = true; // NOTE: swap_work_arrays can go away in this example -- was only ever
// set false in the PPS code in the original D1 coloring...
// NOTE: not using colorset algorithm in this so we don't include colorset data
numUncolored = this->findConflicts(swap_work_arrays,
this->xadj,
this->adj,
this->t_xadj,
this->t_adj,
colors_out,
current_vertexList,
current_vertexListLength,
next_iteration_recolorList,
next_iteration_recolorListLength);
execution_space().fence();
if(_ticToc)
{
time = timer.seconds();
total_time += time;
std::cout << "\t - Time conflict detection : " << time << std::endl;
std::cout << "\t - Num Uncolored (conflicts) : " << numUncolored << std::endl;
gc_handle->add_to_overall_coloring_time_phase2(time);
timer.reset();
}
// Swap the work arrays (for conflictlist)
if(swap_work_arrays)
{
// Swap Work Arrays
if(iter + 1 < this->_max_num_iterations)
{
lno_view_t temp = current_vertexList;
current_vertexList = next_iteration_recolorList;
next_iteration_recolorList = temp;
current_vertexListLength = numUncolored;
next_iteration_recolorListLength = single_lno_view_t("recolorListLength");
}
}
// Bail out if we didn't make any progress since we're probably stuck and it's better to just clean up in serial.
if(numUncolored == numUncoloredPreviousIter)
break;
} // end for iterations && numUncolored > 0...
// ------------------------------------------
// clean up in serial (resolveConflictsSerial)
// ------------------------------------------
if(numUncolored > 0)
{
this->resolveConflictsSerial(this->xadj,
this->adj,
this->t_xadj,
this->t_adj,
colors_out,
current_vertexList,
current_vertexListLength);
}
execution_space().fence();
if(_ticToc)
{
time = timer.seconds();
total_time += time;
std::cout << "\tTime serial conflict resolution : " << time << std::endl;
gc_handle->add_to_overall_coloring_time_phase3(time);
}
// Save the number of phases and vertex colors to the graph coloring handle
this->gc_handle->set_vertex_colors(colors_out);
this->gc_handle->set_num_phases(iter);
} // color_graph_d2 (end)
template<int batch>
struct NB_Coloring
{
NB_Coloring(
const lno_view_t& worklist_,
const single_lno_view_t& worklen_,
color_type colorBase_,
const forbidden_view& forbidden_,
color_view_type colors_,
const rowmap_t& Vrowmap_,
const entries_t& Vcolinds_,
lno_t vertsPerThread_,
lno_t numCols_) :
worklist(worklist_), worklen(worklen_), colorBase(colorBase_), forbidden(forbidden_),
colors(colors_), Vrowmap(Vrowmap_), Vcolinds(Vcolinds_), vertsPerThread(vertsPerThread_), numCols(numCols_)
{}
KOKKOS_INLINE_FUNCTION void operator()(const lno_t ti) const
{
for(lno_t i = ti * vertsPerThread; i < (ti + 1) * vertsPerThread; i++)
{
if(i >= worklen())
return;
lno_t v = worklist(i);
//compute forbidden for v
unsigned forbid[batch] = {0};
//union the forbidden of all incident c's
size_type rowBegin = Vrowmap(v);
size_type rowEnd = Vrowmap(v + 1);
if(!doing_bipartite)
{
//gather distance-1 forbidden colors
for(int b = 0; b < batch; b++)
forbid[b] = forbidden(v * batch + b);
}
//gather distance-2 forbidden colors
for(size_type j = rowBegin; j < rowEnd; j++)
{
lno_t nei = Vcolinds(j);
if(nei < numCols)
{
for(int b = 0; b < batch; b++)
forbid[b] |= forbidden(nei * batch + b);
}
}
//Find the first 0 bit in forbid
color_type color = 0;
int colorWord = 0;
int colorBit = 0;
for(int b = 0; b < batch; b++)
{
if(~forbid[b])
{
//least_set_bit returns 1 for the least significant bit, so subtracting 1
colorWord = b;
colorBit = KokkosKernels::Impl::least_set_bit(~forbid[b]) - 1;
color = colorBase + 32 * b + colorBit;
break;
}
}
if(color && (colors(v) == 0 || colors(v) == CONFLICTED || colors(v) == UNCOLORABLE))
{
//Color v
colors(v) = color;
if(!doing_bipartite)
{
//Update forbidden for v (preventing dist-1 conflicts)
if(v < numCols)
Kokkos::atomic_fetch_or(&forbidden(v * batch + colorWord), (uint32_t) 1 << colorBit);
}
//Update forbidden for all of v's neighbors
for(size_type j = rowBegin; j < rowEnd; j++)
{
lno_t nei = Vcolinds(j);
if(nei < numCols)
{
//Update column forbidden
Kokkos::atomic_fetch_or(&forbidden(nei * batch + colorWord), (uint32_t) 1 << colorBit);
}
}
}
else if (colors(v) == 0 || colors(v) == CONFLICTED || colors(v) == UNCOLORABLE)
{
colors(v) = UNCOLORABLE;
}
}
}
lno_view_t worklist;
single_lno_view_t worklen;
color_type colorBase;
forbidden_view forbidden; //forbidden color bitset for columns
color_view_type colors;
rowmap_t Vrowmap; //V <-> C graph (row v is the columns incident to v)
entries_t Vcolinds;
lno_t vertsPerThread;
const lno_t numCols;
};
template<int batch>
struct NB_Conflict
{
NB_Conflict(
color_type colorBase_, const forbidden_view& forbidden_,
const color_view_type& colors_,
const rowmap_t& Crowmap_, const entries_t& Ccolinds_, lno_t numVerts_)
: colorBase(colorBase_), forbidden(forbidden_), colors(colors_),
Crowmap(Crowmap_), Ccolinds(Ccolinds_), numVerts(numVerts_)
{}
KOKKOS_INLINE_FUNCTION void operator()(const lno_t c) const
{
//Here, only processing 32 colors at a time.
//forbidNei is the (minimum) neighbor ID where each forbidden color was observed.
//This is why the whole batch can't be processed at once
lno_t forbidNei[32];
//Go over all the v neighbors, updating forbidden
size_type rowBegin = Crowmap(c);
size_type rowEnd = Crowmap(c + 1);
for(int b = 0; b < batch; b++)
{
unsigned forbid = 0U;
color_type batchBegin = colorBase + 32 * b;
for(size_type j = rowBegin; j <= rowEnd; j++)
{
lno_t nei;
if(j == rowEnd)
{
if(!doing_bipartite) //note: compile-time branch
nei = c;
else
break;
}
else
nei = Ccolinds(j);
if(nei >= numVerts)
continue;
color_type neiColor = colors(nei);
int colorOffset = neiColor - batchBegin;
if(colorOffset >= 0 && colorOffset < 32)
{
//if this is the first time the color has been seen, register nei in forbidNei
unsigned mask = 1U << colorOffset;
if(0 == (forbid & mask))
{
//First time seeing this color
forbidNei[colorOffset] = nei;
}
else
{
//Have seen this color before:
//must uncolor either nei or forbidNei[colorOffset] (whichever has higher ID)
if(nei > forbidNei[colorOffset])
{
//nei has a higher id than another neighbor of the same color, so uncolor nei
colors(nei) = CONFLICTED;
}
else if(nei < forbidNei[colorOffset])
{
colors(forbidNei[colorOffset]) = CONFLICTED;
forbidNei[colorOffset] = nei;
}
}
forbid |= mask;
}
}
}
}
color_type colorBase;
forbidden_view forbidden; //forbidden color bitset for columns
color_view_type colors;
rowmap_t Crowmap; //C <-> V graph (row c is the vertices incident to c)
entries_t Ccolinds;
const lno_t numVerts;
};
template<int batch>
struct NB_RefreshForbidden
{
NB_RefreshForbidden(
color_type colorBase_, const forbidden_view& forbidden_, const color_view_type& colors_,
const rowmap_t& Crowmap_, const entries_t& Ccolinds_, lno_t numVerts_)
: colorBase(colorBase_), colorEnd(colorBase + 32 * batch), forbidden(forbidden_), colors(colors_), Crowmap(Crowmap_), Ccolinds(Ccolinds_), numVerts(numVerts_)
{}
KOKKOS_INLINE_FUNCTION void operator()(const lno_t c) const
{
//compute this in registers before storing to forbidden
unsigned newForbid[batch] = {0};
//Go over all the v neighbors, updating forbidden
size_type rowBegin = Crowmap(c);
size_type rowEnd = Crowmap(c + 1);
if(!doing_bipartite)
{
//first, add d-1 conflict
color_type selfColor = colors(c);
if(colorBase <= selfColor && selfColor < colorEnd)
{
int colorWord = (selfColor - colorBase) / 32;
int colorBit = (selfColor - colorBase) % 32;
newForbid[colorWord] |= ((uint32_t) 1 << colorBit);
}
}
for(size_type i = rowBegin; i < rowEnd; i++)
{
lno_t nei = Ccolinds(i);
if(nei >= numVerts)
continue;
color_type neiColor = colors(nei);
if(colorBase <= neiColor && neiColor < colorEnd)
{
int colorWord = (neiColor - colorBase) / 32;
int colorBit = (neiColor - colorBase) % 32;
newForbid[colorWord] |= ((uint32_t) 1 << colorBit);
}
}
for(int i = 0; i < batch; i++)
forbidden(c * batch + i) = newForbid[i];
}
color_type colorBase;
color_type colorEnd;
forbidden_view forbidden; //forbidden color bitset for columns
color_view_type colors;
rowmap_t Crowmap; //C <-> V graph (row c is the vertices incident to c)
entries_t Ccolinds;
const lno_t numVerts;
};
struct NB_Worklist
{
NB_Worklist(
const color_view_type colors_, const lno_view_t& worklist_, const single_lno_view_t& worklen_, lno_t nr_)
: colors(colors_), worklist(worklist_), worklen(worklen_), nr(nr_)
{}
KOKKOS_INLINE_FUNCTION void operator()(const lno_t v, lno_t& lnum, bool finalPass) const
{
if(colors(v) == CONFLICTED)
{
if(finalPass)
worklist(lnum) = v;
lnum++;
}
if(finalPass && v == nr - 1)
{
//The very last thread in the kernel knows how many items are in the next worklist
worklen() = lnum;
}
}
color_view_type colors;
lno_view_t worklist;
single_lno_view_t worklen;
lno_t nr;
};
struct NB_UpdateBatch
{
NB_UpdateBatch(
const color_view_type& colors_, const lno_view_t& worklist_, const single_lno_view_t& worklen_, lno_t nr_)
: colors(colors_), worklist(worklist_), worklen(worklen_), nr(nr_)
{}
KOKKOS_INLINE_FUNCTION void operator()(const lno_t v, lno_t & lnum, bool finalPass) const
{
if(colors(v) == UNCOLORABLE)
{
if(finalPass)
worklist(lnum) = v;
lnum++;
}
if(finalPass && v == nr - 1)
{
//The very last thread in the kernel knows the length of the new worklist.
worklen() = lnum;
}
}
color_view_type colors;
lno_view_t worklist;
single_lno_view_t worklen;
lno_t nr;
};
void compute_d2_coloring_nb(const color_view_type& colors_out)
{
//Member data used:
// gc_handle = graph coloring handle
// nr = #vertices
// nc = #columns
// xadj/adj = graph where rows are vertices, and adjacent columns are listed
// t_xadj/t_adj = graph where rows are columns, and adjacent vertices are listed.
// Allowed to alias xadj/adj if same.
if(this->_ticToc)
{
std::cout << "\tcolor_symmetric_graph_d2 params:\n"
<< "\t\t#vertices : " << this->nr << '\n'
<< "\t\t#edges: " << this->ne << '\n';
}
//Initialize worklist with every vertex
lno_view_t worklist("Worklist", this->nr);
single_lno_view_t worklen("Worklist length");
Kokkos::deep_copy(worklen, this->nr);
// init conflictlist sequentially.
Kokkos::parallel_for("InitList", range_policy_type(0, this->nr),
functorInitList<lno_view_t>(worklist));
//Estimate the number of colors that will be needed
//The algorithm can't use more colors than the max distance-2 degree,
//but it can use fewer.
//Here, subtracting 1 to represent the self-edge
lno_t avgDeg = adj.extent(0) / (xadj.extent(0) - 1) - 1;
//This d-2 chromatic number estimate is based on the following assumptions:
// -the number of self-loops to v is just deg(v), and these can't cause conflicts
// -each node has about the same degree, so
// the total number of length-2 walks from v is about deg(v)^2
// -the constant was determined experimentally
int estNumColors = 0.1 * (avgDeg * (avgDeg - 1));
// 8 words (256 bits/colors) is the maximum allowed batch size
int batch = 8;
// but don't use more than the estimate
for(int tryBatch = 1; tryBatch < 8; tryBatch *= 2)
{
if(estNumColors <= 32 * tryBatch)
{
batch = tryBatch;
break;
}
}
const lno_t numVerts = this->nr;
const lno_t numCols = this->nc;
//note: relying on forbidden and colors_out being initialized to 0
forbidden_view forbidden("Forbidden", batch * numCols);
int iter = 0;
Kokkos::Impl::Timer timer;
lno_t currentWork = this->nr;
batch = 1;
double colorTime = 0;
double conflictTime = 0;
double forbiddenTime = 0;
double worklistTime = 0;
for(color_type colorBase = 1;; colorBase += 32 * batch)
{
//Until the worklist is completely empty, run the functor specialization for batch size
while(currentWork)
{
lno_t vertsPerThread = 1;
lno_t workBatches = (currentWork + vertsPerThread - 1) / vertsPerThread;
timer.reset();
//if still using this color set, refresh forbidden.
//This avoids using too many colors, by relying on forbidden from before previous conflict resolution (which is now stale).
//Refreshing forbidden before conflict resolution ensures that previously-colored vertices do not get recolored.
switch(batch)
{
case 1:
Kokkos::parallel_for("NB D2 Forbidden", range_policy_type(0, numCols),
NB_RefreshForbidden<1>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
break;
case 2:
Kokkos::parallel_for("NB D2 Forbidden", range_policy_type(0, numCols),
NB_RefreshForbidden<2>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
break;
case 4:
Kokkos::parallel_for("NB D2 Forbidden", range_policy_type(0, numCols),
NB_RefreshForbidden<4>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
break;
case 8:
Kokkos::parallel_for("NB D2 Forbidden", range_policy_type(0, numCols),
NB_RefreshForbidden<8>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
break;
default:;
}
forbiddenTime += timer.seconds();
timer.reset();
switch(batch)
{
case 1:
timer.reset();
Kokkos::parallel_for("NB D2 Coloring", range_policy_type(0, workBatches),
NB_Coloring<1>(worklist, worklen, colorBase, forbidden, colors_out, this->xadj, this->adj, vertsPerThread, numCols));
colorTime += timer.seconds();
timer.reset();
Kokkos::parallel_for("NB D2 Conflict Resolution", range_policy_type(0, numCols),
NB_Conflict<1>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
conflictTime += timer.seconds();
break;
case 2:
timer.reset();
Kokkos::parallel_for("NB D2 Coloring", range_policy_type(0, workBatches),
NB_Coloring<2>(worklist, worklen, colorBase, forbidden, colors_out, this->xadj, this->adj, vertsPerThread, numCols));
colorTime += timer.seconds();
timer.reset();
Kokkos::parallel_for("NB D2 Conflict Resolution", range_policy_type(0, numCols),
NB_Conflict<2>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
conflictTime += timer.seconds();
break;
case 4:
timer.reset();
Kokkos::parallel_for("NB D2 Coloring", range_policy_type(0, workBatches),
NB_Coloring<4>(worklist, worklen, colorBase, forbidden, colors_out, this->xadj, this->adj, vertsPerThread, numCols));
colorTime += timer.seconds();
timer.reset();
Kokkos::parallel_for("NB D2 Conflict Resolution", range_policy_type(0, numCols),
NB_Conflict<4>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
conflictTime += timer.seconds();
break;
case 8:
timer.reset();
Kokkos::parallel_for("NB D2 Coloring", range_policy_type(0, workBatches),
NB_Coloring<8>(worklist, worklen, colorBase, forbidden, colors_out, this->xadj, this->adj, vertsPerThread, numCols));
colorTime += timer.seconds();
timer.reset();
Kokkos::parallel_for("NB D2 Conflict Resolution", range_policy_type(0, numCols),
NB_Conflict<8>(colorBase, forbidden, colors_out, this->t_xadj, this->t_adj, numVerts));
conflictTime += timer.seconds();
break;
default:
throw std::logic_error("D2 symmetric color batch size is not a power-of-two, or is too big");
}
timer.reset();
//Then build the next worklist
Kokkos::parallel_scan("NB D2 worklist", range_policy_type(0, numVerts),
NB_Worklist(colors_out, worklist, worklen, numVerts), currentWork);
worklistTime += timer.seconds();
timer.reset();
iter++;
}
//Will need to run with a different color base, so rebuild the work list
Kokkos::parallel_scan("NB D2 Worklist Rebuild", range_policy_type(0, numVerts),
NB_UpdateBatch(colors_out, worklist, worklen, numVerts));
Kokkos::deep_copy(currentWork, worklen);
worklistTime += timer.seconds();
timer.reset();
if(currentWork == 0)
{
//Still have no work to do, meaning every vertex is colored
break;
}
//Clear forbidden before continuing
Kokkos::deep_copy(forbidden, 0U);
}
execution_space().fence();
if(this->_ticToc)
{
std::cout << "~~ D2 timings ~~\n";
std::cout << "Coloring: " << colorTime << '\n';
std::cout << "Conflict: " << conflictTime << '\n';
std::cout << "Forbidden: " << forbiddenTime << '\n';
std::cout << "Worklist: " << worklistTime << '\n';
std::cout << "** Total: " << colorTime + conflictTime + forbiddenTime + worklistTime << "\n\n";
}
if(this->_ticToc)
{
gc_handle->add_to_overall_coloring_time_phase1(timer.seconds());
timer.reset();
}
// Save the number of phases and vertex colors to the graph coloring handle
this->gc_handle->set_vertex_colors(colors_out);
this->gc_handle->set_num_phases(iter);
}
void compute_d2_coloring_serial(const color_view_type& colors_out)
{
//Member data used:
// gc_handle = graph coloring handle
// nr = #vertices
// nc = #columns
// xadj/adj = graph where rows are vertices, and adjacent columns are listed
// t_xadj/t_adj = graph where rows are columns, and adjacent vertices are listed.
// Allowed to alias xadj/adj if same.
if(this->_ticToc)
{
std::cout << "\tcolor_symmetric_graph_d2 params:\n"
<< "\t\t#vertices : " << this->nr << '\n'
<< "\t\t#edges: " << this->ne << '\n';
}
Kokkos::View<unsigned*, Kokkos::HostSpace> forbidden("Forbidden", this->nc);
auto colors = Kokkos::create_mirror_view(colors_out);
//Get the graph(s) in host space, if not already
Kokkos::View<const size_type*, Kokkos::HostSpace> Vrowmap = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), this->xadj);
Kokkos::View<const lno_t*, Kokkos::HostSpace> Vcolinds = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), this->adj);
//Create worklist
Kokkos::View<lno_t*, Kokkos::HostSpace> worklist(Kokkos::view_alloc(Kokkos::WithoutInitializing, "Worklist"), this->nr);
int iter = 0;
Kokkos::Impl::Timer timer;
lno_t currentWork = this->nr;
lno_t numCols = this->nc;
for(color_type colorBase = 1; currentWork > 0; colorBase += 32)
{
//Rebuilding the worklist in-place.
lno_t worklistOutput = 0;
for(lno_t i = 0; i < currentWork; i++)
{
lno_t v = i;
if(iter > 0)
v = worklist(i);
//Compute v's forbidden for this batch
unsigned forbid = 0;
size_type rowBegin = Vrowmap(v);
size_type rowEnd = Vrowmap(v + 1);
//always include the diagonal (self-edge), to avoid distance-1 conflicts.
if(!doing_bipartite)
forbid |= forbidden(v);
for(size_type j = rowBegin; j < rowEnd; j++)
{
lno_t nei = Vcolinds(j);
if(nei < numCols)
forbid |= forbidden(nei);
}
if(~forbid)
{
int bitOffset = KokkosKernels::Impl::least_set_bit(~forbid) - 1;
colors(v) = colorBase + bitOffset;
//Together with including diagonal, setting forbidden(v)
//with v's color will prevent all distance-1 conflicts
if(v < numCols)
forbidden(v) |= (1U << bitOffset);
for(size_type j = rowBegin; j < rowEnd; j++)
{
lno_t nei = Vcolinds(j);
//marking forbidden on out-neighbors of v prevents distance-2 conflicts
if(nei < numCols)
forbidden(nei) |= (1U << bitOffset);
}
}
else
{
//Can't color in this batch, so add to worklist
worklist(worklistOutput++) = v;
}
}
currentWork = worklistOutput;
//Clear all forbidden bits
Kokkos::deep_copy(forbidden, 0U);
iter++;
}
if(this->_ticToc)
{
gc_handle->add_to_overall_coloring_time_phase1(timer.seconds());
}
// Save the number of phases and vertex colors to the graph coloring handle
Kokkos::deep_copy(colors_out, colors);
this->gc_handle->set_vertex_colors(colors_out);
this->gc_handle->set_num_phases(iter);
}
private:
// -----------------------------------------------------------------
//
// GraphColorDistance2::colorGreedy()
//
// -----------------------------------------------------------------
void colorGreedy(rowmap_t xadj_,
entries_t adj_,
rowmap_t t_xadj_,
entries_t t_adj_,
color_view_type vertex_colors_,
lno_view_t current_vertexList_,
lno_t current_vertexListLength_)
{
lno_t chunkSize_ = this->_chunkSize;
if(current_vertexListLength_ < 100 * chunkSize_)
{
chunkSize_ = 1;
}
// Pick the right coloring algorithm to use based on which algorithm we're using
switch(this->gc_handle->get_coloring_algo_type())
{
// Single level parallelism on chunks
// 1. [P] loop over vertices
// 2. [S] loop over color offset blocks
// 3. [S] loop over vertex neighbors
// 4. [S] loop over vertex neighbors of neighbors
case COLORING_D2_VB:
{
functorGreedyColorVB gc(
this->nr, this->nc, xadj_, adj_, t_xadj_, t_adj_, vertex_colors_, current_vertexList_, current_vertexListLength_);
Kokkos::parallel_for("LoopOverChunks", range_policy_type(0, this->nr), gc);
}
break;
// One level Perallelism, BIT Array for coloring
// 1. [P] loop over vertices
// 2. [S] loop over color offset blocks
// 3. [S] loop over vertex neighbors
// 4. [S] loop over vertex neighbors of neighbors
case COLORING_D2_VB_BIT:
{
functorGreedyColorVB_BIT gc(
this->nr, this->nc, xadj_, adj_, t_xadj_, t_adj_, vertex_colors_, current_vertexList_, current_vertexListLength_);
Kokkos::parallel_for("LoopOverChunks", range_policy_type(0, this->nr), gc);
}
break;
default:
throw std::invalid_argument("Unknown Distance-2 Algorithm Type or invalid for non Edge Filtering mode.");