tokenizer_spm.go 4.01 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
6
7
package convert

import (
	"cmp"
	"encoding/json"
	"errors"
	"fmt"
8
	"io/fs"
Patrick Devine's avatar
Patrick Devine committed
9
	"log/slog"
Michael Yang's avatar
Michael Yang committed
10
	"os"
Patrick Devine's avatar
Patrick Devine committed
11
	"reflect"
Michael Yang's avatar
Michael Yang committed
12
13
14
15
16
17
18
	"slices"

	"google.golang.org/protobuf/proto"

	"github.com/ollama/ollama/convert/sentencepiece"
)

19
func parseSentencePiece(fsys fs.FS) (*Vocabulary, error) {
Patrick Devine's avatar
Patrick Devine committed
20
21
	slog.Debug("using spm vocabulary")

Michael Yang's avatar
Michael Yang committed
22
23
24
25
26
	ast, err := parseAdditionalSpecialTokens(fsys)
	if err != nil {
		return nil, err
	}

27
	bts, err := fs.ReadFile(fsys, "tokenizer.model")
Michael Yang's avatar
Michael Yang committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
	if err != nil {
		return nil, err
	}

	var spm sentencepiece.ModelProto
	if err := proto.Unmarshal(bts, &spm); err != nil {
		return nil, err
	}

	v := Vocabulary{Model: "llama"}
	for _, piece := range spm.GetPieces() {
		v.Tokens = append(v.Tokens, piece.GetPiece())
		v.Scores = append(v.Scores, piece.GetScore())

		switch t := piece.GetType(); t {
		case sentencepiece.ModelProto_SentencePiece_UNKNOWN,
			sentencepiece.ModelProto_SentencePiece_CONTROL,
			sentencepiece.ModelProto_SentencePiece_UNUSED,
			sentencepiece.ModelProto_SentencePiece_BYTE:
			v.Types = append(v.Types, int32(t))
		default:
Michael Yang's avatar
Michael Yang committed
49
			tt := int32(sentencepiece.ModelProto_SentencePiece_NORMAL)
50
51

			// temporary fix to handle gemma3 broken configs
52
53
			// TODO(parthsareen): allow reading of tokenizer.json to allow managing special tokens when using spm
			if slices.Contains([]string{"<end_of_turn>", "<start_of_turn>", "<start_function_declaration>", "<end_function_declaration>", "<start_function_call>", "<end_function_call>", "<start_function_response>", "<end_function_response>", "<escape>"}, piece.GetPiece()) {
54
55
56
				tt = int32(sentencepiece.ModelProto_SentencePiece_CONTROL)
			}

Patrick Devine's avatar
Patrick Devine committed
57
58
59
60
61
			for _, t := range ast {
				if t.Content == piece.GetPiece() {
					tt = int32(sentencepiece.ModelProto_SentencePiece_CONTROL)
					break
				}
Michael Yang's avatar
Michael Yang committed
62
63
64
			}

			v.Types = append(v.Types, tt)
Michael Yang's avatar
Michael Yang committed
65
66
67
		}
	}

68
	f, err := fsys.Open("added_tokens.json")
Michael Yang's avatar
Michael Yang committed
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
	if errors.Is(err, os.ErrNotExist) {
		return &v, nil
	} else if err != nil {
		return nil, err
	}
	defer f.Close()

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

	type t struct {
		id      int
		content string
	}

	var ts []t
	for content, id := range atm {
		ts = append(ts, t{id, content})
	}

	slices.SortFunc(ts, func(i, j t) int {
		return cmp.Compare(i.id, j.id)
	})

Patrick Devine's avatar
Patrick Devine committed
95
96
97
98
99
100
101
102
103
104
	for _, t := range ts {
		if t.id < len(v.Tokens) {
			if v.Tokens[t.id] == t.content {
				slog.Warn("tokenizer", "duplicate token", t.content, "id", t.id)
				continue
			}
			return nil, fmt.Errorf("token mismatch: %s != %s at pos [%d]", t.content, v.Tokens[t.id], t.id)
		}
		if t.id != len(v.Tokens) {
			return nil, fmt.Errorf("invalid token id: [%d] as pos [%d]", t.id, len(v.Tokens))
Michael Yang's avatar
Michael Yang committed
105
106
107
108
109
110
111
112
113
		}

		v.Tokens = append(v.Tokens, t.content)
		v.Scores = append(v.Scores, -1000.0)
		v.Types = append(v.Types, tokenTypeUserDefined)
	}

	return &v, nil
}
Michael Yang's avatar
Michael Yang committed
114

Patrick Devine's avatar
Patrick Devine committed
115
116
117
118
119
120
121
122
123
type specialToken struct {
	Content    string `json:"content"`
	Lstrip     bool   `json:"lstrip"`
	Normalized bool   `json:"normalized"`
	Rstrip     bool   `json:"rstrip"`
	SingleWord bool   `json:"single_word"`
}

func parseAdditionalSpecialTokens(fsys fs.FS) ([]specialToken, error) {
Michael Yang's avatar
Michael Yang committed
124
125
126
127
128
129
130
131
132
	f, err := fsys.Open("special_tokens_map.json")
	if errors.Is(err, os.ErrNotExist) {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	defer f.Close()

	var m struct {
Patrick Devine's avatar
Patrick Devine committed
133
		AdditionalSpecialTokens any `json:"additional_special_tokens"`
Michael Yang's avatar
Michael Yang committed
134
135
136
137
138
139
	}

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

Patrick Devine's avatar
Patrick Devine committed
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
	var ast []specialToken

	switch st := m.AdditionalSpecialTokens.(type) {
	case []string:
		for _, s := range st {
			ast = append(ast, specialToken{Content: s})
		}
	case []any:
		for _, s := range st {
			// marshal and unmarshal the object to get the special token
			tMap := s.(map[string]any)
			data, err := json.Marshal(tMap)
			if err != nil {
				return nil, err
			}

			var token specialToken
			err = json.Unmarshal(data, &token)
			if err != nil {
				return nil, err
			}

			ast = append(ast, token)
		}

	default:
		slog.Warn("special token", "unknown token", reflect.TypeOf(st))
	}

	slog.Debug("spm tokenizer", "additional tokens", ast)

	return ast, nil
Michael Yang's avatar
Michael Yang committed
172
}