ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

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

Axolotl 微调 Mistral Magistral Small 全攻略:文本、Thinking 与视觉多模态实战 Axolotl 微调 Mistral Magistral Small 全攻略文本、Thinking 与视觉多模态实战【免费下载链接】axolotlGo ahead and axolotl questions项目地址: https://gitcode.com/GitHub_Trending/ax/axolotl导读Magistral Small 是 MistralAI 开源的 24B 参数系列模型在 HuggingFace 上以 2506纯文本、2507Thinking 推理和 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.yamlMagistral-Small-2507Thinking显式思维链推理含独立思考段think/magistral-small-think-qlora.yamlMagistral-Small-2509视觉多模态图文理解vision/magistral-small-vision-24B-qlora.yml此外MistralAI 还发布了专有的中型版本 Magistral Medium不在本仓库微调范围内。仓库作者特别注明MistralAI 团队提前提供了访问权限以协助适配这些新模型。三个版本在仓库中的配置、数据集格式与微调流程各有差异下文分别展开。环境准备安装 Axolotl 与 Cut Cross Entropy安装 AxolotlMagistral 微调依赖 Axolotl 的mistral-commontokenizer 支持与chat_template数据集类型请先按 docs/installation.qmd 完成 Axolotl 安装。以 pip 安装为例# 确保已安装 PyTorch最低 2.9.1 uv pip install --no-build-isolation axolotl0.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 tokenizerMagistral 微调的关键开关 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: qloraload_in_4bit: true4-bit 量化 QLoRA 适配器这是 24B 模型能在单卡 24GB 显存跑起来的关键。若显存充裕可移除这两行切换为全参微调见下文 Tips。sample_packing: true开启样本打包以提升训练吞吐但视觉模型不支持见下文。lora_target_modules覆盖了 MLPgate/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: truefull_shardauto_wrap按 transformer 层自动切分参数将模型分片到多卡。fsdp_transformer_layer_cls_to_wrap: MistralDecoderLayer指定包装的层类型为 Mistral 解码层。fsdp_activation_checkpointing: trueFSDP 下的激活重计算进一步省显存。注意这里gradient_checkpointing留空由fsdp_activation_checkpointing接管。更多多卡/多节点调优可参考 docs/multi-gpu.qmd、docs/multi-node.qmd 与 docs/lora_optims.qmd。Thinking 版微调Magistral-Small-2507examples/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-contentThinking 模型要求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, Ill convert 15% to decimal: 0.15. Then multiply: 0.15 × 240 36. }, { type: text, text: To find 15% of 240, Ill multiply 240 by 0.15:\n\n240 × 0.15 36\n\nTherefore, 15% of 240 is 36. } ] } ] }两个必须注意的约束不能混用content: str与content: list[dict]两种形式否则数据集加载会失败——整个数据集必须保持一致。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.py中split_thinking相关逻辑交互式 CLI 推理端src/axolotl/cli/chat.py定义了THINK_MARKER_PAIRS支持识别think//think、|START_THINKING|/|END_THINKING|等常见思维标记对说明推理阶段同样能感知 thinking 输出。视觉版微调Magistral-Small-2509examples/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: 1、gradient_accumulation_steps: 1单样本起步以控制显存。视觉数据集格式视觉模型要求多模态数据集格式见 docs/multimodal.qmd 的数据集格式章节但有一个重要例外不支持传入image: PIL.Image对象——mistral-common分词器目前只支持path路径、url、base64三种图像表示。示例格式{ messages: [ {role: system, content: [{ type: text, text: {SYSTEM_PROMPT}}]}, {role: user, content: [ { type: text, text: Whats in this image?}, {type: image, path: path/to/image.jpg } ]}, {role: assistant, content: [{ type: text, text: ... }]} ] }注意用户消息的content列表中同时包含text与image两种类型的内容块其中图像通过path字段引用本地文件。实战技巧与调优建议1. 使用与模型对齐的 SystemPrompt强烈建议在数据集中加入与 Magistral 官方微调一致的 SystemPrompt。仓库各示例目录内以SYSTEM_PROMPT.txt命名的文件即为官方对齐用的系统提示词可将其作为{SYSTEM_PROMPT}占位符的替换来源上文的示例数据集中即使用了该占位符。2. 官方推荐的推理参数MistralAI 官方对 Magistral 系列推荐的推理参数为top_p: 0.95temperature: 0.7max_tokens: 40960文本/Thinking 版视觉版推荐max_tokens: 1310723. 从 QLoRA 切换到全参微调只需从配置中删除adapter: qlora与load_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暂不支持覆盖/自定义 tokensoverriding 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),仅供参考
返回列表