Purpose This project is dedicated to building a small-parameter Chinese Llama2 repository, used to pretrain from scratch + SFT train Chinese LLaMa2, and can run on a single 24G GPU to obtain a chat-llama2 with simple Chinese question-answering capabilities. The project hopes to help LLM beginners get started as quickly as possible, and to collect and aggregate a Chinese pretraining corpus, training a Llama2-Chinese pretrained model with 500M-1B parameters so that it performs well in a certain vertical domain.
Main capabilities The project includes the complete pipeline of pretraining, SFT instruction fine-tuning, reward model, and reinforcement learning (to-do), involving distributed training technologies such as DeepSpeed and Megatron; in addition, it plans to organize a complete set of LLM learning materials (in progress). Specific capabilities include:
- Inference: Added a unified inference entry point infer.py, which supports pretrained and SFT weights, and is compatible with the DDP, torch.compile prefixes and causal attention mask saved by earlier versions. The script automatically infers the model dimension, number of layers, vocabulary size, and number of KV heads from the checkpoint, so there is no longer any need to modify the hardcoded configuration in eval.py. By default it automatically selects CUDA, Apple Silicon MPS, or CPU; when --prompt is not passed, it enters interactive mode, and other commonly used parameters can be viewed via python infer.py --help.
- Data cleaning: Data cleaning code was added on May 21, 2024, including short text filtering, Minhash (and Simhash) deduplication, data storage format conversion, multi-dataset merging, and other functions. The code is in the clean_data directory, and data cleaning was performed using budubaike data as an example.
- Tokenizer data processing: Data preprocessing adopts GPT's general approach, tokenizing the corpus in advance, and adding the end symbol <eos> at the end of a sample to distinguish it from the next sample; all training corpora are concatenated into an array (np.uint16) and stored in .bin binary format; when the corpus is too large, mmap format can optionally be used to avoid memory overflow.
- SFT fine-tuning: Provides a full fine-tuning process, and the output SFT model is saved in the out/sft folder.
Tokenizer description There are two ways to build an LLM tokenizer: construct your own vocabulary and train a custom tokenizers, or choose a tokenizer trained with an open-source model (such as ChatGLM2-6B, Llama2, etc.). Since the Chinese portion of the official llama vocabulary contains only 700 entries, this is also why llama's Chinese capability is barely adequate. Therefore, the project chose the ChatGLM2-6B tokenizer, with a vocabulary size of 64793; this number happens to fall within the range representable by uint16 (0–65535 unsigned integers), so each token needs only two bytes to represent, saving half the storage space compared with the commonly used int32 when the corpus is large.
Pretraining corpus The project collected and processed the following classic datasets: Wiki Chinese Encyclopedia (wikipedia-cn-20230720-filtered), BaiduBaiKe (Baidu Netdisk, extraction code bwvb), C4_zh (Baidu Netdisk part1 extraction code zv4r, part2 extraction code sb83, part3 extraction code l89d), WuDaoCorpora (BAAI, 200G data), shibing624/medical (medical-domain pretraining data). The project open-sourced the pretraining corpus processed by the ChatGLM2-6B tokenizer, totaling 63.4 billion Tokens (Baby-llama2-chinese Corpus, extraction code 6unr); after downloading, just put it in the ./data directory. The author stated that, limited by the machine available (4 RTX 3090s), 63.4 billion Tokens of pretraining corpus + a 300M-parameter model is already their pretraining limit, and they did not use distributed training frameworks such as DeepSpeed or Megatron.
Data cleaning operations cd data_clean; python clear.py. Taking the budubaike data as an example, after the run finishes, baike.parquet and all_no_dulpticates.parquet (all_no_dulpticates_simhash.parquet) files are produced. Experimental results (test device CPU: Intel(R) Xeon(R) Platinum 8168 CPU @ 2.70GHz, budubaike data before deduplication totals 5634898 rows): process_baike() short-text filtering + data storage format conversion, 5634898 to 3605212, taking 552.046 s; remove_dataset_duplicate_rows() Minhash deduplication, 3605212 to 2736033, taking 4 h; remove_dataset_duplicate_rows_simhash() Simhash deduplication, 3605212 to 3548779, taking 23 min. It is recommended to use the parquet format to store data to reduce storage usage, and it is recommended to use Minhash deduplication (better effect than Simhash, but more time-consuming).
Tokenizer data processing operations python data_process.py; after the run finishes, a pretrain_data.bin file is produced in the ./data directory. Each function in the script corresponds to the preprocessing of one corpus; newly added corpora can be extended by yourself.
Fine-tuning method explanation NLP currently has an important paradigm: large-scale pretraining on general-domain data, followed by adaptation to a specific task or domain. The four mainstream fine-tuning methods: Full Fine-tuning, Parameter Efficient Fine-tuning (such as LoRA, Adapter, Prefix-tuning, P-tuning, and P-tuning v2), Prompt Engineering, and Retrieval Augmented Generation. Among them, the first two require fine-tuning the model's parameters (all or part) based on specific task or vertical-domain data; the latter two guide the output by designing the model input template and do not require fine-tuning model parameters, while RAG provides domain knowledge input to the model through an external database. Since this project's model has only about 218M parameters (similar to the 340M parameters of bert-large) and is not large, Full Fine-tuning was chosen.
SFT fine-tuning data Daily question-answering SFT data includes alpaca-zh (from shibing624, self-instruct data obtained based on GPT4 with reference to the Alpaca method, about 50,000 entries) and bell (from BelleGroup, about 1 million Chinese instruction data entries). Medical vertical-domain SFT data includes shibing624/medical, HuatuoGPT-sft-data-v1, DISC-Med-SFT (a subset of the HuatuoGPT-sft-data-v1 DISC-Med-SFT Dataset), ChatMed_Consult-v0.3 (549,326 queries or prompts come from medical consultation questions on the Internet, and responses are answered by the OpenAI GPT-3.5 engine).
SFT sample construction and fine-tuning operations Because SFT corpora are generally small, there is no need to tokenize in advance. Instead, tokenization is done when constructing the Dataloader to build batches and send them to the model; refer to dataset_sft.py. Basic logic: a start token <bos> is needed to separate the prompt and the answer, and an end token <eos> is needed after the answer; when calculating loss, mask the loss for the prompt part and only calculate the loss for the answer part. Command: python sft_data_process.py (processes alpaca-zh and bell; after running, an sft_data.csv file is generated in the ./sft_data directory); for full fine-tuning, run python sft.py; after running, the SFT model is saved in the out/sft folder. If you need to run it in the background, you can use screen: screen -S ambrose (create), screen -r ambrose (enter).
Models and experiments Pretraining corpus v1 (8.278 billion tokens): Wiki Chinese Encyclopedia + BaiduBaiKe + shibing624/medical, comparing Llama2-Chinese-92M-v1, Llama2-Chinese-92M-v1-smallvocab, and Llama2-Chinese-218M-v1. Pretraining corpus v2 (14 billion tokens): Wiki Chinese Encyclopedia + BaiduBaiKe + shibing624/medical + C4_zh, comparing Llama2-Chinese-92M-v2 and Llama2-Chinese-218M-v2. Pretraining corpus v3 (63.4 billion tokens): Wiki Chinese Encyclopedia + BaiduBaiKe + shibing624/medical + C4_zh + WuDaoCorpora, model Llama2-Chinese-218M-v3. On January 24, 2024, two new models on an 8.4 billion token pretraining corpus, Llama2-Chinese-92M-v1-smallvocab and Llama2-Chinese-218M-v1, were added, and compared with Llama2-Chinese-92M-v1 to analyze the impact of model size and vocabulary size on pretraining performance. On February 29, 2024, Llama2-Chinese-218M-v3 on a 63.4 billion token corpus was added, and using it as the base, Llama2-Chinese-218M-v3-MedicalChat was obtained by finetuning with medical vertical domain SFT data. The main comparison among pretrained models is from the perspective of continuation ability; the model fine-tuned with medical SFT data is more accurate than other models in answering medical questions, but forgets too much for everyday popular science questions. Overall, the larger the model and the more corpus, the stronger the model performance.
Applicable scenarios Suitable for learners who want to get started with LLMs to practice the full pretraining + SFT workflow, and also suitable for experiments and comparisons on small-parameter models in vertical domains such as medicine.
Limitations and to-dos The reward model and reinforcement learning parts are marked as to-do; complete LLM learning materials are still in progress; the low-quality text filtering part of data cleaning is marked as to be supplemented; the author did not use distributed training frameworks such as DeepSpeed or Megatron, and the training scale is limited by machine conditions.