-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoskar_grid_wproj_gpu.cu.old
2166 lines (1779 loc) · 83.9 KB
/
oskar_grid_wproj_gpu.cu.old
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
#include <math.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#include <assert.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <chrono>
#include <cmath>
#include "datastruct_utils.hpp"
#include "oskar_grid_wproj_gpu.hpp"
#include "gpu_support.hpp"
// The default 8+8 seems to be a good choice but other combinations may be interesting
//
// Remark: Surprisingly, replacing registers by shmem does not seem to reduce register usage
// in my current best version. I suspect that ptxas notices that the shared memory
// elements are written and read multiple times without any possibility that
// the value was changed by another thread (because there is no barrier between the
// reads and writes).
// I fixed that problem by introducing a fake __syncthread() at the end of the loop.
// However, using shared memory is costing a few registers so the benefit of using
// shm is limited. So far, the best configuration appears to be 0+16 (no shared at all
// but 72 registers) and 4+12 (a bit of shared and only 64 registers so optimal 50%
// occupancy).
//
// Reminder: using less than 64 registers does not bing anything when using blocks
// of size 32x1 (on Pascal)
//
// By default. prefer to keep the 4+12 configuration to always verify that the shm
// code is not broken by my changes
//
// As of now: 0+16 is good for VERS==6 but bad for VERS==1
// 4+12 is good for both (the best?)
//
// For version 1, the case 4+12 seems to be the best choice by far.
// The case 5+11 is 20% sloweron the outer tiles for the same register usage. Why?
// There must be a reason. Maybe some shared memory alignment issues
//
#define GRIDDING_TILED_SHMSZ 8
#define GRIDDING_TILED_REGSZ 8
#define GRIDDING_TILED (GRIDDING_TILED_SHMSZ+ GRIDDING_TILED_REGSZ)
// TO INVESTIGATE:
// Th profiling metrics shared_load_transactions_per_request and shared_store_transactions_per_request
// are significantly different for versions 6 and 1 ( ~2.0 vs ~1.5 ). I cannot figure why since
// both versions are supposed to access the shared memory exactly in the same way.
// However, shared_load_transactions and shared_store_transactions are reporting the exact same values.
// This is very strange!!!!
// POSSIBLE ANSWER: Could it be that shared_load_transactions and shared_store_transactions are computed globally
// while shared_load_transactions_per_request and shared_store_transactions_per_request
// are computed on a single SM or block.
//
// Current version with manual software pipelining = 6
// Original version = 1
//
// Initially, the version 6 was the best by far but some of the other
// small optimizations I introduced have a greater effect on version 1 so
// both versions now give similar performances.
//
// In face, version 1 is now the fastest.
//
// Version 6 has the advantage of reducing the stalls caused by load
// latencies but the code is slighly more complex and so generate
// more instructions which is detrimental since the kernel is instruction
// bound.
//
#define VERS 1
// Control a small pointer optimization that may or not be beneficial
// The benefit if any is small (~1%)
// UPDATE: THE BENEFIT IS SIGNIFICANT FOR THE DYNAMIC VERSION (~30ms) BUT ... THAT COULD JUST BE AN UNEXPECTED SIZE EFFECT ...
#define PTR_OPTIM 1
// Control if some integral comptation must be done in a different way
// This is actually benefical for VERS==1 but not for VERS==6
// It is unclear why.
// This is probably because the optimization introduces more instructions (so larger code and more instruction cache misses)
#define OFF_U_OPTIM (VERS==1)
//#define OFF_U_OPTIM 1
// Force the use of FMA in the gridding kernel
// x += a*b + c*d
// =>
// x += a*b
// x += c*d
// That may cause rounding errors so the compiler won't do it by default (even with fast-math)
// The benefit is quite small but measurable (1% to 2%)
#define FORCE_FMA 1
// An attempt to specialize the inner code for the two cases
// conv_mul==-1.0 and conv_mul==+1.0
// This effectively saves one float operation but globally speaking
// this is not beneficial. CURRENTLY BROKEN!!!
// #define USE_CONV_MUL2 0
// Chose the number of warps per block during gridding (1 or 2)
// Warning: This is also going to affect the tile size
// The default is to use 2 warps per block which makes sense on Kepler since
// the number of block per SM is limited to 16 (so max occupancy of (2*32)*16 = 1024 = 50%.
// However, on Pascal, the limit was raised to 32 blocks per SM which mean that
// 50% occupancy can now be achieved with blocks of size 32.
// The main advantage of using a single warp is that we avoid the work imbalance between
// the 2 warps.
// The disavantage is that the tiles are smaller.
// Be aware that in the current implementation the central box has a hardcoded size of 9x9 tiles
// so reducing the tile size will also reduce the the size of the central box.
//
// At the time I write those lines I get
//
// With 32x32 tiles (so NWARPS=2)
// GPU processing tiles: outer tiles is 754.954ms
// GPU processing tiles: central box is 151.815ms
// GPU processing non-tiles: 0.008192ms
// GPU overall gridding tile: 906.801ms
// Total GPU processing time is 1154.11ms
// With 32x16 tiles (so NWARPS=1)
// GPU processing tiles: outer tiles is 734.518ms
// GPU processing tiles: central box is 104.099ms (REMINDER: not the same central box)
// GPU processing non-tiles: 0.00816ms
// GPU overall gridding tile: 838.647ms
// Total GPU processing time is 1155.7ms
//
// So the overall gridding time is better the TOTAL time is the same because the 'initialisation'
// is costing more (because of there is more tiles to prepare?)
//
// IDEA: Consider the idea of tiles of size 16x16 processed by a single warp. Each half warp would
// process either the odd or the even values of 'j'. The main advantage of using tiles with a smaller
// width is to improve the warp efficiency (i.e. less divergence at the is_my_k test )
// This is not very difficult to implement: Rename the current BlockDim.y into BlockDim.z to
// control the number of warps in each block, and use BlockDim.x*BlockDim.y=16*2=32 to control how the
// thread in each warp are distributed. The main advatnage of that approach is of course that
// each thread only has to process 8 value in the j direction so register usage could be quite low.
//
//
#define NWARPS 1
// Tile size
#define TX 32
#define TY (NWARPS*GRIDDING_TILED)
// When that macro is defined, it is used as 'oversample' in the gridding kernel.
// That can lead to a few percents acceleration.
// Comment it out to use the 'unknown' value passed as argument
// In prouction code, the kernel should be specialized for multiple values of oversample (so a template argument?)
#if 1
#define ASSUME_OVERSAMPLE 4
#endif
/**
* Make the grid hit intensity for a given kernel and set of visibilities.
*
* The kernel must be launched with a 2D thread block with 32 threads in the X direction,
* i.e.
* blockDim.x == 32
* The kernel will process each visibility with a warp, so I need a whole number of warps.
* We just use a standard 1D grid of any size
*/
__global__ void oskar_make_grid_hit_intensity(
const int num_w_planes,
const int* support,
const int num_vis,
const float* uu,
const float* vv,
const float* ww,
const double cell_size_rad,
const double w_scale,
const int grid_size,
int * grid_intensity)
{
const int g_centre = grid_size / 2;
const double scale = grid_size * cell_size_rad;
#if 1
/* Compute the grid hit intensity
*/
const int warpIdKernel = blockIdx.x * blockDim.y + threadIdx.y;
const int nwarpsKernel = gridDim.x * blockDim.y;
/* Loop over visibilities. */
for (int i = warpIdKernel; i < num_vis; i+=nwarpsKernel)
{
/* Convert UV coordinates to grid coordinates. */
const float pos_u = -uu[i] * scale;
const float pos_v = vv[i] * scale;
const float ww_i = ww[i];
const int grid_u = (int)round(pos_u) + g_centre;
const int grid_v = (int)round(pos_v) + g_centre;
int grid_w = (int)round(sqrt(fabs(ww_i * w_scale))); /* w-plane index */
if (grid_w >= num_w_planes) grid_w = num_w_planes - 1;
/* Catch points that would lie outside the grid. */
const int wsupport = support[grid_w];
if (grid_u + wsupport >= grid_size || grid_u - wsupport < 0 ||
grid_v + wsupport >= grid_size || grid_v - wsupport < 0)
{
continue;
}
for (int j = -wsupport; j <= wsupport; ++j)
{
for (int k = -wsupport+threadIdx.x; k <= wsupport; k+=warpSize)
{
int p = (((grid_v + j) * grid_size) + grid_u + k);
atomicAdd(grid_intensity+p, 1);
}
}
}
#else
/* Plot the visibility intensity, i.e. a intensity map of just the visibility points
*/
const int tidKernel = blockIdx.x * blockDim.y*blockDim.x + threadIdx.y*blockDim.x + threadIdx.x;
const int nthdsKernel = gridDim.x * blockDim.y*blockDim.x;
/* Loop over visibilities. */
for (int i = tidKernel; i < num_vis; i+=nthdsKernel)
{
/* Convert UV coordinates to grid coordinates. */
const float pos_u = -uu[i] * scale;
const float pos_v = vv[i] * scale;
const float ww_i = ww[i];
const int grid_u = (int)round(pos_u) + g_centre;
const int grid_v = (int)round(pos_v) + g_centre;
int grid_w = (int)round(sqrt(fabs(ww_i * w_scale))); /* w-plane index */
if (grid_w >= num_w_planes) grid_w = num_w_planes - 1;
/* Catch points that would lie outside the grid. */
const int wsupport = support[grid_w];
if (grid_u + wsupport >= grid_size || grid_u - wsupport < 0 ||
grid_v + wsupport >= grid_size || grid_v - wsupport < 0)
{
continue;
}
int p = (((grid_v + 0) * grid_size) + grid_u + 0);
atomicAdd(grid_intensity+p, 1);
}
#endif
}
/**
* Computing the box which bounds the area of grid that is actually updated. We call this the 'active grid'.
*
* Launch kernel with standard 1D grid of 1D blocks, no restrictions.
*/
__global__ void oskar_get_bounding_box(
const int num_w_planes,
const int* support,
const int num_vis,
const float* uu,
const float* vv,
const float* ww,
const double cell_size_rad,
const double w_scale,
const int grid_size,
Box * d_box, // The active grid
int * num_skipped // The number of visibilities skipped
)
{
const int g_centre = grid_size / 2;
const double scale = grid_size * cell_size_rad;
// Our local bounding box
Point topLeft(2*grid_size, 2*grid_size);
Point botRight(-1, -1);
int loc_num_skipped = 0;
// Need 1D thread block
const int tid = threadIdx.x + blockIdx.x*blockDim.x;
// We need 1D grid
const int nthds = blockDim.x*blockDim.y * gridDim.x;
/* Loop over visibilities. */
for (int i = tid; i < num_vis; i+=nthds)
{
/* Convert UV coordinates to grid coordinates. */
const float pos_u = -uu[i] * scale;
const float pos_v = vv[i] * scale;
const float ww_i = ww[i];
const int grid_u = (int)round(pos_u) + g_centre;
const int grid_v = (int)round(pos_v) + g_centre;
int grid_w = (int)round(sqrt(fabs(ww_i * w_scale))); /* w-plane index */
if (grid_w >= num_w_planes) grid_w = num_w_planes - 1;
/* Catch points that would lie outside the grid. */
const int wsupport = support[grid_w];
if (grid_u + wsupport >= grid_size || grid_u - wsupport < 0 ||
grid_v + wsupport >= grid_size || grid_v - wsupport < 0)
{
loc_num_skipped++;
continue;
}
int u = grid_u - wsupport;
int v = grid_v - wsupport;
topLeft.u = (u < topLeft.u ? u : topLeft.u);
topLeft.v = (v < topLeft.v ? v : topLeft.v);
u = grid_u + wsupport;
v = grid_v + wsupport;
botRight.u = (u > botRight.u ? u : botRight.u);
botRight.v = (v > botRight.v ? v : botRight.v);
}
// Now need to reduce these quantities across all the threads in the block
__shared__ int shmem[2*32];
int point[2] = {topLeft.u, topLeft.v};
block_reducemin<int,2>(point, shmem);
topLeft.u = point[0]; topLeft.v = point[1];
point[0] = botRight.u;
point[1] = botRight.v;
block_reducemax<int,2>(point, shmem);
botRight.u = point[0]; botRight.v = point[1];
block_reduceplus<int>(loc_num_skipped, shmem);
// Thread 0 now atomically updates results in GDDR
if(threadIdx.x==0 && threadIdx.y==0) {
atomicMin(&(d_box[0].topLeft.u), topLeft.u);
atomicMin(&(d_box[0].topLeft.v), topLeft.v);
atomicMax(&(d_box[0].botRight.u), botRight.u);
atomicMax(&(d_box[0].botRight.v), botRight.v);
atomicAdd(num_skipped, loc_num_skipped);
}
}
/**
* Runs through all the visibilities and counts how many fall into each tile.
* This is written to numPointsInTiles.
*
* Launch with a regular 1D grid with 1D blocks.
*/
__global__ void oskar_count_elements_in_tiles(
const int num_w_planes,
const int* support,
const int oversample,
const int num_vis,
const float* uu,
const float* vv,
const float* ww,
const double cell_size_rad,
const double w_scale,
const float grid_size,
const Box tileBox, // The tile box describing the region to be tiled
const Point tileSize, // The size of a tile
const Point numTiles, // Number of tiles in the U and V directions
int * numPointsInTiles // Array holding the number of points in each tile
)
{
const int g_centre = int(grid_size) / 2;
const double scale = grid_size * cell_size_rad;
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int nthds = gridDim.x * blockDim.x;
#define NUM_POINTS_IN_TILES(uu, vv) numPointsInTiles[ (uu) + (vv)*numTiles.u ]
#define NUM_POINTS_OUTSIDE_TILES numPointsInTiles[ numTiles.v*numTiles.u ]
const float tileWidth = float(tileSize.u);
const float tileHeight = float(tileSize.v);
/* Loop over visibilities. */
for (int i = tid; i < num_vis; i+=nthds)
{
/* Convert UV coordinates to grid coordinates. */
const float pos_u = -uu[i] * scale;
const float pos_v = vv[i] * scale;
const float ww_i = ww[i];
const float grid_u = (int)round(pos_u) + g_centre;
const float grid_v = (int)round(pos_v) + g_centre;
int grid_w = (int)round(sqrt(fabs(ww_i * w_scale))); /* w-plane index */
if (grid_w >= num_w_planes) grid_w = num_w_planes - 1;
/* Catch points that would lie outside the grid. */
const float wsupport = support[grid_w];
if (grid_u + wsupport >= grid_size || grid_u - wsupport < 0 ||
grid_v + wsupport >= grid_size || grid_v - wsupport < 0)
{
continue;
}
/* This is a fiddly calculation. We know each visibility will intersect one
* or more tiles, and we know the set of tiles that are intersected will
* form a rectangle (since we have rectangles intersecting a square). So we now
* try to find the start and end (U,V) tile coordinates which define this
* rectangle. We compute the following in floating point:
* tileBox.topLeft.u + pu1*tileWidth <= grid_u - wsupport
* grid_u + wsupport <= tileBox.topLeft.u + pu2*tileWidth - 1
*/
float fu1 = float(grid_u - wsupport - tileBox.topLeft.u)/tileWidth;
float fu2 = float(grid_u + wsupport - tileBox.topLeft.u + 1.0f)/tileWidth;
// Intersect [fu1, fu2] with [0, numTiles.u)
float fu_int[] = { (fu1<0.0f ? 0.0f: fu1), (fu2>numTiles.u ? numTiles.u : fu2) };
int u_int[] = { int( floor(fu_int[0]) ), int( ceil(fu_int[1]) ) };
float fv1 = float(grid_v - wsupport - tileBox.topLeft.v)/tileHeight;
float fv2 = float(grid_v + wsupport - tileBox.topLeft.v + 1)/tileHeight;
// Intersect [fv1, fv2] with [0, numTiles.v)
float fv_int[] = { (fv1<0.0f ? 0.0f: fv1), (fv2>numTiles.v ? numTiles.v : fv2) };
int v_int[] = { int( floor(fv_int[0]) ), int( ceil(fv_int[1]) ) };
for (int pv=v_int[0]; pv < v_int[1]; pv++)
{
for (int pu = u_int[0]; pu < u_int[1]; pu++)
{
atomicAdd(&NUM_POINTS_IN_TILES(pu, pv), 1);
}
}
// Now need to check whether this grid point would also have hit grid areas
// not covered by any tiles.
if( grid_u-wsupport < tileBox.topLeft.u ||
grid_u+wsupport >= tileBox.botRight.u ||
grid_v-wsupport < tileBox.topLeft.v ||
grid_v+wsupport >= tileBox.botRight.v )
{
atomicAdd(&NUM_POINTS_OUTSIDE_TILES, 1);
}
} // END of visibilities loop
#undef NUM_POINTS_IN_TILES
#undef NUM_POINTS_OUTSIDE_TILES
}
/**
* This is just a simple scan up the numPointsInTiles array. Since the array is small
* we just use one thread block. The scan is written to offsetsPointsInTiles as
* well as wk_offsetsPointsInTiles - this second copy will be used by the bucket sort
*
* Launch with 1 thread block with 1024 threads.
*/
__global__ void oskar_accumulate_tile_offsets(
const Point numTiles, // Number of tiles
const int * numPointsInTiles, // The number of points in each tile
int * offsetsPointsInTiles, // Starting indexes of visibilities in each tile
int * wk_offsetsPointsInTiles // Copy of the previous array
)
{
__shared__ int intshmem[32];
const int nTiles = numTiles.u*numTiles.v + 1;
int runningTotal = 0;
// Because we have __syncthreads in the loop, we need all the threads
// to do the same number of iterations. Call me paranoid, but ...
int nloops = (nTiles + blockDim.x - 1) / blockDim.x;
int idx = threadIdx.x;
for(int i = 0; i<=nloops; i++)
{
int n = 0;
if(idx < nTiles)
n = numPointsInTiles[idx];
int cusum, total;
block_exclusive_scanplus(n, cusum, total, intshmem);
cusum += runningTotal;
if(idx < nTiles + 1) {
offsetsPointsInTiles[idx] = cusum;
wk_offsetsPointsInTiles[idx] = cusum;
}
idx += blockDim.x;
runningTotal += total;
}
}
/**
* A thoroughly deserving name.
* Exercise to the reader : this can only go faster. Make it so ...
*
* Does a bucket sort on the input visibilities. Each tile is a bucket.
* There is also a final bucket for any visibilities that fall outside
* the tiled region. This is to support the use case where only part
* of the active grid (or none of the active grid) is tiled.
*
* Launch this kernel with a regular 1D grid of 1D blocks, nothing special.
*/
__global__ void oskar_worlds_least_efficient_bucket_sort(
const int num_w_planes,
const int* support,
const int num_vis,
const float* uu,
const float* vv,
const float* ww,
const float* vis,
const float* weight,
const double cell_size_rad,
const double w_scale,
const int grid_size,
const Box tileBox, // The grid region that is tiled
const Point tileSize, // The tile size
const Point numTiles, // Number of tiles in U and V directions
const int * __restrict const numPointsInTiles, // Number of visibilities in each tile and no tiles
int * offsetsPointsInTiles, // Start of visibility data for each tile. This will be
// modified by this routine!
float * bucket_uu, // Output: bucket sorted values
float * bucket_vv, // Output: bucket sorted values
float * bucket_ww, // Output: bucket sorted values
float2 * bucket_vis, // Output: bucket sorted values
float * bucket_weight, // Output: bucket sorted values
int2 * bucket_tile // Output: bucket sorted values
)
{
const int g_centre = grid_size / 2;
const double scale = grid_size * cell_size_rad;
#define NUM_POINTS_IN_TILES(uu, vv) numPointsInTiles[ (uu) + (vv)*numTiles.u]
#define OFFSETS_IN_TILES(uu, vv) offsetsPointsInTiles[ (uu) + (vv)*numTiles.u ]
#define OFFSETS_OUTSIDE_TILES offsetsPointsInTiles[ numTiles.u*numTiles.v ]
const int nthds = gridDim.x * blockDim.x;
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
/* Loop over visibilities. */
for (int i = tid; i < num_vis; i+=nthds)
{
/* Convert UV coordinates to grid coordinates. */
float pos_u = -uu[i] * scale;
float pos_v = vv[i] * scale;
float ww_i = ww[i];
const int grid_u = (int)round(pos_u) + g_centre;
const int grid_v = (int)round(pos_v) + g_centre;
int grid_w = (int)round(sqrt(fabs(ww_i * w_scale))); /* w-plane index */
if(grid_w >= num_w_planes) grid_w = num_w_planes - 1;
/* Skip points that would lie outside the grid. */
const int wsupport = support[grid_w];
if (grid_u + wsupport >= grid_size || grid_u - wsupport < 0 ||
grid_v + wsupport >= grid_size || grid_v - wsupport < 0)
{
continue;
}
/* This is a fiddly calculation. We know each visibility will intersect one
* or more tiles, and we know the set of tiles that are intersected will
* form a rectangle (since we have rectangles intersecting a square). So we now
* try to find the start and end (U,V) tile coordinates which define this
* rectangle. We compute the following in floating point:
* tileBox.topLeft.u + pu1*tileWidth <= grid_u - wsupport
* grid_u + wsupport <= tileBox.topLeft.u + pu2*tileWidth - 1
*/
float fu1 = float(grid_u - wsupport - tileBox.topLeft.u)/tileSize.u;
float fu2 = float(grid_u + wsupport - tileBox.topLeft.u + 1)/tileSize.u;
// Intersect [fu1, fu2] with [0, numTiles.u)
float fu_int[] = { (fu1<0.0f ? 0.0f: fu1), (fu2>numTiles.u ? numTiles.u : fu2) };
int u_int[] = { (int)floor(fu_int[0]), (int)ceil(fu_int[1]) };
float fv1 = float(grid_v - wsupport - tileBox.topLeft.v)/tileSize.v;
float fv2 = float(grid_v + wsupport - tileBox.topLeft.v + 1)/tileSize.v;
// Intersect [fv1, fv2] with [0, numTiles.v)
float fv_int[] = { (fv1<0.0f ? 0.0f: fv1), (fv2>numTiles.v ? numTiles.v : fv2) };
int v_int[] = { (int)floor(fv_int[0]), (int)ceil(fv_int[1]) };
for (int pv=v_int[0]; pv < v_int[1]; pv++)
{
for (int pu = u_int[0]; pu < u_int[1]; pu++)
{
// Get current offset and increment offset by one
int off = atomicAdd(&OFFSETS_IN_TILES(pu, pv), 1);
bucket_uu[off] = uu[i];
bucket_vv[off] = vv[i];
bucket_ww[off] = ww[i];
float2 v;
v.x = vis[2 * i];
v.y = vis[2 * i + 1];
bucket_vis[off] = v;
bucket_weight[off] = weight[i];
int2 pu_pv = { pu,pv } ;
pu_pv.x = pu ;
pu_pv.y = pv ;
bucket_tile[off] = pu_pv ;
}
}
// Now need to check whether this grid point would also have hit grid areas
// not covered by any tiles.
if( grid_u-wsupport < tileBox.topLeft.u ||
grid_u+wsupport >= tileBox.botRight.u ||
grid_v-wsupport < tileBox.topLeft.v ||
grid_v+wsupport >= tileBox.botRight.v )
{
// Get current offset and increment offset by one
int off = atomicAdd(&OFFSETS_OUTSIDE_TILES, 1);
bucket_uu[off] = uu[i];
bucket_vv[off] = vv[i];
bucket_ww[off] = ww[i];
float2 v;
v.x = vis[2 * i];
v.y = vis[2 * i + 1];
bucket_vis[off] = v;
bucket_weight[off] = weight[i];
}
} // END loop over visibilities
#undef NUM_POINTS_IN_TILES
#undef OFFSETS_IN_TILES
#undef OFFSETS_OUTSIDE_TILES
}
/**
* Process all visibilities that fall outside the tiled region. This supports the use case
* where part of the active region is tiled, but not all of it. The extreme case is when
* the active region is not tiled at all, when all visibilities are processed by this kernel.
* This is in fact faster on pre-Pascal architectures.
*
* Launch this kernel with a 1D grid of 2D blocks. We must have
*
* blockDim.x == 32
*
* We can set blockDim.y to any value. This kernel uses a whole warp to
* process each visibility.
*/
__global__ void oskar_process_visibilities_outside_tile_box(
const int num_w_planes,
const int* support,
const int oversample,
const int * const __restrict compacted_wkernel_start_idx, // Start index of each convolution kernel
const float2 * const __restrict compacted_wkernels, // The compacted convolution stack
const double cell_size_rad,
const double w_scale,
const int grid_size,
const Box boundingBox,
const Box tileBox,
const Point numTiles,
const int * __restrict const numPointsInTiles,
const int * __restrict const offsetsPointsInTiles,
const float * __restrict const bucket_uu,
const float * __restrict const bucket_vv,
const float * __restrict const bucket_ww,
const float2 * __restrict const bucket_vis,
const float * __restrict const bucket_weight,
double* norm,
float * grid,
const int ld_grid
)
{
#define OFFSETS_OUTSIDE_TILES offsetsPointsInTiles[ numTiles.u*numTiles.v ]
#define NUM_POINTS_OUTSIDE_TILES numPointsInTiles[ numTiles.u*numTiles.v ]
const int g_centre = grid_size / 2;
const double scale = grid_size * cell_size_rad;
// Index of this warp in the whole kernel
const int warpIdKernel = blockIdx.x * blockDim.y + threadIdx.y;
// Number of warps in the kernel
const int nwarpsKernel = gridDim.x * blockDim.y;
double loc_norm = 0;
const int tileOffset = OFFSETS_OUTSIDE_TILES;
const int num_vis = NUM_POINTS_OUTSIDE_TILES;
/* Loop over visibilities. */
for (int i = warpIdKernel; i < num_vis; i+=nwarpsKernel)
{
double sum;
/* Convert UV coordinates to grid coordinates. */
const float pos_u = -bucket_uu[tileOffset+i] * scale;
const float pos_v = bucket_vv[tileOffset+i] * scale;
const float ww_i = bucket_ww[tileOffset+i];
const float w = bucket_weight[tileOffset+i];
float2 val = bucket_vis[tileOffset+i];
val.x *= w;
val.y *= w;
const int grid_u = (int)round(pos_u) + g_centre;
const int grid_v = (int)round(pos_v) + g_centre;
int grid_w = (int)round(sqrt(fabs(ww_i * w_scale))); /* w-plane index */
if (grid_w >= num_w_planes) grid_w = num_w_planes - 1;
const int wsupport = support[grid_w];
const int wkernel_start = compacted_wkernel_start_idx[grid_w];
const int wkernel_size = oversample/2 + wsupport*oversample + 1;
/* Scaled distance from nearest grid point. */
const int off_u = (int)round( (round(pos_u)-pos_u) * oversample); // \in [-oversample/2, oversample/2]
const int off_v = (int)round( (round(pos_v)-pos_v) * oversample); // \in [-oversample/2, oversample/2]
/* Convolve this point. */
sum = 0.0;
float conv_mul = (ww_i > 0 ? -1.0f : 1.0f);
// Nicer indexing in the wkernel. We only change indexing in u, not v
int abs_offu = (off_u < 0 ? -off_u : off_u);
if(abs_offu == 0) abs_offu = oversample/2;
int wkernel_row_off = (abs_offu-1)*(wsupport+wsupport+1);
if(off_u == oversample/2 || off_u==-oversample/2)
wkernel_row_off += wsupport+1;
// Now need to clamp iteration range to exclude the tile box
// We want
// grid_u + k < tileBox.topLeft.u or
// grid_u + k >= tileBox.botRight.u
// Our grid iteration range is
// grid_u + k
// for -wsupport <= k <= wsupport and
// grid_v + j
// for -wsupport <= j <= wsupport
for (int j = -wsupport; j <= wsupport; ++j)
{
// Assume we are not intersecting the tile box
int kstart = -wsupport, kend = wsupport;
// Check if we intersect
if(tileBox.topLeft.v<=grid_v + j && grid_v+j<tileBox.botRight.v) {
// Clamp k iteration interval
kstart = (grid_u+kstart >= tileBox.topLeft.u ? max(tileBox.botRight.u-grid_u, kstart) : kstart);
kend = (grid_u+kend < tileBox.botRight.u ? min(tileBox.topLeft.u-grid_u-1, kend) : kend);
}
int iy = abs(off_v + j * oversample);
// Parallelise this loop over all threads in a warp
for (int k = kstart+threadIdx.x; k <= kend; k+=warpSize)
{
// More indexing calculations for the wkernel
int myk = k;
if(off_u > 0) myk = -myk;
int wkernel_u_idx;
if(off_u == 0) {
wkernel_u_idx = wsupport - abs(myk);
}
else if(abs_offu == oversample/2) {
wkernel_u_idx = wsupport - abs(myk) + (myk >= 1 ? 1 : 0);
}
else {
wkernel_u_idx = wsupport + myk;
}
float2 c = compacted_wkernels[wkernel_start + iy*wkernel_size + wkernel_row_off + wkernel_u_idx];
c.y *= conv_mul;
sum += c.x; /* Real part only. */
int p = 2 * (((grid_v-boundingBox.topLeft.v + j) * ld_grid) + grid_u-boundingBox.topLeft.u + k);
atomicAdd(grid+p, (val.x*c.x - val.y*c.y) );
atomicAdd(grid+p + 1, (val.y*c.x + val.x*c.y) );
}
}
warp_reduceplus(sum);
loc_norm += sum * w;
}
__shared__ double shmem[32];
{
if(threadIdx.x == 0) shmem[threadIdx.y] = loc_norm;
__syncthreads();
if(threadIdx.x==0 && threadIdx.y==0) {
loc_norm = shmem[0];
for(int i=1; i<blockDim.y; i++) loc_norm += shmem[i];
atomicAdd(norm, loc_norm);
}
}
#undef OFFSETS_OUTSIDE_TILES
#undef NUM_POINTS_OUTSIDE_TILES
}
/**
* Process all the tiles in the tile box, but skip any tiles in the exclusion box.
* If the exclusion box is empty, then we will process all the tiles.
*
* Each thread block processes visibilities in one tile only. Within a thread block, the parallelism
* is over the elements in the tile that are updated (so all threads in a thread block process
* the same visibilities). We can assign multiple thread blocks to each tile so that the work load
* for a given tile is spread over multiple blocks.
*
* Launch with a 3D grid of 2D thread blocks.
* gridDim.x : the number of blocks which will process each tile, i.e. parallelise the visibility
* calculation for a given tile across gridDim.x thread blocks
* gridDim.y : the number of tiles in the U direction
* gridDim.z : the number of tiles in the V direction
*
* blockDim.x : this must be the same as tileSize.u
* blockDim.y : this must satisfy the constraint blockDim.y*(REGSZ+SHMSZ) == tileSize.v
*/
template<int REGSZ, int SHMSZ>
__global__ void oskar_process_tiles_dynamic(
const int num_w_planes,
const int* const __restrict support,
const int oversample_,
const int* const __restrict compact_wkernel_start_idx, // Start index of each convolution kernel
const float2 * const __restrict compact_wkernel, // The compacted convolution stack
const double cell_size_rad,
const double w_scale,
const int grid_size,
const Box boundingBox, // Bounding box defining the active grid region
const Box tileBox, // Region of the active grid that is tiled. We actually
// .. only need the top left corner
const Point tileSize, // The tile size. This can be inferred from blockDim
const Point numTiles, // Number of tiles in U and V directions. The tiled
// .. region starts at tileBox.topLeft
const Point offsetInTileIdx_OBSOLETE,
const Box exclusionBoxInTileIdx_OBSOLETE,
const int * const __restrict d_numPointsInTiles, // Number of visibilities in each tile
const int * const __restrict d_offsetsPointsInTiles, // Start index of buckets, where visibility data in each
// .. tile start
const float * const __restrict d_bucket_uu, // Bucket sorted visibility data
const float * const __restrict d_bucket_vv, // Bucket sorted visibility data
const float * const __restrict d_bucket_ww, // Bucket sorted visibility data
const float2 * const __restrict d_bucket_vis, // Bucket sorted visibility data
const float * const __restrict d_bucket_weight, // Bucket sorted visibility data
const int2 * const __restrict d_bucket_tile, // The tile coordinate associated to that bucket
int * __restrict d_visibility_counter, // Initially 0. Increased atomically
int totalVisibilities,
double* d_norm, // Output norm
float* d_grid, // The active grid
const int ld_grid // The stride separating rows in the active grid. This is
// .. for alignment
)
{
// assert(TX==32 && TY==16) ;
const int BCG = 32 ; // Group of buckets loaded together. Ideally = warp size == TX but could be smaller
const int BCW = 1 ; // Number of groups to process.
const int BCS = BCW*BCG ; // Number of contiguous buckets to process
__shared__ float s_pos_u[BCG] ;
__shared__ float s_pos_v[BCG] ;
__shared__ float s_bucket_ww[BCG] ;
__shared__ float2 s_bucket_vis[BCG] ;
__shared__ float s_bucket_weight[BCG] ;
// s_bucket_pupv contains pu and pv packed together into a single int.
// This is to save a bit of shared memory
__shared__ int s_bucket_pupv[BCG] ;
// __shared__ int s_wsupport[BCG] ;
__shared__ int s_wsupport[BCG] ;
__shared__ int s_wkernel_start[BCG] ;
// Allocate the register array used to store the grid elements for this tile
float2 mygrid[REGSZ+1]; // +1 so that we can set REGSZ==0 without a compilation error. Should not matter since the additional element is never used
extern __shared__ float2 myshmem[];
// Thread idx in warp wid accesses element i at
// shmem[idx + i*BLOCKDIM_X + SHMSZ*BLOCKDIM_X*wid]
#define BLOCKDIM_X TX
const int shmemoff = threadIdx.x + SHMSZ*BLOCKDIM_X*threadIdx.y;
// Oversample is probably a value that could be known at compile time by specializing the kernel for all
// common valiues. The gain can be 5% so not negligible.
// The variable oversample_is_2_or_3 indicate if it known at compile time that oversample==2 or oversample==3
// This is potentially interesting because in those cases, oversample/2 == 1 and -1 <= off_u <= +1
// So off_u is one of the 3 cases -oversample/2, 0 , +oversample/2
// Another potentially interesting case would be oversample==1 for which off_u is always 0.
// If that is a possible case, then the code should also be optimized for it.
#ifdef ASSUME_OVERSAMPLE
int oversample = ASSUME_OVERSAMPLE ;
bool oversample_is_2_or_3 = (ASSUME_OVERSAMPLE==2) ;
#else
// WARNING: THIS VALUE IS FOR THE OSKAR EL30-EL56 DATASET
int oversample = oversample_ ;
bool oversample_is_2_or_3 = false ;
#endif
const int g_centre = grid_size / 2;
const float scale = grid_size * cell_size_rad;
// Current tile index
int pu = -1 ; // -1 is used as a marker to detect that no tile is currently processed
int pv = -1 ;
int my_grid_u_idx = 0 ;
int my_grid_v_idx_start = 0 ;
double loc_norm = 0 ;
#define TSIZE (REGSZ+SHMSZ)
while (true) {
// Figure out the next chunk of BCS buckets we have to process
int imin = 0 ;
if (threadIdx.x==0) {
imin = atomicAdd(d_visibility_counter,BCS) ;
}
imin = __shfl(imin, 0);
if ( imin >= totalVisibilities) {
break ; // We are done.
}
// We are now going to process the BCS buckets by chunks of BCG (or lower for the last chunk)
for (int i0=imin; i0<imin+BCS; i0+=BCG) // will iterate exactly BCW times
{
__syncthreads() ;
// First, load and copy the BCG buckets to shared memory using BCG threads
if (threadIdx.x < BCG )
{
// This part is what I call the "cooperative loading region" in which
// BCG thread are executed in lock step.
int t = threadIdx.x ;
int i = i0 + t ;
if (i<totalVisibilities) {
float w = (d_bucket_weight[i]) ;
s_bucket_weight[t] = w ;
s_pos_u[t] = -(d_bucket_uu[i]) * scale;
s_pos_v[t] = (d_bucket_vv[i]) * scale;
float ww_i = (d_bucket_ww[i]) ;
s_bucket_ww[t] = ww_i ;
float2 val = (d_bucket_vis[i]) ;
val.x *= w;
val.y *= w;
s_bucket_vis[t] = val ;
// ...
// This is the tile coordinate for the bucket.
// Reminder: this is sorted so that should not change often from one bucket to another
// Actually, we could probably store that in a single int.
// Even better, we only need the tiles coordinates for two reasons:
// (1) figure out when we change tile
// (2) write the output at the right place.
//
// IDEA: The output tiles do not need to form a rectangle. We only care
// about the tiles with 1 or more buckets so we can describe
// each tile by a single int (its rank in the active tiles).
// Also, the tile data can be stored contiguously ( 32x16 float2 each )
// with an additional cuda kernel to copy the tiles in the final
// 2D output.
// The advantage of that approach would a reduction of the
// number of instruction needed for the final atomic update of each tile.
//
//
//
int2 tile = (d_bucket_tile[i]) ;
// Ugly! Should use a bitfield.