中文
Geralmente, existem dois esquemas para o Facebook/lhama de ajuste fino. Um é a série Alpaca de Stanford, e o outro é Vicuna baseado em ShareGpt Corpus. Vicuna usa o diálogo de várias rodadas corpus, e o efeito de treinamento é melhor que o Alpaca, que é inadimplente para o diálogo único. Portanto, é recomendável ajustar o LLAMA baseado em Vicuna. As duas maneiras de ajuste fino são descritas em detalhes nos seguintes projetos (a descrição do modo Lora no fastchat é relativamente simples).
https://github.com/tloen/alpaca-lora
https://github.com/lm-sys/fastchat
O Alpaca-Lora possui requisitos de memória baixa, cerca de 12G 2080TI pode suportar, mas o treinamento de modelos de sessão multi-rodada como a Vicuna requer alta memória de GPU. O treinamento do modelo Vicuna requer pelo menos a memória de GPU de 24G [a recomendação oficial é de 4 * V100 (32G)]. Se você tiver uma placa gráfica de ponta, basta seguir o arquivo para treinar. Se você possui apenas uma placa gráfica 16G, mas deseja personalizar o corpus para reproduzir o modelo Vicuna, você deve pensar em muitas maneiras de reduzir continuamente a precisão de 32 bits para meia precisão 16 bits, depois de 16 bits para 8 bits e acelerar o método de treinamento para atingir a meta.
• Use o método Lora para treinar apenas parte dos parâmetros
• O modelo básico adota a meia precisão llama-7b-hf
• Use load_in_8bit para carregar o modelo básico
• Use a tecnologia PEFT para ajuste fino
• Use BitsandBytes para acelerar
Em seguida, baseamos no fastchat, este artigo modifica o código de treinamento da LORA, usa o corpus ShareGPT e tunes finos em um cartão 16G, ocupando cerca de 13g de memória da GPU.
• Sistema operacional: Centos ou Ubuntu
• NVIDA P100 ou T4: 16G Memória da GPU ou acima
• CUDA, CONDA
git clone https://github.com/git-cloner/llama-lora-fine-tuning
cd llama-lora-fine-tuningwget https://pkg-config.freedesktop.org/releases/pkg-config-0.29.2.tar.gz
tar -zxvf pkg-config-0.29.2.tar.gz
cd pkg-config-0.29.2
./configure --with-internal-glib
make -j4
make check
sudo make installwget https://mirrors.aliyun.com/blfs/conglomeration/icu/icu4c-73_1-src.tgz
tar xf icu4c-73_1-src.tgz
cd icu/source
./configure
make
make check
sudo make install
sudo ldconfigconda create -n llama-lora python=3.10
conda activate llama-lora
pip3 install -r requirements.txtVocê pode baixar o modelo original e convertê-lo em meia precisão ou fazer o download do modelo de meia precisão convertido diretamente em https://huggingface.co/decapoda-research/llama-7b-hf.
export GIT_TRACE=1
export GIT_CURL_VERBOSE=1
pip3 install git+https://github.com/juncongmoo/pyllama -i https://pypi.mirrors.ustc.edu.cn/simple --trusted-host=pypi.mirrors.ustc.edu.cn
python -m llama.download --model_size 7BCUDA_VISIBLE_DEVICES=1 python3 ./convert_llama_weights_to_hf.py --input_dir ./pyllama_data --model_size 7B --output_dir ./pyllama_data/output/7BDownload 52k ShareGPT: https: // huggingface.co/datasets/RyokoAI/ShareGPT52K
Other corpora refer to: https: // github.com/Zjh-819/LLMDataHub
Download sg_90k_part1.json and sg_90k_part2.json into the data directorypython3 fastchat/data/merge.py --in ./data/sg_90k_part1.json ./data/sg_90k_part2.json ./data/dummy_cn.json ./data/dummy_en.json --out ./data/sg_90k.jsonpython3 fastchat/data/clean_sharegpt.py --in ./data/sg_90k.json --out ./data/sharegpt_clean.jsonpython3 fastchat/data/optional_clean.py --in ./data/sharegpt_clean.json --out ./data/sharegpt_clean_1.json --skip-lang SOME_LANGUAGE_CODE
The values of SOME_LANGUAGE_CODE are as follows:
en - English
es - Spanish
fr - French
de - German
it - Italian
ja - Japanese
ko - Korean
zh - Chinese
ar - Arabic
ru - Russian
pt - Portuguese
nl - DutchCUDA_VISIBLE_DEVICES=1 python3 fastchat/data/split_long_conversation.py --in ./data/sharegpt_clean.json --out ./data/sharegpt_clean_split.json --model-name ./pyllama_data/output/7B # Disable wandb
wandb disabled
# In order to prevent the SSH terminal from disconnecting and stopping the training, the training can run in the background (remove the # in three places to run in the background)
# If you have multiple GPUs,using --num_gpus parameter
CUDA_VISIBLE_DEVICES=0,1 # nohup
deepspeed --num_gpus=2 fastchat/train/train_lora.py
--deepspeed ./deepspeed-config.json
--lora_r 8
--lora_alpha 16
--lora_dropout 0.05
--model_name_or_path ./pyllama_data/output/7B
--data_path ./data/sharegpt_clean_split.json
--fp16 True
--output_dir ./output
--num_train_epochs 1
--per_device_train_batch_size 14
--per_device_eval_batch_size 14
--gradient_accumulation_steps 1
--evaluation_strategy " no "
--save_strategy " steps "
--save_steps 2400
--save_total_limit 5
--learning_rate 2e-5
--weight_decay 0.
--warmup_ratio 0.03
--lr_scheduler_type " cosine "
--logging_steps 1
--model_max_length 512
--gradient_checkpointing True # >> lora.log 2>&1 &
# If running in the background, tail lora.log to check the training progress
tail -f lora.logO ajuste fino em P100 (16g) ocupa 13,5g de memória. No caso de uma rodada de treinamento, leva 120 horas, cerca de 5 dias, o que ainda consome muito tempo. O efeito do modelo resultante precisa ser verificado. Model_max_length afetará o tempo de treinamento. Se definido como 1024, o tempo será reduzido pela metade em comparação com 2048, mas afetará o efeito de inferência.
Ajuste fino no único A100 e leva cerca de 16 horas.
deepspeed fastchat/train/train_lora.py
--deepspeed ./deepspeed-config.json
--lora_r 8
--lora_alpha 16
--lora_dropout 0.05
--model_name_or_path ./pyllama_data/output/7B
--data_path ./data/sharegpt_clean_split.json
--fp16 True
--output_dir ./output
--num_train_epochs 1
--per_device_train_batch_size 56
--per_device_eval_batch_size 56
--gradient_accumulation_steps 1
--evaluation_strategy " no "
--save_strategy " steps "
--save_steps 1200
--save_total_limit 5
--learning_rate 2e-5
--weight_decay 0.
--warmup_ratio 0.03
--lr_scheduler_type " cosine "
--logging_steps 1
--model_max_length 1024
--gradient_checkpointing TrueO modelo Lora Peft treinado consiste em adaptador_config.json, adaptter_model.bin e treinador_state.json. Abaixo está a estrutura do arquivo do PEFT e o modelo de llama original.
model
───llama-peft
│ adapter_config.json
│ adapter_model.bin
│ trainer_state.json
│
└──llama_7b
config.json
generation_config.json
pytorch_model-00001-of-00002.bin
pytorch_model-00002-of-00002.bin
pytorch_model.bin.index.json
special_tokens_map.json
tokenizer.json
tokenizer.model
tokenizer_config.jsonCUDA_VISIBLE_DEVICES=0 python generate.py --base_model ./model/llama-7b --lora_weights ./model/llama-peft