-
Notifications
You must be signed in to change notification settings - Fork 0
/
distributed_trainer_emb_bag.py
1664 lines (1454 loc) · 63.4 KB
/
distributed_trainer_emb_bag.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# I think this is it. All looks good for now
# training worker, accepts input from the oracle cacher
import os
import sys
import time
import copy
import queue
import logging
import argparse
import threading
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed.rpc as rpc
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
import utils
try:
import examples.s3_utils as s3_utils
except:
pass
from operator import itemgetter
from subprocess import call
class DistTrainModel(nn.Module):
def __init__(
self,
emb_size=1,
ln_top=None,
ln_bot=None,
sigmoid_bot=-1,
sigmoid_top=-1,
feature_interaction="dot",
interact_itself=False,
loss_function="bce",
worker_id=0,
lookahead_value=200,
cache_size=25000,
mini_batch_size=128,
ln_emb=[],
training_worker_id=0,
device="cuda:0",
oracle_prefix=None,
emb_prefix=None,
trainer_prefix=None,
trainer_world_size=None,
cleanup_batch_proportion=0.25,
):
super(DistTrainModel, self).__init__()
"""
Args:
emb_size: Size of for each sparse embedding
ln_top (np.array): Structure of top MLP
ln_bot (np.array): Structure of bottom MLP
sigmoid_bot (int): Integer for listing the location of bottom
sigmoid_top (int): Integer for listing the location of the top
Returns:
None
"""
self.emb_size = emb_size
self.ln_top = ln_top
self.ln_bot = ln_bot
self.sigmoid_bot = sigmoid_bot
self.sigmoid_top = sigmoid_top
self.feature_interaction = feature_interaction
self.interact_itself = interact_itself
self.lookahead_value = lookahead_value
self.mini_batch_size = mini_batch_size
self.ln_emb = ln_emb
self.trainer_world_size = trainer_world_size
self.training_worker_id = training_worker_id
self.device = device
self.bot_mlp = self.create_mlp(self.ln_bot, self.sigmoid_bot)
self.top_mlp = self.create_mlp(self.ln_top, self.sigmoid_top)
self.top_mlp.to(self.device)
self.bot_mlp.to(self.device)
if loss_function == "bce":
self.loss_fn = torch.nn.BCELoss(reduction="mean")
elif loss_function == "mse":
self.loss_fn = torch.nn.MSELoss(reduction="mean")
self.loss_fn.to(self.device)
# holds global to local mapping
self.cache_idx = {
k: torch.ones(idx_vals, dtype=torch.long).to(self.device)
for k, idx_vals in enumerate(self.ln_emb)
}
for k in self.cache_idx:
self.cache_idx[k][:] = -1
# sparse drastically speeds it up
self.local_cache = nn.EmbeddingBag(
cache_size, self.emb_size, mode="sum", sparse=True
).to(device)
# NOTE: I am deciding to keep these mapping on CPU.
# TODO: Verify the tradeoffs here
self.local_to_global_mapping = torch.ones((cache_size, 2), dtype=torch.long)
self.local_to_global_mapping[:] = torch.tensor([-1, -1])
# -1 represents empty
# 1 represent filled
with torch.no_grad():
self.local_cache_status = torch.ones(cache_size, dtype=torch.int32)
self.local_cache_status[:] = -1
self.local_cache_ttl = torch.ones(cache_size, dtype=torch.long)
self.local_cache_ttl[:] = -1
self.train_queue = queue.Queue()
self.prefetch_queue = queue.PriorityQueue()
self.prefetch_futures_queue = queue.Queue()
self.prefetch_queue_ttl = queue.Queue()
self.original_idx_puts = queue.Queue()
self.delete_element_queue = queue.Queue()
self.prefetch_completed_signal = queue.Queue()
self.later_sync_future = None
self.sync_later_buffer = None
self.prefetch_reorder_buffer = dict()
self.dynamic_lookahead_val = dict()
self.prefetch_expected_iter = 0
self.worker_id = worker_id
self.trainer_prefix = trainer_prefix
self.worker_name = f"{trainer_prefix}_{training_worker_id}"
self.emb_worker = f"{emb_prefix}"
self.current_train_epoch = 0
assert (
cleanup_batch_proportion <= 1
), "Batch proportion should be between 0 and 1, currently greater than 1"
assert (
cleanup_batch_proportion >= 0
), "Batch proportion should be between 0 and 1, currently less than 0"
self.cleanup_interval = max(
1, int(cleanup_batch_proportion * self.lookahead_value)
)
self.iter_cleaned_up = 0
self.eviction_number = 0 # use it to load balance
self.cache_usage = 0
self.max_cache_usage = 0
# counters
self.total_forward_time = 0
self.total_backward_time = 0
self.waiting_for_prefetch = 0
self.cache_sync_time = 0
self.total_time = 0
self.total_evictions = 0
self.total_additions = 0
try:
self.write_files = s3_utils.uploadFile("recommendation-data-bagpipe")
except:
pass
self.prev_ttl_idx = None
self.prev_ttl_val = None
return None
def convert_orig_to_local_by_table_id(self, table_id, global_id):
"""
Give a table id and tensor of global ids converts it to local ids
"""
return self.cache_idx[table_id][global_id]
def convert_orig_to_local_idx(self, orig_idx):
"""
Converts original indexes from original indexes to local cache indexes
orig_idx (list(list)): List of list containing original index
"""
local_cache_idxs = list()
for table_id, idxs in enumerate(orig_idx):
local_cache_idxs.append(self.cache_idx[table_id][idxs])
return local_cache_idxs
def update_ttl(self, ttl_update_idx, ttl_update_val):
"""
Only update the TTL of the cache
"""
for table_id in ttl_update_idx:
orig_idx_to_update = ttl_update_idx[table_id]
corresponding_local_idx = self.cache_idx[table_id][orig_idx_to_update]
values_to_update = ttl_update_val[table_id]
self.local_cache_ttl[corresponding_local_idx] = values_to_update
return None
def clean_up_caches(self, iter_cleanup, ttl_update_idx, ttl_update_val):
"""
Based on stored TTLs evict from the caches
"""
try:
print("Clean up cache called {}".format(iter_cleanup))
print("Cleanup Interval {}".format(self.cleanup_interval))
# this is the TTL update code moved from critical path
# NOTE: Following code mode moved to def update_ttl
# we needed to update TTL pre eviction call.
# ttl update
# we got rid of it for the example based setup
for table_id in ttl_update_idx:
orig_idx_to_update = ttl_update_idx[table_id]
corresponding_local_idx = self.cache_idx[table_id][orig_idx_to_update]
values_to_update = ttl_update_val[table_id]
self.local_cache_ttl[corresponding_local_idx] = values_to_update
if iter_cleanup % self.cleanup_interval == 0 and iter_cleanup != 0:
self.iter_cleaned_up = iter_cleanup - 1
self.eviction_number += 1
cleanup_time = time.time()
local_idx_to_remove = (self.local_cache_ttl <= iter_cleanup - 1) & (
self.local_cache_ttl != -1
)
# print("Local cache ttl {}".format(self.local_cache_ttl))
local_idx_to_remove = local_idx_to_remove.nonzero().squeeze()
self.cache_usage -= len(local_idx_to_remove)
self.total_evictions += len(local_idx_to_remove)
global_idx_to_remove = self.local_to_global_mapping[local_idx_to_remove]
# we get global idx to remove
dict_to_update = dict()
emb_to_update = dict()
# we need to reassamble the embeddings
for table_id in range(len(self.ln_emb)):
# for each table ID find the global indexes
relevant_idx_to_table_id = global_idx_to_remove[:, 0] == table_id
relevant_idx_to_table_id = relevant_idx_to_table_id.nonzero()
# if relevant_idx_to_table_id.shape[0] != 1:
relevant_idx_to_table_id = relevant_idx_to_table_id.squeeze()
# print("Relevant idx shape {}".format(relevant_idx_to_table_id.shape))
if len(relevant_idx_to_table_id.shape) == 0:
relevant_idx_to_table_id = torch.tensor(
[relevant_idx_to_table_id.item()]
)
global_idx_to_update_table_id = global_idx_to_remove[
relevant_idx_to_table_id
]
global_idx_to_update_table_id = global_idx_to_update_table_id[:, 1]
# we have indexes to update
dict_to_update[table_id] = global_idx_to_update_table_id
# we need corresponding values
relevant_local_ids = self.convert_orig_to_local_by_table_id(
table_id, global_idx_to_update_table_id
)
with torch.no_grad():
# corresponding values
embedding_vals = self.local_cache(
relevant_local_ids,
torch.arange(len(relevant_local_ids), device=self.device),
)
emb_to_update[table_id] = embedding_vals.to("cpu")
# cleaning up global to local mapping
self.cache_idx[table_id][global_idx_to_update_table_id] = -1
# TODO: Code for dynamic
# delete_elements = range(
# iter_cleanup - self.cleanup_interval, iter_cleanup
# )
# for dm in delete_elements:
# del self.dynamic_lookahead_val[dm]
# if iter_cleanup % self.trainer_world_size == self.training_worker_id:
# # only send one workers embedding to update
# # already synchronized
# # print("Iter cleaned up {}".format(iter_cleanup))
# rpc.rpc_async(
# self.emb_worker,
# cache_eviction_update,
# args=(
# (
# dict_to_update,
# emb_to_update,
# )
# ),
# )
# print("Cache eviction made {}".format(dict_to_update))
# embeddings sent to update
self.local_to_global_mapping[local_idx_to_remove] = torch.tensor(
[-1, -1]
)
self.local_cache_status[local_idx_to_remove] = -1
self.local_cache_ttl[local_idx_to_remove] = -1
end_cleanup_time = time.time()
# print("Time to clean up {}".format(end_cleanup_time - cleanup_time))
prefetch_prep_time = time.time()
batched_embedding = list()
enter_flag = 0
while True:
# batching the prefetch requests
# only fetch when needed
# print("In while True")
# print("Prefetch Queue value {}".format(
is_empty = self.prefetch_queue.empty()
# if is_empty:
# # keep going until there is an element in prefetch queue
# logger.
# continue
# print("is empty {}".format(is_empty))
if not is_empty:
# if prefetech queue is not empty
# print("In first if")
# supporting dynamic lookahead
# TODO: Enable this for dynamic lookahead value
# self.lookahead_value = self.dynamic_lookahead_val[
# self.iter_cleaned_up
# ]
# NOTE This is condition for prefetch queue using usual queue
# if (
# list(self.prefetch_queue.queue[0].keys())[0]
# < self.iter_cleaned_up - 1 + self.lookahead_value
# ):
# NOTE: this is condition for prefetch queue using priority queue
# logger.info(
# "Prefetch queue 1st element{}".format(
# self.prefetch_queue.queue[0][0]
# )
# )
# logger.info("Iter cleaned up {}".format(self.iter_cleaned_up))
if (
self.prefetch_queue.queue[0][0]
< self.iter_cleaned_up - 1 + self.lookahead_value
):
# print("Iter cleaned up {}".format(self.iter_cleaned_up))
enter_flag = 1
# print("Getting prefetch queue")
ttl_val, val = self.prefetch_queue.get(block=True)
if ttl_val != self.prefetch_expected_iter:
while ttl_val != self.prefetch_expected_iter:
self.prefetch_queue.put((ttl_val, val))
ttl_val, val = self.prefetch_queue.get(block=True)
self.prefetch_expected_iter += 1
# print("Got from the queue")
batched_embedding.append(val)
# we are getting ttl val anyways
ttl_val = list(val.keys())[0]
# TODO: Enable for dynamic
# self.dynamic_lookahead_val[ttl_val] = val["lookahead_value"]
# print("Launched prefetch {}".format(ttl_val))
self.original_idx_puts.put(val)
self.prefetch_queue_ttl.put(ttl_val)
else:
if enter_flag == 1:
# print("Making a prefetch req")
fut = rpc.rpc_async(
self.emb_worker,
get_embedding,
args=(batched_embedding,),
)
self.prefetch_futures_queue.put(fut)
enter_flag = 0
break
# print("Launched prefetch {}".format(ttl_val))
else:
if enter_flag == 1:
fut = rpc.rpc_async(
self.emb_worker,
get_embedding,
args=(batched_embedding,),
)
self.prefetch_futures_queue.put(fut)
enter_flag = 0
# print("Launched prefetch {}".format(ttl_val))
# print("Second else")
# print("prefetch queue {}".format(self.prefetch_queue))
break
if enter_flag == 0:
# keep checking prefetch queue
continue
end_prefetch_pre_time = time.time()
# print(
# "Prefetch prep time {}".format(
# end_prefetch_pre_time - prefetch_prep_time
# )
# )
print("Out of prefetch prep loop")
# adding to the cache post eviction
while True:
if not self.prefetch_queue_ttl.empty():
prefetch_add_time = time.time()
fut = self.prefetch_futures_queue.get(block=True)
time_spent_waiting = time.time()
# fetched_batch = fut
fetched_batch = fut.wait()
# print(
# "Time spend waiting on future {}".format(
# time.time() - time_spent_waiting
# )
# )
# print("Fetched iter {}".format(ttl_val))
empty_location = self.local_cache_status == -1
empty_location = empty_location.nonzero().squeeze()
if self.cache_usage > self.max_cache_usage:
self.max_cache_usage = self.cache_usage
# logger.info("Cache Size Remaining {}".format(len(empty_location)))
logger.info("Cache Size used {}".format(self.cache_usage))
last_use_location = 0
# assert (
# len(empty_location) >= emb_vals_length
# ), "Not enought Cache Available"
# cuda_start_movement = torch.cuda.Event(enable_timing=True)
# cuda_stop_movement = torch.cuda.Event(enable_timing=True)
for fetched_vals in fetched_batch:
ttl_val = self.prefetch_queue_ttl.get(block=True)
# print("Fetched itr {}".format(ttl_val))
# print("Evicted till {}".format(self.iter_cleaned_up))
val = self.original_idx_puts.get(block=True)
total_time_movement_per_batch = 0
for table_id, emb_vals in enumerate(fetched_vals):
if len(emb_vals) > 0:
emb_vals_length = len(emb_vals)
self.total_additions += emb_vals_length
with torch.cuda.stream(s):
# cuda_start_movement.record()
emb_vals = emb_vals.to(self.device)
indexing_offset = torch.arange(
emb_vals_length, device=self.device
)
# cuda_stop_movement.record()
original_idx = val[ttl_val][table_id]
empty_location_to_use = empty_location[
last_use_location : last_use_location
+ emb_vals_length
]
# changing indexing avoid running lookups agains and again
last_use_location += emb_vals_length
self.cache_usage += emb_vals_length
self.local_cache_status[empty_location_to_use] = 1
empty_location_to_use_device = empty_location_to_use.to(
self.device
)
self.local_to_global_mapping[
empty_location_to_use, 0
] = table_id
self.local_to_global_mapping[
empty_location_to_use, 1
] = original_idx
self.cache_idx[table_id][
original_idx
] = empty_location_to_use_device
self.local_cache_ttl[empty_location_to_use] = ttl_val
# torch.cuda.synchronize()
# total_time_movement_per_batch += (
# cuda_start_movement.elapsed_time(cuda_stop_movement)
# )
torch.cuda.current_stream().wait_stream(s)
with torch.no_grad():
self.local_cache(
empty_location_to_use_device,
indexing_offset,
).data = emb_vals
# logger.info(
# "Total time data movement {}".format(
# total_time_movement_per_batch
# )
# )
self.prefetch_completed_signal.put(ttl_val)
# end_prefetch_add_time = time.time()
# logger.info(
# "prefetch add time (ms) {}".format(
# (end_prefetch_add_time - prefetch_add_time) * 1000
# )
# )
else:
# no elements in the queue
break
if iter_cleanup % self.cleanup_interval == 0 and iter_cleanup != 0:
if (
self.eviction_number % self.trainer_world_size
== self.training_worker_id
):
# only send one workers embedding to update
# already synchronized
# print("Iter cleaned up {}".format(iter_cleanup))
print("evicted till {}".format(iter_cleanup - 1))
rpc.rpc_async(
self.emb_worker,
cache_eviction_update,
args=(
(
dict_to_update,
emb_to_update,
)
),
)
except Exception as e:
sys.exit(e.__str__())
logger.error(e)
print(e)
def create_mlp(self, ln, sigmoid_layer):
layers = nn.ModuleList()
for i in range(0, ln.size - 1):
n = ln[i]
m = ln[i + 1]
LL = nn.Linear(int(n), int(m), bias=True)
# some xavier stuff the original pytorch code was doing
mean = 0.0
std_dev = np.sqrt(2 / (m + n))
W = np.random.normal(mean, std_dev, size=(m, n)).astype(np.float32)
std_dev = np.sqrt(1 / m)
bt = np.random.normal(mean, std_dev, size=m).astype(np.float32)
LL.weight.data = torch.tensor(W, requires_grad=True)
LL.bias.data = torch.tensor(bt, requires_grad=True)
layers.append(LL)
if i == sigmoid_layer:
layers.append(nn.Sigmoid())
else:
layers.append(nn.ReLU())
return torch.nn.Sequential(*layers)
def apply_mlp(self, dense_x, mlp_network):
"""
Apply MLP on the features
"""
# print("Shape Dense x {}".format(dense_x.shape))
return mlp_network(dense_x)
def get_elements_evicted(self, round_number):
"""
Get element IDs which will be evicted in this round
"""
evicted_in_this_round = self.local_cache_ttl == round_number
evicted_in_this_round = evicted_in_this_round.nonzero().squeeze()
num_elements_in_cache = self.local_cache_ttl > round_number
num_elements_in_cache = num_elements_in_cache.nonzero().squeeze().shape
print("Num Elemnts in cache {}".format(num_elements_in_cache))
return evicted_in_this_round
def get_intersection(self, int_a, int_b):
"""
Calculate intersection of int_a and int_b.
Also return the indices of intersection with respect to int_b
"""
# NOTE: The values help in
a_cat_b, counts = torch.cat([int_a, int_b]).unique(return_counts=True)
intersect_a_b = a_cat_b[torch.where(counts.gt(1))]
idx_in_b = (intersect_a_b.unsqueeze(1) == int_b).nonzero()[:, 1]
return intersect_a_b, idx_in_b
def get_only_in_b(self, intersect_a_b, int_b):
"""
Return elements present only in b
"""
# NOTE: It is very interesting that this works.
# intersect_a_b - delay_update_elements_local_avail
# int_b - grad_update_element_idx
# delay_update_local_avail -> is the elments in the intersection of elements which are being evicted and elements which have been updated by gradient currently(grad_update_element_idx)
# grad_update_element_idx -> is all the elements which are updated in current round
# the interesting point is that all elements in delay_update_local_avail will be in the grad_update_element_idx, so we just need to concatenate and find elements which have a frequency of 1
# print("Intersect a_b {}".format(intersect_a_b.shape))
# print("int_b {}".format(int_b.shape))
a_cat_b, counts = torch.cat([intersect_a_b, int_b]).unique(return_counts=True)
# print("A cat b {}".format(a_cat_b))
# print(" Counte {}".format(counts))
elements_b = a_cat_b[torch.where(counts.eq(1))]
idx_in_b = (elements_b.unsqueeze(1) == int_b).nonzero()[:, 1]
return elements_b, idx_in_b
def find_unique_embs(self, emb_vals):
"""
Find unique embs
"""
split_unique_start = torch.cuda.Event(enable_timing=True)
split_unique_stop = torch.cuda.Event(enable_timing=True)
time_spent_unique = 0
with torch.no_grad():
unique_embs = list()
for table_id, emb_id in enumerate(emb_vals):
local_cache_id = self.cache_idx[table_id][emb_id].tolist()
unique_embs.extend(local_cache_id)
return torch.tensor(unique_embs)
def sync_only_next_round(self, round_number, next_round_emb):
"""
Split the training based on learning
"""
split_start_time = torch.cuda.Event(enable_timing=True)
split_stop_time = torch.cuda.Event(enable_timing=True)
with torch.no_grad():
embeddings_needed_next_iter = self.find_unique_embs(next_round_emb)
embeddings_needed_next_iter = embeddings_needed_next_iter.to(self.device)
self.local_cache.weight.grad = self.local_cache.weight.grad.coalesce()
grad_update_element_idx = copy.deepcopy(
self.local_cache.weight.grad.indices().squeeze()
)
grad_update_element_values = copy.deepcopy(
self.local_cache.weight.grad.values()
)
grad_update_element_shape = copy.deepcopy(
self.local_cache.weight.grad.size()
)
# print("Grad update element shape {}".format(grad_update_element_idx.shape))
(
elements_to_sync_now_local_avail,
elements_to_sync_now_idx_original,
) = self.get_intersection(
embeddings_needed_next_iter, grad_update_element_idx
)
(
delay_update_elements_local_avail,
delay_update_elements_idx_original,
) = self.get_only_in_b(
elements_to_sync_now_local_avail, grad_update_element_idx
)
# print("Delay elements {}".format(delay_update_elements_local_avail.shape))
# print("Elements to sync {}".format(elements_to_sync_now_local_avail.shape))
values_to_sync_now = grad_update_element_values[
elements_to_sync_now_idx_original
]
values_to_sync_later = grad_update_element_values[
delay_update_elements_idx_original
]
elements_to_sync_now_local_avail = (
elements_to_sync_now_local_avail.unsqueeze(0)
)
vector_to_sync_now = torch.sparse_coo_tensor(
elements_to_sync_now_local_avail,
values_to_sync_now,
size=grad_update_element_shape,
)
if round_number != 0:
self.later_sync_future.wait()
dist.all_reduce(vector_to_sync_now, async_op=False)
if round_number != 0:
self.local_cache.weight.grad = (
vector_to_sync_now + self.sync_later_buffer
)
else:
self.local_cache.weight.grad = vector_to_sync_now
delay_update_elements_local_avail = (
delay_update_elements_local_avail.unsqueeze(0)
)
self.sync_later_buffer = torch.sparse_coo_tensor(
delay_update_elements_local_avail,
values_to_sync_later,
size=grad_update_element_shape,
)
self.later_sync_future = dist.all_reduce(
self.sync_later_buffer, async_op=True
)
return None
def sync_split(self, round_number):
"""
Split the embedding sync path. Embeddings which will be needed in future will be synchronized immediately
while embeddings which will be evicted in this round are synced async separately.
"""
with torch.no_grad():
# coealesce the gradient
self.local_cache.weight.grad = self.local_cache.weight.grad.coalesce()
# find the elements from the cache which will be evicted and which will not be evicted
# evicted in this round = sync later
# not currently evicted = sync now because we will need them
evicted_in_this_round = self.get_elements_evicted(round_number)
evicted_in_this_round = evicted_in_this_round.to(self.device)
# print("Evicted in this round length {}".format(evicted_in_this_round.shape))
# this is wehere we keep our dense elements
# dense elements are where we keep up elements which are going to be evicted in future
# NOTE: These elements can be synced using dense as well and then converted to sparse vector.
# Especially I think that hot elements which are usually constantly in cache might benefit the most.
# I will give it a shot later but for the first cut we will just create a sparse vector.
# get local gradients updates indices and values
grad_update_element_idx = copy.deepcopy(
self.local_cache.weight.grad.indices().squeeze()
)
grad_update_element_values = copy.deepcopy(
self.local_cache.weight.grad.values()
)
grad_update_element_shape = copy.deepcopy(
self.local_cache.weight.grad.size()
)
# elements which are going to evicted and also have grad updates available locally
# print(next(self.top_mlp.parameters()).device)
# print("Evicted In this round {}".format(evicted_in_this_round))
# print("Grad update element {}".format(grad_update_element_idx))
# print("Grad update element shape {}".format(grad_update_element_idx.shape))
(
delay_update_elements_local_avail,
delay_update_elements_idx_original,
) = self.get_intersection(evicted_in_this_round, grad_update_element_idx)
# print(
# "Delay update elements local avail {}".format(
# delay_update_elements_local_avail.shape
# )
# )
# print(
# "Delay update idx original {}".format(
# delay_update_elements_idx_original.shape
# )
# )
# elements evicted in this round will be delayed sync
# extract elements from the original vector
(
elements_to_sync_now,
elements_to_sync_now_idx_original,
) = self.get_only_in_b(
delay_update_elements_local_avail, grad_update_element_idx
)
# print("Elements to sync now {}".format(elements_to_sync_now.shape))
# print(
# "Elements to sync now idx original {}".format(
# elements_to_sync_now_idx_original.shape
# )
# )
values_to_sync_later = grad_update_element_values[
delay_update_elements_idx_original
]
values_to_sync_now = grad_update_element_values[
elements_to_sync_now_idx_original
]
# elements going to be evicted in future are going to synced now
# print("Elements to sync now {}".format(elements_to_sync_now))
# print("Values to sync {}".format(values_to_sync_now))
vector_to_sync_now = torch.sparse_coo_tensor(
elements_to_sync_now.unsqueeze_(0),
values_to_sync_now,
size=grad_update_element_shape,
)
if round_number != 0:
# wait for the previous sync to finish
self.later_sync_future.wait()
dist.all_reduce(vector_to_sync_now, async_op=False)
# we now have access to current gradient updates
if round_number != 0:
self.local_cache.weight.grad = (
vector_to_sync_now + self.sync_later_buffer
)
else:
self.local_cache.weight.grad = vector_to_sync_now
self.sync_later_buffer = torch.sparse_coo_tensor(
delay_update_elements_local_avail.unsqueeze_(0),
values_to_sync_later,
size=grad_update_element_shape,
)
self.later_sync_future = dist.all_reduce(
self.sync_later_buffer, async_op=True
)
return None
def sync_id(self):
# sync_embeddings = list()
with torch.no_grad():
# TODO: verify that this actually works in place
dist.all_reduce(self.local_cache.weight.grad)
def apply_emb(self, lS_i):
"""
Fetch embedding
"""
fetched_embeddings = list()
for table_id, emb_id in enumerate(lS_i):
# find the corresponding id to fetch
local_cache_id = self.cache_idx[table_id][emb_id]
# NOTE: Commented checking code
# local_cache_invalid = local_cache_id == -1
# local_cache_invalid = local_cache_invalid.nonzero().squeeze()
# print(local_cache_invalid)
# if len(local_cache_invalid.shape) == 0:
# local_cache_invalid = torch.tensor([local_cache_invalid.item()])
# if len(local_cache_invalid) != 0:
# print("Table {} Emb {}".format(table_id, emb_id[local_cache_invalid]))
# sys.exit("Invalid cache indexed")
# print("local cache id device {}".format(local_cache_id.device))
embs = self.local_cache(
local_cache_id,
torch.arange(len(local_cache_id)).to(self.device),
)
fetched_embeddings.append(embs)
return fetched_embeddings
def interact_features(self, x, ly):
"""
Interaction between dense and embeddings
"""
# Copied from interact features function of original code
if self.feature_interaction == "dot":
(batch_size, d) = x.shape
T = torch.cat([x] + ly, dim=1).view((batch_size, -1, d))
Z = torch.bmm(T, torch.transpose(T, 1, 2))
_, ni, nj = Z.shape
offset = 1 if self.interact_itself else 0
li = torch.tensor([i for i in range(ni) for j in range(i + offset)])
lj = torch.tensor([j for i in range(nj) for j in range(i + offset)])
Zflat = Z[:, li, lj]
R = torch.cat([x] + [Zflat], dim=1)
elif self.feature_interaction == "cat":
R = torch.cat([x] + ly, dim=1)
else:
sys.exit("Unsupported feature interaction")
return R
def forward(self, dense_x, lS_i, target):
"""
Forward pass of the training
"""
# first we perform bottom MLP
# print("Dense x shape {}".format(dense_x.shape))
# start_time = torch.cuda.Event(enable_timing=True)
# stop_time = torch.cuda.Event(enable_timing=True)
# start_time.record()
x = self.apply_mlp(dense_x, self.bot_mlp)
# stop_time.record()
# torch.cuda.synchronize()
# print("Time apply bottom mlp {}".format(start_time.elapsed_time(stop_time)))
# need to fetch the embeddings
# at this point we will either have embeddings in the local cache or
# global cache
# if handle_all_reduce is not None:
# check if all reduce is done or not
# handle_all_reduce.wait()
# start_time.record()
ly = self.apply_emb(lS_i)
# stop_time.record()
# torch.cuda.synchronize()
# print("Time apply emb {}".format(start_time.elapsed_time(stop_time)))
# print(x)
# print(ly)
# feature interaction
# start_time.record()
z = self.interact_features(x, ly)
# stop_time.record()
# torch.cuda.synchronize()
# print("Time feature interat {}".format(start_time.elapsed_time(stop_time)))
# pass through top mlp
# start_time.record()
p = self.apply_mlp(z, self.top_mlp)
# stop_time.record()
# torch.cuda.synchronize()
# print("Time top mlp {}".format(start_time.elapsed_time(stop_time)))
# start_time.record()
loss = self.loss_fn(p, target)
# stop_time.record()
# torch.cuda.synchronize()
# print("Time loss calculation{}".format(start_time.elapsed_time(stop_time)))
# print(loss)
return loss
def update_train_queue(input_dict):
# print("Train queue status {}".format(input_dict))
input_key = list(input_dict.keys())[0]
sparse_vector = input_dict[input_key]["train_data"]["sparse_vector"]
unique_list = list()
for k in sparse_vector:
unique_list.append(torch.unique(k))
input_dict[input_key]["sparse_unique"] = unique_list
comp_intensive_model.train_queue.put(input_dict)
return 1
s = torch.cuda.Stream()
def fill_prefetch_cache():
num_times_run = 0
try:
while num_times_run < comp_intensive_model.lookahead_value:
prefetch_time_start = time.time()
ttl_val, val = comp_intensive_model.prefetch_queue.get(block=True)
# ttl_val = list(val.keys())[0]
if ttl_val != comp_intensive_model.prefetch_expected_iter:
while ttl_val != comp_intensive_model.prefetch_expected_iter:
# wrong fetch putting it back
comp_intensive_model.prefetch_queue.put((ttl_val, val))
# Hopefully by now we will have gotten what we needed
ttl_val, val = comp_intensive_model.prefetch_queue.get(block=True)
# ttl_val = list(val.keys())[0]
fut = rpc.rpc_async(
comp_intensive_model.emb_worker, get_embedding_single, args=(val,)
)
comp_intensive_model.prefetch_expected_iter += 1
# NOTE:Enable for dynamic look ahead
# comp_intensive_model.dynamic_lookahead_val[ttl_val] = val["lookahead_value"]
comp_intensive_model.prefetch_futures_queue.put(fut)
comp_intensive_model.prefetch_queue_ttl.put(ttl_val)
# keep getting prefetch queue
fut = comp_intensive_model.prefetch_futures_queue.get(block=True)
ttl_val = comp_intensive_model.prefetch_queue_ttl.get(block=True)
fetched_vals = fut.wait()
# print("Fetched vals {}".format(fetched_vals))
total_time_movement_per_batch = 0
# cuda_start_movement = torch.cuda.Event(enable_timing=True)
# cuda_stop_movement = torch.cuda.Event(enable_timing=True)
empty_location = comp_intensive_model.local_cache_status == -1
empty_location = empty_location.nonzero().squeeze()
last_use_location = 0
# logger.info("Cache Size Remaining {}".format(len(empty_location)))
# logger.info("Cache Size used {}".format(comp_intensive_model.cache_usage))
# logger.info(
# "Sum of free and empty {}".format(
# len(empty_location) + comp_intensive_model.cache_usage
# )
# )
for table_id, emb_vals in enumerate(fetched_vals):
# find the original idx
if len(emb_vals) > 0:
# cuda_start_movement.record()
emb_vals_length = len(emb_vals)
comp_intensive_model.total_additions += emb_vals_length
# cuda_start_movement.record()
with torch.cuda.stream(s):
emb_vals = emb_vals.to(
comp_intensive_model.device,
)
indexing_offset = torch.arange(
emb_vals_length, device=comp_intensive_model.device
)
# cuda_stop_movement.record()
# torch.cuda.synchronize()
# total_time_movement_per_batch += cuda_start_movement.elapsed_time(
# cuda_stop_movement
# )