Skip to content
fn

prepare_model_for_kbit_training

→nn.Module
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

The base model.
use_gradient_checkpointingbool= True
When True on a quantized model, enable gradients on the input embeddings and call model.gradient_checkpointing_enable if present.
gradient_checkpointing_kwargsdict= None
Keyword arguments forwarded to model.gradient_checkpointing_enable; defaults to {"use_reentrant": False} when None.
auto_clear_cachebool= True
Release the Metal allocator's cached buffers after the casts, which return the memory the half-precision copies held.

Returns

nn.Module

model itself.

Raises

NotImplementedError
model 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)

Used by 1