process_text_spm.go 6.15 KB
Newer Older
Patrick Devine's avatar
Patrick Devine committed
1
2
3
package model

import (
4
5
	"container/heap"
	"fmt"
Patrick Devine's avatar
Patrick Devine committed
6
	"log/slog"
7
	"strconv"
Patrick Devine's avatar
Patrick Devine committed
8
9
10
11
12
13
14
15
16
17
	"strings"
)

const spmWhitespaceSep = "▁"

type SentencePieceModel struct {
	maxTokenLen int
	vocab       *Vocabulary
}

Michael Yang's avatar
Michael Yang committed
18
19
var _ TextProcessor = (*SentencePieceModel)(nil)

20
21
22
23
func (spm SentencePieceModel) Vocabulary() *Vocabulary {
	return spm.vocab
}

24
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel {
Patrick Devine's avatar
Patrick Devine committed
25
26
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
	slog.Debug("Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5])

	counter := map[int]int{}
	var maxTokenLen int
	for cnt := range vocab.Types {
		switch vocab.Types[cnt] {
		case TOKEN_TYPE_NORMAL, TOKEN_TYPE_USER_DEFINED, TOKEN_TYPE_UNUSED:
			maxTokenLen = max(maxTokenLen, len(vocab.Values[cnt]))
			fallthrough
		default:
			counter[int(vocab.Types[cnt])] += 1
		}
	}

	slog.Debug("Token counts", "normal", counter[TOKEN_TYPE_NORMAL], "unknown", counter[TOKEN_TYPE_UNKNOWN], "control", counter[TOKEN_TYPE_CONTROL],
		"user defined", counter[TOKEN_TYPE_USER_DEFINED], "unused", counter[TOKEN_TYPE_UNUSED], "byte", counter[TOKEN_TYPE_BYTE],
		"max token len", maxTokenLen)

	return SentencePieceModel{
		maxTokenLen: maxTokenLen,
		vocab:       vocab,
	}
}

func (spm SentencePieceModel) Is(id int32, special Special) bool {
	return spm.vocab.Is(id, special)
}

Michael Yang's avatar
Michael Yang committed
53
func (spm SentencePieceModel) Encode(s string, addSpecial bool) ([]int32, error) {
Patrick Devine's avatar
Patrick Devine committed
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
	fragments := []fragment{{value: s}}
	for _, special := range spm.vocab.SpecialVocabulary() {
		id := spm.vocab.Encode(special)
		for i := 0; i < len(fragments); i++ {
			frag := fragments[i]
			if len(frag.ids) > 0 {
				continue
			}

			var middle []fragment
			switch i := strings.Index(frag.value, special); {
			case i < 0:
				middle = append(middle, frag)
			case i > 0:
				middle = append(middle, fragment{value: frag.value[:i]})
				fallthrough
			default:
				middle = append(middle, fragment{value: special, ids: []int32{id}})
				if rest := frag.value[i+len(special):]; rest != "" {
					middle = append(middle, fragment{value: rest})
				}
			}

			fragments = append(fragments[:i], append(middle, fragments[i+1:]...)...)
		}
	}

	var ids []int32
	for _, frag := range fragments {
		if len(frag.ids) > 0 {
			ids = append(ids, frag.ids...)
			continue
		}

88
		text := strings.ReplaceAll(frag.value, " ", spmWhitespaceSep)
Patrick Devine's avatar
Patrick Devine committed
89

90
91
92
93
		if id := spm.vocab.Encode(text); id >= 0 {
			ids = append(ids, id)
			continue
		}
Patrick Devine's avatar
Patrick Devine committed
94

95
96
		q := &queue{}
		heap.Init(q)
Patrick Devine's avatar
Patrick Devine committed
97

98
99
100
101
102
103
104
105
106
		runes := []rune(text)
		merges := make([]merge, len(runes))
		for r := range runes {
			merges[r] = merge{
				p:     r - 1,
				n:     r + 1,
				runes: []rune{runes[r]},
			}
		}
Patrick Devine's avatar
Patrick Devine committed
107

108
109
		pairwise := func(a, b int) *candidate {
			if a < 0 || b >= len(runes) {
Patrick Devine's avatar
Patrick Devine committed
110
111
112
				return nil
			}

113
114
115
116
117
118
119
			left, right := string(merges[a].runes), string(merges[b].runes)
			if id := spm.vocab.Encode(left + right); id >= 0 {
				return &candidate{
					a:     a,
					b:     b,
					score: spm.vocab.Scores[id],
					size:  len(left) + len(right),
Patrick Devine's avatar
Patrick Devine committed
120
121
122
				}
			}

123
124
125
126
127
128
			return nil
		}

		for i := range len(runes) - 1 {
			if pair := pairwise(i, i+1); pair != nil {
				heap.Push(q, pair)
Patrick Devine's avatar
Patrick Devine committed
129
			}
130
		}
Patrick Devine's avatar
Patrick Devine committed
131

132
133
134
		for q.Len() > 0 {
			pair := heap.Pop(q).(*candidate)
			left, right := merges[pair.a], merges[pair.b]
Patrick Devine's avatar
Patrick Devine committed
135

136
137
138
			if string(left.runes) == "" || string(right.runes) == "" || len(string(left.runes))+len(string(right.runes)) != pair.size {
				continue
			}
139

140
141
142
143
144
145
			merges[pair.a].runes = append(left.runes, right.runes...)
			merges[pair.b].runes = nil
			merges[pair.a].n = right.n
			if right.n < len(merges) {
				merges[right.n].p = pair.a
			}
Patrick Devine's avatar
Patrick Devine committed
146

147
148
149
			if pair := pairwise(merges[pair.a].p, pair.a); pair != nil {
				heap.Push(q, pair)
			}
Patrick Devine's avatar
Patrick Devine committed
150

151
152
			if pair := pairwise(pair.a, merges[pair.a].n); pair != nil {
				heap.Push(q, pair)
Patrick Devine's avatar
Patrick Devine committed
153
			}
154
		}
Patrick Devine's avatar
Patrick Devine committed
155

156
157
158
		for _, merge := range merges {
			if token := string(merge.runes); token != "" {
				id := spm.vocab.Encode(token)
Patrick Devine's avatar
Patrick Devine committed
159

160
161
162
163
164
165
166
167
168
169
170
171
				if id >= 0 {
					ids = append(ids, id)
					continue
				}

				// Fallback to byte tokenization
				var result []int32
				for _, b := range []byte(token) {
					byteToken := fmt.Sprintf("<0x%02X>", b)
					unknownID := spm.vocab.Encode(byteToken)
					if unknownID >= 0 {
						result = append(result, unknownID)
Patrick Devine's avatar
Patrick Devine committed
172
					} else {
173
						slog.Debug("unknown byte token", "byte", b, "token", byteToken)
Patrick Devine's avatar
Patrick Devine committed
174
175
					}
				}
176
177

				ids = append(ids, result...)
Patrick Devine's avatar
Patrick Devine committed
178
179
180
			}
		}
	}
Michael Yang's avatar
Michael Yang committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

	if addSpecial && len(ids) > 0 {
		if spm.vocab.AddBOS {
			if ids[0] == spm.vocab.BOS {
				slog.Warn("adding bos token to prompt which already has it", "id", spm.vocab.BOS)
			}

			slog.Debug("adding bos token to prompt", "id", spm.vocab.BOS)
			ids = append([]int32{spm.vocab.BOS}, ids...)
		}

		if spm.vocab.AddEOS {
			if ids[len(ids)-1] == spm.vocab.EOS {
				slog.Warn("adding eos token to prompt which already has it", "id", spm.vocab.EOS)
			}

			slog.Debug("adding eos token to prompt", "id", spm.vocab.EOS)
			ids = append(ids, spm.vocab.EOS)
		}
	}
Patrick Devine's avatar
Patrick Devine committed
201
202
203
204
205
206
207

	return ids, nil
}

type candidate struct {
	a, b  int
	score float32
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
	size  int
}

type queue []*candidate

func (q queue) Len() int { return len(q) }

func (q queue) Less(i, j int) bool {
	return (q[i].score > q[j].score) || (q[i].score == q[j].score && q[i].a < q[j].a)
}

func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }

func (q *queue) Push(x interface{}) {
	item := x.(*candidate)
	*q = append(*q, item)
}

func (q *queue) Pop() interface{} {
	old := *q
	n := len(old)
	item := old[n-1]
	*q = old[0 : n-1]
	return item
Patrick Devine's avatar
Patrick Devine committed
232
233
234
235
236
237
238
}

func (spm SentencePieceModel) Decode(ids []int32) (string, error) {
	var sb strings.Builder
	for _, id := range ids {
		data := spm.vocab.Decode(id)
		data = strings.ReplaceAll(data, spmWhitespaceSep, " ")
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

		// For tokenizers that use byte tokens like "<0xEA>"
		// convert them to the partial unicode character
		// so they are buffered correctly by the runner instead
		// of being sent back to the api as "<0xEA>"
		if len(data) == 6 && strings.HasPrefix(data, "<0x") && strings.HasSuffix(data, ">") {
			byteVal, err := strconv.ParseUint(data[1:5], 0, 8)
			if err != nil {
				return "", fmt.Errorf("failed to parse hex byte: %v", err)
			}

			if err := sb.WriteByte(byte(byteVal)); err != nil {
				return "", err
			}
		} else {
			if _, err := sb.WriteString(data); err != nil {
				return "", err
			}
Patrick Devine's avatar
Patrick Devine committed
257
258
259
260
261
		}
	}

	return sb.String(), nil
}