How do you attach a LoRA adapter to a TRL SFTTrainer run through peft_config, and what do its checkpoints and Hub push contain?
answer
- a config object, not a wrapped model
- LoraConfig with a causal-LM task type
- the trainer calls get_peft_model
- two small adapter files
- the base is loaded separately
basics
~10 sPass peft_config=LoraConfig(...) to SFTTrainer; TRL wraps the model with get_peft_model so only adapter weights train. Checkpoints, save_model and push_to_hub then hold just adapter_model.safetensors and adapter_config.json, which records the base model.
solid answer
~30 sI build a PEFT `LoraConfig` with `task_type="CAUSAL_LM"` (rank, alpha and targets are a separate decision) and pass it as `peft_config=` to `SFTTrainer`. TRL 1.14 calls `get_peft_model` itself, freezes the base, and enables input gradients because `SFTConfig` turns gradient checkpointing on by default. It rejects anything that is not a `PeftConfig`, and refuses a model that is already a `PeftModel` plus a new `peft_config`. Checkpoints, `trainer.save_model()` and the Hub push contain only `adapter_model.safetensors` and `adapter_config.json`, whose `base_model_name_or_path` names the base. To use it I call `PeftModel.from_pretrained(base, repo_id)` or `AutoPeftModelForCausalLM.from_pretrained(repo_id)`. One trap: a string model id loads in float32 unless `model_init_kwargs` sets `dtype`.
code
python · 21 linesimport torch
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
peft_config = LoraConfig(task_type="CAUSAL_LM", target_modules="all-linear")
args = SFTConfig(
output_dir="runs/support-lora",
model_init_kwargs={"dtype": torch.bfloat16}, # a string model id loads in float32 otherwise
push_to_hub=True,
hub_model_id="your-org/support-lora",
)
trainer = SFTTrainer(
model="your-org/your-base-model",
args=args,
train_dataset=load_dataset("your-org/support-chats", split="train"),
peft_config=peft_config,
)
trainer.train()
trainer.save_model() # adapter_model.safetensors + adapter_config.json, then a pushgo deeper
Recall that peft_config takes a LoraConfig and that the trained result is an adapter, not a whole new model.
Explain what SFTTrainer does with the config - get_peft_model, frozen base, input gradients with checkpointing - and which two files are saved and pushed.
Catch the silent costs: a float32 base from a string id, a PeftModel plus peft_config error, and loading the adapter on the right base revision.
Decide how a team stores and versions adapters against their bases, so every adapter repo names a base that is still available and pinned.
## Three ways to attach an adapter A **LoRA adapter** is a small set of extra trainable matrices added to a frozen base model; the library that builds it is PEFT, and its configuration object is `LoraConfig`. There are three ways to put one into a training run: 1. **Pass `peft_config=LoraConfig(...)` to TRL's `SFTTrainer`** - the path TRL's docs recommend. The trainer wraps the model itself. 2. **Wrap the model yourself** with PEFT's `get_peft_model(model, config)` and pass the resulting `PeftModel` without `peft_config`. 3. **Use plain Transformers**: `model.add_adapter(lora_config)` and then a normal `Trainer`, which updates only the parameters left trainable. ## What SFTTrainer does with peft_config in TRL 1.14 1. It checks that PEFT is installed (an `ImportError` suggests `pip install trl[peft]`) and that the object is a `PeftConfig`; anything else raises `TypeError`. 2. It refuses a model that is already a `PeftModel` together with a new `peft_config`, raising `ValueError` and asking you to merge and unload the old adapter first. 3. It calls `get_peft_model`, so the base weights are frozen and only adapter parameters train. 4. Because `SFTConfig` turns `gradient_checkpointing` on by default, it calls `enable_input_require_grads()` so gradients reach the adapters through the frozen embeddings. 5. When you also pass `quantization_config` (the QLoRA route, whose mechanics are a separate topic), it casts the trainable adapter parameters to bfloat16. ## LoraConfig fields that are wiring, not tuning | Field | Wiring role | |---|---| | `task_type` | `"CAUSAL_LM"` selects the PEFT model class; `AutoPeftModelForCausalLM` checks it when loading | | `target_modules` | Which layers get adapters; common architectures have predefined defaults, `"all-linear"` selects every linear layer, or pass names | | `modules_to_save` | Layers trained in full and saved with the adapter, such as `lm_head` | | `r`, `lora_alpha`, `lora_dropout` | Present in every config; choosing their values is a method decision made elsewhere | ## Precision defaults that surprise - **A model id string loads in float32.** When `model=` is a string, TRL 1.14 loads it with `model_init_kwargs`, and if those carry no `dtype` the model is float32 - unlike Transformers v5's `from_pretrained`, which infers the dtype from the config. Pass `model_init_kwargs={"dtype": torch.bfloat16}` or load the model yourself. - **`bf16` defaults to `True` in `SFTConfig`** unless `fp16` is set, so mixed precision is on. - **`learning_rate` defaults to `2e-5` in `SFTConfig`.** TRL's docs note adapters are usually trained at a higher rate; the value itself is a hyperparameter question. ## What is saved and pushed - **Checkpoints hold only the adapter**: `adapter_model.safetensors` and `adapter_config.json`, megabytes rather than gigabytes. The base model is not included, and resuming reloads the adapter onto the base. - **`trainer.save_model()`** writes the same two files to `output_dir`, plus the tokenizer. - **`push_to_hub=True` with `hub_model_id`** uploads that folder, so the Hub repo is an adapter repo. - **`adapter_config.json` records `base_model_name_or_path`**, the id of the model the adapter was trained on. ## Loading it back - `PeftModel.from_pretrained(base_model, "your-org/support-lora")` attaches the adapter to a base you loaded yourself. - `AutoPeftModelForCausalLM.from_pretrained("your-org/support-lora")` reads `base_model_name_or_path`, loads that base and attaches the adapter in one call. - `merge_and_unload()` folds the adapter into the base weights to give one plain model; whether to merge or keep adapters separate is a serving decision. - To **continue training** a pushed adapter, load it with `AutoPeftModelForCausalLM.from_pretrained(repo_id, is_trainable=True)` and pass it as `model` with no `peft_config`. ## Resuming an adapter run Resuming works exactly as for a full fine-tune: `trainer.train(resume_from_checkpoint=True)` picks the newest `checkpoint-N` folder. Transformers' Trainer recognises adapter checkpoints - it accepts `adapter_model.safetensors` as valid weights - and reloads the adapter with the right trainable state, while the optimizer and scheduler files restore the rest. The base model must be the same one, loaded the same way, because the checkpoint does not contain it. ## A pre-launch checklist 1. `peft_config` is a `LoraConfig` instance with `task_type="CAUSAL_LM"`, not a dict. 2. The model is a plain base model, or a `PeftModel` with no `peft_config` - never both. 3. `model_init_kwargs` sets `dtype` when the model is given as a string. 4. `output_dir`, `push_to_hub` and `hub_model_id` point at an adapter repository, and the base it names is reachable by whoever loads it - a gated base needs the loader to have access too. 5. Printing `trainer.model.print_trainable_parameters()` shows a small trainable fraction; a large one means the base was not frozen.
- You pass model='your-org/your-base-model' as a string to SFTTrainer. Which dtype is the base loaded in, and how do you change it?TRL 1.14 loads it in float32 when `model_init_kwargs` carries no `dtype`, unlike Transformers v5's `from_pretrained`, which infers the dtype from the config. Set `SFTConfig(model_init_kwargs={"dtype": torch.bfloat16})`, or load the model yourself with the dtype you want and pass the object.
- How do you continue training an adapter you already pushed to the Hub?Load it with `AutoPeftModelForCausalLM.from_pretrained(repo_id, is_trainable=True)` and pass that model to `SFTTrainer` without `peft_config`. Passing a `PeftModel` together with a new `peft_config` raises `ValueError`; TRL asks you to merge and unload first if you really want a fresh adapter on top.
- You must call get_peft_model yourself before handing the model to SFTTrainer.
- The pushed LoRA repo is a full model anyone can load without the base.
- Passing a PeftModel with a new peft_config stacks a second adapter.
- SFTTrainer loads a string model id in its config dtype, like v5 from_pretrained.
- LoRA checkpoints contain the full base weights so that resuming can work.
Assumes TRL 1.14 and PEFT 0.21 on Transformers v5: TRL loads a string model id in float32 unless model_init_kwargs sets dtype, while v5 from_pretrained infers it.