|
| 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 scorer |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "strconv" |
| 22 | + "time" |
| 23 | + |
| 24 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 25 | + |
| 26 | + "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/framework/interface/datalayer" |
| 27 | + "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/framework/interface/requestcontrol" |
| 28 | + schedulingtypes "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/framework/interface/scheduling" |
| 29 | + predictedlatency "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/framework/plugins/scheduling/scorer/predictedlatency" |
| 30 | + logutil "sigs.k8s.io/gateway-api-inference-extension/pkg/common/util/logging" |
| 31 | + requtil "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/util/request" |
| 32 | + latencypredictor "sigs.k8s.io/gateway-api-inference-extension/sidecars/latencypredictorasync" |
| 33 | +) |
| 34 | + |
| 35 | +// PDSLOAwareRouter wraps the base PredictedLatency to add P/D-specific hook logic. |
| 36 | +// This keeps P/D disaggregation concerns in llm-d-inference-scheduler rather than |
| 37 | +// leaking them into the generic gateway-api-inference-extension. |
| 38 | +type PDSLOAwareRouter struct { |
| 39 | + *predictedlatency.PredictedLatency |
| 40 | +} |
| 41 | + |
| 42 | +var _ requestcontrol.PreRequest = &PDSLOAwareRouter{} |
| 43 | +var _ requestcontrol.ResponseReceived = &PDSLOAwareRouter{} |
| 44 | +var _ requestcontrol.ResponseStreaming = &PDSLOAwareRouter{} |
| 45 | +var _ requestcontrol.ResponseComplete = &PDSLOAwareRouter{} |
| 46 | + |
| 47 | +// PreRequest delegates to the base router |
| 48 | +func (p *PDSLOAwareRouter) PreRequest(ctx context.Context, request *schedulingtypes.LLMRequest, schedulingResult *schedulingtypes.SchedulingResult) { |
| 49 | + p.PredictedLatency.PreRequest(ctx, request, schedulingResult) |
| 50 | +} |
| 51 | + |
| 52 | +// ResponseReceived adds P/D-specific logic to extract prefill timing headers |
| 53 | +// before delegating to the base router. |
| 54 | +func (p *PDSLOAwareRouter) ResponseReceived(ctx context.Context, request *schedulingtypes.LLMRequest, response *requestcontrol.Response, targetPod *datalayer.EndpointMetadata) { |
| 55 | + logger := log.FromContext(ctx) |
| 56 | + |
| 57 | + // P/D-specific: Check for prefill timing headers from the decode sidecar |
| 58 | + if prefillTTFTStr, ok := response.Headers["x-prefill-ttft-ms"]; ok && prefillTTFTStr != "" { |
| 59 | + logger.V(logutil.DEBUG).Info("Detected prefill timing header", |
| 60 | + "ttft_ms", prefillTTFTStr, |
| 61 | + "requestID", request.Headers[requtil.RequestIdHeaderKey]) |
| 62 | + |
| 63 | + // Parse prefill TTFT |
| 64 | + prefillTTFT, err := strconv.ParseFloat(prefillTTFTStr, 64) |
| 65 | + if err != nil { |
| 66 | + logger.V(logutil.DEBUG).Error(err, "Failed to parse prefill TTFT header", "value", prefillTTFTStr) |
| 67 | + } else { |
| 68 | + // Record training data for the prefill pod |
| 69 | + p.recordPrefillTrainingData(ctx, request, prefillTTFT) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + // Delegate to base router for decode prediction logic |
| 74 | + p.PredictedLatency.ResponseReceived(ctx, request, response, targetPod) |
| 75 | +} |
| 76 | + |
| 77 | +// ResponseStreaming delegates to the base router |
| 78 | +func (p *PDSLOAwareRouter) ResponseStreaming(ctx context.Context, request *schedulingtypes.LLMRequest, response *requestcontrol.Response, pod *datalayer.EndpointMetadata) { |
| 79 | + p.PredictedLatency.ResponseStreaming(ctx, request, response, pod) |
| 80 | +} |
| 81 | + |
| 82 | +// ResponseComplete delegates to the base router |
| 83 | +func (p *PDSLOAwareRouter) ResponseComplete(ctx context.Context, request *schedulingtypes.LLMRequest, response *requestcontrol.Response, pod *datalayer.EndpointMetadata) { |
| 84 | + p.PredictedLatency.ResponseComplete(ctx, request, response, pod) |
| 85 | +} |
| 86 | + |
| 87 | +// recordPrefillTrainingData records training data for the prefill pod based on timing |
| 88 | +// reported by the decode sidecar via x-prefill-ttft-ms header. |
| 89 | +// |
| 90 | +// This method is P/D-specific and lives in llm-d-inference-scheduler because it: |
| 91 | +// - Assumes two-phase scheduling with "prefill" and "decode" profiles |
| 92 | +// - Knows about the llm-d.ai/role label structure |
| 93 | +// - Understands that prefill pods only handle TTFT (no TPOT) |
| 94 | +func (p *PDSLOAwareRouter) recordPrefillTrainingData( |
| 95 | + ctx context.Context, |
| 96 | + request *schedulingtypes.LLMRequest, |
| 97 | + actualPrefillTTFT float64, |
| 98 | +) { |
| 99 | + logger := log.FromContext(ctx) |
| 100 | + |
| 101 | + // Get scheduling result for this request |
| 102 | + schedulingResult, err := p.PredictedLatency.GetSchedulingResultForRequest(request) |
| 103 | + if err != nil { |
| 104 | + logger.V(logutil.DEBUG).Error(err, "Failed to get scheduling result for prefill training") |
| 105 | + return |
| 106 | + } |
| 107 | + |
| 108 | + // P/D-specific: Extract prefill pod from the "prefill" profile |
| 109 | + prefillResult, exists := schedulingResult.ProfileResults["prefill"] |
| 110 | + if !exists || prefillResult == nil || len(prefillResult.TargetPods) == 0 { |
| 111 | + logger.V(logutil.DEBUG).Info("No prefill pod in scheduling result, skipping prefill training") |
| 112 | + return |
| 113 | + } |
| 114 | + |
| 115 | + prefillPod := prefillResult.TargetPods[0] |
| 116 | + |
| 117 | + // Get metrics for the prefill pod |
| 118 | + lastSeenMetrics, err := p.PredictedLatency.GetLastSeenMetricsForRequest(request) |
| 119 | + if err != nil { |
| 120 | + logger.V(logutil.DEBUG).Error(err, "Failed to get metrics for prefill training") |
| 121 | + return |
| 122 | + } |
| 123 | + |
| 124 | + prefillMetrics, exists := lastSeenMetrics["prefill"] |
| 125 | + if !exists || prefillMetrics == nil { |
| 126 | + logger.V(logutil.DEBUG).Info("No metrics available for prefill pod") |
| 127 | + return |
| 128 | + } |
| 129 | + |
| 130 | + // Get prefix cache score |
| 131 | + prefixCacheScores, err := p.PredictedLatency.GetPrefixCacheScoresForRequest(request) |
| 132 | + if err != nil { |
| 133 | + logger.V(logutil.DEBUG).Error(err, "Failed to get prefix cache scores") |
| 134 | + return |
| 135 | + } |
| 136 | + prefixCacheScore := prefixCacheScores[prefillPod.GetMetadata().String()] |
| 137 | + |
| 138 | + // Get prompt |
| 139 | + prompt, err := p.PredictedLatency.GetRequestPrompt(request) |
| 140 | + if err != nil { |
| 141 | + logger.V(logutil.DEBUG).Error(err, "Failed to get prompt for prefill training") |
| 142 | + return |
| 143 | + } |
| 144 | + |
| 145 | + // Build training entry using the PDPredictionRequestBuilder |
| 146 | + // This will automatically populate PodType="prefill" based on llm-d.ai/role label |
| 147 | + requestBuilder := p.PredictedLatency.GetRequestBuilder() |
| 148 | + entry := requestBuilder.BuildTrainingEntry( |
| 149 | + ctx, |
| 150 | + prefillPod, |
| 151 | + prefillMetrics, |
| 152 | + prompt, |
| 153 | + actualPrefillTTFT, // Actual TTFT from sidecar |
| 154 | + 0, // TPOT not applicable for prefill |
| 155 | + time.Now(), |
| 156 | + 0, // No tokens generated yet for prefill |
| 157 | + prefixCacheScore, |
| 158 | + ) |
| 159 | + |
| 160 | + // Record training data |
| 161 | + latencyPredictor := p.PredictedLatency.GetLatencyPredictor().(latencypredictor.PredictorInterface) |
| 162 | + if err := latencyPredictor.AddTrainingDataBulk([]latencypredictor.TrainingEntry{entry}); err != nil { |
| 163 | + logger.V(logutil.DEBUG).Error(err, "Failed to record prefill training data") |
| 164 | + } else { |
| 165 | + logger.V(logutil.DEBUG).Info("Recorded prefill training data", |
| 166 | + "pod", prefillPod.GetPod().String(), |
| 167 | + "ttft_ms", actualPrefillTTFT, |
| 168 | + "pod_type", "prefill") |
| 169 | + } |
| 170 | +} |
0 commit comments