在本章中,我们将学习 fine-tuning models,以及 Azure AI Foundry 中可用的选项。Azure OpenAI 有很多可以 fine-tune 的 models,同时也提供 serverless 和 managed compute 两类 fine-tuning 选项。你还将学习为什么需要 fine-tuning,哪些 industry-specific tasks 适合 fine-tuning,以及如何评估并确认针对特定 customer scenarios 微调模型是否真正创造了新价值。
例如,我们来看一个 construction RFP application。RFP 是一个繁琐且耗时的流程。假设我们使用 retrieval augmented generation,整体 accuracy 达到 73%。但为了改善 RFP response,并加入你自己的知识,我们可以使用 fine-tuning,初始 accuracy 可以提升到 76%。随后,通过向 fine-tuning dataset 增加更多数据,还可以进一步提升效果。
本章将覆盖以下主要主题:
- Introduction to fine-tuning
- Type of fine-tuning and compute options
- Fine-tuning in the portal
Technical requirements
首先,我们需要能够访问 Azure AI Foundry resources,而这又需要能够访问 Azure portal。如果想通过代码执行 fine-tuning,最好安装 Visual Studio Code,并配置 Azure AI Projects SDK。你需要对 fine-tuning topics 有一些基本理解,因为本章不会详细讲解具体技术,也不会深入论文内容。
我们也可以使用 Azure AI Foundry UI 上传 training 和 validation dataset,并通过 UI 运行 fine-tuning。
以下是一些用于了解 fine-tuning 最新信息的参考内容: learn.microsoft.com/en-us/azure…
Introduction to fine-tuning
Fine-tuning 的概念是:拿一个已经具备 general knowledge 的 existing model,通过加入 industry-specific 或 task-specific functionality,尝试增加或改变它的 behavior。你可以选择 Azure OpenAI 这类 closed-source models,也可以选择 Llama 以及其他 vendors 提供的 open-source models。由于这些 models 体量巨大,在 Azure OpenAI 中只有少数 models 暴露了 fine-tuning 能力。这里我们称之为 Fine-tuning as a Service,也就是说,fine-tuning 应该足够容易,不需要我们担心 compute 和 compute design。
Fine-tuning 的一个大挑战是,根据 model size 不同,所需 compute resources 会非常巨大,比如需要 heavy-duty GPU 和 high bandwidth networking。使用 Azure AI Foundry 时,这些 fine-tuning 中具有挑战性的工作会被平台屏蔽掉,让 fine-tuning 更容易执行。
Fine-tuning 是一个 iterative 和 continuous process。它也很有挑战性,因为我们需要为特定任务收集 dataset,并将其转换成 conversational dataset 来进行 fine-tune。不仅如此,我们还需要用 ground truth dataset 评估 model,以确认 model 的表现符合预期。
我们需要 fine-tune 的原因包括:
- Changing the style and tone
- Domain specialization
- Task-specific performance
- Instructions following
- Compliance and safety
- Language and cultural adaptation
下面是针对特定 task 或 use case 的 fine-tuning process 示例:
图 5.1:The fine-tuning process
上图展示了完整的端到端过程:从拿到一个 use case 开始,经过各种 tasks 或 processes,获取 data sources,创建 data sets,进行 fine-tuning、evaluating、benchmarking,最后创建 consumption layer,定义这些 models 如何被使用。
如果你正在构建 generic model,那么 Common Crawl 和其他 datasets 都可使用。但这也需要专门的 GPU hardware 来处理 TB 级海量数据。NVIDIA 拥有最好的 GPUs,例如 H100 或 H200。最新的 GPU compute models 被称为 B200 和 B300,它们是面向 data center 的 racks,配备 high-performance GPUs。
Fine-tune 所需时间会根据 model size、compute size 和 dataset size 而变化。Fine-tuning 也是一个迭代过程,需要大量 testing 和 evaluation,以确保 output 落在预期范围内。
Dataset format 也可能会根据你选择的 base model 而变化。例如,GPT-4.1 Nano 会接收 messages 作为 input,这是一种 chat style,包含 system message,然后是 assistant、user 的组合,以及 completion。而 Llama 3.2 1B model 可能接收一个 prompt 并生成 completion,其中 prompt 使用 start 和 end tokens 作为 delimiters。
我在使用不同 models 时看到过这一挑战:它们会基于 text、multimodal 和 reasoning models 不断变化,并且各自都有自己的 schema。因此,当我们收集数据时,需要基于 model requirement 将数据转换成特定格式。
Fine-tuning 还需要 qualified resources,他们需要能够创建 dataset,然后把 dataset 转换为 model format,再使用 Azure AI Foundry Fine-tuning UI 或编写代码实现自己的 fine-tuning 方法。在本书写作时,AI Foundry 支持 Azure OpenAI Models。Model version 会取决于当前可用情况,因此请在 Microsoft Learn 网站上查看 model capabilities,以获取当前 model version。
本书中,我将使用 Azure OpenAI GPT-4.1-nano 作为示例。我也会使用 HelpSteer dataset,这是 NVIDIA 为 fine-tuning 策划的 customer care dataset。
Fine-tuning 的 model comparison table 可在以下位置查看: learn.microsoft.com/en-us/azure…
行业中有多种 fine-tuning strategies。例如,Azure AI Foundry 提供 supervised fine-tuning(SFT)、direct preference optimization(DPO)和 reinforced fine-tuning(RFT)等策略。
本节只覆盖 fine-tuning。对于创建 base model 所需的 pre-training 和 post-training,pre-training 与 post-training 的 dataset schema 可能会有很大变化。Pre-training 需要不同的 schema,post-training 也会不同。
Types of fine-tuning and compute options
在本节中,我们将学习 Azure AI Foundry 中可用的不同 training techniques。Fine-tuning 可以帮助不同 industry use cases 以更高 quality 和 safety 运行。
由于 language models 是用 general knowledge dataset 构建的,这些 models 并不具备行业上下文。例如,healthcare practitioners 会花大量时间填写 forms,并记录与 patients 的 conversation。如果我们使用普通 general language model,它们可能无法理解 healthcare-specific terms,例如 diagnosis 或用于 billing 的 medical code。在这些场景中,我们可以拿 base model,无论它是 small language model 还是 large language model,都可以通过 fine-tuning 加入新的 industry knowledge,从而针对特定 task 提升能力。
我观察到的是,model 过度 generalization 会损失 quality,因此更好的方式可能是瞄准某个特定 industry task,并对 model 进行 fine-tune。
Types of fine-tuning
Azure AI Foundry 中可用的 fine-tuning strategies 包括:
- Supervised fine-tuning(SFT)
- Direct preference optimization(DPO)
- Reinforced fine-tuning(RFT)
Supervised fine-tuning or SFT
这种策略适合 text、question and answer 类型,或者 chat style tasks。很多 models 都支持这种能力,也是我见过最常用的技术之一。它也适合 domain specialization、执行特定 task、改变 style and tone、instruction following 和 language conversions。
大多数项目可以从这里开始。SFT 覆盖最广泛的 fine-tuning scenarios,并且在 input-output training data 清晰的情况下,能提供可靠结果。
Direct preference optimization or DPO
DPO 用于 fine-tuning,尤其适合非常需要 instruction following 的任务,特别是 agentic AI 类型的 application,因为这类 application 会基于 language model output 执行动作。
这种技术可以提升 response quality、safety,以及与 human preferences 的对齐程度。当你有 preferred vs. non-preferred outputs 的示例,或者需要优化 helpfulness、harmlessness 或 style 等主观质量时,就可以使用它。Use cases 包括将 models 适配到特定 style and tone,或者让 model 适配 cultural preferences。
Reinforced fine-tuning or RFT
这里使用 reinforcement learning,根据 rewards 来 fine-tune model,非常适合 complex optimization tasks。它也适用于可用数据较少的场景。
RFT 非常适合 mathematics、chemistry 和 physics 等 objective domains,因为这些领域有清晰的对错答案,而且 model 已经展示出一定能力。当 lucky guessing 很难发生,并且 expert evaluators 会稳定同意一个明确正确答案时,RFT 效果最好。有效实施 RFT 需要更多 ML expertise。
关于哪些 models 可以应用上述 training techniques,请参考以下网站: learn.microsoft.com/en-us/azure…
Compute options
本节中,我们将深入了解 fine-tuning 可用的 compute options。由于行业正处在 GPU crisis 中,GPU 设计也在快速变化,我们很难采购 GPUs 并构建用于 fine-tuning 的基础设施。建设 multi-gigawatt capacity 的数据中心,并构建用于训练 AI 或 fine-tune AI 的 super clusters,成本一直非常高。
随着行业持续增长以承载 AI workloads,hyperscalers 都在构建云上的能力,让 companies 或 enterprises 可以利用这些能力。由于 GPU chips 变化很快,hyperscalers 会持续跟进这些变化,而我们则可以从最新、最强的能力中受益。
现在,我们来看 Azure AI Foundry 中的两个可用选项。AI Foundry 提供用于存储 fine-tuning dataset 的能力,也会通过自身服务管理整个 job lifecycle。这对 data scientists 来说更简单:我们只需要提交 fine-tuning run,而不需要盯着系统如何运行。
通常,如果我们在 laptop 或普通 VM 上运行这些任务,它们可能进入 sleep mode 或断连;而这些大型、耗时任务如果运行在 Azure AI Foundry 上,就更容易管理。我们可以之后回来看 logs 和 metrics。
Azure AI Foundry 还会为我们存储 logs 和 metrics,以便 troubleshooting,并在需要时进行 audit。我们可以回头手动比较每一次 run 的表现,因为每一次 run 的 performance 都取决于所使用的数据,这意味着每个 dataset 也都可供我们 review。
Foundry 中有两类选项:
- Serverless API
- Managed Compute
Serverless API
这是最高效、最容易上手的选项。它只需要以 JSONL format files 准备好 training 和 validation dataset。
以 gpt-4.1-nano 为例,我们需要 dataset 采用下面这种包含 messages 的格式,也就是 chat style format:
{
"messages": [
{
"role": "system",
"content": "You are an Xbox customer support agent whose primary goal is to help users with issues they are experiencing with their Xbox devices. You are friendly and concise. You only provide factual answers to queries, and do not provide answers that are not related to Xbox."
},
{
"role": "user",
"content": "Is Xbox better than PlayStation?"
},
{
"role": "assistant",
"content": "I apologize, but I cannot provide personal opinions. My primary job is to assist you with any issues related to your Xbox device. Do you have any Xbox-related issues that need addressing?"
}
]
}
这些选项允许我们选择 model,例如这里的 Azure GPT-4.1-nano,然后部署到 serverless API。这里还提供 content safety filter 选项,默认启用,用于保护 model 的 input 和 output。
不是所有 models 都支持 serverless API,这一点可以在 Azure AI Foundry Portal 中检查:
- 登录 Azure AI Foundry Portal。如何打开 Azure AI Foundry UI,请参考第 2 章。
- 也可以直接访问 Azure AI Foundry UI:
https://ai.azure.com。 - 使用 Entra ID 登录后,确保选择正确的 resource / project。
- 在左侧菜单中,进入 Models + endpoints。
图 5.2
点击 Deploy Models,然后点击 Deploy Base Models。
在左侧搜索菜单中输入:
gpt-4.1
图 5.3:Serverless API model deployment
然后向下滚动并选择 gpt-4.1-nano,再点击 Confirm 按钮。
Billing 主要基于 fine-tuning 中使用的 tokens,而不是使用的 compute time。
Managed compute options
对某些 models 来说,可以选择自己的 compute instance 来使用。该选项允许选择 VM SKU,通常是 GPU-based SKU。SKU 选定后,会出现上传 dataset 并继续 fine-tuning 的选项。Training cost 主要取决于 model 处理所有 tokens 所花费的时间,也就是 training 的 compute time。
图 5.4:Managed compute options for fine-tuning
该选项适用于 phi、llama 以及 model catalog 中其他 open-source models。该选项默认没有启用 content filter。请确保 fine-tuning 完成后,必须进行 evaluation,以验证 model 的 safety 和 quality。Evaluation 应该成为 development 中 training process 的一部分。这样我们才能确保 models 从流程一开始就是 safe 和 secure 的。
在两种情况下,job management 都由 Azure 负责。因此,我们可以提交 job,然后等它运行完再回来查看。我们不需要编写代码去轮询并检查 status,这也是 Azure AI Foundry UI 非常有吸引力的原因。现在,我们在 UI 中看到的内容,也可以通过 Python SDK 创建,并作为 batch process 运行。
在本节中,你学习了有哪些 training techniques 可用,以及这些 techniques 应该在哪里使用。基于 task 和 task complexity,我们可以选择合适的 SFT、DPO 或 RFT 技术。请记住,dataset 应根据要求准备好,以支持基于 UI 的 fine-tuning。
随后,我们学习了不同 compute options,例如 serverless API 和 managed compute。Serverless API 允许 Azure 选择合适 GPU 来执行 model,并屏蔽 infrastructure 背后的复杂性。对于 managed compute,我们拥有选择权,需要设计要使用的 GPU size 和 SKU。如果没有显示可用 SKU,请通过 quota request 申请更多 quota。
Fine-tuning in the Foundry portal UI
在本节中,我们将使用 Azure AI Foundry UI 进行 fine-tuning。该流程也可以通过 Python SDK 完成。我们可以探索不同 techniques 的选项,例如 SFT、DPO 或 RFT,以及支持这些 techniques 的 models。并不是所有 models 都支持所有 techniques。
开始 fine-tuning 前,我们需要下载 datasets。出于本书目的,我们将使用 Hugging Face 上可用的 cleaned dataset。例如,HelpSteer dataset 是 Hugging Face 上的 open-source dataset:
该 dataset 由 NVIDIA 创建,是验证 specific task-based fine-tuning 的良好起点:
import json
input_path = 'finetunedata/val.jsonl'
output_path = 'finetunedata/converted_val.jsonl'
system_message = {
"role": "system",
"content": "I am AI assistant to help with your queries."
}
with open(input_path, 'r', encoding='utf-8') as infile, open(output_path, 'w', encoding='utf-8') as outfile:
for line in infile:
try:
data = json.loads(line)
prompt = data.get('prompt', '').strip()
response = data.get('response', '').strip()
converted = {
"messages": [
system_message,
{"role": "user", "content": prompt},
{"role": "assistant", "content": response}
]
}
outfile.write(json.dumps(converted, ensure_ascii=False) + '\n')
except json.JSONDecodeError as e:
print(f"Skipping invalid JSON line: {e}")
现在进入 Azure AI Foundry UI。更多内容可参考第 2 章。
也可以直接访问:
确保使用 Entra ID 登录。
然后确保选择要工作的 project。
在左侧菜单中,请选择 Fine-tune model。
图 5.5:The fine-tuning process
点击 Fine-tune model 后,会打开一个新窗口。
你应该看到以下选项:
图 5.6:Display models
现在,如果点击 Customization method 下拉菜单,会看到不同 training 类型的选项:
图 5.7:Training Techniques
选择不同选项,可以看到经过筛选后的 model list。只有支持所选 technique 的 models 才会显示。例如,如果选择 Reinforcement,你应该会看到 o4-mini 这类 reasoning models。该列表会基于 availability 变化。通常 vendors 每 6 到 9 个月会变更 models,因此这里可能发生变化。
对于不同 fine-tuning techniques,configuration 可能会根据选择发生变化。例如,对于 RFT,会有 grader configurations 需要提供。对于 SFT 和 DPO,user interface 会显示更多可选择或填写的选项。
关于 reinforcement,请参考当前文档: learn.microsoft.com/en-us/azure…
本节中,我们选择 gpt-4.1-nano,并点击 Next 按钮。
下一屏是大多数 configuration selections 所在的位置。
其中一个要求是,training 和 validation dataset 应以 JSONL format file 存在。下面是需要填写的页面:
图 5.8:Fine-tuning configuration
选择 method 为 Supervised,也就是 SFT。
在下拉菜单中选择 gpt-4.1-nano model version。
对于 training type,有 standard 和 global(preview)两种:
- Standard 会提供 data residency,并在该 region 中运行。
- Global 会基于 availability 使用任意 global region 中的 compute。
- Global 会快得多,因为它可以选择任何可用 region 进行 fine-tune。
我们将选择 Global(Preview) 。
选择 No,不自动 deploy,因为我们需要在部署到 production 前 validate 和 evaluate model。
现在点击 Add Training data。
然后选择 Upload from file。
图 5.9:Upload options
你可以选择之前某次 run 已上传的 existing data;在这个例子中,因为是全新的,我们将从本地 laptop 或 computer 上传 files。
也可以选择 Azure Blob 或 web location,也就是 file 所在的位置。
如果文件来自 Azure blob 或其他 web locations,请确保具备读取该文件的适当 permissions。
现在从 local storage 选择文件,并点击 Apply。
图 5.10:Training file uploaded
现在重复上述流程,添加 validation data upload。你也可以跳过这一步,但为了确认 model 是否 overfitting 或 underfitting,validation 是一个关键阶段,可以确保 model performant。
Dataset 上传完成后,点击 Apply。
图 5.11:Validation dataset uploaded
现在,它应该会带你进入 “Create a fine-tuned model” 页面,如下图所示:
图 5.12:Fine-tune configuration
我们可以配置 Batch size、Learning rate multiplier 和 Number of epochs。Batch sizes 通常是 1、2、4、8,batch size 由可用 compute resources 以及 model 大小决定。
例如,如果我使用 Llama 7B,并且有 8 个 GPU H200,那么可以使用 batch size 8;如果有 4 个 GPUs,batch size 可能是 2 或 4。Learning rate 会影响 fine-tuning duration;rate 越低,fine-tuning 越细粒度,quality 和 run time 都会增加。Epochs 是 transformer-run configurations。
我将设置:
- Batch Size:16
- Learning rate:1.5
- Number of epochs:10
下面是每个 metric 可以使用的默认取值范围。
Learning rate 可以在 0 到 10 范围内,但 preferred range 是 0.5 到 2。
Batch size 计算为 training set 中 examples 的 0.2%,最大值为 32。
Epoch:一个 epoch 指完整遍历 dataset 的一次 cycle。如果设置为 default,epochs 数量会基于 input data 动态决定。
图 5.13:Hyperparameter configuration
现在点击 Submit。
它通常会带你回到 fine-tuning UI,在那里应该会显示 fine-tuning progress。
图 5.14:Fine-tuning status
现在等待 fine-tuning 完成。该过程可能需要 10+ 小时。
Fine-tuning 完成后,我们将能看到 progress status。
Training run 上也会显示 logs 和 metrics。
进入 Metrics 查看 model performance。
Loss Charts
图 5.15:Loss vs steps
Token accuracy charts
图 5.16:Token accuracy vs. steps
Logs tab 会显示所有 running logs。
Checkpoints 会在 fine-tuning run 后提供 model storage。
这个 checkpoint 就是我们可以部署用于 inference,并在其他 downstream applications 中消费的内容。
也有选项可以下载 results、training 和 validation data files。
Fine-tuning 完成后,下一步进入 deploy 进行 testing。
Model inferencing 有不同 deployment 类型可用:
图 5.17:Model inference options
我们将在 development environment 中使用 Developer(Preview) 进行 testing。这是对 Global Standard 和 Regional Provisioned Throughput 的很好补充。如果你想使用 pay-as-you-go 并部署到 production use case,Global Standard 是更推荐的选择。如果你需要 latency 和 performance,那么 Regional Provisioned Throughput 可能更合适。
当 model fine-tuning 完成后,进入 fine-tune 页面,选择该 run 并点击。
图 5.18:Model inference options
现在,我们需要选择 deployment type。这里需要设置 endpoint name,用于 REST 以及其他 Token per Minute(TPM)configuration;还可以选择退出 automatic model version upgrades。对于 fine-tuned models 来说,这通常不太适用,因为我们可以控制 model training run。
图 5.19:Model deployment configuration
提供 deployment name,参考上图中给出的名称。
选择 Deployment type 为 Developer(Preview) 。
设置 Tokens per Minute Rate Limit。
然后点击 Deploy 按钮。
现在,如果进入 Model + endpoint,应该可以看到正在创建 fine-tuned model。创建完成后,Endpoint 就可以使用了。
图 5.20:Model deployment status
现在,fine-tuning 已经完成,并已部署用于 testing。
进入 model card,它会显示 deployment 详情,然后点击 Open Playground,进入 playground 开始手动测试。我们也可以编写代码并使用 SDK 测试。
基于 testing,不断实验:调整 hyperparameters,或者创建高质量 dataset 用于 training,并持续改进 model 的 performance、quality、safety 和 accuracy。
Fine-tuning 也支持使用 images 的 multi-model fine tuning。如果我们希望为带 tools 的 Agent execution 微调 model,也同样可用。鉴于这个科学领域正在随着 physical AI in the loop 发展,未来可能会有新的 updates 和 changes。相关内容会持续变化,因此要留意未来可用的新 modalities 和 techniques。
在本节中,我们看到如何使用 Azure AI Foundry UI,以多种 modalities 和 techniques 对 models 进行 fine-tune。通过为 direct preference 和 reasoning models 创建数据,我们可以使用 DPO 和 RFT 类型的 fine-tuning 处理复杂任务和 validation。对于 reinforcement fine-tuning,需要 grader 来确保它能基于你的 outcomes 提供 reward。请务必查看文档了解具体操作方式。
更好的实践是始终将 safety measures 纳入 dataset,使 model 更 trustworthy。更多信息请查看 Responsible AI 和 Red team 章节。
Training 和 validation JSONL file 应准备为符合 training run 要求的 proper format。Dataset 可以由 partners 创建,也可以由 humans 创建,或者通过 distillation methods 创建。使用 distillation methods 时,加入 human review 会提升 model quality。
Summary
本章中,我们学习了什么是 fine-tuning、它的应用场景,以及 SFT、DPO 和 RFT 等不同 training techniques。我们也看到了不同 compute options,例如 serverless API 和 managed compute。
随后,我们看到如何使用 Hugging Face 上公开可用的 HelpSteer data,将 dataset 转换为用于 fine-tune GPT-4.1-nano model 的格式。然后,我们逐步学习了如何拿这个 dataset,并使用 Azure AI Foundry UI 通过 no-code approach 完成 fine-tuning。
下一章第 6 章中,我们将学习如何使用 Microsoft Foundry 设计和构建实用 AI agents,覆盖它们的核心 architecture、capabilities,以及通过一个 hands-on sales automation case 展示真实世界 implementation,同时介绍 orchestration、testing 和 refinement 技术。
Further reading
在尝试 fine-tune 之前,请务必从以下链接获取最新信息: learn.microsoft.com/en-us/azure…
请查看 safety evaluation process,并注意在真实 use cases 上执行: learn.microsoft.com/en-us/azure…
Fine-tuning 的 costing 和 SLA management 可参考: learn.microsoft.com/en-us/azure…
Fine-tuning troubleshooting,尤其是 dataset formatting issues 很可能发生,请参考: learn.microsoft.com/en-us/azure…