diff --git a/backend/src/baserow/config/settings/base.py b/backend/src/baserow/config/settings/base.py index b2823e755f..157bf8e65c 100644 --- a/backend/src/baserow/config/settings/base.py +++ b/backend/src/baserow/config/settings/base.py @@ -2147,6 +2147,10 @@ BASEROW_MAX_HEALTHY_CELERY_QUEUE_SIZE = int( BASEROW_USE_LOCAL_CACHE = str_to_bool(os.getenv("BASEROW_USE_LOCAL_CACHE", "true")) BASEROW_EMBEDDINGS_API_URL = os.getenv("BASEROW_EMBEDDINGS_API_URL", "") +# An embeddings service on a GPU is faster with more. It accepts at most 256. +BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST = min( + max(int(os.getenv("BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST", "") or 8), 1), 256 +) # -- CACHALOT SETTINGS -- diff --git a/backend/src/baserow/core/embeddings.py b/backend/src/baserow/core/embeddings.py index b547d50777..4f822823d7 100644 --- a/backend/src/baserow/core/embeddings.py +++ b/backend/src/baserow/core/embeddings.py @@ -1,3 +1,5 @@ +import json + from django.conf import settings import httpx @@ -6,6 +8,9 @@ from loguru import logger from baserow.core.pgvector import DEFAULT_EMBEDDING_DIMENSIONS, is_pgvector_enabled +# The embeddings service rejects larger request bodies. +MAX_REQUEST_BYTES = 2**20 + class EmbeddingsServiceError(Exception): # The underlying `httpx` error is only logged because its message contains the @@ -13,6 +18,29 @@ class EmbeddingsServiceError(Exception): pass +def _request_batches(texts: list[str], batch_size: int) -> list[list[str]]: + """ + Splits the texts into the request bodies the embeddings service accepts. Texts + in, for example, Chinese take up to three bytes per character. + """ + + batches = [] + size = 0 + for text in texts: + # Encoded like `httpx` does, with a comma between texts. + text_size = len(json.dumps(text, ensure_ascii=False).encode()) + 1 + if ( + not batches + or len(batches[-1]) == batch_size + or size + text_size > MAX_REQUEST_BYTES + ): + batches.append([]) + size = len('{"texts":[]}') + batches[-1].append(text) + size += text_size + return batches + + class BaserowEmbedder: def __init__( self, @@ -30,14 +58,13 @@ class BaserowEmbedder: self.dimensions = dimensions self.timeout = timeout - def _embed(self, texts: list[str], batch_size=8) -> list[list[float]]: + def _embed(self, texts: list[str]) -> list[list[float]]: + batch_size = settings.BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST embeddings = [] client = httpxClient(base_url=self.api_url, timeout=self.timeout) try: - for i in range(0, len(texts), batch_size): - response = client.post( - "/embed", json={"texts": texts[i : i + batch_size]} - ) + for batch in _request_batches(texts, batch_size): + response = client.post("/embed", json={"texts": batch}) response.raise_for_status() embeddings.extend(response.json()["embeddings"]) # An invalid response, like the error page of a proxy, is retried like an diff --git a/backend/tests/baserow/core/test_embeddings.py b/backend/tests/baserow/core/test_embeddings.py index c2cf5bf8c2..0008be4a32 100644 --- a/backend/tests/baserow/core/test_embeddings.py +++ b/backend/tests/baserow/core/test_embeddings.py @@ -1,3 +1,4 @@ +import json from unittest.mock import patch from django.test import override_settings @@ -37,6 +38,50 @@ def test_embedder_treats_an_invalid_response_as_a_service_error(): BaserowEmbedder("http://test")(["text"]) +@override_settings(BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST=3) +def test_embedder_sends_the_configured_number_of_texts_per_request(): + request_sizes = [] + + def embed(request): + texts = json.loads(request.content)["texts"] + request_sizes.append(len(texts)) + return httpx.Response( + 200, json={"embeddings": [[float(len(text))] for text in texts]} + ) + + real_client = httpx.Client + with patch( + "baserow.core.embeddings.httpxClient", + lambda **kwargs: real_client(transport=httpx.MockTransport(embed), **kwargs), + ): + embeddings = BaserowEmbedder("http://test", dimensions=1)( + ["a", "bb", "ccc", "dddd"] + ) + + assert request_sizes == [3, 1] + assert embeddings == [[1.0], [2.0], [3.0], [4.0]] + + +@override_settings(BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST=256) +def test_embedder_keeps_requests_within_the_body_limit_of_the_service(): + def embed(request): + # Like the embeddings service. + if len(request.content) > 2**20: + return httpx.Response(413, json={"error": "Request body over 1 MiB"}) + texts = json.loads(request.content)["texts"] + return httpx.Response(200, json={"embeddings": [[1.0]] * len(texts)}) + + real_client = httpx.Client + with patch( + "baserow.core.embeddings.httpxClient", + lambda **kwargs: real_client(transport=httpx.MockTransport(embed), **kwargs), + ): + # Chunks of 2000 characters, of three bytes each. + embeddings = BaserowEmbedder("http://test", dimensions=1)(["文" * 2000] * 256) + + assert len(embeddings) == 256 + + def test_embedder_pads_vectors(): with patch("baserow.core.embeddings.httpxClient") as client: client.return_value.post.return_value.json.return_value = { diff --git a/deploy/cloudron/embeddings/DESCRIPTION.md b/deploy/cloudron/embeddings/DESCRIPTION.md index cabeca549f..b161f69628 100644 --- a/deploy/cloudron/embeddings/DESCRIPTION.md +++ b/deploy/cloudron/embeddings/DESCRIPTION.md @@ -1,5 +1,5 @@ ``` -cloudron install -l embeddings.{YOUR_DOMAIN} --image baserow/embeddings:1.1.0 +cloudron install -l embeddings.{YOUR_DOMAIN} --image baserow/embeddings:1.1.1 ``` In the Baserow app in Cloudron do: diff --git a/deploy/helm/baserow/README.md b/deploy/helm/baserow/README.md index 1681440231..d3831e20cf 100644 --- a/deploy/helm/baserow/README.md +++ b/deploy/helm/baserow/README.md @@ -520,7 +520,7 @@ caddy: | --------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------- | | `baserow-embeddings.enabled` | Set to true to enable the Baserow Embeddings service. | `false` | | `baserow-embeddings.image.repository` | Docker image repository for the Embeddings service. | `embeddings` | -| `baserow-embeddings.image.tag` | Docker image tag for the Embeddings service, which is versioned separately from Baserow. | `1.1.0` | +| `baserow-embeddings.image.tag` | Docker image tag for the Embeddings service, which is versioned separately from Baserow. | `1.1.1` | | `baserow-embeddings.workingDir` | Working directory for the container, empty to use the image's own. | `""` | | `baserow-embeddings.resources` | Resource requests and limits for the Embeddings service. | | | `baserow-embeddings.autoscaling.enabled` | Enable autoscaling for the Embeddings service. | `false` | diff --git a/deploy/helm/baserow/values.yaml b/deploy/helm/baserow/values.yaml index cb0d8af0e7..8848a3cde5 100644 --- a/deploy/helm/baserow/values.yaml +++ b/deploy/helm/baserow/values.yaml @@ -688,7 +688,7 @@ baserow-embeddings: enabled: false image: repository: embeddings - tag: "1.1.0" + tag: "1.1.1" workingDir: "" resources: requests: diff --git a/docker-compose.no-caddy.yml b/docker-compose.no-caddy.yml index ab42c806c0..9696ae9399 100644 --- a/docker-compose.no-caddy.yml +++ b/docker-compose.no-caddy.yml @@ -292,6 +292,7 @@ x-backend-variables: BASEROW_ENTERPRISE_ASSISTANT_LLM_MODEL: BASEROW_ENTERPRISE_ASSISTANT_LLM_TEMPERATURE: BASEROW_EMBEDDINGS_API_URL: + BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST: BASEROW_SEMANTIC_SEARCH_CHUNK_SIZE: BASEROW_SEMANTIC_SEARCH_CHUNK_OVERLAP: BASEROW_SEMANTIC_SEARCH_MAX_CHUNKS_PER_CELL: diff --git a/docker-compose.yml b/docker-compose.yml index 3d2cbb86a0..00c90bd30e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -327,6 +327,7 @@ x-backend-variables: BASEROW_ENTERPRISE_ASSISTANT_LLM_MODEL: BASEROW_ENTERPRISE_ASSISTANT_LLM_TEMPERATURE: BASEROW_EMBEDDINGS_API_URL: + BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST: BASEROW_SEMANTIC_SEARCH_CHUNK_SIZE: BASEROW_SEMANTIC_SEARCH_CHUNK_OVERLAP: BASEROW_SEMANTIC_SEARCH_MAX_CHUNKS_PER_CELL: diff --git a/docs/installation/ai-assistant.md b/docs/installation/ai-assistant.md index cadebcebf9..161f81fb21 100644 --- a/docs/installation/ai-assistant.md +++ b/docs/installation/ai-assistant.md @@ -182,9 +182,20 @@ service and point Baserow at it. ### Run the embeddings container ```bash -docker run -d --name baserow-embeddings -p 80:80 baserow/embeddings:1.1.0 +docker run -d --name baserow-embeddings -p 80:80 baserow/embeddings:1.1.1 ``` +To embed large volumes faster, for example for semantic search on big tables, run the +GPU image on a host with an NVIDIA GPU and the NVIDIA Container Toolkit instead, and set +`BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST=64` in Baserow: + +```bash +docker run -d --name baserow-embeddings --gpus all -p 80:80 baserow/embeddings:1.1.1-gpu +``` + +See the [embeddings README](https://github.com/baserow/baserow/blob/develop/embeddings/README.md) +for the requirements and how to run several containers on one GPU. + ### Point Baserow to it ```dotenv diff --git a/docs/installation/configuration.md b/docs/installation/configuration.md index 5c7ce24b9b..db4fdcbb27 100644 --- a/docs/installation/configuration.md +++ b/docs/installation/configuration.md @@ -295,7 +295,6 @@ until you make a model available to Kuma and select it under **AI features**; se ### AI-assistant Configuration | Name | Description | Defaults | | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | -| BASEROW\_EMBEDDINGS\_API\_URL | If not empty, the AI-assistant will use this as embedding server for the knowledge base lookup. Must point to a container running this image: https://hub.docker.com/r/baserow/embeddings | "" (empty string) | | BASEROW\_ENTERPRISE\_ASSISTANT\_LLM\_MODEL | **Deprecated.** The AI-assistant uses this model until you select one under **AI features** in AI providers. Provide in pydantic-ai format like `groq:openai/gpt-oss-120b` or `bedrock:openai.gpt-oss-120b-1:0`. Note that additional API keys must be provided as environment variable depending on the provider. Instructions can be found at https://baserow.io/docs/installation/ai-assistant | "" (empty string) | | AWS\_BEARER\_TOKEN\_BEDROCK | If the BASEROW\_ENTERPRISE\_ASSISTANT\_LLM\_MODEL uses a bedrock provider, then this environment variable must be set. Instructions on how to obtain: https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-use.html | "" (empty string) | | AWS\_REGION\_NAME | If the BASEROW\_ENTERPRISE\_ASSISTANT\_LLM\_MODEL uses a bedrock provider, then the AWS region for the AI-assistant can be provided here. | us-east-1 | @@ -304,6 +303,12 @@ until you make a model available to Kuma and select it under **AI features**; se | OLLAMA\_API\_KEY | If the BASEROW\_ENTERPRISE\_ASSISTANT\_LLM\_MODEL uses an ollama provider (e.g. `ollama:gpt-oss:120b`), then the Ollama API key can be provided here. | "" (empty string) | | UDSPY\_LM\_OPENAI\_COMPATIBLE\_BASE\_URL | If the BASEROW\_ENTERPRISE\_ASSISTANT\_LLM\_MODEL uses an openai provider (e.g. `openai:gpt-5-nano`), then the base URL can be changed here. This can be used to point to a different OpenAI compatible API like Azure, for example. | "" (empty string) | +### Embeddings configuration +| Name | Description | Defaults | +| ---- | ----------- | -------- | +| BASEROW\_EMBEDDINGS\_API\_URL | If not empty, the AI-assistant knowledge base and semantic search use this embeddings server. Must point to a container running this image: https://hub.docker.com/r/baserow/embeddings | "" (empty string) | +| BASEROW\_EMBEDDINGS\_TEXTS\_PER\_REQUEST | The number of texts sent to the embeddings server per request, at most 256. Increase it for an embeddings server on a GPU, like the `-gpu` image. | 8 | + ### Semantic search configuration | Name | Description | Defaults | | ---- | ----------- | -------- | diff --git a/embeddings/Dockerfile b/embeddings/Dockerfile index 38c7838c57..667129bbaf 100644 --- a/embeddings/Dockerfile +++ b/embeddings/Dockerfile @@ -15,7 +15,9 @@ COPY --from=builder /model /model RUN apt-get update && apt-get upgrade -y && rm -rf /var/lib/apt/lists/* WORKDIR /app -COPY requirements.txt . +# requirements-gpu.txt builds the GPU image. +ARG REQUIREMENTS=requirements.txt +COPY ${REQUIREMENTS} requirements.txt # Nothing installs packages at runtime, so pip only adds CVEs. RUN pip install --no-cache-dir --root-user-action=ignore --no-deps \ @@ -25,7 +27,8 @@ RUN pip install --no-cache-dir --root-user-action=ignore --no-deps \ COPY app.py . # --no-deps can't catch a missing dependency, so fail the build instead of startup. -RUN python -B -c "import app" +# There's no GPU while building, but the CUDA libraries can be loaded. +RUN EMBEDDINGS_DEVICE=cpu python -B -c "import app; app.load_cuda_libraries()" EXPOSE 80 CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "80"] diff --git a/embeddings/README.md b/embeddings/README.md index b880eb4a8c..3505d7459a 100644 --- a/embeddings/README.md +++ b/embeddings/README.md @@ -37,30 +37,76 @@ The service uses a multi-stage Docker build: ## Docker -### Run locally +There are two images. Both create the same vectors, so they can be swapped without re-embedding. -``` -docker run -p 127.0.0.1:8080:80 baserow/embeddings:1.1.0 +| Image | Runs on | Platforms | Size | +| ------------------------------ | --------------------- | ---------------------------- | ------- | +| `baserow/embeddings:1.1.1` | CPU | `linux/amd64`, `linux/arm64` | ~0.6 GB | +| `baserow/embeddings:1.1.1-gpu` | NVIDIA GPU, with CUDA | `linux/amd64` | ~2.2 GB | + +The CPU image is enough for the AI assistant's knowledge base and for searching. The GPU image is only worth it to embed large volumes, like enabling semantic search on big tables. + +### Run the CPU image + +```bash +docker run -p 127.0.0.1:8080:80 baserow/embeddings:1.1.1 ``` -### Build for publish +The service will be available at `http://localhost:8080`. +### Run the GPU image + +The host needs an NVIDIA driver of version 525 or newer and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). + +```bash +docker run --gpus all -p 127.0.0.1:8080:80 baserow/embeddings:1.1.1-gpu ``` + +- It fails to start when no GPU is usable, instead of silently falling back to the CPU. Set `EMBEDDINGS_DEVICE=cpu` to run it without a GPU anyway. +- It processes 64 texts at a time instead of 8, because a GPU only runs at full speed with bigger batches. Set `BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST` to 64 in Baserow, so that its requests fill those batches. +- Requests are processed one at a time, while the CPU handles tokenization and JSON. Run two to four containers on one GPU to keep it busy. On an NVIDIA RTX A4000, four containers embedded about 1,200 texts of 200 to 1,000 characters per second, against 18 per second for the CPU image with 1 CPU. +- Its vectors differ from the CPU image's only in the last decimals, which doesn't noticeably change cosine distances. + +### Build and publish + +Bump the version in the tags, and in the run commands above, for every release. Publish both images with the same version. + +CPU image: + +```bash docker buildx build \ --platform linux/amd64,linux/arm64 \ - -t baserow/embeddings:1.1.0 \ + -t baserow/embeddings:1.1.1 \ -t baserow/embeddings:latest \ --push . ``` +GPU image, which only supports `linux/amd64`: + +```bash +docker buildx build \ + --platform linux/amd64 \ + --build-arg REQUIREMENTS=requirements-gpu.txt \ + -t baserow/embeddings:1.1.1-gpu \ + -t baserow/embeddings:latest-gpu \ + --push . +``` + ### Build and run from source +CPU image: + ```bash docker build -t baserow-embeddings . docker run -p 127.0.0.1:8080:80 baserow-embeddings ``` -The service will be available at `http://localhost:8080`. +GPU image: + +```bash +docker build --build-arg REQUIREMENTS=requirements-gpu.txt -t baserow-embeddings-gpu . +docker run --gpus all -p 127.0.0.1:8080:80 baserow-embeddings-gpu +``` ### Configuration @@ -68,6 +114,7 @@ The service will be available at `http://localhost:8080`. | ------------------------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | `EMBEDDINGS_NUM_THREADS` | Number of CPU threads used for inference, as a positive integer. Requests are processed one at a time, using all threads. | The container's CPU limit rounded up, or all CPUs without a limit. | | `EMBEDDINGS_MODEL_DIR` | Directory with the model files. Change it only to run the service outside Docker. | `/model` | +| `EMBEDDINGS_DEVICE` | `cpu` or `gpu`. Set `cpu` to run the GPU image without a GPU. | `gpu` in the GPU image, otherwise `cpu`. | ## API @@ -186,6 +233,8 @@ Python 3.14, with every runtime package pinned in [requirements.txt](requirement To update a package, install the new versions of `numpy`, `onnxruntime`, `starlette` and `uvicorn` into a clean Python 3.14 environment, add `tokenizers` with `--no-deps`, and write the output of `pip freeze` below the comment at the top of `requirements.txt`. The build stage installs `huggingface_hub`, pinned in the Dockerfile and above, with `-c requirements.txt`, so check that it still installs. After a bump, compare a few vectors with the previous image. +[requirements-gpu.txt](requirements-gpu.txt) pins the GPU image the same way, with `onnxruntime-gpu[cuda,cudnn]` instead of `onnxruntime`, in a `linux/amd64` environment. Keep `onnxruntime-gpu` at the same version as `onnxruntime`. + ## License This service is part of the Baserow project. See the main repository for license information. diff --git a/embeddings/app.py b/embeddings/app.py index 60ed7cd902..36640cb7ff 100644 --- a/embeddings/app.py +++ b/embeddings/app.py @@ -1,4 +1,5 @@ import asyncio +import ctypes import json import math import os @@ -15,7 +16,9 @@ from tokenizers import Tokenizer MODEL_DIR = os.environ.get("EMBEDDINGS_MODEL_DIR", "/model") # onnxruntime keeps the memory of its largest batch, so cap the batch size. -INFERENCE_BATCH_SIZE = 8 +CPU_BATCH_SIZE = 8 +# A GPU is only used fully with bigger batches, and has the memory for them. +GPU_BATCH_SIZE = 64 # The tokenizer reads whole texts before truncating them, so bound the input. MAX_BODY_BYTES = 2**20 # Each text adds about 8 KB of JSON to the response. @@ -65,12 +68,50 @@ def inference_threads() -> int: return int(value) +# Only the GPU image installs an onnxruntime that supports CUDA. +gpu_image = "CUDAExecutionProvider" in ort.get_available_providers() + + +def use_gpu() -> bool: + value = os.environ.get("EMBEDDINGS_DEVICE", "").strip().lower() + if not value: + return gpu_image + if value not in ("cpu", "gpu"): + raise ValueError("EMBEDDINGS_DEVICE must be cpu or gpu") + if value == "gpu" and not gpu_image: + raise ValueError("EMBEDDINGS_DEVICE=gpu requires the GPU image") + return value == "gpu" + + +def load_cuda_libraries() -> None: + if not gpu_image: + return + # The GPU image installs CUDA as Python packages, which onnxruntime only finds + # when they are preloaded. + ort.preload_dlls() + # A missing library is otherwise only a warning before falling back to the CPU. + # Loading them doesn't need a GPU, so the build checks this too. + ctypes.CDLL( + os.path.join( + os.path.dirname(ort.__file__), "capi", "libonnxruntime_providers_cuda.so" + ) + ) + + +gpu = use_gpu() +if gpu: + load_cuda_libraries() +providers = ["CUDAExecutionProvider"] if gpu else [] +providers.append("CPUExecutionProvider") + session_options = ort.SessionOptions() session_options.intra_op_num_threads = inference_threads() model_path = os.path.join(MODEL_DIR, "model.onnx") -session = ort.InferenceSession( - model_path, session_options, providers=["CPUExecutionProvider"] -) +session = ort.InferenceSession(model_path, session_options, providers=providers) +# onnxruntime silently falls back to the CPU when CUDA fails to load. +if gpu and session.get_providers()[0] != "CUDAExecutionProvider": + raise RuntimeError("CUDA could not be used, see the onnxruntime error above") +inference_batch_size = GPU_BATCH_SIZE if gpu else CPU_BATCH_SIZE # Inference already uses every thread, so parallel requests would oversubscribe. inference_lock = threading.Lock() @@ -111,8 +152,8 @@ def embed_batch(texts: list[str]) -> list[list[float]]: def compute_embeddings(texts: list[str]) -> list[list[float]]: embeddings = [] with inference_lock: - for start in range(0, len(texts), INFERENCE_BATCH_SIZE): - embeddings.extend(embed_batch(texts[start : start + INFERENCE_BATCH_SIZE])) + for start in range(0, len(texts), inference_batch_size): + embeddings.extend(embed_batch(texts[start : start + inference_batch_size])) return embeddings diff --git a/embeddings/requirements-gpu.txt b/embeddings/requirements-gpu.txt new file mode 100644 index 0000000000..65febe29ab --- /dev/null +++ b/embeddings/requirements-gpu.txt @@ -0,0 +1,21 @@ +# Installed with --no-deps: tokenizers' huggingface-hub is unused. +anyio==4.15.1 +click==8.5.0 +flatbuffers==25.12.19 +h11==0.16.0 +idna==3.20 +numpy==2.5.4 +nvidia-cublas-cu12==12.9.2.10 +nvidia-cuda-nvrtc-cu12==12.9.86 +nvidia-cuda-runtime-cu12==12.9.79 +nvidia-cudnn-cu12==9.27.0.42 +nvidia-cufft-cu12==11.4.1.4 +nvidia-curand-cu12==10.3.10.19 +nvidia-nvjitlink-cu12==12.9.86 +onnxruntime-gpu==1.26.0 +packaging==26.3 +protobuf==7.36.2 +starlette==1.8.0 +tokenizers==0.23.3 +typing_extensions==4.16.0 +uvicorn==0.54.0 diff --git a/enterprise/backend/src/baserow_enterprise/semantic_search/handler.py b/enterprise/backend/src/baserow_enterprise/semantic_search/handler.py index d267feafd0..a8d484b407 100644 --- a/enterprise/backend/src/baserow_enterprise/semantic_search/handler.py +++ b/enterprise/backend/src/baserow_enterprise/semantic_search/handler.py @@ -796,7 +796,10 @@ class _ChunkBatch: (row_id, chunk_index, content_hash, content) for chunk_index, content in enumerate(contents) ) - if len(self.chunks) >= EMBEDDING_BATCH_CHUNKS: + # Otherwise more texts per request wouldn't have any effect. + if len(self.chunks) >= max( + EMBEDDING_BATCH_CHUNKS, settings.BASEROW_EMBEDDINGS_TEXTS_PER_REQUEST + ): self.save() def save(self):