[BUG] Memory usage explosion while using mlx_lm.lora
Describe the bug
When fine-tuning using mlx_lm.lora, memory usage explodes as iterations go, even though reported peak memory stays constant, for example:
Iter 80: Train loss 0.848, Learning Rate 5.000e-05, It/sec 2.028, Tokens/sec 2070.397, Trained Tokens 79811, Peak mem 8.303 GB
The memory usage is visible with activity monitor and macmon, it fills up available RAM and uses some swap after that.
It is most visible with 2048 max sequence length, but smaller sequence lengths also show this behavior, albeit at a slower scale.
To Reproduce
- Pre-process the dataset with:
from datasets import load_dataset
import json
dataset = load_dataset("HuggingFaceTB/smoltalk2_everyday_convs_think")
def format_example(example):
return {"text": example["text"]}
train_data = dataset["train"].map(format_example, remove_columns=dataset["train"].column_names)
with open("train.jsonl", "w") as f:
for row in train_data:
f.write(json.dumps(row) + "\n")
print(f"Wrote {len(train_data)} examples to train.jsonl")
- Finetune using lora:
mlx_lm.lora \
--model HuggingFaceTB/SmolLM3-3B-Base \
--train \
--data ./ \
--batch-size 1 \
--learning-rate 5e-5 \
--iters 1000 \
--num-layers 4 \
--adapter-path ./smollm3-finetuned --max-seq-length 2048
Expected behavior Memory usage should stay at reported peak memory, in this case 8 GB.
Desktop:
- OS Version: MacOS Tahoe 26.4
- Chip: Apple M2 Ultra
- Memory: 64 GB
- Version 0.31.1
This looks like it's already fixed upstream and just hasn't reached you yet. mlx-lm's trainer calls mx.clear_cache() every step once mx.get_cache_memory() crosses a threshold (default 0, so effectively every step), added in PR #986 back in March. The mechanism matches what you're seeing exactly, get_peak_memory() only tracks active allocations, not what MLX's caching allocator is holding onto for reuse, so the reported stat can stay flat while RSS climbs. Your mlx-lm 0.31.1 was tagged three days before that fix merged. Upgrading to 0.31.2 or later (current is 0.31.3) should resolve this without any code changes on your side.
Thanks for checking the issue, I'm closing since the previous comment should have perfectly answered it.
Thank you, indeed the issue is fixed in 0.31.3! I should have updated and checked again.