davanstrien HF Staff commited on
Commit
b905bf7
·
verified ·
1 Parent(s): 180708e

Sync from GitHub via hub-sync

Browse files
Files changed (5) hide show
  1. HEURISTICS.md +137 -0
  2. README.md +139 -0
  3. embed-to-lance.py +180 -0
  4. generate-embeddings-vllm.py +134 -0
  5. generate-embeddings.py +327 -293
HEURISTICS.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Embedding-on-Jobs heuristics — what we measured, and what to try
2
+
3
+ A field guide for the `embeddings/` recipes, for **humans and agents**. Everything here is
4
+ measured on HF Jobs (2026-07), not folklore. If you're an agent picking settings for a user's
5
+ data: read the TL;DR, match the data shape, use the defaults; the recipe's `--batch-size auto`
6
+ + token sniffer handle the rest.
7
+
8
+ ## First: pick a *current* model, not the frozen list below
9
+
10
+ Embedding quality moves fast. The specific models in this guide are what we **benchmarked in
11
+ 2026-07** — a durable baseline, not a permanent answer. Before committing, find the current best
12
+ (an agent should do this automatically, not trust a hard-coded name):
13
+
14
+ - **MTEB leaderboard** — the canonical ranking: <https://huggingface.co/spaces/mteb/leaderboard>
15
+ - **The Hub, from the CLI** (scriptable, always current):
16
+ ```bash
17
+ hf models ls --filter sentence-transformers --sort trending_score --limit 20 # what's hot now
18
+ hf models ls --filter sentence-transformers --sort downloads --limit 20 # proven workhorses
19
+ hf models ls --search embedding --num-parameters min:0,max:1B --sort trending_score
20
+ ```
21
+ Sort by `trending_score` or `downloads`, **not `created_at`** — the newest list is mostly empty
22
+ test repos. Then check the model card for its prompt convention (see Prompts) and license.
23
+
24
+ The **heuristics here are model-independent** — token-bound throughput, batch ~128, L4-for-encoders,
25
+ prompts-matter, seq-len cost hold whatever tops the leaderboard next week. Use them; swap in the
26
+ current model. (E.g. as of this writing the CLI surfaced newer options like jina-embeddings-v5,
27
+ voyage-4-nano, and LiquidAI's ColBERT that postdate parts of this guide.)
28
+
29
+ ## TL;DR decision table
30
+ *(benchmarked examples, 2026-07 — run the queries above for the current best)*
31
+
32
+ | Your situation | Model | Flavor | Notes |
33
+ |---|---|---|---|
34
+ | Default / fast / cheap (English) | `all-MiniLM-L6-v2` | `l4x1` | ~900 rows/s, ~$0.24/1M rows, dim 384 |
35
+ | Better English quality | `BAAI/bge-base-en-v1.5` | `l4x1` | ~120 rows/s, ~$1.87/1M, dim 768 |
36
+ | Multilingual / long-context | `BAAI/bge-m3` | `l4x1`/`a10g-large` | slower (dim 1024); use only if you need it |
37
+ | Top open quality (decoder) | `Qwen/Qwen3-Embedding-0.6B` | `a100-large` + **vLLM variant** | A100 is 4× the L4 here AND cheaper/1M |
38
+ | Max quality, cost no object | `Qwen/Qwen3-Embedding-8B` (4B benched) | `a100-large` + vLLM | ~$7/1M, dim 2560 |
39
+ | Images, fast | `clip-ViT-B-32` | `l4x1` | ~395 img/s (bs=32), dim 512 |
40
+ | Images, higher quality | `clip-ViT-L-14` or SigLIP-2-large | `l4x1`/`a10g-large` | slower, larger dim |
41
+
42
+ **One-line scale proof:** 241,787 Wikipedia articles → a searchable Lance vector DB on the Hub
43
+ in **4.5 min for ~$0.07** on a single L4 (all-MiniLM). Cheap at scale is real.
44
+
45
+ ## Text: the load-bearing heuristics
46
+
47
+ **1. Throughput is token-bound, not row-bound.** Same model (all-MiniLM, L4): short text
48
+ (AG News, median 53 tokens) = **2866 rows/s**; long text (IMDB, median ~300 tokens) = **912
49
+ rows/s**. A 3× swing from text length alone. So estimate cost in *tokens*, not rows, and know
50
+ that "rows/s" quoted anywhere is only meaningful with a text length attached.
51
+
52
+ **2. Batch size peaks around ~128 — bigger is usually *slower*.** Counter-intuitive but
53
+ consistent: at batch 128/256/512/1024, all-MiniLM on short text ran 2443 / 1981 / 1355 / 796
54
+ rows/s — monotonically *down*. sentence-transformers length-sorts internally, and larger
55
+ batches pad to the longest member + add overhead. **Don't crank the batch.** `--batch-size auto`
56
+ probes and lands here for you; the token sniffer widens the probe range for short text (and it
57
+ still picks ~128).
58
+
59
+ **3. Sequence length is a real cost lever — and bigger models feel it more.** On long text
60
+ (IMDB), capping `--max-seq-len` 512 → 128 sped things up **1.8×** for all-MiniLM (912 → 1682
61
+ rows/s) and **2.8×** for bge-base (119 → 332 rows/s). The larger model benefits *more* because
62
+ attention is O(n²), so shorter sequences help disproportionately, not just linearly.
63
+
64
+ | Model | seq-cap 128 | seq-cap 512 | speedup from capping |
65
+ |---|---|---|---|
66
+ | all-MiniLM-L6-v2 | 1682 rows/s | 912 rows/s | 1.8× |
67
+ | bge-base-en-v1.5 | 332 rows/s | 119 rows/s | 2.8× |
68
+
69
+ Rule of thumb: RAG-sized chunks live under 512 tokens, so the `--max-seq-len 512` default is
70
+ right for most retrieval corpora. **Lower the cap for a big, cheap speedup when your text is
71
+ short anyway or you can tolerate truncation** (the token sniffer tells you what fraction you'd
72
+ lose). Raise it only if the sniffer warns you're truncating a lot AND you need the tail —
73
+ budget for the slowdown, especially on bigger models.
74
+
75
+ **4. GPU: L4 for encoders, A100 only for decoders.** $/1M rows (encode-only):
76
+
77
+ | Model (type) | L4 $0.80 | A10G $1.50 | A100 $2.50 |
78
+ |---|---|---|---|
79
+ | all-MiniLM (encoder) | **$0.24** | $0.38 | $0.51 |
80
+ | bge-base (encoder) | **$1.87** | $2.02 | $2.66 |
81
+ | bge-m3 (encoder) | **$6.17** | $6.22 | $8.27 |
82
+ | Qwen3-Embedding-0.6B (decoder) | $3.77 | $4.48 | **$2.78** |
83
+
84
+ Encoders (MiniLM, bge) are cheapest on the L4 — the bigger GPU doesn't earn its price. **Decoder**
85
+ embedders (Qwen3-Embedding) are the exception: the A100 runs them ~4× faster AND cheaper per 1M,
86
+ because decoders actually use the extra compute.
87
+
88
+ **5. Engine: sentence-transformers by default; vLLM ~2× for decoder embedders.** On the same
89
+ Qwen3-Embedding-0.6B/L4, vLLM pooling hit 121 rows/s vs sentence-transformers' 59 (~2×). For
90
+ small encoders, sentence-transformers is already fast and far simpler — use the default. Switch
91
+ to `generate-embeddings-vllm.py` only for large decoder embedders at scale.
92
+
93
+ **6. Prompts are a correctness issue, not a nicety.** Many retrieval models need a *different*
94
+ prefix for documents vs queries, and mismatching them silently hurts retrieval. Gotcha we
95
+ verified: sentence-transformers reports an empty placeholder `{"query":"","document":""}` for
96
+ models that ship NO prompts — so e5 ("passage: "/"query: ") and nomic ("search_document:
97
+ "/"search_query: ") *look* prompt-less but aren't; their prefixes live only in the model card.
98
+ The recipe's built-in family table handles e5 / nomic / bge / Qwen3 automatically for a document
99
+ corpus; pass `--query-mode` for a query set, or `--prompt '<prefix>'` to override.
100
+
101
+ ## Images: heuristics
102
+
103
+ - **Model choice:** `clip-ViT-B-32` (~395 img/s on L4 at bs=32, dim 512) is the fast default; `clip-ViT-L-14`
104
+ (40 img/s, dim 768) or SigLIP-2-large (46 img/s, dim 1024) for quality. SigLIP-2 wins at the
105
+ large tier but needs the transformers path (~4× the code); CLIP-via-sentence-transformers is the
106
+ clean one-liner.
107
+ - **Flavor + cost: L4 is the cost pick for every image model.** clip-ViT-B-32 ≈ **$0.56/1M images**
108
+ (pre-sized) or ~$1.03/1M (full-res); siglip2-large ≈ $4.84/1M. A10G is ~1.3× faster but 1.875× the
109
+ rate (~$0.92/1M for B-32) → use it only when wall-clock, not cost, matters.
110
+ - **`--batch-size auto` uses 32/64/128 for images; 64 is a safe manual default** (only ~6% off the
111
+ bs=32 peak on full-res images, and more robust).
112
+ - **Batch: images favor *small* batches — the opposite of the "fixed-size → batch big" hunch.**
113
+ clip-ViT-B-32 on L4: bs=32 = **395 img/s** (fastest), then flat/slower above (343 / 330 / 333 /
114
+ 331 / 329 at bs 64 / 128 / 256 / 512 / 1024). Peak GPU mem stays tiny (0.7–4 GB even at bs=1024),
115
+ so it's not a memory ceiling — it's per-batch pipeline overhead. So "don't crank the batch" holds
116
+ for images too, at an even smaller optimum than text. `--batch-size auto` probes from 32 and lands
117
+ on it — no image-specific tuning needed.
118
+ - **GPU memory = f(batch × model) only** — models resize to a fixed 224px, so source resolution
119
+ never touches GPU memory (verified: identical peak across a 32px and a full-res dataset). BUT
120
+ **full-res images run ~1.8× slower** than tiny ones (395 → 215 img/s for B-32) — decode/resize is a
121
+ real CPU tax, negligible *only* for pre-sized/small images.
122
+
123
+ ## Storage / dimensions
124
+
125
+ Bigger embedding dim = more storage + slower vector search. If your model supports **Matryoshka**
126
+ truncation (nomic-embed, Qwen3-Embedding), you can keep the first N dims (e.g. 256 of 768) for
127
+ much cheaper storage/search at a small quality cost — worth it for large indexes. Always
128
+ normalize (the recipe does) so cosine = dot product.
129
+
130
+ ## Other modalities
131
+ Text and images are what these recipes cover. **Audio** (CLAP / speech-encoder embeddings) and
132
+ **code** (code-specialized text embedders) use different models — a separate recipe, not this one.
133
+ Note it and route users there rather than forcing them through the image/text path.
134
+
135
+ ## The evidence (measured on HF Jobs, 2026-07)
136
+ Measured on HF Jobs (2026-07) with the scripts in this folder. Text: 20k rows, batch 64, seq-cap 512 unless
137
+ noted. All datasets used were public; all test outputs were private.
README.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ viewer: false
3
+ tags:
4
+ - uv-script
5
+ - embeddings
6
+ - sentence-transformers
7
+ - vector-search
8
+ ---
9
+
10
+ # Embeddings
11
+
12
+ Generate embeddings for a Hugging Face dataset — text or images — with one command, on a
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 two 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-vllm.py` | Max throughput on large *decoder* embedding models (Qwen3-Embedding). | vLLM pooling |
23
+ | `embed-to-lance.py` | Get a **searchable vector index as a Hub dataset** (the "vector DB" path). | sentence-transformers + Lance |
24
+
25
+ ## Quick start
26
+
27
+ ```bash
28
+ # Text — pick a model from the MTEB leaderboard
29
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
30
+ https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings.py \
31
+ stanfordnlp/imdb your-name/imdb-embeddings --column text
32
+
33
+ # Images (CLIP)
34
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
35
+ https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings.py \
36
+ your-name/photos your-name/photos-embeddings --modality image --column image --model clip-ViT-B-32
37
+ ```
38
+
39
+ Always try `--max-samples 100 --private` first.
40
+
41
+ ## Which model?
42
+
43
+ **Find the *current* best — don't trust a fixed list** (embedding quality moves fast). Check the
44
+ [MTEB leaderboard](https://huggingface.co/spaces/mteb/leaderboard), or from the CLI:
45
+
46
+ ```bash
47
+ hf models ls --filter sentence-transformers --sort trending_score --limit 20 # what's hot now
48
+ hf models ls --filter sentence-transformers --sort downloads --limit 20 # proven workhorses
49
+ ```
50
+ (Sort by `trending_score`/`downloads`, not `created_at` — the newest list is mostly test repos.)
51
+
52
+ See **[HEURISTICS.md](./HEURISTICS.md)** for the full "which model / GPU / batch for your data" guide
53
+ (measured). The table below is examples benchmarked 2026-07, not a permanent answer:
54
+
55
+ | Model | Params | Dim | Note |
56
+ |---|---|---|---|
57
+ | `sentence-transformers/all-MiniLM-L6-v2` | 22M | 384 | Fastest; safe default |
58
+ | `BAAI/bge-base-en-v1.5` | 109M | 768 | Strong English quality/speed balance |
59
+ | `BAAI/bge-m3` | 568M | 1024 | Multilingual + long context (slower) |
60
+ | `Qwen/Qwen3-Embedding-0.6B` | 596M | 1024 | Top open MTEB; decoder → use the vLLM variant / A100 |
61
+
62
+ Images: `clip-ViT-B-32` (fast) or `clip-ViT-L-14` (higher quality).
63
+
64
+ ## Prompts (retrieval correctness — read this if you're building search)
65
+
66
+ Many retrieval models need a **different prefix for documents vs queries**, and getting it
67
+ wrong silently degrades results. Worse, you can't trust `model.prompts`: current
68
+ sentence-transformers injects a placeholder `{"query": "", "document": ""}` even for models
69
+ that register **nothing**, so e5 / nomic / bge look "prompt-less" via that attribute while
70
+ their real prefixes live only in the model card.
71
+
72
+ `generate-embeddings.py` handles this. It embeds a **document corpus** by default and picks the
73
+ document convention in this order: (1) the model's **registered** prompt if it ships a real one
74
+ (e.g. Qwen3-Embedding), else (2) a small **built-in family table**, else (3) no prefix. The
75
+ chosen prefix is logged and written into the output dataset card.
76
+
77
+ | Family | Query prefix | Document prefix |
78
+ |---|---|---|
79
+ | e5 (`intfloat/e5-*`, `multilingual-e5-*`, non-instruct) | `query: ` | `passage: ` |
80
+ | nomic (`nomic-embed-text-*`) | `search_query: ` | `search_document: ` |
81
+ | bge English (`bge-*-en-*`) | `Represent this sentence for searching relevant passages: ` | (none) |
82
+ | bge-m3 | (none) | (none) |
83
+ | Qwen3-Embedding | registered by the model | (none) |
84
+ | anything else | — | — (pass `--prompt` if it needs one) |
85
+
86
+ Override the auto-pick:
87
+
88
+ - `--query-mode` — embed inputs as **queries**, not documents (flips the convention)
89
+ - `--prompt 'passage: '` — force a raw prefix (highest precedence; `--prompt ''` forces none)
90
+ - `--prompt-name query` — use a prompt the model registered, by name
91
+ - `--no-auto-prompt` — turn off the family table (still honours registered prompts)
92
+
93
+ Instruct-style models (`e5-*-instruct`, `gte-Qwen…`) are deliberately left to their registered
94
+ prompt or your explicit `--prompt`, since the instruction is task-specific.
95
+
96
+ ## Batch size (auto by default)
97
+
98
+ `--batch-size auto` (the default) times a few batch sizes on a warmup sample and keeps the
99
+ fastest that fits — bigger isn't always faster, because variable-length text wastes compute on
100
+ padding. Pass `--batch-size 128` to pin it.
101
+
102
+ ## Which GPU? (measured, 20k rows, seq-cap 512)
103
+
104
+ Throughput (rows/s) and cost per 1M rows:
105
+
106
+ | Model | L4 ($0.80/hr) | A10G ($1.50/hr) | A100 ($2.50/hr) |
107
+ |---|---|---|---|
108
+ | all-MiniLM-L6-v2 | 912 · **$0.24/1M** | 1099 · $0.38/1M | 1372 · $0.51/1M |
109
+ | bge-base-en-v1.5 | 119 · **$1.87/1M** | 206 · $2.02/1M | 261 · $2.66/1M |
110
+ | Qwen3-Embedding-0.6B | 59 · $3.77/1M | 93 · $4.48/1M | 250 · **$2.78/1M** |
111
+
112
+ **Default to `l4x1`** — cheapest per 1M rows for encoder models. For **decoder** embedders
113
+ (Qwen3-Embedding) the A100 is both faster *and* cheaper per 1M (they use the extra compute),
114
+ and the vLLM variant roughly doubles throughput again (Qwen3-Embedding-0.6B: ~121 rows/s on an
115
+ L4 via `generate-embeddings-vllm.py`, ~2× the sentence-transformers path).
116
+
117
+ Images embed much faster than text: `clip-ViT-B-32` runs ~395 img/s on an L4 at the auto-picked batch (bs=32; ~455 on an A10G). Full-resolution photos land nearer ~215 img/s — decode/resize is a real CPU tax on fast models.
118
+
119
+ ## The vector-DB path (`embed-to-lance.py`)
120
+
121
+ Writes a [Lance](https://huggingface.co/docs/hub/datasets-lance) table with a vector index and
122
+ pushes it as a Hub dataset. You (or anyone you share it with) can then search it directly over
123
+ `hf://` **without downloading it**:
124
+
125
+ ```python
126
+ import lance
127
+ ds = lance.dataset("hf://datasets/your-name/my-vecdb/vecdb.lance") # opens in ~1s, no download
128
+ hits = ds.to_table(nearest={"column": "vector", "q": query_vec, "k": 5})
129
+ ```
130
+
131
+ > **Query prompts:** embed `query_vec` with the model's *query* prefix (e5 → `"query: "`,
132
+ > nomic → `"search_query: "`; the run prints the right one). Documents and queries use
133
+ > different prefixes on these models — mismatching them silently degrades retrieval.
134
+
135
+ End-to-end this is fast and cheap: **all 241,787 Simple-English-Wikipedia articles → a
136
+ searchable Lance vector DB on the Hub in ~4.5 min for ~$0.07 on a single L4** (load → embed →
137
+ index → push, with `all-MiniLM-L6-v2`; pass `--model` to trade speed for quality).
138
+
139
+ Best for share-and-search over a corpus; for high-QPS serving, pull the dataset local first.
embed-to-lance.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "datasets",
5
+ # "sentence-transformers>=5.0.0",
6
+ # "torch",
7
+ # "numpy",
8
+ # "einops",
9
+ # "pyarrow",
10
+ # "pylance",
11
+ # "huggingface-hub",
12
+ # ]
13
+ # ///
14
+ """
15
+ Embed a Hugging Face dataset and push it back as a Lance vector index — a Hub dataset that
16
+ IS a searchable vector database. Anyone you share it with can vector-search it over `hf://`
17
+ without downloading it:
18
+
19
+ import lance
20
+ ds = lance.dataset("hf://datasets/your-name/my-vecdb/vecdb.lance") # opens fast, no download
21
+ hits = ds.to_table(nearest={"column": "vector", "q": query_vector, "k": 5})
22
+
23
+ Best for share-and-search over a corpus; for high-QPS serving, pull the dataset local first.
24
+
25
+ PROMPTS: documents are embedded with the model's known DOCUMENT convention (e5 → "passage: ",
26
+ nomic → "search_document: "; bge-en/bge-m3 → none). At SEARCH time, embed your query with the
27
+ matching QUERY prefix (printed at the end of the run) or retrieval quality silently drops.
28
+ Override the document prefix with --prompt '<prefix>' (or --prompt '' for none).
29
+
30
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN embed-to-lance.py \\
31
+ stanfordnlp/imdb your-name/imdb-vecdb --column text --model BAAI/bge-base-en-v1.5 --private
32
+ """
33
+ import argparse
34
+ import logging
35
+ import os
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ import numpy as np
41
+ import pyarrow as pa
42
+
43
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
44
+ log = logging.getLogger("embed-to-lance")
45
+
46
+
47
+ def known_convention(model_id):
48
+ """(query_prefix, doc_prefix) for common families (documented in model cards, not registered
49
+ in sentence-transformers config). Same table as generate-embeddings.py; None = unknown."""
50
+ m = model_id.lower()
51
+ if "instruct" in m:
52
+ return None
53
+ if "nomic-embed-text" in m:
54
+ return ("search_query: ", "search_document: ")
55
+ if "bge-m3" in m:
56
+ return ("", "")
57
+ if re.search(r"(^|[/_-])e5([_-]|$)", m):
58
+ return ("query: ", "passage: ")
59
+ if "bge" in m and "-en" in m:
60
+ return ("Represent this sentence for searching relevant passages: ", "")
61
+ return None
62
+
63
+
64
+ def main():
65
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
66
+ ap.add_argument("input_dataset")
67
+ ap.add_argument("output_repo")
68
+ ap.add_argument("--column", default="text")
69
+ ap.add_argument("--config", default=None, help="dataset config name (e.g. wikipedia needs one)")
70
+ ap.add_argument("--split", default="train")
71
+ ap.add_argument("--model", default="BAAI/bge-base-en-v1.5")
72
+ ap.add_argument("--max-samples", type=int, default=None)
73
+ ap.add_argument("--batch-size", type=int, default=64)
74
+ ap.add_argument("--max-seq-len", type=int, default=512)
75
+ ap.add_argument("--prompt", default=None,
76
+ help="Document prefix to prepend (default: auto from the known-family table; "
77
+ "pass '' to force none)")
78
+ ap.add_argument("--private", action="store_true")
79
+ args = ap.parse_args()
80
+
81
+ import torch
82
+ import lance
83
+ from datasets import load_dataset
84
+ from huggingface_hub import HfApi, login
85
+ from sentence_transformers import SentenceTransformer
86
+
87
+ if os.environ.get("HF_TOKEN"):
88
+ login(token=os.environ["HF_TOKEN"])
89
+
90
+ t_all = time.perf_counter()
91
+ ds = load_dataset(args.input_dataset, args.config, split=args.split) if args.config \
92
+ else load_dataset(args.input_dataset, split=args.split)
93
+ if args.max_samples:
94
+ ds = ds.select(range(min(args.max_samples, len(ds))))
95
+ texts = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]]
96
+ n = len(texts)
97
+
98
+ t_load = time.perf_counter()
99
+
100
+ device = "cuda" if torch.cuda.is_available() else "cpu"
101
+ model = SentenceTransformer(args.model, device=device, trust_remote_code=True)
102
+ if getattr(model, "max_seq_length", None):
103
+ model.max_seq_length = min(model.max_seq_length, args.max_seq_len)
104
+ dim = model.get_sentence_embedding_dimension()
105
+
106
+ # Document-side prompt: explicit --prompt wins (incl. '' for none), else the known-family
107
+ # table; else None → encode_document() natively selects any REGISTERED document prompt
108
+ # (and routes Router models by task).
109
+ registered = {k: v for k, v in (getattr(model, "prompts", {}) or {}).items() if v}
110
+ kc = known_convention(args.model)
111
+ doc_prompt = args.prompt if args.prompt is not None else (kc[1] if kc else None)
112
+ query_prompt = kc[0] if kc else registered.get("query", "")
113
+ log.info(f"document prompt: {doc_prompt!r}" if doc_prompt
114
+ else ("document prompt: native (registered)" if registered.get("document")
115
+ else "document prompt: (none)"))
116
+
117
+ t0 = time.perf_counter()
118
+ encode_kwargs = {"prompt": doc_prompt} if doc_prompt is not None else {}
119
+ emb = model.encode_document(texts, batch_size=args.batch_size, show_progress_bar=True,
120
+ convert_to_numpy=True, normalize_embeddings=True,
121
+ **encode_kwargs).astype(np.float32)
122
+ log.info(f"embedded {n} rows in {time.perf_counter()-t0:.1f}s, dim={dim}")
123
+
124
+ tbl = pa.table({
125
+ "id": pa.array(range(n), pa.int64()),
126
+ "text": pa.array([t[:2000] for t in texts]),
127
+ "vector": pa.FixedSizeListArray.from_arrays(pa.array(emb.reshape(-1), pa.float32()), dim),
128
+ })
129
+ local = "vecdb.lance"
130
+ if os.path.exists(local):
131
+ shutil.rmtree(local)
132
+ lds = lance.write_dataset(tbl, local, mode="overwrite")
133
+ try:
134
+ parts = max(1, min(256, int(np.sqrt(n))))
135
+ lds.create_index("vector", index_type="IVF_PQ", num_partitions=parts,
136
+ num_sub_vectors=max(1, dim // 16))
137
+ log.info(f"built IVF_PQ index (partitions={parts})")
138
+ except Exception as e:
139
+ log.warning(f"index build skipped ({repr(e)[:120]}); flat search still works over hf://")
140
+
141
+ # Retry the upload with an XET-disable fallback — a transient failure here would lose the
142
+ # whole (paid) embedding run.
143
+ api = HfApi()
144
+ api.create_repo(args.output_repo, repo_type="dataset", private=args.private, exist_ok=True)
145
+ max_retries = 3
146
+ for attempt in range(1, max_retries + 1):
147
+ try:
148
+ if attempt > 1:
149
+ log.warning("Disabling XET (fallback to HTTP upload)")
150
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
151
+ api.upload_folder(folder_path=local, path_in_repo="vecdb.lance",
152
+ repo_id=args.output_repo, repo_type="dataset")
153
+ break
154
+ except Exception as e:
155
+ log.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
156
+ if attempt < max_retries:
157
+ delay = 30 * (2 ** (attempt - 1))
158
+ log.info(f"Retrying in {delay}s...")
159
+ time.sleep(delay)
160
+ else:
161
+ log.error("All upload attempts failed. Results are lost.")
162
+ sys.exit(1)
163
+ total_s = time.perf_counter() - t_all
164
+ import json as _json
165
+ log.info("ROUNDTRIP " + _json.dumps({
166
+ "input": args.input_dataset, "n": n, "dim": dim, "model": args.model,
167
+ "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu",
168
+ "batch_size": args.batch_size, "load_s": round(t_load - t_all, 1),
169
+ "total_roundtrip_s": round(total_s, 1), "rows_per_s_end_to_end": round(n / total_s, 1),
170
+ "hf_path": f"hf://datasets/{args.output_repo}/vecdb.lance"}))
171
+ log.info(f"✅ {n} rows → searchable vector DB in {total_s/60:.1f} min "
172
+ f"(load→embed→index→push). hf://datasets/{args.output_repo}/vecdb.lance")
173
+ if query_prompt or registered.get("query"):
174
+ log.info("⚠️ At search time, embed queries with the QUERY convention — mismatched prompts "
175
+ "degrade retrieval. Easiest: model.encode_query([your_query])"
176
+ + (f", or explicitly: model.encode([{query_prompt!r} + your_query])" if query_prompt else "."))
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
generate-embeddings-vllm.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "datasets",
5
+ # "vllm",
6
+ # "huggingface-hub",
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.
13
+
14
+ Prefer the plain sentence-transformers `generate-embeddings.py` unless you specifically need
15
+ vLLM throughput: this variant has a heavier cold-start and two footguns handled below
16
+ (the embedding-mode kwarg drifted across vLLM versions; vLLM does not auto-truncate).
17
+
18
+ Runs on the BARE uv image (vLLM ships the CUDA toolkit + flashinfer as wheels).
19
+
20
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings-vllm.py \\
21
+ stanfordnlp/imdb your-name/imdb-embeddings --column text --model Qwen/Qwen3-Embedding-0.6B --private
22
+ """
23
+ import argparse
24
+ import logging
25
+ import os
26
+ import time
27
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
28
+ os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
29
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
30
+ log = logging.getLogger("generate-embeddings-vllm")
31
+
32
+
33
+ def build_llm(LLM, model, max_model_len, gpu_mem_util):
34
+ """vLLM's embedding-mode selector drifted: modern uses runner='pooling', old used
35
+ task='embed'. A wrong kwarg raises TypeError at init (cheap) → fall through."""
36
+ base = dict(enforce_eager=True, max_model_len=max_model_len, gpu_memory_utilization=gpu_mem_util)
37
+ for label, extra in [("runner", {"runner": "pooling"}), ("task", {"task": "embed"}), ("auto", {})]:
38
+ try:
39
+ llm = LLM(model=model, **base, **extra)
40
+ log.info(f"engine init via '{label}'")
41
+ return llm
42
+ except TypeError as te:
43
+ log.warning(f"ctor '{label}' rejected: {te}")
44
+ raise RuntimeError("no vLLM constructor form accepted")
45
+
46
+
47
+ def main():
48
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
49
+ ap.add_argument("input_dataset")
50
+ ap.add_argument("output_dataset")
51
+ ap.add_argument("--model", default="Qwen/Qwen3-Embedding-0.6B")
52
+ ap.add_argument("--column", default="text")
53
+ ap.add_argument("--output-column", default="embeddings")
54
+ ap.add_argument("--split", default="train")
55
+ ap.add_argument("--max-samples", type=int, default=None)
56
+ ap.add_argument("--config", default=None, help="dataset config name (e.g. wikipedia needs one)")
57
+ ap.add_argument("--max-model-len", type=int, default=512)
58
+ ap.add_argument("--gpu-mem-util", type=float, default=0.85)
59
+ ap.add_argument("--private", action="store_true")
60
+ args = ap.parse_args()
61
+
62
+ import torch
63
+ from datasets import load_dataset
64
+ from huggingface_hub import DatasetCard, login
65
+ from vllm import LLM
66
+ if not torch.cuda.is_available():
67
+ raise SystemExit("No CUDA GPU available — vLLM needs one. Run with a GPU flavor, e.g. "
68
+ "`hf jobs uv run --flavor l4x1 ...` (or use generate-embeddings.py on CPU).")
69
+ if os.environ.get("HF_TOKEN"):
70
+ login(token=os.environ["HF_TOKEN"])
71
+
72
+ ds = (load_dataset(args.input_dataset, args.config, split=args.split) if args.config
73
+ else load_dataset(args.input_dataset, split=args.split))
74
+ if args.output_column in ds.column_names:
75
+ raise SystemExit(f"Output column {args.output_column!r} already exists — pick another.")
76
+ if args.max_samples:
77
+ ds = ds.select(range(min(args.max_samples, len(ds))))
78
+ texts = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]]
79
+ n = len(texts)
80
+
81
+ llm = build_llm(LLM, args.model, args.max_model_len, args.gpu_mem_util)
82
+ embed_fn = getattr(llm, "embed", None) or getattr(llm, "encode")
83
+
84
+ # vLLM raises on inputs > max_model_len (no silent truncation) — pre-truncate at the tokenizer.
85
+ # Tokenize each text once (not twice) — this pass is CPU-bound on large datasets.
86
+ tk = llm.get_tokenizer()
87
+ cap = max(8, args.max_model_len - 16)
88
+ def _truncate(t):
89
+ ids = tk.encode(t)
90
+ return tk.decode(ids[:cap]) if len(ids) > cap else t
91
+ texts = [_truncate(t) for t in texts]
92
+
93
+ t0 = time.perf_counter()
94
+ outs = embed_fn(texts)
95
+ log.info(f"embedded {n} rows in {time.perf_counter()-t0:.1f}s")
96
+
97
+ def vec(o):
98
+ e = o.outputs
99
+ e = getattr(e, "embedding", None) or getattr(e, "data", e)
100
+ return list(e)
101
+ ds = ds.add_column(args.output_column, [vec(o) for o in outs])
102
+ dim = len(ds[0][args.output_column])
103
+
104
+ card = DatasetCard(
105
+ f"# {args.output_dataset}\n\nEmbeddings of `{args.input_dataset}` column `{args.column}` "
106
+ f"with [`{args.model}`](https://huggingface.co/{args.model}) (dim {dim}, vLLM pooling).\n\n"
107
+ f"Produced on Hugging Face Jobs with `uv-scripts/embeddings/generate-embeddings-vllm.py`.\n")
108
+ # Retry the push with an XET-disable fallback — a transient failure would lose the paid run.
109
+ max_retries = 3
110
+ for attempt in range(1, max_retries + 1):
111
+ try:
112
+ if attempt > 1:
113
+ log.warning("Disabling XET (fallback to HTTP upload)")
114
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
115
+ ds.push_to_hub(args.output_dataset, private=args.private)
116
+ break
117
+ except Exception as e:
118
+ log.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
119
+ if attempt < max_retries:
120
+ delay = 30 * (2 ** (attempt - 1))
121
+ log.info(f"Retrying in {delay}s...")
122
+ time.sleep(delay)
123
+ else:
124
+ log.error("All upload attempts failed. Results are lost.")
125
+ raise SystemExit(1)
126
+ try:
127
+ card.push_to_hub(args.output_dataset, repo_type="dataset")
128
+ except Exception as e:
129
+ log.warning(f"card push skipped: {e}")
130
+ log.info(f"✅ https://huggingface.co/datasets/{args.output_dataset}")
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()
generate-embeddings.py CHANGED
@@ -2,320 +2,354 @@
2
  # requires-python = ">=3.10"
3
  # dependencies = [
4
  # "datasets",
5
- # "sentence-transformers>=3.0.0",
6
- # "batched>=0.1.0",
7
  # "torch",
8
- # "huggingface-hub[hf_transfer]",
9
- # "tqdm",
10
  # "numpy",
 
 
 
11
  # ]
12
  # ///
13
-
14
- """
15
- Generate embeddings for text datasets using Sentence Transformers with dynamic batching.
16
-
17
- This script efficiently generates embeddings for large datasets using GPU acceleration
18
- and dynamic batching for optimal throughput.
19
-
20
- Example usage:
21
- # Basic usage
22
- uv run generate-embeddings.py \
23
- imdb \
24
- imdb-embeddings \
25
- --model-name sentence-transformers/all-MiniLM-L6-v2
26
-
27
- # With custom batch size and column
28
- uv run generate-embeddings.py \
29
- scientific-papers \
30
- paper-embeddings \
31
- --model-name BAAI/bge-base-en-v1.5 \
32
- --text-column abstract \
33
- --batch-size 64
34
-
35
- # Process subset for testing
36
- uv run generate-embeddings.py \
37
- my-dataset \
38
- my-embeddings \
39
- --max-samples 1000
40
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  import argparse
43
  import logging
44
  import os
 
45
  import sys
46
- from typing import List, Optional
47
 
48
- import batched
49
- import numpy as np
50
- import torch
51
- from datasets import Dataset, load_dataset
52
- from huggingface_hub import login
53
- from sentence_transformers import SentenceTransformer
54
- from tqdm import tqdm
55
 
56
- logging.basicConfig(level=logging.INFO)
57
- logger = logging.getLogger(__name__)
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- def estimate_batch_size(model: SentenceTransformer, sample_text: str, gpu_memory_gb: float = None) -> int:
61
- """Estimate optimal batch size based on available GPU memory."""
62
- if not torch.cuda.is_available():
63
- return 32 # CPU fallback
64
-
65
- if gpu_memory_gb is None:
66
- # Get available GPU memory
67
- gpu_memory_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
68
-
69
- # Get model size estimate
70
- model_params = sum(p.numel() for p in model.parameters())
71
- model_size_gb = (model_params * 4) / (1024**3) # Assuming float32
72
-
73
- # Estimate based on model size and available memory
74
- # Conservative estimate: use 60% of available memory for batching
75
- available_for_batch = (gpu_memory_gb - model_size_gb) * 0.6
76
-
77
- # Estimate memory per sample (very rough approximation)
78
- # Assuming average token length of 256, embedding dim of model.get_sentence_embedding_dimension()
79
- embedding_dim = model.get_sentence_embedding_dimension()
80
- memory_per_sample_gb = (256 * embedding_dim * 4) / (1024**3)
81
-
82
- estimated_batch_size = int(available_for_batch / memory_per_sample_gb)
83
-
84
- # Clamp to reasonable values
85
- estimated_batch_size = max(8, min(estimated_batch_size, 512))
86
-
87
- logger.info(f"Estimated optimal batch size: {estimated_batch_size}")
88
- return estimated_batch_size
89
-
90
-
91
- class EmbeddingGenerator:
92
- """Wrapper class for embedding generation with dynamic batching."""
93
-
94
- def __init__(self, model: SentenceTransformer, batch_size: Optional[int] = None):
95
- self.model = model
96
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
97
- self.model = self.model.to(self.device)
98
-
99
- # Estimate batch size if not provided
100
- if batch_size is None:
101
- sample_text = "This is a sample text for batch size estimation."
102
- batch_size = estimate_batch_size(model, sample_text)
103
-
104
- self.batch_size = batch_size
105
- logger.info(f"Using device: {self.device}")
106
- logger.info(f"Using batch size: {self.batch_size}")
107
-
108
- @batched.dynamically(timeout_ms=30000)
109
- def generate_embeddings(self, texts: List[str]) -> List[np.ndarray]:
110
- """Generate embeddings with dynamic batching."""
111
- # Convert to tensors for GPU processing
112
- embeddings = self.model.encode(
113
- texts,
114
- convert_to_tensor=True,
115
- show_progress_bar=False, # We'll use our own progress bar
116
- device=self.device,
117
- batch_size=self.batch_size # Pass batch size to encode
118
- )
119
- # Convert back to numpy arrays
120
- return embeddings.cpu().numpy()
121
-
122
-
123
- def process_dataset(
124
- dataset: Dataset,
125
- model: SentenceTransformer,
126
- text_column: str,
127
- batch_size: Optional[int] = None,
128
- show_progress: bool = True
129
- ) -> Dataset:
130
- """Process dataset to add embeddings."""
131
-
132
- # Initialize embedding generator
133
- generator = EmbeddingGenerator(model, batch_size)
134
-
135
- # Get texts
136
- texts = dataset[text_column]
137
-
138
- # Filter out None/empty texts
139
- valid_indices = []
140
- valid_texts = []
141
- for i, text in enumerate(texts):
142
- if text and isinstance(text, str) and text.strip():
143
- valid_indices.append(i)
144
- valid_texts.append(text)
145
-
146
- if len(valid_texts) == 0:
147
- logger.error(f"No valid texts found in column '{text_column}'")
148
- sys.exit(1)
149
-
150
- logger.info(f"Processing {len(valid_texts)} valid texts (filtered {len(texts) - len(valid_texts)} invalid)")
151
-
152
- # Generate embeddings with progress bar
153
- all_embeddings = []
154
-
155
- if show_progress:
156
- # Process in chunks to show progress
157
- chunk_size = generator.batch_size * 10 # Process multiple batches at once
158
- for i in tqdm(range(0, len(valid_texts), chunk_size), desc="Generating embeddings"):
159
- chunk = valid_texts[i:i + chunk_size]
160
- chunk_embeddings = generator.generate_embeddings(chunk)
161
- all_embeddings.extend(chunk_embeddings)
162
- else:
163
- all_embeddings = generator.generate_embeddings(valid_texts)
164
-
165
- # Create new dataset with embeddings
166
- # Initialize with None for all indices
167
- embedding_column = [None] * len(texts)
168
- for idx, embedding in zip(valid_indices, all_embeddings):
169
- embedding_column[idx] = embedding.tolist()
170
-
171
- # Add embeddings to dataset
172
- dataset = dataset.add_column("embeddings", embedding_column)
173
-
174
- return dataset
175
 
176
 
177
  def main():
178
- parser = argparse.ArgumentParser(
179
- description="Generate embeddings for text datasets",
180
- formatter_class=argparse.RawDescriptionHelpFormatter,
181
- epilog=__doc__,
182
- )
183
-
184
- parser.add_argument(
185
- "input_dataset",
186
- type=str,
187
- help="Input dataset ID from Hugging Face Hub",
188
- )
189
- parser.add_argument(
190
- "output_dataset",
191
- type=str,
192
- help="Output dataset ID for Hugging Face Hub",
193
- )
194
- parser.add_argument(
195
- "--model-name",
196
- type=str,
197
- default="sentence-transformers/all-MiniLM-L6-v2",
198
- help="Sentence Transformer model to use (default: all-MiniLM-L6-v2)",
199
- )
200
- parser.add_argument(
201
- "--text-column",
202
- type=str,
203
- default="text",
204
- help="Name of the text column in the input dataset (default: text)",
205
- )
206
- parser.add_argument(
207
- "--batch-size",
208
- type=int,
209
- default=None,
210
- help="Batch size for processing (default: auto-detect based on GPU memory)",
211
- )
212
- parser.add_argument(
213
- "--max-samples",
214
- type=int,
215
- default=None,
216
- help="Maximum number of samples to process (default: all)",
217
- )
218
- parser.add_argument(
219
- "--split",
220
- type=str,
221
- default="train",
222
- help="Dataset split to use (default: train)",
223
- )
224
- parser.add_argument(
225
- "--hf-token",
226
- type=str,
227
- default=None,
228
- help="Hugging Face API token",
229
- )
230
- parser.add_argument(
231
- "--private",
232
- action="store_true",
233
- help="Make the output dataset private",
234
- )
235
- parser.add_argument(
236
- "--normalize",
237
- action="store_true",
238
- help="Normalize embeddings to unit length",
239
- )
240
-
241
- args = parser.parse_args()
242
-
243
- # Check GPU availability
244
  if not torch.cuda.is_available():
245
- logger.warning("CUDA is not available. Running on CPU will be slower.")
246
- response = input("Continue anyway? (y/n): ")
247
- if response.lower() != 'y':
248
- sys.exit(0)
249
-
250
- # Login to Hugging Face
251
- hf_token = args.hf_token or os.environ.get("HF_TOKEN")
252
- if hf_token:
253
- login(token=hf_token)
254
- else:
255
- logger.warning("No HF token provided. You may not be able to push to the Hub.")
256
-
257
- # Load input dataset
258
- logger.info(f"Loading dataset: {args.input_dataset}")
259
- dataset = load_dataset(args.input_dataset, split=args.split)
260
-
261
- # Validate text column exists
262
- if args.text_column not in dataset.column_names:
263
- logger.error(f"Column '{args.text_column}' not found in dataset.")
264
- logger.error(f"Available columns: {dataset.column_names}")
265
  sys.exit(1)
266
-
267
- # Limit samples if requested
268
  if args.max_samples:
269
- dataset = dataset.select(range(min(args.max_samples, len(dataset))))
270
- logger.info(f"Limited to {len(dataset)} samples")
271
-
272
- # Load model
273
- logger.info(f"Loading model: {args.model_name}")
274
- model = SentenceTransformer(args.model_name)
275
-
276
- # Set normalization if requested
277
- if args.normalize:
278
- model.normalize_embeddings = True
279
- logger.info("Embeddings will be normalized to unit length")
280
-
281
- # Log model info
282
- embedding_dim = model.get_sentence_embedding_dimension()
283
- logger.info(f"Embedding dimension: {embedding_dim}")
284
- logger.info(f"Max sequence length: {model.max_seq_length}")
285
-
286
- # Process dataset
287
- dataset_with_embeddings = process_dataset(
288
- dataset,
289
- model,
290
- args.text_column,
291
- args.batch_size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  )
293
-
294
- # Log statistics
295
- logger.info(f"\n✅ Generated embeddings for {len(dataset_with_embeddings)} samples")
296
- logger.info(f"Embedding dimension: {embedding_dim}")
297
-
298
- # Show sample
299
- sample = dataset_with_embeddings[0]
300
- logger.info(f"\nSample:")
301
- logger.info(f"Text: {sample[args.text_column][:100]}...")
302
- if sample['embeddings'] is not None:
303
- logger.info(f"Embedding shape: {len(sample['embeddings'])}")
304
- logger.info(f"Embedding (first 5 values): {sample['embeddings'][:5]}")
305
-
306
- # Push to Hub
307
- logger.info(f"\nPushing dataset to Hub: {args.output_dataset}")
308
- dataset_with_embeddings.push_to_hub(args.output_dataset, private=args.private)
309
-
310
- logger.info(f"\n✅ Dataset with embeddings available at: https://huggingface.co/datasets/{args.output_dataset}")
 
 
 
 
 
 
 
311
 
312
 
313
  if __name__ == "__main__":
314
- # Show example command if no args provided
315
- if len(sys.argv) == 1:
316
- print("Example command:")
317
- print("uv run generate-embeddings.py imdb imdb-embeddings --model-name sentence-transformers/all-MiniLM-L6-v2")
318
- print("\nFor HF Jobs:")
319
- print("hf jobs run --gpu a10 uv run generate-embeddings.py <input> <output> --model-name <model>")
320
-
321
- main()
 
2
  # requires-python = ">=3.10"
3
  # dependencies = [
4
  # "datasets",
5
+ # "sentence-transformers>=5.0.0",
 
6
  # "torch",
 
 
7
  # "numpy",
8
+ # "pillow",
9
+ # "einops",
10
+ # "huggingface-hub",
11
  # ]
12
  # ///
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  """
14
+ Generate embeddings for a Hugging Face dataset (text OR images) with sentence-transformers,
15
+ and push the result back to the Hub as a new dataset with an `embeddings` column.
16
+
17
+ This is the simple, ergonomic default. It runs as one command on the bare uv image, on CPU
18
+ or any GPU flavor. For maximum throughput on large *decoder* embedding models (e.g.
19
+ Qwen3-Embedding), see the vLLM variant; to get a searchable vector index as a Hub dataset,
20
+ see the Lance variant.
21
+
22
+ PROMPTS (retrieval correctness — read this):
23
+ Many embedding models need a DIFFERENT prefix/instruction for documents vs queries, and
24
+ getting it wrong silently degrades retrieval. This script embeds a *document corpus* by
25
+ default, via sentence-transformers' native encode_document()/encode_query() (which also
26
+ route Router models by task), picking the right document convention for you:
27
+ 1. the model's REGISTERED prompt if it ships one (e.g. Qwen3-Embedding) — selected
28
+ natively by encode_document/encode_query, else
29
+ 2. a small built-in table of well-known families (e5, nomic, bge), else
30
+ 3. no prefix.
31
+ Heads-up: current sentence-transformers injects a placeholder prompts dict
32
+ {"query": "", "document": ""} even for models that register NOTHING — so e5 ("passage: "),
33
+ nomic ("search_document: ") etc. look prompt-less via `.prompts`; their real prefixes live
34
+ only in the model card. The built-in table handles that. Override with --prompt '<prefix>'
35
+ or --prompt-name <registered-name>; embed a query set with --query-mode; force no prefix
36
+ with --prompt ''. The chosen prompt is logged and recorded in the dataset card.
37
+
38
+ Benchmarks (20k rows, seq-cap 512): all-MiniLM-L6-v2 ~900 rows/s on an L4 (~$0.24/1M rows);
39
+ bge-base-en-v1.5 ~120 rows/s. L4 is the cheapest flavor for these encoder models.
40
+
41
+ Examples:
42
+ # Text (default). Document convention auto-picked.
43
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\
44
+ stanfordnlp/imdb your-name/imdb-embeddings \\
45
+ --column text --model sentence-transformers/all-MiniLM-L6-v2
46
 
47
+ # e5: docs auto-get "passage: ". (--prompt 'passage: ' would be the explicit form.)
48
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\
49
+ stanfordnlp/imdb your-name/imdb-e5 --model intfloat/multilingual-e5-large
50
+
51
+ # Images (CLIP) — prompts don't apply.
52
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\
53
+ your-name/photos your-name/photos-embeddings \\
54
+ --modality image --column image --model clip-ViT-B-32
55
+
56
+ # Test on a small slice first, keep the output private
57
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\
58
+ stanfordnlp/imdb your-name/imdb-emb --max-samples 100 --private
59
+ """
60
  import argparse
61
  import logging
62
  import os
63
+ import re
64
  import sys
65
+ import time
66
 
67
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
68
+ logger = logging.getLogger("generate-embeddings")
 
 
 
 
 
69
 
 
 
70
 
71
+ def find_batch_size(model, sample, normalize, candidates=(32, 64, 128, 256)):
72
+ """Probe for the fastest batch that fits (used by --batch-size auto). Throughput is NOT
73
+ monotonic in batch size, so we time a few on a warmup sample and keep the fastest that doesn't
74
+ OOM. Why bigger isn't better: for text, larger batches pad to the longest member + add overhead;
75
+ for images, the ViT forward already saturates the GPU by ~batch 32. Works for text and images."""
76
+ import time
77
+ import torch
78
+ warm = sample[: min(1024, len(sample))]
79
+ try: # one untimed warmup so cudnn autotune doesn't penalise the first probe
80
+ model.encode(warm[:32], batch_size=32, show_progress_bar=False,
81
+ convert_to_numpy=True, normalize_embeddings=normalize)
82
+ except Exception:
83
+ pass
84
+ best_bs, best_rps = candidates[0], 0.0
85
+ for bs in candidates:
86
+ try:
87
+ if torch.cuda.is_available():
88
+ torch.cuda.empty_cache()
89
+ torch.cuda.synchronize()
90
+ t = time.perf_counter()
91
+ model.encode(warm, batch_size=bs, show_progress_bar=False,
92
+ convert_to_numpy=True, normalize_embeddings=normalize)
93
+ if torch.cuda.is_available():
94
+ torch.cuda.synchronize()
95
+ rps = len(warm) / (time.perf_counter() - t)
96
+ logger.info(f" auto-batch probe bs={bs}: {rps:.0f} rows/s")
97
+ if rps > best_rps:
98
+ best_rps, best_bs = rps, bs
99
+ except RuntimeError as e:
100
+ if "out of memory" in str(e).lower():
101
+ logger.info(f" auto-batch bs={bs} OOM → stopping probe")
102
+ if torch.cuda.is_available():
103
+ torch.cuda.empty_cache()
104
+ break
105
+ raise
106
+ logger.info(f"auto-batch chose bs={best_bs} ({best_rps:.0f} rows/s on warmup)")
107
+ return best_bs
108
 
109
+
110
+ def known_convention(model_id):
111
+ """Best-effort (query_prefix, doc_prefix) for common families whose convention is
112
+ documented in the model card but NOT registered in config_sentence_transformers.json.
113
+ Returns None if unknown. Overridable with --prompt / --no-auto-prompt.
114
+
115
+ Verified 2026-07-03 on HF Jobs: of e5 / nomic / bge-en / bge-m3 / Qwen3-Embedding, only
116
+ Qwen3-Embedding registers real ST prompts; the rest ship none and rely on manual prefixes.
117
+ """
118
+ m = model_id.lower()
119
+ # Instruction-style embedders (e5-*-instruct, gte-Qwen, ...): prefer the model's REGISTERED
120
+ # prompt or an explicit --prompt; don't guess a literal prefix.
121
+ if "instruct" in m:
122
+ return None
123
+ if "nomic-embed-text" in m:
124
+ return ("search_query: ", "search_document: ")
125
+ if "bge-m3" in m: # bge-m3 uses no prompts
126
+ return ("", "")
127
+ # e5 family (e5-base/large/small, multilingual-e5-*), boundaried so e.g. "table5" or a
128
+ # model with "e5" mid-word can't silently pick up "query:/passage:" prefixes.
129
+ if re.search(r"(^|[/_-])e5([_-]|$)", m):
130
+ return ("query: ", "passage: ")
131
+ if "bge" in m and "-en" in m: # English bge retrieval: query instruction, docs raw
132
+ return ("Represent this sentence for searching relevant passages: ", "")
133
+ return None
134
+
135
+
136
+ def resolve_prompt(model, model_id, is_query, args):
137
+ """Decide the EXPLICIT prefix to pass to encode_query()/encode_document(), or None to let the
138
+ native method choose. sentence-transformers' encode_query/encode_document already select the
139
+ model's REGISTERED query/document prompt and set the Router task — we lean on that, and only
140
+ supply a prefix ourselves for (a) explicit --prompt/--prompt-name, (b) the known-family table
141
+ covering models that register nothing (e5, nomic, bge-en — their prefixes live only in the
142
+ model card, so the native fallback would silently apply NO prefix)."""
143
+ registered = dict(getattr(model, "prompts", {}) or {})
144
+ # Current sentence-transformers injects a placeholder {"query":"","document":""} for models
145
+ # with no config prompts; only non-empty values are real conventions.
146
+ real = {k: v for k, v in registered.items() if v}
147
+ logger.info(f"Registered prompts: {registered} · real (non-empty): {real or 'none'} · "
148
+ f"default_prompt_name={getattr(model, 'default_prompt_name', None)}")
149
+ side = "query" if is_query else "document"
150
+
151
+ if args.prompt is not None: # includes --prompt '' to force no prefix
152
+ logger.info(f"Prompt: raw --prompt → {args.prompt!r}")
153
+ return args.prompt
154
+ if args.prompt_name:
155
+ if args.prompt_name not in registered:
156
+ logger.error(f"--prompt-name {args.prompt_name!r} not registered ({list(registered)}); "
157
+ f"use --prompt '<raw prefix>' instead.")
158
+ sys.exit(1)
159
+ logger.info(f"Prompt: registered prompt_name={args.prompt_name!r} {registered[args.prompt_name]!r}")
160
+ return registered[args.prompt_name]
161
+ native_keys = ("query",) if is_query else ("document", "passage", "corpus")
162
+ if any(real.get(k) for k in native_keys):
163
+ # Model ships a real prompt for this side (e.g. Qwen3 query) → encode_query/encode_document
164
+ # selects it natively (and routes Router models by task).
165
+ logger.info(f"Prompt: model-registered — selected natively by encode_{side}()")
166
+ return None
167
+
168
+ kc = known_convention(model_id)
169
+ if kc is not None:
170
+ chosen = kc[0] if is_query else kc[1]
171
+ if args.no_auto_prompt:
172
+ if chosen:
173
+ logger.warning(f"--no-auto-prompt set: NOT applying the known {side} prefix {chosen!r} for "
174
+ f"{model_id}. Retrieval may degrade unless you pass --prompt.")
175
+ return ""
176
+ logger.info(f"Prompt: known-family {side} prefix → {chosen!r} (override with --prompt)"
177
+ if chosen else f"Prompt: known-family no {side} prefix needed")
178
+ return chosen
179
+
180
+ logger.info(f"Prompt: none registered or known for {model_id} — encode_{side}() applies no prefix. "
181
+ f"If it's a retrieval model needing a query/document prefix, pass --prompt.")
182
+ return None
183
+
184
+
185
+ def sniff_token_lengths(model, texts, max_seq_len, sample=512):
186
+ """Tokenize a sample to report the token-length distribution + how much --max-seq-len truncates,
187
+ and return the median length (used to pick the auto-batch candidate range: short texts under-use
188
+ the GPU at small batch, long texts waste compute on padding). Text only; returns None on failure."""
189
+ try:
190
+ tok = model.tokenizer
191
+ except Exception:
192
+ return None
193
+ s = texts[: min(sample, len(texts))]
194
+ lens = sorted(len(tok.encode(t, add_special_tokens=True)) for t in s)
195
+ n = len(lens)
196
+ if not n:
197
+ return None
198
+ median, p90, mx = lens[n // 2], lens[min(n - 1, int(n * 0.9))], lens[-1]
199
+ pct_over = 100 * sum(1 for L in lens if L > max_seq_len) / n
200
+ note = (f" → {pct_over:.0f}% exceed --max-seq-len {max_seq_len} and are truncated "
201
+ f"(raise it to keep more, at higher cost/slower)" if pct_over >= 5
202
+ else f" (all within --max-seq-len {max_seq_len})")
203
+ logger.info(f"Token lengths (sample {n}): median {median}, p90 {p90}, max {mx}{note}")
204
+ return median
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
 
207
  def main():
208
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
209
+ p.add_argument("input_dataset", help="Input dataset ID on the Hugging Face Hub")
210
+ p.add_argument("output_dataset", help="Output dataset ID to create on the Hub")
211
+ p.add_argument("--model", default="sentence-transformers/all-MiniLM-L6-v2",
212
+ help="sentence-transformers model (text or CLIP image model)")
213
+ p.add_argument("--modality", choices=["text", "image"], default="text")
214
+ p.add_argument("--column", default="text", help="Input column (text string, or image)")
215
+ p.add_argument("--output-column", default="embeddings")
216
+ p.add_argument("--config", default=None, help="Dataset config name (e.g. wikipedia needs one)")
217
+ p.add_argument("--split", default="train")
218
+ p.add_argument("--max-samples", type=int, default=None, help="Limit rows (for testing)")
219
+ p.add_argument("--batch-size", default="auto",
220
+ help="'auto' probes for the fastest batch that fits, or pass an int")
221
+ p.add_argument("--prompt", default=None,
222
+ help="Raw prefix to prepend to every text (e.g. 'passage: '). Highest precedence. "
223
+ "Use --prompt '' to force NO prefix.")
224
+ p.add_argument("--prompt-name", default=None,
225
+ help="Name of a prompt REGISTERED by the model (e.g. 'query'); errors if not registered.")
226
+ p.add_argument("--query-mode", action="store_true",
227
+ help="Embed inputs as QUERIES, not documents (flips the auto-picked convention).")
228
+ p.add_argument("--no-auto-prompt", action="store_true",
229
+ help="Disable the built-in known-family prefix table (still honours registered prompts).")
230
+ p.add_argument("--max-seq-len", type=int, default=512,
231
+ help="Truncate text to this many tokens (predictable cost; RAG-typical)")
232
+ p.add_argument("--normalize", action="store_true", default=True)
233
+ p.add_argument("--no-normalize", dest="normalize", action="store_false")
234
+ p.add_argument("--private", action="store_true", help="Make the output dataset private")
235
+ args = p.parse_args()
236
+
237
+ import torch
238
+ from datasets import load_dataset
239
+ from huggingface_hub import DatasetCard, login
240
+ from sentence_transformers import SentenceTransformer
241
+
242
+ token = os.environ.get("HF_TOKEN")
243
+ if token:
244
+ login(token=token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  if not torch.cuda.is_available():
246
+ logger.warning("No CUDA running on CPU (much slower). Prefer a GPU flavor, e.g. --flavor l4x1.")
247
+
248
+ logger.info(f"Loading {args.input_dataset} [{args.split}]")
249
+ ds = (load_dataset(args.input_dataset, args.config, split=args.split) if args.config
250
+ else load_dataset(args.input_dataset, split=args.split))
251
+ if args.column not in ds.column_names:
252
+ logger.error(f"Column {args.column!r} not found. Available: {ds.column_names}")
253
+ sys.exit(1)
254
+ if args.output_column in ds.column_names:
255
+ logger.error(f"Output column {args.output_column!r} already exists — choose another --output-column.")
 
 
 
 
 
 
 
 
 
 
256
  sys.exit(1)
 
 
257
  if args.max_samples:
258
+ ds = ds.select(range(min(args.max_samples, len(ds))))
259
+ logger.info(f"{len(ds)} rows; modality={args.modality}")
260
+
261
+ device = "cuda" if torch.cuda.is_available() else "cpu"
262
+ model = SentenceTransformer(args.model, device=device, trust_remote_code=True)
263
+ if args.modality == "text" and getattr(model, "max_seq_length", None):
264
+ model.max_seq_length = min(model.max_seq_length, args.max_seq_len)
265
+ dim = model.get_sentence_embedding_dimension()
266
+ logger.info(f"Model {args.model} on {device}; dim={dim}")
267
+
268
+ # Prompt handling many retrieval models need a query vs document/passage prefix (text only).
269
+ prompt_str = None # None = let encode_query/encode_document choose natively
270
+ if args.modality == "text":
271
+ prompt_str = resolve_prompt(model, args.model, is_query=args.query_mode, args=args)
272
+ items = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]]
273
+ else:
274
+ if args.prompt or args.prompt_name:
275
+ logger.warning("--prompt/--prompt-name ignored for image modality.")
276
+ items = [im.convert("RGB") if hasattr(im, "convert") else im for im in ds[args.column]]
277
+
278
+ median_tok = sniff_token_lengths(model, items, args.max_seq_len) if args.modality == "text" else None
279
+
280
+ if str(args.batch_size).lower() == "auto":
281
+ # Pick the probe range from the data shape. Images: the ViT forward saturates the GPU by
282
+ # ~batch 32, so bigger only adds memory — probe low. Text: short texts under-use the GPU at
283
+ # small batch (probe bigger); long texts pad-waste at big batch (stay modest). Probe verifies.
284
+ if args.modality == "image":
285
+ candidates = (32, 64, 128)
286
+ elif median_tok is None or median_tok >= 256:
287
+ candidates = (32, 64, 128, 256)
288
+ elif median_tok >= 64:
289
+ candidates = (64, 128, 256, 512)
290
+ else:
291
+ candidates = (128, 256, 512, 1024)
292
+ logger.info(f"Finding batch size (--batch-size auto; candidates {candidates})...")
293
+ batch_size = find_batch_size(model, items, args.normalize, candidates=candidates)
294
+ else:
295
+ batch_size = int(args.batch_size)
296
+
297
+ # Text goes through encode_query/encode_document (native registered-prompt selection + Router
298
+ # task routing); our resolved prefix, when not None, overrides via prompt=. Images use encode().
299
+ if args.modality == "text":
300
+ encode_fn = model.encode_query if args.query_mode else model.encode_document
301
+ encode_kwargs = {"prompt": prompt_str} if prompt_str is not None else {}
302
+ else:
303
+ encode_fn = model.encode
304
+ encode_kwargs = {}
305
+ t0 = time.perf_counter()
306
+ emb = encode_fn(items, batch_size=batch_size, show_progress_bar=True,
307
+ convert_to_numpy=True, normalize_embeddings=args.normalize, **encode_kwargs)
308
+ secs = time.perf_counter() - t0
309
+ logger.info(f"Embedded {len(items)} in {secs:.1f}s ({len(items)/secs:.0f} rows/s), dim={dim}")
310
+
311
+ ds = ds.add_column(args.output_column, [e.tolist() for e in emb])
312
+
313
+ # For the card: record the effective prefix (explicit, else the model's registered one).
314
+ side_keys = ("query",) if args.query_mode else ("document", "passage", "corpus")
315
+ effective = prompt_str if prompt_str is not None else next(
316
+ (v for k in side_keys if (v := (getattr(model, "prompts", {}) or {}).get(k))), "")
317
+ prompt_line = f"`{effective}`" if effective else "(none)"
318
+ card = DatasetCard(
319
+ f"# {args.output_dataset}\n\n"
320
+ f"Embeddings of [`{args.input_dataset}`](https://huggingface.co/datasets/{args.input_dataset}) "
321
+ f"column `{args.column}`.\n\n"
322
+ f"- Model: [`{args.model}`](https://huggingface.co/{args.model}) (dim {dim})\n"
323
+ f"- Column: `{args.output_column}` · normalized: {args.normalize}\n"
324
+ f"- Prompt prepended ({'query' if args.query_mode else 'document'} side): {prompt_line}\n\n"
325
+ f"Produced on Hugging Face Jobs with `uv-scripts/embeddings/generate-embeddings.py`.\n"
326
  )
327
+ # Retry the push with an XET-disable fallback: a transient upload failure here would
328
+ # otherwise lose the whole (paid) embedding run.
329
+ logger.info(f"Pushing to {args.output_dataset} (private={args.private})")
330
+ max_retries = 3
331
+ for attempt in range(1, max_retries + 1):
332
+ try:
333
+ if attempt > 1:
334
+ logger.warning("Disabling XET (fallback to HTTP upload)")
335
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
336
+ ds.push_to_hub(args.output_dataset, private=args.private)
337
+ break
338
+ except Exception as e:
339
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
340
+ if attempt < max_retries:
341
+ delay = 30 * (2 ** (attempt - 1))
342
+ logger.info(f"Retrying in {delay}s...")
343
+ time.sleep(delay)
344
+ else:
345
+ logger.error("All upload attempts failed. Results are lost.")
346
+ sys.exit(1)
347
+ try:
348
+ card.push_to_hub(args.output_dataset, repo_type="dataset")
349
+ except Exception as e:
350
+ logger.warning(f"card push skipped: {e}")
351
+ logger.info(f"✅ https://huggingface.co/datasets/{args.output_dataset}")
352
 
353
 
354
  if __name__ == "__main__":
355
+ main()