tokenizer_spm.go 3.74 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
52
53
54
55

			// temporary fix to handle gemma3 broken configs
			if slices.Contains([]string{"<end_of_turn>", "<start_of_turn>"}, piece.GetPiece()) {
				tt = int32(sentencepiece.ModelProto_SentencePiece_CONTROL)
			}

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

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

67
	f, err := fsys.Open("added_tokens.json")
Michael Yang's avatar
Michael Yang committed
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
	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
94
95
96
97
98
99
100
101
102
103
	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
104
105
106
107
108
109
110
111
112
		}

		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
113

Patrick Devine's avatar
Patrick Devine committed
114
115
116
117
118
119
120
121
122
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
123
124
125
126
127
128
129
130
131
	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
132
		AdditionalSpecialTokens any `json:"additional_special_tokens"`
Michael Yang's avatar
Michael Yang committed
133
134
135
136
137
138
	}

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

Patrick Devine's avatar
Patrick Devine committed
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
	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
171
}