process_text.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. ids := make([]int32, 0, len(fragments))
  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. if id := bpe.Vocabulary.Encode(sb.String()); id >= 0 {
  164. ids = append(ids, id)
  165. slog.Debug("encoded", "text", sb.String(), "ids", []int32{id})
  166. continue
  167. }
  168. runes := []rune(sb.String())
  169. merges := make([]merge, len(runes))
  170. for i := range runes {
  171. merges[i] = merge{
  172. p: i - 1,
  173. n: i + 1,
  174. runes: []rune{runes[i]},
  175. }
  176. }
  177. pairwise := func(a, b int) *pair {
  178. if a < 0 || b >= len(runes) {
  179. return nil
  180. }
  181. left, right := string(merges[a].runes), string(merges[b].runes)
  182. rank := bpe.Vocabulary.Merge(left, right)
  183. if rank < 0 {
  184. return nil
  185. }
  186. return &pair{
  187. a: a,
  188. b: b,
  189. rank: rank,
  190. value: left + right,
  191. }
  192. }
  193. pairs := heap.NewWith(func(i, j *pair) int {
  194. return cmp.Compare(i.rank, j.rank)
  195. })
  196. for i := range len(runes) - 1 {
  197. if pair := pairwise(i, i+1); pair != nil {
  198. pairs.Push(pair)
  199. }
  200. }
  201. for !pairs.Empty() {
  202. pair, _ := pairs.Pop()
  203. left, right := merges[pair.a], merges[pair.b]
  204. if len(left.runes) <= 0 || len(right.runes) <= 0 ||
  205. string(left.runes)+string(right.runes) != pair.value {
  206. continue
  207. }
  208. merges[pair.a].runes = append(left.runes, right.runes...)
  209. merges[pair.b].runes = nil
  210. merges[pair.a].n = right.n
  211. if right.n < len(merges) {
  212. merges[right.n].p = pair.a
  213. }
  214. if pair := pairwise(merges[pair.a].p, pair.a); pair != nil {
  215. pairs.Push(pair)
  216. }
  217. if pair := pairwise(pair.a, merges[pair.a].n); pair != nil {
  218. pairs.Push(pair)
  219. }
  220. }
  221. for _, merge := range merges {
  222. if len(merge.runes) > 0 {
  223. // TODO: handle the edge case where the rune isn't in the vocabulary
  224. if id := bpe.Vocabulary.Encode(string(merge.runes)); id >= 0 {
  225. ids = append(ids, id)
  226. slog.Debug("encoded", "text", string(merge.runes), "ids", []int32{id})
  227. }
  228. }
  229. }
  230. }
  231. }
  232. return ids, nil
  233. }
  234. func (bpe BytePairEncoding) Decode(ids []int32) (string, error) {
  235. var sb strings.Builder
  236. for _, id := range ids {
  237. for _, r := range bpe.Vocabulary.Decode(id) {
  238. switch {
  239. case r == 0x0100:
  240. // this produces 0x00 aka NULL
  241. continue
  242. case r == 0x0143:
  243. r = 0x00ad
  244. case r > 0x0100 && r <= 0x0120:
  245. r = r - 0x0100
  246. case r > 0x0120 && r <= 0x0142:
  247. r = r - 0x00a2
  248. }
  249. // NOTE: not using WriteRune here because it writes the UTF-8
  250. // encoding of the rune which is _not_ what we want
  251. if err := sb.WriteByte(byte(r)); err != nil {
  252. return "", err
  253. }
  254. }
  255. }
  256. slog.Debug("decoded", "ids", ids, "text", sb.String())
  257. return sb.String(), nil
  258. }