Repository navigation
Description
Describe the bug
Use GRPO to train Qwen3 model failed:
RuntimeError: Inference tensors cannot be saved for backward. To work around you can make a clone to get a normal tensor and use it in autograd.
-
Environment Setup:
- OS: Ubuntu 22.04
- Python Version: 3.10
- Frameworks/Libraries:
unsloth 2025.4.3
unsloth-zoo 2025.4.2
vllm 0.8.5
-
Model Details:
- Model ID: Qwen/Qwen3-4B
-
Training Configuration:
- Trainer Args:
GRPOConfig
- Trainer Args:
from trl import GRPOConfig, GRPOTrainer
training_args = GRPOConfig(
use_vllm = True, # use vLLM for fast inference!
learning_rate = 5e-6,
adam_beta1 = 0.9,
adam_beta2 = 0.99,
weight_decay = 0.1,
warmup_ratio = 0.1,
lr_scheduler_type = "cosine",
optim = "adamw_8bit",
logging_steps = 1,
bf16 = is_bfloat16_supported(),
fp16 = not is_bfloat16_supported(),
per_device_train_batch_size = 1,
gradient_accumulation_steps = 1, # Increase to 4 for smoother training
num_generations = 8, # Decrease if out of memory
max_prompt_length = 256,
max_completion_length = 200,
# num_train_epochs = 1, # Set to 1 for a full training run
max_steps = 250,
save_steps = 250,
max_grad_norm = 0.1,
report_to = "none", # Can use Weights & Biases
output_dir = "outputs",
)
trainer = GRPOTrainer(
model = model,
processing_class = tokenizer,
reward_funcs = [
xmlcount_reward_func,
soft_format_reward_func,
strict_format_reward_func,
int_reward_func,
correctness_reward_func,
],
args = training_args,
train_dataset = dataset,
)
trainer.train()
- Actual Behavior:
RuntimeError: Inference tensors cannot be saved for backward. To work around you can make a clone to get a normal tensor and use it in autograd.
- Additional notes:
RuntimeError Traceback (most recent call last)
Cell In[3], line 40
2 training_args = GRPOConfig(
3 use_vllm = True, # use vLLM for fast inference!
4 learning_rate = 5e-6,
(...)
24 output_dir = "outputs",
25 )
27 trainer = GRPOTrainer(
28 model = model,
29 processing_class = tokenizer,
(...)
38 train_dataset = dataset,
39 )
---> 40 trainer.train()
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/transformers/trainer.py:2245, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
2243 hf_hub_utils.enable_progress_bars()
2244 else:
-> 2245 return inner_training_loop(
2246 args=args,
2247 resume_from_checkpoint=resume_from_checkpoint,
2248 trial=trial,
2249 ignore_keys_for_eval=ignore_keys_for_eval,
2250 )
File :314, in _fast_inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
File :77, in _unsloth_training_step(failed resolving arguments)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/accelerate/accelerator.py:2454, in Accelerator.backward(self, loss, **kwargs)
2452 self.lomo_backward(loss, learning_rate)
2453 else:
-> 2454 loss.backward(**kwargs)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/_tensor.py:626, in Tensor.backward(self, gradient, retain_graph, create_graph, inputs)
616 if has_torch_function_unary(self):
617 return handle_torch_function(
618 Tensor.backward,
619 (self,),
(...)
624 inputs=inputs,
625 )
--> 626 torch.autograd.backward(
627 self, gradient, retain_graph, create_graph, inputs=inputs
628 )
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/autograd/init.py:347, in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
342 retain_graph = create_graph
344 # The reason we repeat the same comment below is that
345 # some Python versions print out the first line of a multi-line function
346 # calls in the traceback and some print out the last line
--> 347 engine_run_backward(
348 tensors,
349 grad_tensors,
350 retain_graph,
351 create_graph,
352 inputs,
353 allow_unreachable=True,
354 accumulate_grad=True,
355 )
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/autograd/graph.py:823, in _engine_run_backward(t_outputs, *args, **kwargs)
821 unregister_hooks = _register_logging_hooks_on_whole_graph(t_outputs)
822 try:
--> 823 return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
824 t_outputs, *args, **kwargs
825 ) # Calls into the C++ engine to run the backward pass
826 finally:
827 if attach_logging_hooks:
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/autograd/function.py:307, in BackwardCFunction.apply(self, *args)
301 raise RuntimeError(
302 "Implementing both 'backward' and 'vjp' for a custom "
303 "Function is not allowed. You should only implement one "
304 "of them."
305 )
306 user_fn = vjp_fn if vjp_fn is not Function.vjp else backward_fn
--> 307 return user_fn(self, *args)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/unsloth_zoo/gradient_checkpointing.py:554, in UnslothCheckpointFunction.backward(ctx, *args)
551 pass
553 with torch.enable_grad(), device_autocast_ctx, torch.amp.autocast("cpu", **ctx.cpu_autocast_kwargs): # type: ignore[attr-defined]
--> 554 outputs = ctx.run_function(*detached_inputs)
555 pass
556 pass
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/unsloth/models/llama.py:855, in LlamaModel_fast_forward..create_custom_forward..custom_forward(*inputs)
854 def custom_forward(*inputs):
--> 855 return module(*inputs, past_key_value, output_attentions, padding_mask = padding_mask, position_embeddings = position_embeddings)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1737 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
1745 # If we don't have any hooks, we want to skip the rest of the logic in
1746 # this function, and just call forward.
1747 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1748 or _global_backward_pre_hooks or _global_backward_hooks
1749 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1750 return forward_call(*args, **kwargs)
1752 result = None
1753 called_always_called_hooks = set()
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/unsloth/models/llama.py:543, in LlamaDecoderLayer_fast_forward(self, hidden_states, causal_mask, attention_mask, position_ids, past_key_value, output_attentions, use_cache, padding_mask, position_embeddings, *args, **kwargs)
541 residual = hidden_states
542 hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states)
--> 543 hidden_states, self_attn_weights, present_key_value = self.self_attn(
544 hidden_states = hidden_states,
545 causal_mask = causal_mask,
546 attention_mask = attention_mask,
547 position_ids = position_ids,
548 past_key_value = past_key_value,
549 output_attentions = output_attentions,
550 use_cache = use_cache,
551 padding_mask = padding_mask,
552 position_embeddings = position_embeddings,
553 )
554 hidden_states = residual + hidden_states
556 # Fully Connected
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1737 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
1745 # If we don't have any hooks, we want to skip the rest of the logic in
1746 # this function, and just call forward.
1747 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1748 or _global_backward_pre_hooks or _global_backward_hooks
1749 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1750 return forward_call(*args, **kwargs)
1752 result = None
1753 called_always_called_hooks = set()
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/unsloth/models/qwen3.py:96, in Qwen3Attention_fast_forward(self, hidden_states, causal_mask, attention_mask, position_ids, past_key_value, output_attentions, use_cache, padding_mask, position_embeddings, *args, **kwargs)
90 V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)
92 #Qwen3 has QKNorm. This seems to be the only difference from Qwen2.
93 # Note that using fast_layernorm_compiled causes issues as the dimensions don't match up.
94 # I tried to add a compiled version of the new norm but the numbers don't match up with Transformers
95 # TODO: Check on the differences here.
---> 96 Q = fast_rms_layernorm(self.q_norm, Q)
97 K = fast_rms_layernorm(self.k_norm, K)
99 Q = Q.transpose(1, 2)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py:745, in DisableContext.call.._fn(*args, **kwargs)
741 prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe(
742 _is_skip_guard_eval_unsafe_stance()
743 )
744 try:
--> 745 return fn(*args, **kwargs)
746 finally:
747 _maybe_set_eval_frame(prior)
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/unsloth/kernels/rms_layernorm.py:215, in fast_rms_layernorm(layernorm, X, gemma)
211 W : torch.Tensor = layernorm.weight
212 eps : float = layernorm.variance_epsilon if
213 hasattr(layernorm, "variance_epsilon")
214 else layernorm.eps
--> 215 out = Fast_RMS_Layernorm.apply(X, W, eps, gemma)
216 return out
File ~/miniconda3/envs/ft310/lib/python3.10/site-packages/torch/autograd/function.py:575, in Function.apply(cls, *args, **kwargs)
572 if not torch._C._are_functorch_transforms_active():
573 # See NOTE: [functorch vjp and autograd interaction]
574 args = _functorch.utils.unwrap_dead_wrappers(args)
--> 575 return super().apply(*args, **kwargs) # type: ignore[misc]
577 if not is_setup_ctx_defined:
578 raise RuntimeError(
579 "In order to use an autograd.Function with functorch transforms "
580 "(vmap, grad, jvp, jacrev, ...), it must override the setup_context "
581 "staticmethod. For more details, please see "
582 "https://pytorch.org/docs/main/notes/extending.func.html"
583 )
RuntimeError: Inference tensors cannot be saved for backward. To work around you can make a clone to get a normal tensor and use it in autograd.
Activity
[-][Bug] AttributeError: 'Qwen3ForCausalLM' object has no attribute 'vllm_engine'[/-][+][Bug] GRPO Qwen3 Failed: Inference tensors cannot be saved for backward. To work around you can make a clone to get a normal tensor and use it in autograd.[/+]CuppaXanax commentedon May 1, 2025
I wanted to add a +1 to this failure; my setup is similar
unsloth 2025.4.4
unsloth-zoo 2025.4.2
vllm 0.8.5
debackerl commentedon May 1, 2025
I confirm this using GRPO and Qwen3
Setup:
uv pip install --upgrade numpy torch==2.6.0 triton --index-url https://download.pytorch.org/whl/cu124
mamba install -c "nvidia/label/cuda-12.4.1" cuda-libraries-dev cuda-nvcc ninja
uv pip install --upgrade --no-build-isolation 'vllm==0.8.4'
uv pip install --upgrade 'unsloth[cu124-ampere-torch260] @ git+https://github.com/unslothai/unsloth.git#776b83b'
uv pip install flashinfer-python -i https://flashinfer.ai/whl/cu124/torch2.6
CuppaXanax commentedon May 2, 2025
So here's another note - I realize that I'm hitting this error after puttingL
At the top of my training script. I ended up setting that variable after following the advice in #1972
hxssgaa commentedon May 2, 2025
I got the exact same problem with my RTX 5090 setup
bi1101 commentedon May 3, 2025
This can be temporary overcome by not using vllm, just comments out the vllm code. This come with a drawback of extremly slow speed.
and
shimmyshimmer commentedon May 13, 2025
Hey guys apologies for the issues, should now work! Use the latest version of Unsloth and vLLM
Also we just released our advanced Qwen3 GRPO notebook: https://x.com/UnslothAI/status/1922343047435862318
CC: @debackerl @hxssgaa @beston123 @bi1101 @CuppaXanax
shimmyshimmer commentedon May 14, 2025
Closing for now, if there's any issues please make a new thread thanks!
ZQ-Dev8 commentedon May 20, 2025
@shimmyshimmer I'm still seeing this error. However, it isn't caused by anything having to do with GRPO or vLLM. It seems to be stemming from using the
.add_new_tokens()function.vinceamaz commentedon May 23, 2025
@shimmyshimmer I'm still seeing this error too with vllm enabled training Qwen3-4B-Base with GRPO.