process_text.go 6.9 KB

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