| 1 |
// Copyright 2024 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package sentencepiece |
| 16 |
|
| 17 |
import ( |
| 18 |
"fmt" |
| 19 |
"io" |
| 20 |
"os" |
| 21 |
"strconv" |
| 22 |
"strings" |
| 23 |
"unicode/utf8" |
| 24 |
|
| 25 |
"cloud.google.com/go/vertexai/internal/sentencepiece/internal/model" |
| 26 |
"cloud.google.com/go/vertexai/internal/sentencepiece/internal/prefixmatcher" |
| 27 |
"cloud.google.com/go/vertexai/internal/sentencepiece/internal/priorityqueue" |
| 28 |
"google.golang.org/protobuf/proto" |
| 29 |
) |
| 30 |
|
| 31 |
const debugEncode = false |
| 32 |
|
| 33 |
// Processor represents a SentencePiece processor (tokenizer). |
| 34 |
// A Processor converts input text into a sequence of tokens LLMs use, and back. |
| 35 |
// The mapping between token IDs and the text they represent is read from the |
| 36 |
// model proto (provided to the constructor); it's the same between all calls |
| 37 |
// to the Encode method. |
| 38 |
// |
| 39 |
// The term "processor" comes from the original C++ SentencePiece library and |
| 40 |
// its Python bindings. |
| 41 |
type Processor struct { |
| 42 |
model *model.ModelProto |
| 43 |
|
| 44 |
pieces map[string]int |
| 45 |
reserved map[string]int |
| 46 |
|
| 47 |
// unknownID is the token identifier of the UNKNOWN piece |
| 48 |
unknownID int |
| 49 |
|
| 50 |
// userDefinedMatcher is a prefix matcher for symbols that are of |
| 51 |
// "user-defined" type in the model proto. |
| 52 |
userDefinedMatcher *prefixmatcher.PrefixMatcher |
| 53 |
|
| 54 |
// byte2Token is a cache of byte values and the tokens they represent |
| 55 |
byte2Token map[byte]Token |
| 56 |
|
| 57 |
// idToByte maps IDs to byte values they represent |
| 58 |
idToByte map[int]byte |
| 59 |
} |
| 60 |
|
| 61 |
// NewProcessorFromPath creates a new Processor from a file path to the protobuf |
| 62 |
// data. |
| 63 |
func NewProcessorFromPath(protoFile string) (*Processor, error) { |
| 64 |
f, err := os.Open(protoFile) |
| 65 |
if err != nil { |
| 66 |
return nil, fmt.Errorf("unable to read %q: %v", protoFile, err) |
| 67 |
} |
| 68 |
defer f.Close() |
| 69 |
return NewProcessor(f) |
| 70 |
} |
| 71 |
|
| 72 |
// NewProcessor creates a new Processor from a reader with the protobuf data. |
| 73 |
func NewProcessor(protoReader io.Reader) (*Processor, error) { |
| 74 |
b, err := io.ReadAll(protoReader) |
| 75 |
if err != nil { |
| 76 |
return nil, fmt.Errorf("unable to read protobuf data: %v", err) |
| 77 |
} |
| 78 |
|
| 79 |
var mp model.ModelProto |
| 80 |
err = proto.Unmarshal(b, &mp) |
| 81 |
if err != nil { |
| 82 |
return nil, fmt.Errorf("unable to unmarshal protobuf: %v", err) |
| 83 |
} |
| 84 |
|
| 85 |
tspec := mp.GetTrainerSpec() |
| 86 |
if tspec.GetModelType() != model.TrainerSpec_BPE { |
| 87 |
return nil, fmt.Errorf("model type %s not supported", tspec.GetModelType()) |
| 88 |
} |
| 89 |
|
| 90 |
nspec := mp.GetNormalizerSpec() |
| 91 |
if *nspec.AddDummyPrefix || *nspec.RemoveExtraWhitespaces { |
| 92 |
return nil, fmt.Errorf("normalizer spec options not supported: %s", nspec) |
| 93 |
} |
| 94 |
|
| 95 |
userDefined := make(map[string]bool) |
| 96 |
pieces := make(map[string]int) |
| 97 |
reserved := make(map[string]int) |
| 98 |
byte2Token := make(map[byte]Token) |
| 99 |
idToByte := make(map[int]byte) |
| 100 |
unkID := -1 |
| 101 |
|
| 102 |
for i, piece := range mp.GetPieces() { |
| 103 |
isNormalPiece := (piece.GetType() == model.ModelProto_SentencePiece_NORMAL || |
| 104 |
piece.GetType() == model.ModelProto_SentencePiece_USER_DEFINED || |
| 105 |
piece.GetType() == model.ModelProto_SentencePiece_UNUSED) |
| 106 |
|
| 107 |
if isNormalPiece { |
| 108 |
pieces[piece.GetPiece()] = i |
| 109 |
} else { |
| 110 |
reserved[piece.GetPiece()] = i |
| 111 |
} |
| 112 |
|
| 113 |
if piece.GetType() == model.ModelProto_SentencePiece_USER_DEFINED { |
| 114 |
userDefined[piece.GetPiece()] = true |
| 115 |
} else if piece.GetType() == model.ModelProto_SentencePiece_UNKNOWN { |
| 116 |
if unkID > 0 { |
| 117 |
return nil, fmt.Errorf("unk redefined") |
| 118 |
} |
| 119 |
unkID = i |
| 120 |
} else if piece.GetType() == model.ModelProto_SentencePiece_BYTE { |
| 121 |
if !tspec.GetByteFallback() { |
| 122 |
return nil, fmt.Errorf("byte piece %q is found although `byte_fallback=false`", piece.GetPiece()) |
| 123 |
} |
| 124 |
bv := convertHexValue(piece.GetPiece()) |
| 125 |
if bv >= 0 && bv < 256 { |
| 126 |
byte2Token[byte(bv)] = Token{ID: i, Text: piece.GetPiece()} |
| 127 |
idToByte[i] = byte(bv) |
| 128 |
} |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
if unkID < 0 { |
| 133 |
return nil, fmt.Errorf("unk symbol is not defined") |
| 134 |
} |
| 135 |
|
| 136 |
// In case byte_fallback is specified, make sure that all 256 possible byte |
| 137 |
// values were found. |
| 138 |
if tspec.GetByteFallback() { |
| 139 |
for i := 0; i < 256; i++ { |
| 140 |
if _, found := byte2Token[byte(i)]; !found { |
| 141 |
return nil, fmt.Errorf("byte value 0x%02X not found", i) |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
return &Processor{ |
| 147 |
model: &mp, |
| 148 |
userDefinedMatcher: prefixmatcher.NewFromSet(userDefined), |
| 149 |
byte2Token: byte2Token, |
| 150 |
idToByte: idToByte, |
| 151 |
unknownID: unkID, |
| 152 |
pieces: pieces, |
| 153 |
reserved: reserved, |
| 154 |
}, nil |
| 155 |
} |
| 156 |
|
| 157 |
// Encode tokenizes the input text and returns a list of Tokens. |
| 158 |
func (proc *Processor) Encode(text string) []Token { |
| 159 |
text = normalize(text) |
| 160 |
|
| 161 |
// We begin by having each symbol a single Unicode character (or a |
| 162 |
// user-defined string), and will iteratively merge them into larger and |
| 163 |
// larger symbols until we have the final list of tokens. |
| 164 |
// Since this list of symbols changes a lot, we represent it as a |
| 165 |
// doubly-linked list in the symList slice. Each element in this slice has |
| 166 |
// prev/next links to the next "live" symbol in the list; noMerge means this |
| 167 |
// is a user-defined symbol we're not allowed to merge with neighbors. |
| 168 |
// After the algorithm is finished, many elements in symList will be "dead" |
| 169 |
// (unreachable by next/prev links from the first element). |
| 170 |
// This representation is inspired by the implementation of bpe::Model |
| 171 |
// in the SentencePiece C++ library. |
| 172 |
|
| 173 |
type symListElem struct { |
| 174 |
prev, next int |
| 175 |
noMerge bool |
| 176 |
symbol string |
| 177 |
} |
| 178 |
symList := make([]symListElem, 0, len(text)) |
| 179 |
|
| 180 |
for { |
| 181 |
// Match the next symbol in text |
| 182 |
slen, found := proc.symbolMatch(text) |
| 183 |
|
| 184 |
// Append a list element for this symbol; note that this element will be |
| 185 |
// at index len(symList), so prev/next are set up accordingly. |
| 186 |
sym := symListElem{ |
| 187 |
noMerge: found, |
| 188 |
symbol: text[:slen], |
| 189 |
prev: len(symList) - 1, |
| 190 |
next: len(symList) + 1, |
| 191 |
} |
| 192 |
symList = append(symList, sym) |
| 193 |
|
| 194 |
// Advance the text slice to the next symbol; if no more text, we're done. |
| 195 |
text = text[slen:] |
| 196 |
if len(text) == 0 { |
| 197 |
break |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
if len(symList) == 0 { |
| 202 |
return nil |
| 203 |
} |
| 204 |
symList[len(symList)-1].next = -1 |
| 205 |
|
| 206 |
debugShowSymList := func(prefix string) { |
| 207 |
if debugEncode { |
| 208 |
fmt.Println(prefix) |
| 209 |
for i, elem := range symList { |
| 210 |
fmt.Printf("[%3d]: [prev: %3v, next: %3d, noMerge: %v] %q\n", i, elem.prev, elem.next, elem.noMerge, elem.symbol) |
| 211 |
} |
| 212 |
} |
| 213 |
} |
| 214 |
debugShowSymList("initial") |
| 215 |
|
| 216 |
// To avoid repeating work, we manage a priority queue of "merge candidates". |
| 217 |
// Each candidate has pointers to the symList list for the left and right |
| 218 |
// symbol in the pair, as well as the combined symbol's score. |
| 219 |
// The priority of merging is determined by this score, with position as |
| 220 |
// the tie-breaker (earlier pairs are preferred). |
| 221 |
type mergeCandidate struct { |
| 222 |
left, right int |
| 223 |
length int |
| 224 |
score float32 |
| 225 |
} |
| 226 |
|
| 227 |
mergeQueue := priorityqueue.New(func(a, b mergeCandidate) int { |
| 228 |
if a.score > b.score || (a.score == b.score && a.left < b.left) { |
| 229 |
return 1 |
| 230 |
} |
| 231 |
return -1 |
| 232 |
}) |
| 233 |
|
| 234 |
// suggestNewMergePair is called to potentially add a new mergeCandidate to |
| 235 |
// mergeQueue. The candidate is added if it's valid, both its parts are |
| 236 |
// allowed to merge, and it appears in the vocabulary. |
| 237 |
suggestNewMergePair := func(left, right int) { |
| 238 |
if left == -1 || right == -1 || symList[left].noMerge || symList[right].noMerge { |
| 239 |
return |
| 240 |
} |
| 241 |
|
| 242 |
mergedSymbol := symList[left].symbol + symList[right].symbol |
| 243 |
if id, found := proc.pieces[mergedSymbol]; found { |
| 244 |
mergeQueue.Insert(mergeCandidate{ |
| 245 |
left: left, |
| 246 |
right: right, |
| 247 |
length: len(mergedSymbol), |
| 248 |
score: proc.model.GetPieces()[id].GetScore(), |
| 249 |
}) |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
// Seed the merge queue with all pairs of symbols from symList |
| 254 |
for i := 1; i < len(symList); i++ { |
| 255 |
suggestNewMergePair(i-1, i) |
| 256 |
} |
| 257 |
|
| 258 |
// Main loop |
| 259 |
for mergeQueue.Len() > 0 { |
| 260 |
candidate := mergeQueue.PopMax() |
| 261 |
leftSymbol := symList[candidate.left] |
| 262 |
rightSymbol := symList[candidate.right] |
| 263 |
|
| 264 |
// Make sure this candidate is not out of date. If one of its parts was |
| 265 |
// already merged with another symbol, just skip this candidate. |
| 266 |
if len(leftSymbol.symbol) == 0 || |
| 267 |
len(rightSymbol.symbol) == 0 || |
| 268 |
len(leftSymbol.symbol)+len(rightSymbol.symbol) != candidate.length { |
| 269 |
continue |
| 270 |
} |
| 271 |
|
| 272 |
// Do the merge: |
| 273 |
// 1. Merge the concatenation of leftSymbol and rightSymbol into leftSymbol |
| 274 |
symList[candidate.left].symbol = leftSymbol.symbol + rightSymbol.symbol |
| 275 |
|
| 276 |
// 2. Update prev/next pointers |
| 277 |
symList[candidate.left].next = rightSymbol.next |
| 278 |
if rightSymbol.next >= 0 { |
| 279 |
symList[rightSymbol.next].prev = candidate.left |
| 280 |
} |
| 281 |
|
| 282 |
// 3. Mark the right element in the pair as outdated (it's been merged |
| 283 |
// into the left one). |
| 284 |
symList[candidate.right].symbol = "" |
| 285 |
|
| 286 |
// 4. Add merge suggestions for the newly merged symbol with its neighbors |
| 287 |
suggestNewMergePair(leftSymbol.prev, candidate.left) |
| 288 |
suggestNewMergePair(candidate.left, rightSymbol.next) |
| 289 |
} |
| 290 |
|
| 291 |
// Collect the final list of tokens from the remaining elements of symList. |
| 292 |
tokens := make([]Token, 0, len(symList)) |
| 293 |
for i := 0; i >= 0; i = symList[i].next { |
| 294 |
symbol := symList[i].symbol |
| 295 |
id := proc.symbolToID(symbol) |
| 296 |
|
| 297 |
if id == proc.unknownID && proc.model.GetTrainerSpec().GetByteFallback() { |
| 298 |
// Decompose this symbol into bytes, and report each byte as a separate |
| 299 |
// token. |
| 300 |
for i := 0; i < len(symbol); i++ { |
| 301 |
tokens = append(tokens, proc.byte2Token[symbol[i]]) |
| 302 |
} |
| 303 |
} else { |
| 304 |
tokens = append(tokens, Token{ID: id, Text: symbol}) |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
return tokens |
| 309 |
} |
| 310 |
|
| 311 |
// symbolMatch finds the length of the first symbol in text. A symbol is either |
| 312 |
// a user-defined symbol from the proto or a single rune. The second return |
| 313 |
// value is true iff a user-defined symbol was matched. |
| 314 |
func (proc *Processor) symbolMatch(text string) (int, bool) { |
| 315 |
prefixLen := proc.userDefinedMatcher.FindPrefixLen(text) |
| 316 |
if prefixLen > 0 { |
| 317 |
return prefixLen, true |
| 318 |
} |
| 319 |
// Not found a user-defined prefix; get the length of next rune. |
| 320 |
_, rlen := utf8.DecodeRuneInString(text) |
| 321 |
return rlen, false |
| 322 |
} |
| 323 |
|
| 324 |
// symbolToID finds the right ID for the given textual symbol, or returns |
| 325 |
// proc.unknownID if the symbol is unknown. |
| 326 |
func (proc *Processor) symbolToID(symbol string) int { |
| 327 |
if id, found := proc.reserved[symbol]; found { |
| 328 |
return id |
| 329 |
} |
| 330 |
if id, found := proc.pieces[symbol]; found { |
| 331 |
return id |
| 332 |
} |
| 333 |
return proc.unknownID |
| 334 |
} |
| 335 |
|
| 336 |
// convertHexValue converts strings of the form "<0xXY>" to the (unsigned) |
| 337 |
// integer value of the hexadecimal number XY. -1 is returned for bad input. |
| 338 |
func convertHexValue(bv string) int { |
| 339 |
bv = strings.TrimPrefix(bv, "<0x") |
| 340 |
bv = strings.TrimSuffix(bv, ">") |
| 341 |
n, err := strconv.ParseInt(bv, 16, 32) |
| 342 |
if err != nil { |
| 343 |
return -1 |
| 344 |
} |
| 345 |
return int(n) |
| 346 |
} |
| 347 |
|
| 348 |
// Decode translates a list of IDs produced by [Encode] back into the string |
| 349 |
// it represents. |
| 350 |
func (proc *Processor) Decode(ids []int) string { |
| 351 |
var sb strings.Builder |
| 352 |
|
| 353 |
for i := 0; i < len(ids); { |
| 354 |
// Find a run of IDs that represent single bytes starting at i. |
| 355 |
nextNonByte := i |
| 356 |
for nextNonByte < len(ids) && proc.isByteID(ids[nextNonByte]) { |
| 357 |
nextNonByte++ |
| 358 |
} |
| 359 |
numBytes := nextNonByte - i |
| 360 |
|
| 361 |
// Handle a run of numBytes IDs, by decoding them into utf8 runes. |
| 362 |
if numBytes > 0 { |
| 363 |
buf := make([]byte, 0, numBytes) |
| 364 |
for bi := i; bi < nextNonByte; bi++ { |
| 365 |
buf = append(buf, proc.idToByte[ids[bi]]) |
| 366 |
} |
| 367 |
|
| 368 |
for len(buf) > 0 { |
| 369 |
// DecodeRune returns utf8.RuneError ('\uFFFD') for bad UTF8 encodings, |
| 370 |
// and this is exactly what SentencePiece is supposed to emit for them. |
| 371 |
// So we don't do any special handling for UTF8 decode errors here. |
| 372 |
r, size := utf8.DecodeRune(buf) |
| 373 |
sb.WriteRune(r) |
| 374 |
buf = buf[size:] |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
if nextNonByte >= len(ids) { |
| 379 |
break |
| 380 |
} |
| 381 |
// Here nextNonByte is the index of an ID that's not a single byte. |
| 382 |
id := ids[nextNonByte] |
| 383 |
if proc.isControlID(id) { |
| 384 |
// Don't emit anything for control IDs |
| 385 |
} else if id == proc.unknownID { |
| 386 |
// Special "unk_surface" string for unknown IDs |
| 387 |
sb.WriteString(proc.model.GetTrainerSpec().GetUnkSurface()) |
| 388 |
} else { |
| 389 |
piece := proc.model.GetPieces()[id].GetPiece() |
| 390 |
sb.WriteString(replaceSeparatorsBySpace(piece)) |
| 391 |
} |
| 392 |
i = nextNonByte + 1 |
| 393 |
} |
| 394 |
|
| 395 |
return sb.String() |
| 396 |
} |
| 397 |
|
| 398 |
// DecodeTokens is a convenience wrapper around [Decode], accepting a list of |
| 399 |
// tokens as returned by [Encode]. It only uses the ID fields of tokens to |
| 400 |
// decode the text. |
| 401 |
func (proc *Processor) DecodeTokens(tokens []Token) string { |
| 402 |
ids := make([]int, len(tokens)) |
| 403 |
for i, t := range tokens { |
| 404 |
ids[i] = t.ID |
| 405 |
} |
| 406 |
return proc.Decode(ids) |
| 407 |
} |
| 408 |
|
| 409 |
// VocabularySize returns the vocabulary size from the proto model. |
| 410 |
func (proc *Processor) VocabularySize() int { |
| 411 |
return len(proc.model.GetPieces()) |
| 412 |
} |
| 413 |
|
| 414 |
func (proc *Processor) isByteID(id int) bool { |
| 415 |
return proc.model.GetPieces()[id].GetType() == model.ModelProto_SentencePiece_BYTE |
| 416 |
} |
| 417 |
|
| 418 |
func (proc *Processor) isControlID(id int) bool { |
| 419 |
return proc.model.GetPieces()[id].GetType() == model.ModelProto_SentencePiece_CONTROL |
| 420 |
} |