tytodd commited on
Commit
94986aa
·
verified ·
1 Parent(s): ef59299

Upload generate_responses.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. generate_responses.py +203 -291
generate_responses.py CHANGED
@@ -13,46 +13,27 @@
13
  #
14
  # ///
15
  """
16
- Generate responses for prompts in a dataset using vLLM for efficient GPU inference.
17
-
18
- This script loads a dataset from Hugging Face Hub containing chat-formatted messages,
19
- applies the model's chat template, generates responses using vLLM, and saves the
20
- results back to the Hub with a comprehensive dataset card.
21
-
22
- Example usage:
23
- # Local execution with auto GPU detection
24
- uv run generate_responses.py \\
25
- username/input-dataset \\
26
- username/output-dataset \\
27
- --messages-column messages
28
-
29
- # With custom model and sampling parameters
30
- uv run generate_responses.py \\
31
- username/input-dataset \\
32
- username/output-dataset \\
33
- --model-id meta-llama/Llama-3.1-8B-Instruct \\
34
- --temperature 0.9 \\
35
- --top-p 0.95 \\
36
- --max-tokens 2048
37
-
38
- # HF Jobs execution (see script output for full command)
39
- hf jobs uv run --flavor a100x4 ...
40
  """
41
 
42
  import argparse
 
43
  import logging
44
  import os
 
45
  import sys
 
 
 
 
46
  from datetime import datetime
47
- from typing import Optional
48
 
49
  from datasets import load_dataset
50
  from huggingface_hub import DatasetCard, get_token, login
51
  from torch import cuda
52
  from tqdm.auto import tqdm
53
- from vllm import LLM, SamplingParams
54
 
55
- # Enable HF Transfer for faster downloads
56
  os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
57
 
58
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
@@ -61,31 +42,22 @@ logger = logging.getLogger(__name__)
61
  UV_SCRIPT_REPO_ID = "modaic/batch-vllm"
62
  UV_SCRIPT_FILENAME = "generate_responses.py"
63
  UV_SCRIPT_URL = f"https://huggingface.co/datasets/{UV_SCRIPT_REPO_ID}/resolve/main/{UV_SCRIPT_FILENAME}"
 
 
 
64
 
65
 
66
- def extract_output_payload(output) -> dict[str, Optional[str]]:
67
- """Convert a vLLM chat result into a dataset-serializable dict."""
68
- completion = output.outputs[0] if getattr(output, "outputs", None) else None
69
- text = getattr(completion, "text", "") if completion is not None else ""
70
- print("COMPLETION", completion)
71
- print("hasattr reasoning_content", hasattr(completion, "reasoning_content"))
72
- print("hasattr reasoning", hasattr(completion, "reasoning"))
73
- print("completion attrs", dir(completion))
74
-
75
- reasoning_content = None
76
- if completion is not None:
77
- reasoning_content = getattr(completion, "reasoning_content", None)
78
- if reasoning_content is None:
79
- reasoning_content = getattr(completion, "reasoning", None)
80
-
81
- return {
82
- "text": text,
83
- "reasoning_content": reasoning_content,
84
- }
85
 
86
 
87
  def check_gpu_availability() -> int:
88
- """Check if CUDA is available and return the number of GPUs."""
89
  if not cuda.is_available():
90
  logger.error("CUDA is not available. This script requires a GPU.")
91
  logger.error("Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor.")
@@ -100,19 +72,150 @@ def check_gpu_availability() -> int:
100
  return num_gpus
101
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  def create_dataset_card(
104
  source_dataset: str,
105
  model_id: str,
106
  messages_column: str,
107
  prompt_column: Optional[str],
108
- sampling_params: SamplingParams,
109
  tensor_parallel_size: int,
110
  num_examples: int,
111
  generation_time: str,
112
  num_skipped: int = 0,
113
  max_model_len_used: Optional[int] = None,
114
  ) -> str:
115
- """Create a comprehensive dataset card documenting the generation process."""
116
  filtering_section = ""
117
  input_column_flag = f"--prompt-column {prompt_column}" if prompt_column else f"--messages-column {messages_column}"
118
  max_model_len_flag = f" \\\n --max-model-len {max_model_len_used}" if max_model_len_used else ""
@@ -152,12 +255,12 @@ This dataset contains generated responses for prompts from [{source_dataset}](ht
152
 
153
  ### Sampling Parameters
154
 
155
- - **Temperature**: {sampling_params.temperature}
156
- - **Top P**: {sampling_params.top_p}
157
- - **Top K**: {sampling_params.top_k}
158
- - **Min P**: {sampling_params.min_p}
159
- - **Max Tokens**: {sampling_params.max_tokens}
160
- - **Repetition Penalty**: {sampling_params.repetition_penalty}
161
 
162
  ### Hardware Configuration
163
 
@@ -181,10 +284,10 @@ uv run {UV_SCRIPT_URL} \\
181
  <output-dataset> \\
182
  --model-id {model_id} \\
183
  {input_column_flag} \\
184
- --temperature {sampling_params.temperature} \\
185
- --top-p {sampling_params.top_p} \\
186
- --top-k {sampling_params.top_k} \\
187
- --max-tokens {sampling_params.max_tokens}{max_model_len_flag}
188
  ```
189
  """
190
 
@@ -211,34 +314,8 @@ def main(
211
  max_samples: Optional[int] = None,
212
  hf_token: Optional[str] = None,
213
  ):
214
- """
215
- Main generation pipeline.
216
-
217
- Args:
218
- src_dataset_hub_id: Input dataset on Hugging Face Hub
219
- output_dataset_hub_id: Where to save results on Hugging Face Hub
220
- model_id: Hugging Face model ID for generation
221
- reasoning_parser: Optional vLLM reasoning parser to enable structured reasoning extraction
222
- messages_column: Column name containing chat messages
223
- prompt_column: Column name containing plain text prompts (alternative to messages_column)
224
- output_column: Column name for generated responses
225
- temperature: Sampling temperature
226
- top_p: Top-p sampling parameter
227
- top_k: Top-k sampling parameter
228
- min_p: Minimum probability threshold
229
- max_tokens: Maximum tokens to generate
230
- repetition_penalty: Repetition penalty parameter
231
- gpu_memory_utilization: GPU memory utilization factor
232
- max_model_len: Maximum model context length (None uses model default)
233
- tensor_parallel_size: Number of GPUs to use (auto-detect if None)
234
- skip_long_prompts: Deprecated. Prompt pre-filtering is not used in chat mode.
235
- enable_thinking: Enable model thinking/reasoning when supported by the chat template
236
- max_samples: Maximum number of samples to process (None for all)
237
- hf_token: Hugging Face authentication token
238
- """
239
  generation_start_time = datetime.now().isoformat()
240
 
241
- # GPU check and configuration
242
  num_gpus = check_gpu_availability()
243
  if tensor_parallel_size is None:
244
  tensor_parallel_size = num_gpus
@@ -248,10 +325,8 @@ def main(
248
  if tensor_parallel_size > num_gpus:
249
  logger.warning(f"Requested {tensor_parallel_size} GPUs but only {num_gpus} available")
250
 
251
- # Authentication - try multiple methods
252
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") or get_token()
253
-
254
- if not HF_TOKEN:
255
  logger.error("No HuggingFace token found. Please provide token via:")
256
  logger.error(" 1. --hf-token argument")
257
  logger.error(" 2. HF_TOKEN environment variable")
@@ -259,26 +334,9 @@ def main(
259
  sys.exit(1)
260
 
261
  logger.info("HuggingFace token found, authenticating...")
262
- login(token=HF_TOKEN)
263
-
264
- # Initialize vLLM
265
- logger.info(f"Loading model: {model_id}")
266
- vllm_kwargs = {
267
- "model": model_id,
268
- "tensor_parallel_size": tensor_parallel_size,
269
- "gpu_memory_utilization": gpu_memory_utilization,
270
- }
271
- if max_model_len is not None:
272
- vllm_kwargs["max_model_len"] = max_model_len
273
- logger.info(f"Using max_model_len={max_model_len}")
274
- if reasoning_parser is not None:
275
- vllm_kwargs["reasoning_parser"] = reasoning_parser
276
- logger.info(f"Using reasoning_parser={reasoning_parser}")
277
-
278
- llm = LLM(**vllm_kwargs)
279
 
280
- # Create sampling parameters
281
- sampling_params = SamplingParams(
282
  temperature=temperature,
283
  top_p=top_p,
284
  top_k=top_k,
@@ -287,11 +345,9 @@ def main(
287
  repetition_penalty=repetition_penalty,
288
  )
289
 
290
- # Load dataset
291
  logger.info(f"Loading dataset: {src_dataset_hub_id}")
292
  dataset = load_dataset(src_dataset_hub_id, split="train")
293
 
294
- # Apply max_samples if specified
295
  if max_samples is not None and max_samples < len(dataset):
296
  logger.info(f"Limiting dataset to {max_samples} samples")
297
  dataset = dataset.select(range(max_samples))
@@ -299,16 +355,13 @@ def main(
299
  total_examples = len(dataset)
300
  logger.info(f"Dataset loaded with {total_examples:,} examples")
301
 
302
- # Determine which column to use and validate
303
  if prompt_column:
304
- # Use prompt column mode
305
  if prompt_column not in dataset.column_names:
306
  logger.error(f"Column '{prompt_column}' not found. Available columns: {dataset.column_names}")
307
  sys.exit(1)
308
  logger.info(f"Using prompt column mode with column: '{prompt_column}'")
309
  use_messages = False
310
  else:
311
- # Use messages column mode
312
  if messages_column not in dataset.column_names:
313
  logger.error(f"Column '{messages_column}' not found. Available columns: {dataset.column_names}")
314
  sys.exit(1)
@@ -316,55 +369,41 @@ def main(
316
  use_messages = True
317
 
318
  if skip_long_prompts:
319
- logger.info(
320
- "Prompt length pre-filtering is disabled when using llm.chat(); model limits will be enforced at inference time"
321
- )
322
 
323
  logger.info("Preparing chat messages...")
324
- conversations = []
325
-
326
  for example in tqdm(dataset, desc="Processing prompts"):
327
  if use_messages:
328
- messages = example[messages_column]
329
  else:
330
- user_prompt = example[prompt_column]
331
- messages = [{"role": "user", "content": user_prompt}]
332
-
333
- conversations.append(messages)
334
 
335
  if not conversations:
336
  logger.error("No prompts to process!")
337
  sys.exit(1)
338
 
339
- # Generate responses - vLLM handles batching internally
340
- logger.info(f"Starting chat generation for {len(conversations):,} prompts...")
341
- logger.info("vLLM will handle batching and scheduling automatically")
342
-
343
- outputs = llm.chat(
344
  conversations,
345
- sampling_params=sampling_params,
346
- chat_template_kwargs={"enable_thinking": enable_thinking},
 
 
 
 
 
347
  )
348
 
349
- # Extract generated text and create full response list
350
- logger.info("Extracting generated responses...")
351
- responses = [{"text": "", "reasoning_content": None} for _ in range(total_examples)]
352
-
353
- for idx, output in enumerate(outputs):
354
- responses[idx] = extract_output_payload(output)
355
-
356
- # Add responses to dataset
357
  logger.info("Adding responses to dataset...")
358
  dataset = dataset.add_column(output_column, responses)
359
 
360
- # Create dataset card
361
  logger.info("Creating dataset card...")
362
  card_content = create_dataset_card(
363
  source_dataset=src_dataset_hub_id,
364
  model_id=model_id,
365
  messages_column=messages_column,
366
  prompt_column=prompt_column,
367
- sampling_params=sampling_params,
368
  tensor_parallel_size=tensor_parallel_size,
369
  num_examples=total_examples,
370
  generation_time=generation_start_time,
@@ -372,157 +411,44 @@ def main(
372
  max_model_len_used=max_model_len,
373
  )
374
 
375
- # Push dataset to hub
376
  logger.info(f"Pushing dataset to: {output_dataset_hub_id}")
377
- dataset.push_to_hub(output_dataset_hub_id, token=HF_TOKEN)
378
 
379
- # Push dataset card
380
  card = DatasetCard(card_content)
381
- card.push_to_hub(output_dataset_hub_id, token=HF_TOKEN)
382
 
383
- logger.info("Generation complete!")
384
  logger.info(f"Dataset available at: https://huggingface.co/datasets/{output_dataset_hub_id}")
385
 
386
 
387
  if __name__ == "__main__":
388
  if len(sys.argv) > 1:
389
  parser = argparse.ArgumentParser(
390
- description="Generate responses for dataset prompts using vLLM",
391
  formatter_class=argparse.RawDescriptionHelpFormatter,
392
- epilog="""
393
- Examples:
394
- # Basic usage with default Qwen model
395
- uv run generate-responses.py input-dataset output-dataset
396
-
397
- # With custom model and parameters
398
- uv run generate-responses.py input-dataset output-dataset \\
399
- --model-id meta-llama/Llama-3.1-8B-Instruct \\
400
- --temperature 0.9 \\
401
- --max-tokens 2048
402
-
403
- # Force specific GPU configuration
404
- uv run generate-responses.py input-dataset output-dataset \\
405
- --tensor-parallel-size 2 \\
406
- --gpu-memory-utilization 0.95
407
-
408
- # Using environment variable for token
409
- HF_TOKEN=hf_xxx uv run generate-responses.py input-dataset output-dataset
410
- """,
411
  )
412
 
413
- parser.add_argument(
414
- "src_dataset_hub_id",
415
- help="Input dataset on Hugging Face Hub (e.g., username/dataset-name)",
416
- )
417
  parser.add_argument("output_dataset_hub_id", help="Output dataset name on Hugging Face Hub")
418
- parser.add_argument(
419
- "--model-id",
420
- type=str,
421
- default="Qwen/Qwen3-30B-A3B-Instruct-2507",
422
- help="Model to use for generation (default: Qwen3-30B-A3B-Instruct-2507)",
423
- )
424
- parser.add_argument(
425
- "--messages-column",
426
- type=str,
427
- default="messages",
428
- help="Column containing chat messages (default: messages)",
429
- )
430
- parser.add_argument(
431
- "--reasoning-parser",
432
- type=str,
433
- help="vLLM reasoning parser to use for supported models",
434
- )
435
- parser.add_argument(
436
- "--prompt-column",
437
- type=str,
438
- help="Column containing plain text prompts (alternative to --messages-column)",
439
- )
440
- parser.add_argument(
441
- "--output-column",
442
- type=str,
443
- default="outputs",
444
- help="Column name for generated responses (default: outputs)",
445
- )
446
- parser.add_argument(
447
- "--max-samples",
448
- type=int,
449
- help="Maximum number of samples to process (default: all)",
450
- )
451
- parser.add_argument(
452
- "--temperature",
453
- type=float,
454
- default=0.7,
455
- help="Sampling temperature (default: 0.7)",
456
- )
457
- parser.add_argument(
458
- "--top-p",
459
- type=float,
460
- default=0.8,
461
- help="Top-p sampling parameter (default: 0.8)",
462
- )
463
- parser.add_argument(
464
- "--top-k",
465
- type=int,
466
- default=20,
467
- help="Top-k sampling parameter (default: 20)",
468
- )
469
- parser.add_argument(
470
- "--min-p",
471
- type=float,
472
- default=0.0,
473
- help="Minimum probability threshold (default: 0.0)",
474
- )
475
- parser.add_argument(
476
- "--max-tokens",
477
- type=int,
478
- default=16384,
479
- help="Maximum tokens to generate (default: 16384)",
480
- )
481
- parser.add_argument(
482
- "--repetition-penalty",
483
- type=float,
484
- default=1.0,
485
- help="Repetition penalty (default: 1.0)",
486
- )
487
- parser.add_argument(
488
- "--gpu-memory-utilization",
489
- type=float,
490
- default=0.90,
491
- help="GPU memory utilization factor (default: 0.90)",
492
- )
493
- parser.add_argument(
494
- "--max-model-len",
495
- type=int,
496
- help="Maximum model context length (default: model's default)",
497
- )
498
- parser.add_argument(
499
- "--tensor-parallel-size",
500
- type=int,
501
- help="Number of GPUs to use (default: auto-detect)",
502
- )
503
- parser.add_argument(
504
- "--enable-thinking",
505
- action="store_true",
506
- default=False,
507
- help="Enable model thinking/reasoning when supported (default: False)",
508
- )
509
- parser.add_argument(
510
- "--hf-token",
511
- type=str,
512
- help="Hugging Face token (can also use HF_TOKEN env var)",
513
- )
514
- parser.add_argument(
515
- "--skip-long-prompts",
516
- action="store_true",
517
- default=True,
518
- help="Skip prompts that exceed max_model_len instead of failing (default: True)",
519
- )
520
- parser.add_argument(
521
- "--no-skip-long-prompts",
522
- dest="skip_long_prompts",
523
- action="store_false",
524
- help="Fail on prompts that exceed max_model_len",
525
- )
526
 
527
  args = parser.parse_args()
528
 
@@ -549,7 +475,6 @@ Examples:
549
  hf_token=args.hf_token,
550
  )
551
  else:
552
- # Show HF Jobs example when run without arguments
553
  print(f"""
554
  vLLM Response Generation Script
555
  ==============================
@@ -565,17 +490,4 @@ Upload this script to the Hub:
565
 
566
  Canonical script URL:
567
  {UV_SCRIPT_URL}
568
-
569
- Example HF Jobs command with multi-GPU:
570
- # If you're logged in with huggingface-cli, token will be auto-detected
571
- hf jobs uv run \\
572
- --flavor l4x4 \\
573
- --secrets HF_TOKEN \\
574
- {UV_SCRIPT_URL} \\
575
- username/input-dataset \\
576
- username/output-dataset \\
577
- --messages-column messages \\
578
- --model-id Qwen/Qwen3-30B-A3B-Instruct-2507 \\
579
- --temperature 0.7 \\
580
- --max-tokens 16384
581
  """)
 
13
  #
14
  # ///
15
  """
16
+ Generate responses for prompts in a dataset using a local vLLM OpenAI-compatible server.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
 
19
  import argparse
20
+ import json
21
  import logging
22
  import os
23
+ import subprocess
24
  import sys
25
+ import time
26
+ import urllib.request
27
+ from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
28
+ from dataclasses import dataclass
29
  from datetime import datetime
30
+ from typing import Any, Optional
31
 
32
  from datasets import load_dataset
33
  from huggingface_hub import DatasetCard, get_token, login
34
  from torch import cuda
35
  from tqdm.auto import tqdm
 
36
 
 
37
  os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
38
 
39
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
 
42
  UV_SCRIPT_REPO_ID = "modaic/batch-vllm"
43
  UV_SCRIPT_FILENAME = "generate_responses.py"
44
  UV_SCRIPT_URL = f"https://huggingface.co/datasets/{UV_SCRIPT_REPO_ID}/resolve/main/{UV_SCRIPT_FILENAME}"
45
+ SERVER_PORT = 8000
46
+ SERVER_URL = f"http://127.0.0.1:{SERVER_PORT}"
47
+ MAX_IN_FLIGHT_REQUESTS = 256
48
 
49
 
50
+ @dataclass(frozen=True)
51
+ class GenerationConfig:
52
+ temperature: float
53
+ top_p: float
54
+ top_k: int
55
+ min_p: float
56
+ max_tokens: int
57
+ repetition_penalty: float
 
 
 
 
 
 
 
 
 
 
 
58
 
59
 
60
  def check_gpu_availability() -> int:
 
61
  if not cuda.is_available():
62
  logger.error("CUDA is not available. This script requires a GPU.")
63
  logger.error("Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor.")
 
72
  return num_gpus
73
 
74
 
75
+ def _wait_for_server(timeout_seconds: int = 1800) -> None:
76
+ deadline = time.time() + timeout_seconds
77
+ while time.time() < deadline:
78
+ try:
79
+ with urllib.request.urlopen(f"{SERVER_URL}/health", timeout=5) as response:
80
+ if response.status == 200:
81
+ return
82
+ except Exception:
83
+ time.sleep(2)
84
+ raise TimeoutError("Timed out waiting for the vLLM server to become healthy")
85
+
86
+
87
+ def _post_chat_completion(request_body: dict[str, Any]) -> dict[str, Any]:
88
+ request = urllib.request.Request(
89
+ f"{SERVER_URL}/v1/chat/completions",
90
+ data=json.dumps(request_body).encode("utf-8"),
91
+ headers={
92
+ "Content-Type": "application/json",
93
+ "Authorization": "Bearer EMPTY",
94
+ },
95
+ method="POST",
96
+ )
97
+ with urllib.request.urlopen(request, timeout=600) as response:
98
+ return json.loads(response.read().decode("utf-8"))
99
+
100
+
101
+ def _build_request_body(
102
+ model_id: str,
103
+ messages: list[dict[str, Any]],
104
+ generation: GenerationConfig,
105
+ enable_thinking: bool,
106
+ ) -> dict[str, Any]:
107
+ return {
108
+ "model": model_id,
109
+ "messages": messages,
110
+ "max_completion_tokens": generation.max_tokens,
111
+ "temperature": generation.temperature,
112
+ "top_p": generation.top_p,
113
+ "top_k": generation.top_k,
114
+ "min_p": generation.min_p,
115
+ "repetition_penalty": generation.repetition_penalty,
116
+ "include_reasoning": True,
117
+ "chat_template_kwargs": {"enable_thinking": enable_thinking},
118
+ }
119
+
120
+
121
+ def _extract_output_payload(response_body: dict[str, Any]) -> dict[str, Optional[str]]:
122
+ choices = response_body.get("choices") or []
123
+ if not choices:
124
+ return {"text": "", "reasoning_content": None}
125
+
126
+ message = choices[0].get("message") or {}
127
+ return {
128
+ "text": message.get("content") or "",
129
+ "reasoning_content": message.get("reasoning"),
130
+ }
131
+
132
+
133
+ def _run_generation_via_server(
134
+ conversations: list[list[dict[str, Any]]],
135
+ *,
136
+ model_id: str,
137
+ generation: GenerationConfig,
138
+ enable_thinking: bool,
139
+ tensor_parallel_size: int,
140
+ gpu_memory_utilization: float,
141
+ max_model_len: Optional[int],
142
+ reasoning_parser: Optional[str],
143
+ ) -> list[dict[str, Optional[str]]]:
144
+ env = os.environ.copy()
145
+ server_cmd = [
146
+ "vllm",
147
+ "serve",
148
+ model_id,
149
+ "--host",
150
+ "127.0.0.1",
151
+ "--port",
152
+ str(SERVER_PORT),
153
+ "--tensor-parallel-size",
154
+ str(tensor_parallel_size),
155
+ "--gpu-memory-utilization",
156
+ str(gpu_memory_utilization),
157
+ ]
158
+ if max_model_len is not None:
159
+ server_cmd.extend(["--max-model-len", str(max_model_len)])
160
+ if reasoning_parser:
161
+ server_cmd.extend(["--reasoning-parser", reasoning_parser])
162
+
163
+ logger.info("Starting vLLM server: %s", " ".join(server_cmd))
164
+ server = subprocess.Popen(server_cmd, env=env)
165
+
166
+ try:
167
+ _wait_for_server()
168
+ logger.info("vLLM server is healthy; keeping up to %d requests in flight", MAX_IN_FLIGHT_REQUESTS)
169
+
170
+ responses: list[dict[str, Optional[str]]] = [{"text": "", "reasoning_content": None} for _ in conversations]
171
+ submitted = 0
172
+ completed = 0
173
+ futures: dict[Future[dict[str, Any]], int] = {}
174
+
175
+ with ThreadPoolExecutor(max_workers=min(MAX_IN_FLIGHT_REQUESTS, len(conversations))) as executor:
176
+ with tqdm(total=len(conversations), desc="Generating responses") as progress:
177
+ while submitted < len(conversations) or futures:
178
+ while submitted < len(conversations) and len(futures) < MAX_IN_FLIGHT_REQUESTS:
179
+ request_body = _build_request_body(
180
+ model_id=model_id,
181
+ messages=conversations[submitted],
182
+ generation=generation,
183
+ enable_thinking=enable_thinking,
184
+ )
185
+ future = executor.submit(_post_chat_completion, request_body)
186
+ futures[future] = submitted
187
+ submitted += 1
188
+
189
+ done, _ = wait(futures.keys(), return_when=FIRST_COMPLETED)
190
+ for future in done:
191
+ index = futures.pop(future)
192
+ responses[index] = _extract_output_payload(future.result())
193
+ completed += 1
194
+ progress.update(1)
195
+
196
+ return responses
197
+ finally:
198
+ logger.info("Stopping vLLM server")
199
+ server.terminate()
200
+ try:
201
+ server.wait(timeout=30)
202
+ except subprocess.TimeoutExpired:
203
+ server.kill()
204
+ server.wait(timeout=30)
205
+
206
+
207
  def create_dataset_card(
208
  source_dataset: str,
209
  model_id: str,
210
  messages_column: str,
211
  prompt_column: Optional[str],
212
+ generation: GenerationConfig,
213
  tensor_parallel_size: int,
214
  num_examples: int,
215
  generation_time: str,
216
  num_skipped: int = 0,
217
  max_model_len_used: Optional[int] = None,
218
  ) -> str:
 
219
  filtering_section = ""
220
  input_column_flag = f"--prompt-column {prompt_column}" if prompt_column else f"--messages-column {messages_column}"
221
  max_model_len_flag = f" \\\n --max-model-len {max_model_len_used}" if max_model_len_used else ""
 
255
 
256
  ### Sampling Parameters
257
 
258
+ - **Temperature**: {generation.temperature}
259
+ - **Top P**: {generation.top_p}
260
+ - **Top K**: {generation.top_k}
261
+ - **Min P**: {generation.min_p}
262
+ - **Max Tokens**: {generation.max_tokens}
263
+ - **Repetition Penalty**: {generation.repetition_penalty}
264
 
265
  ### Hardware Configuration
266
 
 
284
  <output-dataset> \\
285
  --model-id {model_id} \\
286
  {input_column_flag} \\
287
+ --temperature {generation.temperature} \\
288
+ --top-p {generation.top_p} \\
289
+ --top-k {generation.top_k} \\
290
+ --max-tokens {generation.max_tokens}{max_model_len_flag}
291
  ```
292
  """
293
 
 
314
  max_samples: Optional[int] = None,
315
  hf_token: Optional[str] = None,
316
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  generation_start_time = datetime.now().isoformat()
318
 
 
319
  num_gpus = check_gpu_availability()
320
  if tensor_parallel_size is None:
321
  tensor_parallel_size = num_gpus
 
325
  if tensor_parallel_size > num_gpus:
326
  logger.warning(f"Requested {tensor_parallel_size} GPUs but only {num_gpus} available")
327
 
328
+ hf_access_token = hf_token or os.environ.get("HF_TOKEN") or get_token()
329
+ if not hf_access_token:
 
 
330
  logger.error("No HuggingFace token found. Please provide token via:")
331
  logger.error(" 1. --hf-token argument")
332
  logger.error(" 2. HF_TOKEN environment variable")
 
334
  sys.exit(1)
335
 
336
  logger.info("HuggingFace token found, authenticating...")
337
+ login(token=hf_access_token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
 
339
+ generation = GenerationConfig(
 
340
  temperature=temperature,
341
  top_p=top_p,
342
  top_k=top_k,
 
345
  repetition_penalty=repetition_penalty,
346
  )
347
 
 
348
  logger.info(f"Loading dataset: {src_dataset_hub_id}")
349
  dataset = load_dataset(src_dataset_hub_id, split="train")
350
 
 
351
  if max_samples is not None and max_samples < len(dataset):
352
  logger.info(f"Limiting dataset to {max_samples} samples")
353
  dataset = dataset.select(range(max_samples))
 
355
  total_examples = len(dataset)
356
  logger.info(f"Dataset loaded with {total_examples:,} examples")
357
 
 
358
  if prompt_column:
 
359
  if prompt_column not in dataset.column_names:
360
  logger.error(f"Column '{prompt_column}' not found. Available columns: {dataset.column_names}")
361
  sys.exit(1)
362
  logger.info(f"Using prompt column mode with column: '{prompt_column}'")
363
  use_messages = False
364
  else:
 
365
  if messages_column not in dataset.column_names:
366
  logger.error(f"Column '{messages_column}' not found. Available columns: {dataset.column_names}")
367
  sys.exit(1)
 
369
  use_messages = True
370
 
371
  if skip_long_prompts:
372
+ logger.info("Prompt length pre-filtering remains disabled; server-side limits will apply.")
 
 
373
 
374
  logger.info("Preparing chat messages...")
375
+ conversations: list[list[dict[str, Any]]] = []
 
376
  for example in tqdm(dataset, desc="Processing prompts"):
377
  if use_messages:
378
+ conversations.append(example[messages_column])
379
  else:
380
+ conversations.append([{"role": "user", "content": example[prompt_column]}])
 
 
 
381
 
382
  if not conversations:
383
  logger.error("No prompts to process!")
384
  sys.exit(1)
385
 
386
+ responses = _run_generation_via_server(
 
 
 
 
387
  conversations,
388
+ model_id=model_id,
389
+ generation=generation,
390
+ enable_thinking=enable_thinking,
391
+ tensor_parallel_size=tensor_parallel_size,
392
+ gpu_memory_utilization=gpu_memory_utilization,
393
+ max_model_len=max_model_len,
394
+ reasoning_parser=reasoning_parser,
395
  )
396
 
 
 
 
 
 
 
 
 
397
  logger.info("Adding responses to dataset...")
398
  dataset = dataset.add_column(output_column, responses)
399
 
 
400
  logger.info("Creating dataset card...")
401
  card_content = create_dataset_card(
402
  source_dataset=src_dataset_hub_id,
403
  model_id=model_id,
404
  messages_column=messages_column,
405
  prompt_column=prompt_column,
406
+ generation=generation,
407
  tensor_parallel_size=tensor_parallel_size,
408
  num_examples=total_examples,
409
  generation_time=generation_start_time,
 
411
  max_model_len_used=max_model_len,
412
  )
413
 
 
414
  logger.info(f"Pushing dataset to: {output_dataset_hub_id}")
415
+ dataset.push_to_hub(output_dataset_hub_id, token=hf_access_token)
416
 
 
417
  card = DatasetCard(card_content)
418
+ card.push_to_hub(output_dataset_hub_id, token=hf_access_token)
419
 
420
+ logger.info("Generation complete")
421
  logger.info(f"Dataset available at: https://huggingface.co/datasets/{output_dataset_hub_id}")
422
 
423
 
424
  if __name__ == "__main__":
425
  if len(sys.argv) > 1:
426
  parser = argparse.ArgumentParser(
427
+ description="Generate responses for dataset prompts using a local vLLM server",
428
  formatter_class=argparse.RawDescriptionHelpFormatter,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  )
430
 
431
+ parser.add_argument("src_dataset_hub_id", help="Input dataset on Hugging Face Hub (e.g., username/dataset-name)")
 
 
 
432
  parser.add_argument("output_dataset_hub_id", help="Output dataset name on Hugging Face Hub")
433
+ parser.add_argument("--model-id", type=str, default="Qwen/Qwen3-30B-A3B-Instruct-2507")
434
+ parser.add_argument("--messages-column", type=str, default="messages")
435
+ parser.add_argument("--reasoning-parser", type=str, help="vLLM reasoning parser to use for supported models")
436
+ parser.add_argument("--prompt-column", type=str, help="Column containing plain text prompts")
437
+ parser.add_argument("--output-column", type=str, default="outputs")
438
+ parser.add_argument("--max-samples", type=int, help="Maximum number of samples to process")
439
+ parser.add_argument("--temperature", type=float, default=0.7)
440
+ parser.add_argument("--top-p", type=float, default=0.8)
441
+ parser.add_argument("--top-k", type=int, default=20)
442
+ parser.add_argument("--min-p", type=float, default=0.0)
443
+ parser.add_argument("--max-tokens", type=int, default=16384)
444
+ parser.add_argument("--repetition-penalty", type=float, default=1.0)
445
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.90)
446
+ parser.add_argument("--max-model-len", type=int)
447
+ parser.add_argument("--tensor-parallel-size", type=int)
448
+ parser.add_argument("--enable-thinking", action="store_true", default=False)
449
+ parser.add_argument("--hf-token", type=str)
450
+ parser.add_argument("--skip-long-prompts", action="store_true", default=True)
451
+ parser.add_argument("--no-skip-long-prompts", dest="skip_long_prompts", action="store_false")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
 
453
  args = parser.parse_args()
454
 
 
475
  hf_token=args.hf_token,
476
  )
477
  else:
 
478
  print(f"""
479
  vLLM Response Generation Script
480
  ==============================
 
490
 
491
  Canonical script URL:
492
  {UV_SCRIPT_URL}
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  """)