STEncoder class for encoding queries using SentenceTransformers. Attributes: model_name (str): The name of the model. model_path (str): The path to the model. max_length (int): The maximum length of the input sequences. use_fp16 (bool): Whether to use FP16 p
| 81 | |
| 82 | |
| 83 | class STEncoder: |
| 84 | """ |
| 85 | STEncoder class for encoding queries using SentenceTransformers. |
| 86 | |
| 87 | Attributes: |
| 88 | model_name (str): The name of the model. |
| 89 | model_path (str): The path to the model. |
| 90 | max_length (int): The maximum length of the input sequences. |
| 91 | use_fp16 (bool): Whether to use FP16 precision. |
| 92 | instruction (str): Additional instructions for parsing queries. |
| 93 | |
| 94 | Methods: |
| 95 | encode(query_list: List[str], batch_size=64, is_query=True) -> np.ndarray: |
| 96 | Encodes a list of queries into embeddings. |
| 97 | multi_gpu_encode(query_list: List[str], is_query=True, batch_size=None) -> np.ndarray: |
| 98 | Encodes a list of queries into embeddings using multiple GPUs. |
| 99 | """ |
| 100 | |
| 101 | def __init__(self, model_name, model_path, max_length, use_fp16, instruction): |
| 102 | import torch |
| 103 | from sentence_transformers import SentenceTransformer |
| 104 | |
| 105 | self.model_name = model_name |
| 106 | self.model_path = model_path |
| 107 | self.max_length = max_length |
| 108 | self.use_fp16 = use_fp16 |
| 109 | self.instruction = instruction |
| 110 | self.model = SentenceTransformer( |
| 111 | model_path, trust_remote_code=True, model_kwargs={"torch_dtype": torch.float16 if use_fp16 else torch.float} |
| 112 | ) |
| 113 | |
| 114 | @torch.inference_mode() |
| 115 | def encode(self, query_list: Union[List[str], str], batch_size=64, is_query=True) -> np.ndarray: |
| 116 | query_list = parse_query(self.model_name, query_list, self.instruction, is_query) |
| 117 | query_emb = self.model.encode( |
| 118 | query_list, batch_size=batch_size, convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=True |
| 119 | ) |
| 120 | query_emb = query_emb.astype(np.float32, order="C") |
| 121 | |
| 122 | return query_emb |
| 123 | |
| 124 | @torch.inference_mode() |
| 125 | def multi_gpu_encode(self, query_list: Union[List[str], str], batch_size=None, is_query=True) -> np.ndarray: |
| 126 | query_list = parse_query(self.model_name, query_list, self.instruction, is_query) |
| 127 | pool = self.model.start_multi_process_pool() |
| 128 | query_emb = self.model.encode_multi_process( |
| 129 | query_list, |
| 130 | pool, |
| 131 | convert_to_numpy=True, |
| 132 | normalize_embeddings=True, |
| 133 | batch_size=batch_size, |
| 134 | show_progress_bar=True, |
| 135 | ) |
| 136 | self.model.stop_multi_process_pool(pool) |
| 137 | query_emb = query_emb.astype(np.float32, order="C") |
| 138 | |
| 139 | return query_emb |
| 140 |
no outgoing calls
no test coverage detected