process_text_spm.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package model
  2. import (
  3. "iter"
  4. "log/slog"
  5. "strings"
  6. "github.com/dlclark/regexp2"
  7. queue "github.com/emirpasic/gods/v2/queues/priorityqueue"
  8. )
  9. const spmWhitespaceSep = "▁"
  10. func replaceWhitespaceBySeperator(s string) string {
  11. return strings.ReplaceAll(s, " ", spmWhitespaceSep)
  12. }
  13. type SentencePieceModel struct {
  14. maxTokenLen int
  15. pre *regexp2.Regexp
  16. vocab *Vocabulary
  17. }
  18. func NewSentencePieceModel(pre string, vocab *Vocabulary) SentencePieceModel {
  19. slog.Debug("Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5])
  20. counter := map[int]int{}
  21. var maxTokenLen int
  22. for cnt := range vocab.Types {
  23. switch vocab.Types[cnt] {
  24. case TOKEN_TYPE_NORMAL, TOKEN_TYPE_USER_DEFINED, TOKEN_TYPE_UNUSED:
  25. maxTokenLen = max(maxTokenLen, len(vocab.Values[cnt]))
  26. fallthrough
  27. default:
  28. counter[int(vocab.Types[cnt])] += 1
  29. }
  30. }
  31. slog.Debug("Token counts", "normal", counter[TOKEN_TYPE_NORMAL], "unknown", counter[TOKEN_TYPE_UNKNOWN], "control", counter[TOKEN_TYPE_CONTROL],
  32. "user defined", counter[TOKEN_TYPE_USER_DEFINED], "unused", counter[TOKEN_TYPE_UNUSED], "byte", counter[TOKEN_TYPE_BYTE],
  33. "max token len", maxTokenLen)
  34. return SentencePieceModel{
  35. maxTokenLen: maxTokenLen,
  36. pre: regexp2.MustCompile(pre, regexp2.Unicode|regexp2.RE2),
  37. vocab: vocab,
  38. }
  39. }
  40. func (spm SentencePieceModel) Is(id int32, special Special) bool {
  41. return spm.vocab.Is(id, special)
  42. }
  43. func (spm *SentencePieceModel) split(s string) iter.Seq[string] {
  44. return func(yield func(string) bool) {
  45. for m, _ := spm.pre.FindStringMatch(s); m != nil; m, _ = spm.pre.FindNextMatch(m) {
  46. if !yield(m.String()) {
  47. break
  48. }
  49. }
  50. }
  51. }
  52. func (spm SentencePieceModel) Encode(s string) ([]int32, error) {
  53. fragments := []fragment{{value: s}}
  54. for _, special := range spm.vocab.SpecialVocabulary() {
  55. // TODO: process special tokens concurrently
  56. id := spm.vocab.Encode(special)
  57. for i := 0; i < len(fragments); i++ {
  58. frag := fragments[i]
  59. if len(frag.ids) > 0 {
  60. continue
  61. }
  62. var middle []fragment
  63. switch i := strings.Index(frag.value, special); {
  64. case i < 0:
  65. middle = append(middle, frag)
  66. case i > 0:
  67. middle = append(middle, fragment{value: frag.value[:i]})
  68. fallthrough
  69. default:
  70. middle = append(middle, fragment{value: special, ids: []int32{id}})
  71. if rest := frag.value[i+len(special):]; rest != "" {
  72. middle = append(middle, fragment{value: rest})
  73. }
  74. }
  75. fragments = append(fragments[:i], append(middle, fragments[i+1:]...)...)
  76. }
  77. }
  78. slog.Debug("fragments", "frags", fragments)
  79. var ids []int32
  80. for _, frag := range fragments {
  81. if len(frag.ids) > 0 {
  82. ids = append(ids, frag.ids...)
  83. continue
  84. }
  85. for split := range spm.split(frag.value) {
  86. split = replaceWhitespaceBySeperator(split)
  87. var sb strings.Builder
  88. sb.Write([]byte(split))
  89. if id := spm.vocab.Encode(sb.String()); id >= 0 {
  90. ids = append(ids, id)
  91. continue
  92. }
  93. runes := []rune(sb.String())
  94. pq := queue.NewWith(func(a, b any) int {
  95. priA := a.(*candidate)
  96. priB := b.(*candidate)
  97. if priA.score > priB.score || (priA.score == priB.score && priA.a < priB.a) {
  98. return -1
  99. }
  100. return 1
  101. })
  102. merges := make([]merge, len(runes))
  103. for r := range runes {
  104. merges[r] = merge{
  105. p: r - 1,
  106. n: r + 1,
  107. runes: []rune{runes[r]},
  108. }
  109. }
  110. slog.Debug("tokenizer", "merges", merges)
  111. pairwise := func(a, b int) *candidate {
  112. if a < 0 || b >= len(runes) {
  113. return nil
  114. }
  115. left, right := string(merges[a].runes), string(merges[b].runes)
  116. if id := spm.vocab.Encode(left + right); id >= 0 {
  117. return &candidate{
  118. a: a,
  119. b: b,
  120. score: spm.vocab.Scores[id],
  121. }
  122. }
  123. return nil
  124. }
  125. for i := range len(runes) - 1 {
  126. if pair := pairwise(i, i+1); pair != nil {
  127. pq.Enqueue(pair)
  128. }
  129. }
  130. pqv := pq.Values()
  131. for _, v := range pqv {
  132. e := v.(*candidate)
  133. slog.Debug("candidate", "candidate", e)
  134. }
  135. for !pq.Empty() {
  136. v, _ := pq.Dequeue()
  137. pair := v.(*candidate)
  138. left, right := merges[pair.a], merges[pair.b]
  139. slog.Debug("pair", "left", left, "right", right)
  140. if len(left.runes) == 0 || len(right.runes) == 0 {
  141. continue
  142. }
  143. merges[pair.a].runes = append(left.runes, right.runes...)
  144. merges[pair.b].runes = nil
  145. merges[pair.a].n = right.n
  146. if right.n < len(merges) {
  147. merges[right.n].p = pair.a
  148. }
  149. if pair := pairwise(merges[pair.a].p, pair.a); pair != nil {
  150. pq.Enqueue(pair)
  151. }
  152. if pair := pairwise(pair.a, merges[pair.a].n); pair != nil {
  153. pq.Enqueue(pair)
  154. }
  155. }
  156. slog.Debug("merges", "merges", merges)
  157. for _, merge := range merges {
  158. if len(merge.runes) > 0 {
  159. if id := spm.vocab.Encode(string(merge.runes)); id >= 0 {
  160. ids = append(ids, id)
  161. } else {
  162. slog.Debug("missing token", "token", string(merge.runes))
  163. }
  164. }
  165. }
  166. }
  167. }
  168. slog.Debug("encoded", "ids", ids)
  169. return ids, nil
  170. }
  171. type candidate struct {
  172. a, b int
  173. score float32
  174. }
  175. func (spm SentencePieceModel) Decode(ids []int32) (string, error) {
  176. var sb strings.Builder
  177. for _, id := range ids {
  178. data := spm.vocab.Decode(id)
  179. data = strings.ReplaceAll(data, spmWhitespaceSep, " ")
  180. if _, err := sb.WriteString(data); err != nil {
  181. return "", err
  182. }
  183. }
  184. slog.Debug("decoded", "ids", ids, "text", sb.String())
  185. return sb.String(), nil
  186. }