prepare_model_for_kbit_training(model: nn.Module, use_gradient_checkpointing: bool = True, gradient_checkpointing_kwargs: dict[str, object] | None = None, auto_clear_cache: bool = True)Freeze the base model, upcast its half-precision parameters to float32, and prepare quantized models for QLoRA.
The preparation step run before training an adapter on a base model loaded for
low-memory or k-bit training: every parameter stops requiring a gradient (the adapter
adds its own), and each float16 or bfloat16 parameter becomes float32, so
that the layer norms, embeddings, and output head compute at full precision. When the
model is quantized (lucid.nn.quantized.QuantizedLinearMLX,
lucid.nn.quantized.Linear, lucid.nn.quantized.dynamic.Linear, or
is_loaded_in_4bit / is_loaded_in_8bit) and use_gradient_checkpointing is
True, input embeddings are configured to require gradients and
gradient_checkpointing_enable is invoked if the model provides it. The model is
changed in place and returned.
Parameters
modelnn.Moduleuse_ gradient_ checkpointingbool= TrueTrue on a quantized model, enable gradients on the input embeddings and
call model.gradient_checkpointing_enable if present.gradient_ checkpointing_ kwargsdict= Nonemodel.gradient_checkpointing_enable; defaults to
{"use_reentrant": False} when None.auto_ clear_ cachebool= TrueReturns
nn.Modulemodel itself.
Raises
NotImplementedErrormodel reports an external quantization scheme (gptq, aqlm, eetq, hqq)
that lucid.peft does not support.Examples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.peft import prepare_model_for_kbit_training
>>> net = nn.Sequential(nn.Linear(4, 4)).to(lucid.float16)
>>> net = prepare_model_for_kbit_training(net)
>>> net[0].weight.dtype, net[0].weight.requires_grad
(lucid.float32, False)