aboutsummaryrefslogtreecommitdiff
path: root/src/super-computer.c
blob: 78453b6fcb2f4df78e114bc07af361cc3772869e (plain)
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
// super-computer.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <mpi.h>
#include <omp.h>
#include <dlfcn.h>
#include <fcntl.h>

#include "utils.h"
#include "string-view.h"
#include "scanner.h"
#include "stb_ds.h"
#include "card.h"
#include "user.h"
#include "transaction.h"
#include "transaction-heap.h"

#define RATIO__CPU_GPU (70/30.)

unsigned int hash (register const char *str, register size_t len);
extern const char *wordlist[];
const char *mpi_strerror (int errorcode)
{
  static char string[MPI_MAX_ERROR_STRING];
  MPI_Error_string (errorcode, string, NULL);
  return string;
}

void
die (const char *fmt, ...)
{
  va_list ap;

  va_start (ap, fmt);
  vfprintf (stderr, fmt, ap);
  va_end (ap);

  exit (EXIT_FAILURE);
}

#define DIE(FMT, ...)                                           \
  die (__FILE__ ":" TO_STRING (__LINE__) ": %s: die: " FMT,     \
       __func__ __VA_OPT__ (,) __VA_ARGS__)

int node_count__cpu;
int node_count__gpu;
int world_size;
int world_rank;
char processor_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
int max_threads;
bool has_gpu;

void
mpi_init (int *argc, char ***argv)
{
  int err = MPI_Init (argc, argv);
  if (err) DIE ("MPI_Init: %s", mpi_strerror (err));
}

int
mpi_world_size (void)
{
  int world_size;
  int err = MPI_Comm_size (MPI_COMM_WORLD, &world_size);
  if (err) DIE ("MPI_Comm_size: %s", mpi_strerror (err));
  return world_size;
}

int
mpi_world_rank (void)
{
  int world_rank;
  int err = MPI_Comm_rank (MPI_COMM_WORLD, &world_rank);
  if (err) DIE ("MPI_Comm_rank: %s", mpi_strerror (err));
  return world_rank;
}

void
mpi_get_processor_name (char processor_name[MPI_MAX_PROCESSOR_NAME],
                        int *name_len)
{
  int err = MPI_Get_processor_name (processor_name, name_len);
  if (err) DIE ("MPI_Get_processor_name: %s", mpi_strerror (err));
}

void
mpi_send (const void *buf, int count, MPI_Datatype datatype, int dest)
{
  int err = MPI_Send (buf, count, datatype, dest, 0, MPI_COMM_WORLD);
  if (err) DIE ("MPI_Send: %s", mpi_strerror (err));
}

void
mpi_recv (void *buf, int count, MPI_Datatype datatype, int source)
{
  int err = MPI_Recv (buf, count, datatype, source, 0,
                      MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  if (err) DIE ("MPI_Recv: %s", mpi_strerror (err));
}

void
mpi_finalize (void)
{
  int err = MPI_Finalize ();
  if (err) DIE ("MPI_Finalize: %s", mpi_strerror (err));
}

void
send_top (struct transaction_heap *top, int dest)
{
  mpi_send (&top->count, 1, MPI_UINT8_T, dest);
  mpi_send (top->array, 2*top->count, MPI_UINT64_T, dest);
}

void
recv_top (struct transaction_heap *top, int source)
{
  struct transaction_heap other;

  mpi_recv (&other.count, 1, MPI_UINT8_T, source);
  mpi_recv (other.array, 2*other.count, MPI_UINT64_T, source);

  for (int i = 0; i < other.count; ++i)
    transaction_heap__push (top, other.array[i]);
}

void
process_cards (const char *filename, struct card **cards, struct user **users)
{
  MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size);

  ASSERT (filename);
  ASSERT (cards);
  ASSERT (users);

  int fd = open (filename, O_RDONLY);
  ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno));
  struct string_view sv = mmap_whole (fd);

  struct scanner sc;
  scanner__init (&sc, sv);

  // skip header: id, client_id, card_brand, card_type, card_number,
  // expires, cvv, has_chip, num_cards_issued, credit_limit,
  // acct_open_date, year_pin_last_changed, card_on_dark_web
  scanner__skip_over (&sc, '\n');
  while (!scanner__reached_end (&sc)) {
    struct card card;
    struct user user;

    card.id = scanner__get_uint64 (&sc);

    scanner__skip_n (&sc, 1);

    user.id = scanner__get_uint64 (&sc);

    scanner__skip_over (&sc, '$');

    uint64_t credit_limit = scanner__get_uint64 (&sc);
    scanner__skip_over (&sc, '\n');

    if (credit_limit < 12000)
      continue;

    hmputs (*cards, card);

    if (hmgetp_null (*users, user.key) == NULL)
      hmputs (*users, user);
  }

  munmap ((char *) sv.begin, sv.end - sv.begin);
  close (fd);
}

void
process_users (const char *filename, struct user *users)
{
  MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size);

  ASSERT (filename);
  ASSERT (users);

  int fd = open (filename, O_RDONLY);
  ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno));
  struct string_view sv = mmap_whole (fd);

  struct scanner sc;
  scanner__init (&sc, sv);

  // skip header: id, current_age, retirement_age, birth_year,
  // birth_month, gender, address, latitude, longitude,
  // per_capita_income, yearly_income, total_debt, credit_score,
  // num_credit_cards
  scanner__skip_over (&sc, '\n');

  while (!scanner__reached_end (&sc)) {
    client_id_t id = scanner__get_uint64 (&sc);
    struct user *user = hmgetp_null (users, id);
    if (user == NULL) {
      scanner__skip_over (&sc, '\n');
      continue;
    }

    scanner__skip_over (&sc, '$');

    user->normalizer = 0.12/scanner__get_uint64 (&sc); // 12 months, cents->dollars
    scanner__skip_over (&sc, '\n');
  }

  munmap ((char *) sv.begin, sv.end - sv.begin);
  close (fd);
}

void
scanner__skip_current_month (struct scanner *sc)
{
  scanner__skip_over (sc, '\n');
  if (sc->cursor == sc->end) return;

  uint16_t current_year_month;
  scanner__skip_over (sc, ',');
  current_year_month  = scanner__get_uint64 (sc) << 4; scanner__skip_n (sc, 1);
  current_year_month |= scanner__get_uint64 (sc);

  const char *line;
  uint16_t year_month;
  do {
    scanner__skip_over (sc, '\n');
    line = sc->cursor;
    scanner__skip_over (sc, ',');
    year_month  = scanner__get_uint64 (sc) << 4; scanner__skip_n (sc, 1);
    year_month |= scanner__get_uint64 (sc);
  } while (year_month == current_year_month);

  sc->cursor = line;
}

void
split_transaction_scanner (struct scanner *sc, int block, int blocks)
{
  struct scanner tmp = *sc;

  size_t bytes_total = tmp.end - tmp.cursor;
  size_t bytes_per_block = bytes_total/blocks;

  if (block > 0) {
    sc->cursor += block*bytes_per_block;
    scanner__skip_current_month (sc);
  } else {
    // skip header: id, date, client_id, card_id, amount, use_chip,
    // merchant_id, merchant_city, merchant_state, zip, mcc, errors
    scanner__skip_over (sc, '\n');
  }

  if (block < blocks - 1) {
    tmp.cursor += (block + 1)*bytes_per_block;
    scanner__skip_current_month (&tmp);
    sc->end = tmp.cursor;
  }
}

void
process_transactions__cpu (struct scanner *sc,
                           struct transaction_heap *top_transactions,
                           struct card *cards, struct user *users)
{
  MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size);

  ASSERT (sc != NULL);
  ASSERT (top_transactions != NULL);
  ASSERT (cards != NULL);
  ASSERT (users != NULL);

  struct transaction *transactions = NULL;

  // Parse, aggregate, reduce
  while (!scanner__reached_end (sc)) {
    union transaction_key key;

    scanner__skip_over (sc, ',');

    key.year_month  = scanner__get_uint64 (sc) << 4;
    scanner__skip_n (sc, 1);
    key.year_month |= scanner__get_uint64 (sc);

    scanner__skip_over (sc, ',');

    key.client_id = scanner__get_uint64 (sc);

    scanner__skip_n (sc, 1);

    card_id_t card_id = scanner__get_uint64 (sc);
    if (hmgetp_null (cards, card_id) == NULL) {
      scanner__skip_over (sc, '\n');
      continue;
    }

    scanner__skip_n (sc, 2);

    int64_t amount = 100*scanner__get_int64 (sc);
    scanner__skip_n (sc, 1);
    int sign = amount >= 0 ? 1 : -1;
    amount += sign*scanner__get_uint64 (sc);

    scanner__skip_n    (sc, 1);
    scanner__skip_over (sc, ',');
    scanner__skip_over (sc, ',');

    struct string_view sv = scanner__get_until (sc, ',');
    key.merchant_city_id = hash (sv.begin, STRING_VIEW__LENGTH (sv));

    scanner__skip_over (sc, '\n');

    struct transaction *transaction =
      hmgetp_null (transactions, key);
    if (transaction == NULL)
      hmput (transactions, key, amount);
    else transaction->sum += amount;
  }

  // Normalize
  ptrdiff_t tempvar;
  for (size_t i = 0; i < hmlenu (transactions); ++i) {
    struct transaction *transaction = &transactions[i];
    float normalizer = hmgetp_ts (users, transaction->key.client_id, tempvar)->normalizer;
    transaction->normalized = transaction->sum*normalizer;
  }

  // Exctract top
  for (size_t i = 0; i < hmlenu (transactions); ++i)
    transaction_heap__push (top_transactions, transactions[i]);

  hmfree (transactions);
}

void
process_transactions__gpu (struct scanner *sc,
                           struct transaction_heap *top_transactions,
                           struct card *cards, struct user *users)
{
  MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size);

  ASSERT (sc != NULL);
  ASSERT (top_transactions != NULL);
  ASSERT (cards != NULL);
  ASSERT (users != NULL);

  uint64_t *keys = NULL;
  float    *vals = NULL;
  ptrdiff_t tempvar;
  while (!scanner__reached_end (sc)) {
    union transaction_key key;

    scanner__skip_over (sc, ',');

    key.year_month  = scanner__get_uint64 (sc) << 4;
    scanner__skip_n (sc, 1);
    key.year_month |= scanner__get_uint64 (sc);

    scanner__skip_over (sc, ',');

    key.client_id = scanner__get_uint64 (sc);

    scanner__skip_n (sc, 1);

    card_id_t card_id = scanner__get_uint64 (sc);
    if (hmgetp_null (cards, card_id) == NULL) {
      scanner__skip_over (sc, '\n');
      continue;
    }

    scanner__skip_n (sc, 2);

    int64_t amount = 100*scanner__get_int64 (sc);
    scanner__skip_n (sc, 1);
    int sign = amount >= 0 ? 1 : -1;
    amount += sign*scanner__get_uint64 (sc);

    scanner__skip_n    (sc, 1);
    scanner__skip_over (sc, ',');
    scanner__skip_over (sc, ',');

    struct string_view sv = scanner__get_until (sc, ',');
    key.merchant_city_id = hash (sv.begin, STRING_VIEW__LENGTH (sv));

    scanner__skip_over (sc, '\n');

    float normalizer = hmgetp_ts (users, key.client_id, tempvar)->normalizer;
    arrput (keys, key.packed);
    arrput (vals, amount*normalizer);
  }

  void *handle = dlopen ("./cuda.so", RTLD_LAZY);
  if (handle == NULL)
    DIE ("dlopen: %s", dlerror ());

  int (*cuda_process_transactions) (uint64_t *keys, float *vals, size_t) =
    dlsym (handle, "process_transactions");
  if (cuda_process_transactions == NULL)
    DIE ("dlsym: %s", dlerror ());

  int count = cuda_process_transactions (keys, vals, arrlenu (keys));

  if (dlclose (handle))
    DIE ("dlclose: %s", dlerror ());

  for (int i = 0; i < count; ++i) {
    transaction_heap__push (top_transactions, (struct transaction) {
      .key.packed = keys[i],
      .normalized = vals[i],
    });
  }

  arrfree (keys);
  arrfree (vals);
}

struct sizes {
  size_t cpu;
  size_t gpu;
  size_t tail;
};

struct partition {
  size_t offset;
  size_t size;
};

struct sizes
get_sizes (size_t size)
{
  int thread_count__cpu = ((max_threads - 0)*node_count__cpu +
                           (max_threads - 1)*node_count__gpu);
  int thread_count__gpu = node_count__gpu;

  double weight__cpu = thread_count__cpu*RATIO__CPU_GPU;
  double weight__gpu = thread_count__gpu;

  double ratio__cpu = weight__cpu/(weight__cpu + weight__gpu);

  struct sizes sizes;

  size_t size__cpus = size * ratio__cpu;
  size_t size__gpus = size - size__cpus;
  sizes.cpu  = (thread_count__cpu > 0) ? size__cpus/thread_count__cpu : 0;
  sizes.gpu  = (thread_count__gpu > 0) ? size__gpus/thread_count__gpu : 0;
  sizes.tail = size - (thread_count__cpu*sizes.cpu +
                       thread_count__gpu*sizes.gpu);

  return sizes;
}

struct partition
partition_node (struct sizes sizes, int node_rank)
{
  struct partition partition;

  if (node_rank < node_count__cpu) { // CPU NODE
    partition.size   = max_threads*sizes.cpu;
    partition.offset = node_rank*partition.size;
  } else {                      // GPU NODE
    partition.size   = (max_threads - 1)*sizes.cpu + sizes.gpu;
    partition.offset = (node_count__cpu*max_threads*sizes.cpu +
                        (node_rank - node_count__cpu)*partition.size);
  }

  if (node_rank + 1 == node_count__cpu + node_count__gpu)
    partition.size += sizes.tail;

  return partition;
}

struct partition
partition_thread (struct partition partition, struct sizes sizes,
                  int node_rank, int thread)
{
  if (node_rank < node_count__cpu) {
    partition.size    = sizes.cpu;
    partition.offset += thread*partition.size;
  } else {
    if (thread == 0) {
      partition.size = sizes.gpu;
    } else {
      partition.size    = sizes.cpu;
      partition.offset += sizes.gpu + (thread - 1)*partition.size;
    }
  }

  if (node_rank + 1 == node_count__cpu + node_count__gpu && thread + 1 == max_threads)
    partition.size += sizes.tail;

  return partition;
}

void
align_scanner (struct scanner *sc, const char *base,
               struct partition partition, bool last)
{
  sc->cursor = base + partition.offset;

  struct scanner tmp = *sc;

  if (partition.offset > 0)
    scanner__skip_current_month (sc);

  if (!last) {
    tmp.cursor += partition.size;
    scanner__skip_current_month (&tmp);
    sc->end = tmp.cursor;
  }
}

void
process_transactions (const char *filename,
                      struct transaction_heap *top_transactions,
                      struct card *cards, struct user *users)
{
  MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size);

  ASSERT (filename);
  ASSERT (top_transactions);
  ASSERT (cards);
  ASSERT (users);

  int fd = open (filename, O_RDONLY);
  ASSERT_MSG (fd != -1, "open %s: %s", filename, strerror (errno));

  struct stat st;
  int ret = fstat (fd, &st);
  ASSERT_MSG (ret != -1, "fstat: %s", strerror (errno));
  ASSERT (S_ISREG (st.st_mode));

  struct sizes sizes = get_sizes (st.st_size);

  struct partition node_partition = partition_node (sizes, world_rank);

  off_t page_align = node_partition.offset % 4096;
  struct string_view sv =
    mmap_n_from (fd, //  mmap till end
		 st.st_size - node_partition.offset + page_align,
		 0          + node_partition.offset - page_align);

  struct transaction_heap top_transactions_other = {0};
#pragma omp parallel
  {
    int tid = omp_get_thread_num ();
    struct partition thread_partition =
      partition_thread (node_partition, sizes, world_rank, tid);
    struct scanner sc;
    scanner__init (&sc, sv);
    sc.cursor += page_align;
    align_scanner (&sc, sc.cursor - node_partition.offset, thread_partition,
                   world_rank == world_size - 1 && tid == max_threads - 1);

    if (world_rank == 0 && tid == 0)
      scanner__skip_over (&sc, '\n');

    printf ("[%d/%d] [%d/%d] Data split: 0x%06lx 0x%06lx %7luK %p %p %p\n",
            world_rank + 1, world_size, tid + 1, max_threads,
	    (sc.cursor - (sv.begin + page_align) + node_partition.offset) >> 10,
	    (sc.end - (sv.begin + page_align) + node_partition.offset) >> 10,
	    (sc.end - sc.cursor) >> 10,
	    sc.cursor, sc.end, sv.end);

    if (tid == 0) {
      if (has_gpu) process_transactions__gpu (&sc,  top_transactions,       cards, users);
      else         process_transactions__cpu (&sc,  top_transactions,       cards, users);
    } else         process_transactions__cpu (&sc, &top_transactions_other, cards, users);
  }

  munmap ((char *) sv.begin, sv.end - sv.begin);
  close (fd);

  // Aggregate
  for (int i = 0; i < top_transactions_other.count; ++i)
    transaction_heap__push (top_transactions, top_transactions_other.array[i]);
}

int
compare_transactions (const void *lhs, const void *rhs)
{
  const struct transaction *lhs_transaction = lhs;
  const struct transaction *rhs_transaction = rhs;

  float lhs_normalized = lhs_transaction->normalized;
  float rhs_normalized = rhs_transaction->normalized;

  return (lhs_normalized < rhs_normalized) - (lhs_normalized > rhs_normalized);
}

void
sort_top (struct transaction_heap *top)
{
  MEASURE_SCOPE ();
  ASSERT (top != NULL);

  qsort (top->array, top->count, sizeof (*top->array), compare_transactions);
}

void
print_top (const struct transaction_heap *top)
{
  MEASURE_SCOPE ();
  ASSERT (top != NULL);

  printf (" i client_id normalized_spending year_month city\n");
  for (int i = 0; i < top->count; ++i) {
    printf ("%2d      %4hu              %6.2f    %hu-%02hu %s\n", i,
            top->array[i].key.client_id,
            top->array[i].normalized,
            top->array[i].key.year_month >> 4,
            top->array[i].key.year_month & ((1 << 4) - 1),
            wordlist[top->array[i].key.merchant_city_id]);
  }
}

int
main (int argc, char *argv[])
{
  mpi_init (&argc, &argv);

  if (argc != 3)
    return 1;

  const char *progname = *argv++;
  node_count__cpu = atoi (*argv++);
  node_count__gpu = atoi (*argv++);

  UNUSED (progname);

  world_size = mpi_world_size ();
  world_rank = mpi_world_rank ();
  mpi_get_processor_name (processor_name, &name_len);
  max_threads = omp_get_max_threads ();
  has_gpu = world_rank >= node_count__cpu;

  MEASURE_SCOPE ("[%d/%d]", world_rank + 1, world_size);

  printf ("Hello from processor %s, rank %d out of %d processors (%d threads, %s GPU)\n",
          processor_name, world_rank, world_size,
          max_threads, has_gpu ? "Has" : "Doesn't have");

  struct card *cards = NULL;
  struct user *users = NULL;
  struct transaction_heap top_transactions = {0};

  // TODO(cmmm): all threads read their part, then the host shares with others
  process_cards ("res/cards_data.csv", &cards, &users);
  process_users ("res/users_data.csv", users);

  process_transactions ("res/transactions_data.csv",
                        &top_transactions, cards, users);
  if (world_rank > 0) {
    send_top (&top_transactions, 0);
  } else {
    for (int i = 1; i < world_size; ++i)
      recv_top (&top_transactions, i);
    sort_top  (&top_transactions);
    print_top (&top_transactions);
  }

  mpi_finalize ();
}
// super-computer.c ends here