File size: 7,736 Bytes
2f13bcc
 
 
 
 
 
 
 
 
ec855e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f13bcc
ec855e6
2f13bcc
ec855e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f13bcc
ec855e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---

title: BGE-M3 Multilingual Embedding Server
emoji: πŸš€
colorFrom: blue
colorTo: indigo
sdk: docker
pinned: false
---


# BGE-M3 Multilingual Embedding Server

A high-performance, robust, and production-ready embedding server utilizing the **BGE-M3** model. This server is designed to provide dense, multilingual embeddings with features like batch processing, automatic GPU/CPU detection, and strict security guards.

---

## πŸš€ Key Features

- **State-of-the-Art Model**: Uses `BAAI/bge-m3` for high-quality multilingual embeddings. U can Change it also. with any huggigface model name just make sure it gives 1024 size vector embedding for consistency.
- **FastAPI Powered**: Asynchronous, high-performance API endpoints.
- **Intelligent Device Management**: Automatically detects NVIDIA GPUs (CUDA) or falls back to CPU.
- **Robust Batching**: Efficiently processes large lists of text with automatic chunking and OOM (Out of Memory) recovery.
- **Strict Security**: Built-in guard for API Key enforcement.
- **Premium Logging**: Beautiful, colorized, and structured logs for easy debugging and monitoring.
- **Reliability**: Integrated retry logic for model loading and processing.

---

## πŸ› οΈ Tech Stack

- **Language**: Python 3.11+
- **Web Framework**: FastAPI
- **Deep Learning**: PyTorch & HuggingFace Transformers
- **Validation**: Pydantic V2 & Pydantic Settings
- **Logging**: Colorlog
- **Process Manager**: Uvicorn

---

## πŸ“₯ Installation

It is highly recommended to use a virtual environment to keep dependencies local to the project.

1.  **Clone the project** and navigate to the directory.
2.  **Create a virtual environment**:
    ```cmd

    python -m venv venv

    ```

3.  **Activate the environment**:

    - Windows: `venv\Scripts\activate`

    - Linux/Mac: `source venv/bin/activate`

4.  **Install dependencies**:

    ```cmd

    pip install -r requirements.txt

    ```


---

## βš™οΈ Configuration

Copy the `.env.example` file to `.env` and configure your settings. The application uses these variables to control everything from security to model performance.

```env

# -----------------------------

# Security / Access

# -----------------------------

EMBED_API_KEY=your_secret_key_here

HUGGING_FACE_TOKEN=your_free_token_with_repo_read_access



# -----------------------------

# Model & Device Settings

# -----------------------------

MODEL_NAME=BAAI/bge-m3       # Best if u copy this repo to your personal repo and use updated model name

DEVICE=                      # Leave empty for auto-detection, or use "cuda" / "cpu"

BATCH_SIZE=8                 # Adjust based on your VRAM/RAM

MAX_LENGTH=1024              # Max token length



# -----------------------------

# Server & Reliability

# -----------------------------

RETRY_ATTEMPTS=3             # Retries for model loading/processing

RETRY_BACKOFF_SECONDS=2.0    # Wait time between retries

HOST=0.0.0.0

PORT=8000

WORKERS=1                    # Number of Uvicorn workers

LOG_LEVEL=INFO               # DEBUG, INFO, WARNING, ERROR, CRITICAL

```

---

## 🏁 Running Locally

Start the server using Python's module runner:

```cmd

python -m app.main

```

The server will automatically log the detected device (GPU/CPU) and start listening on the configured port.

---

## 🐳 Docker Deployment

You can deploy the server easily using Docker and Docker Compose. This is the recommended way for production.

### 1. Build and Run

```bash

docker-compose up --build -d

```

This will start the server on the port defined in your `.env` (default `7860`).
# Note: After building the image if u want to run the image without code just use this command
# docker run -d --restart unless-stopped --name embed-server -p 7860:7860 --env-file .env vector-embedding-server-embed-server:latest
# here vector-embedding-server-embed-server:latest is the image name which is build
# .env should have the Configuration specified in the .env.example file

### 2. GPU Acceleration (NVIDIA)

To use your NVIDIA GPU with Docker, you must have the **NVIDIA Container Toolkit** installed on your host system.

1.  Open `docker-compose.yml`.
2.  Uncomment the `deploy` section at the bottom of the file:
    ```yaml

    deploy:

      resources:

        reservations:

          devices:

            - driver: nvidia

              count: all

              capabilities: [gpu]

    ```

3.  Restart the container:

    ```bash

    docker-compose up -d --force-recreate

    ```


The server logs will confirm if `cuda` is being used.

---

## πŸš€ Run Docker Image (Without Source Code)

After building the image, run the container using:
```

docker run -d --restart unless-stopped --name embed-server -p 7860:7860 --env-file .env vector-embedding-server-embed-server:latest

```
# Requirements

- The Docker image vector-embedding-server-embed-server:latest must already be built.
- A .env file must exist in the same directory.

# Environment Setup

Create your .env file based on:
```

.env.example

```
Example:
```

cp .env.example .env

```
Update the values inside .env before running the container.

# Check Running Container
```

docker ps

```
You should see embed-server listed as running.

---

## πŸ“‘ API Endpoints

### 1. Health Check

`GET /embed/health`  
Returns the server status and whether the model is loaded.

### 2. Single Embedding

`POST /embed/single`  
Generates an embedding for a single text string.

### 3. Batch Embedding

`POST /embed/batch`  
Generates embeddings for a list of strings efficiently.

---

## πŸ§ͺ Documentation & Testing

Once the server is running, you can access the interactive API documentation at:

- **Swagger UI**: `http://localhost:7860/docs`
- **Redoc**: `http://localhost:7860/redoc`

### Test with CURL

**Note**: The server requires `x-api-key` header as configured in your `.env`.

#### Single Embedding Request:

```bash

curl -X POST http://localhost:7860/embed/single \

     -H "Content-Type: application/json" \

     -H "x-api-key: MY_SECURE_KEY" \

     -d '{"text": "Hello world, this is a test."}'

```

#### Batch Embedding Request:

```bash

curl -X POST http://localhost:7860/embed/batch \

     -H "Content-Type: application/json" \

     -H "x-api-key: MY_SECURE_KEY" \

     -d '{

       "texts": [

         "First sentence to embed.",

         "BGE-M3 handles multilingual text very well."

       ]

     }'

```

---

## πŸ”§ Troubleshooting

### `OSError: Could not create safetensors conversion PR`

If you see this error in your logs, it means the `transformers` library is trying to auto-convert your PyTorch model to SafeTensors format but failing (often due to repo permissions or structure).

**Solution:**

We have included a script to manually convert and upload the SafeTensors model to your Hugging Face repository.

**Prerequisites:**
1.  **Write Access**: You must have **write access** to the Hugging Face repository defined in `MODEL_NAME`.
2.  **Environment Variable**: Ensure your `HUGGING_FACE_TOKEN` in `.env` has **write permissions**.

**Instructions:**
Run this script **ONLY ONCE** and **ONLY** if you are facing the error:

```bash

python -m scripts.convert_safetensors

```

This will:
1.  Load your current model.
2.  Convert it to SafeTensors format locally.
3.  Verify the converted model loads correctly.
4.  Upload the `model.safetensors` file to your repository.

Once done, the "safetensors not found" error will disappear, and your model loading speed will improve.

---

## πŸ‘¨β€πŸ’» Developed By

**FAYSAL AHMMED**