python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import torch
import numpy as np
from abc import ABC, abstractmethod
from transformers import AutoModel, AutoTokenizer
from typing import Union, Sequence, Optional
class TorchModel(ABC):
def __init__(
self,
model_name: str,
model_path: str,
device: Union[str, torch.device, int] = "cpu",
trust_remote_code: bool = True,
):
self.model_name = model_name
self.model_path = model_path
self.device = self.validate_device(device)
self.trust_remote_code = trust_remote_code
self._model = None
@property
def model(self):
if self._model is None:
self.build_model()
return self._model
@model.setter
def model(self, new_model):
self._model = new_model
@abstractmethod
def build_model(self):
"""构建模型的抽象方法"""
pass
def del_model(self):
"""删除模型并释放内存"""
if self._model is not None:
del self._model
self._model = None
torch.cuda.empty_cache()
@staticmethod
def validate_device(device: Union[str, torch.device, int]) -> torch.device:
if isinstance(device, str):
device = device.lower()
if device == "cpu":
return torch.device("cpu")
if device == "auto":
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
return torch.device(device)
elif isinstance(device, int):
return torch.device(f"cuda:{device}" if torch.cuda.is_available() else "cpu")
elif isinstance(device, torch.device):
return device
else:
raise ValueError(f"Unsupported device type: {type(device)}")
class EmbedModel(TorchModel):
def __init__(
self,
model_name: str,
model_path: str,
tokenizer_path: Optional[str] = None,
**kwargs
):
super().__init__(model_name, model_path, **kwargs)
self.tokenizer_path = tokenizer_path or model_path
self.tokenizer = None
def build_model(self):
"""加载模型和分词器,并移动到指定设备"""
self._model = AutoModel.from_pretrained(
self.model_path, trust_remote_code=self.trust_remote_code
).to(self.device)
self._model.eval() # 设置为评估模式以提升性能
self.tokenizer = AutoTokenizer.from_pretrained(
self.tokenizer_path, trust_remote_code=self.trust_remote_code
)
def generate_embed(self, input_text: Union[Sequence[str], str], **kwargs) -> np.ndarray:
"""生成单批次的嵌入向量"""
if isinstance(input_text, str):
input_text = [input_text]
with torch.no_grad():
encoded_inputs = self.tokenizer(
input_text,
padding=True,
truncation=True,
return_tensors='pt',
**kwargs
).to(self.device)
outputs = self.model(**encoded_inputs)
# 假设使用最后一层的平均池化作为嵌入
embeddings = outputs.last_hidden_state.mean(dim=1).cpu().numpy()
return embeddings
def generate_embed_batch(
self,
input_texts: Sequence[str],
batch_size: int = 1024,
truncate_dim: Optional[int] = None,
**kwargs,
) -> np.ndarray:
"""批量生成嵌入向量,避免在循环中多次拼接数组"""
embeddings_list = []
num_samples = len(input_texts)
for start_idx in range(0, num_samples, batch_size):
batch = input_texts[start_idx:start_idx + batch_size]
batch_embeddings = self.generate_embed(batch, **kwargs)
embeddings_list.append(batch_embeddings)
embeddings = np.vstack(embeddings_list)
if truncate_dim is not None:
if truncate_dim < embeddings.shape[1]:
embeddings = embeddings[:, :truncate_dim]
else:
raise ValueError(f"truncate_dim {truncate_dim} is larger than embedding dimension {embeddings.shape[1]}.")
return embeddings
python
if __name__ == "__main__":
model_name = "example-model"
model_path = "path/to/model"
embedder = EmbedModel(model_name=model_name, model_path=model_path, device="cuda:0")
texts = ["Hello world!", "Optimizing code is important.", "Transformers are powerful."] * 1000 # 示例文本
embeddings = embedder.generate_embed_batch(texts, batch_size=128, truncate_dim=768)
print(embeddings.shape) # 应输出 (3000, 768) 如果 truncate_dim=768