File size: 11,335 Bytes
0d77bb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f48fed
 
0d77bb1
 
 
335e8a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import os
from typing import Optional

import safetensors
import safetensors.torch
import torch
import torch.nn.functional as F
import weave
from transformers import (
    AutoModel,
    AutoTokenizer,
    BertPreTrainedModel,
    PreTrainedTokenizerFast,
)

from ..utils import get_torch_backend, get_wandb_artifact
from .common import SimilarityMetric, argsort_scores, save_vector_index


class MedCPTRetriever(weave.Model):
    """
    A class to retrieve relevant text chunks using MedCPT models.

    This class provides methods to index a dataset of text chunks and retrieve the most relevant
    chunks for a given query using MedCPT models. It uses separate models for encoding queries
    and articles, and supports both cosine similarity and Euclidean distance as similarity metrics.

    Args:
        query_encoder_model_name (str): The name of the model used for encoding queries.
        article_encoder_model_name (str): The name of the model used for encoding articles.
        chunk_size (Optional[int]): The maximum length of text chunks.
        vector_index (Optional[torch.Tensor]): The vector index of encoded text chunks.
        chunk_dataset (Optional[list[dict]]): The dataset of text chunks.
    """

    query_encoder_model_name: str
    article_encoder_model_name: str
    chunk_size: Optional[int]
    _chunk_dataset: Optional[list[dict]]
    _query_tokenizer: PreTrainedTokenizerFast
    _article_tokenizer: PreTrainedTokenizerFast
    _query_encoder_model: BertPreTrainedModel
    _article_encoder_model: BertPreTrainedModel
    _vector_index: Optional[torch.Tensor]

    def __init__(
        self,
        query_encoder_model_name: str,
        article_encoder_model_name: str,
        chunk_size: Optional[int] = None,
        vector_index: Optional[torch.Tensor] = None,
        chunk_dataset: Optional[list[dict]] = None,
    ):
        super().__init__(
            query_encoder_model_name=query_encoder_model_name,
            article_encoder_model_name=article_encoder_model_name,
            chunk_size=chunk_size,
        )
        self._query_tokenizer = AutoTokenizer.from_pretrained(
            self.query_encoder_model_name
        )
        self._article_tokenizer = AutoTokenizer.from_pretrained(
            self.article_encoder_model_name
        )
        self._query_encoder_model = AutoModel.from_pretrained(
            self.query_encoder_model_name
        )
        self._article_encoder_model = AutoModel.from_pretrained(
            self.article_encoder_model_name
        )
        self._chunk_dataset = chunk_dataset
        self._vector_index = vector_index

    def index(self, chunk_dataset_name: str, index_name: Optional[str] = None):
        """
        Indexes a dataset of text chunks and optionally saves the vector index.

        This method retrieves a dataset of text chunks from a Weave reference, encodes the text
        chunks using the article encoder model, and stores the resulting vector index. If an
        index name is provided, the vector index is saved to a file using the `save_vector_index`
        function.

        !!! example "Example Usage"
            ```python
            import weave
            from dotenv import load_dotenv

            import wandb
            from medrag_multi_modal.retrieval import MedCPTRetriever

            load_dotenv()
            weave.init(project_name="ml-colabs/medrag-multi-modal")
            wandb.init(project="medrag-multi-modal", entity="ml-colabs", job_type="medcpt-index")
            retriever = MedCPTRetriever(
                query_encoder_model_name="ncbi/MedCPT-Query-Encoder",
                article_encoder_model_name="ncbi/MedCPT-Article-Encoder",
            )
            retriever.index(
                chunk_dataset_name="grays-anatomy-chunks:v0",
                index_name="grays-anatomy-medcpt",
            )
            ```

        Args:
            chunk_dataset_name (str): The name of the dataset containing text chunks to be indexed.
            index_name (Optional[str]): The name to use when saving the vector index. If not provided,
                the vector index is not saved.

        """
        self._chunk_dataset = weave.ref(chunk_dataset_name).get().rows
        corpus = [row["text"] for row in self._chunk_dataset]
        with torch.no_grad():
            encoded = self._article_tokenizer(
                corpus,
                truncation=True,
                padding=True,
                return_tensors="pt",
                max_length=self.chunk_size,
            )
            vector_index = (
                self._article_encoder_model(**encoded)
                .last_hidden_state[:, 0, :]
                .contiguous()
            )
            self._vector_index = vector_index
            if index_name:
                save_vector_index(
                    self._vector_index,
                    "medcpt-index",
                    index_name,
                    {
                        "query_encoder_model_name": self.query_encoder_model_name,
                        "article_encoder_model_name": self.article_encoder_model_name,
                        "chunk_size": self.chunk_size,
                    },
                )

    @classmethod
    def from_wandb_artifact(cls, chunk_dataset_name: str, index_artifact_address: str):
        """
        Initializes an instance of the class from a Weave artifact.

        This method retrieves a precomputed vector index and its associated metadata from a Weave artifact
        stored in Weights & Biases (wandb). It then loads the vector index into memory and initializes an
        instance of the class with the retrieved model names, vector index, and chunk dataset.

        !!! example "Example Usage"
            ```python
            import weave
            from dotenv import load_dotenv

            import wandb
            from medrag_multi_modal.retrieval import MedCPTRetriever

            load_dotenv()
            weave.init(project_name="ml-colabs/medrag-multi-modal")
            retriever = MedCPTRetriever.from_wandb_artifact(
                chunk_dataset_name="grays-anatomy-chunks:v0",
                index_artifact_address="ml-colabs/medrag-multi-modal/grays-anatomy-medcpt:v0",
            )
            ```

        Args:
            chunk_dataset_name (str): The name of the dataset containing text chunks to be indexed.
            index_artifact_address (str): The address of the Weave artifact containing the precomputed vector index.

        Returns:
            An instance of the class initialized with the retrieved model name, vector index, and chunk dataset.
        """
        artifact_dir, metadata = get_wandb_artifact(
            index_artifact_address, "medcpt-index", get_metadata=True
        )
        with safetensors.torch.safe_open(
            os.path.join(artifact_dir, "vector_index.safetensors"), framework="pt"
        ) as f:
            vector_index = f.get_tensor("vector_index")
        device = torch.device(get_torch_backend())
        vector_index = vector_index.to(device)
        chunk_dataset = [dict(row) for row in weave.ref(chunk_dataset_name).get().rows]
        return cls(
            query_encoder_model_name=metadata["query_encoder_model_name"],
            article_encoder_model_name=metadata["article_encoder_model_name"],
            chunk_size=metadata["chunk_size"],
            vector_index=vector_index,
            chunk_dataset=chunk_dataset,
        )

    @weave.op()
    def retrieve(
        self,
        query: str,
        top_k: int = 2,
        metric: SimilarityMetric = SimilarityMetric.COSINE,
    ):
        """
        Retrieves the top-k most relevant chunks for a given query using the specified similarity metric.

        This method encodes the input query into an embedding and computes similarity scores between
        the query embedding and the precomputed vector index. The similarity metric can be either
        cosine similarity or Euclidean distance. The top-k chunks with the highest similarity scores
        are returned as a list of dictionaries, each containing a chunk and its corresponding score.

        Args:
            query (str): The input query string to search for relevant chunks.
            top_k (int, optional): The number of top relevant chunks to retrieve. Defaults to 2.
            metric (SimilarityMetric, optional): The similarity metric to use for scoring. Defaults to cosine similarity.

        Returns:
            list: A list of dictionaries, each containing a retrieved chunk and its relevance score.
        """
        query = [query]
        device = torch.device(get_torch_backend())
        with torch.no_grad():
            encoded = self._query_tokenizer(
                query,
                truncation=True,
                padding=True,
                return_tensors="pt",
            )
            query_embedding = self._query_encoder_model(**encoded).last_hidden_state[
                :, 0, :
            ]
            query_embedding = query_embedding.to(device)
            if metric == SimilarityMetric.EUCLIDEAN:
                scores = torch.squeeze(query_embedding @ self._vector_index.T)
            else:
                scores = F.cosine_similarity(query_embedding, self._vector_index)
            scores = scores.cpu().numpy().tolist()
        scores = argsort_scores(scores, descending=True)[:top_k]
        retrieved_chunks = []
        for score in scores:
            retrieved_chunks.append(
                {
                    **self._chunk_dataset[score["original_index"]],
                    **{"score": score["item"]},
                }
            )
        return retrieved_chunks

    @weave.op()
    def predict(
        self,
        query: str,
        top_k: int = 2,
        metric: SimilarityMetric = SimilarityMetric.COSINE,
    ):
        """
        Predicts the most relevant chunks for a given query.

        This function uses the `retrieve` method to find the top-k relevant chunks
        from the dataset based on the input query. It allows specifying the number
        of top relevant chunks to retrieve and the similarity metric to use for scoring.

        !!! example "Example Usage"
            ```python
            import weave
            from dotenv import load_dotenv

            import wandb
            from medrag_multi_modal.retrieval import MedCPTRetriever

            load_dotenv()
            weave.init(project_name="ml-colabs/medrag-multi-modal")
            retriever = MedCPTRetriever.from_wandb_artifact(
                chunk_dataset_name="grays-anatomy-chunks:v0",
                index_artifact_address="ml-colabs/medrag-multi-modal/grays-anatomy-medcpt:v0",
            )
            retriever.predict(query="What are Ribosomes?")
            ```

        Args:
            query (str): The input query string to search for relevant chunks.
            top_k (int, optional): The number of top relevant chunks to retrieve. Defaults to 2.
            metric (SimilarityMetric, optional): The similarity metric to use for scoring. Defaults to cosine similarity.

        Returns:
            list: A list of dictionaries, each containing a retrieved chunk and its relevance score.
        """
        return self.retrieve(query, top_k, metric)