如何使用 Kubeflow 微调 LLM

Training Operator 中 LLM 微调 API 概览

此页面描述了如何使用 Training Python SDK 中的 train API,该 API 简化了使用分布式 PyTorchJob worker 微调 LLM 的能力。

如果您想详细了解微调 API 如何融入 Kubeflow 生态系统,请参阅解释指南

先决条件

您需要安装支持微调功能的 Training Python SDK 才能运行此 API。

如何使用 Fine-Tuning API?

要使用 train API,您需要提供以下参数:

  • 预训练模型参数。
  • 数据集参数。
  • 训练器参数。
  • PyTorch worker 数量及每个 worker 的资源。

例如,您可以使用 train API,通过以下代码使用 HuggingFace Hub 中的 Yelp Review 数据集微调 BERT 模型

import transformers
from peft import LoraConfig

from kubeflow.training import TrainingClient
from kubeflow.storage_initializer.hugging_face import (
    HuggingFaceModelParams,
    HuggingFaceTrainerParams,
    HuggingFaceDatasetParams,
)

TrainingClient().train(
    name="fine-tune-bert",
    # BERT model URI and type of Transformer to train it.
    model_provider_parameters=HuggingFaceModelParams(
        model_uri="hf://google-bert/bert-base-cased",
        transformer_type=transformers.AutoModelForSequenceClassification,
    ),
    # Use 3000 samples from Yelp dataset.
    dataset_provider_parameters=HuggingFaceDatasetParams(
        repo_id="yelp_review_full",
        split="train[:3000]",
    ),
    # Specify HuggingFace Trainer parameters. In this example, we will skip evaluation and model checkpoints.
    trainer_parameters=HuggingFaceTrainerParams(
        training_parameters=transformers.TrainingArguments(
            output_dir="test_trainer",
            save_strategy="no",
            eval_strategy="no",
            do_eval=False,
            disable_tqdm=True,
            log_level="info",
        ),
        # Set LoRA config to reduce number of trainable model parameters.
        lora_config=LoraConfig(
            r=8,
            lora_alpha=8,
            lora_dropout=0.1,
            bias="none",
        ),
    ),
    num_workers=4, # nnodes parameter for torchrun command.
    num_procs_per_worker=2, # nproc-per-node parameter for torchrun command.
    resources_per_worker={
        "gpu": 2,
        "cpu": 5,
        "memory": "10G",
    },
)

执行 train 后,Training Operator 将协调相应的 PyTorchJob 资源来微调 LLM。

将自定义镜像与 Fine-Tuning API 结合使用

平台工程师可以在执行 train 命令之前,通过设置 STORAGE_INITIALIZER_IMAGETRAINER_TRANSFORMER_IMAGE 环境变量来自定义存储初始化器和训练器镜像。

例如:在您的 python 代码中,在执行 train 之前设置环境变量

...
os.environ['STORAGE_INITIALIZER_IMAGE'] = 'docker.io/<username>/<custom-storage-initiailizer_image>'
os.environ['TRAINER_TRANSFORMER_IMAGE'] = 'docker.io/<username>/<custom-trainer_transformer_image>'

TrainingClient().train(...)

下一步

反馈

此页面是否有帮助?