forked from llm-d/llm-d-inference-sim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkv_cache.go
More file actions
129 lines (106 loc) · 4.03 KB
/
Copy pathkv_cache.go
File metadata and controls
129 lines (106 loc) · 4.03 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
/*
Copyright 2025 The llm-d-inference-sim 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 kvcache
// contains all logic relevant to KV-cache support
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/llm-d/llm-d-inference-sim/pkg/common"
"github.com/llm-d/llm-d-inference-sim/pkg/common/logging"
openaiserverapi "github.com/llm-d/llm-d-inference-sim/pkg/openai-server-api"
"github.com/llm-d/llm-d-inference-sim/pkg/tokenizer"
"github.com/llm-d/llm-d-kv-cache-manager/pkg/kvcache/kvblock"
)
// PrefixCacheStats holds token-level prefix cache statistics for a single request,
// matching vLLM's PrefixCacheStats semantics where both fields count tokens.
type PrefixCacheStats struct {
// QueriedTokens is the total number of prompt tokens checked against the cache
QueriedTokens int
// CachedTokens is the number of prompt tokens that were already cached
CachedTokens int
}
type KVCacheHelper struct {
tokenizer tokenizer.Tokenizer
tokensProcessor kvblock.TokenProcessor // turns tokens to kv block keys
logger logr.Logger
blockCache *blockCache
blockSize int
prefixCacheStatsChan chan PrefixCacheStats
}
func NewKVCacheHelper(config *common.Configuration, logger logr.Logger, usageChan chan float64,
prefixCacheStatsChan chan PrefixCacheStats, tokenizer tokenizer.Tokenizer) (*KVCacheHelper, error) {
tokenProcConfig := kvblock.DefaultTokenProcessorConfig()
tokenProcConfig.BlockSize = config.TokenBlockSize
if config.HashSeed != "" {
tokenProcConfig.HashSeed = config.HashSeed
}
tokensProcessor := kvblock.NewChunkedTokenDatabase(tokenProcConfig)
blockCache, err := newBlockCache(config, logger, usageChan)
if err != nil {
return nil, fmt.Errorf("failed to create block cache: %w", err)
}
return &KVCacheHelper{
tokenizer: tokenizer,
tokensProcessor: tokensProcessor,
blockCache: blockCache,
logger: logger,
blockSize: config.TokenBlockSize,
prefixCacheStatsChan: prefixCacheStatsChan,
}, nil
}
// Run starts the helper.
func (h *KVCacheHelper) Run(ctx context.Context) {
h.blockCache.start(ctx)
}
func (h *KVCacheHelper) Discard() {
h.blockCache.discard()
}
func (h *KVCacheHelper) Activate() {
h.blockCache.activate()
}
func (h *KVCacheHelper) OnRequestStart(vllmReq openaiserverapi.Request) (float64, error) {
h.logger.V(logging.TRACE).Info("KV cache - process request")
tokens := vllmReq.TokenizedPrompt().Tokens
modelName := vllmReq.GetModel()
// get block keys
blockKeys := h.tokensProcessor.TokensToKVBlockKeys(tokens, modelName)
h.logger.V(logging.TRACE).Info("Found tokens", "tokens", tokens, "block-keys", blockKeys)
blockHashes := make([]uint64, len(blockKeys))
for i, key := range blockKeys {
blockHashes[i] = key.ChunkHash
}
requestID := vllmReq.GetRequestID()
nBlocksAlreadyInCache, err := h.blockCache.startRequest(requestID, blockHashes)
if err != nil {
return 0, err
}
cachedTokens := nBlocksAlreadyInCache * h.blockSize
vllmReq.SetNumberOfCachedPromptTokens(cachedTokens)
totalBlocks := len(blockHashes)
cachedBlocks := h.blockCache.countCachedBlockPrefix(blockHashes)
var hitRate float64
if totalBlocks > 0 {
hitRate = float64(cachedBlocks) / float64(totalBlocks)
}
if h.prefixCacheStatsChan != nil {
common.WriteToChannel(h.prefixCacheStatsChan, PrefixCacheStats{
QueriedTokens: len(tokens),
CachedTokens: cachedTokens,
}, h.logger, "prefixCacheStatsChan")
}
return hitRate, nil
}
func (h *KVCacheHelper) OnRequestEnd(requestID string) error {
return h.blockCache.finishRequest(requestID)
}