davanstrien HF Staff commited on
Commit
9c2126e
·
verified ·
1 Parent(s): 611f9d7

Sync from GitHub via hub-sync

Browse files
Files changed (5) hide show
  1. CLAUDE.md +3 -10
  2. README.md +23 -16
  3. classify-dataset.py +35 -29
  4. generate-responses.py +38 -19
  5. vlm-classify.py +21 -12
CLAUDE.md CHANGED
@@ -14,21 +14,14 @@ if not torch.cuda.is_available():
14
  ```
15
 
16
  ### 2. vLLM Docker Image
17
- Run on the pinned **`vllm/vllm-openai:0.22.1`** image for HF Jobs (ships vLLM + the CUDA toolkit, so FlashInfer works) with `--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`. **Pin the tag (test-then-pin), not `:latest`.** Tested 2026-06-05 on `l4x1` (vLLM 0.22.1).
18
 
19
- The custom nightly / FlashInfer `[[tool.uv.index]]` blocks (§3) are **no longer needed** — the image provides vLLM; keep a `vllm>=0.11.0` floor in the PEP 723 header for the local path.
20
 
21
  **APIs (verified):** structured outputs use `StructuredOutputsParams` (`structured_outputs=`, ≥0.11.0 — `GuidedDecodingParams`/`guided_decoding=` removed in 0.12.0); classification auto-detects the pooling runner from the model architecture (the old `LLM(..., task="classify")` arg was removed → use `LLM(model)`).
22
 
23
  ### 3. Dependencies
24
- Include custom PyPI indexes for vLLM and FlashInfer:
25
- ```python
26
- # [[tool.uv.index]]
27
- # url = "https://flashinfer.ai/whl/cu126/torch2.6"
28
- #
29
- # [[tool.uv.index]]
30
- # url = "https://wheels.vllm.ai/nightly"
31
- ```
32
 
33
  ## Current Scripts
34
 
 
14
  ```
15
 
16
  ### 2. vLLM Docker Image
17
+ Run on the pinned **`vllm/vllm-openai:v0.32.0`** image for HF Jobs (ships vLLM + the CUDA toolkit, so FlashInfer works) with `--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`. Each script's `[tool.hf-jobs]` header sets these. **Pin the tag (test-then-pin), not `:latest`.** Tested 2026-11-05 on `a10g-small`, `a10g-large` and `a100-large` (vLLM 0.32.0).
18
 
19
+ **Do not list `vllm`, `torch`, `transformers` or `flashinfer-python` in the PEP 723 dependencies.** uv would install newer PyPI copies next to the image's. `PYTHONPATH` shadows those, but the `flashinfer-python` 0.7.2.post1 wheel also ships a top-level `b12x` module that the image lacks; the image's vLLM imports it and crashes (`FileNotFoundError: .../flashinfer/experimental/b12x/_api.py`). Import these packages inside `main()` so `uv run <script> --help` works without them. Local GPU runs use `uv run --with vllm <script>`. The custom nightly / FlashInfer `[[tool.uv.index]]` blocks (§3) are **no longer needed**.
20
 
21
  **APIs (verified):** structured outputs use `StructuredOutputsParams` (`structured_outputs=`, ≥0.11.0 — `GuidedDecodingParams`/`guided_decoding=` removed in 0.12.0); classification auto-detects the pooling runner from the model architecture (the old `LLM(..., task="classify")` arg was removed → use `LLM(model)`).
22
 
23
  ### 3. Dependencies
24
+ List only what the image does not provide (for example `datasets`, `huggingface-hub`, `toolz`). No custom `[[tool.uv.index]]` blocks are needed; see §2.
 
 
 
 
 
 
 
25
 
26
  ## Current Scripts
27
 
README.md CHANGED
@@ -7,7 +7,7 @@ tags: [uv-script, vllm, gpu, inference, hf-jobs]
7
 
8
  Ready-to-run UV scripts for GPU-accelerated inference using [vLLM](https://github.com/vllm-project/vllm).
9
 
10
- These scripts use [UV's inline script metadata](https://docs.astral.sh/uv/guides/scripts/) to automatically manage dependencies - just run with `uv run` and everything installs automatically!
11
 
12
  ## 📋 Available Scripts
13
 
@@ -18,7 +18,7 @@ Vision Language Model (VLM) image classification with structured output constrai
18
  **Features:**
19
 
20
  - 🖼️ Process images through state-of-the-art VLMs (Qwen2-VL)
21
- - 🎯 Structured classification using vLLM's `GuidedDecodingParams`
22
  - 📐 Automatic image resizing to optimize token usage
23
  - 💾 Memory-efficient lazy batch processing
24
  - 🏷️ Simple CLI interface for defining classes
@@ -28,13 +28,13 @@ Vision Language Model (VLM) image classification with structured output constrai
28
 
29
  ```bash
30
  # Basic classification
31
- uv run vlm-classify.py \
32
  username/input-dataset \
33
  username/output-dataset \
34
  --classes "document,photo,diagram,other"
35
 
36
  # With custom prompt and image resizing
37
- uv run vlm-classify.py \
38
  username/input-dataset \
39
  username/output-dataset \
40
  --classes "index-card,manuscript,title-page,other" \
@@ -42,7 +42,7 @@ uv run vlm-classify.py \
42
  --max-size 768
43
 
44
  # Quick test with sample limit
45
- uv run vlm-classify.py \
46
  davanstrien/sloane-index-cards \
47
  username/test-output \
48
  --classes "index,content,other" \
@@ -89,7 +89,7 @@ Batch text classification using BERT-style encoder models (e.g., BERT, RoBERTa,
89
 
90
  ```bash
91
  # Local execution (requires GPU)
92
- uv run classify-dataset.py \
93
  davanstrien/ModernBERT-base-is-new-arxiv-dataset \
94
  username/input-dataset \
95
  username/output-dataset \
@@ -103,7 +103,7 @@ uv run classify-dataset.py \
103
  hf jobs uv run \
104
  --flavor l4x1 \
105
  --image vllm/vllm-openai:v0.32.0 \
106
- https://huggingface.co/datasets/uv-scripts/vllm/resolve/main/classify-dataset.py \
107
  davanstrien/ModernBERT-base-is-new-arxiv-dataset \
108
  username/input-dataset \
109
  username/output-dataset \
@@ -130,14 +130,14 @@ Generate responses for prompts using generative LLMs (e.g., Llama, Qwen, Mistral
130
 
131
  ```bash
132
  # With chat-formatted messages (default)
133
- uv run generate-responses.py \
134
  username/input-dataset \
135
  username/output-dataset \
136
  --messages-column messages \
137
  --max-tokens 1024
138
 
139
  # With plain text prompts (NEW!)
140
- uv run generate-responses.py \
141
  username/input-dataset \
142
  username/output-dataset \
143
  --prompt-column question \
@@ -145,7 +145,7 @@ uv run generate-responses.py \
145
  --max-samples 100
146
 
147
  # With custom model and parameters
148
- uv run generate-responses.py \
149
  username/input-dataset \
150
  username/output-dataset \
151
  --model-id meta-llama/Llama-3.1-8B-Instruct \
@@ -207,22 +207,29 @@ vLLM is a high-throughput inference engine optimized for:
207
 
208
  ### Dependencies
209
 
210
- Scripts use UV's inline metadata for automatic dependency management:
211
 
212
  ```python
213
  # /// script
214
  # requires-python = ">=3.10"
215
  # dependencies = [
216
  # "datasets",
217
- # "flashinfer-python",
218
- # "huggingface-hub[hf_transfer]",
219
- # "torch",
220
- # "transformers",
221
- # "vllm",
222
  # ]
 
 
 
 
 
 
 
 
223
  # ///
224
  ```
225
 
 
 
226
  For bleeding-edge features, use the `UV_PRERELEASE=if-necessary` environment variable to allow pre-release versions when needed.
227
 
228
  ### Docker Image
 
7
 
8
  Ready-to-run UV scripts for GPU-accelerated inference using [vLLM](https://github.com/vllm-project/vllm).
9
 
10
+ These scripts use [UV's inline script metadata](https://docs.astral.sh/uv/guides/scripts/) to manage dependencies. On HF Jobs they run on the `vllm/vllm-openai` image, which provides vLLM, PyTorch and Transformers, so the script headers leave those out. On your own Linux + CUDA machine, add vLLM explicitly: `uv run --with vllm <script>.py ...`.
11
 
12
  ## 📋 Available Scripts
13
 
 
18
  **Features:**
19
 
20
  - 🖼️ Process images through state-of-the-art VLMs (Qwen2-VL)
21
+ - 🎯 Structured classification using vLLM's `StructuredOutputsParams`
22
  - 📐 Automatic image resizing to optimize token usage
23
  - 💾 Memory-efficient lazy batch processing
24
  - 🏷️ Simple CLI interface for defining classes
 
28
 
29
  ```bash
30
  # Basic classification
31
+ uv run --with vllm vlm-classify.py \
32
  username/input-dataset \
33
  username/output-dataset \
34
  --classes "document,photo,diagram,other"
35
 
36
  # With custom prompt and image resizing
37
+ uv run --with vllm vlm-classify.py \
38
  username/input-dataset \
39
  username/output-dataset \
40
  --classes "index-card,manuscript,title-page,other" \
 
42
  --max-size 768
43
 
44
  # Quick test with sample limit
45
+ uv run --with vllm vlm-classify.py \
46
  davanstrien/sloane-index-cards \
47
  username/test-output \
48
  --classes "index,content,other" \
 
89
 
90
  ```bash
91
  # Local execution (requires GPU)
92
+ uv run --with vllm classify-dataset.py \
93
  davanstrien/ModernBERT-base-is-new-arxiv-dataset \
94
  username/input-dataset \
95
  username/output-dataset \
 
103
  hf jobs uv run \
104
  --flavor l4x1 \
105
  --image vllm/vllm-openai:v0.32.0 \
106
+ https://huggingface.co/datasets/uv-scripts/vllm/raw/main/classify-dataset.py \
107
  davanstrien/ModernBERT-base-is-new-arxiv-dataset \
108
  username/input-dataset \
109
  username/output-dataset \
 
130
 
131
  ```bash
132
  # With chat-formatted messages (default)
133
+ uv run --with vllm generate-responses.py \
134
  username/input-dataset \
135
  username/output-dataset \
136
  --messages-column messages \
137
  --max-tokens 1024
138
 
139
  # With plain text prompts (NEW!)
140
+ uv run --with vllm generate-responses.py \
141
  username/input-dataset \
142
  username/output-dataset \
143
  --prompt-column question \
 
145
  --max-samples 100
146
 
147
  # With custom model and parameters
148
+ uv run --with vllm generate-responses.py \
149
  username/input-dataset \
150
  username/output-dataset \
151
  --model-id meta-llama/Llama-3.1-8B-Instruct \
 
207
 
208
  ### Dependencies
209
 
210
+ Scripts use UV's inline metadata for dependency management, plus a `[tool.hf-jobs]` table that sets the image, flavor and secrets for `hf jobs uv run`:
211
 
212
  ```python
213
  # /// script
214
  # requires-python = ">=3.10"
215
  # dependencies = [
216
  # "datasets",
217
+ # "huggingface-hub",
218
+ # "hf-xet>= 1.1.7",
 
 
 
219
  # ]
220
+ #
221
+ # [tool.hf-jobs]
222
+ # image = "vllm/vllm-openai:v0.32.0"
223
+ # python = "/usr/bin/python3"
224
+ # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
225
+ # flavor = "a100-large"
226
+ # secrets = ["HF_TOKEN"]
227
+ # timeout = "2h"
228
  # ///
229
  ```
230
 
231
+ vLLM, PyTorch, Transformers and FlashInfer come from the image: `PYTHONPATH` points at its packages. Do not add them to `dependencies`. uv would then install newer PyPI copies next to the image's, and the current `flashinfer-python` wheel adds a `b12x` module that the v0.32.0 image's vLLM imports and crashes on. For a local GPU run, use `uv run --with vllm <script>.py ...`. `hf jobs uv run` reads the `[tool.hf-jobs]` table from hf CLI 1.32; with an older CLI, pass the header's settings as flags yourself: `--image`, `--flavor`, `--timeout`, `--secrets HF_TOKEN`, `--python /usr/bin/python3` and `-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`.
232
+
233
  For bleeding-edge features, use the `UV_PRERELEASE=if-necessary` environment variable to allow pre-release versions when needed.
234
 
235
  ### Docker Image
classify-dataset.py CHANGED
@@ -6,12 +6,14 @@
6
  # "huggingface-hub",
7
  # "setuptools",
8
  # "toolz",
9
- # "torch",
10
- # "transformers",
11
- # "vllm>=0.11.0",
12
  # ]
13
  #
14
  # [tool.hf-jobs]
 
 
 
 
 
15
  # image = "vllm/vllm-openai:v0.32.0"
16
  # python = "/usr/bin/python3"
17
  # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
@@ -27,16 +29,17 @@ a BERT-style model via vLLM, and saves the results back to the Hub with predicte
27
  labels and confidence scores.
28
 
29
  Example usage:
30
- # Local execution
31
- uv run classify-dataset.py \\
 
32
  davanstrien/ModernBERT-base-is-new-arxiv-dataset \\
33
  username/input-dataset \\
34
  username/output-dataset \\
35
  --inference-column text \\
36
  --batch-size 10000
37
 
38
- # HF Jobs execution (see script output for full command)
39
- hfjobs run --flavor l4x1 ...
40
  """
41
 
42
  import argparse
@@ -46,14 +49,14 @@ import sys
46
  from typing import Optional
47
 
48
  import httpx
49
- import torch
50
- import torch.nn.functional as F
51
- import vllm
52
  from datasets import load_dataset
53
  from huggingface_hub import hf_hub_url, login
54
  from toolz import concat, keymap, partition_all
55
  from tqdm.auto import tqdm
56
- from vllm import LLM
 
 
 
57
 
58
  logging.basicConfig(
59
  level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
@@ -63,6 +66,9 @@ logger = logging.getLogger(__name__)
63
 
64
  def check_gpu_availability():
65
  """Check if CUDA is available and log GPU information."""
 
 
 
66
  if not torch.cuda.is_available():
67
  logger.error("CUDA is not available. This script requires a GPU.")
68
  logger.error(
@@ -114,6 +120,9 @@ def get_top_label(output, label_map: Optional[dict[int, str]] = None):
114
  Returns:
115
  Tuple of (label, confidence_score)
116
  """
 
 
 
117
  logits = torch.tensor(output.outputs.probs)
118
  probs = F.softmax(logits, dim=0)
119
  top_idx = torch.argmax(probs).item()
@@ -143,6 +152,8 @@ def main(
143
  batch_size: Number of examples to process at once
144
  hf_token: Hugging Face authentication token
145
  """
 
 
146
  # GPU check
147
  check_gpu_availability()
148
 
@@ -215,16 +226,18 @@ if __name__ == "__main__":
215
  formatter_class=argparse.RawDescriptionHelpFormatter,
216
  epilog="""
217
  Examples:
 
 
218
  # Basic usage
219
- uv run classify-dataset.py model/name input-dataset output-dataset
220
 
221
  # With custom column and batch size
222
- uv run classify-dataset.py model/name input-dataset output-dataset \\
223
  --inference-column prompt \\
224
  --batch-size 50000
225
 
226
  # Using environment variable for token
227
- HF_TOKEN=hf_xxx uv run classify-dataset.py model/name input-dataset output-dataset
228
  """,
229
  )
230
 
@@ -276,19 +289,12 @@ vLLM Classification Script
276
  This script requires arguments. For usage information:
277
  uv run classify-dataset.py --help
278
 
279
- Example HF Jobs command:
280
- hfjobs run \\
281
- --flavor l4x1 \\
282
- --secret HF_TOKEN=$(python -c "from huggingface_hub import HfFolder; print(HfFolder.get_token())") \\
283
- vllm/vllm-openai:latest \\
284
- /bin/bash -c '
285
- uv run https://huggingface.co/datasets/uv-scripts/vllm/resolve/main/classify-dataset.py \\
286
- davanstrien/ModernBERT-base-is-new-arxiv-dataset \\
287
- username/input-dataset \\
288
- username/output-dataset \\
289
- --inference-column text \\
290
- --batch-size 100000
291
- ' \\
292
- --project vllm-classify \\
293
- --name my-classification-job
294
  """)
 
6
  # "huggingface-hub",
7
  # "setuptools",
8
  # "toolz",
 
 
 
9
  # ]
10
  #
11
  # [tool.hf-jobs]
12
+ # # vllm, torch and transformers come from the image (PYTHONPATH). Listing them above makes uv
13
+ # # install newer PyPI copies plus their deps. PYTHONPATH shadows the copies, but the current
14
+ # # flashinfer-python wheel (0.7.2.post1) also ships a top-level b12x module that the image lacks.
15
+ # # The image's vllm imports it and crashes (missing flashinfer/experimental/b12x/_api.py).
16
+ # # Seen on v0.32.0 (2026-11-05); re-test before moving the tag. Local GPU: uv run --with vllm.
17
  # image = "vllm/vllm-openai:v0.32.0"
18
  # python = "/usr/bin/python3"
19
  # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
 
29
  labels and confidence scores.
30
 
31
  Example usage:
32
+ # Local execution (Linux + CUDA). The header leaves vllm, torch and
33
+ # transformers to the HF Jobs image, so add vllm with --with.
34
+ uv run --with vllm classify-dataset.py \\
35
  davanstrien/ModernBERT-base-is-new-arxiv-dataset \\
36
  username/input-dataset \\
37
  username/output-dataset \\
38
  --inference-column text \\
39
  --batch-size 10000
40
 
41
+ # HF Jobs execution (the header sets the vLLM image, flavor and HF_TOKEN secret)
42
+ hf jobs uv run classify-dataset.py model/name input-dataset output-dataset
43
  """
44
 
45
  import argparse
 
49
  from typing import Optional
50
 
51
  import httpx
 
 
 
52
  from datasets import load_dataset
53
  from huggingface_hub import hf_hub_url, login
54
  from toolz import concat, keymap, partition_all
55
  from tqdm.auto import tqdm
56
+
57
+ # torch and vllm are imported inside the functions that use them, so
58
+ # `uv run classify-dataset.py --help` works without them. On HF Jobs they come from
59
+ # the vLLM image (see the header).
60
 
61
  logging.basicConfig(
62
  level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
 
66
 
67
  def check_gpu_availability():
68
  """Check if CUDA is available and log GPU information."""
69
+ import torch
70
+ import vllm
71
+
72
  if not torch.cuda.is_available():
73
  logger.error("CUDA is not available. This script requires a GPU.")
74
  logger.error(
 
120
  Returns:
121
  Tuple of (label, confidence_score)
122
  """
123
+ import torch
124
+ import torch.nn.functional as F
125
+
126
  logits = torch.tensor(output.outputs.probs)
127
  probs = F.softmax(logits, dim=0)
128
  top_idx = torch.argmax(probs).item()
 
152
  batch_size: Number of examples to process at once
153
  hf_token: Hugging Face authentication token
154
  """
155
+ from vllm import LLM
156
+
157
  # GPU check
158
  check_gpu_availability()
159
 
 
226
  formatter_class=argparse.RawDescriptionHelpFormatter,
227
  epilog="""
228
  Examples:
229
+ # Local GPU (Linux + CUDA): the header leaves vllm/torch/transformers to
230
+ # the HF Jobs image, so add vllm with --with.
231
  # Basic usage
232
+ uv run --with vllm classify-dataset.py model/name input-dataset output-dataset
233
 
234
  # With custom column and batch size
235
+ uv run --with vllm classify-dataset.py model/name input-dataset output-dataset \\
236
  --inference-column prompt \\
237
  --batch-size 50000
238
 
239
  # Using environment variable for token
240
+ HF_TOKEN=hf_xxx uv run --with vllm classify-dataset.py model/name input-dataset output-dataset
241
  """,
242
  )
243
 
 
289
  This script requires arguments. For usage information:
290
  uv run classify-dataset.py --help
291
 
292
+ Example HF Jobs command (the header sets the vLLM image, l4x1 and the HF_TOKEN secret):
293
+ hf jobs uv run \\
294
+ https://huggingface.co/datasets/uv-scripts/vllm/raw/main/classify-dataset.py \\
295
+ davanstrien/ModernBERT-base-is-new-arxiv-dataset \\
296
+ username/input-dataset \\
297
+ username/output-dataset \\
298
+ --inference-column text \\
299
+ --batch-size 100000
 
 
 
 
 
 
 
300
  """)
generate-responses.py CHANGED
@@ -2,15 +2,16 @@
2
  # requires-python = ">=3.10"
3
  # dependencies = [
4
  # "datasets",
5
- # "flashinfer-python",
6
  # "huggingface-hub",
7
  # "hf-xet>= 1.1.7",
8
- # "torch",
9
- # "transformers",
10
- # "vllm>=0.11.0",
11
  # ]
12
  #
13
  # [tool.hf-jobs]
 
 
 
 
 
14
  # image = "vllm/vllm-openai:v0.32.0"
15
  # python = "/usr/bin/python3"
16
  # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
@@ -26,14 +27,15 @@ applies the model's chat template, generates responses using vLLM, and saves the
26
  results back to the Hub with a comprehensive dataset card.
27
 
28
  Example usage:
29
- # Local execution with auto GPU detection
30
- uv run generate-responses.py \\
 
31
  username/input-dataset \\
32
  username/output-dataset \\
33
  --messages-column messages
34
 
35
  # With custom model and sampling parameters
36
- uv run generate-responses.py \\
37
  username/input-dataset \\
38
  username/output-dataset \\
39
  --model-id meta-llama/Llama-3.1-8B-Instruct \\
@@ -51,14 +53,18 @@ import logging
51
  import os
52
  import sys
53
  from datetime import datetime
54
- from typing import Optional
55
 
56
  from datasets import load_dataset
57
  from huggingface_hub import DatasetCard, get_token, login
58
- from torch import cuda
59
  from tqdm.auto import tqdm
60
- from transformers import AutoTokenizer
61
- from vllm import LLM, SamplingParams
 
 
 
 
 
62
 
63
  logging.basicConfig(
64
  level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
@@ -68,6 +74,8 @@ logger = logging.getLogger(__name__)
68
 
69
  def check_gpu_availability() -> int:
70
  """Check if CUDA is available and return the number of GPUs."""
 
 
71
  if not cuda.is_available():
72
  logger.error("CUDA is not available. This script requires a GPU.")
73
  logger.error(
@@ -89,7 +97,7 @@ def create_dataset_card(
89
  model_id: str,
90
  messages_column: str,
91
  prompt_column: Optional[str],
92
- sampling_params: SamplingParams,
93
  tensor_parallel_size: int,
94
  num_examples: int,
95
  generation_time: str,
@@ -112,6 +120,12 @@ def create_dataset_card(
112
 
113
  Note: Prompts exceeding the maximum model length were skipped and have empty responses."""
114
 
 
 
 
 
 
 
115
  return f"""---
116
  tags:
117
  - generated
@@ -154,10 +168,10 @@ The dataset contains all columns from the source dataset plus:
154
 
155
  Generated using the vLLM inference script from [uv-scripts/vllm](https://huggingface.co/datasets/uv-scripts/vllm).
156
 
157
- To reproduce this generation:
158
 
159
  ```bash
160
- uv run https://huggingface.co/datasets/uv-scripts/vllm/raw/main/generate-responses.py \\
161
  {source_dataset} \\
162
  <output-dataset> \\
163
  --model-id {model_id} \\
@@ -165,7 +179,7 @@ uv run https://huggingface.co/datasets/uv-scripts/vllm/raw/main/generate-respons
165
  --temperature {sampling_params.temperature} \\
166
  --top-p {sampling_params.top_p} \\
167
  --top-k {sampling_params.top_k} \\
168
- --max-tokens {sampling_params.max_tokens}{f" \\\\\\n --max-model-len {max_model_len_used}" if max_model_len_used else ""}
169
  ```
170
  """
171
 
@@ -213,6 +227,9 @@ def main(
213
  max_samples: Maximum number of samples to process (None for all)
214
  hf_token: Hugging Face authentication token
215
  """
 
 
 
216
  generation_start_time = datetime.now().isoformat()
217
 
218
  # GPU check and configuration
@@ -423,22 +440,24 @@ if __name__ == "__main__":
423
  formatter_class=argparse.RawDescriptionHelpFormatter,
424
  epilog="""
425
  Examples:
 
 
426
  # Basic usage with default Qwen model
427
- uv run generate-responses.py input-dataset output-dataset
428
 
429
  # With custom model and parameters
430
- uv run generate-responses.py input-dataset output-dataset \\
431
  --model-id meta-llama/Llama-3.1-8B-Instruct \\
432
  --temperature 0.9 \\
433
  --max-tokens 2048
434
 
435
  # Force specific GPU configuration
436
- uv run generate-responses.py input-dataset output-dataset \\
437
  --tensor-parallel-size 2 \\
438
  --gpu-memory-utilization 0.95
439
 
440
  # Using environment variable for token
441
- HF_TOKEN=hf_xxx uv run generate-responses.py input-dataset output-dataset
442
  """,
443
  )
444
 
 
2
  # requires-python = ">=3.10"
3
  # dependencies = [
4
  # "datasets",
 
5
  # "huggingface-hub",
6
  # "hf-xet>= 1.1.7",
 
 
 
7
  # ]
8
  #
9
  # [tool.hf-jobs]
10
+ # # vllm, torch, transformers and flashinfer come from the image (PYTHONPATH). Listing them above
11
+ # # makes uv install newer PyPI copies. PYTHONPATH shadows the copies, but the current
12
+ # # flashinfer-python wheel (0.7.2.post1) also ships a top-level b12x module that the image lacks.
13
+ # # The image's vllm imports it and crashes (missing flashinfer/experimental/b12x/_api.py).
14
+ # # Seen on v0.32.0 (2026-11-05); re-test before moving the tag. Local GPU: uv run --with vllm.
15
  # image = "vllm/vllm-openai:v0.32.0"
16
  # python = "/usr/bin/python3"
17
  # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
 
27
  results back to the Hub with a comprehensive dataset card.
28
 
29
  Example usage:
30
+ # Local execution with auto GPU detection. The header leaves vllm, torch and
31
+ # transformers to the HF Jobs image, so add vllm with --with.
32
+ uv run --with vllm generate-responses.py \\
33
  username/input-dataset \\
34
  username/output-dataset \\
35
  --messages-column messages
36
 
37
  # With custom model and sampling parameters
38
+ uv run --with vllm generate-responses.py \\
39
  username/input-dataset \\
40
  username/output-dataset \\
41
  --model-id meta-llama/Llama-3.1-8B-Instruct \\
 
53
  import os
54
  import sys
55
  from datetime import datetime
56
+ from typing import TYPE_CHECKING, Optional
57
 
58
  from datasets import load_dataset
59
  from huggingface_hub import DatasetCard, get_token, login
 
60
  from tqdm.auto import tqdm
61
+
62
+ if TYPE_CHECKING:
63
+ from vllm import SamplingParams
64
+
65
+ # torch, transformers and vllm are imported inside the functions that use them, so
66
+ # `uv run generate-responses.py --help` works without them. On HF Jobs they come from
67
+ # the vLLM image (see the header).
68
 
69
  logging.basicConfig(
70
  level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
 
74
 
75
  def check_gpu_availability() -> int:
76
  """Check if CUDA is available and return the number of GPUs."""
77
+ from torch import cuda
78
+
79
  if not cuda.is_available():
80
  logger.error("CUDA is not available. This script requires a GPU.")
81
  logger.error(
 
97
  model_id: str,
98
  messages_column: str,
99
  prompt_column: Optional[str],
100
+ sampling_params: "SamplingParams",
101
  tensor_parallel_size: int,
102
  num_examples: int,
103
  generation_time: str,
 
120
 
121
  Note: Prompts exceeding the maximum model length were skipped and have empty responses."""
122
 
123
+ # Built outside the card f-string: a backslash inside an f-string expression is a
124
+ # SyntaxError before Python 3.12.
125
+ max_model_len_line = (
126
+ f" \\\n --max-model-len {max_model_len_used}" if max_model_len_used else ""
127
+ )
128
+
129
  return f"""---
130
  tags:
131
  - generated
 
168
 
169
  Generated using the vLLM inference script from [uv-scripts/vllm](https://huggingface.co/datasets/uv-scripts/vllm).
170
 
171
+ To reproduce this generation on HF Jobs (the script header sets the vLLM image, flavor and HF_TOKEN secret):
172
 
173
  ```bash
174
+ hf jobs uv run https://huggingface.co/datasets/uv-scripts/vllm/raw/main/generate-responses.py \\
175
  {source_dataset} \\
176
  <output-dataset> \\
177
  --model-id {model_id} \\
 
179
  --temperature {sampling_params.temperature} \\
180
  --top-p {sampling_params.top_p} \\
181
  --top-k {sampling_params.top_k} \\
182
+ --max-tokens {sampling_params.max_tokens}{max_model_len_line}
183
  ```
184
  """
185
 
 
227
  max_samples: Maximum number of samples to process (None for all)
228
  hf_token: Hugging Face authentication token
229
  """
230
+ from transformers import AutoTokenizer
231
+ from vllm import LLM, SamplingParams
232
+
233
  generation_start_time = datetime.now().isoformat()
234
 
235
  # GPU check and configuration
 
440
  formatter_class=argparse.RawDescriptionHelpFormatter,
441
  epilog="""
442
  Examples:
443
+ # Local GPU (Linux + CUDA): the header leaves vllm/torch/transformers to
444
+ # the HF Jobs image, so add vllm with --with.
445
  # Basic usage with default Qwen model
446
+ uv run --with vllm generate-responses.py input-dataset output-dataset
447
 
448
  # With custom model and parameters
449
+ uv run --with vllm generate-responses.py input-dataset output-dataset \\
450
  --model-id meta-llama/Llama-3.1-8B-Instruct \\
451
  --temperature 0.9 \\
452
  --max-tokens 2048
453
 
454
  # Force specific GPU configuration
455
+ uv run --with vllm generate-responses.py input-dataset output-dataset \\
456
  --tensor-parallel-size 2 \\
457
  --gpu-memory-utilization 0.95
458
 
459
  # Using environment variable for token
460
+ HF_TOKEN=hf_xxx uv run --with vllm generate-responses.py input-dataset output-dataset
461
  """,
462
  )
463
 
vlm-classify.py CHANGED
@@ -5,13 +5,15 @@
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "toolz",
8
- # "torch",
9
  # "tqdm",
10
- # "transformers",
11
- # "vllm>=0.11.0", # StructuredOutputsParams API (guided_decoding removed in 0.12.0)
12
  # ]
13
  #
14
  # [tool.hf-jobs]
 
 
 
 
 
15
  # image = "vllm/vllm-openai:v0.32.0"
16
  # python = "/usr/bin/python3"
17
  # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
@@ -24,17 +26,19 @@
24
  Classify images using Vision Language Models with vLLM.
25
 
26
  This script processes images through VLMs to classify them into user-defined categories,
27
- using vLLM's GuidedDecodingParams for structured output.
28
 
29
  Examples:
 
 
30
  # Basic classification
31
- uv run vlm-classify.py \\
32
  username/input-dataset \\
33
  username/output-dataset \\
34
  --classes "document,photo,diagram,other"
35
 
36
  # With custom prompt and model
37
- uv run vlm-classify.py \\
38
  username/input-dataset \\
39
  username/output-dataset \\
40
  --classes "index-card,manuscript,title-page,other" \\
@@ -42,7 +46,7 @@ Examples:
42
  --model Qwen/Qwen2-VL-7B-Instruct
43
 
44
  # Quick test with sample limit
45
- uv run vlm-classify.py \\
46
  davanstrien/sloane-index-cards \\
47
  username/test-output \\
48
  --classes "index,content,other" \\
@@ -58,14 +62,14 @@ import sys
58
  from collections import Counter
59
  from typing import List, Optional, Union, Dict, Any
60
 
61
- import torch
62
  from PIL import Image
63
  from datasets import load_dataset
64
  from huggingface_hub import login
65
  from toolz import partition_all
66
  from tqdm.auto import tqdm
67
- from vllm import LLM, SamplingParams
68
- from vllm.sampling_params import StructuredOutputsParams
 
69
 
70
  logging.basicConfig(level=logging.INFO)
71
  logger = logging.getLogger(__name__)
@@ -142,6 +146,9 @@ def main(
142
  private: bool = False,
143
  ):
144
  """Classify images from a dataset using a Vision Language Model."""
 
 
 
145
 
146
  # Check GPU availability
147
  if not torch.cuda.is_available():
@@ -303,14 +310,16 @@ if __name__ == "__main__":
303
  formatter_class=argparse.RawDescriptionHelpFormatter,
304
  epilog="""
305
  Examples:
 
 
306
  # Basic classification
307
- uv run vlm-classify.py \\
308
  username/input-dataset \\
309
  username/output-dataset \\
310
  --classes "document,photo,diagram,other"
311
 
312
  # With custom prompt
313
- uv run vlm-classify.py \\
314
  username/input-dataset \\
315
  username/output-dataset \\
316
  --classes "index-card,manuscript,other" \\
 
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "toolz",
 
8
  # "tqdm",
 
 
9
  # ]
10
  #
11
  # [tool.hf-jobs]
12
+ # # vllm, torch and transformers come from the image (PYTHONPATH). Listing them above makes uv
13
+ # # install newer PyPI copies plus their deps. PYTHONPATH shadows the copies, but the current
14
+ # # flashinfer-python wheel (0.7.2.post1) also ships a top-level b12x module that the image lacks.
15
+ # # The image's vllm imports it and crashes (missing flashinfer/experimental/b12x/_api.py).
16
+ # # Seen on v0.32.0 (2026-11-05); re-test before moving the tag. Local GPU: uv run --with vllm.
17
  # image = "vllm/vllm-openai:v0.32.0"
18
  # python = "/usr/bin/python3"
19
  # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
 
26
  Classify images using Vision Language Models with vLLM.
27
 
28
  This script processes images through VLMs to classify them into user-defined categories,
29
+ using vLLM's StructuredOutputsParams for structured output.
30
 
31
  Examples:
32
+ # Local GPU (Linux + CUDA): the header leaves vllm/torch/transformers to
33
+ # the HF Jobs image, so add vllm with --with.
34
  # Basic classification
35
+ uv run --with vllm vlm-classify.py \\
36
  username/input-dataset \\
37
  username/output-dataset \\
38
  --classes "document,photo,diagram,other"
39
 
40
  # With custom prompt and model
41
+ uv run --with vllm vlm-classify.py \\
42
  username/input-dataset \\
43
  username/output-dataset \\
44
  --classes "index-card,manuscript,title-page,other" \\
 
46
  --model Qwen/Qwen2-VL-7B-Instruct
47
 
48
  # Quick test with sample limit
49
+ uv run --with vllm vlm-classify.py \\
50
  davanstrien/sloane-index-cards \\
51
  username/test-output \\
52
  --classes "index,content,other" \\
 
62
  from collections import Counter
63
  from typing import List, Optional, Union, Dict, Any
64
 
 
65
  from PIL import Image
66
  from datasets import load_dataset
67
  from huggingface_hub import login
68
  from toolz import partition_all
69
  from tqdm.auto import tqdm
70
+
71
+ # torch and vllm are imported inside main(), so `uv run vlm-classify.py --help` works
72
+ # without them. On HF Jobs they come from the vLLM image (see the header).
73
 
74
  logging.basicConfig(level=logging.INFO)
75
  logger = logging.getLogger(__name__)
 
146
  private: bool = False,
147
  ):
148
  """Classify images from a dataset using a Vision Language Model."""
149
+ import torch
150
+ from vllm import LLM, SamplingParams
151
+ from vllm.sampling_params import StructuredOutputsParams
152
 
153
  # Check GPU availability
154
  if not torch.cuda.is_available():
 
310
  formatter_class=argparse.RawDescriptionHelpFormatter,
311
  epilog="""
312
  Examples:
313
+ # Local GPU (Linux + CUDA): the header leaves vllm/torch/transformers to
314
+ # the HF Jobs image, so add vllm with --with.
315
  # Basic classification
316
+ uv run --with vllm vlm-classify.py \\
317
  username/input-dataset \\
318
  username/output-dataset \\
319
  --classes "document,photo,diagram,other"
320
 
321
  # With custom prompt
322
+ uv run --with vllm vlm-classify.py \\
323
  username/input-dataset \\
324
  username/output-dataset \\
325
  --classes "index-card,manuscript,other" \\