transforms.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package sample
  2. import (
  3. "container/heap"
  4. "math"
  5. "slices"
  6. )
  7. // tokenHeap implements heap.Interface and holds tokens as a min-heap to track k largest elements
  8. type tokenHeap []token
  9. func (h tokenHeap) Len() int { return len(h) }
  10. func (h tokenHeap) Less(i, j int) bool { return h[i].value < h[j].value } // Use < for min-heap to track largest elements
  11. func (h tokenHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  12. func (h *tokenHeap) Push(x any) {
  13. *h = append(*h, x.(token))
  14. }
  15. func (h *tokenHeap) Pop() any {
  16. old := *h
  17. n := len(old)
  18. x := old[n-1]
  19. *h = old[0 : n-1]
  20. return x
  21. }
  22. // temperature applies scaling and softmax to the logits
  23. func temperature(ts []token, temp float32) []token {
  24. // Find max logit for numerical stability
  25. maxLogit := float32(math.Inf(-1))
  26. for _, t := range ts {
  27. if t.value > maxLogit {
  28. maxLogit = t.value
  29. }
  30. }
  31. // Apply temperature and compute exp(x - max)
  32. temp = max(temp, 1e-7)
  33. var sum float32
  34. for i, v := range ts {
  35. ts[i].value = float32(math.Exp(float64((v.value - maxLogit) / temp)))
  36. sum += ts[i].value
  37. }
  38. // Normalize
  39. for i := range ts {
  40. ts[i].value /= sum
  41. }
  42. return ts
  43. }
  44. // topK limits the number of tokens considered to the k highest logits
  45. func topK(ts []token, k int) []token {
  46. if k >= len(ts) {
  47. sortLogits(ts)
  48. return ts
  49. }
  50. // Initialize min-heap with first k elements
  51. h := make(tokenHeap, k)
  52. copy(h, ts[:k])
  53. heap.Init(&h)
  54. // Process remaining elements
  55. for i := k; i < len(ts); i++ {
  56. if ts[i].value > h[0].value {
  57. heap.Pop(&h)
  58. heap.Push(&h, ts[i])
  59. }
  60. }
  61. // Convert heap to sorted slice in descending order
  62. result := make([]token, k)
  63. for i := k - 1; i >= 0; i-- {
  64. result[i] = heap.Pop(&h).(token)
  65. }
  66. return result
  67. }
  68. // topP limits tokens to those with cumulative probability p
  69. func topP(ts []token, p float32) []token {
  70. if p == 1.0 {
  71. return ts
  72. }
  73. // Find cutoff index where cumulative sum exceeds p
  74. var sum float32
  75. for i, t := range ts {
  76. sum += t.value
  77. if sum > float32(p) {
  78. ts = ts[:i+1]
  79. return ts
  80. }
  81. }
  82. return ts
  83. }
  84. // minP limits tokens to those with cumulative probability p
  85. func minP(ts []token, p float32) []token {
  86. if p == 1.0 {
  87. return ts
  88. }
  89. maxProb := float32(math.Inf(-1))
  90. for _, token := range ts {
  91. if token.value > maxProb {
  92. maxProb = token.value
  93. }
  94. }
  95. threshold := maxProb * float32(p)
  96. // Filter tokens in-place
  97. validTokens := ts[:0]
  98. for i, token := range ts {
  99. if token.value >= threshold {
  100. validTokens = append(validTokens, ts[i])
  101. }
  102. }
  103. ts = validTokens
  104. return ts
  105. }
  106. // TODO(parthsareen): possibly replace with simpler implementation https://github.com/ollama/ollama/issues/9584
  107. // sortLogits sorts implementation to sort tokens by logits using counting sort
  108. // counting sort is faster than built-in sort for this use case
  109. func sortLogits(tokens []token) {
  110. if len(tokens) <= 1 {
  111. return
  112. }
  113. // Find max/min in a single pass
  114. minLogit, maxLogit := tokens[0].value, tokens[0].value
  115. for _, t := range tokens[1:] {
  116. if t.value < minLogit {
  117. minLogit = t.value
  118. } else if t.value > maxLogit {
  119. maxLogit = t.value
  120. }
  121. }
  122. // Calculate scaling to map to uint32 range
  123. logitRange := maxLogit - minLogit
  124. if logitRange < 1e-6 {
  125. return // All values effectively equal
  126. }
  127. // Count frequencies directly from tokens
  128. const maxInt = (1 << 24) - 1 // Use 24 bits for good granularity
  129. var counts [256]int // For first byte
  130. // First pass: count frequencies
  131. for _, t := range tokens {
  132. // Map to [0, maxInt] range
  133. score := min(uint32((t.value-minLogit)*float32(maxInt)/logitRange), maxInt)
  134. counts[score>>16]++
  135. }
  136. // Calculate offsets
  137. var offset int
  138. for i := range counts {
  139. count := counts[i]
  140. counts[i] = offset
  141. offset += count
  142. }
  143. // Second pass: place elements in correct position
  144. output := make([]token, len(tokens))
  145. // Track current positions
  146. countsCopy := counts
  147. for i, t := range tokens {
  148. score := min(uint32((t.value-minLogit)*float32(maxInt)/logitRange), maxInt)
  149. pos := countsCopy[score>>16]
  150. countsCopy[score>>16]++
  151. output[len(tokens)-1-pos] = tokens[i]
  152. }
  153. copy(tokens, output)
  154. }