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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets",
|
| 5 |
+
# "huggingface-hub[hf_transfer]",
|
| 6 |
+
# "hf-xet",
|
| 7 |
+
# "torch",
|
| 8 |
+
# "vllm",
|
| 9 |
+
# ]
|
| 10 |
+
#
|
| 11 |
+
# ///
|
| 12 |
+
"""
|
| 13 |
+
Batch generation with Google Gemma 4 + Multi-Token Prediction (MTP).
|
| 14 |
+
|
| 15 |
+
Wraps the vLLM serving recipe from https://recipes.vllm.ai/Google/gemma-4-26B-A4B-it
|
| 16 |
+
into a batch-style UV script. Defaults pin to the recipe:
|
| 17 |
+
|
| 18 |
+
- main model: google/gemma-4-26B-A4B-it (MoE, 26B with A4B activated)
|
| 19 |
+
- draft model: google/gemma-4-26B-A4B-it-assistant
|
| 20 |
+
- num_speculative_tokens: 4
|
| 21 |
+
|
| 22 |
+
MTP gives up to 3x faster decoding with zero quality degradation by using the
|
| 23 |
+
small "assistant" draft model to predict multiple tokens per step.
|
| 24 |
+
|
| 25 |
+
This script is designed for HF Jobs with the custom Day-0 image:
|
| 26 |
+
--image vllm/vllm-openai:gemma4-0505-cu129
|
| 27 |
+
The image bakes in vLLM with Gemma 4 + MTP support and CUDA 12.9.
|
| 28 |
+
|
| 29 |
+
Hardware: 1x A100/H100 (BF16). The 26B MoE model needs ~50 GB at 0.90 GPU mem util.
|
| 30 |
+
|
| 31 |
+
Pipeline (mirrors generate-responses-chunked.py):
|
| 32 |
+
load_dataset(streaming=True) -> .map(generate_fn, batched=True) -> .push_to_hub()
|
| 33 |
+
|
| 34 |
+
Example usage:
|
| 35 |
+
# HF Jobs run (the supported execution path)
|
| 36 |
+
hf jobs uv run \\
|
| 37 |
+
--flavor a100-large \\
|
| 38 |
+
--image vllm/vllm-openai:gemma4-0505-cu129 \\
|
| 39 |
+
-s HF_TOKEN \\
|
| 40 |
+
https://huggingface.co/datasets/uv-scripts/vllm/raw/main/gemma4-mtp.py \\
|
| 41 |
+
username/input-dataset \\
|
| 42 |
+
username/output-dataset \\
|
| 43 |
+
--prompt-column question \\
|
| 44 |
+
--max-tokens 1024
|
| 45 |
+
|
| 46 |
+
# A/B speedup measurement: same dataset, with and without MTP
|
| 47 |
+
... gemma4-mtp.py ... --max-samples 50 --max-tokens 512
|
| 48 |
+
... gemma4-mtp.py ... --max-samples 50 --max-tokens 512 --disable-mtp
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
import argparse
|
| 52 |
+
import logging
|
| 53 |
+
import os
|
| 54 |
+
import sys
|
| 55 |
+
from datetime import datetime
|
| 56 |
+
from typing import Optional
|
| 57 |
+
|
| 58 |
+
from datasets import Features, Value, load_dataset
|
| 59 |
+
from huggingface_hub import DatasetCard, get_token, login
|
| 60 |
+
from torch import cuda
|
| 61 |
+
from vllm import LLM, SamplingParams
|
| 62 |
+
|
| 63 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 64 |
+
|
| 65 |
+
logging.basicConfig(
|
| 66 |
+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 67 |
+
)
|
| 68 |
+
logger = logging.getLogger(__name__)
|
| 69 |
+
|
| 70 |
+
DEFAULT_MODEL_ID = "google/gemma-4-26B-A4B-it"
|
| 71 |
+
DEFAULT_DRAFT_MODEL_ID = "google/gemma-4-26B-A4B-it-assistant"
|
| 72 |
+
DEFAULT_NUM_SPEC_TOKENS = 4
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def check_gpu_availability() -> int:
|
| 76 |
+
"""Check if CUDA is available and return the number of GPUs."""
|
| 77 |
+
if not cuda.is_available():
|
| 78 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 79 |
+
logger.error(
|
| 80 |
+
"Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor."
|
| 81 |
+
)
|
| 82 |
+
sys.exit(1)
|
| 83 |
+
|
| 84 |
+
num_gpus = cuda.device_count()
|
| 85 |
+
for i in range(num_gpus):
|
| 86 |
+
gpu_name = cuda.get_device_name(i)
|
| 87 |
+
gpu_memory = cuda.get_device_properties(i).total_memory / 1024**3
|
| 88 |
+
logger.info(f"GPU {i}: {gpu_name} with {gpu_memory:.1f} GB memory")
|
| 89 |
+
|
| 90 |
+
return num_gpus
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def create_dataset_card(
|
| 94 |
+
source_dataset: str,
|
| 95 |
+
model_id: str,
|
| 96 |
+
draft_model_id: Optional[str],
|
| 97 |
+
num_speculative_tokens: int,
|
| 98 |
+
mtp_enabled: bool,
|
| 99 |
+
messages_column: str,
|
| 100 |
+
prompt_column: Optional[str],
|
| 101 |
+
sampling_params: SamplingParams,
|
| 102 |
+
tensor_parallel_size: int,
|
| 103 |
+
num_processed: int,
|
| 104 |
+
num_batches: int,
|
| 105 |
+
generation_time: str,
|
| 106 |
+
chunk_size: int,
|
| 107 |
+
split: str,
|
| 108 |
+
max_model_len_used: Optional[int] = None,
|
| 109 |
+
) -> str:
|
| 110 |
+
"""Dataset card recording MTP config alongside the usual generation metadata."""
|
| 111 |
+
mtp_section = (
|
| 112 |
+
f"""
|
| 113 |
+
### Multi-Token Prediction (MTP)
|
| 114 |
+
|
| 115 |
+
- **MTP Enabled**: yes
|
| 116 |
+
- **Draft Model**: [{draft_model_id}](https://huggingface.co/{draft_model_id})
|
| 117 |
+
- **Speculative Tokens**: {num_speculative_tokens}
|
| 118 |
+
|
| 119 |
+
MTP uses a small "assistant" draft model to predict multiple tokens per step,
|
| 120 |
+
giving up to 3x faster decoding with zero quality degradation. Recipe:
|
| 121 |
+
https://recipes.vllm.ai/Google/gemma-4-26B-A4B-it
|
| 122 |
+
"""
|
| 123 |
+
if mtp_enabled
|
| 124 |
+
else """
|
| 125 |
+
### Multi-Token Prediction (MTP)
|
| 126 |
+
|
| 127 |
+
- **MTP Enabled**: no (`--disable-mtp` was set)
|
| 128 |
+
"""
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
return f"""---
|
| 132 |
+
tags:
|
| 133 |
+
- generated
|
| 134 |
+
- vllm
|
| 135 |
+
- uv-script
|
| 136 |
+
- gemma-4
|
| 137 |
+
- multi-token-prediction
|
| 138 |
+
---
|
| 139 |
+
|
| 140 |
+
# Generated Responses Dataset (Gemma 4 + MTP)
|
| 141 |
+
|
| 142 |
+
This dataset contains generated responses for prompts from [{source_dataset}](https://huggingface.co/datasets/{source_dataset}),
|
| 143 |
+
produced with Google Gemma 4 and vLLM's Multi-Token Prediction support.
|
| 144 |
+
|
| 145 |
+
## Generation Details
|
| 146 |
+
|
| 147 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 148 |
+
- **Source Split**: `{split}`
|
| 149 |
+
- **Input Column**: `{prompt_column if prompt_column else messages_column}` ({"plain text prompts" if prompt_column else "chat messages"})
|
| 150 |
+
- **Model**: [{model_id}](https://huggingface.co/{model_id})
|
| 151 |
+
- **Rows Processed**: {num_processed:,}
|
| 152 |
+
- **Batches**: {num_batches:,} (chunk size: {chunk_size:,})
|
| 153 |
+
- **Generation Date**: {generation_time}
|
| 154 |
+
- **Script**: `gemma4-mtp.py`
|
| 155 |
+
{mtp_section}
|
| 156 |
+
### Sampling Parameters
|
| 157 |
+
|
| 158 |
+
- **Temperature**: {sampling_params.temperature}
|
| 159 |
+
- **Top P**: {sampling_params.top_p}
|
| 160 |
+
- **Top K**: {sampling_params.top_k}
|
| 161 |
+
- **Min P**: {sampling_params.min_p}
|
| 162 |
+
- **Max Tokens**: {sampling_params.max_tokens}
|
| 163 |
+
- **Repetition Penalty**: {sampling_params.repetition_penalty}
|
| 164 |
+
|
| 165 |
+
### Hardware Configuration
|
| 166 |
+
|
| 167 |
+
- **Tensor Parallel Size**: {tensor_parallel_size}
|
| 168 |
+
- **GPU Configuration**: {tensor_parallel_size} GPU(s)
|
| 169 |
+
{f"- **Max Model Length**: {max_model_len_used:,} tokens" if max_model_len_used else ""}
|
| 170 |
+
|
| 171 |
+
## Reproduce
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
hf jobs uv run \\
|
| 175 |
+
--flavor a100-large \\
|
| 176 |
+
--image vllm/vllm-openai:gemma4-0505-cu129 \\
|
| 177 |
+
-s HF_TOKEN \\
|
| 178 |
+
https://huggingface.co/datasets/uv-scripts/vllm/raw/main/gemma4-mtp.py \\
|
| 179 |
+
{source_dataset} \\
|
| 180 |
+
<output-dataset> \\
|
| 181 |
+
{"--prompt-column " + prompt_column if prompt_column else "--messages-column " + messages_column} \\
|
| 182 |
+
--split {split} \\
|
| 183 |
+
--chunk-size {chunk_size} \\
|
| 184 |
+
--temperature {sampling_params.temperature} \\
|
| 185 |
+
--top-p {sampling_params.top_p} \\
|
| 186 |
+
--max-tokens {sampling_params.max_tokens}{f" --max-model-len {max_model_len_used}" if max_model_len_used else ""}
|
| 187 |
+
```
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def main(
|
| 192 |
+
src_dataset_hub_id: str,
|
| 193 |
+
output_dataset_hub_id: str,
|
| 194 |
+
model_id: str = DEFAULT_MODEL_ID,
|
| 195 |
+
draft_model_id: str = DEFAULT_DRAFT_MODEL_ID,
|
| 196 |
+
num_speculative_tokens: int = DEFAULT_NUM_SPEC_TOKENS,
|
| 197 |
+
disable_mtp: bool = False,
|
| 198 |
+
messages_column: str = "messages",
|
| 199 |
+
prompt_column: Optional[str] = None,
|
| 200 |
+
output_column: str = "response",
|
| 201 |
+
split: str = "train",
|
| 202 |
+
chunk_size: int = 500,
|
| 203 |
+
temperature: float = 0.7,
|
| 204 |
+
top_p: float = 0.95,
|
| 205 |
+
top_k: int = -1,
|
| 206 |
+
min_p: float = 0.0,
|
| 207 |
+
max_tokens: int = 2048,
|
| 208 |
+
repetition_penalty: float = 1.0,
|
| 209 |
+
gpu_memory_utilization: float = 0.90,
|
| 210 |
+
max_model_len: int = 16384,
|
| 211 |
+
tensor_parallel_size: Optional[int] = None,
|
| 212 |
+
max_samples: Optional[int] = None,
|
| 213 |
+
hf_token: Optional[str] = None,
|
| 214 |
+
):
|
| 215 |
+
generation_start_time = datetime.now().isoformat()
|
| 216 |
+
|
| 217 |
+
num_gpus = check_gpu_availability()
|
| 218 |
+
if tensor_parallel_size is None:
|
| 219 |
+
tensor_parallel_size = num_gpus
|
| 220 |
+
logger.info(
|
| 221 |
+
f"Auto-detected {num_gpus} GPU(s), using tensor_parallel_size={tensor_parallel_size}"
|
| 222 |
+
)
|
| 223 |
+
else:
|
| 224 |
+
logger.info(f"Using specified tensor_parallel_size={tensor_parallel_size}")
|
| 225 |
+
if tensor_parallel_size > num_gpus:
|
| 226 |
+
logger.warning(
|
| 227 |
+
f"Requested {tensor_parallel_size} GPUs but only {num_gpus} available"
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") or get_token()
|
| 231 |
+
if not HF_TOKEN:
|
| 232 |
+
logger.error("No HuggingFace token found. Please provide token via:")
|
| 233 |
+
logger.error(" 1. --hf-token argument")
|
| 234 |
+
logger.error(" 2. HF_TOKEN environment variable")
|
| 235 |
+
logger.error(" 3. Run 'huggingface-cli login' or use login() in Python")
|
| 236 |
+
sys.exit(1)
|
| 237 |
+
|
| 238 |
+
logger.info("HuggingFace token found, authenticating...")
|
| 239 |
+
login(token=HF_TOKEN)
|
| 240 |
+
|
| 241 |
+
mtp_enabled = not disable_mtp
|
| 242 |
+
if mtp_enabled:
|
| 243 |
+
logger.info("=" * 60)
|
| 244 |
+
logger.info("MTP ENABLED")
|
| 245 |
+
logger.info(f" draft model: {draft_model_id}")
|
| 246 |
+
logger.info(f" speculative tokens: {num_speculative_tokens}")
|
| 247 |
+
logger.info("=" * 60)
|
| 248 |
+
else:
|
| 249 |
+
logger.info("MTP disabled (--disable-mtp). Running plain decoding for A/B baseline.")
|
| 250 |
+
|
| 251 |
+
logger.info(f"Loading model: {model_id}")
|
| 252 |
+
vllm_kwargs = {
|
| 253 |
+
"model": model_id,
|
| 254 |
+
"tensor_parallel_size": tensor_parallel_size,
|
| 255 |
+
"gpu_memory_utilization": gpu_memory_utilization,
|
| 256 |
+
"max_model_len": max_model_len,
|
| 257 |
+
}
|
| 258 |
+
if mtp_enabled:
|
| 259 |
+
vllm_kwargs["speculative_config"] = {
|
| 260 |
+
"model": draft_model_id,
|
| 261 |
+
"num_speculative_tokens": num_speculative_tokens,
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
llm = LLM(**vllm_kwargs)
|
| 265 |
+
|
| 266 |
+
sampling_params = SamplingParams(
|
| 267 |
+
temperature=temperature,
|
| 268 |
+
top_p=top_p,
|
| 269 |
+
top_k=top_k,
|
| 270 |
+
min_p=min_p,
|
| 271 |
+
max_tokens=max_tokens,
|
| 272 |
+
repetition_penalty=repetition_penalty,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
use_messages = prompt_column is None
|
| 276 |
+
input_column = messages_column if use_messages else prompt_column
|
| 277 |
+
logger.info(
|
| 278 |
+
f"Using {'messages' if use_messages else 'prompt'} column: '{input_column}'"
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
counters = {"rows": 0, "batches": 0}
|
| 282 |
+
|
| 283 |
+
def generate_responses(batch):
|
| 284 |
+
batch_num = counters["batches"] + 1
|
| 285 |
+
batch_rows = len(batch[input_column])
|
| 286 |
+
logger.info(
|
| 287 |
+
f"Processing batch {batch_num} ({batch_rows} rows, "
|
| 288 |
+
f"total so far: {counters['rows']:,})..."
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if use_messages:
|
| 292 |
+
messages_list = batch[input_column]
|
| 293 |
+
else:
|
| 294 |
+
messages_list = [
|
| 295 |
+
[{"role": "user", "content": p}] for p in batch[input_column]
|
| 296 |
+
]
|
| 297 |
+
|
| 298 |
+
try:
|
| 299 |
+
outputs = llm.chat(messages=messages_list, sampling_params=sampling_params)
|
| 300 |
+
batch[output_column] = [o.outputs[0].text.strip() for o in outputs]
|
| 301 |
+
except Exception:
|
| 302 |
+
logger.exception(f"Error in batch {batch_num}, filling with empty strings")
|
| 303 |
+
batch[output_column] = [""] * batch_rows
|
| 304 |
+
|
| 305 |
+
counters["rows"] += batch_rows
|
| 306 |
+
counters["batches"] += 1
|
| 307 |
+
logger.info(
|
| 308 |
+
f"Batch {batch_num} complete. Total rows processed: {counters['rows']:,}"
|
| 309 |
+
)
|
| 310 |
+
return batch
|
| 311 |
+
|
| 312 |
+
logger.info(
|
| 313 |
+
f"Loading dataset: {src_dataset_hub_id} (split={split}, streaming=True)"
|
| 314 |
+
)
|
| 315 |
+
ds = load_dataset(src_dataset_hub_id, split=split, streaming=True)
|
| 316 |
+
|
| 317 |
+
# Resolve features upfront — .take()/.map() can drop them, and
|
| 318 |
+
# IterableDataset.push_to_hub() crashes on .features=None.
|
| 319 |
+
ds_info = load_dataset(src_dataset_hub_id, split=split, streaming=True)
|
| 320 |
+
source_features = ds_info.features
|
| 321 |
+
if source_features is None:
|
| 322 |
+
logger.info("Features not available, peeking at first row to infer schema...")
|
| 323 |
+
first = next(iter(ds_info))
|
| 324 |
+
source_features = Features({k: Value("string") for k in first.keys()})
|
| 325 |
+
output_features = Features({**source_features, output_column: Value("string")})
|
| 326 |
+
logger.info(f"Dataset features: {list(output_features.keys())}")
|
| 327 |
+
|
| 328 |
+
if max_samples is not None:
|
| 329 |
+
logger.info(f"Limiting to {max_samples} samples")
|
| 330 |
+
ds = ds.take(max_samples)
|
| 331 |
+
|
| 332 |
+
logger.info(f"Setting up streaming pipeline (chunk_size={chunk_size})...")
|
| 333 |
+
ds = ds.map(generate_responses, batched=True, batch_size=chunk_size)
|
| 334 |
+
ds = ds.cast(output_features)
|
| 335 |
+
|
| 336 |
+
logger.info(f"Starting push_to_hub to: {output_dataset_hub_id}")
|
| 337 |
+
ds.push_to_hub(output_dataset_hub_id, token=HF_TOKEN)
|
| 338 |
+
|
| 339 |
+
logger.info(
|
| 340 |
+
f"Push complete! Processed {counters['rows']:,} rows in {counters['batches']} batches."
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
logger.info("Creating and pushing dataset card...")
|
| 344 |
+
card_content = create_dataset_card(
|
| 345 |
+
source_dataset=src_dataset_hub_id,
|
| 346 |
+
model_id=model_id,
|
| 347 |
+
draft_model_id=draft_model_id if mtp_enabled else None,
|
| 348 |
+
num_speculative_tokens=num_speculative_tokens,
|
| 349 |
+
mtp_enabled=mtp_enabled,
|
| 350 |
+
messages_column=messages_column,
|
| 351 |
+
prompt_column=prompt_column,
|
| 352 |
+
sampling_params=sampling_params,
|
| 353 |
+
tensor_parallel_size=tensor_parallel_size,
|
| 354 |
+
num_processed=counters["rows"],
|
| 355 |
+
num_batches=counters["batches"],
|
| 356 |
+
generation_time=generation_start_time,
|
| 357 |
+
chunk_size=chunk_size,
|
| 358 |
+
split=split,
|
| 359 |
+
max_model_len_used=max_model_len,
|
| 360 |
+
)
|
| 361 |
+
card = DatasetCard(card_content)
|
| 362 |
+
card.push_to_hub(output_dataset_hub_id, token=HF_TOKEN)
|
| 363 |
+
|
| 364 |
+
logger.info("Done!")
|
| 365 |
+
logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset_hub_id}")
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
if __name__ == "__main__":
|
| 369 |
+
if len(sys.argv) > 1:
|
| 370 |
+
parser = argparse.ArgumentParser(
|
| 371 |
+
description="Batch generation with Gemma 4 + Multi-Token Prediction via vLLM",
|
| 372 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 373 |
+
epilog="""
|
| 374 |
+
Examples:
|
| 375 |
+
# Default: Gemma 4 26B-A4B with MTP enabled
|
| 376 |
+
uv run gemma4-mtp.py input-dataset output-dataset --prompt-column question
|
| 377 |
+
|
| 378 |
+
# Quick test with 5 samples
|
| 379 |
+
uv run gemma4-mtp.py input-dataset output-dataset \\
|
| 380 |
+
--prompt-column question --max-samples 5 --chunk-size 2 --max-tokens 64
|
| 381 |
+
|
| 382 |
+
# A/B baseline: same run without MTP
|
| 383 |
+
uv run gemma4-mtp.py input-dataset output-dataset \\
|
| 384 |
+
--prompt-column question --max-samples 50 --disable-mtp
|
| 385 |
+
|
| 386 |
+
# HF Jobs (the supported path)
|
| 387 |
+
hf jobs uv run \\
|
| 388 |
+
--flavor a100-large \\
|
| 389 |
+
--image vllm/vllm-openai:gemma4-0505-cu129 \\
|
| 390 |
+
-s HF_TOKEN \\
|
| 391 |
+
https://huggingface.co/datasets/uv-scripts/vllm/raw/main/gemma4-mtp.py \\
|
| 392 |
+
input-dataset output-dataset --prompt-column question
|
| 393 |
+
""",
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
parser.add_argument(
|
| 397 |
+
"src_dataset_hub_id",
|
| 398 |
+
help="Input dataset on Hugging Face Hub (e.g., username/dataset-name)",
|
| 399 |
+
)
|
| 400 |
+
parser.add_argument(
|
| 401 |
+
"output_dataset_hub_id",
|
| 402 |
+
help="Output dataset name on Hugging Face Hub",
|
| 403 |
+
)
|
| 404 |
+
parser.add_argument(
|
| 405 |
+
"--model-id",
|
| 406 |
+
type=str,
|
| 407 |
+
default=DEFAULT_MODEL_ID,
|
| 408 |
+
help=f"Main model (default: {DEFAULT_MODEL_ID})",
|
| 409 |
+
)
|
| 410 |
+
parser.add_argument(
|
| 411 |
+
"--draft-model-id",
|
| 412 |
+
type=str,
|
| 413 |
+
default=DEFAULT_DRAFT_MODEL_ID,
|
| 414 |
+
help=f"MTP draft / assistant model (default: {DEFAULT_DRAFT_MODEL_ID})",
|
| 415 |
+
)
|
| 416 |
+
parser.add_argument(
|
| 417 |
+
"--num-speculative-tokens",
|
| 418 |
+
type=int,
|
| 419 |
+
default=DEFAULT_NUM_SPEC_TOKENS,
|
| 420 |
+
help=f"Tokens proposed per draft step (default: {DEFAULT_NUM_SPEC_TOKENS})",
|
| 421 |
+
)
|
| 422 |
+
parser.add_argument(
|
| 423 |
+
"--disable-mtp",
|
| 424 |
+
action="store_true",
|
| 425 |
+
help="Run without speculative decoding (for A/B speedup measurement)",
|
| 426 |
+
)
|
| 427 |
+
parser.add_argument(
|
| 428 |
+
"--messages-column",
|
| 429 |
+
type=str,
|
| 430 |
+
default="messages",
|
| 431 |
+
help="Column containing chat messages (default: messages)",
|
| 432 |
+
)
|
| 433 |
+
parser.add_argument(
|
| 434 |
+
"--prompt-column",
|
| 435 |
+
type=str,
|
| 436 |
+
help="Column containing plain text prompts (alternative to --messages-column)",
|
| 437 |
+
)
|
| 438 |
+
parser.add_argument(
|
| 439 |
+
"--output-column",
|
| 440 |
+
type=str,
|
| 441 |
+
default="response",
|
| 442 |
+
help="Column name for generated responses (default: response)",
|
| 443 |
+
)
|
| 444 |
+
parser.add_argument(
|
| 445 |
+
"--split",
|
| 446 |
+
type=str,
|
| 447 |
+
default="train",
|
| 448 |
+
help="Dataset split to process (default: train)",
|
| 449 |
+
)
|
| 450 |
+
parser.add_argument(
|
| 451 |
+
"--chunk-size",
|
| 452 |
+
type=int,
|
| 453 |
+
default=500,
|
| 454 |
+
help="Batch size for map() — prompts per llm.chat() call (default: 500)",
|
| 455 |
+
)
|
| 456 |
+
parser.add_argument(
|
| 457 |
+
"--max-samples",
|
| 458 |
+
type=int,
|
| 459 |
+
help="Maximum number of samples to process (default: all)",
|
| 460 |
+
)
|
| 461 |
+
parser.add_argument(
|
| 462 |
+
"--temperature",
|
| 463 |
+
type=float,
|
| 464 |
+
default=0.7,
|
| 465 |
+
help="Sampling temperature (default: 0.7)",
|
| 466 |
+
)
|
| 467 |
+
parser.add_argument(
|
| 468 |
+
"--top-p",
|
| 469 |
+
type=float,
|
| 470 |
+
default=0.95,
|
| 471 |
+
help="Top-p sampling parameter (default: 0.95)",
|
| 472 |
+
)
|
| 473 |
+
parser.add_argument(
|
| 474 |
+
"--top-k",
|
| 475 |
+
type=int,
|
| 476 |
+
default=-1,
|
| 477 |
+
help="Top-k sampling parameter (default: -1, disabled)",
|
| 478 |
+
)
|
| 479 |
+
parser.add_argument(
|
| 480 |
+
"--min-p",
|
| 481 |
+
type=float,
|
| 482 |
+
default=0.0,
|
| 483 |
+
help="Minimum probability threshold (default: 0.0)",
|
| 484 |
+
)
|
| 485 |
+
parser.add_argument(
|
| 486 |
+
"--max-tokens",
|
| 487 |
+
type=int,
|
| 488 |
+
default=2048,
|
| 489 |
+
help="Maximum tokens to generate (default: 2048)",
|
| 490 |
+
)
|
| 491 |
+
parser.add_argument(
|
| 492 |
+
"--repetition-penalty",
|
| 493 |
+
type=float,
|
| 494 |
+
default=1.0,
|
| 495 |
+
help="Repetition penalty (default: 1.0)",
|
| 496 |
+
)
|
| 497 |
+
parser.add_argument(
|
| 498 |
+
"--gpu-memory-utilization",
|
| 499 |
+
type=float,
|
| 500 |
+
default=0.90,
|
| 501 |
+
help="GPU memory utilization factor (default: 0.90)",
|
| 502 |
+
)
|
| 503 |
+
parser.add_argument(
|
| 504 |
+
"--max-model-len",
|
| 505 |
+
type=int,
|
| 506 |
+
default=16384,
|
| 507 |
+
help="Maximum model context length (default: 16384). Recipe default is 32768.",
|
| 508 |
+
)
|
| 509 |
+
parser.add_argument(
|
| 510 |
+
"--tensor-parallel-size",
|
| 511 |
+
type=int,
|
| 512 |
+
help="Number of GPUs to use (default: auto-detect)",
|
| 513 |
+
)
|
| 514 |
+
parser.add_argument(
|
| 515 |
+
"--hf-token",
|
| 516 |
+
type=str,
|
| 517 |
+
help="Hugging Face token (can also use HF_TOKEN env var)",
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
args = parser.parse_args()
|
| 521 |
+
|
| 522 |
+
main(
|
| 523 |
+
src_dataset_hub_id=args.src_dataset_hub_id,
|
| 524 |
+
output_dataset_hub_id=args.output_dataset_hub_id,
|
| 525 |
+
model_id=args.model_id,
|
| 526 |
+
draft_model_id=args.draft_model_id,
|
| 527 |
+
num_speculative_tokens=args.num_speculative_tokens,
|
| 528 |
+
disable_mtp=args.disable_mtp,
|
| 529 |
+
messages_column=args.messages_column,
|
| 530 |
+
prompt_column=args.prompt_column,
|
| 531 |
+
output_column=args.output_column,
|
| 532 |
+
split=args.split,
|
| 533 |
+
chunk_size=args.chunk_size,
|
| 534 |
+
temperature=args.temperature,
|
| 535 |
+
top_p=args.top_p,
|
| 536 |
+
top_k=args.top_k,
|
| 537 |
+
min_p=args.min_p,
|
| 538 |
+
max_tokens=args.max_tokens,
|
| 539 |
+
repetition_penalty=args.repetition_penalty,
|
| 540 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 541 |
+
max_model_len=args.max_model_len,
|
| 542 |
+
tensor_parallel_size=args.tensor_parallel_size,
|
| 543 |
+
max_samples=args.max_samples,
|
| 544 |
+
hf_token=args.hf_token,
|
| 545 |
+
)
|
| 546 |
+
else:
|
| 547 |
+
print("""
|
| 548 |
+
vLLM Gemma 4 + Multi-Token Prediction (MTP) Batch Generation
|
| 549 |
+
============================================================
|
| 550 |
+
|
| 551 |
+
Runs Google Gemma 4 26B-A4B with the official MTP "assistant" draft model
|
| 552 |
+
for up to 3x faster decoding. Defaults pin to the recipe at
|
| 553 |
+
https://recipes.vllm.ai/Google/gemma-4-26B-A4B-it.
|
| 554 |
+
|
| 555 |
+
Designed for HF Jobs with the custom Day-0 image:
|
| 556 |
+
--image vllm/vllm-openai:gemma4-0505-cu129
|
| 557 |
+
|
| 558 |
+
For usage information:
|
| 559 |
+
uv run gemma4-mtp.py --help
|
| 560 |
+
|
| 561 |
+
Example HF Jobs command:
|
| 562 |
+
hf jobs uv run \\
|
| 563 |
+
--flavor a100-large \\
|
| 564 |
+
--image vllm/vllm-openai:gemma4-0505-cu129 \\
|
| 565 |
+
-s HF_TOKEN \\
|
| 566 |
+
https://huggingface.co/datasets/uv-scripts/vllm/raw/main/gemma4-mtp.py \\
|
| 567 |
+
username/input-dataset \\
|
| 568 |
+
username/output-dataset \\
|
| 569 |
+
--prompt-column question \\
|
| 570 |
+
--max-tokens 1024
|
| 571 |
+
""")
|