Prefix Tuning
Prefix-Tuning
A method of adapting a model by adding a learnable prefix to the input
Prefix-Tuning
A method of adapting a model by adding a learnable prefix to the input
Prefix Tuning is a Parameter-Efficient Fine-Tuning (PEFT) technique introduced by a Stanford research team in 2021. It keeps the existing model's parameters frozen and adds trainable continuous vectors (a prefix) in front of the input sequence to adapt the model to a specific task.
The core idea of Prefix Tuning is to inject virtual token embeddings into every layer of the Transformer. These prefix vectors are a "soft prompt" that does not correspond to any actual vocabulary, and they serve as context that guides the model to perform a specific task.
Whereas conventional fine-tuning updates all of the model's parameters, Prefix Tuning trains less than 0.1% of the total parameters. For example, fine-tuning GPT-2 Large (774M) requires 774M parameters, but Prefix Tuning only needs to store about 250K parameters.
In practice, Prefix Tuning is useful for handling multiple tasks with a single model. Only the task-specific prefix needs to be swapped, so multi-task serving is efficient. Along with other PEFT techniques such as LoRA and Adapter, it has become a core technology for LLM customization.
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PrefixTuningConfig, get_peft_model, TaskType
# ๋ฒ ์ด์ค ๋ชจ๋ธ ๋ก๋
model_name = "gpt2-medium"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
# Prefix Tuning ์ค์
peft_config = PrefixTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=20, # prefix ๊ธธ์ด
prefix_projection=True, # MLP๋ก prefix ์๋ฒ ๋ฉ ์์ฑ
encoder_hidden_size=1024 # ์ธ์ฝ๋ ํ๋ ์ฌ์ด์ฆ
)
# PEFT ๋ชจ๋ธ ์์ฑ
model = get_peft_model(model, peft_config)
# ํ์ต ๊ฐ๋ฅํ ํ๋ผ๋ฏธํฐ ํ์ธ
model.print_trainable_parameters()
# trainable params: 983,040 || all params: 355,350,528 || trainable%: 0.2767
# ํ์ต ๋ฐ์ดํฐ ์ค๋น
from datasets import Dataset
train_data = [
{"text": "๊ณ ๊ฐ: ๋ฐฐ์ก์ด ์ธ์ ์ค๋์? ๋ต๋ณ: ์ฃผ๋ฌธ ํ 2-3์ผ ๋ด ๋ฐฐ์ก๋ฉ๋๋ค."},
{"text": "๊ณ ๊ฐ: ๋ฐํํ๊ณ ์ถ์ด์. ๋ต๋ณ: 7์ผ ์ด๋ด ๋ฌด๋ฃ ๋ฐํ ๊ฐ๋ฅํฉ๋๋ค."},
{"text": "๊ณ ๊ฐ: ๊ฒฐ์ ๋ฐฉ๋ฒ์? ๋ต๋ณ: ์ ์ฉ์นด๋, ๊ณ์ข์ด์ฒด, ๊ฐํธ๊ฒฐ์ ๊ฐ๋ฅํฉ๋๋ค."}
]
dataset = Dataset.from_list(train_data)
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length",
truncation=True, max_length=128)
tokenized_dataset = dataset.map(tokenize_function, batched=True)
# ํ์ต
from transformers import Trainer, TrainingArguments
training_args = TrainingArguments(
output_dir="./prefix_tuning_output",
num_train_epochs=3,
per_device_train_batch_size=4,
learning_rate=3e-2, # prefix tuning์ ๋์ LR ์ฌ์ฉ
logging_steps=10
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset
)
trainer.train()
# ์ถ๋ก
model.eval()
input_text = "๊ณ ๊ฐ: ๊ตํํ๋ ค๋ฉด ์ด๋ป๊ฒ ํ๋์? ๋ต๋ณ:"
inputs = tokenizer(input_text, return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=50)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
# ๋ชจ๋ธ ์ ์ฅ (prefix ํ๋ผ๋ฏธํฐ๋ง ์ ์ฅ๋จ)
model.save_pretrained("./my_prefix_model")
# === ๋ฉํฐ ํ์คํฌ ์๋น (prefix ๊ต์ฒด) ===
from peft import PeftModel
base_model = AutoModelForCausalLM.from_pretrained("gpt2-medium")
# ํ์คํฌ๋ณ prefix ๋ก๋
customer_service_model = PeftModel.from_pretrained(base_model, "./prefix_customer_service")
marketing_model = PeftModel.from_pretrained(base_model, "./prefix_marketing")
legal_model = PeftModel.from_pretrained(base_model, "./prefix_legal")
# ์ถ๋ก ์ ํ์คํฌ์ ๋ฐ๋ผ prefix๋ง ๊ต์ฒด
def generate_response(query: str, task: str) -> str:
if task == "customer_service":
model = customer_service_model
elif task == "marketing":
model = marketing_model
elif task == "legal":
model = legal_model
else:
model = base_model
inputs = tokenizer(query, return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=100)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
# === Prefix Tuning vs LoRA ๋น๊ต ===
# Prefix Tuning:
# - ์ฅ์ : ์
๋ ฅ ๊ธธ์ด๊ฐ ์ฆ๊ฐํ๋ฏ๋ก ์ถ๋ก ์ ํด์ ๊ฐ๋ฅ
# - ๋จ์ : prefix๊ฐ ์ค์ ์ปจํ
์คํธ๋ฅผ ์ฐจ์งํจ
# - ํ๋ผ๋ฏธํฐ: ~0.1-0.5%
# LoRA:
# - ์ฅ์ : ์
๋ ฅ ๊ธธ์ด ๊ทธ๋๋ก, ๋ ์ข์ ์ฑ๋ฅ
# - ๋จ์ : weight ์์ ์ด๋ผ ํด์ ์ด๋ ค์
# - ํ๋ผ๋ฏธํฐ: ~0.1-1%
# ๊ฒฐ๋ก : ๋๋ถ๋ถ์ ๊ฒฝ์ฐ LoRA๊ฐ ๋ ์ข์ ์ ํ
# === Prompt Tuning (Prefix Tuning์ ๋จ์ํ ๋ฒ์ ) ===
# Prompt Tuning์ ์
๋ ฅ ์๋ฒ ๋ฉ์๋ง prefix ์ถ๊ฐ
# Prefix Tuning์ ๋ชจ๋ ๋ ์ด์ด์ hidden state์ ์ถ๊ฐ
from peft import PromptTuningConfig, PromptTuningInit
prompt_tuning_config = PromptTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=20,
prompt_tuning_init=PromptTuningInit.RANDOM # ๋๋ TEXT
)
# TEXT ์ด๊ธฐํ: ์์ฐ์ด๋ก ํ๋กฌํํธ ์ด๊ธฐํ
# RANDOM ์ด๊ธฐํ: ๋๋ค ๋ฒกํฐ๋ก ์์
"We want to run chatbots for three teams, customer support, marketing, and legal, with a single LLM. If we create just a prefix for each team with Prefix Tuning, we can serve them by swapping only the prefix at inference time. Infrastructure cost drops to a third compared with running three models."
"What's the difference between Prefix Tuning and LoRA?" - "Both are PEFT techniques, but the approach is different. Prefix Tuning adds virtual tokens to the input, while LoRA adds low-rank matrices to the attention weights. LoRA generally performs better, so these days LoRA or QLoRA is used more."
"The prefix_projection option in Prefix Tuning is a reparameterization trick. Training the prefix vectors directly is unstable, but generating them through a small MLP stabilizes training. After training, only the generated prefix is used without the MLP, so there's no inference overhead."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Setting the prefix length (num_virtual_tokens) too long reduces the actual input context. For most tasks, 10-50 tokens is enough. Performance does not improve proportionally as the prefix gets longer.
If you use a low LR like the 1e-5 used in ordinary fine-tuning, the prefix barely trains. Prefix Tuning needs a high LR of around 1e-2 to 5e-2, because the number of parameters is small and so the gradients are small.
Setting prefix_projection=True greatly improves training stability. A small MLP is used only during training, and only the computed prefix is used at inference, so inference speed is unaffected.