Sync from davanstrien/uv-scripts via hub-sync
Browse files- README.md +25 -2
- generate-embeddings-saturate.py +367 -0
- generate-embeddings-vllm.py +2 -0
README.md
CHANGED
|
@@ -13,13 +13,14 @@ Generate embeddings for a Hugging Face dataset — text or images — with one c
|
|
| 13 |
cloud GPU, no infra. The output lands back on the Hub as a new dataset (or, with the Lance
|
| 14 |
variant, as a **searchable vector index you can query over `hf://` without downloading**).
|
| 15 |
|
| 16 |
-
There is one simple default and
|
| 17 |
their dependencies (sentence-transformers vs vLLM vs Lance) are too different to share one env.
|
| 18 |
|
| 19 |
| Script | Use it for | Engine |
|
| 20 |
|---|---|---|
|
| 21 |
| `generate-embeddings.py` | The default. Text or images. Simple, fast, runs anywhere. | sentence-transformers |
|
| 22 |
-
| `generate-embeddings-
|
|
|
|
| 23 |
| `embed-to-lance.py` | Get a **searchable vector index as a Hub dataset** (the "vector DB" path). | sentence-transformers + Lance |
|
| 24 |
| `launch-embedding-fleet.py` | **Fan one run out across N parallel Jobs** (+ `consolidate-shards.py`). | run_uv_job + Buckets |
|
| 25 |
|
|
@@ -39,6 +40,28 @@ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
|
| 39 |
|
| 40 |
Always try `--max-samples 100 --private` first.
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
## Fan-out: N Jobs in parallel
|
| 43 |
|
| 44 |
One L4 does ~900 rows/s with `all-MiniLM-L6-v2`; a fleet of 8 does ~7k. `launch-embedding-fleet.py`
|
|
|
|
| 13 |
cloud GPU, no infra. The output lands back on the Hub as a new dataset (or, with the Lance
|
| 14 |
variant, as a **searchable vector index you can query over `hf://` without downloading**).
|
| 15 |
|
| 16 |
+
There is one simple default and a few variants; they are separate single-file scripts because
|
| 17 |
their dependencies (sentence-transformers vs vLLM vs Lance) are too different to share one env.
|
| 18 |
|
| 19 |
| Script | Use it for | Engine |
|
| 20 |
|---|---|---|
|
| 21 |
| `generate-embeddings.py` | The default. Text or images. Simple, fast, runs anywhere. | sentence-transformers |
|
| 22 |
+
| `generate-embeddings-saturate.py` | **Large text runs.** A vLLM server in the Job, driven by [saturate](https://github.com/davanstrien/saturate). One row out per row in, resumable. | vLLM server + saturate |
|
| 23 |
+
| `generate-embeddings-vllm.py` | The older vLLM path (offline engine, unpinned `vllm`). Use `generate-embeddings-saturate.py` instead. | vLLM pooling |
|
| 24 |
| `embed-to-lance.py` | Get a **searchable vector index as a Hub dataset** (the "vector DB" path). | sentence-transformers + Lance |
|
| 25 |
| `launch-embedding-fleet.py` | **Fan one run out across N parallel Jobs** (+ `consolidate-shards.py`). | run_uv_job + Buckets |
|
| 26 |
|
|
|
|
| 40 |
|
| 41 |
Always try `--max-samples 100 --private` first.
|
| 42 |
|
| 43 |
+
## Large runs: `generate-embeddings-saturate.py`
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
hf jobs uv run \
|
| 47 |
+
https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings-saturate.py \
|
| 48 |
+
stanfordnlp/imdb your-name/imdb-embeddings --column text --max-samples 100
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
The script's header sets the `vllm/vllm-openai:v0.30.0` image, `a10g-small` and the `HF_TOKEN`
|
| 52 |
+
secret, so the command needs no job flags. Measured on one A10G with 20,000 IMDb reviews of up
|
| 53 |
+
to 300 words, one run each, embedding step only:
|
| 54 |
+
|
| 55 |
+
| Model | `generate-embeddings.py` | `generate-embeddings-saturate.py` |
|
| 56 |
+
|---|---|---|
|
| 57 |
+
| Qwen/Qwen3-Embedding-0.6B | 96 rows/s | 187 rows/s |
|
| 58 |
+
| BAAI/bge-m3 | 71 rows/s | 276 rows/s |
|
| 59 |
+
|
| 60 |
+
The server is ready 100 to 120 seconds after it starts, so `generate-embeddings.py` is quicker
|
| 61 |
+
for a few hundred rows. Texts are cut at the model's own maximum length unless you pass
|
| 62 |
+
`--max-seq-len`. Prompts follow the same rule as below: `--prompt`, then the model's registered
|
| 63 |
+
document prompt, then the known-family table.
|
| 64 |
+
|
| 65 |
## Fan-out: N Jobs in parallel
|
| 66 |
|
| 67 |
One L4 does ~900 rows/s with `all-MiniLM-L6-v2`; a fleet of 8 does ~7k. `launch-embedding-fleet.py`
|
generate-embeddings-saturate.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "saturate[hf]==0.3.1",
|
| 5 |
+
# "huggingface-hub>=1.12",
|
| 6 |
+
# ]
|
| 7 |
+
#
|
| 8 |
+
# [tool.hf-jobs]
|
| 9 |
+
# image = "vllm/vllm-openai:v0.30.0"
|
| 10 |
+
# flavor = "a10g-small"
|
| 11 |
+
# timeout = "2h"
|
| 12 |
+
# secrets = ["HF_TOKEN"]
|
| 13 |
+
# ///
|
| 14 |
+
"""
|
| 15 |
+
Generate embeddings for a text column of a Hugging Face dataset with a vLLM server, and write
|
| 16 |
+
them to a new dataset on the Hub.
|
| 17 |
+
|
| 18 |
+
This is the fast variant for large runs. The script starts a vLLM server on the Job's GPU and
|
| 19 |
+
sends it one text per request with `saturate`, which sets the number of requests in flight.
|
| 20 |
+
vLLM groups the requests into batches itself. For a first try, for image embeddings, or for a
|
| 21 |
+
model vLLM does not serve, use generate-embeddings.py (sentence-transformers) instead.
|
| 22 |
+
|
| 23 |
+
hf jobs uv run \\
|
| 24 |
+
https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings-saturate.py \\
|
| 25 |
+
stanfordnlp/imdb your-username/imdb-embeddings --column text --max-samples 100
|
| 26 |
+
|
| 27 |
+
Measured on one A10G with 20,000 IMDb reviews of up to 300 words (one run each):
|
| 28 |
+
Qwen/Qwen3-Embedding-0.6B 187 rows/s, against 96 rows/s for generate-embeddings.py.
|
| 29 |
+
BAAI/bge-m3 276 rows/s, against 71 rows/s for generate-embeddings.py at full precision.
|
| 30 |
+
The server was ready 100 to 120 seconds after it started, so a run of a few hundred rows is
|
| 31 |
+
quicker with generate-embeddings.py.
|
| 32 |
+
|
| 33 |
+
On Jobs, the [tool.hf-jobs] header sets the vllm/vllm-openai:v0.30.0 image, the a10g-small
|
| 34 |
+
flavor, a 2h timeout and the HF_TOKEN secret (`hf` CLI 1.32+). --flavor and --timeout before
|
| 35 |
+
the script override it.
|
| 36 |
+
|
| 37 |
+
PROMPTS: many retrieval models need a different prefix for documents and for queries. The
|
| 38 |
+
script embeds documents by default and picks the prefix in this order: --prompt, then the
|
| 39 |
+
"document" prompt the model registers in config_sentence_transformers.json, then a small table
|
| 40 |
+
of known families (e5, nomic), then no prefix. --query-mode uses the query side. The prefix is
|
| 41 |
+
logged and written to the dataset card.
|
| 42 |
+
|
| 43 |
+
LONG TEXTS: each text is cut at the model's own maximum length, which the server reports
|
| 44 |
+
(for example 8,192 tokens for BAAI/bge-m3). Long documents cost more to embed. Pass
|
| 45 |
+
--max-seq-len 512 for a shorter cut and a predictable cost; a value above the model's maximum
|
| 46 |
+
is lowered to it. generate-embeddings.py cuts at 512 tokens by default. The cut is logged and
|
| 47 |
+
written to the dataset card.
|
| 48 |
+
|
| 49 |
+
OUTPUT: one record per input row, with `id`, the text column, the embedding column, `model`,
|
| 50 |
+
`prompt_tokens` and `error`. A row that failed has a message in `error` and no embedding.
|
| 51 |
+
Run the same command again to resume: rows already written are skipped. Add --retry-errors to
|
| 52 |
+
try the failed rows again. A retry adds a second record for the row and keeps the old error
|
| 53 |
+
record, so after a --retry-errors run drop the records that have an `error`, or read the
|
| 54 |
+
output with `saturate.read_output`, which keeps one record per id (a success over an earlier
|
| 55 |
+
error).
|
| 56 |
+
"""
|
| 57 |
+
import argparse
|
| 58 |
+
import json
|
| 59 |
+
import os
|
| 60 |
+
import re
|
| 61 |
+
import shlex
|
| 62 |
+
import sys
|
| 63 |
+
import time
|
| 64 |
+
import urllib.request
|
| 65 |
+
|
| 66 |
+
SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings-saturate.py"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def known_family_prefixes(model_id):
|
| 70 |
+
"""Best-effort (query_prefix, doc_prefix) for common families whose convention is
|
| 71 |
+
documented in the model card but NOT registered in config_sentence_transformers.json.
|
| 72 |
+
Returns None if unknown. Overridable with --prompt / --no-auto-prompt.
|
| 73 |
+
|
| 74 |
+
Verified 2026-07-03 on HF Jobs: of e5 / nomic / bge-en / bge-m3 / Qwen3-Embedding, only
|
| 75 |
+
Qwen3-Embedding registers real ST prompts; the rest ship none and rely on manual prefixes.
|
| 76 |
+
"""
|
| 77 |
+
m = model_id.lower()
|
| 78 |
+
# Instruction-style embedders (e5-*-instruct, gte-Qwen, ...): prefer the model's REGISTERED
|
| 79 |
+
# prompt or an explicit --prompt; don't guess a literal prefix.
|
| 80 |
+
if "instruct" in m:
|
| 81 |
+
return None
|
| 82 |
+
if "nomic-embed-text" in m:
|
| 83 |
+
return ("search_query: ", "search_document: ")
|
| 84 |
+
if "bge-m3" in m: # bge-m3 uses no prompts
|
| 85 |
+
return ("", "")
|
| 86 |
+
# e5 family (e5-base/large/small, multilingual-e5-*), boundaried so e.g. "table5" or a
|
| 87 |
+
# model with "e5" mid-word can't silently pick up "query:/passage:" prefixes.
|
| 88 |
+
if re.search(r"(^|[/_-])e5([_-]|$)", m):
|
| 89 |
+
return ("query: ", "passage: ")
|
| 90 |
+
if "bge" in m and "-en" in m: # English bge retrieval: query instruction, docs raw
|
| 91 |
+
return ("Represent this sentence for searching relevant passages: ", "")
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def jobs_flavor() -> str:
|
| 96 |
+
"""Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
|
| 97 |
+
|
| 98 |
+
HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
|
| 99 |
+
in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
|
| 100 |
+
MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
|
| 101 |
+
cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
|
| 102 |
+
"""
|
| 103 |
+
hardware = os.environ.get("ACCELERATOR") or ""
|
| 104 |
+
if "-" in hardware or any(character.isdigit() for character in hardware):
|
| 105 |
+
return hardware # already a flavor name
|
| 106 |
+
try:
|
| 107 |
+
from huggingface_hub import HfApi
|
| 108 |
+
|
| 109 |
+
gpu_name, gpu_count = "", 0
|
| 110 |
+
try:
|
| 111 |
+
import torch
|
| 112 |
+
|
| 113 |
+
if torch.cuda.is_available():
|
| 114 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 115 |
+
gpu_count = torch.cuda.device_count()
|
| 116 |
+
except ImportError:
|
| 117 |
+
# Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
|
| 118 |
+
import subprocess
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
listed = subprocess.run(
|
| 122 |
+
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
|
| 123 |
+
capture_output=True, text=True, timeout=10, check=True,
|
| 124 |
+
).stdout
|
| 125 |
+
names = [line.strip() for line in listed.splitlines() if line.strip()]
|
| 126 |
+
if names:
|
| 127 |
+
gpu_name, gpu_count = names[0], len(names)
|
| 128 |
+
except (OSError, subprocess.SubprocessError):
|
| 129 |
+
pass
|
| 130 |
+
if gpu_count == 0 and hardware == "gpu":
|
| 131 |
+
return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
|
| 132 |
+
|
| 133 |
+
# Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
|
| 134 |
+
gpu_words = gpu_name.upper().replace("-", " ").split()
|
| 135 |
+
candidates = []
|
| 136 |
+
for flavor in HfApi(token=False).list_jobs_hardware():
|
| 137 |
+
accelerator = flavor.accelerator
|
| 138 |
+
if gpu_count == 0 and accelerator is None:
|
| 139 |
+
candidates.append(flavor)
|
| 140 |
+
elif (
|
| 141 |
+
gpu_count > 0
|
| 142 |
+
and accelerator is not None
|
| 143 |
+
and accelerator.model.upper() in gpu_words
|
| 144 |
+
and int(accelerator.quantity) == gpu_count
|
| 145 |
+
):
|
| 146 |
+
candidates.append(flavor)
|
| 147 |
+
if not candidates:
|
| 148 |
+
return ""
|
| 149 |
+
|
| 150 |
+
cores = float(os.environ.get("CPU_CORES") or 0)
|
| 151 |
+
memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
|
| 152 |
+
|
| 153 |
+
def distance(flavor) -> float:
|
| 154 |
+
# Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
|
| 155 |
+
listed_cores = float(flavor.cpu.split()[0])
|
| 156 |
+
listed_memory = float(flavor.ram.split()[0])
|
| 157 |
+
return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
|
| 158 |
+
|
| 159 |
+
return min(candidates, key=distance).name
|
| 160 |
+
except Exception:
|
| 161 |
+
return ""
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def registered_prompt(model_id, side):
|
| 165 |
+
"""Return the prompt the model registers for "document" or "query", or None when it has none."""
|
| 166 |
+
from huggingface_hub import hf_hub_download
|
| 167 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 168 |
+
|
| 169 |
+
try:
|
| 170 |
+
path = hf_hub_download(model_id, "config_sentence_transformers.json")
|
| 171 |
+
except (HfHubHTTPError, OSError):
|
| 172 |
+
return None # the model has no such file
|
| 173 |
+
with open(path) as file:
|
| 174 |
+
prompts = json.load(file).get("prompts") or {}
|
| 175 |
+
return prompts.get(side) or None
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def choose_prefix(args):
|
| 179 |
+
"""Return (prefix, where it came from) for the text side this run embeds."""
|
| 180 |
+
side = "query" if args.query_mode else "document"
|
| 181 |
+
if args.prompt is not None:
|
| 182 |
+
return args.prompt, "--prompt"
|
| 183 |
+
registered = registered_prompt(args.model, side)
|
| 184 |
+
if registered:
|
| 185 |
+
return registered, "registered by the model"
|
| 186 |
+
family = known_family_prefixes(args.model)
|
| 187 |
+
if family:
|
| 188 |
+
query_prefix, document_prefix = family
|
| 189 |
+
return (query_prefix if args.query_mode else document_prefix), "known model family"
|
| 190 |
+
return "", "none"
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def model_max_tokens(endpoint, model_id):
|
| 194 |
+
"""Return the most tokens the server accepts for one text of this model."""
|
| 195 |
+
with urllib.request.urlopen(f"{endpoint}/models", timeout=60) as response:
|
| 196 |
+
served = json.load(response)["data"]
|
| 197 |
+
for entry in served:
|
| 198 |
+
if entry["id"] == model_id:
|
| 199 |
+
return entry["max_model_len"]
|
| 200 |
+
sys.exit(f"The server does not list {model_id}. It serves: {[entry['id'] for entry in served]}")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def embedding_dimension(endpoint, model_id):
|
| 204 |
+
"""Return the length of the model's vectors, from one request to the server."""
|
| 205 |
+
request = urllib.request.Request(
|
| 206 |
+
f"{endpoint}/embeddings",
|
| 207 |
+
data=json.dumps({"model": model_id, "input": "dimension check"}).encode(),
|
| 208 |
+
headers={"Content-Type": "application/json"},
|
| 209 |
+
)
|
| 210 |
+
with urllib.request.urlopen(request, timeout=600) as response:
|
| 211 |
+
return len(json.load(response)["data"][0]["embedding"])
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def reproduce_options(args):
|
| 215 |
+
"""Return the options that give this dataset again, as a shell-quoted string."""
|
| 216 |
+
options = ["--column", args.column, "--model", args.model]
|
| 217 |
+
if args.output_column != "embeddings":
|
| 218 |
+
options += ["--output-column", args.output_column]
|
| 219 |
+
if args.config:
|
| 220 |
+
options += ["--config", args.config]
|
| 221 |
+
if args.split != "train":
|
| 222 |
+
options += ["--split", args.split]
|
| 223 |
+
if args.id_column:
|
| 224 |
+
options += ["--id-column", args.id_column]
|
| 225 |
+
if args.max_samples:
|
| 226 |
+
options += ["--max-samples", str(args.max_samples)]
|
| 227 |
+
if args.max_seq_len:
|
| 228 |
+
options += ["--max-seq-len", str(args.max_seq_len)]
|
| 229 |
+
if args.prompt is not None:
|
| 230 |
+
options += ["--prompt", args.prompt]
|
| 231 |
+
if args.query_mode:
|
| 232 |
+
options += ["--query-mode"]
|
| 233 |
+
return " ".join(shlex.quote(option) for option in options)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def write_card(args, prefix, prefix_source, dimension, max_tokens, stats):
|
| 237 |
+
"""Write the dataset card, with the canonical uv-scripts reproduction section."""
|
| 238 |
+
from huggingface_hub import HfApi
|
| 239 |
+
|
| 240 |
+
on_jobs = os.environ.get("JOB_ID") is not None
|
| 241 |
+
flavor = jobs_flavor()
|
| 242 |
+
origin = (
|
| 243 |
+
"Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
|
| 244 |
+
+ (f" (`{flavor}`)" if flavor else "")
|
| 245 |
+
) if on_jobs else "Generated"
|
| 246 |
+
jobs_tag = "\n- hf-jobs" if on_jobs else ""
|
| 247 |
+
side = "query" if args.query_mode else "document"
|
| 248 |
+
prefix_line = f"`{prefix}` ({prefix_source})" if prefix else "(none)"
|
| 249 |
+
# A resumed run processes only the rows that were missing, so the card gives both counts.
|
| 250 |
+
earlier = f", {stats.rows_done_prior} already written by an earlier run" if stats.rows_done_prior else ""
|
| 251 |
+
card = (
|
| 252 |
+
f"---\ntags:\n- embeddings\n- uv-script\n- generated{jobs_tag}\n---\n\n"
|
| 253 |
+
f"# {args.output_dataset}\n\n"
|
| 254 |
+
f"Embeddings of [`{args.input_dataset}`](https://huggingface.co/datasets/{args.input_dataset}) "
|
| 255 |
+
f"column `{args.column}`, made with a vLLM server.\n\n"
|
| 256 |
+
f"- Model: [`{args.model}`](https://huggingface.co/{args.model}) (dim {dimension})\n"
|
| 257 |
+
f"- Column: `{args.output_column}`, normalized\n"
|
| 258 |
+
f"- Prompt prepended ({side} side): {prefix_line}\n"
|
| 259 |
+
f"- Texts cut at {max_tokens} tokens\n"
|
| 260 |
+
f"- Rows in the last run: {stats.rows_processed} embedded, {stats.rows_failed} failed{earlier}. "
|
| 261 |
+
f"A failed row has a message in `error`.\n\n"
|
| 262 |
+
f"## Reproduction\n\n"
|
| 263 |
+
f"{origin} with the [`generate-embeddings-saturate.py`]({SCRIPT_URL}) recipe "
|
| 264 |
+
f"from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:\n\n"
|
| 265 |
+
f"```bash\nhf jobs uv run {SCRIPT_URL} \\\n"
|
| 266 |
+
f" {args.input_dataset} <output-dataset> {reproduce_options(args)}\n```\n"
|
| 267 |
+
)
|
| 268 |
+
HfApi().upload_file(
|
| 269 |
+
path_or_fileobj=card.encode(), path_in_repo="README.md",
|
| 270 |
+
repo_id=args.output_dataset, repo_type="dataset",
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def main():
|
| 275 |
+
parser = argparse.ArgumentParser(description="Embed a text column with a vLLM server via saturate")
|
| 276 |
+
parser.add_argument("input_dataset", help="Input dataset ID on the Hugging Face Hub")
|
| 277 |
+
parser.add_argument("output_dataset", help="Output dataset ID (created if missing)")
|
| 278 |
+
parser.add_argument("--model", default="Qwen/Qwen3-Embedding-0.6B", help="An embedding model that vLLM serves")
|
| 279 |
+
parser.add_argument("--column", default="text", help="Text column to embed")
|
| 280 |
+
parser.add_argument("--output-column", default="embeddings")
|
| 281 |
+
parser.add_argument("--config", default=None, help="Dataset config name")
|
| 282 |
+
parser.add_argument("--split", default="train")
|
| 283 |
+
parser.add_argument("--id-column", default=None, help="Column to use as the row id (default: the row's position)")
|
| 284 |
+
parser.add_argument("--max-samples", type=int, default=None, help="Embed only the first N rows (for testing)")
|
| 285 |
+
parser.add_argument("--max-seq-len", type=int, default=None,
|
| 286 |
+
help="Cut each text at this many tokens (default: the model's own maximum)")
|
| 287 |
+
parser.add_argument("--prompt", default=None,
|
| 288 |
+
help="Prefix to put before every text, such as 'passage: '. Pass '' for no prefix.")
|
| 289 |
+
parser.add_argument("--query-mode", action="store_true", help="Embed the texts as queries, not documents")
|
| 290 |
+
parser.add_argument("--private", action="store_true", help="Make the output dataset private")
|
| 291 |
+
parser.add_argument("--retry-errors", action="store_true", help="Try again the rows whose only record is an error")
|
| 292 |
+
args = parser.parse_args()
|
| 293 |
+
|
| 294 |
+
import pyarrow as pa
|
| 295 |
+
from huggingface_hub import HfApi
|
| 296 |
+
from saturate import Engine, dataset_rows, pump
|
| 297 |
+
|
| 298 |
+
prefix, prefix_source = choose_prefix(args)
|
| 299 |
+
print(f"Prompt prefix: {prefix!r} ({prefix_source})", file=sys.stderr)
|
| 300 |
+
|
| 301 |
+
if args.id_column is None:
|
| 302 |
+
ids = "index"
|
| 303 |
+
elif args.id_column in ("index", "content"):
|
| 304 |
+
# saturate reads these two names as id strategies, so a column with one of them
|
| 305 |
+
# needs a callable. It returns the raw value, so saturate still refuses a null id.
|
| 306 |
+
def ids(example):
|
| 307 |
+
return example[args.id_column]
|
| 308 |
+
else:
|
| 309 |
+
ids = args.id_column
|
| 310 |
+
|
| 311 |
+
HfApi().create_repo(args.output_dataset, repo_type="dataset", private=args.private, exist_ok=True)
|
| 312 |
+
rows = dataset_rows(
|
| 313 |
+
args.input_dataset, config=args.config, split=args.split,
|
| 314 |
+
columns=[args.column], ids=ids, limit=args.max_samples,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
cut = {"max_tokens": None} # set once the server reports the model's maximum
|
| 318 |
+
|
| 319 |
+
def to_request(row):
|
| 320 |
+
return {
|
| 321 |
+
"model": args.model,
|
| 322 |
+
"input": prefix + (row[args.column] or ""),
|
| 323 |
+
"truncate_prompt_tokens": cut["max_tokens"],
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
# Declared, so a part holding only error rows has the same columns as the rest.
|
| 327 |
+
schema = pa.schema([
|
| 328 |
+
("id", pa.string()), ("error", pa.string()), (args.column, pa.string()),
|
| 329 |
+
(args.output_column, pa.list_(pa.float32())), ("model", pa.string()), ("prompt_tokens", pa.int64()),
|
| 330 |
+
]) # fmt: skip
|
| 331 |
+
def parse(row, body):
|
| 332 |
+
return {
|
| 333 |
+
args.column: row[args.column],
|
| 334 |
+
args.output_column: body["data"][0]["embedding"],
|
| 335 |
+
"model": args.model,
|
| 336 |
+
"prompt_tokens": (body.get("usage") or {}).get("prompt_tokens"),
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
# The readiness check sends one embedding request, so the server is known to embed before the run starts.
|
| 340 |
+
engine = Engine(
|
| 341 |
+
args.model, engine="vllm", extra_args=["--runner", "pooling"],
|
| 342 |
+
ready_route="/embeddings", ready_payload={"model": args.model, "input": "ready"},
|
| 343 |
+
)
|
| 344 |
+
with engine as endpoint:
|
| 345 |
+
model_maximum = model_max_tokens(endpoint, args.model)
|
| 346 |
+
cut["max_tokens"] = min(args.max_seq_len or model_maximum, model_maximum)
|
| 347 |
+
print(f"Texts are cut at {cut['max_tokens']} tokens (the model's maximum is {model_maximum})", file=sys.stderr)
|
| 348 |
+
dimension = embedding_dimension(endpoint, args.model)
|
| 349 |
+
started = time.monotonic()
|
| 350 |
+
stats = pump(
|
| 351 |
+
rows, to_request, parse, endpoint, f"hf://datasets/{args.output_dataset}/data",
|
| 352 |
+
route="/embeddings", retry_errors=args.retry_errors, schema=schema,
|
| 353 |
+
)
|
| 354 |
+
elapsed = time.monotonic() - started
|
| 355 |
+
|
| 356 |
+
write_card(args, prefix, prefix_source, dimension, cut["max_tokens"], stats)
|
| 357 |
+
print(
|
| 358 |
+
f"https://huggingface.co/datasets/{args.output_dataset} "
|
| 359 |
+
f"({stats.rows_processed} ok, {stats.rows_failed} error rows, "
|
| 360 |
+
f"{stats.rows_processed / max(elapsed, 1e-6):.0f} rows/s, dim {dimension})",
|
| 361 |
+
file=sys.stderr,
|
| 362 |
+
)
|
| 363 |
+
print("GENERATE_EMBEDDINGS_SATURATE " + stats.to_json(), flush=True)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
if __name__ == "__main__":
|
| 367 |
+
main()
|
generate-embeddings-vllm.py
CHANGED
|
@@ -7,6 +7,8 @@
|
|
| 7 |
# ]
|
| 8 |
# ///
|
| 9 |
"""
|
|
|
|
|
|
|
| 10 |
High-throughput embedding generation with vLLM pooling mode — the "scale" variant of
|
| 11 |
generate-embeddings.py, for large *decoder* embedding models (e.g. Qwen3-Embedding). On
|
| 12 |
Qwen3-Embedding-0.6B this was ~2x the sentence-transformers throughput on the same GPU.
|
|
|
|
| 7 |
# ]
|
| 8 |
# ///
|
| 9 |
"""
|
| 10 |
+
Superseded by generate-embeddings-saturate.py, which runs a vLLM server on a pinned image.
|
| 11 |
+
|
| 12 |
High-throughput embedding generation with vLLM pooling mode — the "scale" variant of
|
| 13 |
generate-embeddings.py, for large *decoder* embedding models (e.g. Qwen3-Embedding). On
|
| 14 |
Qwen3-Embedding-0.6B this was ~2x the sentence-transformers throughput on the same GPU.
|