MCPcopy Create free account
hub / github.com/Agent-RL/ReCall / STEncoder

Class STEncoder

src/flashrag/retriever/encoder.py:86–142  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

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

Callers 2

build_dense_indexMethod · 0.90
load_modelMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected