tokenizer.go 5.38 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
10
	"fmt"
	"log/slog"
Patrick Devine's avatar
Patrick Devine committed
11
	"os"
Michael Yang's avatar
Michael Yang committed
12
	"path/filepath"
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
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
	*Vocabulary
	SpecialVocabulary []*SpecialVocabulary
	Merges            []string

	Pre      string
	Template string
}

func parseTokenizer(d string, specialTypes []string) (*Tokenizer, error) {
	v, err := parseVocabulary(d)
	if err != nil {
		return nil, err
	}

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

	addedTokens := make(map[string]token)
	if f, err := os.Open(filepath.Join(d, "tokenizer.json")); errors.Is(err, os.ErrNotExist) {
	} 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 != "" {
					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)
		}
	}

	if f, err := os.Open(filepath.Join(d, "tokenizer_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
		}

		if template, ok := p["chat_template"]; ok {
			if err := json.Unmarshal(template, &t.Template); err != nil {
				return nil, err
			}
		}

		for _, st := range specialTypes {
			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
148
149

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

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

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

Michael Yang's avatar
Michael Yang committed
173
174
func parseVocabularyFromTokenizer(p string) (*Vocabulary, error) {
	f, err := os.Open(filepath.Join(p, "tokenizer.json"))
Patrick Devine's avatar
Patrick Devine committed
175
	if err != nil {
Michael Yang's avatar
Michael Yang committed
176
		return nil, err
Patrick Devine's avatar
Patrick Devine committed
177
178
179
	}
	defer f.Close()

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

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

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

Michael Yang's avatar
Michael Yang committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
	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
214
		}
Patrick Devine's avatar
Patrick Devine committed
215
216
	}

Michael Yang's avatar
Michael Yang committed
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
	return &v, nil
}

func parseVocabulary(d string) (*Vocabulary, error) {
	patterns := map[string]func(string) (*Vocabulary, error){
		"tokenizer.model": parseSentencePiece,
		"tokenizer.json":  parseVocabularyFromTokenizer,
	}

	for pattern, parseFn := range patterns {
		matches, err := filepath.Glob(filepath.Join(d, pattern))
		if err != nil {
			return nil, err
		}

		if len(matches) > 0 {
			return parseFn(d)
		}
	}

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

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