process_text.go 6.4 KB

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