Mistral-7B微调:分步指南

2023年10月13日 由 alex 发表 2766 0

Mistral 7B简介:语言模型的强大力量


Mistral AI团队推出了生成型AI领域的最新成员——Mistral 7B模型。拥有惊人的73亿个参数,Mistral 7B是语言模型领域的真正巨人,并且具有许多引人注目的特点和能力。


Mistral 7B最令人印象深刻的一个方面是它能够在各种基准测试中超越其他知名的语言模型。它在所有基准测试中超过了Llama 2 13B甚至在许多测试中与Llama 1 34B一较高下。此外,Mistral 7B在处理与代码相关的任务时表现出色,同时保持其在英语语言任务上的熟练程度。这种卓越的性能证明了它的多功能性和强大性。


Mistral 7B的高效性


Mistral 7B不仅强大,而且高效。它使用分组查询注意力(GQA)进行更快的推理,使其成为实时应用的优秀选择。此外,它还采用滑动窗口注意力(SWA)来处理较长的序列,并具有较小的计算成本。这种创新的方法确保Mistral 7B始终处于人工智能技术的前沿。


开源和易于使用


Mistral AI团队坚信合作和知识共享的精神。这就是为什么他们将Mistral 7B发布在Apache 2.0许可下,使开发人员和研究人员可以无限制地使用它。


轻松进行微调


Mistral7B被设计成可以轻松进行各种任务的微调。作为演示,Mistral AI团队提供了一个针对聊天应用程序进行微调的模型,展示了它在聊天相关任务上优于Llama 2 13B的卓越性能。这种灵活性使Mistral 7B成为各种自然语言处理任务的理想选择。


在各种基准测试中无与伦比的性能


a


详细评估显示,Mistral 7B在多个基准测试中持续优于Llama 2 13B。它在常识推理、世界知识、阅读理解、数学和编码挑战等任务中表现出色。它在这些领域的表现使其成为需要深入理解语言和上下文的人工智能应用的首选。


b


效率与性能相遇——Mistral 7B的独特滑动窗口注意机制不仅提高了性能,还确保了资源的有效利用。在推理、理解和STEM推理任务中,它的表现可以与体积是其三倍的Llama 2模型相媲美。这意味着显著节省内存和提高吞吐量。


c


让我们进入模型构建部分。重要的是,我们无法在免费的Google Colab版本中进行Mistral-7B的微调。


我们需要一个更新的库,所以我们正在直接从Git存储库安装一个软件包。如果您尝试从PyPI安装软件包,您将遇到一个错误。


!pip install -q -U bitsandbytes
!pip install -q -U git+https://github.com/huggingface/transformers.git
!pip install -q -U git+https://github.com/huggingface/peft.git
!pip install -q -U git+https://github.com/huggingface/accelerate.git
!pip install -q trl xformers wandb datasets einops sentencepiece


我们创建了一个包含约210,000个提示的Gath_baize数据集,用于训练Mistral-7b。该数据集包含来自Alpaca、Stack Overflow、医学和Quora数据集的混合数据。


from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,HfArgumentParser,TrainingArguments,pipeline, logging, TextStreamer
from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training, get_peft_model
import os, torch, wandb, platform, warnings
from datasets import load_dataset
from trl import SFTTrainer
from huggingface_hub import notebook_login
base_model, dataset_name, new_model = "mistralai/Mistral-7B-v0.1" , "gathnex/Gath_baize", "gathnex/Gath_mistral_7b"


# Loading a Gath_baize dataset
dataset = load_dataset(dataset_name, split="train")
dataset["chat_sample"][0]


# Load base model(Mistral 7B)
bnb_config = BitsAndBytesConfig(
    load_in_4bit= True,
    bnb_4bit_quant_type= "nf4",
    bnb_4bit_compute_dtype= torch.bfloat16,
    bnb_4bit_use_double_quant= False,
)
model = AutoModelForCausalLM.from_pretrained(
    base_model,
    quantization_config=bnb_config,
    device_map={"": 0}
)
model.config.use_cache = False # silence the warnings. Please re-enable for inference!
model.config.pretraining_tp = 1
model.gradient_checkpointing_enable()
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.add_eos_token = True
tokenizer.add_bos_token, tokenizer.add_eos_token


wandb.login(key = "Wandb authorization key")
run = wandb.init(project='Fine tuning mistral 7B', job_type="training", anonymous="allow")


model = prepare_model_for_kbit_training(model)
peft_config = LoraConfig(
        r=16,
        lora_alpha=16,
        lora_dropout=0.05,
        bias="none",
        task_type="CAUSAL_LM",
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj","gate_proj"]
    )
model = get_peft_model(model, peft_config)


# Training Arguments
# Hyperparameters should beadjusted based on the hardware you using
training_arguments = TrainingArguments(
    output_dir= "./results",
    num_train_epochs= 1,
    per_device_train_batch_size= 8,
    gradient_accumulation_steps= 2,
    optim = "paged_adamw_8bit",
    save_steps= 5000,
    logging_steps= 30,
    learning_rate= 2e-4,
    weight_decay= 0.001,
    fp16= False,
    bf16= False,
    max_grad_norm= 0.3,
    max_steps= -1,
    warmup_ratio= 0.3,
    group_by_length= True,
    lr_scheduler_type= "constant",
    report_to="wandb"
)
# Setting sft parameters
trainer = SFTTrainer(
    model=model,
    train_dataset=dataset,
    peft_config=peft_config,
    max_seq_length= None,
    dataset_text_field="chat_sample",
    tokenizer=tokenizer,
    args=training_arguments,
    packing= False,
)
trainer.train()
# Save the fine-tuned model
trainer.model.save_pretrained(new_model)
wandb.finish()
model.config.use_cache = True
model.eval()


让我们测试这个模型。


def stream(user_prompt):
    runtimeFlag = "cuda:0"
    system_prompt = 'The conversation between Human and AI assisatance named Gathnex\n'
    B_INST, E_INST = "[INST]", "[/INST]"
    prompt = f"{system_prompt}{B_INST}{user_prompt.strip()}\n{E_INST}"
    inputs = tokenizer([prompt], return_tensors="pt").to(runtimeFlag)
    streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
    _ = model.generate(**inputs, streamer=streamer, max_new_tokens=200)


stream("Explain large language models")


# Clear the memory footprint
del model, trainer
torch.cuda.empty_cache()
# Reload the base model
base_model_reload = AutoModelForCausalLM.from_pretrained(
    base_model, low_cpu_mem_usage=True,
    return_dict=True,torch_dtype=torch.bfloat16,
    device_map= {"": 0})
model = PeftModel.from_pretrained(base_model_reload, new_model)
model = model.merge_and_unload()
# Reload tokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"


#push the model to hub
!huggingface-cli login
model.push_to_hub(new_model, use_temp_dir=False)
tokenizer.push_to_hub(new_model, use_temp_dir=False)


结论


来自Fine-tuned Mistral模型的输出效果很好。我们在一个庞大的数据集中进行了训练,包含约210,000个提示-回应对,相比之前的Alpaca数据集有了显著扩展。这个训练过程在一台Tesla V100 32GB GPU上进行,大约花费了45个小时。


文章来源:https://medium.com/@gathnex/mistral-7b-fine-tuning-a-step-by-step-guide-52122cdbeca8
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消