Skip to content

[FIXED] Error patching SFTTrainer #1699

Closed

Description

@emirkaanozdemr

I want to download Llama 3.2 Vision Instruct Model with this code but I take an error
`from unsloth import FastVisionModel # FastLanguageModel for LLMs
import torch

4bit pre quantized models we support for 4x faster downloading + no OOMs.

fourbit_models = [
"unsloth/Llama-3.2-11B-Vision-Instruct-bnb-4bit", # Llama 3.2 vision support
"unsloth/Llama-3.2-11B-Vision-bnb-4bit",
"unsloth/Llama-3.2-90B-Vision-Instruct-bnb-4bit", # Can fit in a 80GB card!
"unsloth/Llama-3.2-90B-Vision-bnb-4bit",

"unsloth/Pixtral-12B-2409-bnb-4bit",              # Pixtral fits in 16GB!
"unsloth/Pixtral-12B-Base-2409-bnb-4bit",         # Pixtral base model

"unsloth/Qwen2-VL-2B-Instruct-bnb-4bit",          # Qwen2 VL support
"unsloth/Qwen2-VL-7B-Instruct-bnb-4bit",
"unsloth/Qwen2-VL-72B-Instruct-bnb-4bit",

"unsloth/llava-v1.6-mistral-7b-hf-bnb-4bit",      # Any Llava variant works!
"unsloth/llava-1.5-7b-hf-bnb-4bit",

] # More models at https://huggingface.co/unsloth

model, tokenizer = FastVisionModel.from_pretrained(
"unsloth/Llama-3.2-11B-Vision-Instruct",
load_in_4bit = True, # Use 4bit to reduce memory use. False for 16bit LoRA.
use_gradient_checkpointing = "unsloth", # True or "unsloth" for long context
)`

Error

🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
🦥 Unsloth Zoo will now patch everything to make training faster!

SyntaxError Traceback (most recent call last)
/usr/local/lib/python3.11/dist-packages/unsloth/tokenizer_utils.py in
1060 try:
-> 1061 exec(trainer_text, globals())
1062 except:

SyntaxError: invalid syntax (, line 4)

During handling of the above exception, another exception occurred:

RuntimeError Traceback (most recent call last)
5 frames
/usr/local/lib/python3.11/dist-packages/unsloth/tokenizer_utils.py in
1061 exec(trainer_text, globals())
1062 except:
-> 1063 raise RuntimeError(f"Unsloth: Please file a bug report! Error patching {trainer_name}")
1064 exec(f"trl.trainer.{trainer_name} = Unsloth{trainer_name}", globals())
1065 pass

RuntimeError: Unsloth: Please file a bug report! Error patching SFTTrainer

Activity

  1. ChagoLB commented on Feb 13, 2025

    @ChagoLB

    Hello, i have the same issue! This happens to me when trying to import the necessary libraries to operate with the models:

    from unsloth import FastLanguageModel
    import torch
    from datasets import Dataset
    import json
    from trl import SFTTrainer
    from transformers import TrainingArguments
    from unsloth import is_bfloat16_supported
    import wandb
    

    From the first import of FastLanguageModel, this error appears:

    ---------------------------------------------------------------------------
    SyntaxError                               Traceback (most recent call last)
    [/usr/local/lib/python3.11/dist-packages/unsloth/tokenizer_utils.py](i redacted the https localhost url) in <module>
       1060     try:
    -> 1061         exec(trainer_text, globals())
       1062     except:
    
    SyntaxError: invalid syntax (<string>, line 4)
    
    During handling of the above exception, another exception occurred:
    
    RuntimeError                              Traceback (most recent call last)
    5 frames
    [/usr/local/lib/python3.11/dist-packages/unsloth/tokenizer_utils.py](i redacted the https localhost url) in <module>
       1061         exec(trainer_text, globals())
       1062     except:
    -> 1063         raise RuntimeError(f"Unsloth: Please file a bug report! Error patching {trainer_name}")
       1064     exec(f"trl.trainer.{trainer_name} = Unsloth{trainer_name}", globals())
       1065 pass
    
    RuntimeError: Unsloth: Please file a bug report! Error patching SFTTrainer
    

    In aditional info, this error raised today, i had no problems running the libraries yesterday

    • Tried importing different vertions of the other libraries to see if it worked, it didn't.
    • i'm using Google Colab as my environment, and tried creating a brand new notebook to see if the one i was working on got corrupted, but got the same error when importing.
    • The last thing i tried was pip upgrading every other library to see if that resolved the compatibility issue, but once again got this error.
  2. styalai commented on Feb 13, 2025

    @styalai

    Maybe try to install trl<1.15.0, I had the same error and it worked for me. There was the same problem here: #1698

  3. kkailaasa commented on Feb 13, 2025

    @kkailaasa

    Exactly how were you able to fix @styalai?

    when running !pip install "trl<0.15.0" followed by !pip install unsloth, getting this error:

    ---------------------------------------------------------------------------
    
    AttributeError                            Traceback (most recent call last)
    
    [<ipython-input-5-74a5cc0ecc2b>](https://localhost:8080/#) in <cell line: 0>()
    ----> 1 from unsloth import FastLanguageModel
          2 import torch
          3 from datasets import load_dataset
          4 from trl import SFTTrainer
          5 from transformers import TrainingArguments
    
    13 frames
    
    [/usr/local/lib/python3.11/dist-packages/torchvision/_meta_registrations.py](https://localhost:8080/#) in wrapper(fn)
         16 def register_meta(op_name, overload_name="default"):
         17     def wrapper(fn):
    ---> 18         if torchvision.extension._has_ops():
         19             get_meta_lib().impl(getattr(getattr(torch.ops.torchvision, op_name), overload_name), fn)
         20         return fn
    
    AttributeError: partially initialized module 'torchvision' has no attribute 'extension' (most likely due to a circular import)
    
  4. styalai commented on Feb 13, 2025

    @styalai

    I install all my libraries like this:
    !pip install -q triton==3.1.0
    !pip install -q trl==0.14.0
    !pip install -q vllm==0.7.1
    !pip install -q unsloth==2025.2.4 unsloth_zoo==2025.2.3

  5. luochongqi commented on Feb 13, 2025

    @luochongqi

    @kkailaasa
    pip install "trl<0.15.0". It will run successfully.You can try using conda and install the environment with the official conda command. After that, run this command in a new environment pip install "trl<0.15.0"

    official conda command: https://docs.unsloth.ai/get-started/installing-+-updating/conda-install

  6. ChagoLB commented on Feb 13, 2025

    @ChagoLB

    Maybe try to install trl<1.15.0, I had the same error and it worked for me. There was the same problem here: #1698

    It worked for me as well, thank you so much for the help!
    i used this cell to run the instalations:

    %%capture
    !pip install unsloth
    !pip uninstall unsloth -y && pip install --upgrade --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git
    !pip install wandb
    #!pip install torchvision --upgrade
    !pip install --upgrade unsloth
    !pip install "trl<0.15.0"
    

    Not sure why the process runs like this, installing, uninstalling and then installing and upgrading unsloth, but i think i got those lines from one of their pre built notebooks (the lamma 8b v0.3 i think).

  7. ChagoLB commented on Feb 13, 2025

    @ChagoLB

    Exactly how were you able to fix @styalai?

    when running !pip install "trl<0.15.0" followed by !pip install unsloth, getting this error:

    ---------------------------------------------------------------------------
    
    AttributeError                            Traceback (most recent call last)
    
    [<ipython-input-5-74a5cc0ecc2b>](https://localhost:8080/#) in <cell line: 0>()
    ----> 1 from unsloth import FastLanguageModel
          2 import torch
          3 from datasets import load_dataset
          4 from trl import SFTTrainer
          5 from transformers import TrainingArguments
    
    13 frames
    
    [/usr/local/lib/python3.11/dist-packages/torchvision/_meta_registrations.py](https://localhost:8080/#) in wrapper(fn)
         16 def register_meta(op_name, overload_name="default"):
         17     def wrapper(fn):
    ---> 18         if torchvision.extension._has_ops():
         19             get_meta_lib().impl(getattr(getattr(torch.ops.torchvision, op_name), overload_name), fn)
         20         return fn
    
    AttributeError: partially initialized module 'torchvision' has no attribute 'extension' (most likely due to a circular import)
    

    I had the same error, fixed it by using this line:

    
    !pip install torchvision --upgrade
    

    although pretty much every time i had to restart the runtime, then i would run smoothly

  8. danielhanchen commented on Feb 13, 2025

    @danielhanchen
    Member

    Apologies on the issue - I'm working on a fix asap

  9. added
    fixed - pending confirmation
    and removed
    currently fixing
    on Feb 13, 2025
  10. danielhanchen commented on Feb 13, 2025

    @danielhanchen
    Member

    Just fixed - for now please use TRL < 0.15.0 - I updated all notebooks as well - so refresh them if you're using them. Ie do:

    pip uninstall trl -y && pip install --no-cache-dir --force-reinstall --no-deps "trl<0.15.0"

    I'm still trying to work on supporting the latest TRL 0.15.0, so it'll take a bit more time.

    For GRPO runs, please use "unsloth==2025.2.4" so pip install "unsloth==2025.2.4"

    Using pip install unsloth should work since it'll use an old TRL version

  11. zhangxuefeng commented on Feb 14, 2025

    @zhangxuefeng

    Just fixed - for now please use TRL < 0.15.0 - I updated all notebooks as well - so refresh them if you're using them. Ie do:

    pip uninstall trl -y && pip install --no-cache-dir --force-reinstall --no-deps "trl<0.15.0"
    I'm still trying to work on supporting the latest TRL 0.15.0, so it'll take a bit more time.

    For GRPO runs, please use "unsloth==2025.2.4" so pip install "unsloth==2025.2.4"

    Using pip install unsloth should work since it'll use an old TRL version

    Hi Daniel,

    After doing this for fine-tuning job, I got new errors in inference phase:

    AttributeError Traceback (most recent call last)
    in <cell line: 0>()
    53 ).to("cuda")
    54
    ---> 55 outputs = model.generate(
    56 input_ids = inputs, max_new_tokens = 64, use_cache = True, temperature = 1.5, min_p = 0.1
    57 )

    11 frames
    /usr/local/lib/python3.11/dist-packages/unsloth/models/llama.py 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)
    725 sliding_window = getattr(self.config, "sliding_window", None),
    726 )
    --> 727 attention_mask = attention_mask.to(torch.bool)
    728 pass
    729

    AttributeError: 'NoneType' object has no attribute 'to'

  12. kkailaasa commented on Feb 14, 2025

    @kkailaasa

    thank you @luochongqi @styalai - I deleted and started up a fresh runtime, it worked.

    @danielhanchen I also got the same error above as @zhangxuefeng just now

    Thank you for providing the recent fix and also actively helping us sort these issues

    Someone has also raised an independent issue here: #1704

  13. changed the title [-]Error patching SFTTrainer[/-] [+][FIXED] Error patching SFTTrainer[/+] on Feb 14, 2025
  14. danielhanchen commented on Feb 14, 2025

    @danielhanchen
    Member

    @zhangxuefeng @kkailaasa Apologies - just added a fix! Please update Unsloth via pip install --upgrade --no-deps --force-reinstall unsloth - or Colab / Kaggle will just need a refresh.

    Apologies this release has been quite annoying - hopefully this won't happen again - sorry again!

  15. kkailaasa commented on Feb 14, 2025

    @kkailaasa

    No problem @danielhanchen I'm testing out the latest version now.

  16. zhangxuefeng commented on Feb 14, 2025

    @zhangxuefeng

    @zhangxuefeng @kkailaasa Apologies - just added a fix! Please update Unsloth via pip install --upgrade --no-deps --force-reinstall unsloth - or Colab / Kaggle will just need a refresh.

    Apologies this release has been quite annoying - hopefully this won't happen again - sorry again!

    Worked now !

    Thanks !

  17. udit-rawat commented on Feb 14, 2025

    @udit-rawat
    ###  Import Error with `torchvision` and `unsloth`
    
     
    I am facing an import issue while using `unsloth` along with `torchvision`. Despite reinstalling the packages, the issue persists.
    I am currently running this code on kaggle kernel instance, earlier this week i had no problem in running the same code.
    
    ##Code
    %%capture
    !pip install unsloth
    !pip uninstall unsloth -y && pip install --upgrade --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git
    !pip install wandb
    #!pip install torchvision --upgrade
    !pip install --upgrade unsloth
    !pip install "trl<0.15.0"
    
    
    
    
    
    
    
    I am encountering the following error:
    
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    /usr/local/lib/python3.10/dist-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
       1816         try:
    -> 1817             return importlib.import_module("." + module_name, self.__name__)
       1818         except Exception as e:
    
    /usr/lib/python3.10/importlib/__init__.py in import_module(name, package)
        125             level += 1
    --> 126     return _bootstrap._gcd_import(name[level:], package, level)
        127 
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _gcd_import(name, package, level)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load(name, import_)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _load_unlocked(spec)
    
    /usr/lib/python3.10/importlib/_bootstrap_external.py in exec_module(self, module)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
    
    /usr/local/lib/python3.10/dist-packages/transformers/image_processing_utils.py in <module>
         20 from .image_processing_base import BatchFeature, ImageProcessingMixin
    ---> 21 from .image_transforms import center_crop, normalize, rescale
         22 from .image_utils import ChannelDimension
    
    /usr/local/lib/python3.10/dist-packages/transformers/image_transforms.py in <module>
         21 
    ---> 22 from .image_utils import (
         23     ChannelDimension,
    
    /usr/local/lib/python3.10/dist-packages/transformers/image_utils.py in <module>
         58     if is_torchvision_available():
    ---> 59         from torchvision.transforms import InterpolationMode
         60 
    
    /usr/local/lib/python3.10/dist-packages/torchvision/__init__.py in <module>
          9 from .extension import _HAS_OPS  # usort:skip
    ---> 10 from torchvision import _meta_registrations, datasets, io, models, ops, transforms, utils  # usort:skip
         11 
    
    /usr/local/lib/python3.10/dist-packages/torchvision/_meta_registrations.py in <module>
         25 @register_meta("roi_align")
    ---> 26 def meta_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned):
         27     torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]")
    
    /usr/local/lib/python3.10/dist-packages/torchvision/_meta_registrations.py in wrapper(fn)
         17     def wrapper(fn):
    ---> 18         if torchvision.extension._has_ops():
         19             get_meta_lib().impl(getattr(getattr(torch.ops.torchvision, op_name), overload_name), fn)
    
    AttributeError: partially initialized module 'torchvision' has no attribute 'extension' (most likely due to a circular import)
    
    The above exception was the direct cause of the following exception:
    
    RuntimeError                              Traceback (most recent call last)
    /usr/local/lib/python3.10/dist-packages/trl/import_utils.py in _get_module(self, module_name)
        110         try:
    --> 111             return importlib.import_module("." + module_name, self.__name__)
        112         except Exception as e:
    
    /usr/lib/python3.10/importlib/__init__.py in import_module(name, package)
        125             level += 1
    --> 126     return _bootstrap._gcd_import(name[level:], package, level)
        127 
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _gcd_import(name, package, level)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load(name, import_)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _load_unlocked(spec)
    
    /usr/lib/python3.10/importlib/_bootstrap_external.py in exec_module(self, module)
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
    
    /usr/local/lib/python3.10/dist-packages/trl/trainer/sft_trainer.py in <module>
         27 from datasets.builder import DatasetGenerationError
    ---> 28 from transformers import (
         29     AutoModelForCausalLM,
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _handle_fromlist(module, fromlist, import_, recursive)
    
    /usr/local/lib/python3.10/dist-packages/transformers/utils/import_utils.py in __getattr__(self, name)
       1804         elif name in self._class_to_module.keys():
    -> 1805             module = self._get_module(self._class_to_module[name])
       1806             value = getattr(module, name)
    
    /usr/local/lib/python3.10/dist-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
       1818         except Exception as e:
    -> 1819             raise RuntimeError(
       1820                 f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
    
    RuntimeError: Failed to import transformers.image_processing_utils because of the following error (look up to see its traceback):
    partially initialized module 'torchvision' has no attribute 'extension' (most likely due to a circular import)
    
    The above exception was the direct cause of the following exception:
    
    RuntimeError                              Traceback (most recent call last)
    <ipython-input-9-47c27722a2bd> in <cell line: 10>()
          8 from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report
          9 from transformers import TrainingArguments
    ---> 10 from trl import SFTTrainer
         11 from unsloth import FastLanguageModel
         12 from accelerate import Accelerator
    
    /usr/lib/python3.10/importlib/_bootstrap.py in _handle_fromlist(module, fromlist, import_, recursive)
    
    /usr/local/lib/python3.10/dist-packages/trl/import_utils.py in __getattr__(self, name)
        100         elif name in self._class_to_module.keys():
        101             module = self._get_module(self._class_to_module[name])
    --> 102             value = getattr(module, name)
        103         else:
        104             raise AttributeError(f"module {self.__name__} has no attribute {name}")
    
    /usr/local/lib/python3.10/dist-packages/trl/import_utils.py in __getattr__(self, name)
         99             value = self._get_module(name)
        100         elif name in self._class_to_module.keys():
    --> 101             module = self._get_module(self._class_to_module[name])
        102             value = getattr(module, name)
        103         else:
    
    /usr/local/lib/python3.10/dist-packages/trl/import_utils.py in _get_module(self, module_name)
        111             return importlib.import_module("." + module_name, self.__name__)
        112         except Exception as e:
    --> 113             raise RuntimeError(
        114                 f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
        115                 f" traceback):\n{e}"
    
    RuntimeError: Failed to import trl.trainer.sft_trainer because of the following error (look up to see its traceback):
    Failed to import transformers.image_processing_utils because of the following error (look up to see its traceback):
    partially initialized module 'torchvision' has no attribute 'extension' (most likely due to a circular import)
    
  18. unpinned this issue on Mar 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    fixed - pending confirmation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions