File size: 19,877 Bytes
bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 90312a8 61f5a7b 90312a8 bbe5ce0 89351df 90312a8 89351df bbe5ce0 89351df bbe5ce0 89351df 90312a8 bbe5ce0 89351df 90312a8 89351df 90312a8 bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 89351df bbe5ce0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "datasets",
# "huggingface-hub[hf_transfer]",
# "hf-xet >= 1.1.7",
# "torch",
# "transformers>=4.55.0",
# "tqdm",
# "accelerate",
# ]
# ///
"""
Generate responses with transparent reasoning using OpenAI's GPT OSS models.
This implementation works on regular GPUs (L4, A100, A10G, T4) without requiring H100s.
The models automatically dequantize MXFP4 to bf16 when needed, making them accessible
on standard datacenter hardware.
Key features:
- Works on regular GPUs without special hardware
- Extracts reasoning from analysis/commentary channels
- Handles the simplified channel output format
- No Flash Attention 3 or special kernels needed
Example usage:
# Quick test with a single prompt
uv run gpt_oss_transformers.py --prompt "Write a haiku about mountains"
# Generate haiku with reasoning
uv run gpt_oss_transformers.py \\
--input-dataset davanstrien/haiku_dpo \\
--output-dataset username/haiku-reasoning \\
--prompt-column question
# HF Jobs execution (A10G for $1.50/hr)
hf jobs uv run --flavor a10g-small \\
https://huggingface.co/datasets/uv-scripts/openai-oss/raw/main/gpt_oss_transformers.py \\
--input-dataset davanstrien/haiku_dpo \\
--output-dataset username/haiku-reasoning \\
--prompt-column question
"""
import argparse
import logging
import os
import re
import sys
from datetime import datetime
from typing import Dict, List, Optional
import torch
from datasets import Dataset, load_dataset
from huggingface_hub import DatasetCard, get_token, login
from tqdm.auto import tqdm
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
GenerationConfig,
set_seed,
)
# Enable HF Transfer for faster downloads
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def check_gpu_availability() -> int:
"""Check if CUDA is available and return the number of GPUs."""
if not torch.cuda.is_available():
logger.error("CUDA is not available. This script requires a GPU.")
logger.error(
"Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor."
)
sys.exit(1)
num_gpus = torch.cuda.device_count()
for i in range(num_gpus):
gpu_name = torch.cuda.get_device_name(i)
gpu_memory = torch.cuda.get_device_properties(i).total_memory / 1024**3
logger.info(f"GPU {i}: {gpu_name} with {gpu_memory:.1f} GB memory")
return num_gpus
def parse_channels(raw_output: str) -> Dict[str, str]:
"""
Extract think/content from GPT OSS channel-based output.
The actual output format is simpler than expected:
analysisREASONING_TEXTassistantfinalRESPONSE_TEXT
Sometimes includes commentary channel:
commentaryMETA_TEXTanalysisREASONING_TEXTassistantfinalRESPONSE_TEXT
"""
result = {"think": "", "content": "", "raw_output": raw_output}
# Clean up the text - remove system prompt if present
if "user" in raw_output:
# Take everything after the last user prompt
parts = raw_output.split("user")
if len(parts) > 1:
text = parts[-1]
# Find where the assistant response starts
for marker in ["analysis", "commentary", "assistant"]:
if marker in text:
idx = text.find(marker)
if idx > 0:
text = text[idx:]
raw_output = text
break
else:
text = raw_output
# Extract reasoning (analysis and/or commentary)
reasoning_parts = []
# Try to extract analysis
if "analysis" in text:
match = re.search(
r"analysis(.*?)(?:commentary|assistantfinal|final|$)", text, re.DOTALL
)
if match:
reasoning_parts.append(("Analysis", match.group(1).strip()))
# Try to extract commentary
if "commentary" in text:
match = re.search(
r"commentary(.*?)(?:analysis|assistantfinal|final|$)", text, re.DOTALL
)
if match:
reasoning_parts.append(("Commentary", match.group(1).strip()))
# Combine reasoning
if reasoning_parts:
result["think"] = "\n\n".join(
f"[{label}] {content}" for label, content in reasoning_parts
)
# Extract final response
if "assistantfinal" in text:
parts = text.split("assistantfinal")
if len(parts) > 1:
result["content"] = parts[-1].strip()
elif "final" in text:
# Fallback - look for "final" keyword
parts = text.split("final")
if len(parts) > 1:
result["content"] = parts[-1].strip()
# Clean up any remaining tokens
for key in ["think", "content"]:
result[key] = result[key].replace("<|end|>", "").replace("<|return|>", "")
result[key] = (
result[key].replace("<|message|>", "").replace("assistant", "").strip()
)
# If no channels found, treat entire output as content
if not result["think"] and not result["content"]:
result["content"] = raw_output.strip()
return result
def create_dataset_card(
input_dataset: str,
model_id: str,
prompt_column: str,
reasoning_level: str,
num_examples: int,
generation_time: str,
num_gpus: int,
temperature: float,
max_tokens: int,
) -> str:
"""Create a dataset card documenting the generation process."""
return f"""---
tags:
- generated
- synthetic
- reasoning
- openai-gpt-oss
---
# Generated Responses with Reasoning (Transformers)
This dataset contains AI-generated responses with transparent chain-of-thought reasoning using OpenAI GPT OSS models via Transformers.
## Generation Details
- **Source Dataset**: [{input_dataset}](https://huggingface.co/datasets/{input_dataset})
- **Model**: [{model_id}](https://huggingface.co/{model_id})
- **Reasoning Level**: {reasoning_level}
- **Number of Examples**: {num_examples:,}
- **Generation Date**: {generation_time}
- **Implementation**: Transformers (fallback)
- **GPUs Used**: {num_gpus}
## Dataset Structure
Each example contains:
- `prompt`: The input prompt from the source dataset
- `think`: The model's internal reasoning process
- `content`: The final response
- `raw_output`: Complete model output with channel markers
- `reasoning_level`: The reasoning effort level used
- `model`: Model identifier
## Generation Script
Generated using [uv-scripts/openai-oss](https://huggingface.co/datasets/uv-scripts/openai-oss).
To reproduce:
```bash
uv run gpt_oss_transformers.py \\
--input-dataset {input_dataset} \\
--output-dataset <your-dataset> \\
--prompt-column {prompt_column} \\
--model-id {model_id} \\
--reasoning-level {reasoning_level}
```
"""
def main(
input_dataset: str,
output_dataset_hub_id: str,
prompt_column: str = "prompt",
model_id: str = "openai/gpt-oss-20b",
reasoning_level: str = "high",
max_samples: Optional[int] = None,
temperature: float = 0.7,
max_tokens: int = 512,
batch_size: int = 1,
seed: int = 42,
hf_token: Optional[str] = None,
):
"""
Main generation pipeline using Transformers.
Args:
input_dataset: Source dataset on Hugging Face Hub
output_dataset_hub_id: Where to save results on Hugging Face Hub
prompt_column: Column containing the prompts
model_id: OpenAI GPT OSS model to use
reasoning_level: Reasoning effort level (high/medium/low)
max_samples: Maximum number of samples to process
temperature: Sampling temperature
max_tokens: Maximum tokens to generate
batch_size: Batch size for generation
seed: Random seed for reproducibility
hf_token: Hugging Face authentication token
"""
generation_start_time = datetime.now().isoformat()
set_seed(seed)
# GPU check
num_gpus = check_gpu_availability()
# Authentication
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") or get_token()
if not HF_TOKEN:
logger.error("No HuggingFace token found. Please provide token via:")
logger.error(" 1. --hf-token argument")
logger.error(" 2. HF_TOKEN environment variable")
logger.error(" 3. Run 'huggingface-cli login'")
sys.exit(1)
logger.info("HuggingFace token found, authenticating...")
login(token=HF_TOKEN)
# Load tokenizer (always use padding_side="left" for generation)
logger.info(f"Loading tokenizer: {model_id}")
tokenizer = AutoTokenizer.from_pretrained(
model_id,
padding_side="left", # Always use left padding for generation
)
# Add padding token if needed
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# Model loading configuration based on OpenAI cookbook
# For 20B model, standard auto device map works
# For 120B model, use tensor parallel planning
if "120b" in model_id:
model_kwargs = {
"tp_plan": "auto",
"enable_expert_parallel": True,
}
else:
model_kwargs = {
"device_map": "auto",
}
# Load model
logger.info(f"Loading model: {model_id}")
logger.info("Using standard configuration (no Flash Attention 3 needed)")
# Note about MXFP4
logger.info("Note: MXFP4 will auto-dequantize to bf16 on non-Hopper GPUs")
# Check available GPU memory
if num_gpus > 0:
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
if gpu_memory < 40 and "20b" in model_id.lower():
logger.info(
f"GPU has {gpu_memory:.1f}GB. 20B model needs ~40GB when dequantized"
)
logger.info("Model will still load but may use CPU offloading if needed")
try:
# Load with standard configuration (no Flash Attention 3)
# This works on L4, A100, A10G, T4 GPUs
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16, # Can also use "auto"
# DO NOT USE: attn_implementation="kernels-community/vllm-flash-attn3"
**model_kwargs,
)
model.eval()
logger.info("Successfully loaded model")
# Report memory usage
if torch.cuda.is_available():
memory_gb = torch.cuda.memory_allocated() / 1024**3
logger.info(f"GPU memory used: {memory_gb:.1f}GB")
except torch.cuda.OutOfMemoryError as e:
logger.error(f"Out of memory error: {e}")
logger.error("\nMemory requirements:")
logger.error("- 20B model: ~40GB VRAM (use A100-40GB or 2xL4)")
logger.error("- 120B model: ~240GB VRAM (use 4xA100-80GB)")
logger.error("\nFor HF Jobs, try:")
logger.error("- 20B: --flavor a10g-large or a100-large")
logger.error("- 120B: --flavor 4xa100")
sys.exit(1)
except Exception as e:
logger.error(f"Error loading model: {e}")
sys.exit(1)
# Generation configuration
generation_config = GenerationConfig(
max_new_tokens=max_tokens,
temperature=temperature,
do_sample=temperature > 0,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.pad_token_id,
)
# Load dataset
logger.info(f"Loading dataset: {input_dataset}")
dataset = load_dataset(input_dataset, split="train")
# Validate prompt column
if prompt_column not in dataset.column_names:
logger.error(
f"Column '{prompt_column}' not found. Available columns: {dataset.column_names}"
)
sys.exit(1)
# Limit samples if requested
if max_samples:
dataset = dataset.select(range(min(max_samples, len(dataset))))
total_examples = len(dataset)
logger.info(f"Processing {total_examples:,} examples")
# Prepare prompts with reasoning control
logger.info(f"Applying chat template with reasoning_level={reasoning_level}...")
prompts = []
original_prompts = []
# Get current date for system prompt
from datetime import datetime
current_date = datetime.now().strftime("%Y-%m-%d")
for example in tqdm(dataset, desc="Preparing prompts"):
prompt_text = example[prompt_column]
original_prompts.append(prompt_text)
# Create messages with reasoning level in system prompt
messages = [
{
"role": "system",
"content": f"""You are ChatGPT, a large language model trained by OpenAI.
Knowledge cutoff: 2024-06
Current date: {current_date}
Reasoning: {reasoning_level}
# Valid channels: analysis, commentary, final. Channel must be included for every message.""",
},
{"role": "user", "content": prompt_text},
]
# Apply chat template
prompt = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=False,
)
prompts.append(prompt)
# Generate responses in batches
logger.info(f"Starting generation for {len(prompts):,} prompts...")
results = []
for i in tqdm(range(0, len(prompts), batch_size), desc="Generating"):
batch_prompts = prompts[i : i + batch_size]
batch_original = original_prompts[i : i + batch_size]
# Tokenize batch
inputs = tokenizer(
batch_prompts, return_tensors="pt", padding=True, truncation=True
).to(model.device)
# Generate
with torch.no_grad():
outputs = model.generate(**inputs, generation_config=generation_config)
# Decode and parse
for j, output in enumerate(outputs):
# Decode without input prompt
output_ids = output[inputs.input_ids.shape[1] :]
raw_output = tokenizer.decode(output_ids, skip_special_tokens=False)
parsed = parse_channels(raw_output)
result = {
"prompt": batch_original[j],
"think": parsed["think"],
"content": parsed["content"],
"raw_output": parsed["raw_output"],
"reasoning_level": reasoning_level,
"model": model_id,
}
results.append(result)
# Create dataset
logger.info("Creating output dataset...")
output_dataset = Dataset.from_list(results)
# Create dataset card
logger.info("Creating dataset card...")
card_content = create_dataset_card(
input_dataset=input_dataset,
model_id=model_id,
prompt_column=prompt_column,
reasoning_level=reasoning_level,
num_examples=total_examples,
generation_time=generation_start_time,
num_gpus=num_gpus,
temperature=temperature,
max_tokens=max_tokens,
)
# Push to hub
logger.info(f"Pushing dataset to: {output_dataset_hub_id}")
output_dataset.push_to_hub(output_dataset_hub_id, token=HF_TOKEN)
# Push dataset card
card = DatasetCard(card_content)
card.push_to_hub(output_dataset_hub_id, token=HF_TOKEN)
logger.info("✅ Generation complete!")
logger.info(
f"Dataset available at: https://huggingface.co/datasets/{output_dataset_hub_id}"
)
if __name__ == "__main__":
if len(sys.argv) > 1:
parser = argparse.ArgumentParser(
description="Generate responses with reasoning using OpenAI GPT OSS models (Transformers)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Generate haiku with reasoning
uv run gpt_oss_transformers.py \\
--input-dataset davanstrien/haiku_dpo \\
--output-dataset username/haiku-reasoning \\
--prompt-column question
# Any prompt dataset
uv run gpt_oss_transformers.py \\
--input-dataset username/prompts \\
--output-dataset username/responses-reasoning \\
--reasoning-level high \\
--max-samples 100
# Use larger 120B model (requires 80GB+ GPU)
uv run gpt_oss_transformers.py \\
--input-dataset username/prompts \\
--output-dataset username/responses-reasoning \\
--model-id openai/gpt-oss-120b
""",
)
parser.add_argument(
"--input-dataset",
type=str,
required=True,
help="Input dataset on Hugging Face Hub",
)
parser.add_argument(
"--output-dataset",
type=str,
required=True,
help="Output dataset name on Hugging Face Hub",
)
parser.add_argument(
"--prompt-column",
type=str,
default="prompt",
help="Column containing prompts (default: prompt)",
)
parser.add_argument(
"--model-id",
type=str,
default="openai/gpt-oss-20b",
help="Model to use (default: openai/gpt-oss-20b)",
)
parser.add_argument(
"--reasoning-level",
type=str,
choices=["high", "medium", "low"],
default="high",
help="Reasoning effort level (default: high)",
)
parser.add_argument(
"--max-samples", type=int, help="Maximum number of samples to process"
)
parser.add_argument(
"--temperature",
type=float,
default=0.7,
help="Sampling temperature (default: 0.7)",
)
parser.add_argument(
"--max-tokens",
type=int,
default=512,
help="Maximum tokens to generate (default: 512)",
)
parser.add_argument(
"--batch-size",
type=int,
default=1,
help="Batch size for generation (default: 1)",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Random seed (default: 42)",
)
parser.add_argument(
"--hf-token",
type=str,
help="Hugging Face token (can also use HF_TOKEN env var)",
)
args = parser.parse_args()
main(
input_dataset=args.input_dataset,
output_dataset_hub_id=args.output_dataset,
prompt_column=args.prompt_column,
model_id=args.model_id,
reasoning_level=args.reasoning_level,
max_samples=args.max_samples,
temperature=args.temperature,
max_tokens=args.max_tokens,
batch_size=args.batch_size,
seed=args.seed,
hf_token=args.hf_token,
)
else:
# Show HF Jobs example when run without arguments
print("""
OpenAI GPT OSS Reasoning Generation Script (Transformers)
========================================================
This script requires arguments. For usage information:
uv run gpt_oss_transformers.py --help
Example HF Jobs command for 20B model:
hf jobs uv run \\
--flavor a10g-small \\
https://huggingface.co/datasets/uv-scripts/openai-oss/raw/main/gpt_oss_transformers.py \\
--input-dataset davanstrien/haiku_dpo \\
--output-dataset username/haiku-reasoning \\
--prompt-column question \\
--reasoning-level high
Example HF Jobs command for 120B model:
hf jobs uv run \\
--flavor a100-large \\
https://huggingface.co/datasets/uv-scripts/openai-oss/raw/main/gpt_oss_transformers.py \\
--input-dataset username/prompts \\
--output-dataset username/responses-reasoning \\
--model-id openai/gpt-oss-120b \\
--reasoning-level high
""")
|