ray-embedding 0.12.0__py3-none-any.whl → 0.12.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of ray-embedding might be problematic. Click here for more details.
- ray_embedding/deploy.py +3 -4
- ray_embedding/dto.py +1 -0
- ray_embedding/embedding_model.py +7 -6
- ray_embedding/model_router.py +15 -8
- {ray_embedding-0.12.0.dist-info → ray_embedding-0.12.2.dist-info}/METADATA +1 -1
- ray_embedding-0.12.2.dist-info/RECORD +9 -0
- ray_embedding-0.12.0.dist-info/RECORD +0 -9
- {ray_embedding-0.12.0.dist-info → ray_embedding-0.12.2.dist-info}/WHEEL +0 -0
- {ray_embedding-0.12.0.dist-info → ray_embedding-0.12.2.dist-info}/top_level.txt +0 -0
ray_embedding/deploy.py
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
import os
|
|
2
|
-
|
|
2
|
+
|
|
3
|
+
import torch
|
|
3
4
|
from ray.serve import Application
|
|
4
|
-
from ray.serve.handle import DeploymentHandle
|
|
5
5
|
|
|
6
6
|
from ray_embedding.dto import AppConfig, ModelDeploymentConfig, DeployedModel
|
|
7
7
|
from ray_embedding.embedding_model import EmbeddingModel
|
|
8
|
-
import torch
|
|
9
|
-
|
|
10
8
|
from ray_embedding.model_router import ModelRouter
|
|
11
9
|
|
|
12
10
|
|
|
@@ -19,6 +17,7 @@ def build_model(model_config: ModelDeploymentConfig) -> DeployedModel:
|
|
|
19
17
|
matryoshka_dim = model_config.matryoshka_dim
|
|
20
18
|
trust_remote_code = model_config.trust_remote_code or False
|
|
21
19
|
model_kwargs = model_config.model_kwargs or {}
|
|
20
|
+
|
|
22
21
|
if "torch_dtype" in model_kwargs:
|
|
23
22
|
torch_dtype = model_kwargs["torch_dtype"].strip()
|
|
24
23
|
if torch_dtype == "float16":
|
ray_embedding/dto.py
CHANGED
ray_embedding/embedding_model.py
CHANGED
|
@@ -37,12 +37,14 @@ class EmbeddingModel:
|
|
|
37
37
|
self.logger.info(f"Successfully initialized model {self.model} using device {self.torch_device}")
|
|
38
38
|
|
|
39
39
|
async def __call__(self, text: Union[str, List[str]], dimensions: Optional[int] = None) -> List[List[float]]:
|
|
40
|
-
"""Compute embeddings for the input text using the
|
|
41
|
-
if isinstance(text,
|
|
42
|
-
text
|
|
40
|
+
"""Compute embeddings for the input text using the current model."""
|
|
41
|
+
if not text or (isinstance(text, list) and not all(text)):
|
|
42
|
+
raise ValueError("Input text is empty or invalid")
|
|
43
|
+
|
|
44
|
+
text = [text] if isinstance(text, str) else text
|
|
43
45
|
truncate_dim = dimensions or self.matryoshka_dim
|
|
44
46
|
|
|
45
|
-
# Compute embeddings
|
|
47
|
+
# Compute embeddings in PyTorch format
|
|
46
48
|
embeddings = self.embedding_model.encode(
|
|
47
49
|
text, convert_to_tensor=True, normalize_embeddings=True, show_progress_bar=False,
|
|
48
50
|
).to(self.torch_device)
|
|
@@ -56,7 +58,6 @@ class EmbeddingModel:
|
|
|
56
58
|
embeddings_list = embeddings.cpu().tolist()
|
|
57
59
|
return embeddings_list
|
|
58
60
|
|
|
59
|
-
|
|
60
61
|
def wait_for_cuda(self, wait: int = 10):
|
|
61
62
|
if self.init_device == "cuda" and not torch.cuda.is_available():
|
|
62
63
|
time.sleep(wait)
|
|
@@ -65,7 +66,7 @@ class EmbeddingModel:
|
|
|
65
66
|
def check_health(self):
|
|
66
67
|
if self.init_device == "cuda":
|
|
67
68
|
# Even though CUDA was available at init time,
|
|
68
|
-
# CUDA can become unavailable - this is a known problem in AWS EC2
|
|
69
|
+
# CUDA can become unavailable - this is a known problem in AWS EC2+Docker
|
|
69
70
|
# https://github.com/ray-project/ray/issues/49594
|
|
70
71
|
try:
|
|
71
72
|
nvmlInit()
|
ray_embedding/model_router.py
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
import logging
|
|
3
3
|
import time
|
|
4
|
-
from typing import Optional, Dict, List, Tuple
|
|
4
|
+
from typing import Optional, Dict, List, Tuple
|
|
5
5
|
|
|
6
6
|
from fastapi import FastAPI, HTTPException
|
|
7
7
|
from ray import serve
|
|
8
8
|
from ray.serve.handle import DeploymentHandle
|
|
9
9
|
|
|
10
|
-
from ray_embedding.dto import
|
|
10
|
+
from ray_embedding.dto import DeployedModel, EmbeddingRequest, EmbeddingResponse
|
|
11
11
|
|
|
12
12
|
web_api = FastAPI(title="Ray Embeddings - OpenAI-compatible API")
|
|
13
13
|
|
|
14
14
|
@serve.deployment
|
|
15
15
|
@serve.ingress(web_api)
|
|
16
16
|
class ModelRouter:
|
|
17
|
-
def __init__(self, deployed_models: Dict[str, DeployedModel], path_prefix: List[str]):
|
|
17
|
+
def __init__(self, deployed_models: Dict[str, DeployedModel], path_prefix: List[str], max_concurrency: Optional[int] = 32):
|
|
18
18
|
assert deployed_models, "models cannot be empty"
|
|
19
19
|
assert path_prefix, "path_prefix cannot be empty"
|
|
20
20
|
|
|
21
21
|
logging.basicConfig(level=logging.INFO)
|
|
22
22
|
self.logger = logging.getLogger(self.__class__.__name__)
|
|
23
23
|
self.deployed_models = deployed_models
|
|
24
|
-
self.path_prefix = path_prefix
|
|
24
|
+
self.path_prefix = [item.removeprefix("/").removesuffix("/") for item in path_prefix]
|
|
25
|
+
self.max_concurrency = max_concurrency
|
|
26
|
+
self.rate_limiter = asyncio.Semaphore(self.max_concurrency)
|
|
25
27
|
self.available_models = [
|
|
26
28
|
{"id": str(item),
|
|
27
29
|
"object": "model",
|
|
@@ -43,17 +45,18 @@ class ModelRouter:
|
|
|
43
45
|
self.logger.info(f"Original input (length {len(inputs)} was resized "
|
|
44
46
|
f"to {len(batches)} mini-batches, each with max length {batch_size}.")
|
|
45
47
|
|
|
46
|
-
# Call embedding model replicas in parallel
|
|
47
|
-
tasks = [
|
|
48
|
+
# Call embedding model replicas in parallel (rate-limited)
|
|
49
|
+
tasks = [self._rate_limited_embedding_call(model_handle, batch, dimensions) for batch in batches]
|
|
48
50
|
all_results = await asyncio.gather(*tasks, return_exceptions=True)
|
|
49
51
|
|
|
50
52
|
# Retry any failed model calls
|
|
51
53
|
for i, result in enumerate(all_results):
|
|
52
54
|
if isinstance(result, Exception):
|
|
55
|
+
self.logger.warning(f"Retrying mini-batch {i} due to exception: {result}")
|
|
53
56
|
result_retried, retries = await self._retry_failed_embedding_call(model_handle, batches[i], dimensions,
|
|
54
57
|
num_retries)
|
|
55
|
-
if
|
|
56
|
-
raise result_retried or ValueError(f"Failed to compute `{model}` embeddings for mini-batch
|
|
58
|
+
if retries >= num_retries and (isinstance(result_retried, Exception) or result_retried is None):
|
|
59
|
+
raise result_retried or ValueError(f"Failed to compute `{model}` embeddings for mini-batch {i} after {num_retries} retries.")
|
|
57
60
|
|
|
58
61
|
all_results[i] = result_retried
|
|
59
62
|
|
|
@@ -61,6 +64,10 @@ class ModelRouter:
|
|
|
61
64
|
self.logger.info(f"Successfully computed embeddings from {len(batches)} mini-batches")
|
|
62
65
|
return [emb for result in all_results for emb in result]
|
|
63
66
|
|
|
67
|
+
async def _rate_limited_embedding_call(self, model_handle: DeploymentHandle, batch: List[str], dimensions: int):
|
|
68
|
+
async with self.rate_limiter:
|
|
69
|
+
return await model_handle.remote(batch, dimensions)
|
|
70
|
+
|
|
64
71
|
async def _retry_failed_embedding_call(self, model_handle: DeploymentHandle, batch: List[str],
|
|
65
72
|
dimensions: Optional[int] = None, num_retries: Optional[int] = 2) \
|
|
66
73
|
-> Tuple[List[List[float]] | Exception, int]:
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
ray_embedding/__init__.py,sha256=YS5LAZfRIwwVvE3C9g7hsauvjgIkqKtHyxkwMFFfAGY,46
|
|
2
|
+
ray_embedding/deploy.py,sha256=xE-NznVlYftTPIfN3aAqCF0DpFIvTuC4vMTNrGfjkxI,2627
|
|
3
|
+
ray_embedding/dto.py,sha256=rzPEB-R7XDYlTqeaXGGgfOjTWyTeRinnJ6LbI1oOWGY,1463
|
|
4
|
+
ray_embedding/embedding_model.py,sha256=wHyDgDCR11VcV2by4bCCp6CSi0mI9zcwkmSbnL3WdRY,3519
|
|
5
|
+
ray_embedding/model_router.py,sha256=ELmD9gU6Tn8AUChN2CTaP3Puvnl8S5EcljnpRwsRI1Y,5701
|
|
6
|
+
ray_embedding-0.12.2.dist-info/METADATA,sha256=VHUh1jHfc47rgef1RuAmlepj_uS081sEp6JkxaGMWUw,1094
|
|
7
|
+
ray_embedding-0.12.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
8
|
+
ray_embedding-0.12.2.dist-info/top_level.txt,sha256=ziCblpJq1YsrryshFqxTRuRMgNuO1_tgvAAkGShATNA,14
|
|
9
|
+
ray_embedding-0.12.2.dist-info/RECORD,,
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
ray_embedding/__init__.py,sha256=YS5LAZfRIwwVvE3C9g7hsauvjgIkqKtHyxkwMFFfAGY,46
|
|
2
|
-
ray_embedding/deploy.py,sha256=_p8LXLfRP2y9z4Jj1BbuVTuDYkuXZpGI_JkTEj_bMa4,2712
|
|
3
|
-
ray_embedding/dto.py,sha256=NwS8EkeZZcfWDE6RFsLG0WtZtnc7onlr95llRSgnIQc,1432
|
|
4
|
-
ray_embedding/embedding_model.py,sha256=cZe6voJTXYz0OKjjkFskC05V8frm3B-B3-Ae1j9GMKo,3408
|
|
5
|
-
ray_embedding/model_router.py,sha256=04PN_ZptFwEGeSSaDVbCodbDMRMu2i-jeamC1Sb2v24,5145
|
|
6
|
-
ray_embedding-0.12.0.dist-info/METADATA,sha256=jSrtclfqYRIfyd5e1KErc3DvDjXSB2TZEvXSyi-aGqk,1094
|
|
7
|
-
ray_embedding-0.12.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
8
|
-
ray_embedding-0.12.0.dist-info/top_level.txt,sha256=ziCblpJq1YsrryshFqxTRuRMgNuO1_tgvAAkGShATNA,14
|
|
9
|
-
ray_embedding-0.12.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|