File size: 20,355 Bytes
b6beed8 | 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 | import json
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from torch import Tensor
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
from sentence_transformers import SentenceTransformer, util
from utils.constants import *
from utils.api_utils import embedding_generate
from table2tree.feature_tree import *
def average_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
"""Average masked pooling: average token vectors into one vector per sample."""
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
def get_detailed_instruct(task_description: str, query: str) -> str:
return f"Instruct: {task_description}\nQuery: {query}"
def find_topk_indices(lst, k):
import heapq
topk_with_indices = heapq.nlargest(k, enumerate(lst), key=lambda x: x[1])
indices = [index for index, value in topk_with_indices]
return indices
class EmbeddingModel:
"""Embedding cannot be preprocessed because a task must be specified."""
_instance = None # Class variable used to store the singleton instance
def __init__(self):
if EMBEDDING_TYPE == 'local':
self.model_path = EMBEDDING_MODE_PATH
self.model = SentenceTransformer(EMBEDDING_MODE_PATH)
else:
self.similarity = util.cos_sim
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
# TODO
def get_entity_embedding(self, entity_list):
entity_list = ["#" if str(x).strip() == '' else x for x in entity_list]
if EMBEDDING_TYPE == 'local':
embeddings = self.model.encode(entity_list)
else:
embeddings = embedding_generate(input_texts=entity_list)
return embeddings
def get_embedding_dict(self, entity_list):
embeddings = self.get_entity_embedding(entity_list)
embedding_dict = {
str(entity): embedding.tolist()
for entity, embedding in zip(entity_list, embeddings)
}
return embedding_dict
def save_embedding_dict(self, embedding_dict, output_file):
with open(output_file, "w") as f:
json.dump(embedding_dict, f, ensure_ascii=False)
def load_embedding_dict(self, input_file):
# Load from a JSON file
with open(input_file, "r") as f:
loaded_embedding_dict = json.load(f)
# Convert lists back to NumPy arrays
loaded_embedding_dict = {
k: np.array(v) for k, v in loaded_embedding_dict.items()
}
return loaded_embedding_dict
def split_embedding_dict(self, embedding_dict):
values = []
embeddings = []
for (
k,
v,
) in embedding_dict.items():
values.append(k)
embeddings.append(v.tolist())
return values, embeddings
def one_to_many_semilarity(self, value, value_list=None, embedding_cache_file=None):
"""One of value_list or embedding_cache_file must be specified"""
if embedding_cache_file is None: # without cache
input_texts = [value] + value_list
input_texts = [str(s) for s in input_texts]
embeddings = self.get_entity_embedding(input_texts)
scores = (embeddings[:1] @ embeddings[1:].T) * 100
scores = scores.tolist()
else:
embedding_dict = self.load_embedding_dict(embedding_cache_file)
value_list, embedding_list = self.split_embedding_dict(embedding_dict)
value_embedding = self.get_entity_embedding([value]).astype(np.float64)
if EMBEDDING_TYPE == 'local':
scores = self.model.similarity(value_embedding, embedding_list)
else:
scores = self.similarity(value_embedding, embedding_list)
scores = scores.tolist()
return scores
def topk_match(
self,
entities: list,
table: list = None,
k=10,
embedding_cache_file=None,
):
"""One of table or embedding_cache_file must be specified"""
if embedding_cache_file is None: # without cache
if table is None or len(table) == 0:
return [[x] for x in entities]
input_texts = entities + table
input_texts = [str(s) for s in input_texts]
embeddings = self.get_entity_embedding(input_texts)
scores = (embeddings[: len(entities)] @ embeddings[len(entities) :].T) * 100
scores = scores.tolist()
if not isinstance(scores, list): scores = [[scores]]
# Find Max Top-k Values
values = []
for index, score_lst in enumerate(scores):
indices = find_topk_indices(score_lst, k)
values.append([table[i] for i in indices])
else:
embedding_dict = self.load_embedding_dict(embedding_cache_file)
value_list, embedding_list = self.split_embedding_dict(embedding_dict)
value_embedding = self.get_entity_embedding(entities)
# Find Max Top-k Values
if EMBEDDING_TYPE == 'local':
scores = self.model.similarity(value_embedding.tolist(), embedding_list)
else:
scores = self.similarity(value_embedding.tolist(), embedding_list)
scores = scores.tolist()
if not isinstance(scores, list): scores = [[scores]]
values = []
for index, score_lst in enumerate(scores):
indices = find_topk_indices(score_lst, k)
values.append([value_list[i] for i in indices])
return values
def top1_match(self, entities: list, table: list = None, embedding_cache_file=None):
"""One of table or file must be specified"""
return flatten_nested_list(
self.topk_match(entities=entities, table=table, k=1, embedding_cache_file=embedding_cache_file)
)
# def one_to_many_semilarity(
# self,
# value,
# value_list,
# task="Given an sentence, retrieve relevant sentences that relevant to the sentence.",
# ):
# value = get_detailed_instruct(task, value)
# input_texts = [value] + value_list
# input_texts = [str(s) for s in input_texts]
# # Tokenize the input texts
# batch_dict = self.tokenizer(
# input_texts,
# max_length=512,
# padding=True,
# truncation=True,
# return_tensors="pt",
# )
# outputs = self.model(**batch_dict)
# embeddings = average_pool(
# outputs.last_hidden_state, batch_dict["attention_mask"]
# )
# # normalize embeddings
# embeddings = F.normalize(embeddings, p=2, dim=1)
# scores = (embeddings[:1] @ embeddings[1:].T) * 100
# scores = scores.tolist()
# return scores
# def topk_match(
# self,
# entities: list,
# table: list,
# k=10,
# task="Given an entity, retrieve relevant values that relevant to the entity.",
# log_file=None,
# ):
# entities = [get_detailed_instruct(task, query) for query in entities]
# input_texts = entities + table
# input_texts = [str(s) for s in input_texts]
# # Tokenize the input texts
# batch_dict = self.tokenizer(
# input_texts,
# max_length=512,
# padding=True,
# truncation=True,
# return_tensors="pt",
# )
# outputs = self.model(**batch_dict)
# embeddings = average_pool(
# outputs.last_hidden_state, batch_dict["attention_mask"]
# )
# # normalize embeddings
# embeddings = F.normalize(embeddings, p=2, dim=1)
# scores = (embeddings[: len(entities)] @ embeddings[len(entities) :].T) * 100
# scores = scores.tolist()
# # Find Max Top-k Values
# values = []
# for index, score_lst in enumerate(scores):
# indices = find_topk_indices(score_lst, k)
# values.append([table[i] for i in indices])
# if log_file is not None: # Log
# with open(log_file, "a") as file:
# file.write(f"{DELIMITER} Top-{k} Match Result {DELIMITER}\n")
# for i, (entity, values) in enumerate(zip(entities, values)):
# file.write(f"Entity: {entity}\n")
# file.write(f"Values: {values}\n")
# return values
# def top1_match(
# self,
# entities: list,
# table: list,
# task="Given an string, retrieve most relevant value that relevant to the entity.",
# ):
# return flatten_nested_list(
# self.topk_match(entities=entities, table=table, k=1, task=task)
# )
def calculate_topk_similarity(query_vectors, target_vectors, topk=6):
"""
Compute similarities between two embedding vector lists and return the Top-K most relevant results.
Args:
query_vectors (np.ndarray): Query vectors to match, shaped (n, embedding_dim).
target_vectors (np.ndarray): Target vectors to be matched, shaped (m, embedding_dim).
topk (int): Number of Top-K relevant results to return.
Returns:
topk_indices (list): Indices of the Top-K most relevant items, shaped (n, topk).
topk_scores (list): Similarity scores of the Top-K most relevant items, shaped (n, topk).
"""
# Compute the cosine similarity matrix
similarity_matrix = cosine_similarity(query_vectors, target_vectors) # shape (n, m)
# Get the Top-K indices and scores
topk_indices = np.argsort(similarity_matrix, axis=1)[:, -topk:][
:, ::-1
] # shape (n, topk)
topk_scores = np.take_along_axis(
similarity_matrix, topk_indices, axis=1
) # shape (n, topk)
return topk_indices.tolist(), topk_scores.tolist()
# class EmbeddingModelAllMiniLML6V2:
# _instance = None # Class variable used to store the singleton instance
# def __init__(self, model_path=ALLMINILM_MODEL_PATH):
# self.model_path = model_path
# self.model = SentenceTransformer(model_path)
# def __new__(cls, *args, **kwargs):
# if not cls._instance:
# cls._instance = super().__new__(cls)
# return cls._instance
# def get_entity_embedding(self, entity_list):
# embeddings = self.model.encode(entity_list)
# return embeddings
# def get_embedding_dict(self, entity_list):
# embeddings = self.get_entity_embedding(entity_list)
# embedding_dict = {
# str(entity): embedding.tolist()
# for entity, embedding in zip(entity_list, embeddings)
# }
# return embedding_dict
# def save_embedding_dict(self, embedding_dict, output_file):
# with open(output_file, "w") as f:
# json.dump(embedding_dict, f, ensure_ascii=False)
# def load_embedding_dict(self, input_file):
# # Load from a JSON file
# with open(input_file, "r") as f:
# loaded_embedding_dict = json.load(f)
# # Convert lists back to NumPy arrays
# loaded_embedding_dict = {
# k: np.array(v) for k, v in loaded_embedding_dict.items()
# }
# return loaded_embedding_dict
# def split_embedding_dict(self, embedding_dict):
# values = []
# embeddings = []
# for (
# k,
# v,
# ) in embedding_dict.items():
# values.append(k)
# embeddings.append(v.tolist())
# return values, embeddings
# def one_to_many_semilarity(self, value, value_list=None, embedding_cache_file=None):
# """One of value_list or embedding_cache_file must be specified"""
# if embedding_cache_file is None: # without cache
# input_texts = [value] + value_list
# input_texts = [str(s) for s in input_texts]
# embeddings = self.get_entity_embedding(input_texts)
# scores = (embeddings[:1] @ embeddings[1:].T) * 100
# scores = scores.tolist()
# else:
# embedding_dict = self.load_embedding_dict(embedding_cache_file)
# value_list, embedding_list = self.split_embedding_dict(embedding_dict)
# value_embedding = self.get_entity_embedding([value]).astype(np.float64)
# scores = self.model.similarity(
# value_embedding, embedding_dict
# )
# scores = scores.tolist()
# return scores
# def topk_match(
# self,
# entities: list,
# table: list = None,
# k=10,
# threshold=None,
# embedding_cache_file=None,
# log_file=None,
# ):
# """One of table or embedding_cache_file must be specified"""
# if embedding_cache_file is None: # without cache
# input_texts = entities + table
# input_texts = [str(s) for s in input_texts]
# embeddings = self.get_entity_embedding(input_texts)
# scores = (embeddings[: len(entities)] @ embeddings[len(entities) :].T) * 100
# scores = scores.tolist()
# if not isinstance(scores, list): scores = [[scores]]
# # Find Max Top-k Values
# values = []
# for index, score_lst in enumerate(scores):
# indices = find_topk_indices(score_lst, k)
# values.append([table[i] for i in indices])
# else:
# embedding_dict = self.load_embedding_dict(embedding_cache_file)
# value_list, embedding_list = self.split_embedding_dict(embedding_dict)
# value_embedding = self.get_entity_embedding(entities)
# # Find Max Top-k Values
# scores = self.model.similarity(
# value_embedding.tolist(), embedding_list
# )
# scores = scores.tolist()
# if not isinstance(scores, list): scores = [[scores]]
# values = []
# for index, score_lst in enumerate(scores):
# indices = find_topk_indices(score_lst, k)
# values.append([value_list[i] for i in indices])
# if log_file is not None: # Log
# with open(log_file, "a") as file:
# file.write(f"{DELIMITER} Top-{k} Match Result {DELIMITER}\n")
# for i, (entity, values) in enumerate(zip(entities, values)):
# file.write(f"Entity: {entity}\n")
# file.write(f"Values: {values}\n")
# return values
# def top1_match(self, entities: list, table: list = None, embedding_cache_file=None, threshold=None):
# """One of table or file must be specified"""
# return flatten_nested_list(
# self.topk_match(entities=entities, table=table, k=1, embedding_cache_file=embedding_cache_file, threshold=threshold)
# )
def match_sub_table(entities: list, f_tree): #: FeatureTree):
"""Use embedding vectors to extract a subtree from FeatureTree and return JSON."""
model = EmbeddingModel()
values = model.topk_match(entities, f_tree.body_value_list())
return values
def flatten_nested_list(value):
res = []
for x in value:
if isinstance(x, list):
res.extend(flatten_nested_list(x))
else:
res.append(x)
return res
def get_sub_json(values: list, json_dict: dict):
values = list(set(flatten_nested_list(values)))
def dfs(values: list, j_dict: dict):
return_dict = {}
for key, value in j_dict.items():
if isinstance(value, list):
tmp_list = []
for x in value:
if isinstance(x, dict):
x = dfs(values, x)
if len(x) > 0:
tmp_list.append(x)
else:
if x in values:
tmp_list.append(x)
if len(tmp_list) > 0:
return_dict[key] = tmp_list
elif isinstance(value, dict):
value = dfs(values, value)
if len(value) > 0:
return_dict[key] = value
else:
if value in values or key in values:
return_dict[key] = value
return return_dict
return dfs(values, json_dict)
def demo():
# Each query must come with a one-sentence instruction that describes the task
task = "Given a web search query, retrieve relevant passages that answer the query"
queries = [
get_detailed_instruct(task, "how much protein should a female eat"),
get_detailed_instruct(task, "Homestyle pumpkin recipes"),
]
# No need to add instruction for retrieval documents
documents = [
"As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"1. Stir-fried shredded pumpkin. Ingredients: half a tender pumpkin. Seasonings: scallion, salt, sugar, chicken bouillon. Steps: 1. Peel the pumpkin thinly and scoop out the pulp. 2. Shred it finely. 3. Heat oil in a wok and stir-fry scallions until fragrant. 4. Add the shredded pumpkin and stir-fry briefly, then season and serve. 2. Pumpkin with scallions. Ingredients: 1 pumpkin. Seasonings: scallions, minced garlic, olive oil, salt. Steps: 1. Peel and slice the pumpkin. 2. Heat oil and saute the garlic. 3. Add the pumpkin slices and stir-fry. 4. Add a little water as needed. 5. Add salt and stir evenly. 6. Once the pumpkin is soft, turn off the heat. 7. Sprinkle scallions and serve.",
]
input_texts = queries + documents
tokenizer = AutoTokenizer.from_pretrained("intfloat/multilingual-e5-large-instruct")
model = AutoModel.from_pretrained("intfloat/multilingual-e5-large-instruct")
# Tokenize the input texts
batch_dict = tokenizer(
input_texts, max_length=512, padding=True, truncation=True, return_tensors="pt"
)
outputs = model(**batch_dict)
embeddings = average_pool(outputs.last_hidden_state, batch_dict["attention_mask"])
# normalize embeddings
embeddings = F.normalize(embeddings, p=2, dim=1)
scores = (embeddings[:2] @ embeddings[2:].T) * 100
print(scores.tolist())
# => [[91.92852783203125, 67.580322265625], [70.3814468383789, 92.1330795288086]]
def main():
model = EmbeddingModel()
res = model.one_to_many_semilarity(
"How many people are funded by public finance?",
[
"How many second-tier subordinate units does the Zhanjiang Human Resources and Social Security Bureau have?",
"How many second-tier subordinate units does this department have?",
"How many subordinate institutions does the Zhanjiang Human Resources and Social Security Bureau have?",
"What is the total number of second-tier units under this department?",
],
)
print(res)
def main2():
model = EmbeddingModel()
res = model.topk_match(
entities=["Overall Budget Situation", "Urban and Rural Resident Pension"],
embedding_cache_file="/Users/tangzirui/Desktop/SJTU-DB/TaQA/dataset_json/sstqa/table/1.embedding.json",
k=3,
)
print(res)
with open(
"/Users/tangzirui/Desktop/SJTU-DB/TaQA/dataset_json/sstqa/table/1_embedding.json",
"r",
) as f:
data: dict = json.load(f)
res = model.topk_match(
entities=["Overall Budget Situation", "Urban and Rural Resident Pension"], table=list(data.keys()), k=3
)
print(res)
def main3():
model = EmbeddingModel()
res = model.top1_match(["1", "2"], ["1", "2", "3", "4"])
print(res)
if __name__ == "__main__":
# main()
# main2()
main3() |