|
| 1 | +/* |
| 2 | +Copyright 2025 The llm-d Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/json" |
| 22 | + "fmt" |
| 23 | + "os" |
| 24 | + "strings" |
| 25 | + "time" |
| 26 | + |
| 27 | + corev1 "k8s.io/api/core/v1" |
| 28 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 29 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 30 | + apitypes "k8s.io/apimachinery/pkg/types" |
| 31 | + "k8s.io/apimachinery/pkg/util/sets" |
| 32 | + "k8s.io/apimachinery/pkg/util/wait" |
| 33 | + corev1client "k8s.io/client-go/kubernetes/typed/core/v1" |
| 34 | + |
| 35 | + dpctlr "github.com/llm-d-incubation/llm-d-fast-model-actuation/pkg/controller/dual-pods" |
| 36 | + |
| 37 | + "k8s.io/klog/v2" |
| 38 | +) |
| 39 | + |
| 40 | +// This code maintains a ConfigMap named "gpu-allocs" that holds the current test allocations |
| 41 | +// of GPUs. The data of this ConfigMap is a map from GPU UID to the JSON marshaling of a GPUHolder. |
| 42 | + |
| 43 | +// gpuMap maps node name to nodeGPUMap |
| 44 | +type gpuMap map[string]nodeGPUMap |
| 45 | + |
| 46 | +// nodeGPUMap maps GPU UID to index |
| 47 | +type nodeGPUMap map[string]int |
| 48 | + |
| 49 | +// GPUHolder identifies a test requester that is currently allocated the use of a GPU |
| 50 | +type GPUHolder struct { |
| 51 | + NodeName string |
| 52 | + PodUID apitypes.UID |
| 53 | +} |
| 54 | + |
| 55 | +// GPUAllocMap maps GPU UID to GPUHolder |
| 56 | +type GPUAllocMap map[string]GPUHolder |
| 57 | + |
| 58 | +func getGPUMap(ctx context.Context, cmClient corev1client.ConfigMapInterface) (gpuMap, error) { |
| 59 | + cm, err := cmClient.Get(ctx, dpctlr.GPUMapName, metav1.GetOptions{}) |
| 60 | + if err != nil { |
| 61 | + return nil, fmt.Errorf("failed to retrieve gpu-map ConfigMap: %w", err) |
| 62 | + } |
| 63 | + ans := gpuMap{} |
| 64 | + for nodeName, mapStr := range cm.Data { |
| 65 | + nm := nodeGPUMap{} |
| 66 | + err := json.Unmarshal([]byte(mapStr), &nm) |
| 67 | + if err != nil { |
| 68 | + return nil, fmt.Errorf("failed to parse GPU map for node %s: %w", nodeName, err) |
| 69 | + } |
| 70 | + ans[nodeName] = nm |
| 71 | + } |
| 72 | + return ans, nil |
| 73 | +} |
| 74 | + |
| 75 | +func (gm gpuMap) onNode(nodeName string) sets.Set[string] { |
| 76 | + ngm := gm[nodeName] |
| 77 | + if ngm != nil { |
| 78 | + return sets.KeySet(ngm) |
| 79 | + } |
| 80 | + return sets.New[string]() |
| 81 | +} |
| 82 | + |
| 83 | +func getGPUAlloc(ctx context.Context, cmClient corev1client.ConfigMapInterface) (GPUAllocMap, *corev1.ConfigMap, error) { |
| 84 | + cm, err := cmClient.Get(ctx, allocMapName, metav1.GetOptions{}) |
| 85 | + if err != nil { |
| 86 | + if apierrors.IsNotFound(err) { |
| 87 | + // It up to us to create it |
| 88 | + cmProto := corev1.ConfigMap{ |
| 89 | + TypeMeta: metav1.TypeMeta{ |
| 90 | + Kind: "ConfigMap", |
| 91 | + APIVersion: corev1.SchemeGroupVersion.String(), |
| 92 | + }, |
| 93 | + ObjectMeta: metav1.ObjectMeta{ |
| 94 | + Name: allocMapName, |
| 95 | + }, |
| 96 | + } |
| 97 | + cm, err = cmClient.Create(ctx, &cmProto, metav1.CreateOptions{FieldManager: agentName}) |
| 98 | + if err != nil { |
| 99 | + return nil, nil, fmt.Errorf("failed to create GPU allocation ConfigMap: %w", err) |
| 100 | + } |
| 101 | + } else { |
| 102 | + return nil, nil, fmt.Errorf("failed to fetch GPU allocation ConfigMap: %w", err) |
| 103 | + } |
| 104 | + } |
| 105 | + ans := GPUAllocMap{} |
| 106 | + for gpuUID, holderStr := range cm.Data { |
| 107 | + holderReader := strings.NewReader(holderStr) |
| 108 | + var holder GPUHolder |
| 109 | + decoder := json.NewDecoder(holderReader) |
| 110 | + decoder.DisallowUnknownFields() |
| 111 | + err = decoder.Decode(&holder) |
| 112 | + if err != nil { |
| 113 | + return nil, nil, fmt.Errorf("failed to decode GPU allocation for GPU UID %s: %w", gpuUID, err) |
| 114 | + } |
| 115 | + ans[gpuUID] = holder |
| 116 | + } |
| 117 | + cm = cm.DeepCopy() |
| 118 | + if cm.Data == nil { |
| 119 | + cm.Data = map[string]string{} |
| 120 | + } |
| 121 | + return ans, cm, nil |
| 122 | +} |
| 123 | + |
| 124 | +func allocateGPUs(ctx context.Context, coreClient corev1client.CoreV1Interface, nodeName, namespace string, podUID apitypes.UID, numGPUs uint) []string { |
| 125 | + logger := klog.FromContext(ctx) |
| 126 | + cmClient := coreClient.ConfigMaps(namespace) |
| 127 | + podClient := coreClient.Pods(namespace) |
| 128 | + var gpuUIDs []string |
| 129 | + // try once to allocate the requested number of GPUs; |
| 130 | + // on failure return explanatory error; |
| 131 | + // on success return nil. |
| 132 | + try := func(ctx context.Context) (err error) { |
| 133 | + gpuMap, err := getGPUMap(ctx, cmClient) |
| 134 | + if err != nil { |
| 135 | + return err |
| 136 | + } |
| 137 | + avail := gpuMap.onNode(nodeName) |
| 138 | + podUIDs, err := getPodUIDs(ctx, podClient) |
| 139 | + if err != nil { |
| 140 | + return err |
| 141 | + } |
| 142 | + if !podUIDs.Has(podUID) { |
| 143 | + return fmt.Errorf("pod UID %q not found among current Pods", podUID) |
| 144 | + } |
| 145 | + // Get the current allocations, as a data structure and as a ConfigMap object. |
| 146 | + gpuAllocMap, gpuAllocCM, err := getGPUAlloc(ctx, cmClient) |
| 147 | + if err != nil { |
| 148 | + return err |
| 149 | + } |
| 150 | + // Collect the ones used by other Pods on the same Node, |
| 151 | + // and remove obsolete entries from the ConfigMap. |
| 152 | + used := sets.New[string]() |
| 153 | + for gpuUID, holder := range gpuAllocMap { |
| 154 | + if holder.NodeName != nodeName { |
| 155 | + continue |
| 156 | + } |
| 157 | + if !podUIDs.Has(holder.PodUID) { |
| 158 | + delete(gpuAllocCM.Data, gpuUID) |
| 159 | + } else if holder.PodUID != podUID { |
| 160 | + used.Insert(gpuUID) |
| 161 | + } |
| 162 | + } |
| 163 | + // Compute the sorted list of unused GPUs on the right Node. |
| 164 | + rem := sets.List(avail.Difference(used)) |
| 165 | + if uint(len(rem)) < numGPUs { |
| 166 | + return fmt.Errorf("fewer than %d GPUs available (%v) for node %q", numGPUs, rem, nodeName) |
| 167 | + } |
| 168 | + // Take the requested number |
| 169 | + // FROM THE HEAD OF THE LIST --- this is a choice to aid making repeatable tests. |
| 170 | + gpuUIDs = rem[:numGPUs] |
| 171 | + for _, gpuUID := range gpuUIDs { |
| 172 | + holder := GPUHolder{NodeName: nodeName, PodUID: podUID} |
| 173 | + holderBytes, err := json.Marshal(holder) |
| 174 | + if err != nil { |
| 175 | + return fmt.Errorf("failed to marshal holder for GPU %s (%#v): %w", gpuUID, holder, err) |
| 176 | + } |
| 177 | + gpuAllocCM.Data[gpuUID] = string(holderBytes) |
| 178 | + } |
| 179 | + echo, err := cmClient.Update(ctx, gpuAllocCM, metav1.UpdateOptions{ |
| 180 | + FieldManager: agentName, |
| 181 | + }) |
| 182 | + if err != nil { |
| 183 | + return fmt.Errorf("failed to update GPU allocation ConfigMap: %w", err) |
| 184 | + } |
| 185 | + logger.Info("Successful allocation", "nodeName", nodeName, "podUID", podUID, "gpus", gpuUIDs, "newResourceVersion", echo.ResourceVersion) |
| 186 | + return nil |
| 187 | + } |
| 188 | + err := wait.PollUntilContextCancel(ctx, time.Second, true, func(ctx context.Context) (bool, error) { |
| 189 | + err := try(ctx) |
| 190 | + if err != nil { |
| 191 | + logger.Error(err, "Failed to allocate") |
| 192 | + } |
| 193 | + return err == nil, nil |
| 194 | + }) |
| 195 | + if err != nil { |
| 196 | + fmt.Fprintf(os.Stderr, "Failed to allocate GPUS: %s\n", err.Error()) |
| 197 | + os.Exit(100) |
| 198 | + } |
| 199 | + return gpuUIDs |
| 200 | +} |
| 201 | + |
| 202 | +func getPodUIDs(ctx context.Context, podClient corev1client.PodInterface) (sets.Set[apitypes.UID], error) { |
| 203 | + podList, err := podClient.List(ctx, metav1.ListOptions{}) |
| 204 | + if err != nil { |
| 205 | + return nil, err |
| 206 | + } |
| 207 | + uids, _ := dpctlr.SliceMap(podList.Items, func(pod corev1.Pod) (apitypes.UID, error) { |
| 208 | + return pod.UID, nil |
| 209 | + }) |
| 210 | + return sets.New(uids...), nil |
| 211 | +} |
0 commit comments