Llama 2 的特定任務微調



微調是一個定製預訓練大型語言模型 (LLM) 以使其在特定任務上表現更好的過程。Llama 2 的微調是一個調整預訓練模型引數以提高其在特定任務或資料集上效能的過程。此過程可用於使 Llama 2 適應各種任務。

本章涵蓋了遷移學習微調技術的概念,以及如何針對不同任務微調 Llama 的示例。

理解遷移學習

遷移學習是機器學習的一種應用,其中一個在更大的語料庫上預訓練的模型被應用於相關的任務,但規模要小得多。它不是從頭開始訓練模型(這在計算上代價高昂且耗時),而是建立在模型在更大語料庫上已經獲得的知識之上。

以 Llama 為例:它在大量的文字資料上進行了預訓練。我們將使用遷移學習;我們將對較小的資料集進行微調,用於非常不同的 NLP 任務:例如,情感分析、文字分類或問答。

遷移學習的主要優勢

  • 節省時間 - 微調比從原始資料集訓練模型所需的時間少得多。
  • 改進泛化能力 - 預訓練模型已經學習了普遍的語言模式,這對於一系列自然語言處理應用非常有用。
  • 資料效率 - 微調即使在較小的資料集上也能使模型高效。

微調技術

微調Llama 或任何其他大型語言模型都是一個為任務微調模型引數的過程。有幾種微調技術

全模型微調

這會更新模型每一層的引數。但這確實需要大量的計算,並且對於特定任務的效能可能更好。

from transformers import LlamaForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset

# Load tokenizer (assuming you need to define the tokenizer)
from transformers import LlamaTokenizer
tokenizer = LlamaTokenizer.from_pretrained("meta-Llama/Llama-2-7b-chat-hf")

# Load dataset
dataset = load_dataset("imdb")

# Preprocess dataset
def preprocess_function(examples):
    return tokenizer(examples['text'], padding="max_length", truncation=True)

tokenized_dataset = dataset.map(preprocess_function, batched=True)

# Set up training arguments
training_args = TrainingArguments(
    output_dir="./results",
    evaluation_strategy="epoch",
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=3,
    weight_decay=0.01
)

model = LlamaForSequenceClassification.from_pretrained("meta-Llama/Llama-2-7b-chat-hf", num_labels=2)

# Trainer Initialization
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["test"]
)

# Fine-tune the model
trainer.train()

輸出

Epoch 1/3
Training Loss: 0.1345, Evaluation Loss: 0.1523
Epoch 2/3
Training Loss: 0.0821, Evaluation Loss: 0.1042
Epoch 3/3
Training Loss: 0.0468, Evaluation Loss: 0.0879

層凍結

僅凍結模型的最後一層,前幾層也“凍結”。當您想要節省記憶體使用和訓練時間時,主要應用此方法。如果它更接近預訓練資料,則此技術很有價值。

# Freeze all layers except the classifier layer
for param in model.base_model.parameters():
    param.requires_grad = False
     # Now, fine-tune only the classifier layers
trainer.train()

學習率調整

其他方法包括嘗試調整學習率作為微調方法。這在低學習率下更好,因為在微調時對預先學習的知識造成的干擾最小。

training_args = TrainingArguments(
    output_dir="./results",
    learning_rate=2e-5,  
# Low pace of fine-tuning learning
    num_train_epochs=3,
    evaluation_strategy="epoch"
)

基於提示的微調

它採用精心設計的提示來引導模型完成特定任務,而無需更新模型的權重。它在零樣本和少樣本學習的所有型別任務中都具有很高的實用性。

其他任務的微調示例

讓我們來看一些微調 Llama 模型的實際例子:

1. 用於情感分析的微調

廣義地說,情感分析將文字輸入分類為以下類別之一,這些類別表示文字的性質是積極的、消極的還是中性的。微調 Llama 可能比理解不同文字輸入背後的情感更出色。

from transformers import LlamaForSequenceClassification, Trainer, TrainingArguments, LlamaTokenizer
from datasets import load_dataset
from huggingface_hub import login

access_token_read = "<Enter token>"

# Authenticate with the Hugging Face Hub
login(token=access_token_read)

# Load the tokenizer
tokenizer = LlamaTokenizer.from_pretrained("meta-Llama/Llama-2-7b-chat-hf")

# Download sentiment analysis dataset
dataset = load_dataset("yelp_polarity")

# Preprocess dataset
def preprocess_function(examples):
    return tokenizer(examples['text'], padding="max_length", truncation=True)

tokenized_dataset = dataset.map(preprocess_function, batched=True)

# Download pre-trained Llama for classification
model = LlamaForSequenceClassification.from_pretrained("meta-Llama/Llama-2-7b-chat-hf", num_labels=2)

# Training arguments
training_args = TrainingArguments(
    output_dir="./results",
    learning_rate=2e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=3,
    weight_decay=0.01,
)

# Initialize Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["test"]
)

# Fine-tune model for sentiment analysis
trainer.train()

輸出

Epoch 1/3
Training Loss: 0.2954, Evaluation Loss: 0.3121
Epoch 2/3
Training Loss: 0.1786, Evaluation Loss: 0.2245
Epoch 3/3
Training Loss: 0.1024, Evaluation Loss: 0.1893

2. 問答微調

微調模型還可以支援它從文字中生成簡短且相關的答案來回答問題。

from transformers import LlamaForQuestionAnswering, Trainer, TrainingArguments, LlamaTokenizer
from datasets import load_dataset
from huggingface_hub import login

access_token_read = "<Enter token>"

# Authenticate with the Hugging Face Hub
login(token=access_token_read)

# Load the tokenizer
tokenizer = LlamaTokenizer.from_pretrained("meta-Llama/Llama-2-7b-chat-hf")

# Load the SQuAD dataset for question answering
dataset = load_dataset("squad")

# Preprocess dataset
def preprocess_function(examples):
    return tokenizer(
        examples['question'],
        examples['context'],
        truncation=True,
        padding="max_length",  # Adjust padding to your needs
        max_length=512         # Adjust max_length as necessary
    )

tokenized_dataset = dataset.map(preprocess_function, batched=True)

# Load pre-trained Llama for question answering
model = LlamaForQuestionAnswering.from_pretrained("meta-Llama/Llama-2-7b-chat-hf")

# Training arguments
training_args = TrainingArguments(
    output_dir="./results",
    learning_rate=3e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=3,
    weight_decay=0.01,
)

# Initialize Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["validation"]
)

# Fine-tune model on question answering
trainer.train()

輸出

Epoch 1/3
Training Loss: 1.8234, Eval. Loss: 1.5243
Epoch 2/3
Training Loss: 1.3451, Eval. Loss: 1.2212
Epoch 3/3
Training Loss: 1.0152, Eval. Loss: 1.0435

3. 用於文字生成的微調

Llama 可以進行微調以增強其文字生成能力,這可以用於故事生成、對話系統甚至創意寫作等應用。

from transformers import LlamaForCausalLM, Trainer, TrainingArguments, LlamaTokenizer
from datasets import load_dataset
from huggingface_hub import login

access_token_read = "<Enter token>"

login(token=access_token_read)

# Load the tokenizer
tokenizer = LlamaTokenizer.from_pretrained("meta-Llama/Llama-2-7b-chat-hf")

# Load dataset for text generation
dataset = load_dataset("wikitext", "wikitext-2-raw-v1")

# Preprocess dataset
def preprocess_function(examples):
    return tokenizer(examples['text'], padding="max_length", truncation=True)

tokenized_dataset = dataset.map(preprocess_function, batched=True)

# Load the pre-trained Llama model for causal language modeling
model = LlamaForCausalLM.from_pretrained("meta-Llama/Llama-2-7b-chat-hf")

# Training arguments
training_args = TrainingArguments(
    output_dir="./results",
    learning_rate=5e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=3,
    weight_decay=0.01,
)

# Initialize the Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["validation"],
)

# Fine-tune the model for text generation
trainer.train()

輸出

Epoch 1/3
Training Loss: 2.9854, Eval Loss: 2.6452
Epoch 2/3
Training Loss: 2.5423, Eval Loss: 2.4321
Epoch 3/3
Training Loss: 2.2356, Eval Loss: 2.1987

總結

事實上,在某些特定任務上對 Llama 進行微調,無論是情感分析、問答還是文字生成,都展示了遷移學習的強大功能。換句話說,從一些巨大的預訓練模型開始,微調允許用最少的資料和計算來定製它以適應特定用例。本章描述了這些技術和示例,以展示 Llama 的多功能性,從而提供可能方便適應各種不同 NLP 挑戰的實踐步驟。

廣告
© . All rights reserved.