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

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

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

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

	Pre      string
	Template string
}

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

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

	addedTokens := make(map[string]token)
47
	if f, err := fsys.Open("tokenizer.json"); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
	} 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
		}

		t.Merges = tt.Model.Merges

		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
69
70
					// create a checksum of all Split pretokenizers which should be sufficient
					// to identify the pretokenizer
Michael Yang's avatar
Michael Yang committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
					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"
		case "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855":
			// noop, empty pretokenizer
		default:
			slog.Warn("unknown pretokenizer, using default", "digest", digest)
		}
	}

90
	if f, err := fsys.Open("tokenizer_config.json"); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
	} 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 {
			if err := json.Unmarshal(template, &t.Template); err != nil {
				return nil, err
			}
		}

Michael Yang's avatar
Michael Yang committed
107
		for _, st := range specialTokenTypes {
Michael Yang's avatar
Michael Yang committed
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
			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)
			}
		}
	}

	return t, nil
}

type tokenizer struct {
	Version     string  `json:"version"`
	AddedTokens []token `json:"added_tokens"`
	Model       struct {
		Type   string         `json:"type"`
		Vocab  map[string]int `json:"vocab"`
		Merges []string       `json:"merges"`
	} `json:"model"`
Michael Yang's avatar
Michael Yang committed
150
151

	PreTokenizer struct {
152
		PreTokenizers []struct {
Michael Yang's avatar
Michael Yang committed
153
154
155
156
157
158
			Type    string `json:"type"`
			Pattern struct {
				Regex string `json:"Regex"`
			} `json:"pattern"`
		} `json:"pretokenizers"`
	} `json:"pre_tokenizer"`
Patrick Devine's avatar
Patrick Devine committed
159
160
}

Michael Yang's avatar
Michael Yang committed
161
type token struct {
Patrick Devine's avatar
Patrick Devine committed
162
163
164
165
166
167
	ID          int    `json:"id"`
	Content     string `json:"content"`
	Special     bool   `json:"special"`
	UserDefined bool
}

Michael Yang's avatar
Michael Yang committed
168
169
170
171
172
type Vocabulary struct {
	Model  string
	Tokens []string
	Scores []float32
	Types  []int32
Michael Yang's avatar
Michael Yang committed
173
}
Patrick Devine's avatar
Patrick Devine committed
174

175
176
func parseVocabularyFromTokenizer(fsys fs.FS) (*Vocabulary, error) {
	f, err := fsys.Open("tokenizer.json")
Patrick Devine's avatar
Patrick Devine committed
177
	if err != nil {
Michael Yang's avatar
Michael Yang committed
178
		return nil, err
Patrick Devine's avatar
Patrick Devine committed
179
180
181
	}
	defer f.Close()

Michael Yang's avatar
Michael Yang committed
182
	var t tokenizer
Michael Yang's avatar
Michael Yang committed
183
	if err := json.NewDecoder(f).Decode(&t); err != nil {
Michael Yang's avatar
Michael Yang committed
184
		return nil, err
Patrick Devine's avatar
Patrick Devine committed
185
186
	}

Michael Yang's avatar
Michael Yang committed
187
	var tokens []token
Michael Yang's avatar
Michael Yang committed
188
	for k, v := range t.Model.Vocab {
Michael Yang's avatar
Michael Yang committed
189
190
191
192
		tokens = append(tokens, token{
			ID:      v,
			Content: k,
		})
Patrick Devine's avatar
Patrick Devine committed
193
194
	}

Michael Yang's avatar
Michael Yang committed
195
196
197
	for _, t := range t.AddedTokens {
		t.UserDefined = true
		tokens = append(tokens, t)
Michael Yang's avatar
Michael Yang committed
198
	}
Patrick Devine's avatar
Patrick Devine committed
199

Michael Yang's avatar
Michael Yang committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
	slices.SortFunc(tokens, func(i, j token) int {
		return cmp.Compare(i.ID, j.ID)
	})

	v := Vocabulary{Model: "gpt2"}
	for _, t := range tokens {
		v.Tokens = append(v.Tokens, t.Content)
		v.Scores = append(v.Scores, float32(t.ID))

		switch {
		case t.Special:
			v.Types = append(v.Types, tokenTypeControl)
		case t.UserDefined:
			v.Types = append(v.Types, tokenTypeUserDefined)
		default:
			v.Types = append(v.Types, tokenTypeNormal)
Michael Yang's avatar
Michael Yang committed
216
		}
Patrick Devine's avatar
Patrick Devine committed
217
218
	}

Michael Yang's avatar
Michael Yang committed
219
220
221
	return &v, nil
}

222
223
func parseVocabulary(fsys fs.FS) (*Vocabulary, error) {
	patterns := map[string]func(fs.FS) (*Vocabulary, error){
Michael Yang's avatar
Michael Yang committed
224
225
226
227
228
		"tokenizer.model": parseSentencePiece,
		"tokenizer.json":  parseVocabularyFromTokenizer,
	}

	for pattern, parseFn := range patterns {
229
		if _, err := fs.Stat(fsys, pattern); errors.Is(err, os.ErrNotExist) {
Michael Yang's avatar
Michael Yang committed
230
231
			continue
		} else if err != nil {
Michael Yang's avatar
Michael Yang committed
232
233
234
			return nil, err
		}

235
		return parseFn(fsys)
Michael Yang's avatar
Michael Yang committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
	}

	return nil, errors.New("unknown tensor format")
}

type SpecialVocabulary struct {
	Type     string
	ID       int
	Content  string
	AddToken bool
}

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
259
260
	}

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