Elffuss BraidHub

kikocis/lancedb public

main · 9.9 KiBRenderedRawPermalink
1To use your own custom embedding function, you can follow these 2 simple steps:
2
31. Create your embedding function by implementing the `EmbeddingFunction` interface
42. Register your embedding function in the global `EmbeddingFunctionRegistry`.
5
6Let us see how this looks like in action.
7
8![](../assets/embeddings_api.png)
9
10`EmbeddingFunction` and `EmbeddingFunctionRegistry` handle low-level details for serializing schema and model information as metadata. To build a custom embedding function, you don't have to worry about the finer details - simply focus on setting up the model and leave the rest to LanceDB.
11
12## `TextEmbeddingFunction` interface
13
14There is another optional layer of abstraction available: `TextEmbeddingFunction`. You can use this abstraction if your model isn't multi-modal in nature and only needs to operate on text. In such cases, both the source and vector fields will have the same work for vectorization, so you simply just need to setup the model and rest is handled by `TextEmbeddingFunction`. You can read more about the class and its attributes in the class reference.
15
16Let's implement `SentenceTransformerEmbeddings` class. All you need to do is implement the `generate_embeddings()` and `ndims` function to handle the input types you expect and register the class in the global `EmbeddingFunctionRegistry`
17
18
19=== "Python"
20
21 ```python
22 from lancedb.embeddings import register
23 from lancedb.util import attempt_import_or_raise
24
25 @register("sentence-transformers")
26 class SentenceTransformerEmbeddings(TextEmbeddingFunction):
27 name: str = "all-MiniLM-L6-v2"
28 # set more default instance vars like device, etc.
29
30 def __init__(self, **kwargs):
31 super().__init__(**kwargs)
32 self._ndims = None
33
34 def generate_embeddings(self, texts):
35 return self._embedding_model().encode(list(texts), ...).tolist()
36
37 def ndims(self):
38 if self._ndims is None:
39 self._ndims = len(self.generate_embeddings("foo")[0])
40 return self._ndims
41
42 @cached(cache={})
43 def _embedding_model(self):
44 return sentence_transformers.SentenceTransformer(name)
45 ```
46
47=== "TypeScript"
48
49 ```ts
50 --8<--- "nodejs/examples/custom_embedding_function.ts:imports"
51
52 --8<--- "nodejs/examples/custom_embedding_function.ts:embedding_impl"
53 ```
54
55
56This is a stripped down version of our implementation of `SentenceTransformerEmbeddings` that removes certain optimizations and default settings.
57
58Now you can use this embedding function to create your table schema and that's it! you can then ingest data and run queries without manually vectorizing the inputs.
59
60=== "Python"
61
62 ```python
63 from lancedb.pydantic import LanceModel, Vector
64
65 registry = EmbeddingFunctionRegistry.get_instance()
66 stransformer = registry.get("sentence-transformers").create()
67
68 class TextModelSchema(LanceModel):
69 vector: Vector(stransformer.ndims) = stransformer.VectorField()
70 text: str = stransformer.SourceField()
71
72 tbl = db.create_table("table", schema=TextModelSchema)
73
74 tbl.add(pd.DataFrame({"text": ["halo", "world"]}))
75 result = tbl.search("world").limit(5)
76 ```
77
78=== "TypeScript"
79
80 ```ts
81 --8<--- "nodejs/examples/custom_embedding_function.ts:call_custom_function"
82 ```
83
84!!! note
85
86 You can always implement the `EmbeddingFunction` interface directly if you want or need to, `TextEmbeddingFunction` just makes it much simpler and faster for you to do so, by setting up the boiler plat for text-specific use case
87
88## Multi-modal embedding function example
89You can also use the `EmbeddingFunction` interface to implement more complex workflows such as multi-modal embedding function support.
90
91=== "Python"
92
93 LanceDB implements `OpenClipEmeddingFunction` class that suppports multi-modal seach. Here's the implementation that you can use as a reference to build your own multi-modal embedding functions.
94
95 ```python
96 @register("open-clip")
97 class OpenClipEmbeddings(EmbeddingFunction):
98 name: str = "ViT-B-32"
99 pretrained: str = "laion2b_s34b_b79k"
100 device: str = "cpu"
101 batch_size: int = 64
102 normalize: bool = True
103 _model = PrivateAttr()
104 _preprocess = PrivateAttr()
105 _tokenizer = PrivateAttr()
106
107 def __init__(self, *args, **kwargs):
108 super().__init__(*args, **kwargs)
109 open_clip = attempt_import_or_raise("open_clip", "open-clip") # EmbeddingFunction util to import external libs and raise if not found
110 model, _, preprocess = open_clip.create_model_and_transforms(
111 self.name, pretrained=self.pretrained
112 )
113 model.to(self.device)
114 self._model, self._preprocess = model, preprocess
115 self._tokenizer = open_clip.get_tokenizer(self.name)
116 self._ndims = None
117
118 def ndims(self):
119 if self._ndims is None:
120 self._ndims = self.generate_text_embeddings("foo").shape[0]
121 return self._ndims
122
123 def compute_query_embeddings(
124 self, query: Union[str, "PIL.Image.Image"], *args, **kwargs
125 ) -> List[np.ndarray]:
126 """
127 Compute the embeddings for a given user query
128
129 Parameters
130 ----------
131 query : Union[str, PIL.Image.Image]
132 The query to embed. A query can be either text or an image.
133 """
134 if isinstance(query, str):
135 return [self.generate_text_embeddings(query)]
136 else:
137 PIL = attempt_import_or_raise("PIL", "pillow")
138 if isinstance(query, PIL.Image.Image):
139 return [self.generate_image_embedding(query)]
140 else:
141 raise TypeError("OpenClip supports str or PIL Image as query")
142
143 def generate_text_embeddings(self, text: str) -> np.ndarray:
144 torch = attempt_import_or_raise("torch")
145 text = self.sanitize_input(text)
146 text = self._tokenizer(text)
147 text.to(self.device)
148 with torch.no_grad():
149 text_features = self._model.encode_text(text.to(self.device))
150 if self.normalize:
151 text_features /= text_features.norm(dim=-1, keepdim=True)
152 return text_features.cpu().numpy().squeeze()
153
154 def sanitize_input(self, images: IMAGES) -> Union[List[bytes], np.ndarray]:
155 """
156 Sanitize the input to the embedding function.
157 """
158 if isinstance(images, (str, bytes)):
159 images = [images]
160 elif isinstance(images, pa.Array):
161 images = images.to_pylist()
162 elif isinstance(images, pa.ChunkedArray):
163 images = images.combine_chunks().to_pylist()
164 return images
165
166 def compute_source_embeddings(
167 self, images: IMAGES, *args, **kwargs
168 ) -> List[np.array]:
169 """
170 Get the embeddings for the given images
171 """
172 images = self.sanitize_input(images)
173 embeddings = []
174 for i in range(0, len(images), self.batch_size):
175 j = min(i + self.batch_size, len(images))
176 batch = images[i:j]
177 embeddings.extend(self._parallel_get(batch))
178 return embeddings
179
180 def _parallel_get(self, images: Union[List[str], List[bytes]]) -> List[np.ndarray]:
181 """
182 Issue concurrent requests to retrieve the image data
183 """
184 with concurrent.futures.ThreadPoolExecutor() as executor:
185 futures = [
186 executor.submit(self.generate_image_embedding, image)
187 for image in images
188 ]
189 return [future.result() for future in futures]
190
191 def generate_image_embedding(
192 self, image: Union[str, bytes, "PIL.Image.Image"]
193 ) -> np.ndarray:
194 """
195 Generate the embedding for a single image
196
197 Parameters
198 ----------
199 image : Union[str, bytes, PIL.Image.Image]
200 The image to embed. If the image is a str, it is treated as a uri.
201 If the image is bytes, it is treated as the raw image bytes.
202 """
203 torch = attempt_import_or_raise("torch")
204 # TODO handle retry and errors for https
205 image = self._to_pil(image)
206 image = self._preprocess(image).unsqueeze(0)
207 with torch.no_grad():
208 return self._encode_and_normalize_image(image)
209
210 def _to_pil(self, image: Union[str, bytes]):
211 PIL = attempt_import_or_raise("PIL", "pillow")
212 if isinstance(image, bytes):
213 return PIL.Image.open(io.BytesIO(image))
214 if isinstance(image, PIL.Image.Image):
215 return image
216 elif isinstance(image, str):
217 parsed = urlparse.urlparse(image)
218 # TODO handle drive letter on windows.
219 if parsed.scheme == "file":
220 return PIL.Image.open(parsed.path)
221 elif parsed.scheme == "":
222 return PIL.Image.open(image if os.name == "nt" else parsed.path)
223 elif parsed.scheme.startswith("http"):
224 return PIL.Image.open(io.BytesIO(url_retrieve(image)))
225 else:
226 raise NotImplementedError("Only local and http(s) urls are supported")
227
228 def _encode_and_normalize_image(self, image_tensor: "torch.Tensor"):
229 """
230 encode a single image tensor and optionally normalize the output
231 """
232 image_features = self._model.encode_image(image_tensor)
233 if self.normalize:
234 image_features /= image_features.norm(dim=-1, keepdim=True)
235 return image_features.cpu().numpy().squeeze()
236 ```
237
238=== "TypeScript"
239
240 Coming Soon! See this [issue](https://github.com/lancedb/lancedb/issues/1482) to track the status!