mlx-optiq
Fine-tuning · Reference

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

Every optiq lora train flag

terminalbash
$ optiq lora train MODEL --data DIR [OPTIONS]

MODEL is an OptiQ quant, as a Hugging Face repo id or a local folder.

flagdefaultwhat it does
--data DIRrequiredFolder with train.jsonl and an optional valid.jsonl.
-o, --output PATH./optiq_lora_adaptersWhere the adapter is written.
--methodsftsft or dpo.
--rank8Base LoRA rank. With by_bits, layers kept at higher bits go above it.
--scale1.0Alpha as a multiple of rank (alpha = rank × scale).
--presetnoneSets 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-scalingby_bitsby_bits, by_kl or constant; see below.
--dropout0.0LoRA 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-modulesall sevenq_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj.
--adapt-expertsoffAlso adapt a MoE model's expert pools; see tuning knobs.
--use-doraoffDoRA instead of LoRA.
--itersby epochAbsolute step count. Omitted, the run is num_epochs × ceil(examples / batch) steps.
--num-epochs3 SFT, 1 DPOEpochs over the data. Ignored when --iters is given.
--learning-rate, --lr2e-4 SFT, 5e-5 DPOAdamW learning rate.
--batch-size1Sequences per step.
--grad-accumulation-steps1Steps per optimizer update, to keep the effective batch at batch size 1.
--grad-checkpoint / --no-grad-checkpointonRecompute activations in the backward instead of keeping them.
--max-seq-length512Longest training example, in tokens.
--mask-prompt / --no-mask-promptonSFT loss on the answer only. Needs messages or prompt/completion rows; bare text cannot be masked.
--all-turnsautoTrain 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-ceautoFused cut-cross-entropy for SFT. On by itself once the logit tensor (batch × seq × vocab × 2 bytes) passes 512 MB.
--dpo-beta0.1How hard DPO holds the model to its reference.
--mount-adapter PATHnoneDPO 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-losssigmoidsigmoid (standard DPO) or ipo, which keeps small preference sets from collapsing.
--dpo-label-smoothing0.0cDPO smoothing; 0.1 to 0.3 for small or noisy sets. Ignored with ipo.
--dpo-warmup-itersmax(10, iters / 10)Linear warmup for DPO.
--dpo-lr-schedulecosineAfter warmup, cosine anneals to 10% of the peak; constant holds it.
--fused-dpo / --no-fused-dpooffChunked log-probabilities for DPO, for long examples; see tuning knobs.
--neftune-noise-alpha0 (off)NEFTune embedding noise during SFT; the paper suggests 5 to 15.
--early-stopping-patience0 (off)Stop after N evaluations with no validation improvement and return the best adapter. Needs valid.jsonl.
--early-stopping-min-delta0.0Smallest drop in validation loss that counts as progress.
--val-batches25Validation batches per evaluation.
--steps-per-report10Steps between training-loss lines.
--steps-per-eval200Steps between validation passes.
--steps-per-save100Steps between checkpoints.
--report-tooffwandb, swanlab, or both comma-separated.
--wandb-projectoptiq-loraW&B project name.
--decisionoffGive 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-lr3e-4Learning rate for the decision head.
--head-warmup-steps0Train a new decision head alone first, with the backbone frozen.
--visionautoImage+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):

ConfigTrainable paramsTest accuracy
Constant rank-811.58 M27 %
by_bits (rank 8 / 16)13.49 M (+16%)35 %
Constant rank-1622.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:

scaling.shbash
# 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)

Measured · Qwen3.5-4B-OptiQ-4bit · M3 Max 36 GB
contextSFT stepSFT peakDPO step (--fused-dpo)DPO peak
20482.8 s7.7 GB29 s8.7 GB
40966.7 s11.4 GB144 s10.9 GB
819245 s19.9 GB216 s17.3 GB
Measured · Qwen3.5-4B-OptiQ-4bit · M4 24 GB · SFT on real agent traces
contextSFT stepSFT peak
204826.3 s8.72 GB
409655.6 s11.90 GB (14.06 GB without the fused loss)
8192~125 s14.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.

16k on a 24 GB Mac Do not run 16k context on a 24 GB Mac. It does not fail with an out-of-memory error; it hangs the machine until the kernel watchdog restarts 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.

ModelLongest sequencePeak memoryTokens/sec
Qwen3.5-0.8B2,80023.4 GB29.2
Qwen3.5-2B2,40019.3 GB38.3
Qwen3.5-4B1,60024.8 GB19.1
Qwen3.5-9B1,40025.4 GB21.6
Qwen3.5-27B / Qwen3.6-27B51227.7 GB11.4
Qwen3.5-35B-A3B / Qwen3.6-35B-A3B12825.3 GB32.2
gemma-4-e2b-it2,40022 GB~28
gemma-4-e4b-it1,80024 GB~22
gemma-4-26B-A4B-it51227.6 GB22.2
gemma-4-31B-it3221.4 GB30.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 / envdefaultwhat it does
--adapt-expertsoff 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_ATTNauto 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_GB25% of wired limit How much of Metal's wired limit stock SDPA's scores may occupy before the tiled backward takes over.
OPTIQ_FLASH_BLOCK128 Query-block size for the tiled backward. Peak memory scales with it; step time does not.
OPTIQ_FUSED_CEauto Fused cut-cross-entropy for the SFT LM head; 0 / 1 force it, like --no-fused-ce / --fused-ce.
--fused-dpo, OPTIQ_FUSED_DPOoff The same chunked head for DPO's four log-probability passes. Needed beyond ~4k on a 24 GB Mac.
These numbers changed in 0.3.0 Earlier docs quoted ~30 min per DPO step at 4k and called anything beyond 4k impractical. Those figures reflected a slow kernel that ran on every step (fixed in 0.3.0): OptiQ's flash-attention Metal kernel is 14–137× slower than MLX's fused SDPA. It is now taken only when stock SDPA's [B, Hq, T, T] score tensor would not fit in memory. Same math, ~13× faster DPO at 4k. See the changelog.