tokenizer.go 7.28 KB
Newer Older
Patrick Devine's avatar
Patrick Devine committed
1
2
3
package convert

import (
Michael Yang's avatar
Michael Yang committed
4
	"crypto/sha256"
Michael Yang's avatar
Michael Yang committed
5
	"encoding/hex"
Patrick Devine's avatar
Patrick Devine committed
6
	"encoding/json"
Michael Yang's avatar
Michael Yang committed
7
	"errors"
Michael Yang's avatar
Michael Yang committed
8
	"fmt"
9
	"io/fs"
Michael Yang's avatar
Michael Yang committed
10
	"log/slog"
Patrick Devine's avatar
Patrick Devine committed
11
	"os"
Michael Yang's avatar
Michael Yang committed
12
	"slices"
Michael Yang's avatar
Michael Yang committed
13
	"strings"
Michael Yang's avatar
bert  
Michael Yang committed
14
15

	"golang.org/x/exp/maps"
Michael Yang's avatar
Michael Yang committed
16
)
Michael Yang's avatar
Michael Yang committed
17

Michael Yang's avatar
Michael Yang committed
18
19
20
21
22
23
24
25
const (
	_ int32 = iota
	tokenTypeNormal
	tokenTypeUnknown
	tokenTypeControl
	tokenTypeUserDefined
	tokenTypeUnused
	tokenTypeByte
Patrick Devine's avatar
Patrick Devine committed
26
27
28
)

type Tokenizer struct {
Michael Yang's avatar
Michael Yang committed
29
30
31
32
33
34
35
36
	*Vocabulary
	SpecialVocabulary []*SpecialVocabulary
	Merges            []string

	Pre      string
	Template string
}

37
38
func parseTokenizer(fsys fs.FS, specialTokenTypes []string) (*Tokenizer, error) {
	v, err := parseVocabulary(fsys)
Michael Yang's avatar
Michael Yang committed
39
40
41
42
43
44
45
46
47
48
	if err != nil {
		return nil, err
	}

	t := &Tokenizer{
		Vocabulary: v,
		Pre:        "default",
	}

	addedTokens := make(map[string]token)
49
	if f, err := fsys.Open("tokenizer.json"); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
	} else if err != nil {
		return nil, err
	} else {
		defer f.Close()

		var tt tokenizer
		if err := json.NewDecoder(f).Decode(&tt); err != nil {
			return nil, err
		}

		for _, t := range tt.AddedTokens {
			addedTokens[t.Content] = t
		}

Michael Yang's avatar
Michael Yang committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
		if len(tt.Model.Merges) == 0 {
			// noop; merges is empty
		} else if err := json.Unmarshal(tt.Model.Merges, &t.Merges); err == nil {
			// noop; merges is []string
		} else if merges, err := func() ([][]string, error) {
			var merges [][]string
			if err := json.Unmarshal(tt.Model.Merges, &merges); err != nil {
				return nil, err
			}

			return merges, nil
		}(); err == nil {
			t.Merges = make([]string, len(merges))
			for i := range merges {
				t.Merges[i] = strings.Join(merges[i], " ")
			}
		} else {
			return nil, fmt.Errorf("could not parse tokenizer merges. expected []string or [][]string: %w", err)
		}
Michael Yang's avatar
Michael Yang committed
83
84
85
86
87
88

		sha256sum := sha256.New()
		for _, pt := range tt.PreTokenizer.PreTokenizers {
			switch pt.Type {
			case "Split":
				if pt.Pattern.Regex != "" {
Michael Yang's avatar
Michael Yang committed
89
90
					// create a checksum of all Split pretokenizers which should be sufficient
					// to identify the pretokenizer
Michael Yang's avatar
Michael Yang committed
91
92
93
94
95
96
97
98
99
100
101
102
					sha256sum.Write([]byte(pt.Pattern.Regex))
				}
			}
		}

		switch digest := hex.EncodeToString(sha256sum.Sum(nil)); digest {
		case "d98f9631be1e9607a9848c26c1f9eac1aa9fc21ac6ba82a2fc0741af9780a48f":
			t.Pre = "llama-bpe"
		case "03df5c5863ad70781dcfdef491ead25140f895fe8010964be0daefe27be32b02":
			t.Pre = "deepseek-llm"
		case "21cde974d587f0d54dc8d56b183cc1e6239600172035c68fbd6d4b9f8da0576e":
			t.Pre = "deepseek-coder"
103
104
		case "1ff7f41064896984db5d1bb6ff64fa4bc29007d08c1b439e505b7392777a319e":
			t.Pre = "qwen2"
Michael Yang's avatar
Michael Yang committed
105
106
107
108
109
110
111
		case "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855":
			// noop, empty pretokenizer
		default:
			slog.Warn("unknown pretokenizer, using default", "digest", digest)
		}
	}

112
	if f, err := fsys.Open("tokenizer_config.json"); errors.Is(err, os.ErrNotExist) {
113
		// noop
Michael Yang's avatar
Michael Yang committed
114
115
116
117
118
119
120
121
122
123
124
	} else if err != nil {
		return nil, err
	} else {
		defer f.Close()

		var p map[string]json.RawMessage
		if err := json.NewDecoder(f).Decode(&p); err != nil {
			return nil, err
		}

		if template, ok := p["chat_template"]; ok {
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
			var s []struct {
				Name     string `json:"name"`
				Template string `json:"template"`
			}
			if err := json.Unmarshal(template, &t.Template); err == nil {
				// noop
			} else if err := json.Unmarshal(template, &s); err == nil {
				for _, e := range s {
					if e.Name == "default" {
						t.Template = e.Template
						break
					}
				}
			} else {
				return nil, fmt.Errorf("invalid chat_template: %w", err)
Michael Yang's avatar
Michael Yang committed
140
141
142
			}
		}

Michael Yang's avatar
Michael Yang committed
143
		for _, st := range specialTokenTypes {
Michael Yang's avatar
Michael Yang committed
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
			sv := SpecialVocabulary{Type: st}
			if bts, ok := p[fmt.Sprintf("add_%s_token", st)]; ok {
				if err := json.Unmarshal(bts, &sv.AddToken); err != nil {
					return nil, err
				}
			}

			if bts, ok := p[fmt.Sprintf("%s_token", st)]; ok {
				var content string
				if err := json.Unmarshal(bts, &content); err != nil {
					var mm map[string]any
					if err := json.Unmarshal(bts, &mm); err != nil {
						continue
					}

					content, ok = mm["content"].(string)
					if !ok {
						continue
					}
				}

				sv.Content = content
			}

			if id, ok := addedTokens[sv.Content]; ok {
				sv.ID = id.ID
				t.SpecialVocabulary = append(t.SpecialVocabulary, &sv)
			}
		}
	}

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
	if f, err := fsys.Open("generation_config.json"); errors.Is(err, os.ErrNotExist) {
	} else if err != nil {
		return nil, err
	} else {
		defer f.Close()

		var p map[string]json.RawMessage
		if err := json.NewDecoder(f).Decode(&p); err != nil {
			return nil, err
		}

		for _, st := range specialTokenTypes {
			if bts, ok := p[fmt.Sprintf("%s_token_id", st)]; ok {
				var ids []int32
				if err := json.Unmarshal(bts, &ids); err != nil {
					// value is not a list so the existing ID is used
					continue
				}

				if i := slices.IndexFunc(t.SpecialVocabulary, func(sv *SpecialVocabulary) bool {
					return sv.Type == st
				}); i >= 0 {
					t.SpecialVocabulary[i].IDs = ids
				}
			}
		}
	}

Michael Yang's avatar
Michael Yang committed
203
204
205
206
207
208
	return t, nil
}

type tokenizer struct {
	AddedTokens []token `json:"added_tokens"`
	Model       struct {
Michael Yang's avatar
Michael Yang committed
209
210
211
		Type   string          `json:"type"`
		Vocab  map[string]int  `json:"vocab"`
		Merges json.RawMessage `json:"merges"`
Michael Yang's avatar
Michael Yang committed
212
	} `json:"model"`
Michael Yang's avatar
Michael Yang committed
213
214

	PreTokenizer struct {
215
		PreTokenizers []struct {
Michael Yang's avatar
Michael Yang committed
216
217
218
219
220
221
			Type    string `json:"type"`
			Pattern struct {
				Regex string `json:"Regex"`
			} `json:"pattern"`
		} `json:"pretokenizers"`
	} `json:"pre_tokenizer"`
Patrick Devine's avatar
Patrick Devine committed
222
223
}

Michael Yang's avatar
Michael Yang committed
224
type token struct {
Patrick Devine's avatar
Patrick Devine committed
225
226
227
228
229
230
	ID          int    `json:"id"`
	Content     string `json:"content"`
	Special     bool   `json:"special"`
	UserDefined bool
}

Michael Yang's avatar
Michael Yang committed
231
232
233
234
235
type Vocabulary struct {
	Model  string
	Tokens []string
	Scores []float32
	Types  []int32
Michael Yang's avatar
Michael Yang committed
236
}
Patrick Devine's avatar
Patrick Devine committed
237

238
239
func parseVocabularyFromTokenizer(fsys fs.FS) (*Vocabulary, error) {
	f, err := fsys.Open("tokenizer.json")
Patrick Devine's avatar
Patrick Devine committed
240
	if err != nil {
Michael Yang's avatar
Michael Yang committed
241
		return nil, err
Patrick Devine's avatar
Patrick Devine committed
242
243
244
	}
	defer f.Close()

Michael Yang's avatar
Michael Yang committed
245
	var t tokenizer
Michael Yang's avatar
Michael Yang committed
246
	if err := json.NewDecoder(f).Decode(&t); err != nil {
Michael Yang's avatar
Michael Yang committed
247
		return nil, err
Patrick Devine's avatar
Patrick Devine committed
248
249
	}

Michael Yang's avatar
bert  
Michael Yang committed
250
	tokens := make(map[int]token, len(t.Model.Vocab))
Michael Yang's avatar
Michael Yang committed
251
	for k, v := range t.Model.Vocab {
Michael Yang's avatar
bert  
Michael Yang committed
252
		tokens[v] = token{
Michael Yang's avatar
Michael Yang committed
253
254
			ID:      v,
			Content: k,
Michael Yang's avatar
bert  
Michael Yang committed
255
		}
Patrick Devine's avatar
Patrick Devine committed
256
257
	}

Michael Yang's avatar
bert  
Michael Yang committed
258
259
260
	for _, token := range t.AddedTokens {
		token.UserDefined = true
		tokens[token.ID] = token
Michael Yang's avatar
Michael Yang committed
261
	}
Patrick Devine's avatar
Patrick Devine committed
262

Michael Yang's avatar
bert  
Michael Yang committed
263
264
	keys := maps.Keys(tokens)
	slices.Sort(keys)
Michael Yang's avatar
Michael Yang committed
265
266

	v := Vocabulary{Model: "gpt2"}
Michael Yang's avatar
bert  
Michael Yang committed
267
268
269
270
	for _, k := range keys {
		token := tokens[k]
		v.Tokens = append(v.Tokens, token.Content)
		v.Scores = append(v.Scores, float32(token.ID))
Michael Yang's avatar
Michael Yang committed
271
272

		switch {
Michael Yang's avatar
bert  
Michael Yang committed
273
		case token.Special:
Michael Yang's avatar
Michael Yang committed
274
			v.Types = append(v.Types, tokenTypeControl)
Michael Yang's avatar
bert  
Michael Yang committed
275
		case token.UserDefined:
Michael Yang's avatar
Michael Yang committed
276
277
278
			v.Types = append(v.Types, tokenTypeUserDefined)
		default:
			v.Types = append(v.Types, tokenTypeNormal)
Michael Yang's avatar
Michael Yang committed
279
		}
Patrick Devine's avatar
Patrick Devine committed
280
281
	}

Michael Yang's avatar
Michael Yang committed
282
283
284
	return &v, nil
}

285
func parseVocabulary(fsys fs.FS) (*Vocabulary, error) {
Michael Yang's avatar
Michael Yang committed
286
287
288
289
290
291
	patterns := []struct {
		Pattern string
		Func    func(fs.FS) (*Vocabulary, error)
	}{
		{"tokenizer.model", parseSentencePiece},
		{"tokenizer.json", parseVocabularyFromTokenizer},
Michael Yang's avatar
Michael Yang committed
292
293
	}

Michael Yang's avatar
Michael Yang committed
294
295
	for _, pattern := range patterns {
		if _, err := fs.Stat(fsys, pattern.Pattern); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
296
297
			continue
		} else if err != nil {
Michael Yang's avatar
Michael Yang committed
298
299
300
			return nil, err
		}

Michael Yang's avatar
Michael Yang committed
301
		return pattern.Func(fsys)
Michael Yang's avatar
Michael Yang committed
302
303
	}

Michael Yang's avatar
Michael Yang committed
304
	return nil, errors.New("unknown tokenizer format")
Michael Yang's avatar
Michael Yang committed
305
306
307
308
309
310
311
}

type SpecialVocabulary struct {
	Type     string
	ID       int
	Content  string
	AddToken bool
312
313
314

	// IDs is populated by generation_config.json
	IDs []int32
Michael Yang's avatar
Michael Yang committed
315
316
317
318
319
320
321
322
323
324
325
326
327
}

func (sv SpecialVocabulary) Key() string {
	switch t := sv.Type; t {
	case "bos", "eos", "cls", "mask":
		return t
	case "unk":
		return "unknown"
	case "sep":
		//nolint:misspell // this is an upstream typo
		return "seperator"
	case "pad":
		return "padding"
Patrick Devine's avatar
Patrick Devine committed
328
329
	}

Michael Yang's avatar
Michael Yang committed
330
	panic("unknown special vocabulary type")
Patrick Devine's avatar
Patrick Devine committed
331
}