LoRA reference
mlx-optiq ships a LoRA trainer that reads its own per-layer sensitivity assignments and gives sensitive layers proportionally more adapter capacity. Output is PEFT-compatible (adapter_config.json + adapters.safetensors) plus an optiq_lora_config.json sidecar recording the rank each layer got. This page is the reference: every flag, the rank-scaling result, and how far each model stretches on a Mac.
Guides
- Fine-tune on your Mac: the whole path on one page.
- Build a training set from your files: the data formats and the Lab's dataset templates.
- LoRA SFT on Apple Silicon: the defaults, presets, and what to change when memory runs short.
- DPO on top of an SFT adapter: preference data, the DPO defaults, combining adapters.
- Compare tuned and base in the Arena.
- Quantize and serve the tuned model:
optiq lora export, serving and hot-swapping adapters. - Fine-tune a decision model.
- NEFTune and early stopping, and experiment logging.
- Gemma 4 specifics.
Every optiq lora train flag
$ optiq lora train MODEL --data DIR [OPTIONS]
MODEL is an OptiQ quant, as a Hugging Face repo id or a local folder.
| flag | default | what it does |
|---|---|---|
| --data DIR | required | Folder with train.jsonl and an optional valid.jsonl. |
| -o, --output PATH | ./optiq_lora_adapters | Where the adapter is written. |
| --method | sft | sft or dpo. |
| --rank | 8 | Base LoRA rank. With by_bits, layers kept at higher bits go above it. |
| --scale | 1.0 | Alpha as a multiple of rank (alpha = rank × scale). |
| --preset | none | Sets rank and alpha together: small (r=8, α=16), default (r=8, α=8), medium (r=16, α=16), large (r=32, α=32), xl (r=64, α=64), xxl (r=128, α=128). An explicit --rank or --scale still wins. |
| --rank-scaling | by_bits | by_bits, by_kl or constant; see below. |
| --dropout | 0.0 | LoRA dropout. |
| --num-layers | -1 (all) | Adapt only the last N blocks. Lower it on 9B and larger models if a full-depth backward hits Metal's resource limit. |
| --target-modules | all seven | q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj. |
| --adapt-experts | off | Also adapt a MoE model's expert pools; see tuning knobs. |
| --use-dora | off | DoRA instead of LoRA. |
| --iters | by epoch | Absolute step count. Omitted, the run is num_epochs × ceil(examples / batch) steps. |
| --num-epochs | 3 SFT, 1 DPO | Epochs over the data. Ignored when --iters is given. |
| --learning-rate, --lr | 2e-4 SFT, 5e-5 DPO | AdamW learning rate. |
| --batch-size | 1 | Sequences per step. |
| --grad-accumulation-steps | 1 | Steps per optimizer update, to keep the effective batch at batch size 1. |
| --grad-checkpoint / --no-grad-checkpoint | on | Recompute activations in the backward instead of keeping them. |
| --max-seq-length | 512 | Longest training example, in tokens. |
| --mask-prompt / --no-mask-prompt | on | SFT loss on the answer only. Needs messages or prompt/completion rows; bare text cannot be masked. |
| --all-turns | auto | Train every assistant turn of multi-turn data, not just the last. auto turns it on for multi-turn data; on / off force it. SFT only. |
| --fused-ce / --no-fused-ce | auto | Fused cut-cross-entropy for SFT. On by itself once the logit tensor (batch × seq × vocab × 2 bytes) passes 512 MB. |
| --dpo-beta | 0.1 | How hard DPO holds the model to its reference. |
| --mount-adapter PATH | none | DPO on top of an SFT adapter: the SFT adapter is mounted frozen and is part of the reference. The saved adapter holds only the DPO change. |
| --dpo-loss | sigmoid | sigmoid (standard DPO) or ipo, which keeps small preference sets from collapsing. |
| --dpo-label-smoothing | 0.0 | cDPO smoothing; 0.1 to 0.3 for small or noisy sets. Ignored with ipo. |
| --dpo-warmup-iters | max(10, iters / 10) | Linear warmup for DPO. |
| --dpo-lr-schedule | cosine | After warmup, cosine anneals to 10% of the peak; constant holds it. |
| --fused-dpo / --no-fused-dpo | off | Chunked log-probabilities for DPO, for long examples; see tuning knobs. |
| --neftune-noise-alpha | 0 (off) | NEFTune embedding noise during SFT; the paper suggests 5 to 15. |
| --early-stopping-patience | 0 (off) | Stop after N evaluations with no validation improvement and return the best adapter. Needs valid.jsonl. |
| --early-stopping-min-delta | 0.0 | Smallest drop in validation loss that counts as progress. |
| --val-batches | 25 | Validation batches per evaluation. |
| --steps-per-report | 10 | Steps between training-loss lines. |
| --steps-per-eval | 200 | Steps between validation passes. |
| --steps-per-save | 100 | Steps between checkpoints. |
| --report-to | off | wandb, swanlab, or both comma-separated. |
| --wandb-project | optiq-lora | W&B project name. |
| --decision | off | Give a plain Qwen-family model a new decision head and train it with the LoRA. A model that already has a head is detected without the flag. |
| --head-lr | 3e-4 | Learning rate for the decision head. |
| --head-warmup-steps | 0 | Train a new decision head alone first, with the backbone frozen. |
| --vision | auto | Image+text LoRA on a quant with a vision sidecar; on by itself when the model carries one. The vision tower stays frozen. |
Two model types change some defaults. A decision model trains 200 steps unless told otherwise, at a learning rate of 1e-4, with 4 accumulation steps and a maximum length of at least 4,096 tokens. An image+text LoRA uses a learning rate of 5e-5 and a scale of 8 when you leave those flags unset, because the text learning rate collapses a vision LoRA.
Sensitivity-aware rank scaling
--rank-scaling by_bits (default) gives each layer an adapter rank proportional to its quantization bit-width. With --rank 8:
- Layers mlx-optiq quantized at 4-bit get rank 8.
- Layers mlx-optiq quantized at 8-bit get rank 16.
Head-to-head on a 6-category logical-puzzles reasoning dataset (Qwen3.5-4B-OptiQ-4bit, 1 epoch over 200 training samples, 100-sample test split):
| Config | Trainable params | Test accuracy |
|---|---|---|
| Constant rank-8 | 11.58 M | 27 % |
| by_bits (rank 8 / 16) | 13.49 M (+16%) | 35 % |
| Constant rank-16 | 22.20 M (+92%) | 36 % |
by_bits matches constant rank-16 on accuracy (35% vs 36%, within noise at n=100) using 39% fewer trainable parameters. Versus constant rank-8 at almost matched param budget, by_bits is +8 absolute accuracy points. Full per-category breakdown in the sensitivity-aware LoRA blog post.
Other scaling modes:
# Constant rank (matches Unsloth / PEFT default behaviour) $ optiq lora train ... --rank-scaling constant # Scale by raw KL sensitivity (more aggressive than by_bits) $ optiq lora train ... --rank-scaling by_kl
optiq lora info ./my_adapter prints the rank each layer got.
Training-ceiling map
Sequence length is what fills memory. All figures are measured at the system-default GPU memory limit (iogpu.wired_limit_mb=0), batch 1, with --grad-checkpoint.
With the default recipe (all layers, all seven projections)
| context | SFT step | SFT peak | DPO step (--fused-dpo) | DPO peak |
|---|---|---|---|---|
| 2048 | 2.8 s | 7.7 GB | 29 s | 8.7 GB |
| 4096 | 6.7 s | 11.4 GB | 144 s | 10.9 GB |
| 8192 | 45 s | 19.9 GB | 216 s | 17.3 GB |
| context | SFT step | SFT peak |
|---|---|---|
| 2048 | 26.3 s | 8.72 GB |
| 4096 | 55.6 s | 11.90 GB (14.06 GB without the fused loss) |
| 8192 | ~125 s | 14.41 GB |
Peak memory carries over between Macs closely; step time does not. The base M4 runs 8 to 9 times slower than the M3 Max on the same run, so plan capacity from these figures, not throughput. Step time grows faster than context (attention is O(seq²), and DPO pays it across four forward passes), so 4k is the comfortable working point and 8k is for when you need it.
Per model, with a lighter recipe
Longest sequence that trains on a 36 GB Mac when only the last 16 blocks are adapted (--num-layers 16), on the query and value projections only (--target-modules q_proj,v_proj), at rank 8 with by_bits. The default recipe adapts about three times as many LoRA modules, which lowers these ceilings to match; pass the two flags above to reach them.
| Model | Longest sequence | Peak memory | Tokens/sec |
|---|---|---|---|
| Qwen3.5-0.8B | 2,800 | 23.4 GB | 29.2 |
| Qwen3.5-2B | 2,400 | 19.3 GB | 38.3 |
| Qwen3.5-4B | 1,600 | 24.8 GB | 19.1 |
| Qwen3.5-9B | 1,400 | 25.4 GB | 21.6 |
| Qwen3.5-27B / Qwen3.6-27B | 512 | 27.7 GB | 11.4 |
| Qwen3.5-35B-A3B / Qwen3.6-35B-A3B | 128 | 25.3 GB | 32.2 |
| gemma-4-e2b-it | 2,400 | 22 GB | ~28 |
| gemma-4-e4b-it | 1,800 | 24 GB | ~22 |
| gemma-4-26B-A4B-it | 512 | 27.6 GB | 22.2 |
| gemma-4-31B-it | 32 | 21.4 GB | 30.9 |
The 35B-A3B MoE caps at 128 tokens because of per-expert memory overhead, but trains about three times faster per step than the dense 27B because only 3B parameters are active. The dense Gemma-4 31B has almost no room for sequence length because of its large embedding and vocabulary, so on a 36 GB Mac it is a model to serve rather than to train; the 26B-A4B fits longer sequences at the same memory. MiniCPM5-1B trains at 2,048 tokens on a 24 GB Mac with the default recipe, every block and all seven projections.
Tuning knobs you rarely need
At long context the full [seq, vocab] logit tensor is what runs out first. The fused cut-cross-entropy computes the LM-head loss in chunks so that tensor is never materialized, with the same gradients; it switches on once the tensor would pass 512 MB, so a 248k-vocab model uses it from 4k while a 32k-vocab one stays on the plain path even at 8k. DPO builds those logits four times per step (policy and reference, chosen and rejected), so on a 24 GB Mac its plain path runs out around 4k; --fused-dpo applies the same chunking, costs no step time, and its peak does not grow with the cap. It is opt-in because the break point depends on the Mac.
| flag / env | default | what it does |
|---|---|---|
| --adapt-experts | off | Adapt a MoE model's expert pools. Every expert gets its own LoRA, so the adapter grows by the expert count, on a 256-expert model that is 128×, a 1.2 B-parameter adapter at r=8. Attention projections are adapted either way. |
| OPTIQ_FLASH_ATTN | auto | auto uses MLX's fused SDPA whenever its [B, Hq, T, T] score tensor fits a memory budget, and a tiled FlashAttention-2 backward otherwise. always / never force it. |
| OPTIQ_FLASH_ATTN_BUDGET_GB | 25% of wired limit | How much of Metal's wired limit stock SDPA's scores may occupy before the tiled backward takes over. |
| OPTIQ_FLASH_BLOCK | 128 | Query-block size for the tiled backward. Peak memory scales with it; step time does not. |
| OPTIQ_FUSED_CE | auto | Fused cut-cross-entropy for the SFT LM head; 0 / 1 force it, like --no-fused-ce / --fused-ce. |
| --fused-dpo, OPTIQ_FUSED_DPO | off | The same chunked head for DPO's four log-probability passes. Needed beyond ~4k on a 24 GB Mac. |
[B, Hq, T, T] score tensor would not fit in memory. Same math, ~13× faster DPO at 4k. See the changelog.