ray-embedding 0.12.0__tar.gz → 0.12.1__tar.gz

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.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ray-embedding
3
- Version: 0.12.0
3
+ Version: 0.12.1
4
4
  Summary: Deploy SentenceTransformers embedding models to a ray cluster
5
5
  Author: Crispin Almodovar
6
6
  Author-email:
@@ -1,12 +1,10 @@
1
1
  import os
2
- from typing import Dict, Any, Optional
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":
@@ -21,6 +21,7 @@ class EmbeddingResponse(BaseModel):
21
21
  class ModelRouterConfig(BaseModel):
22
22
  deployment: str
23
23
  path_prefix: List[str] = []
24
+ max_concurrency: int = 32
24
25
 
25
26
 
26
27
  class ModelDeploymentConfig(BaseModel):
@@ -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 loaded model."""
41
- if isinstance(text, str):
42
- text = [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 and convert to a PyTorch tensor on the GPU
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()
@@ -1,27 +1,29 @@
1
1
  import asyncio
2
2
  import logging
3
3
  import time
4
- from typing import Optional, Dict, List, Tuple, Any, Coroutine
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 EmbeddingResponse, EmbeddingRequest, DeployedModel
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 = [model_handle.remote(batch, dimensions) for batch in batches]
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 (retries >= num_retries and isinstance(result_retried, Exception)) or result_retried is None:
56
- raise result_retried or ValueError(f"Failed to compute `{model}` embeddings for mini-batch of size {batch_size}.")
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
+ 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]:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ray-embedding
3
- Version: 0.12.0
3
+ Version: 0.12.1
4
4
  Summary: Deploy SentenceTransformers embedding models to a ray cluster
5
5
  Author: Crispin Almodovar
6
6
  Author-email:
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = ray-embedding
3
- version = 0.12.0
3
+ version = 0.12.1
4
4
  author = Crispin Almodovar
5
5
  author_email =
6
6
  description = Deploy SentenceTransformers embedding models to a ray cluster
File without changes