Skip to content

VRAM spikes after "LlamaForCausalLM does not accept 'num_items_in_batch'" #1801

Closed

Description

@RWTHEY

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.

Image

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

  1. danielhanchen commented on Feb 23, 2025

    @danielhanchen
    Member

    @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

  2. RWTHEY commented on Feb 23, 2025

    @RWTHEY
    Author

    @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.

  3. joshcx commented on Feb 25, 2025

    @joshcx

    Facing the same issue with transformers 4.49.0. Only occurs when running evaluations. I've temporarily set the following:

    import os
    os.environ["UNSLOTH_RETURN_LOGITS"] = "1"
    
    def preprocess_logits_for_metrics(logits, labels):
        #This is a workaround to avoid storing too many tensors that are not needed.
        pred_ids = torch.argmax(logits, dim=-1)
        return pred_ids, labels
    
    
    trainer = SFTTrainer(
        ...
        preprocess_logits_for_metrics=preprocess_logits_for_metrics
        ...
    )
    

    as mentioned here:
    #1548

  4. RWTHEY commented on Feb 26, 2025

    @RWTHEY
    Author

    @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.

    Image

    The following picture is without the eval_dataset, therefore only train_dataset and without the workaround:

    Image

    So this workaround doesn't seem to work for me.

  5. RWTHEY commented on Feb 26, 2025

    @RWTHEY
    Author

    Hey @danielhanchen , sorry for disturbing you again (maybe you are already trying to fix this).
    This issue also occurs for Qwen2.5-3b:

    Unsloth: Not an error, but Qwen2ForCausalLM 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

    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:

    import wandb
    import os
    import torch
    from unsloth import FastLanguageModel, is_bfloat16_supported, unsloth_train
    from datasets import load_dataset
    from trl import SFTTrainer
    from transformers import TrainingArguments, DataCollatorForSeq2Seq
    
    wandb.init(
        project="Qwen2.5-3b",
        config={
            XXX
        }
    )
    
    os.environ["UNSLOTH_RETURN_LOGITS"] = "1"
    
    def preprocess_logits_for_metrics(logits, labels):
        #This is a workaround to avoid storing too many tensors that are not needed.
        pred_ids = torch.argmax(logits, dim=-1)
        return pred_ids, labels
    
    
    max_seq_length = 16300  # Choose any! We auto support RoPE Scaling internally!
    dtype = None
    load_in_4bit = True  # Use 4bit quantization to reduce memory usage. Can be False.
    
    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name = r"C:\Users\path\to\qwen2.5",
        max_seq_length = max_seq_length,
        dtype = dtype,
        load_in_4bit = load_in_4bit
    )
    
    FastLanguageModel.for_training(model)
    
    model = FastLanguageModel.get_peft_model(
        model,
        r = 32,
        target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                          "gate_proj", "up_proj", "down_proj",],
        lora_alpha = 32,
        lora_dropout = 0, 
        bias = "none",  
        use_gradient_checkpointing = "unsloth", 
        random_state = 3407,
        use_rslora = False, 
        loftq_config = None, 
    )
    
    alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
    
    ### Instruction:
    {}
    
    ### Input:
    {}
    
    ### Response:
    {}"""
    
    EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
    def formatting_prompts_func(examples):
        instructions = examples["system"] # Structure of my data
        inputs       = examples["user"] # Structure of my data
        outputs      = examples["assistant"] # Structure of my data
        texts = []
        for instruction, input, output in zip(instructions, inputs, outputs):
            # Must add EOS_TOKEN, otherwise your generation will go on forever!
            text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
            texts.append(text)
        return { "text" : texts, }
    pass
    
    dataset = load_dataset("json", data_files="finished_qwen_format.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 = train_dataset.map(
        formatting_prompts_func,
        batched=True
    )
    
    test_dataset = test_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,
        # No data_collater = DataCollatorForSeq2Seq because it crashes then
        dataset_num_proc = 2,
        packing = False,
        preprocess_logits_for_metrics = preprocess_logits_for_metrics,
        args = TrainingArguments(
            per_device_train_batch_size = 2,
            per_device_eval_batch_size = 2,
            gradient_accumulation_steps = 4,
            warmup_steps = 10,
            num_train_epochs = 2,
            learning_rate = 2e-4,
            fp16 = not is_bfloat16_supported(),
            bf16 = is_bfloat16_supported(),
            logging_steps = 1,
            optim = "adamw_8bit",
            weight_decay = 0.05,
            lr_scheduler_type = "linear",
            seed = 3407,
            output_dir = "outputs",
            report_to = "wandb",
            eval_strategy = "steps",
            eval_steps = 50,
            save_strategy = "steps",
            save_steps = 300,
        ),
    )
    
    wandb.watch(model, log="all", log_freq=300)
    
    trainer_stats = unsloth_train(trainer)
    
    wandb.finish()
    model.save_pretrained_merged(r"C:\Users\path\to\model\storage\folder", tokenizer, save_method = "merged_16bit")

    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](file:///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 Qwen2 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](file:///C:/Users/XXX/.venv/Lib/site-packages/unsloth/models/llama.py:1277): UserWarning: expandable_segments not supported on this platform (Triggered internally at [C:\actions-runner\_work\pytorch\pytorch\pytorch\c10/cuda/CUDAAllocatorConfig.h:28](file:///C:/actions-runner/_work/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)
    13Qwen2ForCausalLM(
    14 (model): Qwen2Model(
    15    (embed_tokens): Embedding(151936, 2048, padding_idx=151654)
    16    (layers): ModuleList(
    17      (0-1): 2 x Qwen2DecoderLayer(
    18        (self_attn): Qwen2Attention(
    19          (q_proj): Linear4bit(in_features=2048, out_features=2048, bias=True)
    20          (k_proj): Linear4bit(in_features=2048, out_features=256, bias=True)
    21          (v_proj): Linear4bit(in_features=2048, out_features=256, bias=True)
    22          (o_proj): Linear4bit(in_features=2048, out_features=2048, bias=False)
    23          (rotary_emb): LlamaRotaryEmbedding()
    24        )
    25        (mlp): Qwen2MLP(
    26          (gate_proj): Linear4bit(in_features=2048, out_features=11008, bias=False)
    27          (up_proj): Linear4bit(in_features=2048, out_features=11008, bias=False)
    28          (down_proj): Linear4bit(in_features=11008, out_features=2048, bias=False)
    29          (act_fn): SiLU()
    30        )
    31        (input_layernorm): Qwen2RMSNorm((2048,), eps=1e-06)
    32        (post_attention_layernorm): Qwen2RMSNorm((2048,), eps=1e-06)
    33      )
    34      (2-3): 2 x Qwen2DecoderLayer(
    35        (self_attn): Qwen2Attention(
    36          (q_proj): Linear4bit(in_features=2048, out_features=2048, bias=True)
    37          (k_proj): Linear4bit(in_features=2048, out_features=256, bias=True)
    38 ...
    39    (norm): Qwen2RMSNorm((2048,), eps=1e-06)
    40    (rotary_emb): LlamaRotaryEmbedding()
    41  )
    42  (lm_head): Linear(in_features=2048, out_features=151936, bias=False)
    43 )
    44 Unsloth 2025.2.15 patched 36 layers with 36 QKV layers, 36 O layers and 36 MLP layers.
    45 Tokenizing train dataset (num_proc=2): 100%|██████████| 2732/2732 [00:09<00:00, 294.40 examples/s] 
    46 Tokenizing train dataset (num_proc=2): 100%|██████████| 2732/2732 [00:05<00:00, 473.33 examples/s] 
    47 Tokenizing eval dataset (num_proc=2): 100%|██████████| 684/684 [00:06<00:00, 99.00 examples/s] 
    48 Tokenizing eval dataset (num_proc=2): 100%|██████████| 684/684 [00:04<00:00, 147.05 examples/s]
    49 ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs = 1
    50    \\   /|    Num examples = 2,732 | Num Epochs = 2
    51 O^O/ \_/ \    Batch size per device = 2 | Gradient Accumulation steps = 4
    52  \        /    Total batch size = 8 | Total steps = 682
    53  "-____-"     Number of trainable parameters = 59,867,136
    54 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.
    55 Step | Training Loss | Validation Loss
    XX | XX | XX
    56 Unsloth: Not an error, but Qwen2ForCausalLM does not accept `num_items_in_batch`.
    57 Using gradient accumulation will be very slightly less accurate.
    58 Read more on gradient accumulation issues here: https://unsloth.ai/blog/gradient
  6. DevBerge commented on Feb 27, 2025

    @DevBerge

    @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.

    Image

  7. RWTHEY commented on Mar 1, 2025

    @RWTHEY
    Author

    @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.

  8. Kwonmoment commented on Mar 20, 2025

    @Kwonmoment

    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.

    if True:
        from unsloth import FastLanguageModel
        model, tokenizer = FastLanguageModel.from_pretrained(
            model_name = "C:/Users/user/Desktop/test/checkpoint-100", # YOUR MODEL YOU USED FOR TRAINING
            max_seq_length = 2048,
            dtype = None,
            load_in_4bit = True,
        )
        FastLanguageModel.for_inference(model) # Enable native 2x faster inference
    
    def evaluate_model(model, dataset):
        from torch.utils.data import DataLoader
        import torch
    
        device = "cuda" if torch.cuda.is_available() else "cpu"
        model.to(device)
        model.eval()
    
        dataloader = DataLoader(dataset, batch_size=4)
    
        total_loss = 0
        for batch in dataloader:
            inputs = tokenizer(batch["text"], return_tensors="pt", padding=True, truncation=True)
            inputs = {key: value.to(device) for key, value in inputs.items()}
    
            with torch.no_grad():
                outputs = model(**inputs, labels=inputs["input_ids"])
                total_loss += outputs.loss.item()
    
        avg_loss = total_loss / len(dataloader)
        print(f"Validation Loss: {avg_loss}")
    
    evaluate_model(model, valid_dataset)
    
  9. RWTHEY commented on Apr 2, 2025

    @RWTHEY
    Author

    @Kwonmoment I noticed that this issue only seems to happen if the per_device_eval_batch_size is bigger than 1. The VRAM doesn't spike if per_device_eval_batch_size = 1 (it then appears to react like shown by @DevBerge).

  10. abuchnick-aiola commented on Apr 4, 2025

    @abuchnick-aiola

    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 trl nor in unsloth, but in the base transformers package, which doesn't take into account the optimizations of the dataloader which happen in unsloath_train for 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.

  11. abuchnick-aiola commented on Apr 6, 2025

    @abuchnick-aiola

    What sort-of-fixed the problem for me, was adding the following to TrainingArguments:

    eval_accumulation_steps=4,
    

    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.

  12. abuchnick-aiola commented on Apr 19, 2025

    @abuchnick-aiola

    @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:

        # Define training arguments
        training_args = TrainingArguments(
            per_device_train_batch_size=args.batch_size,
            gradient_accumulation_steps=4,
            per_device_eval_batch_size=args.batch_size,  # Match training batch size
            eval_accumulation_steps=4,
            warmup_ratio=0.05,
            num_train_epochs=args.epochs,
            learning_rate=args.lr,
            fp16=not is_bfloat16_supported(),
            bf16=is_bfloat16_supported(),
            logging_steps=100,
            optim="adamw_8bit",
            weight_decay=args.weight_decay,
            lr_scheduler_type=args.lr_scheduler_type,
            seed=args.seed,
            output_dir=args.output_dir,
            logging_dir=os.path.join(args.output_dir, "logs"),
            save_strategy="epoch",
            eval_strategy="epoch",
            load_best_model_at_end=True,
            metric_for_best_model=args.metric_for_best_model,
            greater_is_better=args.greater_is_better,
            save_total_limit=3,
            remove_unused_columns=False,
            report_to="wandb" if args.wandb else "none",
            dataloader_num_workers=4,  # Parallel data loading
            dataloader_pin_memory=True,  # Speed up data transfer to GPU
            dataloader_persistent_workers=True,
            gradient_checkpointing=True,  # Save memory
            run_name=args.output_dir,
            group_by_length=args.group_by_length,
        )
    
        def _preprocess_logits_for_metrics(logits, labels):
            return logits[:, :, 32:34]
    
        trainer = SFTTrainer(
            model=model,
            train_dataset=train_dataset,
            eval_dataset={"validation": validation_dataset},  # Use validation dataset during training
            data_collator=data_collator,
            args=training_args,
            processing_class=tokenizer,
            compute_metrics=metrics_function,
            preprocess_logits_for_metrics=_preprocess_logits_for_metrics,
            callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
            dataset_text_field="text",
            max_seq_length=args.max_length,
        )

    I think that the following are the ones that led to the greatest improvements:

            dataloader_num_workers=4,  # Parallel data loading
            dataloader_pin_memory=True,  # Speed up data transfer to GPU
            dataloader_persistent_workers=True, # Reuse dataloader workers. Important for reducing I/O time.
            preprocess_logits_for_metrics=_preprocess_logits_for_metrics, # In my case, I only need 2 logits per each token, and since there's aggregation buffer that holds up the evaluation results until calling `compute_metrics`, it takes quite amount of memory and time to hold it all together. In my case - I simply disregarded whatever I don't need.

    With this configuration I'm able to run train and validation by using trainer.train() and testing by using trainer.predict() with this amount of samples:

    Dataset sizes - Train: 50854, Validation: 100, Test: 13700
    Starting training...
    ==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
       \\   /|    Num examples = 47,954 | Num Epochs = 3 | Total steps = 4,494
    O^O/ \_/ \    Batch size per device = 8 | Gradient accumulation steps = 4
    \        /    Data Parallel GPUs = 1 | Total batch size (8 x 4 x 1) = 32
     "-____-"     Trainable parameters = 4,884,480/86,315,904 (5.66% trained)
    

    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.

  13. grmelacz commented on Sep 15, 2025

    @grmelacz

    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:

    gradient_accumulation_steps = 4
    ...
    eval_accumulation_steps = 4,
    eval_strategy="steps",
    eval_steps=4,
    

    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_size to 2 actually fixed the Using gradient accumulation will be very slightly less accurate. warning that was displayed when set to 1.

    Other than this, most of the settings are based on Unsloth notebook defaults and only tweaked for my needs.

  14. sudarsun commented on Sep 27, 2025

    @sudarsun

    On an RTX 4090 Ti, I had to set up per_device_eval_batch_size=1 and per_device_train_batch_size=1; however, I could make it work when my eval_accumulation_steps and gradient_accumulation_steps were set to 8.

  15. self-assigned this
    on Oct 8, 2026
  16. danielhanchen commented on Oct 8, 2026

    @danielhanchen
    Member

    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_metrics or call trainer.predict(). The num_items_in_batch message 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions