使用 Dynamic Resource Allocation (DRA) 进行 GPU 切分

经典的 device-plugin 模型分配的是整块 GPU:Pod 请求 nvidia.com/gpu: 1,拿到的是一整张卡,即使只是进行 LoRA 微调,也从未使用超过几个 GiB。在一块 24 GB 的 A30 上,这相当于作业实际需要的内存最多 20 倍,却一直处于闲置状态。

Dynamic Resource Allocation (DRA) —— 这是一个 resource.k8s.io/v1 API,并且已在 Kubernetes 1.34 中达到 GA —— 允许 Pod 改为请求 GPU 的一个 切片。借助 Alauda Build of NVIDIA DRA Driver for GPUs,这个切片可以是:

  • 一个 MIG 分区——由硬件隔离的卡片部分(拥有自己的 SM 和 VRAM,并由 GPU 强制隔离),或者
  • 一个 时间切片 / MPS 共享 的整块 GPU——多个 Pod 共享一张卡,但没有内存隔离。

本指南通过 ResourceClaimTemplate 请求一个 MIG 切片,然后在其中使用 Kubeflow Trainer v2 运行一个监督式微调。所有资源都位于 assets/dra/,并且该流程已通过仓库 e2e harness 中的 c15_dra_gpu_slice.sh 用例完成端到端验证。

Device plugin 与 DRA

经典 device pluginDynamic Resource Allocation
请求形式resources.limits."nvidia.com/gpu": 1resources.claims: [{name: gpu-slice}] + 一个 ResourceClaim
粒度整块 GPU(或厂商固定的 vGPU,例如 HAMi 的 gpualloc)按 claim 切片:在请求时选择 MIG profile 或共享模式
由谁定义形状集群范围的 device-plugin 配置 / 节点重标记 + 重启用户按工作负载在 ResourceClaimTemplate 中定义
隔离性整卡,或厂商特定方案使用 MIG 时为硬件隔离;使用 TimeSlicing/MPS 时为时间共享
选择逻辑节点标签 + 资源名称基于设备属性(profile、memory、productName、…)的 CEL 表达式

DRA 并不会替代调度器或 Kueue——它改变的是如何描述和声明设备。配额、优先级和抢占仍然有效(参见 将切片与 Kueue 配额结合使用)。

前提条件

要求详情
Kubernetes 1.34+已提供 resource.k8s.io/v1——可通过 kubectl api-resources --api-group=resource.k8s.io 检查
Alauda Build of NVIDIA DRA Driver for GPUs已安装在集群中,并且其 kubelet-plugin 在 GPU 节点上发布 ResourceSlices(参见 准备 GPU 节点和 DRA 驱动)
支持 MIG 且已创建 profile 的 GPU对于 MIG 切片:A30 / A100 / H100 / H200,需已启用 MIG 模式并创建 MIG 实例(参见 在节点上准备 MIG profile)。不支持 MIG 的 GPU 仍可使用 时间切片路径
Kubeflow Trainer v2trainer.kubeflow.org API group(参见 使用 Kubeflow Trainer v2 进行微调)。对于 KFP、Volcano 或普通 Jobs,DRA 的接入方式完全相同——参见 将同一个 claim 接入其他 orchestrator
kubectl 访问权限允许在你的 namespace 中管理 resourceclaimtemplates,并读取 deviceclasses / resourceslices(cluster-scoped)
NOTE

DeviceClass 和 ResourceSlice 是 cluster-scoped,由驱动/管理员拥有。ResourceClaimTemplate 和 ResourceClaim 是 namespaced,由你创建。ResourceClaimTemplate 必须位于引用它的 Pod 所在的同一 namespace 中。

一个切片请求中的三个对象

  cluster (driver/admin)                    namespace (you)
  ┌────────────────────┐        ┌──────────────────────────────────┐
  │ DeviceClass         │◄───────│ ResourceClaimTemplate            │
  │  mig.nvidia.com     │  refs  │  request: 1× mig.nvidia.com      │
  │  gpu.nvidia.com     │        │  selector: profile == "1g.6gb"   │
  └────────────────────┘        └──────────────┬───────────────────┘
  ┌────────────────────┐                        │ per-Pod instance
  │ ResourceSlice(s)    │  scheduler matches     ▼
  │  advertised by the  │◄──────────  Pod.spec.resourceClaims ──► container.resources.claims
  │  kubelet-plugin     │  claim & allocate a slice, inject it into the Pod
  └────────────────────┘
  • DeviceClass(由驱动创建)定义一种设备类型和一个基础选择器。Alauda Build of NVIDIA DRA Driver for GPUs 提供了 gpu.nvidia.com(整块 GPU)和 mig.nvidia.com(MIG 切片)。
  • ResourceClaimTemplate(由你创建)表示“从这个 class 中给每个 Pod 分配一个设备,并匹配这个 CEL selector”。调度器会据此为每个 Pod 生成一个 ResourceClaim。
  • Pod 在 spec.resourceClaims 中引用该模板,而 container 通过 resources.claims 选择启用。整个过程完全不使用任何 nvidia.com/* limit。

第 1 步 — 确认驱动正在发布切片

只要安装了驱动,DeviceClass 就会存在,但只有当 kubelet-plugin 为节点上的 GPU 发布了 ResourceSlices 后,Pod 才能被调度:

kubectl get deviceclasses
# NAME              ...
# gpu.nvidia.com
# mig.nvidia.com

kubectl get resourceslices
# NAME                       NODE              DRIVER           ...
# <node>-gpu.nvidia.com-...  192.168.143.59    gpu.nvidia.com   ...

如果 get resourceslices 为空,说明驱动已安装,但尚未在任何节点上发布设备——请先跳转到 准备 GPU 节点和 DRA 驱动,然后再继续。

检查已发布的设备,以了解你的 CEL selector 可以匹配的确切属性键和值——不要假设 profile 字符串;请从你的集群中读取:

kubectl get resourceslices -o yaml | grep -A20 'attributes:'
# ...
#   attributes:
#     gpu.nvidia.com/profile: {string: "1g.6gb"}
#     gpu.nvidia.com/productName: {string: "NVIDIA A30"}
#     gpu.nvidia.com/type: {string: "mig"}

第 2 步 — 冒烟测试一个切片

在将 DRA 接入训练作业之前,先使用 dra-smoke-pod.yaml 验证驱动是否确实能为你分配一个切片。它会请求一个 MIG 切片并打印 container 看到的内容:

base=https://raw.githubusercontent.com/alauda/aml-docs/master/docs/en/training_guides/assets/dra
NS=my-namespace   # namespace where your Pods run

# 1. A ResourceClaimTemplate for one 1g.6gb MIG slice.
curl -fsSL $base/mig-slice-resourceclaimtemplate.yaml | sed "s/kubeflow-admin-cpaas-io/$NS/" | kubectl apply -f -

# 2. A Pod that claims it and runs nvidia-smi + a matmul on the slice.
curl -fsSL $base/dra-smoke-pod.yaml | sed "s/kubeflow-admin-cpaas-io/$NS/" | kubectl create -f -

# 3. Watch it, then read the logs.
kubectl -n "$NS" get pods -l app=dra-smoke -w
kubectl -n "$NS" logs -l app=dra-smoke --tail=40

你应该能看到该切片的降低后的内存上限——例如 1g.6gb 大约是 6 GiB,而不是整块卡的 24 GiB——这正是它的目的:

===== nvidia-smi -L =====
GPU 0: NVIDIA A30 (UUID: GPU-...)
  MIG 1g.6gb  Device  0: (UUID: MIG-...)
cuda_available: True
device: NVIDIA A30 MIG 1g.6gb
slice_total_mem_GiB: 5.75
matmul_on_slice: OK

从控制平面检查分配结果:

kubectl -n "$NS" get resourceclaims
# NAME                 STATE                ...
# dra-smoke-...-gpu-slice   allocated,reserved

第 3 步 — 在切片内使用 Kubeflow Trainer v2 进行微调

dra-sft-trainingruntime.yaml 这个 TrainingRuntime 是一个普通的 Trainer v2 runtime,只包含两个 DRA hook,并且没有 nvidia.com/* limit:

spec:
  template:
    spec:
      replicatedJobs:
        - name: node
          template:
            spec:
              template:
                spec:
                  resourceClaims:                         # (1) Pod-level: bind a per-Pod claim
                    - name: gpu-slice
                      resourceClaimTemplateName: mig-1g-6gb
                  containers:
                    - name: node
                      resources:
                        claims:                           # (2) Container-level: consume it
                          - name: gpu-slice
                        # NOTE: no nvidia.com/gpu here — the GPU comes from the claim

它的训练脚本是自包含的——它会构建一个小型 causal-LM,将其封装为 LoRA adapter,并在合成数据集上训练,因此运行时无需下载模型或数据集,并且大约一分钟即可完成。这使它非常适合在离线 GPU 节点上安全运行并验证切片是否可用。若要将其用于生产微调,只需替换为真实的 base model 和数据集即可(参见 将其改造成真实微调);DRA 的接入方式保持不变。

应用 runtime 并提交作业:

base=https://raw.githubusercontent.com/alauda/aml-docs/master/docs/en/training_guides/assets/dra
NS=my-namespace

# ResourceClaimTemplate (skip if you already applied it in Step 2).
curl -fsSL $base/mig-slice-resourceclaimtemplate.yaml | sed "s/kubeflow-admin-cpaas-io/$NS/" | kubectl apply -f -
# TrainingRuntime that consumes the slice.
curl -fsSL $base/dra-sft-trainingruntime.yaml         | sed "s/kubeflow-admin-cpaas-io/$NS/" | kubectl apply -f -
# TrainJob.
curl -fsSL $base/dra-sft-trainjob.yaml                | sed "s/kubeflow-admin-cpaas-io/$NS/" | kubectl create -f -

跟踪直到完成:

kubectl -n "$NS" get trainjob,pods
pod=$(kubectl -n "$NS" get pods -l jobset.sigs.k8s.io/replicatedjob-name=node -o jsonpath='{.items[0].metadata.name}')
kubectl -n "$NS" logs -f "$pod"

成功时如下:

[slice] device=NVIDIA A30 MIG 1g.6gb total_mem=5.75 GiB
trainable params: 147,456 || all params: 4,...  || trainable%: ...
{'loss': ..., 'step': 10}
[slice] peak_mem=1.83 GiB
DRA LoRA SFT on GPU slice: OK

peak_mem 明显低于切片的 total_mem,说明该微调完全运行在其分区内。在第一个 TrainJob 运行时再启动第二个:在一张被分成四个 1g.6gb 切片的卡上,最多可以有四个微调并发且相互隔离地运行在一块物理 GPU 上——彼此看不到对方的内存。

切片大小 / 选择 profile

修改 mig-slice-resourceclaimtemplate.yaml 中 CEL selector 里的 MIG profile:

selectors:
  - cel:
      expression: device.attributes["gpu.nvidia.com"].profile == "2g.12gb"

典型 profile(请根据你的 ResourceSlices 确认精确字符串——几何配置是按 GPU 而定的):

GPUProfile每卡最大切片数
A30 (24 GB)1g.6gb, 2g.12gb, 4g.24gb4
A100 / H100 (80 GB)1g.10gb, 2g.20gb, 3g.40gb, 7g.80gb7

请选择能轻松容纳你的 model + LoRA + optimizer state + activations 的最小 profile。0.5–1.5B 模型的 LoRA 适合 1g.6gb;7B QLoRA 通常需要 2g.12gb 及以上。

没有 MIG?通过时间切片共享整块 GPU

如果 GPU 不支持 MIG,或者你不想对其进行分区,shared-gpu-resourceclaimtemplate.yaml 会通过一个 opaque 的 GpuConfig 请求通过时间切片共享的整块 GPU:

spec:
  spec:
    devices:
      requests:
        - name: gpu-slice
          exactly:
            deviceClassName: gpu.nvidia.com
            allocationMode: ExactCount
            count: 1
      config:
        - requests: ["gpu-slice"]
          opaque:
            driver: gpu.nvidia.com
            parameters:
              apiVersion: resource.nvidia.com/v1beta1
              kind: GpuConfig
              sharing:
                strategy: TimeSlicing   # or MPS for concurrent sharing

改为让 runtime 使用这个模板(resourceClaimTemplateName: shared-gpu-timeslice)——其余部分无需更改。e2e case 使用 DRA_SLICE_MODE=shared 来执行的正是这条路径。

MIG 切片时间切片 / MPS
内存隔离有——由硬件强制执行无——每个使用者都能看到完整 VRAM
故障隔离有无——一个工作负载可能让其他工作负载 OOM
需要 MIG 模式是否
最适合需要保证隔离的训练切片在一张卡上塞入大量轻量或突发型作业

将切片与 Kueue 配额结合使用

DRA 关注的是设备的形状;Kueue 关注的是谁可以使用多少。Kueue 能理解 DRA 的 DeviceClass,因此 ClusterQueue 可以像对 nvidia.com/gpu 一样,对 mig.nvidia.com 设备设置配额——按切片预算接纳 TrainJobs,并在更高优先级作业需要切片时抢占借用者。[Preemptible TrainJobs with Kueue](./preemptible-trainjobs-with-kueue) 指南中的 cohort 模式可以原样使用;只需将 ResourceFlavor 中受覆盖的资源替换为 DRA device class 即可。(Kueue 中对 DRA 的支持仍在演进——在生产环境依赖它之前,请先根据你的 Kueue 版本进行验证。)

将同一个 claim 接入其他 orchestrator

DRA hooks 位于 Pod spec 中,因此任何允许你塑造 Pod 的系统都可以请求一个切片——Trainer v2 只是其中一个调用方:

  • Kubeflow Pipelines (KFP v2): 通过 kfp-kubernetes 平台配置(或一个 pod-spec patch)将 resourceClaims / resources.claims 附加到任务的 Pod 上,从而让 pipeline component 在一个切片上运行。
  • Volcano / 普通 Job / Pod: 这两个 hook 与 smoke Pod 完全字节级一致——设置 spec.resourceClaims 以及 container 的 resources.claims 即可。

smoke Pod 就是这些场景的最小模板。

将其改造成真实微调

随附的脚本训练的是一个合成模型,以便可以离线验证切片。若要在切片上微调真实模型,请保留这两个 DRA hook,并将容器替换为真实 recipe——例如 使用 Kubeflow Trainer v2 进行微调 中的 LlamaFactory runtime,其中 dataset-initializer / model-initializer 步骤会将 base model 和数据集下载到共享 PVC 上。对该 runtime 的唯一修改是删除 nvidia.com/gpualloc / gpucores / gpumem limits,并添加 spec.resourceClaims + resources.claims。根据模型大小选择合适的 MIG profile(0.6B LoRA 适合 1g.6gb;7B QLoRA 需要 2g.12gb 及以上)。

准备 GPU 节点和 DRA 驱动(管理员)

Alauda Build of NVIDIA DRA Driver for GPUs 会安装一个 controller,以及一个由节点标签控制的 kubelet-plugin DaemonSet。只要 GPU 节点没有该标签,插件就不会发布任何 ResourceSlices,而 DRA Pod 会一直处于 Pending 状态。

# The kubelet-plugin DaemonSet is scheduled by a node label (check its nodeSelector):
kubectl -n kube-system get ds nvidia-dra-driver-gpu-kubelet-plugin \
  -o jsonpath='{.spec.template.spec.nodeSelector}{"\n"}'
# {"nvidia-device-enable":"pgpu-dra"}

# Label the GPU node so the plugin lands and starts advertising devices:
kubectl label node <gpu-node> nvidia-device-enable=pgpu-dra

对于整块 GPU / 时间切片的 claim,你只需要这些——此时插件会为每张卡发布一个 gpu.nvidia.com 设备,你可以直接跳到 冒烟测试一个切片。MIG 切片则需要下面的额外准备。

在节点上准备 MIG profile

在驱动发放它们之前,MIG 切片必须已经存在于卡上。 Alauda Build of NVIDIA DRA Driver for GPUs 不会按需创建 MIG 分区——它只会暴露已经存在的 MIG 设备。如果已启用 MIG 模式但尚未创建任何实例,kubelet-plugin 会因 invalid CDI Spec: no devices 而进入 crash-loop。因此,管理员需要在每个 GPU 节点上创建一次 MIG profile(所有 nvidia-smi 命令都在节点宿主机上运行——通过特权 Pod 或 SSH):

# 0. The GPU must be IDLE. MIG-mode changes reset GPU state and are refused while any
#    CUDA workload or monitoring client (e.g. dcgm-exporter) holds the card. Stop GPU
#    workloads and move dcgm-exporter off this node first.

# 1. Enable MIG mode on the GPU (index 0 here) and confirm it took effect.
nvidia-smi -i 0 -mig 1
nvidia-smi -i 0 --query-gpu=mig.mode.current,mig.mode.pending --format=csv
#    If mode stays "pending", a client is still attached — free it, then finalise with
#    a GPU reset (`nvidia-smi -i 0 -r`) or a node reboot.

# 2. List the GPU-instance profiles this card supports, with their IDs and how many fit.
nvidia-smi mig -lgip
#   GPU  Name          ID   Free/Total   Memory
#     0  MIG 1g.6gb    19    4/4         ~6 GiB     <- four small slices
#     0  MIG 2g.12gb   14    2/2         ~12 GiB
#     0  MIG 4g.24gb    0    1/1         ~24 GiB    <- whole card as a single MIG device

# 3. CREATE the GPU instances and their compute instances (-C). Repeat a profile ID to
#    make several slices of it. This carves the card into FOUR 1g slices (ID 19 x4):
nvidia-smi mig -cgi 19,19,19,19 -C
#    ...or two medium slices:  nvidia-smi mig -cgi 14,14 -C

# 4. Confirm the MIG devices now exist.
nvidia-smi -L
nvidia-smi mig -lgi          # list the created GPU instances
WARNING

profile 的ID、名称以及每个实例的内存容量都与硬件相关,并且 nvidia-smi mig -lgip 显示的名称可能与驱动发布的 profile 属性不同——例如,A30 上显示为 2g.6gb 的 GPU-instance profile,在 DRA 中可能会暴露为 1g.6gb。不要从本示例硬编码。 请先在第 2 步中读取你卡上的真实 profile,然后再读取下面发布出来的 profile 字符串,并让你的 ResourceClaimTemplate 的 CEL selector 与之匹配。

使用 nvidia-smi mig -cgi 创建的 MIG 实例并不一定能在 GPU 或节点重置后保留下来。请在重启后重新创建它们,或者使用驱动的 MIG-config 工具 / 启动时 unit 来自动创建。

最后,重启 kubelet-plugin Pod,使其重新枚举这张卡并发布 MIG ResourceSlices,然后读取你的 CEL selector 必须匹配的精确 profile 字符串:

kubectl -n kube-system delete pod -l app.kubernetes.io/name=nvidia-dra-driver-gpu --field-selector spec.nodeName=<gpu-node>

kubectl get resourceslices -o json \
  | jq -r '.items[].spec.devices[].attributes."gpu.nvidia.com".profile.string' | sort -u
# 1g.6gb          <- use this exact string in mig-slice-resourceclaimtemplate.yaml
WARNING

一块物理 GPU 只能由一个 device plugin 管理。 NVIDIA DRA kubelet-plugin 与经典 device plugin(例如 HAMi 的 nvidia.com/gpualloc,或标准的 nvidia.com/gpu plugin)不能同时管理同一张卡——它们会重复预订。请将某个节点(或某块特定 GPU)专门留给 DRA,并确保其他 plugin 不会选中它。在另一插件正在服务的卡上启用 MIG 模式会干扰该插件所运行的工作负载。

故障排查

现象原因 / 解决办法
Pod 卡在 Pending,事件为 cannot allocate all claims没有任何 ResourceSlice 与 selector 匹配。执行 kubectl get resourceslices -o yaml 并检查 profile / attribute 字符串;确认节点已被打标签且 kubelet-plugin Pod 处于 Running 状态。
ResourceClaim 一直处于 pending(从未变成 allocated)GPU 未处于 MIG 模式(对于 mig.nvidia.com),或者该 profile 的所有切片都已被预留。
kubelet-plugin CrashLoopBackOff,日志为 invalid CDI Spec: no devicesMIG 模式已开启,但没有创建 MIG 实例。请在节点上运行 nvidia-smi mig -cgi <ids> -C(参见管理员章节),然后重启插件 Pod。
nvidia-smi -i 0 -mig 1 报告 pending,模式始终不变为 Enabled其他进程占用了 GPU(CUDA workload,或 dcgm-exporter)。停止它们 / 将监控 DaemonSet 移出该节点,然后重试;GPU reset(nvidia-smi -i 0 -r)或节点重启可最终完成卡住的切换。
TrainingRuntime 被拒绝:numProcPerNode ... no such overloadnumProcPerNode 必须是 auto、cpu、gpu,或者一个不带引号的整数——应使用 numProcPerNode: 1,而不是 "1"。
must be no more than ... / 应用时出现 schema 错误API 版本偏差——本指南面向 resource.k8s.io/v1(K8s 1.34 GA)。在 1.31–1.33 中,该 group 是 v1beta1/v1beta2,requests 的形状略有不同。
两个 GPU 资源互相争抢 / 随机出现 CUDA 错误一个经典 device plugin 和 DRA plugin 正在同时管理这张卡。请参见上面的警告。
Trainer container 看到的是完整的 24 GiB,而不是切片你应用的是 shared-gpu-timeslice(整块 GPU)模板,或者 MIG 模式已关闭。要获得真正的内存隔离切片,请在启用了 MIG 模式的 GPU 上使用 MIG 模板。

为了对整个流程进行可重复的覆盖,c15_dra_gpu_slice.sh 用例会应用模板、runtime 和 TrainJob,并断言微调在切片内完成。当不存在 gpu.nvidia.com ResourceSlices 时,它会自动跳过,因此在仅使用 device plugin 的集群上也会保持通过。