Repository navigation
Description
Hello there,
I am new to all of this and I am currently trying to fine-tune the unsloth/phi-4 model (testing the code with a smaller set right now, so don't care about the Epochs).
I need to do this for my master thesis.
Problem
Somehow after a few minutes I get the information Unsloth: Not an error, but LlamaForCausalLM 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 .
Straight after the message, the VRAM usage spikes and a few minutes later, the Error occurs that it is not possible to allocate the needed VRAM.
I already use the unsloth_train(trainer) but the message still occurs.
Following the code (I use it in jypter and load it step by step):
import wandb
from unsloth import FastLanguageModel, is_bfloat16_supported, unsloth_train
import torch
from unsloth.chat_templates import get_chat_template, standardize_sharegpt. train_on_responses_only
from trl import SFTTrainer
from transformers import TrainingArguments, DataCollatorForSeq2Seq
from datasets import load_dataset
wandb.init(
project="Test_Run",
config={
"learning_rate": 2e-4,
"batch_size": 2,
"architecture": r"C:\Users\path\to\model",
}
)
max_seq_length = 16300
load_in_4bit = True
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = r"C:\Users\path\to\model",
max_seq_length = max_seq_length,
load_in_4bit = load_in_4bit
)
FastLanguageModel.for_training(model)
model = FastLanguageModel.get_peft_model(
model,
r = 16, # 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 = 16,
lora_dropout = 0,
bias = "none",
use_gradient_checkpointing = "unsloth",
random_state = 3407,
use_rslora = False,
loftq_config = None,
)
tokenizer = get_chat_template(
tokenizer,
chat_template = "phi-4",
)
def formatting_prompts_func(examples):
convos = examples["conversations"]
texts = [
tokenizer.apply_chat_template(
convo, tokenize = False, add_generation_prompt = False
)
for convo in convos
]
return { "text" : texts, }
pass
dataset = load_dataset("json", data_files="my_dataset.json", split="train")
split_dataset = dataset.train_test_split(test_size=0.2, seed=3407)
train_dataset = split_dataset['train']
test_dataset = split_dataset['test']
train_dataset = standardize_sharegpt(train_dataset)
train_dataset = dataset.map(
formatting_prompts_func,
batched=True
)
test_dataset = standardize_sharegpt(test_dataset)
test_dataset = dataset.map(
formatting_prompts_func,
batched=True
)
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
eval_dataset = test_dataset,
train_dataset = train_dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), # Comment out, if training on user and system prompt as well
dataset_num_proc = 2,
packing = False, # Can make training 5x faster for short sequences.
args = TrainingArguments(
per_device_train_batch_size = 2,
per_device_eval_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 2,
# num_train_epochs = 1, # Set this for 1 full training run.
max_steps = 30,
learning_rate = 2e-4,
fp16 = not is_bfloat16_supported(),
bf16 = is_bfloat16_supported(),
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
output_dir = "outputs",
report_to = "wandb",
eval_strategy = "steps",
eval_steps = 1,
save_strategy = "steps",
save_steps = 5,
),
)
wandb.watch(model, log="all", log_freq=1)
trainer = train_on_responses_only(
trainer,
instruction_part="<|im_start|>user<|im_sep|>",
response_part="<|im_start|>assistant<|im_sep|>",
)
# trainer_stats = trainer.train()
trainer_stats = unsloth_train(trainer)
gpu_memory = torch.cuda.memory_allocated() / (1024 ** 3)
wandb.log({"gpu_memory_used": gpu_memory})
Output:
1 🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
2 c:\Users\XXX\.venv\Lib\site-packages\tqdm\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
3 from .autonotebook import tqdm as notebook_tqdm
4 🦥 Unsloth Zoo will now patch everything to make training faster!
5 ==((====))== Unsloth 2025.2.15: Fast Llama patching. Transformers: 4.49.0.
6 \\ /| GPU: NVIDIA GeForce RTX 4080 SUPER. Max memory: 15.992 GB. Platform: Windows.
7 O^O/ \_/ \ Torch: 2.6.0+cu124. CUDA: 8.9. CUDA Toolkit: 12.4. Triton: 3.1.0
8 \ / Bfloat16 = TRUE. FA [Xformers = 0.0.29.post3. FA2 = False]
9 "-____-" Free Apache license: http://github.com/unslothai/unsloth
10 Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
11 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\llama.py:1277: UserWarning: expandable_segments not supported on this platform (Triggered internally at C:\XXX\pytorch\pytorch\pytorch\c10/cuda/CUDAAllocatorConfig.h:28.)
12 self.register_buffer("cos_cached", emb.cos().to(dtype=dtype, device=device, non_blocking=True), persistent=False)
13 Loading checkpoint shards: 67%|██████▋ | 2/3 [00:03<00:01, 1.80s/it]
14 Unsloth 2025.2.15 patched 40 layers with 40 QKV layers, 40 O layers and 40 MLP layers.
15 Tokenizing train dataset (num_proc=2): 0%| | 0/52 [00:00<?, ? examples/s]
16 Tokenizing train dataset (num_proc=2): 100%|██████████| 52/52 [00:04<00:00, 11.61 examples/s]
17 Tokenizing train dataset (num_proc=2): 0%| | 0/52 [00:00<?, ? examples/s]
18 Tokenizing train dataset (num_proc=2): 100%|██████████| 52/52 [00:04<00:00, 11.57 examples/s]
19 Map: 100%|██████████| 52/52 [00:00<00:00, 2400.60 examples/s]
20 Map: 100%|██████████| 52/52 [00:00<00:00, 3062.35 examples/s]
21 ==((====))== Unsloth - 2x faster free finetuning | Num GPUs = 1
22 \\ /| Num examples = 52 | Num Epochs = 5
23 O^O/ \_/ \ Batch size per device = 2 | Gradient Accumulation steps = 4
24 \ / Total batch size = 8 | Total steps = 30
25 "-____-" Number of trainable parameters = 65,536,000
26 wandb: WARNING The `run_name` is currently set to the same value as `TrainingArguments.output_dir`. If this was not intended, please specify a different run name by setting the `TrainingArguments.run_name` parameter.
**27 Unsloth: Not an error, but LlamaForCausalLM does not accept `num_items_in_batch`.
28 Using gradient accumulation will be very slightly less accurate.
29 Read more on gradient accumulation issues here: https://unsloth.ai/blog/gradient**
30 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\_utils.py:592: SyntaxWarning: invalid escape sequence '\.'
31 source = re.sub("([^\.])nn\.", r"\1torch.nn.", source)
32 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\_utils.py:855: SyntaxWarning: invalid escape sequence '\)'
33 "self.rotary_emb = .+?\)", function,
34 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\_utils.py:955: SyntaxWarning: invalid escape sequence '\)'
35 "self.rotary_emb = .+?\)", function,
36 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\llama.py:1891: SyntaxWarning: invalid escape sequence '\.'
37 start = re.search('logger\.info\([\"\'].+?Running training', inner_training_loop).span(0)[0]
38 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\llama.py:1894: SyntaxWarning: invalid escape sequence '\s'
39 spaces = re.search('\n([\s\t]{1,})', original_debug).group(0)[1:]
40 c:\Users\XXX\.venv\Lib\site-packages\unsloth\models\llama.py:1895: SyntaxWarning: invalid escape sequence '\s'
41 front_spaces = re.match('([\s\t]{1,})', inner_training_loop).group(0)
I have interrupted the run after this.
I would be very grateful for some help! 🥰

Activity
danielhanchen commentedon Feb 23, 2025
@Erland366 Would it be possible to fix the syntax errors - thanks :))
Also @Erland366 could you confirm if 4.49.0 transformers still functions ok? I thought it works ok
RWTHEY commentedon Feb 23, 2025
@danielhanchen I tried again without the eval_dataset and save_strategy/save_steps and it works fine.
So the problem seems to be with the eval_dataset somehow.
The syntaxWarnings are because of my interruption I guess. So I think these SyntaxWarnings are no faults in your code, I guess.
joshcx commentedon Feb 25, 2025
Facing the same issue with transformers 4.49.0. Only occurs when running evaluations. I've temporarily set the following:
as mentioned here:
#1548
RWTHEY commentedon Feb 26, 2025
@joshcx Thank you for your answer. But the workaround doesn't seem to work for me.
When implementing this into my code, the usage of my VRAM spikes immediately without waiting for any error message, as shown in the picture. For your information, I am trying it with Qwen2.5-3b, which should not spike like this at all while training.
The following picture is without the eval_dataset, therefore only train_dataset and without the workaround:
So this workaround doesn't seem to work for me.
RWTHEY commentedon Feb 26, 2025
Hey @danielhanchen , sorry for disturbing you again (maybe you are already trying to fix this).
This issue also occurs for Qwen2.5-3b:
Like I said, the workaround doesn't work and just let's my GPU spike immediately after loading the model.
I would be very grateful if there would be another solution to this or an update 🥰
This is my code (I have it in a jypter notebook) for the two screenshots of my GPU-Usage above:
Output:
DevBerge commentedon Feb 27, 2025
@RWTHEY This happens when setting eval on llama models too.
Unsloth: Not an error, but LlamaForCausalLM 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
Currently using Unsloth Version: 2025.2.15, transformers Version: 4.49.0 and Pytorch Version: 2.6.0+cu124.
I've gotten OOM errors from this before if the eval batch size is too large for available VRAM. Strangely my wandb metrics seem to show a drop in memory allocation when the "LlamaForCausalLM does not accept
num_items_in_batch." occurs as evaluation is initiated.RWTHEY commentedon Mar 1, 2025
@DevBerge There was one time when it worked for me with the eval_dataset and I had the same experience as you have had with the drop. But at least it was running.
When I wanted to run the exact same code another time, there was the spike again. No clue what was different since I just ran it again to test.
Btw. I am using the exact same versions of Unsloth, Transformers and Pytorch as you are.
Kwonmoment commentedon Mar 20, 2025
Is the issue fixed now?
I have the same issue. I got a hint from the comment above, and when I loaded the saved model and calculated the Evaluation separately, I confirmed that the GPU temperature and power consumption W increased.
However, the issue only occurred on the A100 80GB server, and did not occur on my local PC with the 4080 super.
The evaluation was performed separately using the code below.
RWTHEY commentedon Apr 2, 2025
@Kwonmoment I noticed that this issue only seems to happen if the
per_device_eval_batch_sizeis bigger than 1. The VRAM doesn't spike ifper_device_eval_batch_size = 1(it then appears to react like shown by @DevBerge).abuchnick-aiola commentedon Apr 4, 2025
I'm running into this as well, when trying to finetune SmolLM2-135M.
@danielhanchen I think it's related to the fact that the validation phase is not implemented in
trlnor inunsloth, but in the basetransformerspackage, which doesn't take into account the optimizations of thedataloaderwhich happen inunsloath_trainfor example. It really feels like the validation is happening not using batching, as I can see that the GPU is idle (GPU utilization is 0) for a lot of time, although memory is allocated on it, so probably we spend a lot of time in I/O operations. What's your opinion?I'll try using my custom dataloader for evaluation and will update here again.
abuchnick-aiola commentedon Apr 6, 2025
What sort-of-fixed the problem for me, was adding the following to TrainingArguments:
With this configuration, I'm able to run evaluation using the same batch size as in training, and nothing freezes for too long.
I still wish this would have worked more fluently and quickly, but it's better than the previous freezing glitches I had.
BTW, the warning of
Unsloth: Not an error, but LlamaForCausalLM does not accept "num_items_in_batch"...isn't related to this issue, but it's some parameter passed to the model stub that is precompiled by unsloth. I didn't fully understand it's meaning as it held a number of items which didn't make any sense with my datasets, so I elegantly disregarded it.abuchnick-aiola commentedon Apr 19, 2025
@RWTHEY @danielhanchen I experimented with it A LOT, so to be honest- I'm not 100% sure what fixed it, maybe it's a voodoo combination of everything, but here is my configuration:
I think that the following are the ones that led to the greatest improvements:
With this configuration I'm able to run train and validation by using
trainer.train()and testing by usingtrainer.predict()with this amount of samples:With nicer utilization of the GPU (steady around 50%), low VRAM usage (3 GB) and I finish e2e fine-tuning in around 1.5 hours on a single A40.
grmelacz commentedon Sep 15, 2025
Hi everyone, I have fixed the problem only by applying the workaround as commented by @joshcx in #1801 (comment).
Other config values related to validation that I have set are:
Both the training and validation loss is reported normally and the OOM error is not triggered.
Note that in my case setting
per_device_train_batch_sizeto2actually fixed the Using gradient accumulation will be very slightly less accurate. warning that was displayed when set to1.Other than this, most of the settings are based on Unsloth notebook defaults and only tweaked for my needs.
sudarsun commentedon Sep 27, 2025
On an RTX 4090 Ti, I had to set up
per_device_eval_batch_size=1andper_device_train_batch_size=1; however, I could make it work when myeval_accumulation_stepsandgradient_accumulation_stepswere set to8.danielhanchen commentedon Oct 8, 2026
Fixed! Sorry on the delay. Evaluation was building the full vocabulary logits for every eval batch even when only the loss was needed, so eval used far more VRAM than training (on a 0.5B model with ~7k token rows, eval peaked at 13 GB versus 1.5 GB per training step). #13065 keeps loss-only evaluation on the same fused, memory-saving loss path as training, so eval now stays at about the training step's memory (1.4 GB in the same setup). Logits are still produced when you pass
compute_metricsor calltrainer.predict(). Thenum_items_in_batchmessage was unrelated and no longer shows up during eval.To update:
uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir(if it's not in the current release yet it'll be in the next one). Reopen if it still happens.