AI Hints
Home›Fine-Tuning LLMs Tutorial›Fast Inference, Many Adapters and Costs
Fine-Tuning LLMs · Lesson 100 of 120

Fast Inference

Quicker answers.

⏱ 2 min read▶ Video at 2:33:48🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Training happens once. But a model in use might answer millions of messages. So small speed-ups in inference save a lot of time, and money.

  • Training happens once
  • Inference happens millions of times
  • Speed saves money

Three big speed-ups

There are three big speed-ups. The KV cache stores the work already done for earlier tokens, so each new token is cheap. Batching answers many requests at once. And merging the adapter removes the small extra cost of LoRA layers.

KV cachereuse earlier work
Batchingmany requests at once
Mergingno extra LoRA layers

Measuring the speed-ups

Let's measure. We have twelve customer messages. Padding side left pads on the left, which generation needs, when batching. Our run function generates answers, in batches of a given size, and times it. First, one at a time, with no KV cache. Then with the cache. Then all twelve in one batch. Run it. The KV cache makes it much faster. And batching makes it faster again. Same answers, a fraction of the time.

app.pypython
import time
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
from chat import SYSTEM
NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME, padding_side="left")
model = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(NAME), "ticket-lora").eval()
msgs = ["Is Dune in stock?", "How much is Circe?", "Where is my Rebecca order?"] * 4
chats = [[{"role": "system", "content": SYSTEM}, {"role": "user", "content": m}] for m in msgs]
def run(batch, use_cache=True):
    t = time.time()
    for i in range(0, len(chats), batch):
        ids = tok.apply_chat_template(chats[i:i + batch], add_generation_prompt=True, padding=True,
                                      return_dict=True, return_tensors="pt")
        model.generate(**ids, max_new_tokens=20, do_sample=False, use_cache=use_cache)
    return f"{time.time() - t:5.1f} s"
print("one at a time, no KV cache:", run(1, use_cache=False))
print("one at a time:             ", run(1))
print("batches of 12:             ", run(12))
Output
one at a time, no KV cache:  15.4 s
one at a time:                5.0 s
batches of 12:                1.6 s
Also uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/ticket-lora', 'ticket-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)

More speed-ups

There's more you can do. Quantize the model, to use less memory. Limit max new tokens, because every extra token costs time. And on a GPU server, use v LLM, which does all of this, and more, for you.

keyvalue
Quantizeless memory, often faster
max_new_tokensonly what you need
ServervLLM does it for you
Alwaysmeasure before and after

Summary

Let's recap. The KV cache reuses earlier work. Batching answers many requests at once. Merging removes LoRA overhead. And always limit max new tokens. Next, serving many adapters at once.

Key takeaways
  • KV cache
  • Batching
  • Merge, limit tokens
Next up: Serving Many Adapters — one model, many skills