AI算法 | 如何訓練自己的大模型?
1、第一階段:二次預訓練
模型選擇與轉換
在開始訓練之前,需要選擇一個合適的基礎模型。本文以LLaMA-7B為例,簡單介紹下。為了方便后續(xù)的操作,將LLaMA-7B模型轉換為Hugging Face格式。
from transformers import AutoModelForCausalLM, AutoTokenizer
# 加載原始LLaMA模型
model_path = "original_llama_7b"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path)
# 保存為Hugging Face格式
hf_path = "llama_7b_hf"
model.save_pretrained(hf_path)
tokenizer.save_pretrained(hf_path)
此外,為了更好地處理中文文本,還需要擴充中文詞表??梢詤⒖糃hinese-LLaMA項目,它在原始詞表的基礎上新增了大量漢字token,從而讓模型能夠更好地理解和生成中文內容。
from transformers import AddedToken
# 加載原始tokenizer
tokenizer = AutoTokenizer.from_pretrained("llama_7b_hf")
# 添加中文字符
new_tokens = ["中文", "中國", "人工智能"] # 實際應用中需要更全面的詞表
new_tokens = [AddedToken(token) for token in new_tokens]
# 擴充詞表
tokenizer.add_tokens(new_tokens)
model.resize_token_embeddings(len(tokenizer))
# 保存擴充后的tokenizer
tokenizer.save_pretrained("llama_7b_zh_extended")
數(shù)據(jù)準備
數(shù)據(jù)是訓練模型的關鍵。需要根據(jù)任務需求收集海量的中文文本數(shù)據(jù)。例如,這些數(shù)據(jù)可以來自中文維基百科、新聞文章、小說等多個領域。這樣可以確保模型能夠學習到豐富的知識。在收集數(shù)據(jù)之后,還需要對數(shù)據(jù)進行清洗和預處理,去除其中的噪聲和無關內容,以保證數(shù)據(jù)的質量。
下面是一個簡單的清晰流程實例:
def clean_text(text):
# 去除HTML標簽
text = re.sub(r'<[^>]+>', '', text)
# 去除特殊字符和多余空格
text = re.sub(r'\s+', ' ', text).strip()
# 其他自定義清洗規(guī)則
return text
# 假設我們有一個文本文件列表
text_files = ["data/wiki_zh.txt", "data/news_zh.txt"]
cleaned_data = []
for file in text_files:
with open(file, 'r', encoding='utf-8') as f:
for line in tqdm(f):
cleaned = clean_text(line)
if len(cleaned) > 10: # 過濾過短文本
cleaned_data.append(cleaned)
# 保存清洗后的數(shù)據(jù)
with open("cleaned_zh_data.txt", 'w', encoding='utf-8') as f:
f.write('\n'.join(cleaned_data))
訓練設置
為了降低計算資源的需求,可以使用LoRA(Low-Rank Adaptation)技術進行二次預訓練。LoRA通過在模型中添加低秩矩陣來實現(xiàn)高效的微調,大大減少了需要訓練的參數(shù)數(shù)量。例如,原本全參微調7B模型需要8卡A100,使用LoRA后,單卡3090就足夠了。此外,還需要設置合適的超參數(shù),如學習率、批次大小等。這些超參數(shù)可以根據(jù)實驗結果進行調整,以達到更好的訓練效果。
from transformers import Trainer, TrainingArguments
from peft import LoraConfig, get_peft_model
# 配置LoRA
lora_config = LoraConfig(
r=8, # 低秩矩陣的維度
lora_alpha=32,
target_modules=["q_proj", "v_proj"], # 對query和value矩陣進行適配
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
# 應用LoRA到模型
model = get_peft_model(model, lora_config)
model.print_trainable_parameters() # 查看可訓練參數(shù)數(shù)量
# 準備訓練參數(shù)
training_args = TrainingArguments(
output_dir="./output",
overwrite_output_dir=True,
num_train_epochs=3,
per_device_train_batch_size=4,
save_steps=10_000,
save_total_limit=2,
learning_rate=1e-4,
fp16=True,
logging_steps=100,
evaluation_strategy="steps",
eval_steps=5_000,
load_best_model_at_end=True
)
# 創(chuàng)建數(shù)據(jù)集
from datasets import load_dataset
dataset = load_dataset("text", data_files={"train": "cleaned_zh_data.txt"})
# 開始訓練
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset["train"],
tokenizer=tokenizer
)
trainer.train()
2、第二階段:指令微調
數(shù)據(jù)準備
在第一階段的預訓練之后,需要對模型進行指令微調,以使其能夠更好地理解和執(zhí)行指令。為此,需要構造指令微調數(shù)據(jù)集,這些數(shù)據(jù)集包括中文指令和對應的回答。可以參考Alpaca-CoT項目,它提供了豐富的指令數(shù)據(jù)集。如果模型需要應用于特定的領域,如金融領域,還可以收集相關的領域指令數(shù)據(jù)。
訓練設置
在第一階段的預訓練模型基礎上進行指令微調。同樣可以使用LoRA技術,進一步降低計算成本。如果希望模型更好地理解下游任務信息,可以將指令微調數(shù)據(jù)集拼接成文檔格式,放入第一階段進行增量預訓練。
訓練過程
使用FT(Full-Tuning)+LoRA SFT(Sparse Fine-Tuning)的方式進行微調。在訓練過程中,模型會學習如何更好地理解和執(zhí)行指令。為了確保模型的性能,需要定期評估模型在指令微調數(shù)據(jù)集上的表現(xiàn),并根據(jù)評估結果調整訓練策略。
from transformers import DataCollatorForLanguageModeling
# 加載預訓練模型
model = AutoModelForCausalLM.from_pretrained("./output/checkpoint-final")
tokenizer = AutoTokenizer.from_pretrained("llama_7b_zh_extended")
# 準備數(shù)據(jù)集
def preprocess_function(examples):
texts = []
for inst in examples["text"]:
try:
data = json.loads(inst)
text = f"指令:{data['instruction']}\n輸入:{data['input']}\n輸出:{data['output']}"
texts.append(text)
except:
continue
return tokenizer(texts, truncatinotallow=True, max_length=512)
dataset = load_dataset("json", data_files={"train": "instruction_data.json"})
tokenized_dataset = dataset.map(preprocess_function, batched=True)
# 數(shù)據(jù)收集器
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False
)
# 微調參數(shù)
training_args = TrainingArguments(
output_dir="./sft_output",
per_device_train_batch_size=4,
num_train_epochs=5,
learning_rate=5e-5,
fp16=True,
save_steps=10_000,
logging_steps=100,
evaluation_strategy="no",
)
# 開始微調
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset["train"],
data_collator=data_collator,
tokenizer=tokenizer
)
trainer.train()
低成本方案
例如8-bit優(yōu)化:
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(
load_in_8bit=True,
llm_int8_threshold=6.0
)
model = AutoModelForCausalLM.from_pretrained(
"llama_7b_hf",
quantization_cnotallow=quantization_config
)
3、注意事項
- 數(shù)據(jù)質量:在實際應用中,數(shù)據(jù)清洗和預處理的邏輯可能需要根據(jù)具體數(shù)據(jù)進行調整。
- 超參數(shù)調整:超參數(shù)(如學習率、批次大小、LoRA的秩等)需要根據(jù)實驗結果進行調整。
- 模型評估:在訓練過程中,建議定期在驗證集上評估模型性能,以確保模型沒有過擬合。