SuperAPIAI Directory

mistral-finetune

github.com · AI developer platforms

A light-weight codebase that enables memory-efficient and performant finetuning of Mistral's models.

Open website Alternatives
PricingOpen source开源项目(可免费自部署)
PlatformsAPI

About this tool

mistral-finetune is a lightweight codebase for memory-efficient and well-performing fine-tuning of Mistral models. It is based on LoRA (Low-Rank Adaptation), freezing most weights during training and training only 1-2% of low-rank matrix perturbation additional weights. The repository is currently archived and no longer actively maintained, and the official statement says that a new library or major update may be released in the future if the community needs it or if it can bring value.

Purpose and Positioning The goal of this project is to provide a simple, guided entry point for fine-tuning Mistral models, so it has strong preferences in aspects such as data format, and does not aim to cover multiple model architectures or hardware types. For more general solutions, projects such as torchtune can be referenced.

Hardware and Efficiency For maximum efficiency, using A100 or H100 GPUs is recommended. The code is optimized for multi-GPU single-node training, but for smaller models such as 7B, a single GPU is also sufficient.

Supported Models and Version Updates August 13, 2024: Mistral Large v2 is now compatible with mistral-finetune. You need to download 123B Instruct and set model_id_or_path to the downloaded checkpoint directory. Because the model is larger, fine-tuning requires significantly more memory; currently seq_len must be set to <= 8192, and it is recommended to use a lower learning rate than for other models, for example lr=1e-6 works for most cases. July 19, 2024: Mistral Nemo is now compatible. You need to download 12B Base or Instruct, set model_id_or_path to the downloaded checkpoint directory, and run pip install --upgrade mistral-common to support Tekkenizer (>=1.3.1). Because the vocabulary is larger, the peak memory requirement of the cross-entropy loss increases, and fine-tuning Mistral-Nemo currently requires more memory (the official statement says an improved CE loss will be added soon); currently seq_len must be set to <= 16384, and it is recommended to use the same hyperparameters as for 7B v3.

Main Capabilities Supports LoRA fine-tuning; supports pretraining data and instruction-following data; supports two types of instruction-following data: conversational Instruct data and function calling data; provides data validation tools, data reformatting tools, training configuration examples, and supports Weights & Biases logging.

Usage Quick start steps: clone the repository, install all dependencies, download the official Mistral model (recommended), prepare the dataset, validate the dataset, configure the training script, and start training. Note: For 8x7B Base V1 and 8x7B Instruct V1, you must use the v3 tokenizer and extend the vocabulary to 32768 before fine-tuning; see the "Model extension" section for details. After downloading the 7B-base model, you need to change model_id_or_path in the training script to the downloaded folder path, for example modify example/7B.yaml to include the absolute path of $HOME/mistral_models/7B.

Data format requirements All data files must be in jsonl format. Two types of data files can be constructed:

  • Pretraining data: plain text stored in the "text" key.
  • Instruction-following data: two types are currently supported.
    • Instruct: conversation data is stored in a list under the "messages" key, where each item is a dictionary containing "content" and "role", and "role" is one of "user", "assistant", or "system"; loss is computed only when "role" == "assistant".
    • Function calling: conversation data is stored in a list under the "messages" key, where each item is a dictionary containing "role" and "content" or "tool_calls", and "role" is one of "user", "assistant", "system", or "tool"; loss is computed only when "role" == "assistant". Note: The "id" and "tool_call_id" of "tool_calls" in function calling are randomly generated strings of exactly 9 characters, and it is recommended to generate them automatically in the data preparation script. Before starting training, you should use ./utils/validate_data to validate the dataset format and estimate the training time; this step is crucial.

Instruction-following example You can load one data chunk of Ultachat_200k, create a data folder, load the data with Pandas (pandas and pyarrow need to be installed), split the training and evaluation sets, save them as jsonl, modify the training yaml to add the ultrachat dataset and validate the yaml. If during validation you see the error "many conversations end with the 'user' role", you can use ./utils/reformat_data.py to correct the data. Then you can adjust the number of training steps and run the script again to obtain a summary of the data input and training parameters. On an 8xH100 cluster, the example setup takes about 30 minutes.

Function-calling example You can load the Glaive function-calling dataset in chat format; this dataset does not conform to the required format and needs to be reformatted (for example, renaming "from" to "user" and removing extra newline characters), and you can use ./utils/reformat_data_glaive.py. Note: It is impossible to write a universal reformatting script applicable to all datasets; if a dataset does not conform to the above format, you will most likely need to write your own reformatting script. After that, you can validate the dataset by setting data.instruct_data and data.eval_instruct_data, and use --create_corrected to remove errors, generating $HOME/data/glaive_train.jsonl.corrected and $HOME/data/glaive_eval.jsonl.corrected, then run validation again. During training, you can set max_steps to 300 to speed things up, define run_dir as the experiment folder, and optionally set wandb_project for Weights & Biases logging. Save the training configuration and start training, making sure --nproc-per-node is set to the number of available GPUs. On an 8xH100 node, ultra-chat training takes about 30 minutes, with an MT Bench score of about 6.3; glaive training takes about 1 hour, and the results are suitable for function calling.

Custom training configuration The example mistral-finetune/examples/7B defines reasonable parameters such as learning rate and weight decay, but it is recommended to customize them according to your use case. The training configuration usually includes the following parameters:

  • model_id_or_path: the path to the starting model, which can be a pretrained model or a local model directory.
  • run_dir: the directory for storing training checkpoints and metrics.
  • seq_len: the training sequence length, i.e., the maximum input sequence length processed by the model; samples will be packed to reach seq_len to maximize efficiency.
  • batch_size: the number of training samples per GPU; the total effective batch_size across all GPUs (in tokens) is num_gpus x batch_size x seq_len.
  • max_steps: the maximum number of training steps; the total number of tokens during training is max_steps x num_gpus x batch_size x seq_len.
  • optim.lr: the initial learning rate.
  • optim.weight_decay: weight decay, it is recommended to keep it at 0.1.
  • optim.pct_start: the percentage of the total steps occupied by the learning rate warmup phase, corresponding to pct_start in PyTorch OneCycleLR.
  • lora.rank: the LoRA adapter size, 64 or smaller is recommended.
  • seed: the random seed for initialization and data shuffling/sampling.
  • log_freq: logging frequency (steps).
  • data.instruct_data: the instruction data path, which may contain one or more data sources, in the format <path>:<weight>, for example "/path/to/data1.jsonl:5.,/path/to/data2.jsonl:1.,/path/to/dir_of_jsonls:1.".
  • data.data: an optional additional pretraining data path, which may be left empty.
  • data.eval_instruct_data: an optional evaluation instruction data path; cross-validation is run every eval_freq steps, and metrics are displayed as loss and perplexity.
  • eval_freq: evaluation frequency (steps).
  • no_eval: enable or disable intermediate evaluation; set to False to enable periodic evaluation.
  • ckpt_freq: checkpoint saving frequency (steps).
  • save_adapters: whether to save only the trained LoRA checkpoint, or merge it directly into the base model and save it; when set to False, ensure that a single process has enough CPU and GPU memory to save the full model (usually only feasible for a 7B model). The Weights & Biases API key must be provided through the WANDB_API_KEY environment variable (for example export WANDB_API_KEY=<your-key>), and for security reasons it is not read from the YAML configuration. wandb.project defines the wandb project name.

Inference After model training is complete, it is recommended to use mistral-inference for inference. Assuming lora.safetensors is saved at $HOME/ultra_chat_test/checkpoints/checkpoint_000300/consolidated/lora.safetensors, you can use mistral_inference to chat with the model.

Weights and Biases support Explicit support for Weights & Biases has been added to facilitate monitoring and visualization of training runs. Setup steps: install the wandb library (pip install wandb), and authenticate by providing the API key through the WANDB_API_KEY environment variable.

Up/Down to navigate · Enter to open · ESC to closeBrowse all tools