process_text.go 7.0 KB

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