process_text.go 6.7 KB

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