Skip to content

RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward. #2972

Closed

Description

@adi-lb-phoenix

I was trying to finetune whisper-large following the tutorial https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Whisper.ipynb#scrollTo=y7rOo10YkEqf.

i made small changes to the code , that is dtype = torch.float32 for the model loaded.

model, tokenizer = FastModel.from_pretrained(
    model_name = "unsloth/whisper-large-v3",
    dtype = torch.float32, 
    load_in_4bit = False, 
    auto_model = WhisperForConditionalGeneration,
    whisper_language = "English",
    whisper_task = "transcribe",
    # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)

below is the error I get

python3 fine_tune_whisper.py 
🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).
  warnings.warn(
🦥 Unsloth Zoo will now patch everything to make training faster!
==((====))==  Unsloth 2025.7.3: Fast Whisper patching. Transformers: 4.53.2.
   \\   /|    NVIDIA GeForce RTX 4070 Ti SUPER. Num GPUs = 1. Max memory: 15.58 GB. Platform: Linux.
O^O/ \_/ \    Torch: 2.7.1+cu126. CUDA: 8.9. CUDA Toolkit: 12.6. Triton: 3.3.1
\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.31.post1. FA2 = False]
 "-____-"     Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
Unsloth: QLoRA and full finetuning all not selected. Switching to 16bit LoRA.
unsloth/whisper-large-v3 does not have a padding token! Will use pad_token = <|endoftext|>.
off to get_peft_model
Unsloth: Making `model.base_model.model.model.encoder` require gradients
train split: 100%|███████████████████████████████████████████████████████| 1123/1123 [00:06<00:00, 185.32it/s]
Test Split: 100%|████████████████████████████████████████████████████████████| 72/72 [00:00<00:00, 194.89it/s]
/home/phoenix/llama/llama.lisp/src/AI/stt/unsloathAI/fine_tune_whisper.py:115: FutureWarning: `tokenizer` is deprecated and will be removed in version 5.0.0 for `Seq2SeqTrainer.__init__`. Use `processing_class` instead.
  trainer = Seq2SeqTrainer(
GPU = NVIDIA GeForce RTX 4070 Ti SUPER. Max memory = 15.58 GB.
6.021 GB of memory reserved.
==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
   \\   /|    Num examples = 1,123 | Num Epochs = 1 | Total steps = 60
O^O/ \_/ \    Batch size per device = 2 | Gradient accumulation steps = 4
\        /    Data Parallel GPUs = 1 | Total batch size (2 x 4 x 1) = 8
 "-____-"     Trainable parameters = 31,457,280 of 1,574,947,840 (2.00% trained)
  0%|                                                                                  | 0/60 [00:00<?, ?it/s]Unsloth: Not an error, but WhisperForConditionalGeneration does not accept `num_items_in_batch`.
Using gradient accumulation will be very slightly less accurate.
Read more on gradient accumulation issues here: https://unsloth.ai/blog/gradient
Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.43.0. You should pass an instance of `EncoderDecoderCache` instead, e.g. `past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`.
`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`...
Traceback (most recent call last):
  File "/home/phoenix/llama/llama.lisp/src/AI/stt/unsloathAI/fine_tune_whisper.py", line 149, in <module>
    trainer_stats = trainer.train()
                    ^^^^^^^^^^^^^^^
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/transformers/trainer.py", line 2206, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 321, in _fast_inner_training_loop
  File "<string>", line 82, in _unsloth_training_step
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/accelerate/accelerator.py", line 2553, in backward
    loss.backward(**kwargs)
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/_tensor.py", line 648, in backward
    torch.autograd.backward(
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/autograd/__init__.py", line 353, in backward
    _engine_run_backward(
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/autograd/graph.py", line 824, in _engine_run_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/autograd/function.py", line 307, in apply
    return user_fn(self, *args)
           ^^^^^^^^^^^^^^^^^^^^
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/unsloth_zoo/gradient_checkpointing.py", line 589, in backward
    torch.autograd.backward(outputs_with_grad, args_with_grad)
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/autograd/__init__.py", line 353, in backward
    _engine_run_backward(
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/autograd/graph.py", line 824, in _engine_run_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/autograd/function.py", line 307, in apply
    return user_fn(self, *args)
           ^^^^^^^^^^^^^^^^^^^^
  File "/home/phoenix/miniconda3/envs/unsloth/lib/python3.11/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 2050, in backward
    ctx.saved_tensors,
    ^^^^^^^^^^^^^^^^^
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.
  0%|          | 0/60 [00:02<?, ?it/s]                                   

GPU 4070 ti Super

uname -a
Linux JOHNAIC 6.5.0-45-generic #45~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Mon Jul 15 16:40:02 UTC 2 x86_64 x86_64 x86_64 GNU/Linux
/usr/local/cuda-12.6/bin/nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2024 NVIDIA Corporation
Built on Tue_Oct_29_23:50:19_PDT_2024
Cuda compilation tools, release 12.6, V12.6.85
Build cuda_12.6.r12.6/compiler.35059454_0

Command to create the conda environment:

conda create --name unsloth_env \
    python=3.11 \
    pytorch-cuda=12.1 \
    pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers \
    -y
conda activate unsloth_env

pip install unsloth

I suspect it is some form of compatibility issue.
can I run unsloth on CUDA 12.6?

Activity

  1. changed the title [-][Bug] Please fill in your issue title here.[/-] [+]RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.[/+] on Jul 15, 2025
  2. fanalyaen commented on Jul 16, 2025

    @fanalyaen

    I encountered the same error. Downgrading the transformers library to 4.51.3 fixed it for me.
    (But my CUDA version is 11.8)
    Reference here.

  3. adi-lb-phoenix commented on Jul 16, 2025

    @adi-lb-phoenix
    Author

    @fanalyaen that does not work

  4. csanadpoda commented on Jul 23, 2025

    @csanadpoda

    I am facing the same issue. Any updates?

  5. VanshRana12 commented on Aug 1, 2025

    @VanshRana12

    These fixed it for me.
    requirements1.txt:
    unsloth
    librosa
    soundfile
    evaluate
    jiwer
    transformers==4.51.3
    xformers==0.0.29.post3

    requirements3.txt:
    -i https://download.pytorch.org/whl/cu124
    torch==2.6.0
    torchvision==0.21.0
    torchaudio==2.6.0

  6. sujianwei1 commented on Sep 2, 2025

    @sujianwei1

    running it directly in Colab reports this error.
    RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.

  7. Erland366 commented on Sep 2, 2025

    @Erland366
    Collaborator

    Did you run with the transformers==4.51.3? latest transformers won't work

  8. sujianwei1 commented on Sep 3, 2025

    @sujianwei1

    🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
    🦥 Unsloth Zoo will now patch everything to make training faster!
    ==((====))== Unsloth 2025.8.10: Fast Whisper patching. Transformers: 4.55.4.
    \ /| Tesla T4. Num GPUs = 1. Max memory: 14.741 GB. Platform: Linux.
    O^O/ _/ \ Torch: 2.8.0+cu126. CUDA: 7.5. CUDA Toolkit: 12.6. Triton: 3.4.0
    \ / Bfloat16 = FALSE. FA [Xformers = 0.0.32.post2. FA2 = False]
    "-____-" Free license: http://github.com/unslothai/unsloth
    Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
    Unsloth: QLoRA and full finetuning all not selected. Switching to 16bit LoRA.

  9. sujianwei1 commented on Sep 3, 2025

    @sujianwei1

    It's the same even if I change to this version.
    🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning. 🦥 Unsloth Zoo will now patch everything to make training faster! ==((====))== Unsloth 2025.8.10: Fast Whisper patching. **Transformers: 4.55.3.** \\ /| Tesla T4. Num GPUs = 1. Max memory: 14.741 GB. Platform: Linux. O^O/ \_/ \ Torch: 2.8.0+cu126. CUDA: 7.5. CUDA Toolkit: 12.6. Triton: 3.4.0 \ / Bfloat16 = FALSE. FA [Xformers = 0.0.32.post2. FA2 = False] "-____-" Free license: http://github.com/unslothai/unsloth Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored! Unsloth: QLoRA and full finetuning all not selected. Switching to 16bit LoRA. unsloth/whisper-large-v3 does not have a padding token! Will use pad_token = <|endoftext|>.

  10. rsokolewicz commented on Nov 10, 2025

    @rsokolewicz

    pinning transformers worked for me as well. Since some folks in this thread claim it doesn't work, for completeness:

    replace the cell

    %%capture
    import os, re
    if "COLAB_" not in "".join(os.environ.keys()):
        !pip install unsloth
    else:
        # Do this only in Colab notebooks! Otherwise use pip install unsloth
        import torch; v = re.match(r"[0-9\.]{3,}", str(torch.__version__)).group(0)
        xformers = "xformers==" + ("0.0.32.post2" if v == "2.8.0" else "0.0.29.post3")
        !pip install --no-deps bitsandbytes accelerate {xformers} peft trl triton cut_cross_entropy unsloth_zoo
        !pip install sentencepiece protobuf "datasets>=3.4.1,<4.0.0" "huggingface_hub>=0.34.0" hf_transfer
        !pip install --no-deps unsloth
    !pip install transformers==4.56.2
    !pip install --no-deps trl==0.22.2
    !pip install librosa soundfile evaluate jiwer
    

    with

    %%capture
    import os, re
    if "COLAB_" not in "".join(os.environ.keys()):
        !pip install unsloth
    else:
        # Do this only in Colab notebooks! Otherwise use pip install unsloth
        import torch; v = re.match(r"[0-9\.]{3,}", str(torch.__version__)).group(0)
        xformers = "xformers==" + ("0.0.32.post2" if v == "2.8.0" else "0.0.29.post3")
        !pip install --no-deps bitsandbytes accelerate {xformers} peft trl triton cut_cross_entropy unsloth_zoo
        !pip install sentencepiece protobuf "datasets>=3.4.1,<4.0.0" "huggingface_hub>=0.34.0" hf_transfer
        !pip install --no-deps unsloth
    !pip install transformers==4.51.3,
    !pip install --no-deps trl==0.22.2
    !pip install librosa soundfile evaluate jiwer
    

    and don't forget to restart the instance, since python caches imports

  11. added
    fixed - pending confirmation
    on Nov 16, 2025
  12. mmathew23 commented on Nov 16, 2025

    @mmathew23
    Contributor

    Hi @rsokolewicz @VanshRana12 @sujianwei1 @csanadpoda @adi-lb-phoenix @fanalyaen this is now fixed in the latest unsloth and unsloth_zoo.

    pip install --force-reinstall --no-deps --upgrade unsloth unsloth_zoo

  13. danielhanchen commented on Jun 17, 2026

    @danielhanchen
    Member

    This issue should be fixed now - sorry on the delay - please update with uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir - if the issue is still there, please open another issue - appreciate it again!

  14. rsokolewicz commented on Jun 17, 2026

    @rsokolewicz

    thanks!

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 confirmationunsure bug?

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions