process_text.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package model
  2. import (
  3. "cmp"
  4. "log/slog"
  5. "strings"
  6. "sync"
  7. "github.com/dlclark/regexp2"
  8. heap "github.com/emirpasic/gods/v2/trees/binaryheap"
  9. )
  10. type Special int32
  11. const (
  12. SpecialBOS Special = iota
  13. SpecialEOS
  14. )
  15. type TextProcessor interface {
  16. Encode(string) ([]int32, error)
  17. Decode([]int32) (string, error)
  18. Is(uint32, Special) bool
  19. }
  20. type Vocabulary struct {
  21. Values []string
  22. Types []uint32
  23. Scores []uint32
  24. Merges []string
  25. BOS, EOS uint32
  26. specialOnce sync.Once
  27. special []string
  28. valuesOnce sync.Once
  29. values map[string]int32
  30. mergeOnce sync.Once
  31. merge map[string]int32
  32. }
  33. func (v *Vocabulary) Is(id uint32, special Special) bool {
  34. switch special {
  35. case SpecialBOS:
  36. return id == v.BOS
  37. case SpecialEOS:
  38. return id == v.EOS
  39. default:
  40. return false
  41. }
  42. }
  43. func (v *Vocabulary) Encode(s string) int32 {
  44. v.valuesOnce.Do(func() {
  45. v.values = make(map[string]int32, len(v.Values))
  46. for i, value := range v.Values {
  47. v.values[value] = int32(i)
  48. }
  49. })
  50. if id, ok := v.values[s]; ok {
  51. return id
  52. }
  53. return -1
  54. }
  55. func (v *Vocabulary) Decode(id int32) string {
  56. return v.Values[id]
  57. }
  58. func (v *Vocabulary) SpecialVocabulary() []string {
  59. v.specialOnce.Do(func() {
  60. for i := range v.Values {
  61. if v.Types[i] == 3 {
  62. v.special = append(v.special, v.Values[i])
  63. }
  64. }
  65. })
  66. return v.special
  67. }
  68. func (v *Vocabulary) Merge(left, right string) int {
  69. v.mergeOnce.Do(func() {
  70. v.merge = make(map[string]int32, len(v.Merges))
  71. for i, merge := range v.Merges {
  72. v.merge[merge] = int32(i)
  73. }
  74. })
  75. if id, ok := v.merge[left+" "+right]; ok {
  76. return int(id)
  77. }
  78. return -1
  79. }
  80. type BytePairEncoding struct {
  81. Pretokenizer string
  82. *Vocabulary
  83. }
  84. func (bpe BytePairEncoding) split(s string) ([]string, error) {
  85. re, err := regexp2.Compile(bpe.Pretokenizer, regexp2.Unicode|regexp2.RE2)
  86. if err != nil {
  87. return nil, err
  88. }
  89. var matches []string
  90. for m, _ := re.FindStringMatch(s); m != nil; m, _ = re.FindNextMatch(m) {
  91. matches = append(matches, m.String())
  92. }
  93. return matches, nil
  94. }
  95. // fragment is a string fragment and their corresponding token IDs
  96. type fragment struct {
  97. value string
  98. ids []int32
  99. }
  100. // pair is a pair of runes and its rank
  101. type pair struct {
  102. a, b int
  103. rank int
  104. value string
  105. }
  106. type merge struct {
  107. p, n int
  108. runes []rune
  109. }
  110. func (bpe BytePairEncoding) Encode(s string) ([]int32, error) {
  111. fragments := []fragment{{value: s}}
  112. for _, special := range bpe.Vocabulary.SpecialVocabulary() {
  113. // TODO: process special tokens concurrently
  114. id := bpe.Vocabulary.Encode(special)
  115. for i := 0; i < len(fragments); i++ {
  116. frag := fragments[i]
  117. if len(frag.ids) > 0 {
  118. continue
  119. }
  120. var middle []fragment
  121. switch i := strings.Index(frag.value, special); {
  122. case i < 0:
  123. middle = append(middle, frag)
  124. case i > 0:
  125. middle = append(middle, fragment{value: frag.value[:i]})
  126. fallthrough
  127. default:
  128. middle = append(middle, fragment{value: special, ids: []int32{id}})
  129. if rest := frag.value[i+len(special):]; rest != "" {
  130. middle = append(middle, fragment{value: rest})
  131. }
  132. }
  133. fragments = append(fragments[:i], append(middle, fragments[i+1:]...)...)
  134. }
  135. }
  136. var ids []int32
  137. for _, frag := range fragments {
  138. if len(frag.ids) > 0 {
  139. ids = append(ids, frag.ids...)
  140. slog.Debug("encoded", "text", frag.value, "ids", frag.ids, "special", true)
  141. continue
  142. }
  143. // split fragment using pretokenizer
  144. splits, err := bpe.split(frag.value)
  145. if err != nil {
  146. return nil, err
  147. }
  148. for _, split := range splits {
  149. // TODO: process splits concurrently
  150. var sb strings.Builder
  151. for _, b := range []byte(split) {
  152. r := rune(b)
  153. switch {
  154. case r == 0x00ad:
  155. r = 0x0143
  156. case r <= 0x0020:
  157. r = r + 0x0100
  158. case r >= 0x007e && r <= 0x00a0:
  159. r = r + 0x00a2
  160. }
  161. sb.WriteRune(r)
  162. }
  163. // short circuit if the fragment is in the vocabulary
  164. if id := bpe.Vocabulary.Encode(sb.String()); id >= 0 {
  165. ids = append(ids, id)
  166. slog.Debug("encoded", "text", sb.String(), "ids", []int32{id})
  167. continue
  168. }
  169. runes := []rune(sb.String())
  170. merges := make([]merge, len(runes))
  171. for r := range runes {
  172. merges[r] = merge{
  173. p: r - 1,
  174. n: r + 1,
  175. runes: []rune{runes[r]},
  176. }
  177. }
  178. pairwise := func(a, b int) *pair {
  179. if a < 0 || b >= len(runes) {
  180. return nil
  181. }
  182. left, right := string(merges[a].runes), string(merges[b].runes)
  183. rank := bpe.Vocabulary.Merge(left, right)
  184. if rank < 0 {
  185. return nil
  186. }
  187. return &pair{
  188. a: a,
  189. b: b,
  190. rank: rank,
  191. value: left + right,
  192. }
  193. }
  194. pairs := heap.NewWith(func(i, j *pair) int {
  195. return cmp.Compare(i.rank, j.rank)
  196. })
  197. for i := range len(runes) - 1 {
  198. if pair := pairwise(i, i+1); pair != nil {
  199. pairs.Push(pair)
  200. }
  201. }
  202. for !pairs.Empty() {
  203. pair, _ := pairs.Pop()
  204. left, right := merges[pair.a], merges[pair.b]
  205. if len(left.runes) == 0 || len(right.runes) == 0 ||
  206. string(left.runes)+string(right.runes) != pair.value {
  207. continue
  208. }
  209. merges[pair.a].runes = append(left.runes, right.runes...)
  210. merges[pair.b].runes = nil
  211. merges[pair.a].n = right.n
  212. if right.n < len(merges) {
  213. merges[right.n].p = pair.a
  214. }
  215. if pair := pairwise(merges[pair.a].p, pair.a); pair != nil {
  216. pairs.Push(pair)
  217. }
  218. if pair := pairwise(pair.a, merges[pair.a].n); pair != nil {
  219. pairs.Push(pair)
  220. }
  221. }
  222. for _, merge := range merges {
  223. if len(merge.runes) > 0 {
  224. // TODO: handle the edge case where the rune isn't in the vocabulary
  225. if id := bpe.Vocabulary.Encode(string(merge.runes)); id >= 0 {
  226. ids = append(ids, id)
  227. slog.Debug("encoded", "text", string(merge.runes), "ids", []int32{id})
  228. }
  229. }
  230. }
  231. }
  232. }
  233. return ids, nil
  234. }
  235. func (bpe BytePairEncoding) Decode(ids []int32) (string, error) {
  236. var sb strings.Builder
  237. for _, id := range ids {
  238. for _, r := range bpe.Vocabulary.Decode(id) {
  239. switch {
  240. case r == 0x0100:
  241. // this produces 0x00 aka NULL
  242. continue
  243. case r == 0x0143:
  244. r = 0x00ad
  245. case r > 0x0100 && r <= 0x0120:
  246. r = r - 0x0100
  247. case r > 0x0120 && r <= 0x0142:
  248. r = r - 0x00a2
  249. }
  250. // NOTE: not using WriteRune here because it writes the UTF-8
  251. // encoding of the rune which is _not_ what we want
  252. if err := sb.WriteByte(byte(r)); err != nil {
  253. return "", err
  254. }
  255. }
  256. }
  257. slog.Debug("decoded", "ids", ids, "text", sb.String())
  258. return sb.String(), nil
  259. }