Many Adapters
One base, many skills.
Riverside Books wants two skills. Reading messages into JSON, and writing friendly replies. Two full models would double the memory. With LoRA, one base model can hold both adapters, and switch between them instantly.
- Two skills
- Two full models? Too big
- One base, two adapters
Switch adapters
We trained a second adapter, called reply LoRA, in exactly the same way, on example replies. Here, we load the base model with the tickets adapter, and give it a name. Load adapter adds the reply adapter, with its own name. For each job, set adapter switches to that adapter, and we generate with its system message. Run it. Same base model, same message. The tickets adapter writes JSON. The reply adapter writes a friendly answer, signed by Riverside Books.
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME),
"ticket-lora", adapter_name="tickets")
model.load_adapter("reply-lora", adapter_name="reply")
model.eval()
jobs = {"tickets": "Read the customer's message. Reply with JSON: the intent and the book.",
"reply": "Write a short, friendly reply to the customer."}
msg = "Hi, my copy of Circe still hasn't arrived."
for adapter, system in jobs.items():
model.set_adapter(adapter)
ids = tok.apply_chat_template([{"role": "system", "content": system},
{"role": "user", "content": msg}],
add_generation_prompt=True, return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=40, do_sample=False)
print(f"{adapter:8}", tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True))tickets {"intent": "order_status", "book": "Circe"}
reply Sorry for the wait! Your copy of Circe is on its way, and you'll get a tracking
email soon. - Riverside BooksAlso uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/ticket-lora', 'ticket-lora')
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/reply-lora', 'reply-lora')Also uses chat.py
import json
from datasets import load_dataset
SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."
def to_example(row):
answer = json.dumps({"intent": row["intent"], "book": row["book"]})
return {"prompt": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": row["message"]}],
"completion": [{"role": "assistant", "content": answer}]}
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])Also uses ask.py
from chat import SYSTEM
def ask(model, tok, message):
model.eval() # switch off training-only behaviour
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
ids = tok.apply_chat_template(messages, add_generation_prompt=True,
return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=30, do_sample=False)
return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)Also uses sft.py
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
per_device_train_batch_size=8, logging_steps=11,
eval_strategy="steps", eval_steps=22,
save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["test"], processing_class=tok, peft_config=lora)Why this is powerful
This pattern scales. A company can keep one copy of a base model in memory, and dozens of small adapters. Each request picks the adapter it needs. Serving tools, like v LLM, can even mix different adapters in the same batch. We'll come back to this when we talk about deployment.
| key | value |
|---|---|
| One base model | in memory once |
| Many adapters | a few MB each |
| Each request | picks its adapter |
| vLLM | mixes adapters in a batch |
Summary
Let's recap. Load adapter adds more adapters, each with a name. Set adapter switches between them. And one base model can serve many skills. Next, some practice.
Key takeaways- load_adapter(name)
- set_adapter(name)
- One base, many skills