forked from HKUDS/EasyRec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode_easyrec.py
132 lines (119 loc) · 5.39 KB
/
encode_easyrec.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
import os
import math
import json
import torch
import pickle
import argparse
from tqdm import tqdm
import torch.nn.functional as F
from scipy.spatial.distance import cosine
from model import *
from utility.logger import *
from utility.metric import *
from utility.trainer import *
from datetime import datetime
from utility.load_data import *
from dataclasses import dataclass, field
from typing import Dict, Optional, Sequence, List
from transformers import AutoConfig, AutoModel, AutoTokenizer
save = True
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default='hkuds/easyrec-roberta-large', help='Model name')
parser.add_argument('--cuda', type=str, default='0')
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda
model_name_or_path = args.model
print(model_name_or_path)
config = AutoConfig.from_pretrained(model_name_or_path)
model = Easyrec.from_pretrained(
model_name_or_path,
from_tf=bool(".ckpt" in model_name_or_path),
config=config,
).cuda()
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_name_or_path,
use_fast=False,
)
eval_datas = ['movies']
diverse_profile_num = 3
for _dataset in eval_datas:
save_path = f'./data/{_dataset}/text_emb'
os.makedirs(save_path, exist_ok=True)
# original profiles
user_profile, item_profile = {}, {}
user_profile_list, item_profile_list = [], []
with open(f'./data/{_dataset}/user_profile.json', 'r') as f:
for _line in f.readlines():
_data = json.loads(_line)
user_profile[_data['user_id']] = _data['profile']
with open(f'./data/{_dataset}/item_profile.json', 'r') as f:
for _line in f.readlines():
_data = json.loads(_line)
item_profile[_data['item_id']] = _data['profile']
for i in range(len(user_profile)):
user_profile_list.append(user_profile[i])
for i in range(len(item_profile)):
item_profile_list.append(item_profile[i])
profiles = user_profile_list + item_profile_list
batch_size = 128
n_batchs = math.ceil(len(profiles) / batch_size)
text_emb = []
for i in tqdm(range(n_batchs), desc=f'{_dataset}'):
start = i * batch_size
end = (i + 1) * batch_size
batch_profile = profiles[start: end]
inputs = tokenizer(batch_profile, padding=True, truncation=True, max_length=512, return_tensors="pt")
for tem in inputs:
inputs[tem] = inputs[tem].cuda()
with torch.inference_mode():
embeddings = model.encode(input_ids=inputs.input_ids, attention_mask=inputs.attention_mask)
embeddings = F.normalize(embeddings.pooler_output.detach().float(), dim=-1)
text_emb.append(embeddings.cpu())
text_emb = torch.concat(text_emb, dim=0)
user_emb = text_emb[: len(user_profile)].numpy()
item_emb = text_emb[len(user_profile): ].numpy()
if save:
with open(f'{save_path}/user_{model_name_or_path.split("/")[-1]}.pkl', 'wb') as f:
pickle.dump(user_emb, f)
with open(f'{save_path}/item_{model_name_or_path.split("/")[-1]}.pkl', 'wb') as f:
pickle.dump(item_emb, f)
# diversified profiles
os.makedirs(f'{save_path}/diverse_profile', exist_ok=True)
for diverse_no in range(diverse_profile_num):
user_profile, item_profile = {}, {}
user_profile_list, item_profile_list = [], []
with open(f'./data/{_dataset}/diverse_profile/diverse_user_profile_{diverse_no}.json', 'r') as f:
for _line in f.readlines():
_data = json.loads(_line)
user_profile[_data['user_id']] = _data['profile']
with open(f'./data/{_dataset}/diverse_profile/diverse_item_profile_{diverse_no}.json', 'r') as f:
for _line in f.readlines():
_data = json.loads(_line)
item_profile[_data['item_id']] = _data['profile']
for i in range(len(user_profile)):
user_profile_list.append(user_profile[i])
for i in range(len(item_profile)):
item_profile_list.append(item_profile[i])
profiles = user_profile_list + item_profile_list
batch_size = 128
n_batchs = math.ceil(len(profiles) / batch_size)
text_emb = []
for i in tqdm(range(n_batchs), desc=f'diverse_{_dataset}_{diverse_no}'):
start = i * batch_size
end = (i + 1) * batch_size
batch_profile = profiles[start: end]
inputs = tokenizer(batch_profile, padding=True, truncation=True, max_length=512, return_tensors="pt")
for tem in inputs:
inputs[tem] = inputs[tem].cuda()
with torch.inference_mode():
embeddings = model.encode(input_ids=inputs.input_ids, attention_mask=inputs.attention_mask)
embeddings = F.normalize(embeddings.pooler_output.detach().float(), dim=-1)
text_emb.append(embeddings.cpu())
text_emb = torch.concat(text_emb, dim=0)
user_emb = text_emb[: len(user_profile)].numpy()
item_emb = text_emb[len(user_profile): ].numpy()
if save:
with open(f'{save_path}/diverse_profile/user_{model_name_or_path.split("/")[-1]}_{diverse_no}.pkl', 'wb') as f:
pickle.dump(user_emb, f)
with open(f'{save_path}/diverse_profile/item_{model_name_or_path.split("/")[-1]}_{diverse_no}.pkl', 'wb') as f:
pickle.dump(item_emb, f)