Repository navigation
Description
I'm finetuning Llama 70b 4 bit on a dataset of blog posts, with max post length = 4000 tokens. The training data has ~1,600 posts, and 102 posts for validation.
The whole training process took around 3 hours for 4 epochs (1600 steps in total, with evaluation at every 100 steps).
After training, I run inference on the validation set (102 posts), but it is pretty slow.
Inference speed:
Batch 1: 323 tokens in 51.71 sec (6.25 tokens/sec)
Batch 2: 1063 tokens in 288.29 sec (3.69 tokens/sec)
Batch 3: 1122 tokens in 296.92 sec (3.78 tokens/sec)
Batch 4: 4675 tokens in 1888.87 sec (2.48 tokens/sec)
Batch 5: 626 tokens in 113.23 sec (5.53 tokens/sec)
Is this expected? I'm attaching my training and inference scripts below if that helps.
-
Did you update?
pip install --upgrade unsloth unsloth_zoo
Yes -
ColaborKaggleor local / cloud
Local/cloud -
Number GPUs used, use
nvidia-smi
NVIDIA A100-SXM4-80GB. Num GPUs = 1 -
Which notebook? Please link!
train.py:
import argparse
import glob
import os
from typing import Optional
# unsloth should be imported first before trl, peft... in order to be optimized
from unsloth import FastLanguageModel, FastModel, UnslothTrainingArguments
from datasets import load_dataset
from trl import SFTTrainer
from dotenv import load_dotenv
import wandb
load_dotenv()
MODEL_NAME = os.getenv("MODEL_NAME")
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "outputs")
HF_LORA_REPO = os.getenv("HF_LORA_REPO")
HF_FINAL_REPO = os.getenv("HF_FINAL_REPO")
WANDB_PROJECT = os.getenv("WANDB_PROJECT")
WANDB_RUN_ID = os.getenv("WANDB_RUN_ID")
WANDB_RESUME = os.getenv("WANDB_RESUME")
wandb.init(
project=WANDB_PROJECT,
id=WANDB_RUN_ID,
resume=WANDB_RESUME or False,
)
def latest_checkpoint(output_dir: str) -> Optional[str]:
"""Return the newest checkpoint folder inside `output_dir`, or None."""
ckpts = sorted(
glob.glob(os.path.join(output_dir, "checkpoint-*")),
key=lambda p: int(p.split("-")[-1]),
reverse=True,
)
return ckpts[0] if ckpts else None
def build_trainer(resume: Optional[str] = None) -> SFTTrainer:
max_seq_length = 4096
# Load 4-bit base
model, tokenizer = FastModel.from_pretrained(
MODEL_NAME,
load_in_4bit=True, # QLoRA
full_finetuning=False, # LoRA-only
max_seq_length=max_seq_length,
)
# Attach LoRA adapters
model = FastLanguageModel.get_peft_model(
model,
r=64,
target_modules=[
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
],
lora_dropout=0.0,
bias="none",
use_gradient_checkpointing="unsloth",
use_rslora=True,
cut_cross_entropy=True,
)
# Load dataset
train_dataset = load_dataset(
"json",
data_files="../data/training_data_before_2025.jsonl"
)["train"]
eval_dataset = load_dataset(
"json",
data_files="../data/val_data_2025_onward.jsonl"
)["train"]
# Training arguments
training_args = UnslothTrainingArguments(
per_device_train_batch_size=1, # micro-batch
gradient_accumulation_steps=4, # effective batch = 4
num_train_epochs=4, # 2 past + 2 more
max_seq_length=max_seq_length,
learning_rate=2e-5, # lower LR for continued SFT
embedding_learning_rate=3e-6,
lr_scheduler_type="cosine",
warmup_ratio=0.1,
weight_decay=0.0,
optim="adamw_8bit",
bf16=True,
logging_steps=1,
save_steps=200,
seed=3407,
output_dir=OUTPUT_DIR,
report_to="wandb",
run_name=WANDB_PROJECT,
eval_strategy="steps", # or "epoch"
eval_steps=100,
)
# Build trainer
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
dataset_text_field="text",
dataset_num_proc=12,
args=training_args,
)
# If resuming, HF will restore optimizer/scheduler/etc internally.
if resume:
print(f"👉 Resuming from checkpoint: {resume}")
else:
print("👉 Starting a fresh run")
return trainer
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--resume",
type=str,
default=None,
help="Path to a specific checkpoint to resume from "
"(defaults to the latest in outputs/)",
)
args = parser.parse_args()
resume_ckpt = (
args.resume
if args.resume
else latest_checkpoint(OUTPUT_DIR)
)
trainer = build_trainer(resume=resume_ckpt)
trainer.train(resume_from_checkpoint=resume_ckpt)
if __name__ == "__main__":
main()
inference.py:
import argparse
import json
import gc
import time
from tqdm import tqdm
from unsloth import FastLanguageModel
import torch
BATCH_SIZE = 2
parser = argparse.ArgumentParser()
parser.add_argument("checkpoint_dir")
parser.add_argument("output_path")
args = parser.parse_args()
model, tokenizer = FastLanguageModel.from_pretrained(args.checkpoint_dir)
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
model.eval()
with open('../data/val_data_2025_onward.jsonl', 'r') as f:
posts = [json.loads(line)['text'] for line in f]
prompts = []
for post in posts:
content_marker = '### Content: \n'
content_start_idx = post.find(content_marker) + len(content_marker)
first_paragraph_end = post.find('\n', content_start_idx) + 1
prompts.append(post[:first_paragraph_end])
results = []
for i in tqdm(range(0, len(prompts), BATCH_SIZE)):
batch_prompts = prompts[i:i + BATCH_SIZE]
inputs = tokenizer(batch_prompts, return_tensors='pt',
padding=True, truncation=True).to('cuda')
# Track time and token count
start_time = time.time()
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=4000)
end_time = time.time()
decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)
results.extend(decoded)
# Token/sec calculation
generated_tokens = sum(len(tokenizer.encode(d)) for d in decoded)
elapsed_time = end_time - start_time
throughput = generated_tokens / elapsed_time if elapsed_time > 0 else float('inf')
print(f"Batch {i//BATCH_SIZE + 1}: {generated_tokens} tokens in {elapsed_time:.2f} sec "
f"({throughput:.2f} tokens/sec)")
del inputs, outputs
torch.cuda.empty_cache()
gc.collect()
with open(args.output_path, 'w') as out_file:
for line in results:
json.dump({"text": line.strip()}, out_file)
out_file.write('\n')
Unsloth log:
🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
🦥 Unsloth Zoo will now patch everything to make training faster!
==((====))== Unsloth 2025.6.3: Fast Llama patching. Transformers: 4.52.4.
\\ /| NVIDIA A100-SXM4-80GB. Num GPUs = 1. Max memory: 79.254 GB. Platform: Linux.
O^O/ \_/ \ Torch: 2.7.0+cu126. CUDA: 8.0. CUDA Toolkit: 12.6. Triton: 3.3.0
\ / Bfloat16 = TRUE. FA [Xformers = 0.0.30. FA2 = False]
"-____-" Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
Loading checkpoint shards: 100%|████████████████████████████████████████████████████████████████████████████████| 6/6 [00:06<00:00, 1.06s/it]
Unsloth 2025.6.3 patched 80 layers with 80 QKV layers, 80 O layers and 80 MLP layers.
-
Which Unsloth version, TRL version, transformers version, PyTorch version?
unsloth==2025.6.3
trl==0.19.0
transformers==4.52.4
torch==2.7.0 -
Which trainer?
SFTTrainer,GRPOTraineretc```pythonPut Minimal code to reproduce error here
SFTTrainer
Activity
shimmyshimmer commentedon Jul 2, 2025
@duc-ph inference using Unsloth or vLLM or native transformers?
duc-ph commentedon Jul 3, 2025
@shimmyshimmer from the inference code above I think I'm using Unsloth:
Decode small 4bit batches with the NF4 GEMV instead of dequantizing e…