在自定义数据集上微调Tiny-Llama模型

2024年05月22日 由 alex 发表 232 0

在快速发展的机器学习领域,在自定义数据集上对模型进行微调的能力改变了游戏规则。它不仅能创建功能强大的模型,还能为特定领域量身定制模型,从而提高模型的性能和相关性。本文将深入探讨在自定义数据集上微调 Tiny-Llama 模型的复杂性,探索从数据准备到模型训练的整个过程,并重点介绍 PEFT 和 QLORA 等高级训练技术。


微调的力量

微调是在较小的、特定领域的数据集上对预先训练好的模型进行进一步训练(即 "微调")的过程。这种方法充分利用了在初始训练阶段获得的知识,并使其适应新任务的特定需求。Tiny-Llama 模型是 GPT 系列的一个紧凑而高效的变体,由于其在性能和资源效率之间的平衡,特别适合进行微调。


数据准备:成功的基础

微调的成功取决于训练数据的质量和相关性。在本文中,我们将探讨如何从 PDF 文档中准备数据集,并将其转换为可有效用于训练的结构化格式。


从 PDF 文档中提取文本

第一步是从 PDF 文档中提取有意义的文本。这对于生成可用于微调模型的问题和答案至关重要。我们使用 PyPDF2 库,它提供了读取 PDF 文件和提取文本的直接方法。


import PyPDF2
def extract_text_from_pdf(file_path):
    pdf_file_obj = open(file_path, 'rb')
    pdf_reader = PyPDF2.PdfReader(pdf_file_obj)
    text = ''
    for page_num in range(len(pdf_reader.pages)):
        page_obj = pdf_reader.pages[page_num]
        text += page_obj.extract_text()
    pdf_file_obj.close()
    return text


生成问题和答案

获得文本后,我们需要生成问题和答案。具体方法是将文本发送到 API(本例中使用 OpenAI 的 GPT-4 模型),然后处理响应以提取问题和答案。


import openai
import json
from typing import List
from tqdm import tqdm
def generate_questions_answers(text_chunk):
    messages = [
        {'role': 'system', 'content': 'You are an API that converts bodies of text into a single question and answer into a JSON format. Each JSON " \
          "contains a single question with a single answer. Only respond with the JSON and no additional text. \n.'},
        {'role': 'user', 'content': 'Text: ' + text_chunk}
    ]
    response = openai.chat.completions.create(
        model="gpt-4",
        messages=messages,
        max_tokens=2048,
        n=1,
        stop=None,
        temperature=0.7,
    )
    response_text = response.choices[0].message.content.strip()
    try:
        json_data = json.loads(response_text)
        return json_data
    except json.JSONDecodeError:
        print("Error: Response is not valid JSON.")
        return []


处理文本并写入 JSON

数据准备的最后一步是处理文本块,为每个文本块生成问题和答案,并将结果写入 JSON 文件。这种结构化格式对于后续的训练步骤至关重要。


def process_text(text: str, chunk_size: int = 4000) -> List[dict]:
    text_chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
    all_responses = []
    for chunk in tqdm(text_chunks, desc="Processing chunks", unit="chunk"):
        responses = generate_questions_answers(chunk)
        all_responses.extend(responses)
    return all_responses
text = extract_text_from_pdf('Provide Path to your file')
responses = {"responses": process_text(text)}
with open('responses.json', 'w') as f:
    json.dump(responses, f, indent=2)


将 json 转换为 CSV 用于训练

准备好数据后,我们将其转换成适合培训的 CSV 格式。这包括从 JSON 中提取问题和答案,然后将其写入 CSV 文件,并为提示、问题和答案设置列。


import json
import csv
instruction = "You will answer questions about Machine Learning"
with open('responses.json', 'r', encoding='utf-8') as f:
    responses = json.load(f)
with open('responses.csv', 'w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['prompt', 'question', 'answer']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for response in responses['responses']:
        if 'question' in response and 'answer' in response:
            writer.writerow({'prompt': instruction, 'question': response['question'], 'answer': response['answer']})


为训练准备数据

训练前,我们需要正确格式化数据。这包括读取 CSV 文件,将提示、问题和答案合并为一列文本,然后将格式化后的数据保存到新的 CSV 文件中。


import pandas as pd
df = pd.read_csv("responses.csv")
df.fillna("")
text_col = []
for _, row in df.iterrows():
 prompt = "Below is an instruction which describes a tasks paired with a question that provides further context. Write a response that completes the request.\n\n"
 instruction = str(row["prompt"])
 input_query = str(row["question"])
 response = str(row["answer"])
 if len(input_query.strip()) == 0: 
    text = prompt + "### Instruction:\n " + instruction + "\n### Response:\n " + response
 else:
    text = prompt + "### Instruction:\n " + instruction + "\n### Input:" + input_query + "\n### Response:\n " + response
 text_col.append(text)
df.loc[:, "train"] = text_col
df.to_csv("train.csv", index=False)


使用自动培训高级版进行培训


我们使用自动训练高级版进行训练,这是一款功能强大的工具,可简化训练过程。它支持 PEFT(过程高效微调)和 QLORA(量化低方根逼近)等高级训练技术,可以显著减少训练时间和内存使用。


TINY-LLAMA


1


Tiny-Llama 模型是 GPT 系列的一个紧凑而高效的变体,专为在定制数据集上进行微调而设计。它利用 Llama 架构增强了文本生成能力,为以更高的效率和性能重新创建 TinyStories-1M 模型提供了概念验证。Tiny-Llama 模型由 Hugging Face 托管,展示了微调和特定领域建模在机器学习领域的潜力。


! autotrain llm --train --project-name josh-ops --model Maykeye/TinyLLama-v0 --data-path /kaggle/input/llamav2 --use-peft --quantization int4 --lr 1e-4 --train-batch-size 15 --epochs 60 --trainer sftinput/llamav2 --use-peft --quantization int4 --lr 1e-4 --train-batch-size 15 --epochs 60 --trainer sft


了解 PEFT 和 Qlora

  • PEFT(过程高效微调): 该技术通过减少每个训练步骤中需要更新的参数数量来优化训练过程。它对于在自定义数据集上微调大型模型特别有用。
  • QLORA(Quantized Low-Rank Approximation): QLORA 是一种在训练过程中减少模型内存占用的方法。它包括量化模型的权重,并对权重矩阵应用低阶近似。这可以大大减少训练所需的内存量,从而可以在资源有限的硬件上训练更大的模型。


结论

在自定义数据集上微调 Tiny-Llama 模型是实现特定领域性能的有力方法。通过利用 PEFT 和 QLORA 等高级训练技术以及 Auto Train Advanced 等工具,我们可以在自定义数据集上高效地训练模型。这一过程不仅能提高模型在特定任务上的性能,还能为机器学习在各个领域的应用提供新的可能性。随着机器学习领域的不断发展,在自定义数据集上对模型进行微调的能力仍将是一项关键技能,它使我们能够创建不仅功能强大,而且符合我们特定需求的模型。

文章来源:https://medium.com/@dongreanay/fine-tuning-the-tiny-llama-model-on-a-custom-dataset-9d1ce4eb663d
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
写评论取消
回复取消