-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathdata.py
More file actions
1807 lines (1422 loc) · 73.4 KB
/
data.py
File metadata and controls
1807 lines (1422 loc) · 73.4 KB
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
import pandas as pd
import torch
from torch.utils.data import Dataset
import numpy as np
from typing import List, Tuple
import json
import random
from tqdm import tqdm
import os
import copy
import torch.nn.functional as F
class Tokenizer:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.bos_id: int = self.tokenizer.bos_token_id
self.eos_id: int = self.tokenizer.eos_token_id
def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
assert type(s) is str
t = self.tokenizer.encode(s)
while t[0] == self.bos_id:
t = t[1:]
while t[-1] == self.eos_id:
t = t[:-1]
if bos and self.bos_id is not None:
t = [self.bos_id] + t
if eos and self.eos_id is not None:
t = t + [self.eos_id]
return t
def decode(self, t: List[int]) -> str:
return self.tokenizer.decode(t)
class BaseDataset(Dataset):
def __init__(self, tokenizer=None, max_len=2048, test=False, category="", dedup=False, seed=None):
super().__init__()
self.data = None
self.inputs = None
if tokenizer is not None:
self.tokenizer = Tokenizer(tokenizer)
if seed is not None:
random.seed(seed)
self.test = test
self.max_len = max_len
self.category = category
self.dedup = dedup
def __len__(self):
return len(self.data)
def get_inputs(self):
inputs = []
for i in tqdm(range(len(self.data))):
inputs.append(self.pre(i))
self.inputs = inputs
def get_all(self):
temp = []
for i in range(len(self.data)):
temp.append(self.get_history(self.data.iloc[i]))
return temp
def get_inputs_list(self):
return self.inputs
def __getitem__(self, idx):
return self.inputs[idx]
def pre(self, idx):
raise NotImplementedError(None)
def get_history(self, row):
raise {}
def generate_prompt(self, data_point):
return f"""### User Input:
{data_point["input"]}
### Response:\n{data_point["output"]}"""
class CSVBaseDataset(BaseDataset):
def __init__(self, train_file, sample=-1, seed=0, max_len=2048, category="", dedup=False, tokenizer=None, test=False):
super().__init__(tokenizer, max_len, test, category, dedup, seed)
self.data = pd.read_csv(train_file)
if sample > 0:
self.data = self.data.sample(sample, random_state=seed)
class JSONBaseDataset(BaseDataset):
def __init__(self, item_file=None, index_file=None, tokenizer=None, max_len=2048, test=False, category="", dedup=False, seed=None):
super().__init__(tokenizer, max_len, test, category, dedup, seed)
# Load item features and indices if files are provided
with open(item_file, 'r') as f:
self.item_feat = json.load(f)
with open(index_file, 'r') as f:
self.indices = json.load(f)
class SFTData(CSVBaseDataset):
def __init__(self, train_file, tokenizer, max_len=2048, sample=-1, test = False, seed=0, category="", K=4, dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer, test)
self.instructs = [
f"Given a list of {category} the user recetenly enjoy, please write a new {category} that the user may bought",
f"Considering the {category} that has recently captured the user's interest, kindly create a compilation of other {category} that the user might have played prior to this.",
f"Based on the user's current gaming preference, please draft a list of potential {category} they may have experienced beforehand.",
f"Reflecting on the {category} the user has taken pleasure in recently, we request that you formulate a list of {category} that may have preceded the user's current enjoyment.",
f"In light of the recent gaming enjoyment expressed by the user, please assemble a list of {category} that could potentially include past titles the user has engaged with.",
f"Taking into account the {category} that has lately provided enjoyment to the user, please put together an inventory of {category} the user might have explored previously.",
f"Given the user's newfound enjoyment of a particular {category}, would you kindly generate a roster of other {category} that might resonate with their past gaming experiences?",
f"In response to the user's recent fondness for a specific {category}, we seek your assistance in listing possible {category} the user may have delighted in earlier.",
f"With respect to the {category} currently enjoyed by the user, please compile a suggestive list of {category} they may have played in the past.",
f"Bearing in mind the {category} that the user has recently been enthralled by, please construct a catalog of other {category} that the user potentially partook in beforehand.",
f"In relation to the user's recent entertainment with a given {category}, it would be appreciated if you could curate a list of {category} that might form part of the user's previous gaming history."
]
self.get_inputs()
def generate_example_prompt(self, data_point):
return f"""### Example {data_point["idx"]}:
{data_point["input"]}
### Response:\n{data_point["output"]}
"""
def get_history(self, row):
row['history_item_title'] = eval(row['history_item_title'])
L = len(row['history_item_title'])
history = ""
history_str = "::".join(row["history_item_title"])
for i in range(L):
if i == 0:
history += "\"" + row['history_item_title'][i] + "\""
else:
history += ",\t\"" + row['history_item_title'][i] + "\""
target_item = str(row['item_title'])
target_item = "\"" + target_item + "\"\n"
target_item_id = row["item_id"]
last_history_item_id = eval(row["history_item_id"])[-1]
return {"input": f"The user has palyed the following {self.category}s before: {history}",
"output": target_item,
"history_str": history_str,
"dedup": target_item_id == last_history_item_id}
def pre(self, idx):
instruction = f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{self.instructs[random.randint(0, len(self.instructs)-1)]}\n
"""
tokens = self.tokenizer.encode(instruction, bos=True, eos=False)
history = self.get_history(self.data.iloc[idx])
target_item = history['output']
history['output'] = ''
negative_prompt_ids = copy.deepcopy(tokens)
prompt = self.generate_prompt(history)
tokens = tokens + self.tokenizer.encode(prompt, bos=False, eos=False)
history["input"] = ""
attention_mask = [1] * len(tokens)
if self.test:
return {
"input_ids": tokens,
"attention_mask": attention_mask,
}
golden_tokens = self.tokenizer.encode(target_item, bos=False, eos=True)
input_prompt_len = len(tokens)
tokens = tokens + golden_tokens
attention_mask = [1] * len(tokens)
labels = [-100] * input_prompt_len + tokens[input_prompt_len:]
if len(tokens) >= self.max_len:
print(len(tokens))
return {
"input_ids": tokens[-self.max_len:],
"attention_mask": attention_mask[-self.max_len:],
"labels": labels[-self.max_len:],
}
class D3Dataset(CSVBaseDataset):
def __init__(self, train_file, max_len=2048, sample=-1, seed=0, category="", dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer=None, test=False)
self.prompt2history = {}
self.history2target = {}
self.instructs = [
f"Given a list of {category} the user recetenly enjoy, please write a new {category} that the user may bought",
f"Considering the {category} that has recently captured the user's interest, kindly create a compilation of other {category} that the user might have played prior to this.",
f"Based on the user's current gaming preference, please draft a list of potential {category} they may have experienced beforehand.",
f"Reflecting on the {category} the user has taken pleasure in recently, we request that you formulate a list of {category} that may have preceded the user's current enjoyment.",
f"In light of the recent gaming enjoyment expressed by the user, please assemble a list of {category} that could potentially include past titles the user has engaged with.",
f"Taking into account the {category} that has lately provided enjoyment to the user, please put together an inventory of {category} the user might have explored previously.",
f"Given the user's newfound enjoyment of a particular {category}, would you kindly generate a roster of other {category} that might resonate with their past gaming experiences?",
f"In response to the user's recent fondness for a specific {category}, we seek your assistance in listing possible {category} the user may have delighted in earlier.",
f"With respect to the {category} currently enjoyed by the user, please compile a suggestive list of {category} they may have played in the past.",
f"Bearing in mind the {category} that the user has recently been enthralled by, please construct a catalog of other {category} that the user potentially partook in beforehand.",
f"In relation to the user's recent entertainment with a given {category}, it would be appreciated if you could curate a list of {category} that might form part of the user's previous gaming history."
]
self.get_inputs()
def get_history(self, row):
row['history_item_title'] = eval(row['history_item_title'])
L = len(row['history_item_title'])
history = ""
history_str = "::".join(row["history_item_title"])
for i in range(L):
if i == 0:
history += "\"" + row['history_item_title'][i] + "\""
else:
history += ",\t\"" + row['history_item_title'][i] + "\""
target_item = str(row['item_title'])
target_item = "\"" + target_item + "\"\n"
target_item_id = row["item_id"]
last_history_item_id = eval(row["history_item_id"])[-1]
return {"input": f"The user has palyed the following {self.category}s before: {history}",
"output": target_item,
"history_str": history_str,
"dedup": target_item_id == last_history_item_id}
def pre(self, idx):
instruction = f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{self.instructs[random.randint(0, len(self.instructs)-1)]}\n
"""
history = self.get_history(self.data.iloc[idx])
target_item = history['output']
history['output'] = ''
prompt = self.generate_prompt(history)
self.prompt2history[instruction + prompt] = history["history_str"]
self.history2target[history["history_str"]] = target_item
return {
"prompt": instruction + prompt,
"completion": target_item,
}
class EvalD3Dataset(CSVBaseDataset):
def __init__(self, train_file, tokenizer, max_len=2048, sample=-1, test = False, seed=0, category="", K=4, dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer, test)
self.instructs = [
f"Given a list of {category} the user recetenly enjoy, please write a new {category} that the user may bought",
f"Considering the {category} that has recently captured the user's interest, kindly create a compilation of other {category} that the user might have played prior to this.",
f"Based on the user's current gaming preference, please draft a list of potential {category} they may have experienced beforehand.",
f"Reflecting on the {category} the user has taken pleasure in recently, we request that you formulate a list of {category} that may have preceded the user's current enjoyment.",
f"In light of the recent gaming enjoyment expressed by the user, please assemble a list of {category} that could potentially include past titles the user has engaged with.",
f"Taking into account the {category} that has lately provided enjoyment to the user, please put together an inventory of {category} the user might have explored previously.",
f"Given the user's newfound enjoyment of a particular {category}, would you kindly generate a roster of other {category} that might resonate with their past gaming experiences?",
f"In response to the user's recent fondness for a specific {category}, we seek your assistance in listing possible {category} the user may have delighted in earlier.",
f"With respect to the {category} currently enjoyed by the user, please compile a suggestive list of {category} they may have played in the past.",
f"Bearing in mind the {category} that the user has recently been enthralled by, please construct a catalog of other {category} that the user potentially partook in beforehand.",
f"In relation to the user's recent entertainment with a given {category}, it would be appreciated if you could curate a list of {category} that might form part of the user's previous gaming history."
]
self.get_inputs()
def generate_example_prompt(self, data_point):
return f"""### Example {data_point["idx"]}:
{data_point["input"]}
### Response:\n{data_point["output"]}
"""
def get_history(self, row):
row['history_item_title'] = eval(row['history_item_title'])
L = len(row['history_item_title'])
history = ""
for i in range(L):
if i == 0:
history += "\"" + row['history_item_title'][i] + "\""
else:
history += ",\t\"" + row['history_item_title'][i] + "\""
target_item = str(row['item_title'])
target_item = "\"" + target_item + "\""
target_item_id = row["item_id"]
last_history_item_id = eval(row["history_item_id"])[-1]
return {"input": f"The user has palyed the following {self.category}s before: {history}",
"output": target_item + '\n',
"dedup": target_item_id == last_history_item_id}
def pre(self, idx):
instruction = f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{self.instructs[random.randint(0, len(self.instructs)-1)]}\n
"""
tokens = self.tokenizer.encode(instruction, bos=True, eos=False)
history = self.get_history(self.data.iloc[idx])
target_item = history['output']
history['output'] = ''
negative_prompt_ids = copy.deepcopy(tokens)
prompt = self.generate_prompt(history)
tokens = tokens + self.tokenizer.encode(prompt, bos=False, eos=False)
history["input"] = ""
attention_mask = [1] * len(tokens)
if self.test:
return {
"input_ids": tokens,
"attention_mask": attention_mask,
# "select_index": select_index,
}
golden_tokens = self.tokenizer.encode(target_item, bos=False, eos=True)
input_prompt_len = len(tokens)
tokens = tokens + golden_tokens
attention_mask = [1] * len(tokens)
labels = [-100] * input_prompt_len + tokens[input_prompt_len:]
if len(tokens) >= self.max_len:
print(len(tokens))
return {
"input_ids": tokens[-self.max_len:],
"attention_mask": attention_mask[-self.max_len:],
"labels": labels[-self.max_len:],
}
class SidDataset(CSVBaseDataset):
def __init__(self, train_file, max_len=2048, sample=-1, seed=0, category="", dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer=None, test=False)
self.prompt2history = {}
self.history2target = {}
self.get_inputs()
def get_history(self, row):
row['history_item_sid'] = eval(row['history_item_sid'])
L = len(row['history_item_sid'])
history = ""
history_str = "::".join(row["history_item_sid"])
for i in range(L):
if i == 0:
history += row['history_item_sid'][i]
else:
history += ", " + row['history_item_sid'][i]
target_item = str(row['item_sid'])
target_item_sid = row["item_sid"]
last_history_item_sid = row['history_item_sid'][-1] if row['history_item_sid'] else None
return {"input": f"The user has interacted with items {history} in chronological order. Can you predict the next possible item that the user may expect?",
# Analyze user preferences and then predict the semantic ID of the next item.
"output": target_item + "\n",
"history_str": history_str,
"dedup": target_item_sid == last_history_item_sid}
def pre(self, idx):
history = self.get_history(self.data.iloc[idx])
target_item = history['output']
history['output'] = ''
prompt = self.generate_prompt(history)
self.prompt2history[prompt] = history["history_str"]
self.history2target[history["history_str"]] = target_item
return {
"prompt": prompt,
"completion": target_item,
}
class SidSFTDataset(CSVBaseDataset):
def __init__(self, train_file, tokenizer, max_len=2048, sample=-1, test=False, seed=0, category="", K=4, dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer, test)
self.get_inputs()
def get_history(self, row):
row['history_item_sid'] = eval(row['history_item_sid'])
L = len(row['history_item_sid'])
history = ""
history_str = ", ".join(row["history_item_sid"])
for i in range(L):
if i == 0:
history += row['history_item_sid'][i]
else:
history += ", " + row['history_item_sid'][i]
target_item = str(row['item_sid'])
target_item_sid = row["item_sid"]
last_history_item_sid = row['history_item_sid'][-1] if row['history_item_sid'] else None
return {"input": f"The user has interacted with items {history} in chronological order. Can you predict the next possible item that the user may expect?",
"output": target_item + "\n",
"history_str": history_str,
"dedup": target_item_sid == last_history_item_sid}
def pre(self, idx):
instruction = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
Can you predict the next possible item that the user may expect?
"""
tokens = self.tokenizer.encode(instruction, bos=True, eos=False)
history = self.get_history(self.data.iloc[idx])
# print("**********************")
# print("history: ", history)
target_item = history['output']
history['output'] = ''
negative_prompt_ids = copy.deepcopy(tokens)
prompt = self.generate_prompt(history)
# print("prompt: ", prompt)
tokens = tokens + self.tokenizer.encode(prompt, bos=False, eos=False)
# print("tokens: ", tokens)
# print("**********************")
history["input"] = ""
attention_mask = [1] * len(tokens)
if self.test:
return {
"input_ids": tokens,
"attention_mask": attention_mask,
}
golden_tokens = self.tokenizer.encode(target_item, bos=False, eos=True)
input_prompt_len = len(tokens)
tokens = tokens + golden_tokens
attention_mask = [1] * len(tokens)
labels = [-100] * input_prompt_len + tokens[input_prompt_len:]
if len(tokens) >= self.max_len:
print(len(tokens))
return {
"input_ids": tokens[-self.max_len:],
"attention_mask": attention_mask[-self.max_len:],
"labels": labels[-self.max_len:],
}
class SidSFTDataset_GPR(CSVBaseDataset):
def __init__(self, train_file, tokenizer, max_len=2048, sample=-1, test=False, seed=0, category="", K=4, dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer, test)
# Try to load features from standard location
try:
with open(f'data/{category}/{category}.user.json', 'r') as f:
self.user_features = json.load(f)
except FileNotFoundError:
try:
dataset_dir = os.path.dirname(train_file)
# Assuming structure data/Amazon/train/Sports... -> data/Sports/Sports.user.json
with open(f'data/{category}/{category}.user.json', 'r') as f:
self.user_features = json.load(f)
except:
self.user_features = {}
try:
with open(f'data/{category}/{category}.item.json', 'r') as f:
self.item_features = json.load(f)
except FileNotFoundError:
self.item_features = {}
self.get_inputs()
def get_history(self, row):
row['history_item_sid'] = eval(row['history_item_sid'])
L = len(row['history_item_sid'])
history = ""
history_str = ", ".join(row["history_item_sid"])
for i in range(L):
if i == 0:
history += row['history_item_sid'][i]
else:
history += ", " + row['history_item_sid'][i]
target_item = str(row['item_sid'])
target_item_sid = row["item_sid"]
last_history_item_sid = row['history_item_sid'][-1] if row['history_item_sid'] else None
return {"input": f"The user has interacted with items {history} in chronological order. Can you predict the next possible item that the user may expect?",
"output": target_item + "\n",
"history_str": history_str,
"dedup": target_item_sid == last_history_item_sid}
def pre(self, idx):
instruction = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
Can you predict the next possible item that the user may expect?
"""
tokens = self.tokenizer.encode(instruction, bos=True, eos=False)
row = self.data.iloc[idx]
# Heterogeneous Prompt Construction
user_id = str(row.get('user_id_original_str', ''))
u_token = self.user_features.get(user_id, '[USER_UNKNOWN]')
e_token = row.get('e_token', '[CTX_HOMEPAGE]')
try:
history_item_ids = eval(str(row['history_item_id']))
history_sids = eval(str(row['history_item_sid']))
except:
history_item_ids = []
history_sids = []
history_str = ""
for i, item_id in enumerate(history_item_ids):
item_type = self.item_features.get(str(item_id), {}).get('item_type', 'O')
token_prefix = '[O_TOKEN]' if item_type == 'O' else '[I_TOKEN]'
if i > 0: history_str += ", "
sid = history_sids[i] if i < len(history_sids) else ""
history_str += f"{token_prefix}{sid}"
target_item_id = str(row['item_id'])
target_sid = str(row['item_sid'])
target_type = self.item_features.get(target_item_id, {}).get('item_type', 'O')
target_prefix = '[O_TOKEN]' if target_type == 'O' else '[I_TOKEN]'
target_item_with_prefix = f"{target_prefix}{target_sid}\n"
# Prompt
input_text = f"{u_token} {e_token} The user has interacted with items {history_str} in chronological order. Can you predict the next possible item that the user may expect?"
history = {
"input": input_text,
"output": target_item_with_prefix
}
target_item = history['output']
history['output'] = ''
negative_prompt_ids = copy.deepcopy(tokens)
prompt = self.generate_prompt(history)
tokens = tokens + self.tokenizer.encode(prompt, bos=False, eos=False)
history["input"] = ""
attention_mask = [1] * len(tokens)
# Final Value for VAFT
final_value = self.item_features.get(target_item_id, {}).get('final_value', 0.0)
if self.test:
return {
"input_ids": tokens,
"attention_mask": attention_mask,
"final_value": final_value
}
golden_tokens = self.tokenizer.encode(target_item, bos=False, eos=True)
input_prompt_len = len(tokens)
tokens = tokens + golden_tokens
attention_mask = [1] * len(tokens)
labels = [-100] * input_prompt_len + tokens[input_prompt_len:]
if len(tokens) >= self.max_len:
print(len(tokens))
return {
"input_ids": tokens[-self.max_len:],
"attention_mask": attention_mask[-self.max_len:],
"labels": labels[-self.max_len:],
"final_value": final_value
}
class EvalSidDataset(CSVBaseDataset):
def __init__(self, train_file, tokenizer, max_len=2048, sample=-1, test = False, seed=0, category="", K=4, dedup=False):
super().__init__(train_file, sample, seed, max_len, category, dedup, tokenizer, test)
self.get_inputs()
def generate_example_prompt(self, data_point):
return f"""### Example {data_point["idx"]}:
{data_point["input"]}
### Response:\n{data_point["output"]}
"""
def get_history(self, row):
row['history_item_sid'] = eval(row['history_item_sid'])
L = len(row['history_item_sid'])
history = ""
for i in range(L):
if i == 0:
history += row['history_item_sid'][i]
else:
history += ", " + row['history_item_sid'][i]
target_item = str(row['item_sid'])
target_item_sid = row["item_sid"]
last_history_item_sid = row['history_item_sid'][-1] if row['history_item_sid'] else None
return {"input": # f"The user has interacted with items {history} in chronological order. Can you predict the next possible item that the user may expect?",
f"Can you predict the next possible item the user may expect, given the following chronological interaction history: {history}",
"output": target_item + '\n',
"dedup": target_item_sid == last_history_item_sid}
def pre(self, idx):
instruction = f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
Can you predict the next possible item that the user may expect?
"""
tokens = self.tokenizer.encode(instruction, bos=True, eos=False)
history = self.get_history(self.data.iloc[idx])
target_item = history['output']
history['output'] = ''
negative_prompt_ids = copy.deepcopy(tokens)
prompt = self.generate_prompt(history)
tokens = tokens + self.tokenizer.encode(prompt, bos=False, eos=False)
history["input"] = ""
attention_mask = [1] * len(tokens)
if self.test:
return {
"input_ids": tokens,
"attention_mask": attention_mask,
}
golden_tokens = self.tokenizer.encode(target_item, bos=False, eos=True)
input_prompt_len = len(tokens)
tokens = tokens + golden_tokens
attention_mask = [1] * len(tokens)
labels = [-100] * input_prompt_len + tokens[input_prompt_len:]
if len(tokens) >= self.max_len:
print(len(tokens))
return {
"input_ids": tokens[-self.max_len:],
"attention_mask": attention_mask[-self.max_len:],
"labels": labels[-self.max_len:],
}
class SidItemFeatDataset(JSONBaseDataset):
def __init__(self, item_file, index_file, tokenizer=None, max_len=2048, sample=-1, test=False, seed=0, category=""):
"""
Dataset for sid2title and title2sid tasks.
Args:
item_file: Path to .item.json file with item features
index_file: Path to .index.json file with item indices
tokenizer: Tokenizer for encoding text
max_len: Maximum sequence length
sample: Number of samples to use (-1 for all)
test: Whether this is test mode
seed: Random seed
category: Category name for prompts
"""
super().__init__(item_file=item_file, index_file=index_file, tokenizer=tokenizer, max_len=max_len, test=test, category=category, dedup=False, seed=seed)
# Build sid2title and title2sid mappings
self.sid2title = {}
self.title2sid = {}
for item_id, sids in self.indices.items():
if item_id in self.item_feat:
title = self.item_feat[item_id]['title']
# Concatenate all three semantic IDs as the key
if len(sids) >= 3:
combined_sid = sids[0] + sids[1] + sids[2]
self.sid2title[combined_sid] = title
self.title2sid[title] = combined_sid
# Create data samples
self.data = []
# Create sid2title samples
for sid, title in self.sid2title.items():
self.data.append({
'task': 'sid2title',
'input': sid,
'output': title
})
# Create title2sid samples
for title, sid in self.title2sid.items():
self.data.append({
'task': 'title2sid',
'input': title,
'output': sid
})
if sample > 0 and sample < len(self.data):
self.data = random.sample(self.data, sample)
if self.tokenizer is not None:
self.get_inputs()
def generate_prompt(self, data_point):
if data_point['task'] == 'title2sid':
prompt = f"Which item has the title: {data_point['input']}?"
response = data_point['output']
else: # sid2title
prompt = f'What is the title of item "{data_point["input"]}"?'
response = data_point['output']
return f"""### User Input:
{prompt}
### Response:\n"""
def pre(self, idx):
if self.tokenizer is None:
return self.data[idx]
instruction = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
Answer the question about item identification.
"""
tokens = self.tokenizer.encode(instruction, bos=True, eos=False)
data_point = self.data[idx]
prompt = self.generate_prompt(data_point)
# print("sidfeature prompt: ", prompt)
tokens = tokens + self.tokenizer.encode(prompt, bos=False, eos=False)
attention_mask = [1] * len(tokens)
if self.test:
return {
"input_ids": tokens,
"attention_mask": attention_mask,
}
target = data_point['output'] + '\n'
golden_tokens = self.tokenizer.encode(target, bos=False, eos=True)
input_prompt_len = len(tokens)
tokens = tokens + golden_tokens
attention_mask = [1] * len(tokens)
labels = [-100] * input_prompt_len + tokens[input_prompt_len:]
if len(tokens) >= self.max_len:
print(f"Sequence length {len(tokens)} exceeds max_len {self.max_len}")
return {
"input_ids": tokens[-self.max_len:],
"attention_mask": attention_mask[-self.max_len:],
"labels": labels[-self.max_len:],
}
class RLTitle2SidDataset(JSONBaseDataset):
def __init__(self, item_file, index_file, sample=-1, seed=0, category="", dedup=False):
"""
RL-specific dataset for title2sid and description2sid tasks.
Returns prompt-completion pairs for RL training.
Args:
item_file: Path to .item.json file with item features
index_file: Path to .index.json file with item indices
max_len: Maximum sequence length (not used for RL format)
sample: Number of samples to use (-1 for all)
seed: Random seed
category: Category name for prompts
dedup: Whether to filter duplicate items
"""
super().__init__(item_file, index_file, tokenizer=None, max_len=1024, test=False, category=category, dedup=dedup, seed=seed)
self.prompt2history = {}
self.history2target = {}
# Build sid2title and sid2description mappings
self.sid2title = {}
self.title2sid = {}
self.sid2description = {}
self.description2sid = {}
for item_id, sids in self.indices.items():
if item_id in self.item_feat:
title = self.item_feat[item_id]['title']
description = self.item_feat[item_id]['description']
# Handle description format
if isinstance(description, str) and description.startswith("['") and description.endswith("']"):
try:
desc_list = eval(description)
description = desc_list[0] if desc_list else description
except:
pass
# Concatenate all three semantic IDs as the key
if len(sids) >= 3:
combined_sid = sids[0] + sids[1] + sids[2]
self.sid2title[combined_sid] = title
self.title2sid[title] = combined_sid
self.sid2description[combined_sid] = description
self.description2sid[description] = combined_sid
# Create data samples
self.data = []
# Create title2sid samples
for title, sid in self.title2sid.items():
self.data.append({
'task': 'title2sid',
'input': title,
'output': sid
})
# Create description2sid samples
for description, sid in self.description2sid.items():
self.data.append({
'task': 'description2sid',
'input': description,
'output': sid
})
if sample > 0 and sample < len(self.data):
self.data = random.sample(self.data, sample)
self.get_inputs()
def generate_prompt(self, data_point):
if data_point['task'] == 'title2sid':
prompt = f"Which item has the title: {data_point['input']}?"
response = data_point['output']
else: # description2sid
prompt = f"An item can be described as follows: \"{data_point['input']}\". Which item is it describing?"
response = data_point['output']
return f"""### User Input:
{prompt}
### Response:\n"""
def pre(self, idx):
data_point = self.data[idx]
prompt = self.generate_prompt(data_point)
target_item = data_point['output'] + "\n"
self.prompt2history[prompt] = data_point['input']
self.history2target[data_point['input']] = target_item
return {
"prompt": prompt,
"completion": target_item,
}
class RLSeqTitle2SidDataset(CSVBaseDataset):
def __init__(self, train_file, sample=-1, seed=0, category="", dedup=False):
"""
RL-specific dataset for sequential recommendation using title sequences.
Uses user interaction history with item titles to recommend next item's semantic ID.
Args:
train_file: Path to CSV file with sequence data (must have history_item_title and item_sid columns)
sample: Number of samples to use (-1 for all)
seed: Random seed
category: Category name for prompts
dedup: Whether to filter duplicate items
"""
super().__init__(train_file, sample, seed, max_len=1024, category=category, dedup=dedup, tokenizer=None, test=False)
self.prompt2history = {}
self.history2target = {}
self.get_inputs()
def generate_prompt(self, inter_titles):
return f"Given the title sequence of user historical interactive items: {inter_titles}, can you recommend a suitable next item for the user?"
def get_history(self, row):
# Parse history_item_title field
history_item_title = eval(row['history_item_title'])
# Format title sequence for prompt
inter_titles = ", ".join([f'"{title}"' for title in history_item_title])
target_sid = row['item_sid']
# Check for deduplication if needed
is_duplicate = False
if self.dedup and 'history_item_id' in row:
try:
history_item_id = eval(row['history_item_id'])
target_item_id = row.get('item_id', None)
last_history_item_id = history_item_id[-1] if history_item_id else None
is_duplicate = target_item_id == last_history_item_id
except:
is_duplicate = False
return {
"inter_titles": inter_titles,
"target_sid": target_sid,
"dedup": is_duplicate,
"history_str": "::".join(history_item_title)
}
def generate_formatted_prompt(self, prompt, response):
return f"""### User Input:
{prompt}
### Response:\n"""
def pre(self, idx):
history_data = self.get_history(self.data.iloc[idx])
# Skip if duplicate and dedup is enabled
if self.dedup and history_data['dedup']:
return None
# Generate prompt using title sequence
prompt = self.generate_prompt(history_data['inter_titles'])
target = history_data['target_sid'] + '\n'
formatted_prompt = self.generate_formatted_prompt(prompt, "")
self.prompt2history[formatted_prompt] = history_data['history_str']
self.history2target[history_data['history_str']] = target
return {
"prompt": formatted_prompt,
"completion": target,
}
class RLSid2TitleDataset(JSONBaseDataset):
def __init__(self, item_file, index_file, sample=-1, seed=0, category="", dedup=False):
"""
RL-specific dataset for sid2title tasks.
Returns prompt-completion pairs for RL training where input is semantic ID and output is item title.
Args:
item_file: Path to .item.json file with item features
index_file: Path to .index.json file with item indices
sample: Number of samples to use (-1 for all)
seed: Random seed
category: Category name for prompts
dedup: Whether to filter duplicate items
"""
super().__init__(item_file, index_file, tokenizer=None, max_len=1024, test=False, category=category, dedup=dedup, seed=seed)
self.prompt2history = {}
self.history2target = {}
# Build sid2title mapping
self.sid2title = {}
for item_id, sids in self.indices.items():
if item_id in self.item_feat:
title = self.item_feat[item_id]['title']
# Concatenate all three semantic IDs as the key
if len(sids) >= 3:
combined_sid = sids[0] + sids[1] + sids[2]
self.sid2title[combined_sid] = title
# Create data samples
self.data = []