model.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # coding=utf-8
  2. """
  3. @project: MaxKB
  4. @Author:虎虎
  5. @file: model.py
  6. @date:2025/11/5 15:30
  7. @desc:
  8. """
  9. from typing import Sequence, Optional, Dict, Any
  10. from langchain_core.callbacks import Callbacks
  11. from langchain_core.documents import Document, BaseDocumentCompressor
  12. from models_provider.base_model_provider import MaxKBBaseModel
  13. class LocalReranker(MaxKBBaseModel, BaseDocumentCompressor):
  14. client: Any = None
  15. tokenizer: Any = None
  16. model: Optional[str] = None
  17. cache_dir: Optional[str] = None
  18. model_kwargs: Any = {}
  19. def __init__(self, model_name, cache_dir=None, **model_kwargs):
  20. super().__init__()
  21. from transformers import AutoModelForSequenceClassification, AutoTokenizer
  22. self.model = model_name
  23. self.cache_dir = cache_dir
  24. self.model_kwargs = model_kwargs
  25. self.client = AutoModelForSequenceClassification.from_pretrained(self.model, cache_dir=self.cache_dir)
  26. self.tokenizer = AutoTokenizer.from_pretrained(self.model, cache_dir=self.cache_dir)
  27. self.client = self.client.to(self.model_kwargs.get('device', 'cpu'))
  28. self.client.eval()
  29. @staticmethod
  30. def is_cache_model():
  31. return False
  32. @staticmethod
  33. def new_instance(model_type, model_name, model_credential: Dict[str, object], **model_kwargs):
  34. return LocalReranker(model_name, cache_dir=model_credential.get('cache_dir'))
  35. def compress_documents(self, documents: Sequence[Document], query: str, callbacks: Optional[Callbacks] = None) -> \
  36. Sequence[Document]:
  37. if documents is None or len(documents) == 0:
  38. return []
  39. import torch
  40. with torch.no_grad():
  41. inputs = self.tokenizer([[query, document.page_content] for document in documents], padding=True,
  42. truncation=True, return_tensors='pt', max_length=512)
  43. scores = [torch.sigmoid(s).float().item() for s in
  44. self.client(**inputs, return_dict=True).logits.view(-1, ).float()]
  45. result = [Document(page_content=documents[index].page_content, metadata={'relevance_score': scores[index]})
  46. for index
  47. in range(len(documents))]
  48. result.sort(key=lambda row: row.metadata.get('relevance_score'), reverse=True)
  49. return result