Sync from GitHub via hub-sync
Browse filesFiles changed (5)
- HEURISTICS.mdAdded+137
- README.mdAdded+139
- embed-to-lance.pyAdded+180
- generate-embeddings-vllm.pyAdded+134
- generate-embeddings.py+327-293
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Embedding-on-Jobs heuristics — what we measured, and what to try
A field guide for the `embeddings/` recipes, for **humans and agents**. Everything here ismeasured on HF Jobs (2026-07), not folklore. If you're an agent picking settings for a user'sdata: read the TL;DR, match the data shape, use the defaults; the recipe's `--batch-size auto`+ token sniffer handle the rest.
## First: pick a *current* model, not the frozen list below
Embedding quality moves fast. The specific models in this guide are what we **benchmarked in2026-07** — a durable baseline, not a permanent answer. Before committing, find the current best(an agent should do this automatically, not trust a hard-coded name):
- **MTEB leaderboard** — the canonical ranking: <https://huggingface.co/spaces/mteb/leaderboard>- **The Hub, from the CLI** (scriptable, always current): ```bash hf models ls --filter sentence-transformers --sort trending_score --limit 20 # what's hot now hf models ls --filter sentence-transformers --sort downloads --limit 20 # proven workhorses hf models ls --search embedding --num-parameters min:0,max:1B --sort trending_score ``` Sort by `trending_score` or `downloads`, **not `created_at`** — the newest list is mostly empty test repos. Then check the model card for its prompt convention (see Prompts) and license.
The **heuristics here are model-independent** — token-bound throughput, batch ~128, L4-for-encoders,prompts-matter, seq-len cost hold whatever tops the leaderboard next week. Use them; swap in thecurrent model. (E.g. as of this writing the CLI surfaced newer options like jina-embeddings-v5,voyage-4-nano, and LiquidAI's ColBERT that postdate parts of this guide.)
## TL;DR decision table*(benchmarked examples, 2026-07 — run the queries above for the current best)*
| Your situation | Model | Flavor | Notes ||---|---|---|---|| Default / fast / cheap (English) | `all-MiniLM-L6-v2` | `l4x1` | ~900 rows/s, ~$0.24/1M rows, dim 384 || Better English quality | `BAAI/bge-base-en-v1.5` | `l4x1` | ~120 rows/s, ~$1.87/1M, dim 768 || Multilingual / long-context | `BAAI/bge-m3` | `l4x1`/`a10g-large` | slower (dim 1024); use only if you need it || Top open quality (decoder) | `Qwen/Qwen3-Embedding-0.6B` | `a100-large` + **vLLM variant** | A100 is 4× the L4 here AND cheaper/1M || Max quality, cost no object | `Qwen/Qwen3-Embedding-8B` (4B benched) | `a100-large` + vLLM | ~$7/1M, dim 2560 || Images, fast | `clip-ViT-B-32` | `l4x1` | ~395 img/s (bs=32), dim 512 || Images, higher quality | `clip-ViT-L-14` or SigLIP-2-large | `l4x1`/`a10g-large` | slower, larger dim |
**One-line scale proof:** 241,787 Wikipedia articles → a searchable Lance vector DB on the Hubin **4.5 min for ~$0.07** on a single L4 (all-MiniLM). Cheap at scale is real.
## Text: the load-bearing heuristics
**1. Throughput is token-bound, not row-bound.** Same model (all-MiniLM, L4): short text(AG News, median 53 tokens) = **2866 rows/s**; long text (IMDB, median ~300 tokens) = **912rows/s**. A 3× swing from text length alone. So estimate cost in *tokens*, not rows, and knowthat "rows/s" quoted anywhere is only meaningful with a text length attached.
**2. Batch size peaks around ~128 — bigger is usually *slower*.** Counter-intuitive butconsistent: at batch 128/256/512/1024, all-MiniLM on short text ran 2443 / 1981 / 1355 / 796rows/s — monotonically *down*. sentence-transformers length-sorts internally, and largerbatches pad to the longest member + add overhead. **Don't crank the batch.** `--batch-size auto`probes and lands here for you; the token sniffer widens the probe range for short text (and itstill picks ~128).
**3. Sequence length is a real cost lever — and bigger models feel it more.** On long text(IMDB), capping `--max-seq-len` 512 → 128 sped things up **1.8×** for all-MiniLM (912 → 1682rows/s) and **2.8×** for bge-base (119 → 332 rows/s). The larger model benefits *more* becauseattention is O(n²), so shorter sequences help disproportionately, not just linearly.
| Model | seq-cap 128 | seq-cap 512 | speedup from capping ||---|---|---|---|| all-MiniLM-L6-v2 | 1682 rows/s | 912 rows/s | 1.8× || bge-base-en-v1.5 | 332 rows/s | 119 rows/s | 2.8× |
Rule of thumb: RAG-sized chunks live under 512 tokens, so the `--max-seq-len 512` default isright for most retrieval corpora. **Lower the cap for a big, cheap speedup when your text isshort anyway or you can tolerate truncation** (the token sniffer tells you what fraction you'dlose). Raise it only if the sniffer warns you're truncating a lot AND you need the tail —budget for the slowdown, especially on bigger models.
**4. GPU: L4 for encoders, A100 only for decoders.** $/1M rows (encode-only):
| Model (type) | L4 $0.80 | A10G $1.50 | A100 $2.50 ||---|---|---|---|| all-MiniLM (encoder) | **$0.24** | $0.38 | $0.51 || bge-base (encoder) | **$1.87** | $2.02 | $2.66 || bge-m3 (encoder) | **$6.17** | $6.22 | $8.27 || Qwen3-Embedding-0.6B (decoder) | $3.77 | $4.48 | **$2.78** |
Encoders (MiniLM, bge) are cheapest on the L4 — the bigger GPU doesn't earn its price. **Decoder**embedders (Qwen3-Embedding) are the exception: the A100 runs them ~4× faster AND cheaper per 1M,because decoders actually use the extra compute.
**5. Engine: sentence-transformers by default; vLLM ~2× for decoder embedders.** On the sameQwen3-Embedding-0.6B/L4, vLLM pooling hit 121 rows/s vs sentence-transformers' 59 (~2×). Forsmall encoders, sentence-transformers is already fast and far simpler — use the default. Switchto `generate-embeddings-vllm.py` only for large decoder embedders at scale.
**6. Prompts are a correctness issue, not a nicety.** Many retrieval models need a *different*prefix for documents vs queries, and mismatching them silently hurts retrieval. Gotcha weverified: sentence-transformers reports an empty placeholder `{"query":"","document":""}` formodels that ship NO prompts — so e5 ("passage: "/"query: ") and nomic ("search_document:"/"search_query: ") *look* prompt-less but aren't; their prefixes live only in the model card.The recipe's built-in family table handles e5 / nomic / bge / Qwen3 automatically for a documentcorpus; pass `--query-mode` for a query set, or `--prompt '<prefix>'` to override.
## Images: heuristics
- **Model choice:** `clip-ViT-B-32` (~395 img/s on L4 at bs=32, dim 512) is the fast default; `clip-ViT-L-14` (40 img/s, dim 768) or SigLIP-2-large (46 img/s, dim 1024) for quality. SigLIP-2 wins at the large tier but needs the transformers path (~4× the code); CLIP-via-sentence-transformers is the clean one-liner.- **Flavor + cost: L4 is the cost pick for every image model.** clip-ViT-B-32 ≈ **$0.56/1M images** (pre-sized) or ~$1.03/1M (full-res); siglip2-large ≈ $4.84/1M. A10G is ~1.3× faster but 1.875× the rate (~$0.92/1M for B-32) → use it only when wall-clock, not cost, matters.- **`--batch-size auto` uses 32/64/128 for images; 64 is a safe manual default** (only ~6% off the bs=32 peak on full-res images, and more robust).- **Batch: images favor *small* batches — the opposite of the "fixed-size → batch big" hunch.** clip-ViT-B-32 on L4: bs=32 = **395 img/s** (fastest), then flat/slower above (343 / 330 / 333 / 331 / 329 at bs 64 / 128 / 256 / 512 / 1024). Peak GPU mem stays tiny (0.7–4 GB even at bs=1024), so it's not a memory ceiling — it's per-batch pipeline overhead. So "don't crank the batch" holds for images too, at an even smaller optimum than text. `--batch-size auto` probes from 32 and lands on it — no image-specific tuning needed.- **GPU memory = f(batch × model) only** — models resize to a fixed 224px, so source resolution never touches GPU memory (verified: identical peak across a 32px and a full-res dataset). BUT **full-res images run ~1.8× slower** than tiny ones (395 → 215 img/s for B-32) — decode/resize is a real CPU tax, negligible *only* for pre-sized/small images.
## Storage / dimensions
Bigger embedding dim = more storage + slower vector search. If your model supports **Matryoshka**truncation (nomic-embed, Qwen3-Embedding), you can keep the first N dims (e.g. 256 of 768) formuch cheaper storage/search at a small quality cost — worth it for large indexes. Alwaysnormalize (the recipe does) so cosine = dot product.
## Other modalitiesText and images are what these recipes cover. **Audio** (CLAP / speech-encoder embeddings) and**code** (code-specialized text embedders) use different models — a separate recipe, not this one.Note it and route users there rather than forcing them through the image/text path.
## The evidence (measured on HF Jobs, 2026-07)Measured on HF Jobs (2026-07) with the scripts in this folder. Text: 20k rows, batch 64, seq-cap 512 unlessnoted. All datasets used were public; all test outputs were private.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139---viewer: falsetags:- uv-script- embeddings- sentence-transformers- vector-search---
# Embeddings
Generate embeddings for a Hugging Face dataset — text or images — with one command, on acloud GPU, no infra. The output lands back on the Hub as a new dataset (or, with the Lancevariant, as a **searchable vector index you can query over `hf://` without downloading**).
There is one simple default and two variants; they are separate single-file scripts becausetheir dependencies (sentence-transformers vs vLLM vs Lance) are too different to share one env.
| Script | Use it for | Engine ||---|---|---|| `generate-embeddings.py` | The default. Text or images. Simple, fast, runs anywhere. | sentence-transformers || `generate-embeddings-vllm.py` | Max throughput on large *decoder* embedding models (Qwen3-Embedding). | vLLM pooling || `embed-to-lance.py` | Get a **searchable vector index as a Hub dataset** (the "vector DB" path). | sentence-transformers + Lance |
## Quick start
```bash# Text — pick a model from the MTEB leaderboardhf jobs uv run --flavor l4x1 -s HF_TOKEN \ https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings.py \ stanfordnlp/imdb your-name/imdb-embeddings --column text
# Images (CLIP)hf jobs uv run --flavor l4x1 -s HF_TOKEN \ https://huggingface.co/datasets/uv-scripts/embeddings/raw/main/generate-embeddings.py \ your-name/photos your-name/photos-embeddings --modality image --column image --model clip-ViT-B-32```
Always try `--max-samples 100 --private` first.
## Which model?
**Find the *current* best — don't trust a fixed list** (embedding quality moves fast). Check the[MTEB leaderboard](https://huggingface.co/spaces/mteb/leaderboard), or from the CLI:
```bashhf models ls --filter sentence-transformers --sort trending_score --limit 20 # what's hot nowhf models ls --filter sentence-transformers --sort downloads --limit 20 # proven workhorses```(Sort by `trending_score`/`downloads`, not `created_at` — the newest list is mostly test repos.)
See **[HEURISTICS.md](./HEURISTICS.md)** for the full "which model / GPU / batch for your data" guide(measured). The table below is examples benchmarked 2026-07, not a permanent answer:
| Model | Params | Dim | Note ||---|---|---|---|| `sentence-transformers/all-MiniLM-L6-v2` | 22M | 384 | Fastest; safe default || `BAAI/bge-base-en-v1.5` | 109M | 768 | Strong English quality/speed balance || `BAAI/bge-m3` | 568M | 1024 | Multilingual + long context (slower) || `Qwen/Qwen3-Embedding-0.6B` | 596M | 1024 | Top open MTEB; decoder → use the vLLM variant / A100 |
Images: `clip-ViT-B-32` (fast) or `clip-ViT-L-14` (higher quality).
## Prompts (retrieval correctness — read this if you're building search)
Many retrieval models need a **different prefix for documents vs queries**, and getting itwrong silently degrades results. Worse, you can't trust `model.prompts`: currentsentence-transformers injects a placeholder `{"query": "", "document": ""}` even for modelsthat register **nothing**, so e5 / nomic / bge look "prompt-less" via that attribute whiletheir real prefixes live only in the model card.
`generate-embeddings.py` handles this. It embeds a **document corpus** by default and picks thedocument convention in this order: (1) the model's **registered** prompt if it ships a real one(e.g. Qwen3-Embedding), else (2) a small **built-in family table**, else (3) no prefix. Thechosen prefix is logged and written into the output dataset card.
| Family | Query prefix | Document prefix ||---|---|---|| e5 (`intfloat/e5-*`, `multilingual-e5-*`, non-instruct) | `query: ` | `passage: ` || nomic (`nomic-embed-text-*`) | `search_query: ` | `search_document: ` || bge English (`bge-*-en-*`) | `Represent this sentence for searching relevant passages: ` | (none) || bge-m3 | (none) | (none) || Qwen3-Embedding | registered by the model | (none) || anything else | — | — (pass `--prompt` if it needs one) |
Override the auto-pick:
- `--query-mode` — embed inputs as **queries**, not documents (flips the convention)- `--prompt 'passage: '` — force a raw prefix (highest precedence; `--prompt ''` forces none)- `--prompt-name query` — use a prompt the model registered, by name- `--no-auto-prompt` — turn off the family table (still honours registered prompts)
Instruct-style models (`e5-*-instruct`, `gte-Qwen…`) are deliberately left to their registeredprompt or your explicit `--prompt`, since the instruction is task-specific.
## Batch size (auto by default)
`--batch-size auto` (the default) times a few batch sizes on a warmup sample and keeps thefastest that fits — bigger isn't always faster, because variable-length text wastes compute onpadding. Pass `--batch-size 128` to pin it.
## Which GPU? (measured, 20k rows, seq-cap 512)
Throughput (rows/s) and cost per 1M rows:
| Model | L4 ($0.80/hr) | A10G ($1.50/hr) | A100 ($2.50/hr) ||---|---|---|---|| all-MiniLM-L6-v2 | 912 · **$0.24/1M** | 1099 · $0.38/1M | 1372 · $0.51/1M || bge-base-en-v1.5 | 119 · **$1.87/1M** | 206 · $2.02/1M | 261 · $2.66/1M || Qwen3-Embedding-0.6B | 59 · $3.77/1M | 93 · $4.48/1M | 250 · **$2.78/1M** |
**Default to `l4x1`** — cheapest per 1M rows for encoder models. For **decoder** embedders(Qwen3-Embedding) the A100 is both faster *and* cheaper per 1M (they use the extra compute),and the vLLM variant roughly doubles throughput again (Qwen3-Embedding-0.6B: ~121 rows/s on anL4 via `generate-embeddings-vllm.py`, ~2× the sentence-transformers path).
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.
## The vector-DB path (`embed-to-lance.py`)
Writes a [Lance](https://huggingface.co/docs/hub/datasets-lance) table with a vector index andpushes it as a Hub dataset. You (or anyone you share it with) can then search it directly over`hf://` **without downloading it**:
```pythonimport lanceds = lance.dataset("hf://datasets/your-name/my-vecdb/vecdb.lance") # opens in ~1s, no downloadhits = ds.to_table(nearest={"column": "vector", "q": query_vec, "k": 5})```
> **Query prompts:** embed `query_vec` with the model's *query* prefix (e5 → `"query: "`,> nomic → `"search_query: "`; the run prints the right one). Documents and queries use> different prefixes on these models — mismatching them silently degrades retrieval.
End-to-end this is fast and cheap: **all 241,787 Simple-English-Wikipedia articles → asearchable Lance vector DB on the Hub in ~4.5 min for ~$0.07 on a single L4** (load → embed →index → push, with `all-MiniLM-L6-v2`; pass `--model` to trade speed for quality).
Best for share-and-search over a corpus; for high-QPS serving, pull the dataset local first.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180# /// script# requires-python = ">=3.10"# dependencies = [# "datasets",# "sentence-transformers>=5.0.0",# "torch",# "numpy",# "einops",# "pyarrow",# "pylance",# "huggingface-hub",# ]# ///"""Embed a Hugging Face dataset and push it back as a Lance vector index — a Hub dataset thatIS a searchable vector database. Anyone you share it with can vector-search it over `hf://`without downloading it:
import lance ds = lance.dataset("hf://datasets/your-name/my-vecdb/vecdb.lance") # opens fast, no download hits = ds.to_table(nearest={"column": "vector", "q": query_vector, "k": 5})
Best for share-and-search over a corpus; for high-QPS serving, pull the dataset local first.
PROMPTS: documents are embedded with the model's known DOCUMENT convention (e5 → "passage: ",nomic → "search_document: "; bge-en/bge-m3 → none). At SEARCH time, embed your query with thematching QUERY prefix (printed at the end of the run) or retrieval quality silently drops.Override the document prefix with --prompt '<prefix>' (or --prompt '' for none).
hf jobs uv run --flavor l4x1 -s HF_TOKEN embed-to-lance.py \\ stanfordnlp/imdb your-name/imdb-vecdb --column text --model BAAI/bge-base-en-v1.5 --private"""import argparseimport loggingimport osimport reimport shutilimport sysimport timeimport numpy as npimport pyarrow as pa
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("embed-to-lance")
def known_convention(model_id): """(query_prefix, doc_prefix) for common families (documented in model cards, not registered in sentence-transformers config). Same table as generate-embeddings.py; None = unknown.""" m = model_id.lower() if "instruct" in m: return None if "nomic-embed-text" in m: return ("search_query: ", "search_document: ") if "bge-m3" in m: return ("", "") if re.search(r"(^|[/_-])e5([_-]|$)", m): return ("query: ", "passage: ") if "bge" in m and "-en" in m: return ("Represent this sentence for searching relevant passages: ", "") return None
def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("input_dataset") ap.add_argument("output_repo") ap.add_argument("--column", default="text") ap.add_argument("--config", default=None, help="dataset config name (e.g. wikipedia needs one)") ap.add_argument("--split", default="train") ap.add_argument("--model", default="BAAI/bge-base-en-v1.5") ap.add_argument("--max-samples", type=int, default=None) ap.add_argument("--batch-size", type=int, default=64) ap.add_argument("--max-seq-len", type=int, default=512) ap.add_argument("--prompt", default=None, help="Document prefix to prepend (default: auto from the known-family table; " "pass '' to force none)") ap.add_argument("--private", action="store_true") args = ap.parse_args()
import torch import lance from datasets import load_dataset from huggingface_hub import HfApi, login from sentence_transformers import SentenceTransformer
if os.environ.get("HF_TOKEN"): login(token=os.environ["HF_TOKEN"])
t_all = time.perf_counter() ds = load_dataset(args.input_dataset, args.config, split=args.split) if args.config \ else load_dataset(args.input_dataset, split=args.split) if args.max_samples: ds = ds.select(range(min(args.max_samples, len(ds)))) texts = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]] n = len(texts)
t_load = time.perf_counter()
device = "cuda" if torch.cuda.is_available() else "cpu" model = SentenceTransformer(args.model, device=device, trust_remote_code=True) if getattr(model, "max_seq_length", None): model.max_seq_length = min(model.max_seq_length, args.max_seq_len) dim = model.get_sentence_embedding_dimension()
# Document-side prompt: explicit --prompt wins (incl. '' for none), else the known-family # table; else None → encode_document() natively selects any REGISTERED document prompt # (and routes Router models by task). registered = {k: v for k, v in (getattr(model, "prompts", {}) or {}).items() if v} kc = known_convention(args.model) doc_prompt = args.prompt if args.prompt is not None else (kc[1] if kc else None) query_prompt = kc[0] if kc else registered.get("query", "") log.info(f"document prompt: {doc_prompt!r}" if doc_prompt else ("document prompt: native (registered)" if registered.get("document") else "document prompt: (none)"))
t0 = time.perf_counter() encode_kwargs = {"prompt": doc_prompt} if doc_prompt is not None else {} emb = model.encode_document(texts, batch_size=args.batch_size, show_progress_bar=True, convert_to_numpy=True, normalize_embeddings=True, **encode_kwargs).astype(np.float32) log.info(f"embedded {n} rows in {time.perf_counter()-t0:.1f}s, dim={dim}")
tbl = pa.table({ "id": pa.array(range(n), pa.int64()), "text": pa.array([t[:2000] for t in texts]), "vector": pa.FixedSizeListArray.from_arrays(pa.array(emb.reshape(-1), pa.float32()), dim), }) local = "vecdb.lance" if os.path.exists(local): shutil.rmtree(local) lds = lance.write_dataset(tbl, local, mode="overwrite") try: parts = max(1, min(256, int(np.sqrt(n)))) lds.create_index("vector", index_type="IVF_PQ", num_partitions=parts, num_sub_vectors=max(1, dim // 16)) log.info(f"built IVF_PQ index (partitions={parts})") except Exception as e: log.warning(f"index build skipped ({repr(e)[:120]}); flat search still works over hf://")
# Retry the upload with an XET-disable fallback — a transient failure here would lose the # whole (paid) embedding run. api = HfApi() api.create_repo(args.output_repo, repo_type="dataset", private=args.private, exist_ok=True) max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: log.warning("Disabling XET (fallback to HTTP upload)") os.environ["HF_HUB_DISABLE_XET"] = "1" api.upload_folder(folder_path=local, path_in_repo="vecdb.lance", repo_id=args.output_repo, repo_type="dataset") break except Exception as e: log.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: delay = 30 * (2 ** (attempt - 1)) log.info(f"Retrying in {delay}s...") time.sleep(delay) else: log.error("All upload attempts failed. Results are lost.") sys.exit(1) total_s = time.perf_counter() - t_all import json as _json log.info("ROUNDTRIP " + _json.dumps({ "input": args.input_dataset, "n": n, "dim": dim, "model": args.model, "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu", "batch_size": args.batch_size, "load_s": round(t_load - t_all, 1), "total_roundtrip_s": round(total_s, 1), "rows_per_s_end_to_end": round(n / total_s, 1), "hf_path": f"hf://datasets/{args.output_repo}/vecdb.lance"})) log.info(f"✅ {n} rows → searchable vector DB in {total_s/60:.1f} min " f"(load→embed→index→push). hf://datasets/{args.output_repo}/vecdb.lance") if query_prompt or registered.get("query"): log.info("⚠️ At search time, embed queries with the QUERY convention — mismatched prompts " "degrade retrieval. Easiest: model.encode_query([your_query])" + (f", or explicitly: model.encode([{query_prompt!r} + your_query])" if query_prompt else "."))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# /// script# requires-python = ">=3.10"# dependencies = [# "datasets",# "vllm",# "huggingface-hub",# ]# ///"""High-throughput embedding generation with vLLM pooling mode — the "scale" variant ofgenerate-embeddings.py, for large *decoder* embedding models (e.g. Qwen3-Embedding). OnQwen3-Embedding-0.6B this was ~2x the sentence-transformers throughput on the same GPU.
Prefer the plain sentence-transformers `generate-embeddings.py` unless you specifically needvLLM throughput: this variant has a heavier cold-start and two footguns handled below(the embedding-mode kwarg drifted across vLLM versions; vLLM does not auto-truncate).
Runs on the BARE uv image (vLLM ships the CUDA toolkit + flashinfer as wheels).
hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings-vllm.py \\ stanfordnlp/imdb your-name/imdb-embeddings --column text --model Qwen/Qwen3-Embedding-0.6B --private"""import argparseimport loggingimport osimport timeos.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("generate-embeddings-vllm")
def build_llm(LLM, model, max_model_len, gpu_mem_util): """vLLM's embedding-mode selector drifted: modern uses runner='pooling', old used task='embed'. A wrong kwarg raises TypeError at init (cheap) → fall through.""" base = dict(enforce_eager=True, max_model_len=max_model_len, gpu_memory_utilization=gpu_mem_util) for label, extra in [("runner", {"runner": "pooling"}), ("task", {"task": "embed"}), ("auto", {})]: try: llm = LLM(model=model, **base, **extra) log.info(f"engine init via '{label}'") return llm except TypeError as te: log.warning(f"ctor '{label}' rejected: {te}") raise RuntimeError("no vLLM constructor form accepted")
def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("input_dataset") ap.add_argument("output_dataset") ap.add_argument("--model", default="Qwen/Qwen3-Embedding-0.6B") ap.add_argument("--column", default="text") ap.add_argument("--output-column", default="embeddings") ap.add_argument("--split", default="train") ap.add_argument("--max-samples", type=int, default=None) ap.add_argument("--config", default=None, help="dataset config name (e.g. wikipedia needs one)") ap.add_argument("--max-model-len", type=int, default=512) ap.add_argument("--gpu-mem-util", type=float, default=0.85) ap.add_argument("--private", action="store_true") args = ap.parse_args()
import torch from datasets import load_dataset from huggingface_hub import DatasetCard, login from vllm import LLM if not torch.cuda.is_available(): raise SystemExit("No CUDA GPU available — vLLM needs one. Run with a GPU flavor, e.g. " "`hf jobs uv run --flavor l4x1 ...` (or use generate-embeddings.py on CPU).") if os.environ.get("HF_TOKEN"): login(token=os.environ["HF_TOKEN"])
ds = (load_dataset(args.input_dataset, args.config, split=args.split) if args.config else load_dataset(args.input_dataset, split=args.split)) if args.output_column in ds.column_names: raise SystemExit(f"Output column {args.output_column!r} already exists — pick another.") if args.max_samples: ds = ds.select(range(min(args.max_samples, len(ds)))) texts = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]] n = len(texts)
llm = build_llm(LLM, args.model, args.max_model_len, args.gpu_mem_util) embed_fn = getattr(llm, "embed", None) or getattr(llm, "encode")
# vLLM raises on inputs > max_model_len (no silent truncation) — pre-truncate at the tokenizer. # Tokenize each text once (not twice) — this pass is CPU-bound on large datasets. tk = llm.get_tokenizer() cap = max(8, args.max_model_len - 16) def _truncate(t): ids = tk.encode(t) return tk.decode(ids[:cap]) if len(ids) > cap else t texts = [_truncate(t) for t in texts]
t0 = time.perf_counter() outs = embed_fn(texts) log.info(f"embedded {n} rows in {time.perf_counter()-t0:.1f}s")
def vec(o): e = o.outputs e = getattr(e, "embedding", None) or getattr(e, "data", e) return list(e) ds = ds.add_column(args.output_column, [vec(o) for o in outs]) dim = len(ds[0][args.output_column])
card = DatasetCard( f"# {args.output_dataset}\n\nEmbeddings of `{args.input_dataset}` column `{args.column}` " f"with [`{args.model}`](https://huggingface.co/{args.model}) (dim {dim}, vLLM pooling).\n\n" f"Produced on Hugging Face Jobs with `uv-scripts/embeddings/generate-embeddings-vllm.py`.\n") # Retry the push with an XET-disable fallback — a transient failure would lose the paid run. max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: log.warning("Disabling XET (fallback to HTTP upload)") os.environ["HF_HUB_DISABLE_XET"] = "1" ds.push_to_hub(args.output_dataset, private=args.private) break except Exception as e: log.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: delay = 30 * (2 ** (attempt - 1)) log.info(f"Retrying in {delay}s...") time.sleep(delay) else: log.error("All upload attempts failed. Results are lost.") raise SystemExit(1) try: card.push_to_hub(args.output_dataset, repo_type="dataset") except Exception as e: log.warning(f"card push skipped: {e}") log.info(f"✅ https://huggingface.co/datasets/{args.output_dataset}")
if __name__ == "__main__": main()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203211 unmodified line# requires-python = ">=3.10"# dependencies = [# "datasets",# "sentence-transformers>=3.0.0",# "batched>=0.1.0",# "torch",# "huggingface-hub[hf_transfer]",# "tqdm",# "numpy",# ]# ///"""Generate embeddings for text datasets using Sentence Transformers with dynamic batching.This script efficiently generates embeddings for large datasets using GPU accelerationand dynamic batching for optimal throughput.Example usage:# Basic usageuv run generate-embeddings.py \imdb \imdb-embeddings \--model-name sentence-transformers/all-MiniLM-L6-v2# With custom batch size and columnuv run generate-embeddings.py \scientific-papers \paper-embeddings \--model-name BAAI/bge-base-en-v1.5 \--text-column abstract \--batch-size 64# Process subset for testinguv run generate-embeddings.py \my-dataset \my-embeddings \--max-samples 1000"""import argparseimport loggingimport osimport sysfrom typing import List, Optionalimport batchedimport numpy as npimport torchfrom datasets import Dataset, load_datasetfrom huggingface_hub import loginfrom sentence_transformers import SentenceTransformerfrom tqdm import tqdmlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)def estimate_batch_size(model: SentenceTransformer, sample_text: str, gpu_memory_gb: float = None) -> int:"""Estimate optimal batch size based on available GPU memory."""if not torch.cuda.is_available():return 32 # CPU fallbackif gpu_memory_gb is None:# Get available GPU memorygpu_memory_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)# Get model size estimatemodel_params = sum(p.numel() for p in model.parameters())model_size_gb = (model_params * 4) / (1024**3) # Assuming float32# Estimate based on model size and available memory# Conservative estimate: use 60% of available memory for batchingavailable_for_batch = (gpu_memory_gb - model_size_gb) * 0.6# Estimate memory per sample (very rough approximation)# Assuming average token length of 256, embedding dim of model.get_sentence_embedding_dimension()embedding_dim = model.get_sentence_embedding_dimension()memory_per_sample_gb = (256 * embedding_dim * 4) / (1024**3)estimated_batch_size = int(available_for_batch / memory_per_sample_gb)# Clamp to reasonable valuesestimated_batch_size = max(8, min(estimated_batch_size, 512))logger.info(f"Estimated optimal batch size: {estimated_batch_size}")return estimated_batch_sizeclass EmbeddingGenerator:"""Wrapper class for embedding generation with dynamic batching."""def __init__(self, model: SentenceTransformer, batch_size: Optional[int] = None):self.model = modelself.device = "cuda" if torch.cuda.is_available() else "cpu"self.model = self.model.to(self.device)# Estimate batch size if not providedif batch_size is None:sample_text = "This is a sample text for batch size estimation."batch_size = estimate_batch_size(model, sample_text)self.batch_size = batch_sizelogger.info(f"Using device: {self.device}")logger.info(f"Using batch size: {self.batch_size}")@batched.dynamically(timeout_ms=30000)def generate_embeddings(self, texts: List[str]) -> List[np.ndarray]:"""Generate embeddings with dynamic batching."""# Convert to tensors for GPU processingembeddings = self.model.encode(texts,convert_to_tensor=True,show_progress_bar=False, # We'll use our own progress bardevice=self.device,batch_size=self.batch_size # Pass batch size to encode)# Convert back to numpy arraysreturn embeddings.cpu().numpy()def process_dataset(dataset: Dataset,model: SentenceTransformer,text_column: str,batch_size: Optional[int] = None,show_progress: bool = True) -> Dataset:"""Process dataset to add embeddings."""# Initialize embedding generatorgenerator = EmbeddingGenerator(model, batch_size)# Get textstexts = dataset[text_column]# Filter out None/empty textsvalid_indices = []valid_texts = []for i, text in enumerate(texts):if text and isinstance(text, str) and text.strip():valid_indices.append(i)valid_texts.append(text)if len(valid_texts) == 0:logger.error(f"No valid texts found in column '{text_column}'")sys.exit(1)logger.info(f"Processing {len(valid_texts)} valid texts (filtered {len(texts) - len(valid_texts)} invalid)")# Generate embeddings with progress barall_embeddings = []if show_progress:# Process in chunks to show progresschunk_size = generator.batch_size * 10 # Process multiple batches at oncefor i in tqdm(range(0, len(valid_texts), chunk_size), desc="Generating embeddings"):chunk = valid_texts[i:i + chunk_size]chunk_embeddings = generator.generate_embeddings(chunk)all_embeddings.extend(chunk_embeddings)else:all_embeddings = generator.generate_embeddings(valid_texts)# Create new dataset with embeddings# Initialize with None for all indicesembedding_column = [None] * len(texts)for idx, embedding in zip(valid_indices, all_embeddings):embedding_column[idx] = embedding.tolist()# Add embeddings to datasetdataset = dataset.add_column("embeddings", embedding_column)return datasetdef main():parser = argparse.ArgumentParser(description="Generate embeddings for text datasets",formatter_class=argparse.RawDescriptionHelpFormatter,epilog=__doc__,)parser.add_argument("input_dataset",type=str,help="Input dataset ID from Hugging Face Hub",)parser.add_argument("output_dataset",type=str,help="Output dataset ID for Hugging Face Hub",)parser.add_argument("--model-name",type=str,default="sentence-transformers/all-MiniLM-L6-v2",help="Sentence Transformer model to use (default: all-MiniLM-L6-v2)",)parser.add_argument("--text-column",type=str,default="text",help="Name of the text column in the input dataset (default: text)",)parser.add_argument("--batch-size",type=int,default=None,help="Batch size for processing (default: auto-detect based on GPU memory)",)parser.add_argument("--max-samples",type=int,default=None,help="Maximum number of samples to process (default: all)",)parser.add_argument("--split",type=str,default="train",help="Dataset split to use (default: train)",)parser.add_argument("--hf-token",type=str,default=None,help="Hugging Face API token",)parser.add_argument("--private",action="store_true",help="Make the output dataset private",)parser.add_argument("--normalize",action="store_true",help="Normalize embeddings to unit length",)args = parser.parse_args()# Check GPU availabilityif not torch.cuda.is_available():logger.warning("CUDA is not available. Running on CPU will be slower.")response = input("Continue anyway? (y/n): ")if response.lower() != 'y':sys.exit(0)# Login to Hugging Facehf_token = args.hf_token or os.environ.get("HF_TOKEN")if hf_token:login(token=hf_token)else:logger.warning("No HF token provided. You may not be able to push to the Hub.")# Load input datasetlogger.info(f"Loading dataset: {args.input_dataset}")dataset = load_dataset(args.input_dataset, split=args.split)# Validate text column existsif args.text_column not in dataset.column_names:logger.error(f"Column '{args.text_column}' not found in dataset.")logger.error(f"Available columns: {dataset.column_names}")sys.exit(1)# Limit samples if requestedif args.max_samples:dataset = dataset.select(range(min(args.max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# Load modellogger.info(f"Loading model: {args.model_name}")model = SentenceTransformer(args.model_name)# Set normalization if requestedif args.normalize:model.normalize_embeddings = Truelogger.info("Embeddings will be normalized to unit length")# Log model infoembedding_dim = model.get_sentence_embedding_dimension()logger.info(f"Embedding dimension: {embedding_dim}")logger.info(f"Max sequence length: {model.max_seq_length}")# Process datasetdataset_with_embeddings = process_dataset(dataset,model,args.text_column,args.batch_size)# Log statisticslogger.info(f"\n✅ Generated embeddings for {len(dataset_with_embeddings)} samples")logger.info(f"Embedding dimension: {embedding_dim}")# Show samplesample = dataset_with_embeddings[0]logger.info(f"\nSample:")logger.info(f"Text: {sample[args.text_column][:100]}...")if sample['embeddings'] is not None:logger.info(f"Embedding shape: {len(sample['embeddings'])}")logger.info(f"Embedding (first 5 values): {sample['embeddings'][:5]}")# Push to Hublogger.info(f"\nPushing dataset to Hub: {args.output_dataset}")dataset_with_embeddings.push_to_hub(args.output_dataset, private=args.private)logger.info(f"\n✅ Dataset with embeddings available at: https://huggingface.co/datasets/{args.output_dataset}")if __name__ == "__main__":# Show example command if no args providedif len(sys.argv) == 1:print("Example command:")print("uv run generate-embeddings.py imdb imdb-embeddings --model-name sentence-transformers/all-MiniLM-L6-v2")print("\nFor HF Jobs:")print("hf jobs run --gpu a10 uv run generate-embeddings.py <input> <output> --model-name <model>")main()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543551 unmodified line# requires-python = ">=3.10"# dependencies = [# "datasets",# "sentence-transformers>=5.0.0",# "torch",# "numpy",# "pillow",# "einops",# "huggingface-hub",# ]# ///"""Generate embeddings for a Hugging Face dataset (text OR images) with sentence-transformers,and push the result back to the Hub as a new dataset with an `embeddings` column.This is the simple, ergonomic default. It runs as one command on the bare uv image, on CPUor any GPU flavor. For maximum throughput on large *decoder* embedding models (e.g.Qwen3-Embedding), see the vLLM variant; to get a searchable vector index as a Hub dataset,see the Lance variant.PROMPTS (retrieval correctness — read this):Many embedding models need a DIFFERENT prefix/instruction for documents vs queries, andgetting it wrong silently degrades retrieval. This script embeds a *document corpus* bydefault, via sentence-transformers' native encode_document()/encode_query() (which alsoroute Router models by task), picking the right document convention for you:1. the model's REGISTERED prompt if it ships one (e.g. Qwen3-Embedding) — selectednatively by encode_document/encode_query, else2. a small built-in table of well-known families (e5, nomic, bge), else3. no prefix.Heads-up: current sentence-transformers injects a placeholder prompts dict{"query": "", "document": ""} even for models that register NOTHING — so e5 ("passage: "),nomic ("search_document: ") etc. look prompt-less via `.prompts`; their real prefixes liveonly in the model card. The built-in table handles that. Override with --prompt '<prefix>'or --prompt-name <registered-name>; embed a query set with --query-mode; force no prefixwith --prompt ''. The chosen prompt is logged and recorded in the dataset card.Benchmarks (20k rows, seq-cap 512): all-MiniLM-L6-v2 ~900 rows/s on an L4 (~$0.24/1M rows);bge-base-en-v1.5 ~120 rows/s. L4 is the cheapest flavor for these encoder models.Examples:# Text (default). Document convention auto-picked.hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\stanfordnlp/imdb your-name/imdb-embeddings \\--column text --model sentence-transformers/all-MiniLM-L6-v2# e5: docs auto-get "passage: ". (--prompt 'passage: ' would be the explicit form.)hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\stanfordnlp/imdb your-name/imdb-e5 --model intfloat/multilingual-e5-large# Images (CLIP) — prompts don't apply.hf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\your-name/photos your-name/photos-embeddings \\--modality image --column image --model clip-ViT-B-32# Test on a small slice first, keep the output privatehf jobs uv run --flavor l4x1 -s HF_TOKEN generate-embeddings.py \\stanfordnlp/imdb your-name/imdb-emb --max-samples 100 --private"""import argparseimport loggingimport osimport reimport sysimport timelogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")logger = logging.getLogger("generate-embeddings")def find_batch_size(model, sample, normalize, candidates=(32, 64, 128, 256)):"""Probe for the fastest batch that fits (used by --batch-size auto). Throughput is NOTmonotonic in batch size, so we time a few on a warmup sample and keep the fastest that doesn'tOOM. Why bigger isn't better: for text, larger batches pad to the longest member + add overhead;for images, the ViT forward already saturates the GPU by ~batch 32. Works for text and images."""import timeimport torchwarm = sample[: min(1024, len(sample))]try: # one untimed warmup so cudnn autotune doesn't penalise the first probemodel.encode(warm[:32], batch_size=32, show_progress_bar=False,convert_to_numpy=True, normalize_embeddings=normalize)except Exception:passbest_bs, best_rps = candidates[0], 0.0for bs in candidates:try:if torch.cuda.is_available():torch.cuda.empty_cache()torch.cuda.synchronize()t = time.perf_counter()model.encode(warm, batch_size=bs, show_progress_bar=False,convert_to_numpy=True, normalize_embeddings=normalize)if torch.cuda.is_available():torch.cuda.synchronize()rps = len(warm) / (time.perf_counter() - t)logger.info(f" auto-batch probe bs={bs}: {rps:.0f} rows/s")if rps > best_rps:best_rps, best_bs = rps, bsexcept RuntimeError as e:if "out of memory" in str(e).lower():logger.info(f" auto-batch bs={bs} OOM → stopping probe")if torch.cuda.is_available():torch.cuda.empty_cache()breakraiselogger.info(f"auto-batch chose bs={best_bs} ({best_rps:.0f} rows/s on warmup)")return best_bsdef known_convention(model_id):"""Best-effort (query_prefix, doc_prefix) for common families whose convention isdocumented in the model card but NOT registered in config_sentence_transformers.json.Returns None if unknown. Overridable with --prompt / --no-auto-prompt.Verified 2026-07-03 on HF Jobs: of e5 / nomic / bge-en / bge-m3 / Qwen3-Embedding, onlyQwen3-Embedding registers real ST prompts; the rest ship none and rely on manual prefixes."""m = model_id.lower()# Instruction-style embedders (e5-*-instruct, gte-Qwen, ...): prefer the model's REGISTERED# prompt or an explicit --prompt; don't guess a literal prefix.if "instruct" in m:return Noneif "nomic-embed-text" in m:return ("search_query: ", "search_document: ")if "bge-m3" in m: # bge-m3 uses no promptsreturn ("", "")# e5 family (e5-base/large/small, multilingual-e5-*), boundaried so e.g. "table5" or a# model with "e5" mid-word can't silently pick up "query:/passage:" prefixes.if re.search(r"(^|[/_-])e5([_-]|$)", m):return ("query: ", "passage: ")if "bge" in m and "-en" in m: # English bge retrieval: query instruction, docs rawreturn ("Represent this sentence for searching relevant passages: ", "")return Nonedef resolve_prompt(model, model_id, is_query, args):"""Decide the EXPLICIT prefix to pass to encode_query()/encode_document(), or None to let thenative method choose. sentence-transformers' encode_query/encode_document already select themodel's REGISTERED query/document prompt and set the Router task — we lean on that, and onlysupply a prefix ourselves for (a) explicit --prompt/--prompt-name, (b) the known-family tablecovering models that register nothing (e5, nomic, bge-en — their prefixes live only in themodel card, so the native fallback would silently apply NO prefix)."""registered = dict(getattr(model, "prompts", {}) or {})# Current sentence-transformers injects a placeholder {"query":"","document":""} for models# with no config prompts; only non-empty values are real conventions.real = {k: v for k, v in registered.items() if v}logger.info(f"Registered prompts: {registered} · real (non-empty): {real or 'none'} · "f"default_prompt_name={getattr(model, 'default_prompt_name', None)}")side = "query" if is_query else "document"if args.prompt is not None: # includes --prompt '' to force no prefixlogger.info(f"Prompt: raw --prompt → {args.prompt!r}")return args.promptif args.prompt_name:if args.prompt_name not in registered:logger.error(f"--prompt-name {args.prompt_name!r} not registered ({list(registered)}); "f"use --prompt '<raw prefix>' instead.")sys.exit(1)logger.info(f"Prompt: registered prompt_name={args.prompt_name!r} → {registered[args.prompt_name]!r}")return registered[args.prompt_name]native_keys = ("query",) if is_query else ("document", "passage", "corpus")if any(real.get(k) for k in native_keys):# Model ships a real prompt for this side (e.g. Qwen3 query) → encode_query/encode_document# selects it natively (and routes Router models by task).logger.info(f"Prompt: model-registered — selected natively by encode_{side}()")return Nonekc = known_convention(model_id)if kc is not None:chosen = kc[0] if is_query else kc[1]if args.no_auto_prompt:if chosen:logger.warning(f"--no-auto-prompt set: NOT applying the known {side} prefix {chosen!r} for "f"{model_id}. Retrieval may degrade unless you pass --prompt.")return ""logger.info(f"Prompt: known-family {side} prefix → {chosen!r} (override with --prompt)"if chosen else f"Prompt: known-family → no {side} prefix needed")return chosenlogger.info(f"Prompt: none registered or known for {model_id} — encode_{side}() applies no prefix. "f"If it's a retrieval model needing a query/document prefix, pass --prompt.")return Nonedef sniff_token_lengths(model, texts, max_seq_len, sample=512):"""Tokenize a sample to report the token-length distribution + how much --max-seq-len truncates,and return the median length (used to pick the auto-batch candidate range: short texts under-usethe GPU at small batch, long texts waste compute on padding). Text only; returns None on failure."""try:tok = model.tokenizerexcept Exception:return Nones = texts[: min(sample, len(texts))]lens = sorted(len(tok.encode(t, add_special_tokens=True)) for t in s)n = len(lens)if not n:return Nonemedian, p90, mx = lens[n // 2], lens[min(n - 1, int(n * 0.9))], lens[-1]pct_over = 100 * sum(1 for L in lens if L > max_seq_len) / nnote = (f" → {pct_over:.0f}% exceed --max-seq-len {max_seq_len} and are truncated "f"(raise it to keep more, at higher cost/slower)" if pct_over >= 5else f" (all within --max-seq-len {max_seq_len})")logger.info(f"Token lengths (sample {n}): median {median}, p90 {p90}, max {mx}{note}")return mediandef main():p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)p.add_argument("input_dataset", help="Input dataset ID on the Hugging Face Hub")p.add_argument("output_dataset", help="Output dataset ID to create on the Hub")p.add_argument("--model", default="sentence-transformers/all-MiniLM-L6-v2",help="sentence-transformers model (text or CLIP image model)")p.add_argument("--modality", choices=["text", "image"], default="text")p.add_argument("--column", default="text", help="Input column (text string, or image)")p.add_argument("--output-column", default="embeddings")p.add_argument("--config", default=None, help="Dataset config name (e.g. wikipedia needs one)")p.add_argument("--split", default="train")p.add_argument("--max-samples", type=int, default=None, help="Limit rows (for testing)")p.add_argument("--batch-size", default="auto",help="'auto' probes for the fastest batch that fits, or pass an int")p.add_argument("--prompt", default=None,help="Raw prefix to prepend to every text (e.g. 'passage: '). Highest precedence. ""Use --prompt '' to force NO prefix.")p.add_argument("--prompt-name", default=None,help="Name of a prompt REGISTERED by the model (e.g. 'query'); errors if not registered.")p.add_argument("--query-mode", action="store_true",help="Embed inputs as QUERIES, not documents (flips the auto-picked convention).")p.add_argument("--no-auto-prompt", action="store_true",help="Disable the built-in known-family prefix table (still honours registered prompts).")p.add_argument("--max-seq-len", type=int, default=512,help="Truncate text to this many tokens (predictable cost; RAG-typical)")p.add_argument("--normalize", action="store_true", default=True)p.add_argument("--no-normalize", dest="normalize", action="store_false")p.add_argument("--private", action="store_true", help="Make the output dataset private")args = p.parse_args()import torchfrom datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom sentence_transformers import SentenceTransformertoken = os.environ.get("HF_TOKEN")if token:login(token=token)if not torch.cuda.is_available():logger.warning("No CUDA — running on CPU (much slower). Prefer a GPU flavor, e.g. --flavor l4x1.")logger.info(f"Loading {args.input_dataset} [{args.split}]")ds = (load_dataset(args.input_dataset, args.config, split=args.split) if args.configelse load_dataset(args.input_dataset, split=args.split))if args.column not in ds.column_names:logger.error(f"Column {args.column!r} not found. Available: {ds.column_names}")sys.exit(1)if args.output_column in ds.column_names:logger.error(f"Output column {args.output_column!r} already exists — choose another --output-column.")sys.exit(1)if args.max_samples:ds = ds.select(range(min(args.max_samples, len(ds))))logger.info(f"{len(ds)} rows; modality={args.modality}")device = "cuda" if torch.cuda.is_available() else "cpu"model = SentenceTransformer(args.model, device=device, trust_remote_code=True)if args.modality == "text" and getattr(model, "max_seq_length", None):model.max_seq_length = min(model.max_seq_length, args.max_seq_len)dim = model.get_sentence_embedding_dimension()logger.info(f"Model {args.model} on {device}; dim={dim}")# Prompt handling — many retrieval models need a query vs document/passage prefix (text only).prompt_str = None # None = let encode_query/encode_document choose nativelyif args.modality == "text":prompt_str = resolve_prompt(model, args.model, is_query=args.query_mode, args=args)items = [t if isinstance(t, str) and t.strip() else " " for t in ds[args.column]]else:if args.prompt or args.prompt_name:logger.warning("--prompt/--prompt-name ignored for image modality.")items = [im.convert("RGB") if hasattr(im, "convert") else im for im in ds[args.column]]median_tok = sniff_token_lengths(model, items, args.max_seq_len) if args.modality == "text" else Noneif str(args.batch_size).lower() == "auto":# Pick the probe range from the data shape. Images: the ViT forward saturates the GPU by# ~batch 32, so bigger only adds memory — probe low. Text: short texts under-use the GPU at# small batch (probe bigger); long texts pad-waste at big batch (stay modest). Probe verifies.if args.modality == "image":candidates = (32, 64, 128)elif median_tok is None or median_tok >= 256:candidates = (32, 64, 128, 256)elif median_tok >= 64:candidates = (64, 128, 256, 512)else:candidates = (128, 256, 512, 1024)logger.info(f"Finding batch size (--batch-size auto; candidates {candidates})...")batch_size = find_batch_size(model, items, args.normalize, candidates=candidates)else:batch_size = int(args.batch_size)# Text goes through encode_query/encode_document (native registered-prompt selection + Router# task routing); our resolved prefix, when not None, overrides via prompt=. Images use encode().if args.modality == "text":encode_fn = model.encode_query if args.query_mode else model.encode_documentencode_kwargs = {"prompt": prompt_str} if prompt_str is not None else {}else:encode_fn = model.encodeencode_kwargs = {}t0 = time.perf_counter()emb = encode_fn(items, batch_size=batch_size, show_progress_bar=True,convert_to_numpy=True, normalize_embeddings=args.normalize, **encode_kwargs)secs = time.perf_counter() - t0logger.info(f"Embedded {len(items)} in {secs:.1f}s ({len(items)/secs:.0f} rows/s), dim={dim}")ds = ds.add_column(args.output_column, [e.tolist() for e in emb])# For the card: record the effective prefix (explicit, else the model's registered one).side_keys = ("query",) if args.query_mode else ("document", "passage", "corpus")effective = prompt_str if prompt_str is not None else next((v for k in side_keys if (v := (getattr(model, "prompts", {}) or {}).get(k))), "")prompt_line = f"`{effective}`" if effective else "(none)"card = DatasetCard(f"# {args.output_dataset}\n\n"f"Embeddings of [`{args.input_dataset}`](https://huggingface.co/datasets/{args.input_dataset}) "f"column `{args.column}`.\n\n"f"- Model: [`{args.model}`](https://huggingface.co/{args.model}) (dim {dim})\n"f"- Column: `{args.output_column}` · normalized: {args.normalize}\n"f"- Prompt prepended ({'query' if args.query_mode else 'document'} side): {prompt_line}\n\n"f"Produced on Hugging Face Jobs with `uv-scripts/embeddings/generate-embeddings.py`.\n")# Retry the push with an XET-disable fallback: a transient upload failure here would# otherwise lose the whole (paid) embedding run.logger.info(f"Pushing to {args.output_dataset} (private={args.private})")max_retries = 3for attempt in range(1, max_retries + 1):try:if attempt > 1:logger.warning("Disabling XET (fallback to HTTP upload)")os.environ["HF_HUB_DISABLE_XET"] = "1"ds.push_to_hub(args.output_dataset, private=args.private)breakexcept Exception as e:logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")if attempt < max_retries:delay = 30 * (2 ** (attempt - 1))logger.info(f"Retrying in {delay}s...")time.sleep(delay)else:logger.error("All upload attempts failed. Results are lost.")sys.exit(1)try:card.push_to_hub(args.output_dataset, repo_type="dataset")except Exception as e:logger.warning(f"card push skipped: {e}")logger.info(f"✅ https://huggingface.co/datasets/{args.output_dataset}")if __name__ == "__main__":main()
HEURISTICS.mdAdded+137
README.mdAdded+139
embed-to-lance.pyAdded+180
generate-embeddings-vllm.pyAdded+134
generate-embeddings.py+327-293