当前位置:   article > 正文

【NLP】人人玩转Llama 2!Meta正式官宣免费用,微调羊驼指南大全集

meta nlp

554eba463bce8c2ef6376d642cf7b531.jpeg


  新智元报道  

编辑:桃子 好困

【导读】Llama 2正式官宣免费用,赶快上手微调一个自己的羊驼吧。

今天,Llama 2宣布正式开源,免费用于研究和商用。

47466de386edea4aa68aaf64b27861d5.png

下载地址:https://ai.meta.com/resources/models-and-libraries/llama-downloads/?utm_source=twitter&utm_medium=organic_social&utm_campaign=llama2&utm_content=card

发布不到一周的Llama 2,已经在研究社区爆火,一系列性能评测、在线试用的demo纷纷出炉。

就连OpenAI联合创始人Karpathy用C语言实现了对Llama 2婴儿模型的推理。

既然Llama 2现已人人可用,那么如何去微调实现更多可能的应用呢?

Llama 2微调指南

这两天,来自Brev的创始工程师Sam L'Huillier,就做了一个简易版的Llama 2微调指南。

甚至还一度冲进了Hacker News榜单的前五。

6830d52f2e33fad3118188affcce112f.png

为了制作这个「对话摘要生成器」,作者利用samsum对话摘要数据集对Llama 2进行了微调。

记得准备一个A10、A10G、A100(或其他显存大于24GB的GPU)。如果没有的话,也可以选择线上的开发环境。

6ac212dafb6f6f733c7b9fd036064acc.png

数据集地址:https://huggingface.co/datasets/samsum

1. 下载模型

克隆Meta的Llama推理存储库(包含下载脚本):

 
 
git clone https://github.com/facebookresearch/llama.git

然后运行下载脚本:

 
 
bash download.sh

在这里,你只需要下载7B模型就可以了。

2. 将模型转换为Hugging Face支持的格式

 
 
pip install git+https://github.com/huggingface/transformerscd transformerspython convert_llama_weights_to_hf.py \    --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir models_hf/7B

现在,我们得到了一个Hugging Face模型,可以利用Hugging Face库进行微调了!

3. 运行微调笔记本:

克隆Llama-recipies存储库:

 
 
git clone https://github.com/facebookresearch/llama-recipes.git

然后,在你喜欢的notebook界面中打开quickstart.ipynb文件,并运行整个notebook。

(此处,作者使用的是Jupyter lab):

 
 
  1. pip install
  2. jupyterlabjupyter lab # in the repo you want to work in

为了适应转换后的实际模型路径,确保将以下一行更改为:

 
 
model_id="./models_hf/7B"

最后,一个经过Lora微调的模型就完成了。

4. 在微调的模型上进行推理

当前,问题在于Hugging Face只保存了适配器权重,而不是完整的模型。所以我们需要将适配器权重加载到完整的模型中。

导入库:

 
 
  1. import torch
  2. from transformers import LlamaForCausalLM, LlamaTokenizer
  3. from peft import PeftModel, PeftConfig

加载分词器和模型:

  1. model_id="./models_hf/7B"
  2. tokenizer = LlamaTokenizer.from_pretrained(model_id)
  3. model =LlamaForCausalLM.from_pretrained(model_id, load_in_8bit=True, device_map='auto', torch_dtype=torch.float16)

从训练后保存的位置加载适配器:

 
 
model = PeftModel.from_pretrained(model, "/root/llama-recipes/samsungsumarizercheckpoint")

运行推理:

  1. eval_prompt = """
  2. Summarize this dialog:
  3. A: Hi Tom, are you busy tomorrow’s afternoon?
  4. B: I’m pretty sure I am. What’s up?
  5. A: Can you go with me to the animal shelter?.
  6. B: What do you want to do?
  7. A: I want to get a puppy for my son.
  8. B: That will make him so happy.
  9. A: Yeah, we’ve discussed it many times. I think he’s ready now.
  10. B: That’s good. Raising a dog is a tough issue. Like having a baby ;-)
  11. A: I'll get him one of those little dogs.
  12. B: One that won't grow up too big;-)A: And eat too much;-))
  13. B: Do you know which one he would like?
  14. A: Oh, yes, I took him there last Monday. He showed me one that he really liked.
  15. B: I bet you had to drag him away.
  16. A: He wanted to take it home right away ;-).
  17. B: I wonder what he'll name it.
  18. A: He said he’d name it after his dead hamster – Lemmy - he's a great Motorhead fan :-)))
  19. ---
  20. Summary:
  21. """
  22. model_input = tokenizer(eval_prompt, return_tensors="pt").to("cuda")
  23. model.eval()
  24. with torch.no_grad():
  25. print(tokenizer.decode(model.generate(**model_input, max_new_tokens=100)[0], skip_special_tokens=True))

LLM Engine微调更便捷

如果你想用自己的数据对Llama 2微调,该如何做?

创办Scale AI初创公司的华人CEO Alexandr Wang表示,自家公司开源的LLM Engine,能够用最简单方法微调Llama 2。

aaf16873cd6c9d57a5391f3623531e31.png

Scale AI的团队在一篇博文中,具体介绍了Llama 2的微调方法。

 
 
  1. from llmengine import FineTune
  2. response = FineTune.create(
  3. model="llama-2-7b",
  4. training_file="s3://my-bucket/path/to/training-file.csv",
  5. )
  6. print(response.json())

数据集

在如下示例中,Scale使用了Science QA数据集。

这是一个由多项选择题组成的流行数据集,每个问题可能有文本上下文和图像上下文,并包含支持解决方案的详尽解释和讲解。

c7d3f2f852aed36627254068dc143519.png

Science QA的示例

目前,LLM Engine支持对「提示完成对」进行微调。首先,需要将Science QA数据集转换为支持的格式,一个包含两列的CSV:prompt和response 。

在开始之前,请安装所需的依赖项。

pip install datasets==2.13.1 smart_open[s3]==5.2.1 pandas==1.4.4

可以从Hugging Face加载数据集,并观察数据集的特征。

 
 
  1. from datasets import load_dataset
  2. from smart_open import smart_open
  3. import pandas as pd
  4. dataset = load_dataset('derek-thomas/ScienceQA')
  5. dataset['train'].features

提供Science QA示例的常用格式是:

 
 
  1. Context: A baby wants to know what is inside of a cabinet. Her hand applies a force to the door, and the door opens.
  2. Question: Which type of force from the baby's hand opens the cabinet door?
  3. Options: (A) pull (B) push
  4. Answer: A.

由于Hugging Face数据集中options的格式是「可能答案的列表」,需要通过添加枚举前缀,将此列表转换为上面的示例格式。

  1. choice_prefixes = [chr(ord('A') + i) for i in range(26)] # A-Z
  2. def format_options(options, choice_prefixes):
  3. return ' '.join([f'({c}) {o}' for c, o in zip(choice_prefixes, options)])

现在,编写格式化函数,将这个数据集中的单个样本转换为输入模型的prompt和response 。

 
 
  1. def format_prompt(r, choice_prefixes):
  2. options = format_options(r['choices'], choice_prefixes)
  3. return f'''Context: {r["hint"]}\nQuestion: {r["question"]}\nOptions:{options}\nAnswer:'''
  4. def format_response(r, choice_prefixes):
  5. return choice_prefixes[r['answer']]

最后,构建数据集。

请注意,Science QA中的某些示例只有上下文图像。(如下演示中会跳过这些示例,因为Llama-2纯粹是一种语言模型,并且不能接受图像输入。)

 
 
  1. def convert_dataset(ds):
  2. prompts = [format_prompt(i, choice_prefixes) for i in ds if i['hint'] != '']
  3. labels = [format_response(i, choice_prefixes) for i in ds if i['hint'] != '']
  4. df = pd.DataFrame.from_dict({'prompt': prompts, 'response': labels})
  5. return df

LLM Engine支持使用「预训练和验证数据集」来进行训练。假如你只提供训练集,LLM Engine会从数据集中随机拆分10%内容进行验证。

因为拆分数据集可以防止模型过度拟合训练数据,不会导致在推理期间实时数据泛化效果不佳。

另外,这些数据集文件必须存储在可公开访问的URL中,以便LLM Engine可以读取。对于此示例,Scale将数据集保存到s3。

并且,还在Github Gist中公开了预处理训练数据集和验证数据集。你可以直接用这些链接替换train_url和val_url 。

 
 
  1. train_url = 's3://...'
  2. val_url = 's3://...'
  3. df_train = convert_dataset(dataset['train'])
  4. with smart_open(train_url, 'wb') as f:
  5. df_train.to_csv(f)
  6. df_val = convert_dataset(dataset['validation'])
  7. with smart_open(val_url, 'wb') as f:
  8. df_val.to_csv(f)

现在,可以通过LLM Engine API开始微调。

微调

首先,需要安装LLM Engine。

pip install scale-llm-engine

接下来,你需要设置Scale API密钥。按照README的说明获你唯一的API密钥。

高级用户还可以按照自托管LLM Engine指南进行操作,由此就不需要Scale API密钥。

 
 
  1. import os
  2. os.environ['SCALE_API_KEY'] = 'xxx'

一旦你设置好一切,微调模型只需要一个API的调用。

在此,Scale选择了Llama-2的70亿参数版本,因为它对大多数用例来说已经足够强大了。

 
 
  1. from llmengine import FineTune
  2. response = FineTune.create(
  3. model="llama-2-7b",
  4. training_file=train_url,
  5. validation_file=val_url,
  6. hyperparameters={
  7. 'lr':2e-4,
  8. },
  9. suffix='science-qa-llama'
  10. )
  11. run_id = response.fine_tune_id

通过run_id ,你可以监控工作状态,并获取每个epoch的实时更新指标,比如训练和验证损失。

Science QA是一个大型数据集,因此训练可能需要一两个小时才能完成。

 
 
  1. while True:
  2. job_status = FineTune.get(run_id).status
  3. # Returns one of `PENDING`, `STARTED`, `SUCCESS`, `RUNNING`,
  4. # `FAILURE`, `CANCELLED`, `UNDEFINED` or `TIMEOUT`
  5. print(job_status)
  6. if job_status == 'SUCCESS':
  7. break
  8. time.sleep(60)
  9. #Logs for completed or running jobs can be fetched with
  10. logs = FineTune.get_events(run_id)

推理与评估

完成微调后,你可以开始对任何输入生成响应。但是,在此之前,确保模型存在,并准备好接受输入。

ft_model = FineTune.get(run_id).fine_tuned_model

不过,你的第一个推理结果可能需要几分钟才能输出。之后,推理过程就会加快。

一起评估下在Science QA上微调的Llama-2模型的性能。

  1. import pandas as pd
  2. #Helper a function to get outputs for fine-tuned model with retries
  3. def get_output(prompt: str, num_retry: int = 5):
  4. for _ in range(num_retry):
  5. try:
  6. response = Completion.create(
  7. model=ft_model,
  8. prompt=prompt,
  9. max_new_tokens=1,
  10. temperature=0.01
  11. )
  12. return response.output.text.strip()
  13. except Exception as e:
  14. print(e)
  15. return ""
  16. #Read the test data
  17. test = pd.read_csv(val_url)
  18. test["prediction"] = test["prompt"].apply(get_output)
  19. print(f"Accuracy: {(test['response'] == test['prediction']).mean() * 100:.2f}%")

微调后的Llama-2能够达到82.15%的准确率,已经相当不错了。

那么,这个结果与Llama-2基础模型相比如何?

由于预训练模型没有在这些数据集上进行微调,因此需要在提示中提供一个示例,以便模型学会遵从我们期望的回复格式。

另外,我们还可以看到与微调类似大小的模型MPT-7B相比的情况。

527023c3c171409bb6857763183d78cd.png

在Science QA上微调Llama-2,其性能增益有26.59%的绝对差异!

此外,由于提示长度较短,使用微调模型进行推理比使用少样本提示更便宜。这种微调Llama-27B模型也优于1750亿参数模型GPT-3.5。

可以看到,Llama-2模型在微调和少样本提示设置中表现都优于MPT,充分展示了它作为基础模型和可微调模型的优势。

此外,Scale还使用LLM Engine微调和评估LLAMA-2在GLUE(一组常用的NLP基准数据集)的几个任务上的性能。

8a330758fd2e01617f147cbaaba73101.png

现在,任何人都可以释放微调模型的真正潜力,并见证强大的AI生成回复的魔力。

我发现虽然Huggingface在transformers方面构建了一个出色的库,但他们的指南对于普通用户来说往往过于复杂。

参考资料:

https://twitter.com/MetaAI/status/1683581366758428672

https://brev.dev/blog/fine-tuning-llama-2

https://scale.com/blog/fine-tune-llama-2

 
 

afeeec1cb1a1944d8153968c2423b8c0.jpeg

 
 
 
 
 
 
 
 
  1. 往期精彩回顾
  2. 适合初学者入门人工智能的路线及资料下载(图文+视频)机器学习入门系列下载机器学习及深度学习笔记等资料打印《统计学习方法》的代码复现专辑机器学习交流qq群955171419,加入微信群请扫码
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/961793
推荐阅读
相关标签
  

闽ICP备14008679号