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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "datasets",
#     "huggingface-hub[hf_transfer]",
#     "torch",
#     "transformers>=4.45.0",
#     "tqdm",
#     "accelerate",
# ]
# ///
"""
Generate responses with transparent reasoning using OpenAI's open source GPT OSS models.

This implementation uses standard Transformers library for maximum compatibility.
The models output structured reasoning in separate channels, allowing you to
capture both the thinking process and final response.

Example usage:
    # 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 with custom settings
    uv run gpt_oss_transformers.py \\
        --input-dataset username/prompts \\
        --output-dataset username/responses-with-reasoning \\
        --prompt-column prompt \\
        --reasoning-level high \\
        --max-samples 100
    
    # HF Jobs execution
    hf jobs uv run --flavor a10g-small \\
        https://huggingface.co/datasets/uv-scripts/openai-oss/raw/main/gpt_oss_transformers.py \\
        --input-dataset username/prompts \\
        --output-dataset username/responses-with-reasoning
"""

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.

    Expected format:
    <|start|>assistant<|channel|>analysis<|message|>CHAIN_OF_THOUGHT<|end|>
    <|start|>assistant<|channel|>final<|message|>ACTUAL_MESSAGE
    """
    think = ""
    content = ""

    # Extract analysis channel (chain of thought)
    analysis_pattern = (
        r"<\|start\|>assistant<\|channel\|>analysis<\|message\|>(.*?)<\|end\|>"
    )
    analysis_match = re.search(analysis_pattern, raw_output, re.DOTALL)
    if analysis_match:
        think = analysis_match.group(1).strip()

    # Extract final channel (user-facing content)
    final_pattern = (
        r"<\|start\|>assistant<\|channel\|>final<\|message\|>(.*?)(?:<\|end\|>|$)"
    )
    final_match = re.search(final_pattern, raw_output, re.DOTALL)
    if final_match:
        content = final_match[1].strip()

    # If no channels found, treat entire output as content
    if not think and not content:
        content = raw_output.strip()

    return {"think": think, "content": content, "raw_output": raw_output}


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
    logger.info(f"Loading tokenizer: {model_id}")
    tokenizer = AutoTokenizer.from_pretrained(
        model_id, padding_side="left" if "120b" in model_id else "right"
    )

    # Add padding token if needed
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    # Model loading configuration
    device_map = {"tp_plan": "auto"} if "120b" in model_id else "auto"

    # Load model
    logger.info(f"Loading model: {model_id}")
    logger.info("This may take a few minutes for large models...")

    try:
        model = AutoModelForCausalLM.from_pretrained(
            model_id,
            torch_dtype=torch.bfloat16,
            **device_map,
        )
        model.eval()
    except Exception as e:
        logger.error(f"Failed to load model: {e}")
        logger.error("Trying with default configuration...")
        # Fallback to simpler loading
        model = AutoModelForCausalLM.from_pretrained(
            model_id,
            torch_dtype="auto",
            device_map="auto",
        )
        model.eval()

    # 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 = []

    for example in tqdm(dataset, desc="Preparing prompts"):
        prompt_text = example[prompt_column]
        original_prompts.append(prompt_text)

        # Create message format (using user role only as per documentation)
        messages = [{"role": "user", "content": prompt_text}]

        # Apply chat template with reasoning effort
        try:
            prompt = tokenizer.apply_chat_template(
                messages,
                reasoning_effort=reasoning_level,
                add_generation_prompt=True,
                tokenize=False,
            )
        except TypeError:
            # Fallback if reasoning_effort parameter not supported
            logger.warning(
                "reasoning_effort parameter not supported, using standard 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
        """)