File size: 4,598 Bytes
811e03d |
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 |
import os
import collections
import json
import logging
import argparse
import numpy as np
import pandas as pd
import torch
from time import time
from torch import optim
from tqdm import tqdm
from torch.utils.data import DataLoader
from rq_llama import *
from index.datasets import EmbDataset
def if_collided(all_indices_str):
tot_item = len(all_indices_str)
tot_indice = len(set(all_indices_str.tolist()))
return tot_item == tot_indice
def get_indices_count(all_indices_str):
indices_count = collections.defaultdict(int)
for index in all_indices_str:
indices_count[index] += 1
return indices_count
def get_collision_item(all_indices_str):
index2id = {}
for i, index in enumerate(all_indices_str):
if index not in index2id:
index2id[index] = []
index2id[index].append(i)
collision_item_groups = []
for index in index2id:
if len(index2id[index]) > 1:
collision_item_groups.append(index2id[index])
return collision_item_groups
def parse_args():
parser = argparse.ArgumentParser(description = "Index")
parser.add_argument("--ckpt_path", type = str, default = "", help = "")
parser.add_argument("--data_path", type = str, default = "", help = "")
parser.add_argument("--save_path", type = str, default = "", help = "")
parser.add_argument("--device_map", type = str, default = "1", help = "gpu or cpu")
return parser.parse_args()
args = parse_args()
print(args)
data = EmbDataset(args.data_path)
data_loader = DataLoader(data, num_workers = 4, batch_size = 64, shuffle = False, pin_memory = True)
device_map = {'': int(args.device_map)}
MODEL = LlamaWithRQ.from_pretrained(args.ckpt_path, torch_dtype = torch.float16, low_cpu_mem_usage = True, device_map = device_map)
MODEL.eval()
device = MODEL.device
rqvae = MODEL.rqvae
prefix = MODEL.prefix
postfix = '<p-{}>'
index_table = {}
all_indices = []
all_indices_str = []
with torch.no_grad():
for x in tqdm(data_loader):
indices = rqvae.get_indices(x.to(device), False)
indices = indices.view(-1, indices.shape[-1]).cpu().numpy()
for index in indices:
code = []
for i, ind in enumerate(index):
code.append(prefix[i].format(int(ind)))
if str(code) in index_table:
index_table[str(code)] += 1
else:
index_table[str(code)] = 0
code.append(postfix.format(index_table[str(code)]))
all_indices.append(code)
all_indices_str.append(str(code))
all_indices = np.array(all_indices)
all_indices_str = np.array(all_indices_str)
for vq in rqvae.rq.vq_layers[:-1]:
vq.sk_epsilon=0.0
if rqvae.rq.vq_layers[-1].sk_epsilon == 0.0:
rqvae.rq.vq_layers[-1].sk_epsilon = 0.003
'''
tt = 0
while True:
if tt >= 20 or if_collided(all_indices_str):
break
collision_item_groups = get_collision_item(all_indices_str)
# print(collision_item_groups)
print(len(collision_item_groups))
with torch.no_grad():
for collision_items in collision_item_groups:
indices = rqvae.get_indices(data[collision_items].to(device), True)
indices = indices.view(-1, indices.shape[-1]).cpu().numpy()
for item, index in zip(collision_items, indices):
code = []
for i, ind in enumerate(index):
code.append(prefix[i].format(int(ind)))
all_indices[item] = code
all_indices_str[item] = str(code)
tt += 1
'''
print("All indices number: ", len(all_indices))
print("Max number of conflicts: ", max(get_indices_count(all_indices_str).values()))
print('Re-index number:', max(index_table.values()))
# tot_item = len(all_indices_str)
# tot_indice = len(set(all_indices_str.tolist()))
# print("Collision Rate", (tot_item - tot_indice) / tot_item)
all_indices_dict = {}
for item, indices in enumerate(all_indices.tolist()):
all_indices_dict[item] = list(indices)
reindex_dict = {'reindex': max(index_table.values())}
json_path = os.path.join(args.save_path,'indices.json')
with open(json_path, 'w',encoding = 'utf-8') as f:
json.dump(all_indices_dict, f)
reindex_path = os.path.join(args.save_path,'reindex.json')
with open(reindex_path, 'w',encoding = 'utf-8') as f:
json.dump(reindex_dict, f)
# with open(args.save_path, 'w',encoding = 'utf-8') as f:
# json.dump(all_indices_dict, f) |