从 GPT 到 Mistral-7B:AI 对话技术再突破!

介绍

近年来,人工智能领域取得了显著的进步,尤其是在大型语言模型领域。LLM 可以生成类似人类的文本、总结文档和编写软件代码。Mistral-7B 是最近支持英文文本和代码生成能力的大型语言模型之一,可用于文本摘要、分类、文本补全、代码补全等各种任务。

Mistral-7B-Instruct 的与众不同之处在于,尽管参数较少,但它仍能提供出色的性能,使其成为高性能且具有成本效益的解决方案。该模型最近在基准测试结果显示它不仅优于 MT-Bench 上的所有 7B 模型,而且与 13B 聊天模型竞争良好后获得了普及。在这篇博客中,我们将探讨 Mistral 7B 的特性和功能,包括其用例、性能以及微调模型的实践指南。

学习目标

● 了解大型语言模型和 Mistral 7B 的工作原理

● Mistral 7B 的架构和基准测试

● Mistral 7B 的用例及其性能

● 深入研究用于推理和微调的代码

什么是大型语言模型?

大型语言模型的架构是由 transformer 形成的,transformer 使用注意力机制来捕获数据中的长程依赖关系,其中多层 transformer 块包含多头自注意力和前馈神经网络。这些模型在文本数据上进行了预训练,学习预测序列中的下一个单词,从而捕获语言中的模式。训练前的权重可以针对特定任务进行微调。我们将专门研究 Mistral 7B LLM 的架构,以及是什么让它脱颖而出。

Mistral 7B 架构

Mistral 7B 模型转换器架构有效地平衡了高性能与内存使用,使用注意力机制和缓存策略在速度和质量上优于大型模型。它使用 4096 窗口滑动窗口注意力 (SWA),通过允许每个标记关注前体标记的子集,优化较长序列的注意力,最大限度地提高较长序列的注意力。

给定的隐藏层可以在由窗口大小和层深度决定的距离下访问输入层的令牌。该模型集成了对 Flash Attention 和 xForers 的修改,速度比传统注意力机制快了一倍。此外,滚动缓冲区缓存机制保持固定的缓存大小,以实现高效的内存使用。

Google Colab 中的 Mistral 7B

让我们深入研究代码,并了解如何在 Google Colab 中使用 Mistral 7B 模型运行推理。我们将使用带有单个 T4 GPU 的免费版本,并从 Hugging Face 加载模型。

1.在 Colab 中安装并导入 ctransformers 库。

#intsall ctransformers
pip install ctransformers[cuda]

#import
from ctransformers import AutoModelForCausalLM

2.从 Hugging Face 初始化模型对象并设置必要的参数。我们将使用该模型的不同版本,因为 Mistral AI 的原始模型在将整个模型加载到 Google Colab 的内存中时可能会出现问题。

#load the model from huggingface with 50 gpu layers
llm = AutoModelForCausalLM.from_pretrained("TheBloke/Mistral-7B-Instruct-v0.1-GGUF", 
model_file="mistral-7b-instruct-v0.1.Q4_K_M.gguf", 
model_type = "mistral", gpu_layers = 50)

3.定义一个函数以在 Google Colab 中垂直打印结果。如果此步骤在不同的环境中运行,则可以跳过或修改此步骤。

#function to print the model output in colab in a readable manner
def colab_print(text, max_width = 120):
  words = text.split()
  line = ""
  for word in words:
    if len(line) + len(word) + 1 > max_width:
      print(line)
      line = ""
    line += word + " "
  print (line)

4.使用模型生成文本并查看结果。修改参数以更改生成的文本的质量。

#generate text
colab_print(llm('''Give me a well-written paragraph in 5 sentences about a Senior Data 
Scientist (name - Suvojit) who writes blogs on LLMs on Analytics Vidhya. He studied 
Masters in AIML in BITS Pilani and works at AZ Company, with a total of 4 years of 
experience. Start the sentence with - Suvojit is a''', 
max_new_tokens = 2048, temperature = 0.9, top_k = 55, top_p = 0.93, 
repetition_penalty = 1.2))

模型响应:Suvojit 是一名高级数据科学家,他在 AZ 公司工作了 4 年,是其团队的一员,专注于使用有限内存机器学习技术在客户的品牌和业务线中设计、实施和改进消费者行为预测模型。他在 Analytics Vidhya 上撰写了有关 LLM 的文章,这有助于他了解数据科学的最新趋势。他拥有 BITS Pilani 的 AIML 硕士学位,在那里他研究了机器学习算法及其应用。Suvojit 热衷于利用他的数据科学知识来帮助企业做出更好的决策并提高绩效。

使用案例

让我们更详细地看一下Mistral 7B的一些用例。

译本

Mistral 7B 支持多种语言的翻译。让我们看一下英语到法语和西班牙语的翻译并检查准确性。

#translate English to French
colab_print(llm('''Translate this text from English to French: 
"Suvojit is a Senior Data Scientist who writes blogs on Analytics Vidhya."''',
                max_new_tokens = 2048, temperature = 0.9, top_k = 55, top_p = 0.93, 
                repetition_penalty = 1.2))

模型响应: 翻译为:“Suvojit est un scientifique des données sénior qui écrit des blogues sur Analytics Vidhya。
模型响应: 翻译为:“Suvojit 是一名高级数据科学家,他在博客上发表了有关 Analytics Vidhya 的文章。

#tranlsate English to Spanish
colab_print(llm('''Translate this text from English to Spanish:
"Suvojit is a Senior Data Scientist who writes blogs on Analytics Vidhya."''',
                max_new_tokens = 2048, temperature = 0.9, top_k = 55, top_p = 0.93, 
                repetition_penalty = 1.2))

模型响应: 翻译为:“Suvojit es un Senior Data Científico que escribe blogs en Analytics Vidhya。

综述

使用 Mistral 7B 使用适当的摘要说明将文档汇总为较短的版本。

#Define the prompt with instructions
prompt = '''[INST] You are a helpful code assistant. Your task is to summarize text 
into exactly two short sentences:

Transformers have revolutionized the field of large language models with their ability 
to capture long-range dependencies and intricate patterns in text. Originating 
from the paper "Attention Is All You Need" by Vaswani et al. in 2017, transformers 
introduced the self-attention mechanism, which weighs input tokens differently based 
on their relevance to a given token. This mechanism enables transformers to process
information more flexibly than traditional RNNs or LSTMs. Consequently, models 
like GPT, BERT, and their subsequent iterations have been built on the transformer 
architecture, leading to breakthroughs in numerous natural language processing tasks. 
Their parallel processing capabilities further make them conducive to training on 
vast amounts of data. However, as these models grow in size, concerns about their  
environmental impact and computational demands also emerge. Despite these challenges, 
the transformative power of transformers in language models remains undeniable.

Just summarize the text in exactly 2 short sentences without explanations:
[/INST]'''

#Summarize
colab_print(llm(prompt,
                max_new_tokens = 2048, temperature = 0.9, top_k = 55, top_p = 0.93, 
                repetition_penalty = 1.2))

模型响应: Transformer 通过捕获远程依赖关系和复杂的模式彻底改变了大型语言模型,引入了一种自注意力机制,使它们能够灵活地处理信息,随后的实现包括 GPT 和 BERT 等突破。然而,随着这些模型规模的增长,人们对它们对环境的影响和计算需求的担忧也随之而来,尽管存在这些挑战,但它们在语言建模中仍然具有不可否认的变革性。

自定义说明

我们可以使用 [INST] 标签来修改用户输入,以从模型中获取特定响应。例如,我们可以根据文本描述生成 JSON。

prompt = '''[INST] You are a helpful code assistant. Your task is to generate a valid 
JSON object based on the given information:

My name is Suvojit Hore, working in company AB and my address is AZ Street NY.

Just generate the JSON object without explanations:
[/INST]
'''

colab_print(llm(prompt,
                max_new_tokens = 2048, temperature = 0.9, top_k = 55, top_p = 0.93, 
                repetition_penalty = 1.2))

模型响应: “'json { ”name“: ”Suvojit Hore“, ”company“: ”AB“, ”address“: ”AZ Street NY“ } ”'

微调 Mistral 7B

让我们看看如何在 Google Colab 上使用单个 GPU 微调模型。我们将使用一个数据集,将关于图像的少量描述转换为详细且高度描述性的文本。这些结果可以在 Midjourney 中用于生成特定图像。目标是训练 LLM 充当图像生成的提示工程师。

在 Google Colab 中设置环境并导入必要的库:

# Install the necessary libraries
!pip install pandas autotrain-advanced -q
!autotrain setup --update-torch
!pip install -q peft  accelerate bitsandbytes safetensors

#import the necesary libraries
import pandas as pd
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import transformers
from huggingface_hub import notebook_login

从浏览器登录 Hugging Face 并复制访问令牌。使用此令牌登录到笔记本中的 Hugging Face。 notebook_login()

将数据集上传到 Colab 会话存储。我们将使用 Midjourney 数据集。

df = pd.read_csv("prompt_engineering.csv")
df.head(5)

使用具有适当参数的自动训练来训练模型。修改以下命令,为你自己的 Huggin Face 存储库和用户访问令牌运行它。

!autotrain llm --train --project_name mistral-7b-sh-finetuned --model 
username/Mistral-7B-Instruct-v0.1-sharded --token hf_yiguyfTFtufTFYUTUfuytfuys 
--data_path . --use_peft --use_int4 --learning_rate 2e-4 --train_batch_size 12 
--num_train_epochs 3 --trainer sft --target_modules q_proj,v_proj --push_to_hub 
--repo_id username/mistral-7b-sh-finetuned

现在,让我们使用微调的模型来运行推理引擎并生成图像的一些详细描述。

#adapter and model
adapters_name = "suvz47/mistral-7b-sh-finetuned"
model_name = "bn22/Mistral-7B-Instruct-v0.1-sharded" 

device = "cuda"

#set the config
bnb_config = transformers.BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16
)

#initialize the model
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    load_in_4bit=True,
    torch_dtype=torch.bfloat16,
    quantization_config=bnb_config,
    device_map='auto'
)

加载微调的模型和分词器。

#load the model and tokenizer
model = PeftModel.from_pretrained(model, adapters_name) 

tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.bos_token_id = 1

stop_token_ids = [0]

只需几句话即可生成详细且描述性的 Midjourney 提示。

#prompt
text = "[INST] generate a midjourney prompt in less than 20 words for A computer 
with an emotional chip     [/INST]"

#encoder and decoder
encoded = tokenizer(text, return_tensors="pt", add_special_tokens=False)
model_input = encoded
model.to(device)
generated_ids = model.generate(**model_input, max_new_tokens=200, do_sample=True)
decoded = tokenizer.batch_decode(generated_ids)
print('\n\n')
print(decoded[0])

模型响应:当带有情感芯片的计算机开始处理其情感时,它开始质疑自己的存在和目的,从而开启了自我发现和自我完善的旅程。

#prompt
text = "[INST] generate a midjourney prompt in less than 20 words for A rainbow 
chasing its colors     [/INST]"

#encoder and decoder
encoded = tokenizer(text, return_tensors="pt", add_special_tokens=False)
model_input = encoded
model.to(device)
generated_ids = model.generate(**model_input, max_new_tokens=200, do_sample=True)
decoded = tokenizer.batch_decode(generated_ids)
print('\n\n')
print(decoded[0])

模型响应:追逐色彩的彩虹发现自己置身于沙漠中,天空是一望无际的蓝色海洋,彩虹的颜色散落在沙子中。

结论

Mistral 7B 已被证明是大型语言模型领域的重大进步。其高效的架构,结合其卓越的性能,展示了其成为未来各种 NLP 任务的主要内容的潜力。这篇博客提供了有关模型架构、应用以及如何利用其功能执行特定任务(如翻译、摘要和微调其他应用程序)的见解。通过正确的指导和实验,Mistral 7B可以重新定义LLM的界限。

关键要点

● 尽管参数较少,但 Mistral-7B-Instruct 在性能上表现出色。

● 它使用滑动窗口注意力进行长序列优化。

● Flash Attention 和 xFormers 等功能使其速度翻倍。

● 滚动缓冲区缓存可确保高效的内存管理。

● 多功能:处理翻译、摘要、结构化数据生成、文本生成和文本完成。

● 提示工程添加自定义指令可以帮助模型更好地理解查询并执行多个复杂的语言任务。

● 微调 Mistral 7B 以执行任何特定的语言任务,例如充当提示工程师。

常见问题解答

问题1. Mistral-7B 与其他大型语言模型的主要区别是什么?

答:Mistral-7B 专为效率和性能而设计。虽然它的参数比其他一些模型少,但它的架构进步,如滑动窗口注意力,使其能够提供出色的结果,甚至在特定任务中优于更大的模型。

问题2. 是否可以为自定义任务微调 Mistral-7B?

答:是的,Mistral-7B 可以针对各种任务进行微调。本指南提供了一个微调模型的示例,以将简短的文本描述转换为详细的图像生成提示。

问题3. Mistral-7B 中的滑动窗口注意力机制如何提高其性能?

答:滑动窗口注意力 (SWA) 允许模型有效地处理较长的序列。SWA 的窗口大小为 4096,优化了注意力操作,使 Mistral-7B 能够在不影响速度或准确性的情况下处理冗长的文本。

问题4. 您是否需要一个特定的库来运行 Mistral-7B 推理?

答:是的,在运行 Mistral-7B 推理时,我们建议使用 ctransformers 库,尤其是在 Google Colab 中工作时。您还可以从 Hugging Face 加载模型以增加便利性

问题5. 使用 Mistral-7B 生成输出时,如何确保最佳结果?

答:在输入提示中制定详细说明至关重要。Mistral-7B 的多功能性使其能够理解并遵循这些详细说明,确保准确和所需的输出。适当的提示工程可以显著提高模型的性能。
 


非常感谢大家的阅读,小Mo在这里祝你在末来的 Python 学习职业生涯中一切顺利!

后续小Mo会不定期更新书籍、视频等学习资源,以上这些书籍资料也可通过关注微信公众号免费获取 哦!

欢迎关注我们的微信公众号:MomodelAl

同时,欢迎使用「Mo AI编程」微信小程序

以及登录官网,了解更多信息:Mo 人工智能教育实训平台

Mo,发现意外,创造可能

注:部分资源来源于互联网,若有侵权,请直接联系作者删除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值