๐Ÿค– AI/ML

Prefix Tuning

Prefix-Tuning

A method of adapting a model by adding a learnable prefix to the input

๐Ÿ“– Detailed Explanation

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.

๐Ÿ’ป Code Example

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 ์ดˆ๊ธฐํ™”: ๋žœ๋ค ๋ฒกํ„ฐ๋กœ ์‹œ์ž‘

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a Meeting

"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."

๐Ÿ’ฌ In an Interview

"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."

๐Ÿ’ฌ In a Technical Discussion

"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

โš ๏ธ Common Mistakes & Cautions

โŒ
Using too long a prefix

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.

โŒ
Using a low learning rate

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.

โœ…
Enable prefix_projection

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.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More