-
Notifications
You must be signed in to change notification settings - Fork 3
/
rwkv.go
351 lines (307 loc) · 8.23 KB
/
rwkv.go
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright (c) seasonjs. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
package rwkv
import (
"errors"
"log"
"os"
"strings"
"time"
)
type RwkvModel struct {
cRwkv CRwkv
tokenizer Tokenizer
dylibPath string
ctx *RwkvCtx
options *RwkvOptions
isAutoLoad bool
}
type RwkvOptions struct {
PrintError bool
MaxTokens int
StopString string
Temperature float32
TopP float32
TokenizerType TokenizerType
CpuThreads uint32
GpuEnable bool
GpuOffLoadLayers uint32
}
func NewRwkvAutoModel(options RwkvOptions) (*RwkvModel, error) {
file, err := dumpRwkvLibrary(options.GpuEnable)
if err != nil {
return nil, err
}
dylibPath := file.Name()
model, err := NewRwkvModel(dylibPath, options)
if err != nil {
return nil, err
}
model.isAutoLoad = true
return model, nil
}
func NewRwkvModel(dylibPath string, options RwkvOptions) (*RwkvModel, error) {
cRwkv, err := NewCRwkv(dylibPath)
if err != nil {
return nil, err
}
var tk Tokenizer
if options.TokenizerType == Normal {
tk, err = NewNormalTokenizer()
}
if options.TokenizerType == World {
tk, err = NewWorldTokenizer()
}
if err != nil {
return nil, err
}
if options.GpuEnable {
log.Printf("If you want to try offload your model to the GPU. " +
"Please confirm the size of your GPU memory to prevent memory overflow." +
"If the model is larger than GPU memory, please specify the layers to offload.")
}
return &RwkvModel{
dylibPath: dylibPath,
cRwkv: cRwkv,
options: &options,
tokenizer: tk,
}, nil
}
func (m *RwkvModel) LoadFromFile(path string) error {
_, err := os.Stat(path)
if err != nil {
return errors.New("the system cannot find the model file specified")
}
ctx := m.cRwkv.RwkvInitFromFile(path, m.options.CpuThreads)
m.ctx = ctx
// offload all layers to GPU
gpuNLayers := uint32(m.cRwkv.RwkvGetNLayer(ctx) + 1)
// if user specify the layers to offload, use the user specified value
if m.options.GpuOffLoadLayers > 0 {
gpuNLayers = m.options.GpuOffLoadLayers
}
if m.options.GpuEnable {
err = m.cRwkv.RwkvGpuOffloadLayers(ctx, gpuNLayers)
if err != nil {
return err
}
}
// by default disable error printing and handle errors by go error
m.cRwkv.RwkvSetPrintErrors(ctx, m.options.PrintError)
return nil
}
func (m *RwkvModel) QuantizeModelFile(in, out string, format QuantizedFormat) error {
return m.cRwkv.RwkvQuantizeModelFile(m.ctx, in, out, format)
}
func (m *RwkvModel) Close() error {
if m.ctx != nil {
if err := m.cRwkv.RwkvFree(m.ctx); err != nil {
return err
}
m.ctx = nil
}
if m.isAutoLoad {
err := os.Remove(m.dylibPath)
return err
}
return nil
}
type RwkvState struct {
state []float32
logits []float32
rwkvModel *RwkvModel
}
// InitState give a new state for new chat context state
func (m *RwkvModel) InitState(prompt ...string) (*RwkvState, error) {
if err := hasCtx(m.ctx); err != nil {
return nil, err
}
state := make([]float32, m.cRwkv.RwkvGetStateLength(m.ctx))
m.cRwkv.RwkvInitState(m.ctx, state)
logits := make([]float32, m.cRwkv.RwkvGetLogitsLength(m.ctx))
p := ""
if len(prompt) > 0 {
p = prompt[0]
}
if len(p) > 0 {
startT := time.Now()
encode, err := m.tokenizer.Encode(p)
for _, token := range encode {
err = m.cRwkv.RwkvEval(m.ctx, uint32(token), state, state, logits)
if err != nil {
return nil, err
}
}
tc := time.Since(startT)
log.Print("init state time cost: ", tc, " total tokens: ", len(encode))
}
return &RwkvState{
state: state,
rwkvModel: m,
logits: logits,
}, nil
}
// CleanState will clean old state and set new state for new chat context state
func (s *RwkvState) CleanState(prompt ...string) (*RwkvState, error) {
if err := checkState(s); err != nil {
return nil, err
}
if s.state != nil {
s.state = nil
}
if s.logits != nil {
s.logits = nil
}
state := make([]float32, s.rwkvModel.cRwkv.RwkvGetStateLength(s.rwkvModel.ctx))
s.rwkvModel.cRwkv.RwkvInitState(s.rwkvModel.ctx, state)
logits := make([]float32, s.rwkvModel.cRwkv.RwkvGetLogitsLength(s.rwkvModel.ctx))
p := ""
if len(prompt) > 0 {
p = prompt[0]
}
if len(p) > 0 {
startT := time.Now()
encode, err := s.rwkvModel.tokenizer.Encode(p)
for _, token := range encode {
err = s.rwkvModel.cRwkv.RwkvEval(s.rwkvModel.ctx, uint32(token), state, state, logits)
if err != nil {
return nil, err
}
}
tc := time.Since(startT)
log.Print("init state time cost: ", tc, "total tokens: ", len(encode))
}
return &RwkvState{
state: state,
rwkvModel: s.rwkvModel,
logits: logits,
}, nil
}
// Predict give current chat a response
func (s *RwkvState) Predict(input string) (string, error) {
if err := checkState(s); err != nil {
return "", err
}
err := s.handelInput(input)
if err != nil {
return "", err
}
return s.generateResponse(nil)
}
// GetEmbedding give the model embedding.
// the embedding in rwkv is hidden state the len is n_emb*5*n_layer=46080.
// So if distillation is true, we split len to n_emb = 768
func (s *RwkvState) GetEmbedding(input string, distill bool) ([]float32, error) {
if err := checkState(s); err != nil {
return nil, err
}
encode, err := s.rwkvModel.tokenizer.Encode(input)
for _, token := range encode {
err = s.rwkvModel.cRwkv.RwkvEval(s.rwkvModel.ctx, uint32(token), s.state, s.state, s.logits)
if err != nil {
return nil, err
}
}
// we should keep state clean
nState := s.rwkvModel.cRwkv.RwkvGetStateLength(s.rwkvModel.ctx)
if distill {
nState = s.rwkvModel.cRwkv.RwkvGetNEmbedding(s.rwkvModel.ctx)
}
emb := make([]float32, nState)
copy(emb, s.state)
s.state = make([]float32, nState)
return emb, nil
}
func (s *RwkvState) PredictStream(input string, output chan string) {
go func() {
err := s.handelInput(input)
if err != nil {
output <- err.Error()
close(output)
return
}
_, err = s.generateResponse(func(s string) bool {
output <- s
return true
})
close(output)
}()
}
func (s *RwkvState) SaveState() ([]float32, error) {
if err := checkState(s); err != nil {
return nil, err
}
return s.state, nil
}
func (s *RwkvState) LoadState(state []float32) error {
if err := checkState(s); err != nil {
return err
}
if len(state) != len(s.state) {
return errors.New("state length is not match")
}
s.state = state
return nil
}
func (s *RwkvState) handelInput(input string) error {
encode, err := s.rwkvModel.tokenizer.Encode(input)
if err != nil {
return err
}
for _, token := range encode {
err = s.rwkvModel.cRwkv.RwkvEval(s.rwkvModel.ctx, uint32(token), s.state, s.state, s.logits)
if err != nil {
return err
}
}
return nil
}
func (s *RwkvState) generateResponse(callback func(s string) bool) (string, error) {
responseText := ""
for i := 0; i < s.rwkvModel.options.MaxTokens; i++ {
token, err := SampleLogits(s.logits, s.rwkvModel.options.Temperature, s.rwkvModel.options.TopP, map[int]float32{})
if err != nil {
return "", err
}
err = s.rwkvModel.cRwkv.RwkvEval(s.rwkvModel.ctx, uint32(token), s.state, s.state, s.logits)
if err != nil {
return "", err
}
chars := s.rwkvModel.tokenizer.Decode([]int{token})
responseText += chars
if callback != nil && !callback(chars) {
break
}
if strings.Contains(responseText, s.rwkvModel.options.StopString) {
responseText = strings.Split(responseText, s.rwkvModel.options.StopString)[0]
break
}
}
return responseText, nil
}
func hasCtx(ctx *RwkvCtx) error {
if ctx.ctx == 0 {
return errors.New("you must call LoadFromFile first")
}
return nil
}
func checkState(state *RwkvState) error {
if (state == nil) || (len(state.state) == 0) {
return errors.New("you must call InitState first")
}
if state.rwkvModel == nil {
return errors.New("you must call RwkvModel and InitState")
}
if err := hasCtx(state.rwkvModel.ctx); err != nil {
return err
}
rwkvStateLen := int(state.rwkvModel.cRwkv.RwkvGetStateLength(state.rwkvModel.ctx))
if len(state.state) != rwkvStateLen {
return errors.New("state length is not match,don't init state manually")
}
rwkvLogitsLen := int(state.rwkvModel.cRwkv.RwkvGetLogitsLength(state.rwkvModel.ctx))
if len(state.logits) != rwkvLogitsLen {
return errors.New("logits length is not match,don't init state manually")
}
return nil
}