基于MindSpore的llama微调在OpenI平台上运行

这篇具有很好参考价值的文章主要介绍了基于MindSpore的llama微调在OpenI平台上运行。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

基于MindSpore的llama微调在OpenI平台上运行

克隆预训练模型

克隆chatglm-6b代码仓,下载分布式的模型文件

git lfs install
git clone https://huggingface.co/openlm-research/open_llama_7b

准备环境

安装Transformer

pip install transformers

执行转换脚本

python mindformers/models/glm/convert_weight.py --pt_ckpt_path /home/ma-user/work/models/mindspore/pt_glm_6b.pth --ms_ckpt_path ../models/mindspore/ms_glm_6b.ckpt

注意可能会遇到以下错误:

执行转换脚本,得到转换后的输出文件ms_glm_6b.ckpt

解决方法:

export LD_PRELOAD=$LD_PRELOAD:/home/ma-user/anaconda3/envs/MindSpore/lib/python3.7/site-packages/torch/lib/libgomp-d22c30c5.so.1 

原理:找到torch中的libgomp-d22c30c5.so.1 然后赋值给LD_PRELOAD环境变量,这个报错好像只有ARM平台会有

微调训练集准备

微调方式:lora

目前提供alpaca数据集的预处理脚本用于全参微调/lora微调任务。

数据集地址:https://github.com/tatsu-lab/stanford_alpaca/blob/main/alpaca_data.json

alpaca数据集原始格式样例:

# alpaca examples:
    {
        "instruction": "Describe a time when you had to make a difficult decision.",
        "input": "",
        "output": "I had to make a difficult decision when I was working as a project manager at a construction company. I was in charge of a project that needed to be completed by a certain date in order to meet the client\u2019s expectations. However, due to unexpected delays, we were not able to meet the deadline and so I had to make a difficult decision. I decided to extend the deadline, but I had to stretch the team\u2019s resources even further and increase the budget. Although it was a risky decision, I ultimately decided to go ahead with it to ensure that the project was completed on time and that the client\u2019s expectations were met. The project was eventually successfully completed and this was seen as a testament to my leadership and decision-making abilities."
    },
    {
        "instruction": "Identify the odd one out.",
        "input": "Twitter, Instagram, Telegram",
        "output": "Telegram"
    },

执行alpaca_converter.py,使用fastchat工具添加prompts模板,将原始数据集转换为多轮对话格式

# 脚本路径:tools/dataset_preprocess/llama/alpaca_converter.py
# 执行转换脚本
python alpaca_converter.py \
--data_path /home/ma-user/work/data/alpaca_data.json \
--output_path /home/ma-user/work/data/alpaca-data-conversation.json

参数说明

# 参数说明
data_path: 存放alpaca数据的路径
output_path: 输出转换后对话格式的数据路径

转换后的样例:

{
    "id": "1",
    "conversations": [
      {
        "from": "human",
        "value": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nGive three tips for staying healthy.\n\n### Response:"
      },
      {
        "from": "gpt",
        "value": "1.Eat a balanced diet and make sure to include plenty of fruits and vegetables. \n2. Exercise regularly to keep your body active and strong. \n3. Get enough sleep and maintain a consistent sleep schedule."
      }
    ]
  },

执行llama_preprocess.py,进行数据预处理、Mindrecord数据生成,将带有prompt模板的数据转换为mindrecord格式。

安装依赖:

pip install "fschat[model_worker,webui]"

执行脚本

# 脚本路径:tools/dataset_preprocess/llama/llama_preprocess.py
# 由于此工具依赖fschat工具包解析prompt模板,请提前安装fschat >= 0.2.13 python = 3.9
python llama_preprocess.py \
--dataset_type qa \
--input_glob /home/ma-user/work/data/alpaca-data-conversation.json \
--model_file /home/ma-user/work/models/open_llama_7b/tokenizer.model \
--seq_length 2048 \
--output_file /home/ma-user/work/models/alpaca-fastchat2048.mindrecord

lora微调

目前lora微调适配了llama_7b模型,并给出了默认配置文件config/llama/run_llama_7b_lora.yaml

  • step 1. 修改配置文件,参考全参微调修改训练数据集路径与预训练权重路径。
  • step 2. 启动lora微调任务。
    注:llama_7b_lora模型支持单卡启动,需将配置文件中的use_parallel参数置为False。

脚本启动文章来源地址https://www.toymoban.com/news/detail-771813.html

python run_mindformer.py --config=./configs/llama/run_llama_7b_lora.yaml --use_parallel=False --run_mode=finetune

run_llma_7b_lora.yaml

seed: 0
output_dir: './output'  # 当前不支持自定义修改,请勿修改该默认值
load_checkpoint: '/home/ma-user/work/models/mindspore/open_llama_7b_ms.ckpt'
src_strategy_path_or_dir: ''
auto_trans_ckpt: False  # If true, auto transform load_checkpoint to load in distributed model
only_save_strategy: False
resume_training: False
run_mode: 'finetune'

# trainer config
trainer:
  type: CausalLanguageModelingTrainer
  model_name: 'llama_7b_lora'

# runner config
runner_config:
  epochs: 1
  batch_size: 2
  sink_mode: True
  sink_size: 2

# optimizer
optimizer:
  type: FP32StateAdamWeightDecay
  beta1: 0.9
  beta2: 0.95
  eps: 1.e-8
  learning_rate: 1.e-4

# lr sechdule
lr_schedule:
  type: CosineWithWarmUpLR
  learning_rate: 1.e-4
  warmup_ratio: 0.03
  total_steps: -1 # -1 means it will load the total steps of the dataset

# dataset
train_dataset: &train_dataset
  data_loader:
    type: MindDataset
    dataset_dir: "/home/ma-user/work/models/alpaca-fastchat2048.mindrecord"
    shuffle: True
  input_columns: ["input_ids", "labels"]  # "input_ids", "labels" , labels are used in instruction finetune.
  num_parallel_workers: 8
  python_multiprocessing: False
  drop_remainder: True
  batch_size: 2
  repeat: 1
  numa_enable: False
  prefetch_size: 1

train_dataset_task:
  type: CausalLanguageModelDataset
  dataset_config: *train_dataset
# if True, do evaluate during the training process. if false, do nothing.
# note that the task trainer should support _evaluate_in_training function.
do_eval: False

# eval dataset
eval_dataset: &eval_dataset
  data_loader:
    type: MindDataset
    dataset_dir: "/home/ma-user/work/models/alpaca-fastchat2048.mindrecord"
    shuffle: False
  input_columns: ["input_ids", "labels"]
  num_parallel_workers: 8
  python_multiprocessing: False
  drop_remainder: False
  repeat: 1
  numa_enable: False
  prefetch_size: 1
eval_dataset_task:
  type: CausalLanguageModelDataset
  dataset_config: *eval_dataset

use_parallel: False
# parallel context config
parallel:
  parallel_mode: 1 # 0-data parallel, 1-semi-auto parallel, 2-auto parallel, 3-hybrid parallel
  gradients_mean: False
  enable_alltoall: False
  full_batch: True
  search_mode: "sharding_propagation"
  enable_parallel_optimizer: False
  strategy_ckpt_save_file: "./ckpt_strategy.ckpt"
  parallel_optimizer_config:
    gradient_accumulation_shard: False
    parallel_optimizer_threshold: 64
# default parallel of device num = 8 910A
parallel_config:
  data_parallel: 8
  model_parallel: 1
  pipeline_stage: 1
  use_seq_parallel: False
  optimizer_shard: False
  micro_batch_num: 1
  vocab_emb_dp: True
  gradient_aggregation_group: 4
# when model parallel is greater than 1, we can set micro_batch_interleave_num=2, that may accelerate the train process.
micro_batch_interleave_num: 1

# recompute config
recompute_config:
  recompute: True
  select_recompute: False
  parallel_optimizer_comm_recompute: False
  mp_comm_recompute: True
  recompute_slice_activation: True

# callbacks
callbacks:
  - type: MFLossMonitor
  - type: CheckpointMointor
    prefix: "llama_7b_lora"
    save_checkpoint_steps: 20000
    integrated_save: False
    async_save: False
  - type: ObsMonitor

# mindspore context init config
context:
  mode: 0 #0--Graph Mode; 1--Pynative Mode
  device_target: "Ascend"
  enable_graph_kernel: False
  graph_kernel_flags: "--disable_expand_ops=Softmax,Dropout --enable_parallel_fusion=true --reduce_fuse_depth=8 --enable_auto_tensor_inplace=true"
  max_call_depth: 10000
  max_device_memory: "31GB"
  save_graphs: False
  save_graphs_path: "./graph"
  device_id: 0

# model config
model:
  model_config:
    type: LlamaConfig
    batch_size: 1 # add for increase predict
    seq_length: 2048
    hidden_size: 4096
    num_layers: 32
    num_heads: 32
    vocab_size: 32000
    multiple_of: 256
    rms_norm_eps: 1.0e-6
    bos_token_id: 1
    eos_token_id: 2
    pad_token_id: 0
    ignore_token_id: -100
    compute_dtype: "float16"
    layernorm_compute_dtype: "float32"
    softmax_compute_dtype: "float16"
    rotary_dtype: "float16"
    param_init_type: "float16"
    use_past: False
    pretrain_seqlen: 2048 # seqlen of the pretrain checkpoint: 2048 for llama and 4096 for llama2
    extend_method: "None" # support "None", "PI", "NTK"
    compute_in_2d: False
    use_flash_attention: False
    offset: 0
    use_past_shard: False
    checkpoint_name_or_path: "llama_7b_lora"
    repetition_penalty: 1
    max_decode_length: 512
    top_k: 3
    top_p: 1
    do_sample: False
    pet_config:
      pet_type: lora
      # configuration of lora
      in_channels: 4096
      out_channels: 4096
      lora_rank: 16
      lora_alpha: 16
      lora_dropout: 0.05
  arch:
    type: LlamaForCausalLMWithLora

processor:
  return_tensors: ms
  tokenizer:
    unk_token: '<unk>'
    bos_token: '<s>'
    eos_token: '</s>'
    pad_token: '<pad>'
    type: LlamaTokenizer

# metric
metric:
  type: PerplexityMetric

# wrapper cell config
runner_wrapper:
  type: MFTrainOneStepCell
  scale_sense:
    type: DynamicLossScaleUpdateCell
    loss_scale_value: 4294967296
    scale_factor: 2
    scale_window: 1000
  use_clip_grad: True

eval_callbacks:
  - type: ObsMonitor

auto_tune: False
filepath_prefix: './autotune'
autotune_per_step: 10

profile: False
profile_start_step: 1
profile_stop_step: 10
init_start_profile: False
profile_communication: False
profile_memory: True
layer_scale: False
layer_decay: 0.65
lr_scale_factor: 256

# cfts init config
remote_save_url: "Please input obs url on AICC platform."

到了这里,关于基于MindSpore的llama微调在OpenI平台上运行的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 基于医疗领域数据微调LLaMA——ChatDoctor模型

    ChatDoctor论文: ChatDoctor: A Medical Chat Model Fine-tuned on LLaMA Model using Medical Domain Knowledge ChatDoctor是一款使用LLaMA模型并结合医学知识进行训练的医疗助手,研究人员先收集了10多万条真实医患对话(为了尊重隐私,这些数据已经经过了清洗和匿名的处理),然后使用这些数据对LL

    2024年02月12日
    浏览(26)
  • 大模型入门(四)—— 基于peft 微调 LLaMa模型

    llama-7b模型大小大约27G,本文在单张/两张 16G V100上基于hugging face的peft库实现了llama-7b的微调。 1、模型和数据准备 使用的大模型:https://huggingface.co/decapoda-research/llama-7b-hf,已经是float16的模型。 微调数据集:https://github.com/LC1332/Chinese-alpaca-lora/blob/main/data/trans_chinese_alpaca_data.

    2024年02月10日
    浏览(40)
  • 高效微调技术QLoRA实战,基于LLaMA-65B微调仅需48G显存,真香

    目录 环境搭建 数据集准备 模型权重格式转换 模型微调 模型权重合并

    2024年02月11日
    浏览(34)
  • [NLP]使用Alpaca-Lora基于llama模型进行微调教程

    Stanford Alpaca 是在 LLaMA 整个模型上微调,即对预训练模型中的所有参数都进行微调(full fine-tuning)。但该方法对于硬件成本要求仍然偏高且训练低效。 [NLP]理解大型语言模型高效微调(PEFT) 因此, Alpaca-Lora 则是利用 Lora 技术,在冻结原模型 LLaMA 参数的情况下,通过往模型中加

    2024年02月15日
    浏览(42)
  • 大模型微调踩坑记录 - 基于Alpaca-LLaMa+Lora

    为了使用开放权重的LLM(大语言模型),基于自己的训练集,微调模型,会涉及到如下一些技术要点: 配置运行环境 下载、加载基础模型 收集语料、微调训练 检验训练效果 在实施过程中,遇到不少困难,因此写下这篇文档,做为记录。 (1) 问题描述 在huggingface的模型库中,大

    2024年02月09日
    浏览(33)
  • 微调语言大模型选LoRA还是全参数?基于LLaMA 2深度分析

    本文对比了全参数微调和LoRA,并分析了这两种技术各自的优势和劣势。作者使用了三个真实用例来训练LLaMA 2模型,这提供了比较特定任务的性能、硬件要求和训练成本的基准。本文证明了使用LoRA需要在serving效率和模型质量之间做出权衡,而这取决于具体的任务。 此外,本

    2024年02月05日
    浏览(35)
  • 快速训练自己的大语言模型:基于LLAMA-7B的lora指令微调

    前言: 系统:ubuntu 18.04 显卡:A100-80G(蹭的,嘿嘿~) (本次主要记录如何快速进行大模型的指令微调) 地址:https://github.com/Lightning-AI/lit-llama 切换到工程目录 使用pip安装依赖库 (当然,这里可能会遇到网络问题,安装不了lightning) 可使用以下方式安装: 下载lightning工程

    2024年02月11日
    浏览(42)
  • ChatDoctor:一个基于微调LLaMA模型用于医学领域的医学聊天机器人

    ChatDoctor:一个基于微调LLaMA模型用于医学领域的医学聊天机器人 https://www.yunxiangli.top/ChatDoctor/ Demo.自动聊天医生与疾病数据库演示。 HealthCareMagic-100k.100k患者和医生之间的真实的对话HealthCareMagic.com。 icliniq-10k.患者和医生之间的真实的对话来自icliniq.com icliniq-10 k。 link.ChatDoct

    2024年02月13日
    浏览(37)
  • ChatGPT全球最大开源平替OpenAssistant:基于Pythia和LLaMA微调而来

    论文地址:https://drive.google.com/file/d/10iR5hKwFqAKhL3umx8muOWSRm7hs5FqX/view 项目地址:https://github.com/LAION-AI/Open-Assistant 数据集地址:https://huggingface.co/datasets/OpenAssistant/oasst1 体验地址:https://open-assistant.io/chat 观看公告视频:https://youtu.be/ddG2fM9i4Kk OpenAssistant介绍 最近火爆的ChatGPT使用如

    2024年02月15日
    浏览(29)
  • 大语言模型之十六-基于LongLoRA的长文本上下文微调Llama-2

    增加LLM上下文长度可以提升大语言模型在一些任务上的表现,这包括多轮长对话、长文本摘要、视觉-语言Transformer模型的高分辨4k模型的理解力以及代码生成、图像以及音频生成等。 对长上下文场景,在解码阶段,缓存先前token的Key和Value(KV)需要巨大的内存开销,其次主流

    2024年02月06日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包