ray-embedding 0.9.0__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/__init__.py +2 -0
- ray_embedding/deploy.py +34 -0
- ray_embedding/dto.py +16 -0
- ray_embedding/embedding_model.py +93 -0
- ray_embedding-0.9.0.dist-info/METADATA +24 -0
- ray_embedding-0.9.0.dist-info/RECORD +8 -0
- ray_embedding-0.9.0.dist-info/WHEEL +5 -0
- ray_embedding-0.9.0.dist-info/top_level.txt +1 -0
ray_embedding/deploy.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from typing import Dict, Any, Optional
|
|
2
|
+
from ray.serve import Application
|
|
3
|
+
from ray_embedding.embedding_model import EmbeddingModel
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def deploy_model(args: Dict[str, Any]) -> Application:
|
|
8
|
+
assert args
|
|
9
|
+
deployment_name: str = args.pop("deployment", "")
|
|
10
|
+
assert deployment_name
|
|
11
|
+
|
|
12
|
+
model: str = args.pop("model", "")
|
|
13
|
+
assert model
|
|
14
|
+
|
|
15
|
+
backend: Optional[str] = args.pop("backend", "torch")
|
|
16
|
+
matryoshka_dim: Optional[int] = args.pop("matryoshka_dim", None)
|
|
17
|
+
trust_remote_code: Optional[bool] = args.pop("trust_remote_code", False)
|
|
18
|
+
model_kwargs: Dict[str, Any] = args.pop("model_kwargs", {})
|
|
19
|
+
if "torch_dtype" in model_kwargs:
|
|
20
|
+
model_kwargs["torch_dtype"] = model_kwargs["torch_dtype"].strip()
|
|
21
|
+
if model_kwargs["torch_dtype"] == "float16":
|
|
22
|
+
model_kwargs["torch_dtype"] = torch.float16
|
|
23
|
+
elif model_kwargs["torch_dtype"] == "bfloat16":
|
|
24
|
+
model_kwargs["torch_dtype"] = torch.bfloat16
|
|
25
|
+
else:
|
|
26
|
+
del model_kwargs["torch_dtype"]
|
|
27
|
+
|
|
28
|
+
deployment = EmbeddingModel.options(name=deployment_name).bind(model=model,
|
|
29
|
+
backend=backend,
|
|
30
|
+
matryoshka_dim=matryoshka_dim,
|
|
31
|
+
trust_remote_code=trust_remote_code,
|
|
32
|
+
model_kwargs=model_kwargs
|
|
33
|
+
)
|
|
34
|
+
return deployment
|
ray_embedding/dto.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from typing import Union, List, Optional
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class EmbeddingRequest(BaseModel):
|
|
6
|
+
"""Schema of embedding requests (compatible with OpenAI)"""
|
|
7
|
+
model: str # Model name (for compatibility; only one model is used here)
|
|
8
|
+
input: Union[str, List[str]] # List of strings to embed
|
|
9
|
+
dimensions: Optional[int] = None
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EmbeddingResponse(BaseModel):
|
|
13
|
+
"""Schema of embedding response (compatible with OpenAI)"""
|
|
14
|
+
object: str
|
|
15
|
+
data: List[dict] # Embedding data including index and vector
|
|
16
|
+
model: str # Model name used for embedding
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os.path
|
|
3
|
+
import time
|
|
4
|
+
from typing import Optional, Dict, Any
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
from fastapi import FastAPI, HTTPException
|
|
8
|
+
from ray import serve
|
|
9
|
+
from sentence_transformers import SentenceTransformer
|
|
10
|
+
|
|
11
|
+
from ray_embedding.dto import EmbeddingResponse, EmbeddingRequest
|
|
12
|
+
|
|
13
|
+
web_api = FastAPI(title=f"Ray Embeddings - OpenAI-compatible API")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@serve.deployment(
|
|
17
|
+
ray_actor_options={"num_gpus": 1},
|
|
18
|
+
autoscaling_config={
|
|
19
|
+
"target_ongoing_requests": 2,
|
|
20
|
+
"min_replicas": 0,
|
|
21
|
+
"initial_replicas": 1,
|
|
22
|
+
"max_replicas": 1,
|
|
23
|
+
}
|
|
24
|
+
)
|
|
25
|
+
@serve.ingress(web_api)
|
|
26
|
+
class EmbeddingModel:
|
|
27
|
+
def __init__(self, model: str, backend: Optional[str] = "torch", matryoshka_dim: Optional[int] = None,
|
|
28
|
+
trust_remote_code: Optional[bool] = False, model_kwargs: Dict[str, Any] = None):
|
|
29
|
+
logging.basicConfig(level=logging.INFO)
|
|
30
|
+
self.logger = logging.getLogger(__name__)
|
|
31
|
+
self.model = model
|
|
32
|
+
self.backend = backend or "torch"
|
|
33
|
+
self.matryoshka_dim = matryoshka_dim
|
|
34
|
+
self.trust_remote_code = trust_remote_code or False
|
|
35
|
+
self.model_kwargs = model_kwargs or {}
|
|
36
|
+
self.torch_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
37
|
+
self.logger.info(f"Initializing embedding model: {self.model}")
|
|
38
|
+
self.embedding_model = SentenceTransformer(self.model, backend=self.backend, trust_remote_code=self.trust_remote_code,
|
|
39
|
+
model_kwargs=self.model_kwargs)
|
|
40
|
+
|
|
41
|
+
self.served_model_name = os.path.basename(self.model)
|
|
42
|
+
self.available_models = [
|
|
43
|
+
{"id": self.served_model_name,
|
|
44
|
+
"object": "model",
|
|
45
|
+
"created": int(time.time()),
|
|
46
|
+
"owned_by": "openai",
|
|
47
|
+
"permission": []}
|
|
48
|
+
]
|
|
49
|
+
self.logger.info(f"Successfully initialized embedding model {self.model}")
|
|
50
|
+
|
|
51
|
+
@web_api.post("/v1/embeddings", response_model=EmbeddingResponse)
|
|
52
|
+
async def create_embeddings(self, request: EmbeddingRequest):
|
|
53
|
+
"""Generate embeddings for the input text using the specified model."""
|
|
54
|
+
try:
|
|
55
|
+
assert request.model == self.served_model_name, (
|
|
56
|
+
f"Model '{request.model}' is not supported. Use '{self.served_model_name}' instead."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
if isinstance(request.input, str):
|
|
60
|
+
request.input = [request.input]
|
|
61
|
+
|
|
62
|
+
truncate_dim = request.dimensions or self.matryoshka_dim
|
|
63
|
+
|
|
64
|
+
# Compute embeddings and convert to a PyTorch tensor on the GPU
|
|
65
|
+
embeddings = self.embedding_model.encode(
|
|
66
|
+
request.input, convert_to_tensor=True, normalize_embeddings=True
|
|
67
|
+
).to(self.torch_device)
|
|
68
|
+
|
|
69
|
+
if truncate_dim is not None:
|
|
70
|
+
# Truncate and re-normalize the embeddings
|
|
71
|
+
embeddings = embeddings[:, :truncate_dim]
|
|
72
|
+
embeddings = embeddings / torch.norm(embeddings, dim=1, keepdim=True)
|
|
73
|
+
|
|
74
|
+
# Move all embeddings to CPU at once before conversion
|
|
75
|
+
embeddings = embeddings.cpu().tolist()
|
|
76
|
+
|
|
77
|
+
# Convert embeddings to list format for response
|
|
78
|
+
response_data = [
|
|
79
|
+
{"index": idx, "embedding": emb}
|
|
80
|
+
for idx, emb in enumerate(embeddings)
|
|
81
|
+
]
|
|
82
|
+
return EmbeddingResponse(object="list", data=response_data, model=request.model)
|
|
83
|
+
|
|
84
|
+
except Exception as e:
|
|
85
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
86
|
+
|
|
87
|
+
@web_api.get("/v1/models")
|
|
88
|
+
async def list_models(self):
|
|
89
|
+
"""Returns the list of available models in OpenAI-compatible format."""
|
|
90
|
+
return {"object": "list", "data": self.available_models}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ray-embedding
|
|
3
|
+
Version: 0.9.0
|
|
4
|
+
Summary: Deploy SentenceTransformers models to a ray cluster
|
|
5
|
+
Author: Crispin Almodovar
|
|
6
|
+
Author-email: crispin.almodovar@docorto.ai
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# ray-embedding
|
|
14
|
+
|
|
15
|
+
A tool for deploying SentenceTransformers models to a ray cluster.
|
|
16
|
+
|
|
17
|
+
### Supports the following backends
|
|
18
|
+
|
|
19
|
+
- sbert-pytorch-gpu
|
|
20
|
+
- sbert-pytorch-cpu
|
|
21
|
+
- sbert-onnx-gpu
|
|
22
|
+
- sbert-onnx-cpu
|
|
23
|
+
- sbert-openvino-cpu
|
|
24
|
+
- fastembed-onnx-cpu
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
ray_embedding/__init__.py,sha256=OYJT0rVaaGzY613JqgfktsCgroDnBkGOHxR2FE9UtRU,49
|
|
2
|
+
ray_embedding/deploy.py,sha256=E79J0bcVNXAFlFMVrjZTaSXLnrMZ6LvtRdD4d1DKu1w,1598
|
|
3
|
+
ray_embedding/dto.py,sha256=e91ejZbM_NB9WTjF1YnfuV71cajYIh0vOX8oV_g2OwM,595
|
|
4
|
+
ray_embedding/embedding_model.py,sha256=1sx5jXo61UgLLL8BtFBPflsbBay6J3yG1u2UMIPgAtk,3768
|
|
5
|
+
ray_embedding-0.9.0.dist-info/METADATA,sha256=zfS00PtWu6mTcHloTDJDqEQ9bwbLJWUSgiv21degWNc,636
|
|
6
|
+
ray_embedding-0.9.0.dist-info/WHEEL,sha256=1tXe9gY0PYatrMPMDd6jXqjfpz_B-Wqm32CPfRC58XU,91
|
|
7
|
+
ray_embedding-0.9.0.dist-info/top_level.txt,sha256=ziCblpJq1YsrryshFqxTRuRMgNuO1_tgvAAkGShATNA,14
|
|
8
|
+
ray_embedding-0.9.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ray_embedding
|