-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.go
More file actions
209 lines (181 loc) · 4.75 KB
/
Copy pathcache.go
File metadata and controls
209 lines (181 loc) · 4.75 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package tokenest
import (
"container/list"
"encoding/binary"
"hash/maphash"
"math"
"sync"
)
const defaultCacheMinTextBytes = 512
var cacheSeed = maphash.MakeSeed()
type cacheEntry struct {
key uint64
value Result
}
type lruCache struct {
mu sync.Mutex
cap int
ll *list.List
items map[uint64]*list.Element
}
func newLRU(size int) *lruCache {
if size <= 0 {
return nil
}
return &lruCache{
cap: size,
ll: list.New(),
items: make(map[uint64]*list.Element, size),
}
}
func (c *lruCache) Get(key uint64) (Result, bool) {
if c == nil {
return Result{}, false
}
c.mu.Lock()
defer c.mu.Unlock()
if elem, ok := c.items[key]; ok {
c.ll.MoveToFront(elem)
return elem.Value.(cacheEntry).value, true
}
return Result{}, false
}
func (c *lruCache) Add(key uint64, value Result) {
if c == nil {
return
}
c.mu.Lock()
defer c.mu.Unlock()
if elem, ok := c.items[key]; ok {
elem.Value = cacheEntry{key: key, value: value}
c.ll.MoveToFront(elem)
return
}
elem := c.ll.PushFront(cacheEntry{key: key, value: value})
c.items[key] = elem
if c.ll.Len() > c.cap {
back := c.ll.Back()
if back != nil {
c.ll.Remove(back)
entry := back.Value.(cacheEntry)
delete(c.items, entry.key)
}
}
}
// WithCache wraps an estimator with an LRU cache. Caching is opt-in and disabled by default.
func WithCache(inner Estimator, size int) Estimator {
if inner == nil {
inner = DefaultEstimator()
}
cache := newLRU(size)
if cache == nil {
return inner
}
return &cachedEstimator{
inner: inner,
cache: cache,
minTextSize: defaultCacheMinTextBytes,
}
}
type cachedEstimator struct {
inner Estimator
cache *lruCache
minTextSize int
}
func (c *cachedEstimator) EstimateBytes(data []byte, opts Options) Result {
if len(data) < c.minTextSize {
return c.inner.EstimateBytes(data, opts)
}
key := cacheKeyBytes(data, opts)
if val, ok := c.cache.Get(key); ok {
return val
}
val := c.inner.EstimateBytes(data, opts)
c.cache.Add(key, val)
return val
}
func (c *cachedEstimator) EstimateText(text string, opts Options) Result {
if len(text) < c.minTextSize {
return c.inner.EstimateText(text, opts)
}
key := cacheKeyText(text, opts)
if val, ok := c.cache.Get(key); ok {
return val
}
val := c.inner.EstimateText(text, opts)
c.cache.Add(key, val)
return val
}
func (c *cachedEstimator) EstimateInput(text string, images ImageCounts, messageCount int, opts Options) Result {
if len(text) < c.minTextSize {
return c.inner.EstimateInput(text, images, messageCount, opts)
}
key := cacheKeyInput(text, images, messageCount, opts)
if val, ok := c.cache.Get(key); ok {
return val
}
val := c.inner.EstimateInput(text, images, messageCount, opts)
c.cache.Add(key, val)
return val
}
func (c *cachedEstimator) EstimateOutput(text string, opts Options) Result {
return c.EstimateText(text, opts)
}
func cacheKeyBytes(data []byte, opts Options) uint64 {
strategy := effectiveBytesStrategy(opts.Strategy)
profile := resolveProfile(opts)
return hashKey(strategy, profile, opts, data, ImageCounts{}, 0, 'b')
}
func cacheKeyText(text string, opts Options) uint64 {
strategy := effectiveTextStrategy(opts.Strategy)
profile := resolveProfile(opts)
return hashKey(strategy, profile, opts, []byte(text), ImageCounts{}, 0, 't')
}
func cacheKeyInput(text string, images ImageCounts, messageCount int, opts Options) uint64 {
strategy := effectiveTextStrategy(opts.Strategy)
profile := resolveProfile(opts)
return hashKey(strategy, profile, opts, []byte(text), images, messageCount, 'i')
}
func effectiveBytesStrategy(strategy Strategy) Strategy {
if strategy == StrategyAuto {
return StrategyUltraFast
}
return strategy
}
func effectiveTextStrategy(strategy Strategy) Strategy {
if strategy == StrategyAuto {
return StrategyFast
}
return strategy
}
func hashKey(strategy Strategy, profile Profile, opts Options, data []byte, images ImageCounts, messageCount int, kind byte) uint64 {
var h maphash.Hash
h.SetSeed(cacheSeed)
writeUint64(&h, uint64(kind))
writeUint64(&h, uint64(strategy))
writeUint64(&h, uint64(profile))
writeUint64(&h, math.Float64bits(opts.GlobalMultiplier))
writeUint64(&h, boolToUint64(opts.Explain))
writeUint64(&h, uint64(messageCount))
writeUint64(&h, uint64(images.LowDetail))
writeUint64(&h, uint64(images.HighDetail))
writeUint64(&h, uint64(images.Unknown))
writeUint64(&h, uint64(BaseOverhead))
writeUint64(&h, uint64(PerMessageOverhead))
writeUint64(&h, uint64(ImageTokensLow))
writeUint64(&h, uint64(ImageTokensHigh))
writeUint64(&h, uint64(ImageTokensDefault))
h.Write(data)
return h.Sum64()
}
func writeUint64(h *maphash.Hash, v uint64) {
var buf [8]byte
binary.LittleEndian.PutUint64(buf[:], v)
h.Write(buf[:])
}
func boolToUint64(v bool) uint64 {
if v {
return 1
}
return 0
}