1. 思考优化 2. 设计UMl 3. 反思设计 4、输出优化代码 #!/usr/bin/env python -- coding: utf-8 -- import torch…
- User
- 思考优化
- 设计UMl
- 反思设计 4、输出优化代码
#!/usr/bin/env python
-- coding: utf-8 --
import torch import numpy as np from abc import ABC, abstractmethod from transformers import AutoModel from typing import Union, Sequence
class TorchModel(ABC): def init( self, model_name: str, model_path: str, device: Union[str, torch.device] = "cpu", trust_remote_code: bool = True, ): self.model_name = model_name self.model_path = model_path self.device = TorchModel.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() # 可选:释放GPU缓存 @staticmethod def validate_device(device: Union[str, torch.device, int]) -> torch.device: if isinstance(device, str): if device == "cpu": return torch.device("cpu") if device == "auto": device = "cuda" if torch.cuda.is_available() else "cpu" return torch.device(device) return deviceclass EmbedModel(TorchModel): def build_model(self): self.model = AutoModel.from_pretrained( self.model_path, trust_remote_code=self.trust_remote_code ) self.model = self.model.to(self.device) return self.model
def generate_embed(self, input_text: Union[Sequence[str], np.ndarray], **kwargs): return self.model.encode(input_text, **kwargs) def generate_embed_batch( self, input_text: Union[Sequence[str], np.ndarray], batch_size: int = 1024, truncate_dim: int = 32, **kwargs, ): out_array = np.empty((0, truncate_dim)) for i in range(0, len(input_text), batch_size): batch = input_text[i : i + batch_size] embeddings = self.generate_embed(batch, truncate_dim=truncate_dim, **kwargs) out_array = np.concatenate((out_array, embeddings), axis=0) return out_array - Assistant