Repository navigation
Closed
Labels
fixed - pending confirmationFixed, waiting for confirmation from poster
Description
Hey there,
Worked on this quite a lot yesterday with the help of GPT-4, but I'm having some issues with errors similar to the following:
Traceback (most recent call last):
File "/mnt/c/Users/magda/OneDrive/Desktop/python_work/unsloth_finetuner.py", line 67, in <module>
trainer.train()
File "/home/harry/.local/lib/python3.10/site-packages/transformers/trainer.py", line 1537, in train
return inner_training_loop(
File "/home/harry/.local/lib/python3.10/site-packages/transformers/trainer.py", line 1854, in _inner_training_loop
tr_loss_step = self.training_step(model, inputs)
File "/home/harry/.local/lib/python3.10/site-packages/transformers/trainer.py", line 2744, in training_step
self.accelerator.backward(loss)
File "/home/harry/.local/lib/python3.10/site-packages/accelerate/accelerator.py", line 1903, in backward
self.scaler.scale(loss).backward(**kwargs)
File "/home/harry/.local/lib/python3.10/site-packages/torch/_tensor.py", line 492, in backward
torch.autograd.backward(
File "/home/harry/.local/lib/python3.10/site-packages/torch/autograd/__init__.py", line 251, in backward
Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
File "/home/harry/.local/lib/python3.10/site-packages/torch/autograd/function.py", line 288, in apply
return user_fn(self, *args)
File "/home/harry/.local/lib/python3.10/site-packages/torch/utils/checkpoint.py", line 288, in backward
torch.autograd.backward(outputs_with_grad, args_with_grad)
File "/home/harry/.local/lib/python3.10/site-packages/torch/autograd/__init__.py", line 251, in backward
Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
File "/home/harry/.local/lib/python3.10/site-packages/torch/autograd/function.py", line 288, in apply
return user_fn(self, *args)
File "/home/harry/.local/lib/python3.10/site-packages/torch/cuda/amp/autocast_mode.py", line 140, in decorate_bwd
return bwd(*args, **kwargs)
File "/home/harry/.local/lib/python3.10/site-packages/unsloth/kernels/fast_lora.py", line 291, in backward
dX = torch.matmul(dQ, QW.t(), out = X)
RuntimeError: Expected out tensor to have dtype c10::Half, but got float instead
I'm running an RTX 3090 locally, for the record--I want to say CUDA 118. Downgraded Pytorch to 2.1.0 as well. Here's what the script is looking like right now. This is my first time trying to locally finetune, so I'm not sure if the args are wrong, or what, but any advice would be very much appreciated.
from unsloth import FastLlamaModel, FastMistralModel
import torch
max_seq_length = 4096 # Can change to any number <= 4096
HAS_BFLOAT16 = torch.cuda.is_bf16_supported()
dtype = torch.bfloat16 if HAS_BFLOAT16 else torch.float16
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
# Load Llama model
model, tokenizer = FastLlamaModel.from_pretrained(
model_name = "unsloth/llama-2-7b", # Supports any llama model eg meta-llama/Llama-2-7b-hf
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
token = "hf...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)
# Do model patching and add fast LoRA weights
model = FastLlamaModel.get_peft_model(
model,
r = 16,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 16,
lora_dropout = 0, # Currently only supports dropout = 0
bias = "none", # Currently only supports bias = "none"
use_gradient_checkpointing = True,
random_state = 3407,
max_seq_length = max_seq_length,
)
from transformers import Trainer, TrainingArguments
from datasets import load_dataset
dataset = load_dataset('json', data_files='processed_data.json', split='train')
# Tokenize the dataset
def tokenize_and_prepare_labels(examples):
tokenized_inputs = tokenizer(examples['text'], padding='max_length', truncation=True, max_length=max_seq_length)
# Shift the tokenized inputs to the right for the labels
tokenized_inputs["labels"] = tokenized_inputs["input_ids"].copy()
return tokenized_inputs
tokenized_dataset = dataset.map(tokenize_and_prepare_labels, batched=True)
# Define training arguments
training_args = TrainingArguments(
output_dir='outputs',
num_train_epochs=3,
per_device_train_batch_size=8,
warmup_steps=500,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=10,
fp16=True, # Enable mixed precision
)
# Initialize Trainer with the entire tokenized dataset
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
eval_dataset=None # Set this to your evaluation dataset if you have one
)
print(f"Max sequence length: {max_seq_length}")
trainer.train()
print(f"Training done! Check outputs")
For the record, when I remove fp16 = True, it errors out a lot faster and gives a slight variation of the error:
RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != float
Metadata
Metadata
Assignees
Labels
fixed - pending confirmationFixed, waiting for confirmation from poster
Activity
danielhanchen commentedon Dec 21, 2023
@hrhdegenetrix Instead of
fp16 = True, since u have a RTX 3090 which supports bfloat16, replacefp16 = Truewithbf16 = Truehrhdegenetrix commentedon Dec 22, 2023
Thank you so much! That helped get me off the ground. Didn't seem to save (at least where I expected it to) but I'll figure that out later today. Before this is marked as close, could I get your help with this assertion error? I tried changing max sequence length to 8192, but wound up with this. Do I need to manually add a RoPE scaling dictionary as you mentioned to another user, or is there something else afoot here? Maybe I should try a different base model?
danielhanchen commentedon Dec 22, 2023
@hrhdegenetrix Ok that's weird - when you changed
max_seq_length = 8192did u put this in 2 places? Both inFastLlamaModel.from_pretrainedandFastLlamaModel.get_peft_modelYou should get the following warning message:
hrhdegenetrix commentedon Dec 22, 2023
Yeah it's a weird one! It looks like I've got max_seq_length in 2 places for sure. And I do get the warning message, but then I get the traceback like so:
danielhanchen commentedon Dec 23, 2023
@hrhdegenetrix Hmm I'll have to check my code on how I approached RoPE scaling - maybe I did it wrong oops.
For now, could it be possible for you to just try 4096 for now - I'll update Unsloth in a bit :)
danielhanchen commentedon Dec 25, 2023
@hrhdegenetrix Sorry on the delay - just updated Unsloth - would it be possible for you to update Unsloth and see if RoPE scaling works now? Thanks so much!
[-]Float problems?[/-][+]RoPE Scaling issues[/+]hrhdegenetrix commentedon Dec 29, 2023
Hey man! Merry Christmas and Happy New Year, thanks for working so hard during the holiday season. So, I updated Unsloth and then just to be sure I ended up doing a clean install of it. 4096 works, but 8192 gets hung up. You can see Map never completed; it just sat here looking like this with the GPU running but nothing happening for around an hour or so:
No error this time, but no progress beyond this point.
danielhanchen commentedon Dec 30, 2023
@hrhdegenetrix Hey early HNY! Hmm ok ok hm I'll do more checking - sorry my fixes didn't fix it :(
I'll have to manaully create some long context datasets and see why Unsloth is getting stuck
danielhanchen commentedon Dec 31, 2023
So I tried it with
max_seq_length=8192so RoPE Scaling of 2 on Llama-2-7b. I manually editted the Alpaca dataset by ensuring I see 8000 spaces ie, and sampling the first 1% of examples:Running the tokenizer on the first exampl ull get around 13,932 tokens, which is what we want (tokenizer will truncate this).
I ran the model, and it's super SLOW - the backward pass is notoriously taking loads of time - I'll have to check why, but it seems like the attention layer is the culprit since O(N^2) during the backward pass must really hurt Flash Attention.
Google Colab showing forward pass:

And the extremely painstakinly slow backward pass:

After a horribly 3 minutes and 36 seconds on bsz=2, ga=4, finally 1 step is completed... On 60 steps we need a crazy 3 hours:

My notebook: https://colab.research.google.com/drive/1TLI18PEeWXYR_4IeOx0wG-NvHYNBxdEW?usp=sharing
neru1234 commentedon Jul 3, 2024
Hi @danielhanchen
My gpu can't use bf16, but it looks like bf16 supported?
error:
Thanks
danielhanchen commentedon Jul 4, 2024
@neru1234 Set
fp16 = Trueandbf16 = Falsein the training argsFix CUDA_VISIBLE_DEVICES with vllm (unslothai#47)
Fix CUDA_VISIBLE_DEVICES with vllm (unslothai#47)
Fix CUDA_VISIBLE_DEVICES with vllm (unslothai#47)
Merge pull request unslothai#47 from unslothai/fix/add-jwt-dependency
Studio sd.cpp: --mmap for CPU renders on builds whose --mmap keeps th…
Studio sd.cpp: pin the prebuilt resynced with upstream master-1056 (u…