colbert.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import os
  2. import logging
  3. import torch
  4. import numpy as np
  5. from colbert.infra import ColBERTConfig
  6. from colbert.modeling.checkpoint import Checkpoint
  7. from open_webui.env import SRC_LOG_LEVELS
  8. log = logging.getLogger(__name__)
  9. log.setLevel(SRC_LOG_LEVELS["RAG"])
  10. class ColBERT:
  11. def __init__(self, name, **kwargs) -> None:
  12. log.info("ColBERT: Loading model", name)
  13. self.device = "cuda" if torch.cuda.is_available() else "cpu"
  14. DOCKER = kwargs.get("env") == "docker"
  15. if DOCKER:
  16. # This is a workaround for the issue with the docker container
  17. # where the torch extension is not loaded properly
  18. # and the following error is thrown:
  19. # /root/.cache/torch_extensions/py311_cpu/segmented_maxsim_cpp/segmented_maxsim_cpp.so: cannot open shared object file: No such file or directory
  20. lock_file = (
  21. "/root/.cache/torch_extensions/py311_cpu/segmented_maxsim_cpp/lock"
  22. )
  23. if os.path.exists(lock_file):
  24. os.remove(lock_file)
  25. self.ckpt = Checkpoint(
  26. name,
  27. colbert_config=ColBERTConfig(model_name=name),
  28. ).to(self.device)
  29. pass
  30. def calculate_similarity_scores(self, query_embeddings, document_embeddings):
  31. query_embeddings = query_embeddings.to(self.device)
  32. document_embeddings = document_embeddings.to(self.device)
  33. # Validate dimensions to ensure compatibility
  34. if query_embeddings.dim() != 3:
  35. raise ValueError(
  36. f"Expected query embeddings to have 3 dimensions, but got {query_embeddings.dim()}."
  37. )
  38. if document_embeddings.dim() != 3:
  39. raise ValueError(
  40. f"Expected document embeddings to have 3 dimensions, but got {document_embeddings.dim()}."
  41. )
  42. if query_embeddings.size(0) not in [1, document_embeddings.size(0)]:
  43. raise ValueError(
  44. "There should be either one query or queries equal to the number of documents."
  45. )
  46. # Transpose the query embeddings to align for matrix multiplication
  47. transposed_query_embeddings = query_embeddings.permute(0, 2, 1)
  48. # Compute similarity scores using batch matrix multiplication
  49. computed_scores = torch.matmul(document_embeddings, transposed_query_embeddings)
  50. # Apply max pooling to extract the highest semantic similarity across each document's sequence
  51. maximum_scores = torch.max(computed_scores, dim=1).values
  52. # Sum up the maximum scores across features to get the overall document relevance scores
  53. final_scores = maximum_scores.sum(dim=1)
  54. normalized_scores = torch.softmax(final_scores, dim=0)
  55. return normalized_scores.detach().cpu().numpy().astype(np.float32)
  56. def predict(self, sentences):
  57. query = sentences[0][0]
  58. docs = [i[1] for i in sentences]
  59. # Embedding the documents
  60. embedded_docs = self.ckpt.docFromText(docs, bsize=32)[0]
  61. # Embedding the queries
  62. embedded_queries = self.ckpt.queryFromText([query], bsize=32)
  63. embedded_query = embedded_queries[0]
  64. # Calculate retrieval scores for the query against all documents
  65. scores = self.calculate_similarity_scores(
  66. embedded_query.unsqueeze(0), embedded_docs
  67. )
  68. return scores