|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes 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 picker |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/json" |
| 22 | + "fmt" |
| 23 | + "math" |
| 24 | + "math/rand" |
| 25 | + "sort" |
| 26 | + "time" |
| 27 | + |
| 28 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 29 | + |
| 30 | + "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/plugins" |
| 31 | + "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/scheduling/framework" |
| 32 | + "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/scheduling/types" |
| 33 | + logutil "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/util/logging" |
| 34 | +) |
| 35 | + |
| 36 | +const ( |
| 37 | + WeightedRandomPickerType = "weighted-random-picker" |
| 38 | +) |
| 39 | + |
| 40 | +// weightedScoredPod represents a scored pod with its A-Res sampling key |
| 41 | +type weightedScoredPod struct { |
| 42 | + *types.ScoredPod |
| 43 | + key float64 |
| 44 | +} |
| 45 | + |
| 46 | +var _ framework.Picker = &WeightedRandomPicker{} |
| 47 | + |
| 48 | +func WeightedRandomPickerFactory(name string, rawParameters json.RawMessage, _ plugins.Handle) (plugins.Plugin, error) { |
| 49 | + parameters := pickerParameters{ |
| 50 | + MaxNumOfEndpoints: DefaultMaxNumOfEndpoints, |
| 51 | + } |
| 52 | + if rawParameters != nil { |
| 53 | + if err := json.Unmarshal(rawParameters, ¶meters); err != nil { |
| 54 | + return nil, fmt.Errorf("failed to parse the parameters of the '%s' picker - %w", WeightedRandomPickerType, err) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return NewWeightedRandomPicker(parameters.MaxNumOfEndpoints).WithName(name), nil |
| 59 | +} |
| 60 | + |
| 61 | +func NewWeightedRandomPicker(maxNumOfEndpoints int) *WeightedRandomPicker { |
| 62 | + if maxNumOfEndpoints <= 0 { |
| 63 | + maxNumOfEndpoints = DefaultMaxNumOfEndpoints |
| 64 | + } |
| 65 | + |
| 66 | + return &WeightedRandomPicker{ |
| 67 | + typedName: plugins.TypedName{Type: WeightedRandomPickerType, Name: WeightedRandomPickerType}, |
| 68 | + maxNumOfEndpoints: maxNumOfEndpoints, |
| 69 | + randomPicker: NewRandomPicker(maxNumOfEndpoints), |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +type WeightedRandomPicker struct { |
| 74 | + typedName plugins.TypedName |
| 75 | + maxNumOfEndpoints int |
| 76 | + randomPicker *RandomPicker // fallback for zero weights |
| 77 | +} |
| 78 | + |
| 79 | +func (p *WeightedRandomPicker) WithName(name string) *WeightedRandomPicker { |
| 80 | + p.typedName.Name = name |
| 81 | + return p |
| 82 | +} |
| 83 | + |
| 84 | +func (p *WeightedRandomPicker) TypedName() plugins.TypedName { |
| 85 | + return p.typedName |
| 86 | +} |
| 87 | + |
| 88 | +// WeightedRandomPicker performs weighted random sampling using A-Res algorithm. |
| 89 | +// Reference: https://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf |
| 90 | +// Algorithm: |
| 91 | +// - Uses A-Res (Algorithm for Reservoir Sampling): keyᵢ = Uᵢ^(1/wᵢ) |
| 92 | +// - Selects k items with largest keys for mathematically correct weighted sampling |
| 93 | +// - More efficient than traditional cumulative probability approach |
| 94 | +// |
| 95 | +// Key characteristics: |
| 96 | +// - Mathematically correct weighted random sampling |
| 97 | +// - Single pass algorithm with O(n + k log k) complexity |
| 98 | +func (p *WeightedRandomPicker) Pick(ctx context.Context, cycleState *types.CycleState, scoredPods []*types.ScoredPod) *types.ProfileRunResult { |
| 99 | + log.FromContext(ctx).V(logutil.DEBUG).Info(fmt.Sprintf("Selecting maximum '%d' pods from %d candidates using weighted random sampling: %+v", |
| 100 | + p.maxNumOfEndpoints, len(scoredPods), scoredPods)) |
| 101 | + |
| 102 | + // Check if all weights are zero or negative |
| 103 | + allZeroWeights := true |
| 104 | + for _, scoredPod := range scoredPods { |
| 105 | + if scoredPod.Score > 0 { |
| 106 | + allZeroWeights = false |
| 107 | + break |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + // Delegate to RandomPicker for uniform selection when all weights are zero |
| 112 | + if allZeroWeights { |
| 113 | + log.FromContext(ctx).V(logutil.DEBUG).Info("All weights are zero, delegating to RandomPicker for uniform selection") |
| 114 | + return p.randomPicker.Pick(ctx, cycleState, scoredPods) |
| 115 | + } |
| 116 | + |
| 117 | + randomGenerator := rand.New(rand.NewSource(time.Now().UnixNano())) |
| 118 | + |
| 119 | + // A-Res algorithm: keyᵢ = Uᵢ^(1/wᵢ) |
| 120 | + weightedPods := make([]weightedScoredPod, 0, len(scoredPods)) |
| 121 | + |
| 122 | + for _, scoredPod := range scoredPods { |
| 123 | + weight := float64(scoredPod.Score) |
| 124 | + |
| 125 | + // Handle zero or negative weights |
| 126 | + if weight <= 0 { |
| 127 | + // Assign very small key for zero-weight pods (effectively excludes them) |
| 128 | + weightedPods = append(weightedPods, weightedScoredPod{ |
| 129 | + ScoredPod: scoredPod, |
| 130 | + key: 0, |
| 131 | + }) |
| 132 | + continue |
| 133 | + } |
| 134 | + |
| 135 | + // Generate random number U in (0,1) |
| 136 | + u := randomGenerator.Float64() |
| 137 | + if u == 0 { |
| 138 | + u = 1e-10 // Avoid log(0) |
| 139 | + } |
| 140 | + |
| 141 | + // Calculate key = U^(1/weight) |
| 142 | + key := math.Pow(u, 1.0/weight) |
| 143 | + |
| 144 | + weightedPods = append(weightedPods, weightedScoredPod{ |
| 145 | + ScoredPod: scoredPod, |
| 146 | + key: key, |
| 147 | + }) |
| 148 | + } |
| 149 | + |
| 150 | + // Sort by key in descending order (largest keys first) |
| 151 | + sort.Slice(weightedPods, func(i, j int) bool { |
| 152 | + return weightedPods[i].key > weightedPods[j].key |
| 153 | + }) |
| 154 | + |
| 155 | + // Select top k pods |
| 156 | + selectedCount := min(p.maxNumOfEndpoints, len(weightedPods)) |
| 157 | + |
| 158 | + scoredPods = make([]*types.ScoredPod, selectedCount) |
| 159 | + for i := range selectedCount { |
| 160 | + scoredPods[i] = weightedPods[i].ScoredPod |
| 161 | + } |
| 162 | + |
| 163 | + targetPods := make([]types.Pod, len(scoredPods)) |
| 164 | + for i, scoredPod := range scoredPods { |
| 165 | + targetPods[i] = scoredPod |
| 166 | + } |
| 167 | + |
| 168 | + return &types.ProfileRunResult{TargetPods: targetPods} |
| 169 | +} |
0 commit comments