-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathdecode.go
More file actions
167 lines (144 loc) · 5.22 KB
/
Copy pathdecode.go
File metadata and controls
167 lines (144 loc) · 5.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
Copyright 2026 The llm-d Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package steps
import (
"context"
"errors"
"fmt"
"net/http"
"sigs.k8s.io/controller-runtime/pkg/log"
logutil "github.com/llm-d/llm-d-router/pkg/common/observability/logging"
reqcommon "github.com/llm-d/llm-d-router/pkg/common/request"
"github.com/llm-d/llm-d-router/pkg/coordinator/connectors/kv"
"github.com/llm-d/llm-d-router/pkg/coordinator/gateway"
coordmetrics "github.com/llm-d/llm-d-router/pkg/coordinator/metrics"
"github.com/llm-d/llm-d-router/pkg/coordinator/pipeline"
)
const DecodeStepName = "decode"
func init() {
pipeline.Register(DecodeStepName, NewDecodeStep)
}
type DecodeStep struct {
useOpenAIFormat bool
gwClient *gateway.Client
kv kv.Connector
}
func NewDecodeStep(gwClient *gateway.Client, params map[string]any) (pipeline.Step, error) {
if gwClient == nil {
return nil, errors.New("decode: gateway client is required")
}
useOpenAI, err := parseUseOpenAIFormat(params)
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
kvName, err := paramString(params, ParamKVConnector)
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
kvConn, err := kv.Build(kvName)
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return &DecodeStep{useOpenAIFormat: useOpenAI, gwClient: gwClient, kv: kvConn}, nil
}
func (s *DecodeStep) Name() string { return DecodeStepName }
func (s *DecodeStep) Execute(ctx context.Context, reqCtx *pipeline.RequestContext) error {
logger := log.FromContext(ctx).WithName(DecodeStepName)
s.prepareDecodeBody(ctx, reqCtx)
logger.V(logutil.DEFAULT).Info("sending request", "path", reqCtx.OriginalPath, "stream", reqCtx.Stream)
proxyReq, err := newDecodeProxyRequest(ctx, logger, DecodeStepName, reqCtx, s.gwClient, reqCtx.Body, nil)
if err != nil {
return err
}
transport := instrumentedTransport(s.gwClient.Transport(), coordmetrics.UpstreamDecode)
proxy, out := newDecodeProxy(logger, transport, nil)
proxy.ServeHTTP(reqCtx.ResponseWriter, proxyReq)
if out.TransportErr != nil {
return &pipeline.UpstreamStreamedError{Step: DecodeStepName, Cause: out.TransportErr}
}
if out.Status >= http.StatusBadRequest {
return &pipeline.UpstreamStreamedError{Step: DecodeStepName, StatusCode: out.Status}
}
return nil
}
// prepareDecodeBody mutates reqCtx.Body in place rather than on a clone (unlike
// prefill and conditional-decode). decode is the terminal pipeline step: its body
// is streamed straight to the client and no later step reads reqCtx.Body. A clone
// would also be insufficient, since injectUUIDs mutates nested values that a shallow
// maps.Clone would still share. This is sound only while the pipeline runs steps
// sequentially; if it ever goes concurrent, decode must copy like the others.
func (s *DecodeStep) prepareDecodeBody(ctx context.Context, reqCtx *pipeline.RequestContext) {
kvParams := s.kv.PrepareDecodeKVParams(ctx, reqCtx)
s.injectUUIDs(reqCtx)
format := resolveFormat(s.useOpenAIFormat, reqCtx.OriginalPath)
switch format {
case gateway.FormatChatCompletions:
reqCtx.Body[reqcommon.FieldKVTransferParams] = kvParams
s.injectTokensField(reqCtx)
case gateway.FormatCompletions:
reqCtx.Body[reqcommon.FieldKVTransferParams] = kvParams
if len(reqCtx.TokenIDs) > 0 {
reqCtx.Body["prompt"] = reqCtx.TokenIDs
}
case gateway.FormatGenerate:
// The /inference/v1/generate engine reads transfer params only from
// sampling_params.extra_args; a top-level kv_transfer_params is ignored,
// so the decode worker never pulls the prefill KV over NIXL. Merge into
// the client's sampling_params to preserve max_tokens and other fields.
sampling, ok := reqCtx.Body[reqcommon.FieldSamplingParams].(map[string]any)
if !ok {
sampling = map[string]any{}
reqCtx.Body[reqcommon.FieldSamplingParams] = sampling
}
setGenerateTransferParams(sampling, kvParams, nil)
}
}
func (s *DecodeStep) injectTokensField(reqCtx *pipeline.RequestContext) {
tokens := map[string]any{
"token_ids": reqCtx.TokenIDs,
}
if features := buildMMFeatures(reqCtx.MultimodalEntries, false); features != nil {
tokens["features"] = features
}
reqCtx.Body["tokens"] = tokens
}
func (s *DecodeStep) injectUUIDs(reqCtx *pipeline.RequestContext) {
messages, ok := reqCtx.Body["messages"].([]any)
if !ok {
return
}
hashIdx := 0
for _, msg := range messages {
msgMap, ok := msg.(map[string]any)
if !ok {
continue
}
content, ok := msgMap["content"].([]any)
if !ok {
continue
}
for _, part := range content {
partMap, ok := part.(map[string]any)
if !ok {
continue
}
if partMap["type"] != "image_url" {
continue
}
if hashIdx < len(reqCtx.MultimodalEntries) {
partMap["uuid"] = reqCtx.MultimodalEntries[hashIdx].Hash
hashIdx++
}
}
}
}