Axolotl 微调 Mistral Magistral Small 全攻略:文本、Thinking 与视觉多模态实战
2026/9/15 19:54:07 网站建设 项目流程

Axolotl 微调 Mistral Magistral Small 全攻略:文本、Thinking 与视觉多模态实战

【免费下载链接】axolotlGo ahead and axolotl questions项目地址: https://gitcode.com/GitHub_Trending/ax/axolotl

导读

Magistral Small 是 MistralAI 开源的 24B 参数系列模型,在 HuggingFace 上以 2506(纯文本)、2507(Thinking 推理)和 2509(视觉多模态)三个版本发布。本指南以仓库中的 examples/magistral/README.md 为骨架,完整讲解如何用 Axolotl 对这三个版本进行带多轮对话与正确掩码的监督微调(SFT),包括 QLoRA 与 FSDP 两种配置、Thinking 模型特有的 multi-content 数据集格式、视觉模型的图像输入格式,以及环境搭建、显存占用、推理参数等关键实操细节。读完本文,你将能独立复现 Magistral Small 的文本/推理/视觉三种微调流水线,并理解其底层 tokenizer 与数据处理的实现原理。

Magistral Small 系列概览

MistralAI 共发布了三个开源的 Magistral Small 检查点,对应三种不同的能力定位:

版本能力定位微调入口配置
Magistral-Small-2506纯文本对话magistral-small-qlora.yaml
Magistral-Small-2507Thinking(显式思维链推理,含独立思考段)think/magistral-small-think-qlora.yaml
Magistral-Small-2509视觉多模态(图文理解)vision/magistral-small-vision-24B-qlora.yml

此外,MistralAI 还发布了专有的中型版本 Magistral Medium(不在本仓库微调范围内)。仓库作者特别注明,MistralAI 团队提前提供了访问权限以协助适配这些新模型。

三个版本在仓库中的配置、数据集格式与微调流程各有差异,下文分别展开。

环境准备:安装 Axolotl 与 Cut Cross Entropy

安装 Axolotl

Magistral 微调依赖 Axolotl 的mistral-commontokenizer 支持与chat_template数据集类型,请先按 docs/installation.qmd 完成 Axolotl 安装。以 pip 安装为例:

# 确保已安装 PyTorch(最低 2.9.1) uv pip install --no-build-isolation 'axolotl>=0.16.1'

安装 Cut Cross Entropy 插件

为了降低训练显存占用,官方推荐安装 Cut Cross Entropy(截断交叉熵),它只对答案 token 计算交叉熵损失,从而显著减少前向/反向传播的内存开销。仓库提供了安装脚本:

python scripts/cutcrossentropy_install.py | sh

该脚本位于 scripts/cutcrossentropy_install.py,执行后会编译对应的 CUDA kernel。插件在 Axolotl 中的实现见 src/axolotl/integrations/cut_cross_entropy/(包含__init__.py与详细 README),并在三个 Magistral 配置文件中通过 plugins 字段启用:

plugins: - axolotl.integrations.cut_cross_entropy.CutCrossEntropyPlugin

快速开始:文本版 QLoRA 微调

运行仓库自带的 QLoRA 示例:

axolotl train examples/magistral/magistral-small-qlora.yaml

该配置在单卡上大约占用24GB 显存(基于 4-bit 量化加载 + LoRA 适配器)。

配置文件逐项解析

以 examples/magistral/magistral-small-qlora.yaml 为基准:

base_model: mistralai/Magistral-Small-2506 # 启用 mistral-common tokenizer(Magistral 微调的关键开关) tokenizer_use_mistral_common: true # 自动上传 checkpoint 与最终模型到 HF(按需填写) # hub_model_id: username/custom_model_name plugins: - axolotl.integrations.cut_cross_entropy.CutCrossEntropyPlugin load_in_8bit: false load_in_4bit: true datasets: - path: fozziethebeat/alpaca_messages_2k_test type: chat_template dataset_prepared_path: last_run_prepared val_set_size: 0.1 output_dir: ./outputs/lora-out adapter: qlora lora_model_dir: sequence_len: 2048 sample_packing: true lora_r: 32 lora_alpha: 16 lora_dropout: 0.05 lora_target_linear: true lora_target_modules: - gate_proj - down_proj - up_proj - q_proj - v_proj - k_proj - o_proj gradient_accumulation_steps: 4 micro_batch_size: 2 num_epochs: 1 optimizer: adamw_bnb_8bit lr_scheduler: cosine learning_rate: 0.0002 bf16: auto tf32: false gradient_checkpointing: true resume_from_checkpoint: logging_steps: 1 attn_implementation: flash_attention_2 warmup_ratio: 0.1 evals_per_epoch: 1 saves_per_epoch: 1 # save_first_step: true # 取消注释以验证 checkpoint 保存是否正常

关键参数说明:

  • tokenizer_use_mistral_common: true:强制使用mistral-common分词器。这是 Magistral 微调的核心开关,在源码中由 src/axolotl/loaders/tokenizer.py 与 src/axolotl/loaders/processor.py 解析处理,并受 src/axolotl/utils/schemas/model.py 中的配置校验约束。
  • adapter: qlora+load_in_4bit: true:4-bit 量化 + QLoRA 适配器,这是 24B 模型能在单卡 24GB 显存跑起来的关键。若显存充裕,可移除这两行切换为全参微调(见下文 Tips)。
  • sample_packing: true:开启样本打包以提升训练吞吐(但视觉模型不支持,见下文)。
  • lora_target_modules:覆盖了 MLP(gate/down/up)与注意力(q/k/v/o)全部线性层;lora_target_linear: true可自动覆盖其余线性层。
  • attn_implementation: flash_attention_2:使用 FlashAttention-2 加速注意力计算。

多卡扩展:FSDP + QLoRA

若需多卡训练,仓库提供了 FSDP 版本配置 examples/magistral/magistral-small-fsdp-qlora.yaml。与单卡版本相比,主要差异如下:

optimizer: adamw_torch_fused eval_sample_packing: false fsdp: - full_shard - auto_wrap fsdp_config: fsdp_state_dict_type: FULL_STATE_DICT fsdp_transformer_layer_cls_to_wrap: MistralDecoderLayer fsdp_activation_checkpointing: true
  • full_shard+auto_wrap:按 transformer 层自动切分参数,将模型分片到多卡。
  • fsdp_transformer_layer_cls_to_wrap: MistralDecoderLayer:指定包装的层类型为 Mistral 解码层。
  • fsdp_activation_checkpointing: true:FSDP 下的激活重计算,进一步省显存。
  • 注意这里gradient_checkpointing留空,由fsdp_activation_checkpointing接管。

更多多卡/多节点调优可参考 docs/multi-gpu.qmd、docs/multi-node.qmd 与 docs/lora_optims.qmd。

Thinking 版微调:Magistral-Small-2507

examples/magistral/think/README.md 专门讲解了 2507 Thinking 模型的微调。Thinking 模型在回答前会显式输出独立的思维链(Chain-of-Thought)段落,将推理与最终回答分开展示。

运行配置

axolotl train examples/magistral/think/magistral-small-think-qlora.yaml

该配置约占用19.1 GiB 显存。配置主体与文本版一致,仅将base_model换为mistralai/Magistral-Small-2507,并把示例数据集换为Nanobit/text-think-2k-test(见 think/magistral-small-think-qlora.yaml),同时val_set_size: 0以充分利用全部数据训练。

Thinking 数据集格式(multi-content)

Thinking 模型要求multi-content 数据集格式:即content字段不再是一个字符串,而是由多个内容块组成的列表,并在系统消息与助手消息中支持额外的role: thinking。标准示例:

{ "messages": [ { "role": "system", "content": [ { "type": "text", "text": "{SYSTEM_PROMPT}"} ] }, { "role": "user", "content": [ { "type": "text", "text": "Solve this step by step: What is 15% of 240?"} ] }, { "role": "assistant", "content": [ { "type": "thinking", "thinking": "I need to calculate 15% of 240. First, I'll convert 15% to decimal: 0.15. Then multiply: 0.15 × 240 = 36." }, { "type": "text", "text": "To find 15% of 240, I'll multiply 240 by 0.15:\n\n240 × 0.15 = 36\n\nTherefore, 15% of 240 is 36." } ] } ] }

两个必须注意的约束:

  1. 不能混用content: strcontent: list[dict]两种形式,否则数据集加载会失败——整个数据集必须保持一致。
  2. thinking 块支持可选的closed参数,控制是否追加闭合的[/THINK]标签:
{ "type": "thinking", "thinking": "Internal reasoning here...", "closed": true // 默认 true,控制是否追加 [/THINK] 闭合标签 }

源码层面的 thinking 处理机制

从源码结构看,Thinking 数据的处理在 src/axolotl/prompt_strategies/chat_template.py 中实现,相关机制包括:

  • field_thinking(默认reasoning_content)与template_thinking_key:将数据集中的思维链字段映射到聊天模板对应的 key,从而让模板正确渲染思考过程;
  • split_thinking(默认False):若开启,会把content<think>...</think>标记包裹的段落拆分并映射到template_thinking_key(见src/axolotl/prompt_strategies/chat_template.pysplit_thinking相关逻辑);
  • 交互式 CLI 推理端(src/axolotl/cli/chat.py)定义了THINK_MARKER_PAIRS,支持识别<think>/</think><|START_THINKING|>/<|END_THINKING|>等常见思维标记对,说明推理阶段同样能感知 thinking 输出。

视觉版微调:Magistral-Small-2509

examples/magistral/vision/README.md 讲解了 2509 视觉模型的微调,除文本外还支持图像输入。

三步启动

# 1. 安装视觉依赖(含 opencv 的 mistral-common) uv pip install 'mistral-common[opencv]==1.8.5' # 2. 下载示例数据集图片 wget https://huggingface.co/datasets/Nanobit/text-vision-2k-test/resolve/main/African_elephant.jpg # 3. 启动微调 axolotl train examples/magistral/vision/magistral-small-vision-24B-qlora.yml

该配置约占用17GiB 显存

警告:视觉版训练初期 loss 与 grad norm 会比正常情况高很多,仓库作者推测这是该模型当前固有的特性,欢迎社区提交修复(详见 vision/README.md)。

视觉配置要点

examples/magistral/vision/magistral-small-vision-24B-qlora.yml 与文本版差异明显:

base_model: mistralai/Magistral-Small-2509 processor_type: AutoProcessor tokenizer_use_mistral_common: true # 以下三行是处理"含图像的视觉聊天模板"所必需的 skip_prepare_dataset: true remove_unused_columns: false sample_packing: false gradient_accumulation_steps: 1 micro_batch_size: 1 bf16: true tf32: true weight_decay: 0.0 lora_target_modules: 'model.language_model.layers.[\d]+.(mlp|cross_attn|self_attn).(up|down|gate|q|k|v|o)_proj'

关键点:

  • processor_type: AutoProcessor:视觉模型需要 processor 而非纯 tokenizer。
  • skip_prepare_dataset: true/remove_unused_columns: false:当前阶段处理含图像的视觉聊天模板所必需的配置,避免预处理阶段丢弃图像列。
  • sample_packing: false:视觉多模态训练当前不支持样本打包
  • lora_target_modules使用正则表达式:匹配model.language_model.layers.<N>.(mlp|cross_attn|self_attn).(up|down|gate|q|k|v|o)_proj,覆盖语言模型部分所有线性投影层。
  • micro_batch_size: 1gradient_accumulation_steps: 1:单样本起步以控制显存。

视觉数据集格式

视觉模型要求多模态数据集格式(见 docs/multimodal.qmd 的数据集格式章节),但有一个重要例外:不支持传入"image": PIL.Image对象——mistral-common分词器目前只支持path(路径)、urlbase64三种图像表示。

示例格式:

{ "messages": [ {"role": "system", "content": [{ "type": "text", "text": "{SYSTEM_PROMPT}"}]}, {"role": "user", "content": [ { "type": "text", "text": "What's in this image?"}, {"type": "image", "path": "path/to/image.jpg" } ]}, {"role": "assistant", "content": [{ "type": "text", "text": "..." }]} ] }

注意用户消息的content列表中同时包含textimage两种类型的内容块,其中图像通过path字段引用本地文件。

实战技巧与调优建议

1. 使用与模型对齐的 SystemPrompt

强烈建议在数据集中加入与 Magistral 官方微调一致的 SystemPrompt。仓库各示例目录内以SYSTEM_PROMPT.txt命名的文件即为官方对齐用的系统提示词,可将其作为{SYSTEM_PROMPT}占位符的替换来源(上文的示例数据集中即使用了该占位符)。

2. 官方推荐的推理参数

MistralAI 官方对 Magistral 系列推荐的推理参数为:

  • top_p: 0.95
  • temperature: 0.7
  • max_tokens: 40960(文本/Thinking 版;视觉版推荐max_tokens: 131072

3. 从 QLoRA 切换到全参微调

只需从配置中删除adapter: qloraload_in_4bit: true两行,即可从 QLoRA 切换为全参微调(full finetuning),前提是显存充足。

4. 自备数据集

加载自己的数据集可参考 docs/dataset_loading.qmd。Magistral 的数据集类型为type: chat_template,其文本格式遵循 OpenAI Messages 格式,具体结构见 docs/dataset-formats/conversation.qmd 中关于 chat_template 的章节。

5. 保存与验证

配置末尾的# save_first_step: true注释可以取消,用于快速验证 checkpoint 保存是否在你的配置下正常工作,推荐首次跑通时开启。

已知限制与未来工作

当前限制

  • 目前仅支持mistral-commontokenizer 下的监督微调(SFT),且数据集类型仅限于type: chat_template
  • 暂不支持覆盖/自定义 tokens(overriding tokens);
  • 视觉版存在两个额外限制:样本打包(sample packing)不支持;训练初期 loss 与 grad norm 偏高(推测为模型固有特性);
  • Thinking 版要求content形式全局一致(字符串或多内容块二选一),混用会导致加载失败。

未来规划(来自仓库维护者)

  • 补齐 Preference Tuning(偏好微调)、RL(强化学习)等训练范式对 Magistral 的支持;
  • 补齐其他 tokenizer 配置(如 tokens 覆盖)的能力。

仓库还提供了丰富的优化指南可供进一步查阅:multi-gpu 训练、multi-node 训练 与 LoRA 优化,以及视觉相关文档 docs/multimodal.qmd。

【免费下载链接】axolotlGo ahead and axolotl questions项目地址: https://gitcode.com/GitHub_Trending/ax/axolotl

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询