Repository navigation
Description
- Did you update?
pip install --upgrade unsloth unsloth_zooyes ColaborKaggleor local / cloud cloud- Number GPUs used, use
nvidia-smi1 - Which notebook? Qwen3_(4B)-GRPO.ipynb
- Paste
Unslothprintout with 🦥 sloth emoji - Which trainer?
SFTTrainer,GRPOTraineretc from_pretrained - Minimal code to reproduce error Remove Hugging Face token!
For quick replies, got to https://discord.com/invite/unsloth.
Have you tried https://docs.unsloth.ai/basics/errors-troubleshooting
When using the Qwen3_(4B)-GRPO.ipynb notebook for training, an error occurs when using this code
from unsloth import FastLanguageModel
import torch
max_seq_length = 2048 # Can increase for longer reasoning traces
lora_rank = 32 # Larger rank = smarter, but slowermodel, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Qwen3-4B-Base",
max_seq_length = max_seq_length,
load_in_4bit = False, # False for LoRA 16bit
fast_inference = True, # Enable vLLM fast inference
max_lora_rank = lora_rank,
gpu_memory_utilization = 0.7, # Reduce if out of memory
)model = FastLanguageModel.get_peft_model(
model,
r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
],
lora_alpha = lora_rank*2, # *2 speeds up training
use_gradient_checkpointing = "unsloth", # Reduces memory usage
random_state = 3407,
)
The error content is:
AttributeError Traceback (most recent call last)
File ~/miniconda3/lib/python3.12/site-packages/unsloth_zoo/vllm_utils.py:1042, in load_vllm(model_name, config, gpu_memory_utilization, max_seq_length, dtype, training, float8_kv_cache, random_state, enable_lora, max_lora_rank, max_loras, use_async, use_engine, disable_log_stats, enforce_eager, enable_prefix_caching, compilation_config, conservativeness, max_logprobs, use_bitsandbytes, return_args)
1041 else:
-> 1042 llm = LLM(**engine_args)
1043 passFile ~/miniconda3/lib/python3.12/site-packages/vllm/utils.py:1031, in deprecate_args..wrapper..inner(*args, **kwargs)
1026 warnings.warn(
1027 DeprecationWarning(msg),
1028 stacklevel=3, # The inner function takes up one level
1029 )
-> 1031 return fn(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/vllm/entrypoints/llm.py:242, in LLM.init(self, model, tokenizer, tokenizer_mode, skip_tokenizer_init, trust_remote_code, allowed_local_media_path, tensor_parallel_size, dtype, quantization, revision, tokenizer_revision, seed, gpu_memory_utilization, swap_space, cpu_offload_gb, enforce_eager, max_seq_len_to_capture, disable_custom_all_reduce, disable_async_output_proc, hf_overrides, mm_processor_kwargs, task, override_pooler_config, compilation_config, **kwargs)
241 # Create the Engine (autoselects V0 vs V1)
--> 242 self.llm_engine = LLMEngine.from_engine_args(
243 engine_args=engine_args, usage_context=UsageContext.LLM_CLASS)
244 self.engine_class = type(self.llm_engine)File ~/miniconda3/lib/python3.12/site-packages/vllm/engine/llm_engine.py:520, in LLMEngine.from_engine_args(cls, engine_args, usage_context, stat_loggers)
518 engine_cls = V1LLMEngine
--> 520 return engine_cls.from_vllm_config(
521 vllm_config=vllm_config,
522 usage_context=usage_context,
523 stat_loggers=stat_loggers,
524 disable_log_stats=engine_args.disable_log_stats,
525 )File ~/miniconda3/lib/python3.12/site-packages/vllm/engine/llm_engine.py:496, in LLMEngine.from_vllm_config(cls, vllm_config, usage_context, stat_loggers, disable_log_stats)
488 @classmethod
489 def from_vllm_config(
490 cls,
(...)
494 disable_log_stats: bool = False,
495 ) -> "LLMEngine":
--> 496 return cls(
497 vllm_config=vllm_config,
498 executor_class=cls._get_executor_cls(vllm_config),
499 log_stats=(not disable_log_stats),
500 usage_context=usage_context,
501 stat_loggers=stat_loggers,
502 )File ~/miniconda3/lib/python3.12/site-packages/vllm/engine/llm_engine.py:283, in LLMEngine.init(self, vllm_config, executor_class, log_stats, usage_context, stat_loggers, input_registry, mm_registry, use_cached_outputs)
282 if self.model_config.runner_type != "pooling":
--> 283 self._initialize_kv_caches()
285 # If usage stat is enabled, collect relevant info.File ~/miniconda3/lib/python3.12/site-packages/vllm/engine/llm_engine.py:432, in LLMEngine._initialize_kv_caches(self)
430 start = time.time()
431 num_gpu_blocks, num_cpu_blocks = (
--> 432 self.model_executor.determine_num_available_blocks())
434 if self.cache_config.num_gpu_blocks_override is not None:File ~/miniconda3/lib/python3.12/site-packages/vllm/executor/executor_base.py:102, in ExecutorBase.determine_num_available_blocks(self)
90 """Determine the number of available blocks for the GPU KV cache and
91 swappable CPU KV cache.
92
(...)
100 appended to.
101 """
--> 102 results = self.collective_rpc("determine_num_available_blocks")
103 a = min([r[0] for r in results])File ~/miniconda3/lib/python3.12/site-packages/vllm/executor/uniproc_executor.py:56, in UniProcExecutor.collective_rpc(self, method, timeout, args, kwargs)
55 kwargs = {}
---> 56 answer = run_method(self.driver_worker, method, args, kwargs)
57 return [answer]File ~/miniconda3/lib/python3.12/site-packages/vllm/utils.py:2216, in run_method(obj, method, args, kwargs)
2215 func = partial(method, obj) # type: ignore
-> 2216 return func(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
115 with ctx_factory():
--> 116 return func(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/vllm/worker/worker.py:229, in Worker.determine_num_available_blocks(self)
226 with memory_profiling(
227 self.baseline_snapshot,
228 weights_memory=self.model_runner.model_memory_usage) as result:
--> 229 self.model_runner.profile_run()
231 self._assert_memory_footprint_increased_during_profiling()File ~/miniconda3/lib/python3.12/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
115 with ctx_factory():
--> 116 return func(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/vllm/worker/model_runner.py:1243, in GPUModelRunnerBase.profile_run(self)
1242 max_num_seqs = self.scheduler_config.max_num_seqs
-> 1243 self._dummy_run(max_num_batched_tokens, max_num_seqs)File ~/miniconda3/lib/python3.12/site-packages/vllm/worker/model_runner.py:1354, in GPUModelRunnerBase._dummy_run(self, max_num_batched_tokens, max_num_seqs)
1352 model_input.attn_metadata.enable_kv_scales_calculation = False
-> 1354 self.execute_model(model_input, kv_caches, intermediate_tensors)
1355 torch.cuda.synchronize()File ~/miniconda3/lib/python3.12/site-packages/torch/utils/_contextlib.py:116, in context_decorator..decorate_context(*args, **kwargs)
115 with ctx_factory():
--> 116 return func(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/vllm/worker/model_runner.py:1742, in ModelRunner.execute_model(self, model_input, kv_caches, intermediate_tensors, num_steps, **kwargs)
1740 with set_forward_context(model_input.attn_metadata,
1741 self.vllm_config, virtual_engine):
-> 1742 hidden_or_intermediate_states = model_executable(
1743 input_ids=model_input.input_tokens,
1744 positions=model_input.input_positions,
1745 intermediate_tensors=intermediate_tensors,
1746 **MultiModalKwargs.as_kwargs(multi_modal_kwargs,
1747 device=self.device),
1748 **seqlen_agnostic_kwargs,
1749 **model_kwargs,
1750 )
1752 if (self.observability_config is not None
1753 and self.observability_config.collect_model_forward_time):File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
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 = NoneFile ~/miniconda3/lib/python3.12/site-packages/vllm/model_executor/models/transformers.py:212, in TransformersModel.forward(self, input_ids, positions, intermediate_tensors, inputs_embeds)
205 def forward(
206 self,
207 input_ids: torch.Tensor,
(...)
210 inputs_embeds: Optional[torch.Tensor] = None,
211 ) -> Union[torch.Tensor, IntermediateTensors]:
--> 212 model_output = self.model(
213 input_ids[None, ...],
214 use_cache=False,
215 position_ids=positions[None, ...],
216 intermediate_tensors=intermediate_tensors,
217 attention_instances=self.attention_instances,
218 return_dict=False)[0][0, ...] # we remove batch dimension for now
219 return model_outputFile ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
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 = NoneFile ~/miniconda3/lib/python3.12/site-packages/unsloth/models/llama.py:871, in LlamaModel_fast_forward(self, input_ids, causal_mask, attention_mask, position_ids, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict, *args, **kwargs)
870 else:
--> 871 layer_outputs = decoder_layer(
872 hidden_states,
873 causal_mask=mask,
874 attention_mask = attention_mask,
875 position_ids = position_ids,
876 past_key_value = past_key_value,
877 output_attentions = output_attentions,
878 use_cache = use_cache,
879 padding_mask = padding_mask,
880 position_embeddings = position_embeddings,
881 )
882 hidden_states = layer_outputs[0]File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
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 = NoneFile ~/miniconda3/lib/python3.12/site-packages/unsloth/models/llama.py:544, 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)
543 hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states)
--> 544 hidden_states, self_attn_weights, present_key_value = self.self_attn(
545 hidden_states = hidden_states,
546 causal_mask = causal_mask,
547 attention_mask = attention_mask,
548 position_ids = position_ids,
549 past_key_value = past_key_value,
550 output_attentions = output_attentions,
551 use_cache = use_cache,
552 padding_mask = padding_mask,
553 position_embeddings = position_embeddings,
554 )
555 hidden_states = residual + hidden_statesFile ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
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 = NoneFile ~/miniconda3/lib/python3.12/site-packages/unsloth/models/qwen3.py:89, 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)
87 assert(n_kv_heads * n_groups == n_heads)
---> 89 Q, K, V = self.apply_qkv(self, hidden_states)
90 Q = Q.view(bsz, q_len, n_heads, head_dim)#.transpose(1, 2) # we will transpose after normalisationFile ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1928, in Module.getattr(self, name)
1927 return modules[name]
-> 1928 raise AttributeError(
1929 f"'{type(self).name}' object has no attribute '{name}'"
1930 )AttributeError: 'Qwen3Attention' object has no attribute 'apply_qkv'
During handling of the above exception, another exception occurred:
RuntimeError Traceback (most recent call last)
Cell In[4], line 6
3 max_seq_length = 2048 # Can increase for longer reasoning traces
4 lora_rank = 32 # Larger rank = smarter, but slower
----> 6 model, tokenizer = FastLanguageModel.from_pretrained(
7 model_name = "/root/autodl-tmp/models/Qwen/Qwen3-4B-Base",
8 max_seq_length = max_seq_length,
9 load_in_4bit = False, # False for LoRA 16bit
10 fast_inference = True, # Enable vLLM fast inference
11 max_lora_rank = lora_rank,
12 gpu_memory_utilization = 0.7, # Reduce if out of memory
13 )
15 model = FastLanguageModel.get_peft_model(
16 model,
17 r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
(...)
24 random_state = 3407,
25 )File ~/miniconda3/lib/python3.12/site-packages/unsloth/models/loader.py:376, in FastLanguageModel.from_pretrained(model_name, max_seq_length, dtype, load_in_4bit, load_in_8bit, full_finetuning, token, device_map, rope_scaling, fix_tokenizer, trust_remote_code, use_gradient_checkpointing, resize_model_vocab, revision, use_exact_model_name, fast_inference, gpu_memory_utilization, float8_kv_cache, random_state, max_lora_rank, disable_log_stats, *args, **kwargs)
373 pass
374 pass
--> 376 model, tokenizer = dispatch_model.from_pretrained(
377 model_name = model_name,
378 max_seq_length = max_seq_length,
379 dtype = _get_dtype(dtype),
380 load_in_4bit = load_in_4bit,
381 token = token,
382 device_map = device_map,
383 rope_scaling = rope_scaling,
384 fix_tokenizer = fix_tokenizer,
385 model_patcher = dispatch_model,
386 tokenizer_name = tokenizer_name,
387 trust_remote_code = trust_remote_code,
388 revision = revision if not is_peft else None,
389
390 fast_inference = fast_inference,
391 gpu_memory_utilization = gpu_memory_utilization,
392 float8_kv_cache = float8_kv_cache,
393 random_state = random_state,
394 max_lora_rank = max_lora_rank,
395 disable_log_stats = disable_log_stats,
396 *args, **kwargs,
397 )
399 if resize_model_vocab is not None:
400 model.resize_token_embeddings(resize_model_vocab)File ~/miniconda3/lib/python3.12/site-packages/unsloth/models/qwen3.py:419, in FastQwen3Model.from_pretrained(model_name, max_seq_length, dtype, load_in_4bit, token, device_map, rope_scaling, fix_tokenizer, model_patcher, tokenizer_name, trust_remote_code, **kwargs)
404 @staticmethod
405 def from_pretrained( #TODO: Change after release
406 model_name = "Qwen/Qwen3-7B",
(...)
417 **kwargs,
418 ):
--> 419 return FastLlamaModel.from_pretrained(
420 model_name = model_name,
421 max_seq_length = max_seq_length,
422 dtype = dtype,
423 load_in_4bit = load_in_4bit,
424 token = token,
425 device_map = device_map,
426 rope_scaling = rope_scaling,
427 fix_tokenizer = fix_tokenizer,
428 model_patcher = FastQwen3Model,
429 tokenizer_name = tokenizer_name,
430 trust_remote_code = trust_remote_code,
431 **kwargs,
432 )File ~/miniconda3/lib/python3.12/site-packages/unsloth/models/llama.py:1827, in FastLlamaModel.from_pretrained(model_name, max_seq_length, dtype, load_in_4bit, token, device_map, rope_scaling, fix_tokenizer, model_patcher, tokenizer_name, trust_remote_code, fast_inference, gpu_memory_utilization, float8_kv_cache, random_state, max_lora_rank, disable_log_stats, **kwargs)
1824 pass
1826 # Load vLLM first
-> 1827 llm = load_vllm(**load_vllm_kwargs)
1829 # Convert to HF format
1830 _, quant_state_dict = get_vllm_state_dict(llm, config = model_config)File ~/miniconda3/lib/python3.12/site-packages/unsloth_zoo/vllm_utils.py:1065, in load_vllm(model_name, config, gpu_memory_utilization, max_seq_length, dtype, training, float8_kv_cache, random_state, enable_lora, max_lora_rank, max_loras, use_async, use_engine, disable_log_stats, enforce_eager, enable_prefix_caching, compilation_config, conservativeness, max_logprobs, use_bitsandbytes, return_args)
1060 print(
1061 f"Unsloth: Retrying vLLM to process {approx_max_num_seqs} sequences and {max_num_batched_tokens} tokens in tandem.\n"
1062 f"Error:\n{error}"
1063 )
1064 else:
-> 1065 raise RuntimeError(error)
1066 pass
1067 passRuntimeError: 'Qwen3Attention' object has no attribute 'apply_qkv'
Activity
Hodoryu commentedon May 20, 2025
you can exec cmd :pip3 install vllm==0.8.5, case adapted for qwen3 model from this vllm version, i sloved this problem when exec this cmd
codeysun commentedon May 21, 2025
I am getting the same error but with Qwen2Attention. pip install vllm did not work.
github-actions commentedon Jul 1, 2025
Is this issue still important to you? Apologies in advance we might have missed this issue as well. For faster response times, please post on our Reddit server - https://www.reddit.com/r/unsloth or our Discord - https://discord.com/invite/unsloth
Lorg0n commentedon Aug 27, 2025
Same error
ZMW-DW commentedon Apr 15, 2026
ye I meet same error.
ZMW-DW commentedon Apr 15, 2026
🛠 Issue Report & Resolution
Subject:
AttributeError: 'Qwen2Attention' object has no attribute 'apply_qkv'during Inference.Issue Description:
The inference pipeline crashes when processing
Qwen2.5-0.5Bmodels using theunslothpatched environment. Although the model loads successfully, the forward pass fails during the attention mechanism.Root Cause:
This is a dependency regression caused by a version mismatch between
unslothandunsloth-zoo.unsloth-zoo==2026.4.6introduces a monkey-patching logic that attempts to callapply_qkvonQwen2Attentionobjects. However, in the current environment, this method is not properly injected/initialized.unsloth-zoo==2026.4.4is verified to work correctly with the current model architecture.Resolution Steps:
1. Downgrade Dependencies (Recommended)
Force the environment to use the stable version pair. Run the following command in your terminal:
2. Environment Isolation
To prevent
unslothfrom interfering with the standardtransformersinference logic, set the following environment variable at the very top of your entry script (inference.py):3. Verify Installation
Check the package list to ensure the versions are synchronized:
Summary of Changes:
unsloth-zoofrom2026.4.6to2026.4.4.LLM_Train).AttributeErrorby ensuring compatible monkey-patching logic.Suggested Git Commit Message:
Resolve apply_qkv and apply_o defensively, and explain zero patch cou…
Resolve apply_qkv and apply_o defensively, and explain zero patch cou…