OpenAI gpt-oss-20b 的分布式微调

在 AI Runtime 上通过分布式训练微调 OpenAI 的 gpt-oss-20b 模型。 你将了解如何:

  • 应用 LoRA(低秩适应)高效微调 200 亿参数模型
  • 使用 MXFP4 量化 来减少训练期间的内存需求
  • 利用跨 8 个 H100 GPU 的分布式数据并行
  • 在 Unity 目录中注册经过微调的模型进行部署

关键概念:

  • GPT-OSS-20b:OpenAI 拥有 200 亿参数的开源语言模型
  • LoRA:参数高效的微调,在冻结基础模型的同时训练小型适配器层
  • MXFP4 量化:微缩放 4 位浮点格式,减少内存占用
  • TRL:用于监督微调的变压器强化学习库
  • AI 运行时:Databricks 托管的计算资源,可自动扩展 GPU 资源

连接到无服务器 GPU 计算

此笔记本需要无服务器 GPU 计算。 若要连接:

  1. 单击右上角笔记本的计算选择器,然后选择 无服务器 GPU
  2. 在右侧,单击“环境”按钮
  3. 选择 8xH100 作为 加速器
  4. 从包含运行此笔记本示例所需库的右侧面板中选择 AI v6 环境
  5. 单击“应用”

训练功能运行在附加的 8 块 H100 GPU 上。

注释

此示例需要Databricks AI环境版本6及以上。

配置 Unity Catalog 和模型参数

设置 Unity 目录注册和模型训练的配置参数。 可以使用上面的控件自定义这些参数。

  • uc_catalog、 uc_schema、 uc_model_name:用于模型注册的 Unity Catalog 位置
  • uc_volume:用于存储模型检查点的卷名
  • 模型:Hugging Face 模型标识符(默认:openai/gpt-oss-20b)
  • dataset_path:用于微调的数据集(默认:HuggingFaceH4/Multilingual-Thinking)
dbutils.widgets.text("uc_catalog", "main")
dbutils.widgets.text("uc_schema", "default")
dbutils.widgets.text("uc_model_name", "gpt-oss-20b-peft")
dbutils.widgets.text("uc_volume", "checkpoints")
dbutils.widgets.text("model", "openai/gpt-oss-20b")
dbutils.widgets.text("dataset_path", "HuggingFaceH4/Multilingual-Thinking")

UC_CATALOG = dbutils.widgets.get("uc_catalog")
UC_SCHEMA = dbutils.widgets.get("uc_schema")
UC_MODEL_NAME = dbutils.widgets.get("uc_model_name")
UC_VOLUME = dbutils.widgets.get("uc_volume")
HF_MODEL_NAME = dbutils.widgets.get("model")
DATASET_PATH = dbutils.widgets.get("dataset_path")

print(f"UC_CATALOG: {UC_CATALOG}")
print(f"UC_SCHEMA: {UC_SCHEMA}")
print(f"UC_MODEL_NAME: {UC_MODEL_NAME}")
print(f"UC_VOLUME: {UC_VOLUME}")
print(f"HF_MODEL_NAME: {HF_MODEL_NAME}")
print(f"DATASET_PATH: {DATASET_PATH}")

OUTPUT_DIR = f"/Volumes/{UC_CATALOG}/{UC_SCHEMA}/{UC_VOLUME}/{UC_MODEL_NAME}"
print(f"OUTPUT_DIR: {OUTPUT_DIR}")

选择数据集

默认情况下,此笔记本使用 'HuggingFaceH4/Multilingual-Thinking',该模型已通过多种语言的翻译思维链专门整理。 可以编辑上述“数据集路径”参数以使用另一个数据集。

定义 GPU 内存日志记录实用工具

此实用工具函数可帮助监视分布式训练期间的 GPU 内存使用情况。 它记录为每个 GPU 排名分配和保留的内存,这对于调试内存问题很有用。

import os
import torch
import torch.distributed as dist

def log_gpu_memory(tag=""):
    if not torch.cuda.is_available():
        return

    # rank info (if distributed is initialized)
    if dist.is_available() and dist.is_initialized():
        rank = dist.get_rank()
        world_size = dist.get_world_size()
    else:
        rank = 0
        world_size = 1

    device = torch.cuda.current_device()  # current GPU for this process
    torch.cuda.synchronize(device)

    allocated = torch.cuda.memory_allocated(device) / 1024**2
    reserved  = torch.cuda.memory_reserved(device) / 1024**2

    print(
        f"[{tag}] rank={rank}/{world_size-1}, "
        f"device={device}, "
        f"allocated={allocated:.1f} MB, reserved={reserved:.1f} MB"
    )

定义分布式训练函数

以下单元格使用 databricks.air 库中的 @distributed 装饰器定义了训练函数。 此修饰器:

  • 在所连接的 8 块 H100 GPU 上运行分布式训练
  • 自动处理多个 GPU 之间的数据并行度

该函数包括:

  • 数据集加载和标记化
  • 使用 MXFP4 量化进行模型初始化
  • LoRA 适配器配置
  • 使用梯度检查点和混合精度进行训练
  • 模型保存到 Unity Catalog 卷
from databricks.air import distributed

@distributed(num_accelerators=8, accelerator_type="GPU_8xH100")
def run_train():
    import logging
    import os
    import torch

    rank = int(os.environ.get("RANK", "0"))
    local_rank = int(os.environ.get("LOCAL_RANK", "0"))
    torch.cuda.set_device(local_rank)
    world_size = int(os.environ.get("WORLD_SIZE", str(torch.cuda.device_count())))

    os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")

    is_main = rank == 0
    if is_main:
        logging.info("DDP environment")
        logging.info(f"\tWORLD_SIZE={world_size}  RANK={rank}  LOCAL_RANK={local_rank}")
        logging.info(f"\tCUDA device count (this node): {torch.cuda.device_count()}")

    from datasets import load_dataset
    dataset = load_dataset(DATASET_PATH, split="train")

    from transformers import AutoTokenizer
    tokenizer = AutoTokenizer.from_pretrained(HF_MODEL_NAME)

    from transformers import AutoModelForCausalLM, Mxfp4Config

    quantization_config = Mxfp4Config(dequantize=True)
    model_kwargs = dict(
        attn_implementation="eager", # Use eager attention implementation for better performance
        dtype=torch.bfloat16,
        quantization_config=quantization_config,
        use_cache=False, # Since using gradient checkpointing
    )

    model = AutoModelForCausalLM.from_pretrained(HF_MODEL_NAME, **model_kwargs)

    from peft import LoraConfig, get_peft_model

    peft_config = LoraConfig(
        r=8,
        lora_alpha=16,
        target_modules="all-linear",
        lora_dropout=0.05,
        bias="none",
        task_type="CAUSAL_LM",
    )
    peft_model = get_peft_model(model, peft_config)
    if is_main:
        peft_model.print_trainable_parameters()

    from trl import SFTConfig

    training_args = SFTConfig(
        learning_rate=2e-4,
        num_train_epochs=1,
        logging_steps=1,
        per_device_train_batch_size=1,
        gradient_accumulation_steps=2,
        gradient_checkpointing=True,
        gradient_checkpointing_kwargs={"use_reentrant": False},
        max_length=2048,
        warmup_ratio=0.03,
        lr_scheduler_type="cosine_with_min_lr",
        lr_scheduler_kwargs={"min_lr_rate": 0.1},
        output_dir=OUTPUT_DIR,
        report_to="mlflow",  # No reporting to avoid Gradio issues
        push_to_hub=False,  # Disable push to hub to avoid authentication issues
        logging_dir=None,  # Disable tensorboard logging
        disable_tqdm=False,  # Keep progress bars for monitoring
        ddp_find_unused_parameters=False,
    )

    from trl import SFTTrainer

    trainer = SFTTrainer(
        model=peft_model,
        args=training_args,
        train_dataset=dataset,
        processing_class=tokenizer,
    )
    #torch.cuda.empty_cache()
    #log_gpu_memory("before model training")
    result = trainer.train()
    #log_gpu_memory("after model loading")

    if is_main:
        logging.info("Training complete!")
        logging.info(f"Final training loss: {result.training_loss:.4f}")
        logging.info(f"Train runtime (s): {result.metrics.get('train_runtime', 'N/A')}")
        logging.info(f"Samples/sec: {result.metrics.get('train_samples_per_second', 'N/A')}")
        logging.info("\nSaving trained model...")
        trainer.save_model(OUTPUT_DIR)
        logging.info("✓ LoRA adapters saved - use with base model for inference")
        tokenizer.save_pretrained(OUTPUT_DIR)
        logging.info("✓ Tokenizer saved with model")
        logging.info(f"\n🎉 All artifacts saved to: {OUTPUT_DIR}")

    import mlflow
    mlflow_run_id = None
    if mlflow.last_active_run() is not None:
        mlflow_run_id = mlflow.last_active_run().info.run_id

    return mlflow_run_id

执行分布式训练

此单元在 8 个 H100 GPU 上运行训练函数。 训练通常需要 30-60 分钟,具体取决于数据集大小和计算可用性。 该函数返回用于模型注册的 MLflow 运行 ID。

run_id = run_train.distributed()[0]

在 Unity 目录中注册模型

现在,可以将微调的模型注册到 MLflow 和 Unity 目录进行部署。

重要提示: 鉴于模型大小(20B参数),在运行注册单元前,请将笔记本重新连接到 H100 加速器。

注册过程将:

  1. 加载基本模型并将其与微调的 LoRA 适配器合并
  2. 创建文本生成管道
  3. 使用 Unity 目录注册将模型记录到 MLflow
dbutils.widgets.dropdown("register_model", "False", ["True", "False"])
register_model = dbutils.widgets.get("register_model")
if register_model == "False":
  dbutils.notebook.exit("Skipping model registration...")

检查注册参数

此单元格检查 register_model 参数。 如果设置为False,笔记本将跳过模型注册。 可以使用笔记本顶部的工具来更改此参数。

print("\nRegistering model with MLflow and Unity Catalog...")

from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline

from peft import PeftModel
import mlflow
import torch

torch.cuda.empty_cache()
# Load the trained model for registration
print("Loading LoRA model for registration...")
# For LoRA models, we need both base model and adapter
base_model = AutoModelForCausalLM.from_pretrained(
    HF_MODEL_NAME,
    trust_remote_code=True
)
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(HF_MODEL_NAME)
adapter_dir = OUTPUT_DIR
peft_model = PeftModel.from_pretrained(base_model, adapter_dir)
# Merge LoRA into base and drop PEFT wrappers
merged_model = peft_model.merge_and_unload()

components = {
    "model": merged_model,
    "tokenizer": tokenizer,
}

# Create Unity Catalog model name
full_model_name = f"{UC_CATALOG}.{UC_SCHEMA}.{UC_MODEL_NAME}"

print(f"Registering model as: {full_model_name}")

text_gen_pipe = pipeline(
    task="text-generation",
    model=peft_model,
    tokenizer=tokenizer,
)

input_example = ["Hello, world!"]

with mlflow.start_run():
    model_info = mlflow.transformers.log_model(
        transformers_model=text_gen_pipe,   # 🚨 pass the pipeline, not just the model
        artifact_path="model",
        input_example=input_example,
        # optional: save_pretrained=False for reference-only PEFT logging
        # save_pretrained=False,
    )
# Start MLflow run and log model
print(f"✓ Model successfully registered in Unity Catalog: {full_model_name}")
print(f"✓ MLflow model URI: {model_info.model_uri}")
print(f"✓ Model version: {model_info.registered_model_version}")

# Print deployment information
print(f"\n📦 Model Registration Complete!")
print(f"Unity Catalog Path: {full_model_name}")
print(f"Optimization: Liger Kernels + LoRA")

测试多语言推理功能

经过微调的模型已在 Multilingual-Thinking 数据集上进行了训练,其中包含多种语言的思维链推理。

以下单元格通过以下方法演示了此功能:

  • 将推理语言设置为德语
  • 在西班牙语中提供提示(“澳大利亚首都是什么?”
  • 观察到模型的内部推理是用德语进行的
REASONING_LANGUAGE = "German"
SYSTEM_PROMPT = f"reasoning language: {REASONING_LANGUAGE}"
USER_PROMPT = "¿Cuál es el capital de Australia?"  # Spanish for "What is the capital of Australia?"

messages = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {"role": "user", "content": USER_PROMPT},
]

input_ids = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    return_tensors="pt",
).to(merged_model.device)

gen_kwargs = {"max_new_tokens": 512, "do_sample": True, "temperature": 0.6, "top_p": None, "top_k": None}

output_ids = merged_model.generate(**input_ids, **gen_kwargs)
response = tokenizer.batch_decode(output_ids)[0]
print(response)

后续步骤

现在,你已经微调并测试了模型,接下来可以:

示例笔记本

OpenAI gpt-oss-20b 的分布式微调

获取笔记本