Repository navigation
Description
rope_scaling parameter not passed to vLLM when using fast_inference=True, causing CUDA errors with long contexts
Environment Information
- Unsloth version: 2025.8.1
- vLLM version: 0.9.2
- Platform: Cloud (RunPod)
- GPUs: I used A100 and H100 but I guess it's not specific to these GPUs
- Trainer:
GRPOTrainer
Problem Description
When fine-tuning Qwen 2.5 7B with GRPOTrainer using contexts longer than 32,768 tokens, the training fails with CUDA errors. The issue occurs because the rope_scaling parameter is not being passed to vLLM when fast_inference=True is enabled in FastLanguageModel.from_pretrained().
According to the Qwen documentation, for contexts longer than 32,768 tokens, the following rope scaling configuration is required:
{
"rope_type": "yarn",
"factor": 4.0,
"original_max_position_embeddings": 32768
}Root Cause
The rope_scaling parameter is not included in the allowed_args or load_vllm_kwargs parameters in the FastLlamaModel.from_pretrained method (specifically around line 2021 in llama.py). This prevents the rope scaling configuration from being passed to the underlying vLLM engine, causing Flash Attention 2 to use the default 32,768 context length limit.
Error Details
The training fails with the following CUDA assertion error:
unknown:0: unknown: block: [122794,0,0], thread: [64,0,0] Assertion `index out of bounds: 0 <= tl.broadcast_to(tmp10, [XBLOCK]) < 32768` failed.
...
RuntimeError: CUDA error: device-side assert triggered
The key error message shows that Flash Attention 2 is enforcing the 32,768 token limit: index out of bounds: 0 <= tl.broadcast_to(tmp10, [XBLOCK]) < 32768.
Expected Behavior
The rope_scaling parameter should be properly passed to vLLM when fast_inference=True, allowing models to handle contexts longer than their default maximum position embeddings.
Reproduction
Minimal vLLM Example
When using vLLM directly, the rope_scaling parameter works correctly and allows processing of long contexts:
from vllm import LLM
llm = LLM(
model="unsloth/Qwen2.5-7B-Instruct",
gpu_memory_utilization=0.95,
max_model_len=131072,
quantization=None,
load_format="auto",
kv_cache_dtype="auto",
dtype=torch.bfloat16,
max_num_batched_tokens=131072,
max_num_seqs=256,
rope_scaling={
"rope_type": "yarn",
"factor": 4.0,
"original_max_position_embeddings": 32768,
},
)
# With this configuration, vLLM can successfully process prompts longer than 32768 tokens
# without triggering the Flash Attention 2 assertion errorsThe key difference is that when calling vLLM directly, we can explicitly pass the rope_scaling parameter, which configures the underlying Flash Attention 2 kernels to handle the extended context length. Without this parameter, FA2 enforces the original 32,768 token limit.
Full Unsloth Reproduction Script
This can be run with uv run script.py
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "requests",
# "transformers<=4.53.0",
# "unsloth==2025.8.1",
# "vllm==0.9.2",
# ]
# ///
from unsloth import FastLanguageModel
import os
import requests
from datasets import Dataset
from trl import GRPOTrainer, GRPOConfig
# Allow vLLM to use very long context lengths
os.environ["VLLM_ALLOW_LONG_MAX_MODEL_LEN"] = "1"
MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct"
MAX_SEQ_LENGTH = 131072
LORA_RANK = 32
def create_dataset():
"""Creates a single-row dataset by downloading a book from the internet."""
# URL of a public domain book from Project Gutenberg
url = "https://www.gutenberg.org/cache/epub/1661/pg1661.txt"
try:
response = requests.get(url)
response.raise_for_status()
book_content = response.text
except requests.exceptions.RequestException as e:
print(f"Failed to download the book: {e}")
exit()
# Create the dataset
data = {
"prompt": [
[
{
"role": "system",
"content": "Summarize the following book.",
},
{
"role": "user",
"content": " ".join(book_content.split()[:50000]),
}, # 50k words
]
]
}
return Dataset.from_dict(data)
def dummy_reward_function(prompts, completions, **kwargs):
"""A simple reward function that returns a score of 1.0 for every completion."""
return [1.0] * len(completions)
def main():
"""Main function to run the minimal reproduction script."""
# 1. Load the dataset
print("Creating dataset...")
train_dataset = create_dataset()
print("Dataset created.")
# 2. Load the model and tokenizer
print("Initializing model...")
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=MODEL_NAME,
max_seq_length=MAX_SEQ_LENGTH,
load_in_4bit=False,
fast_inference=True,
max_lora_rank=LORA_RANK,
gpu_memory_utilization=0.95,
rope_scaling={ # This parameter is not passed to vLLM, causing the error
"rope_type": "yarn",
"factor": 4.0,
"original_max_position_embeddings": 32768,
},
)
print("Model initialized.")
# 3. Configure LoRA
print("Setting up LoRA...")
model = FastLanguageModel.get_peft_model(
model,
r=LORA_RANK,
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
],
lora_alpha=LORA_RANK * 2,
use_gradient_checkpointing="unsloth",
random_state=3407,
)
print("LoRA configured.")
# 4. Calculate prompt and completion lengths
print("Computing maximum prompt length...")
max_prompt_length = 0
for item in train_dataset:
tokens = tokenizer.apply_chat_template(
item["prompt"], add_generation_prompt=True, tokenize=True
)
max_prompt_length = max(max_prompt_length, len(tokens))
max_completion_length = MAX_SEQ_LENGTH - max_prompt_length
print(f"Max prompt length: {max_prompt_length}")
print(f"Max completion length: {max_completion_length}")
# 5. Set up GRPO training configuration
training_args = GRPOConfig(
per_device_train_batch_size=1,
gradient_accumulation_steps=1,
max_steps=2, # Set to a small number for quick testing
logging_steps=1,
output_dir="outputs_minimal",
report_to="none", # Disable wandb
learning_rate=5e-6,
lr_scheduler_type="cosine",
warmup_ratio=0.1,
weight_decay=0.01,
optim="adamw_8bit",
num_generations=2,
max_prompt_length=max_prompt_length,
max_completion_length=max_completion_length,
mask_truncated_completions=True,
max_grad_norm=1.0,
temperature=0.8,
)
# 6. Initialize the GRPOTrainer
print("Setting up GRPO trainer...")
trainer = GRPOTrainer(
model=model,
processing_class=tokenizer,
reward_funcs=[dummy_reward_function],
args=training_args,
train_dataset=train_dataset,
eval_dataset=None, # No validation dataset
)
print("Trainer configured.")
# 7. Start training
print("Starting training...")
trainer.train() # This will fail with CUDA error
print("Training completed!")
if __name__ == "__main__":
main()Proposed Solution
Add rope_scaling to the allowed parameters that get passed to vLLM in the FastLlamaModel.from_pretrained method. This would enable proper long-context training with models that require rope scaling configuration.
Question
Is the current behavior (not passing rope_scaling to vLLM) intentional, or should this parameter be supported for long-context fine-tuning scenarios?
Activity
Forward rope_scaling from load_vllm to vLLM (#1687)
Apply an explicit rope_scaling to the model and to vLLM (#13315)
danielhanchen commentedon Oct 11, 2026
Fixed! Sorry on the delay.
rope_scalingpassed toFastLanguageModel.from_pretrainedwas never applied, so withfast_inference = TruevLLM kept Qwen2.5's native 32K RoPE and crashed past it. It is now applied to both the training model and vLLM (YaRN, linear and llama3 types), and the issue's long-context GRPO setup trains past 32K withoutVLLM_ALLOW_LONG_MAX_MODEL_LEN. Fixed in #13315 and unslothai/unsloth-zoo#1687.To update:
uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir(if it's not in the current release yet it'll be in the next one). Reopen if it still happens.