runner.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "log/slog"
  9. "net"
  10. "net/http"
  11. "strconv"
  12. "sync"
  13. "github.com/ollama/ollama/api"
  14. "github.com/ollama/ollama/llama"
  15. )
  16. type Sequence struct {
  17. // number of tokens evaluated
  18. nPast int
  19. // tokens left to evaluate
  20. tokens []int
  21. responses chan string
  22. samplingCtx *llama.SamplingContext
  23. }
  24. // prompt returns true if the prompt is still being processed
  25. func (s *Sequence) prompt() bool {
  26. return s.nPast < len(s.tokens)-1
  27. }
  28. func (s *Server) NewSequence(r Request, w http.ResponseWriter) *Sequence {
  29. var samplingParams llama.SamplingParams
  30. samplingParams.TopK = r.TopK
  31. samplingParams.TopP = r.TopP
  32. samplingParams.TfsZ = r.TFSZ
  33. samplingParams.TypicalP = r.TypicalP
  34. samplingParams.Temp = r.Temperature
  35. samplingParams.PenaltyRepeat = r.RepeatPenalty
  36. samplingParams.PenaltyFreq = r.FrequencyPenalty
  37. samplingParams.PenaltyPresent = r.PresencePenalty
  38. samplingParams.Mirostat = r.Mirostat
  39. samplingParams.MirostatTau = r.MirostatTau
  40. samplingParams.MirostatEta = r.MirostatEta
  41. samplingParams.PenalizeNl = r.PenalizeNewline
  42. samplingParams.Seed = uint32(r.Seed)
  43. samplingParams.Grammar = r.Grammar
  44. tokens, err := s.lc.Model().Tokenize(r.Prompt, 2048, false, true)
  45. if err != nil {
  46. panic(err)
  47. }
  48. sc := llama.NewSamplingContext(samplingParams)
  49. for _, t := range tokens {
  50. sc.Accept(s.lc, t, false)
  51. }
  52. return &Sequence{
  53. tokens: tokens,
  54. responses: make(chan string, 1),
  55. samplingCtx: sc,
  56. }
  57. }
  58. type Server struct {
  59. model *llama.Model
  60. lc *llama.Context
  61. cc *llama.ClipContext
  62. // parallel is the number of parallel requests to handle
  63. parallel int
  64. // seqs is the list of parallel sequences being evaluated
  65. seqs []*Sequence
  66. mu sync.Mutex
  67. cond *sync.Cond
  68. }
  69. func (s *Server) allNil() bool {
  70. for _, item := range s.seqs {
  71. if item != nil {
  72. return false
  73. }
  74. }
  75. return true
  76. }
  77. func (s *Server) run(ctx context.Context) {
  78. batch := llama.NewBatch(512, 0, s.parallel)
  79. defer batch.Free()
  80. for {
  81. select {
  82. case <-ctx.Done():
  83. return
  84. default:
  85. slog.Info("Processing batch", "seqs", len(s.seqs))
  86. s.mu.Lock()
  87. for s.allNil() {
  88. s.cond.Wait() // Wait until an item is added
  89. }
  90. s.mu.Unlock()
  91. // prepare the batch
  92. ibatch := make([]int, s.parallel)
  93. for i, seq := range s.seqs {
  94. if seq == nil {
  95. continue
  96. }
  97. for j, t := range seq.tokens {
  98. // todo: make this n_batch
  99. if j > 512 {
  100. break
  101. }
  102. batch.Add(t, seq.nPast, []int{i}, !seq.prompt())
  103. seq.nPast++
  104. if seq.prompt() {
  105. ibatch[i] = batch.NumTokens() + 1
  106. }
  107. }
  108. }
  109. err := s.lc.Decode(batch)
  110. if err != nil {
  111. panic("Failed to decode")
  112. }
  113. for i, seq := range s.seqs {
  114. if seq == nil {
  115. continue
  116. }
  117. // don't sample prompt processing
  118. if seq.prompt() {
  119. if len(seq.tokens) < 512 {
  120. seq.tokens = []int{}
  121. } else {
  122. seq.tokens = seq.tokens[512:]
  123. }
  124. continue
  125. }
  126. // sample a token
  127. // logits := s.lc.GetLogitsIth(ibatch[i])
  128. // token := s.lc.SampleTokenGreedy(logits)
  129. token := seq.samplingCtx.Sample(s.lc, nil, ibatch[i])
  130. seq.samplingCtx.Accept(s.lc, token, true)
  131. seq.responses <- s.model.TokenToPiece(token)
  132. seq.tokens = []int{token}
  133. // if it's an end of sequence token, break
  134. // TODO: just end this sequence
  135. if s.model.TokenIsEog(token) {
  136. // TODO: end the sequence instead of quitting the pool
  137. s.lc.KvCacheSeqRm(i, 0, -1)
  138. close(seq.responses)
  139. seq.samplingCtx.Free()
  140. s.seqs[i] = nil
  141. continue
  142. }
  143. }
  144. batch.Clear()
  145. }
  146. }
  147. }
  148. type Request struct {
  149. Prompt string `json:"prompt"`
  150. Images []string `json:"images"`
  151. Grammar string `json:"grammar"`
  152. api.Options
  153. }
  154. type Response struct {
  155. Token string `json:"token"`
  156. }
  157. func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
  158. var request Request
  159. request.Options = api.DefaultOptions()
  160. if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
  161. http.Error(w, "Bad request", http.StatusBadRequest)
  162. return
  163. }
  164. // Set the headers to indicate streaming
  165. w.Header().Set("Content-Type", "application/json")
  166. w.Header().Set("Transfer-Encoding", "chunked")
  167. w.WriteHeader(http.StatusOK)
  168. seq := s.NewSequence(request, w)
  169. s.mu.Lock()
  170. for i, sq := range s.seqs {
  171. if sq == nil {
  172. s.seqs[i] = seq
  173. s.cond.Signal()
  174. break
  175. }
  176. }
  177. s.mu.Unlock()
  178. for token := range seq.responses {
  179. if err := json.NewEncoder(w).Encode(&Response{
  180. Token: token,
  181. }); err != nil {
  182. log.Println("Failed to encode result:", err)
  183. return
  184. }
  185. flusher, ok := w.(http.Flusher)
  186. if !ok {
  187. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  188. return
  189. }
  190. flusher.Flush()
  191. }
  192. }
  193. func main() {
  194. mpath := flag.String("model", "", "Path to model binary file")
  195. ppath := flag.String("projector", "", "Path to projector binary file")
  196. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  197. port := flag.Int("port", 8080, "Port to expose the server on")
  198. flag.Parse()
  199. // load the model
  200. llama.BackendInit()
  201. params := llama.NewModelParams()
  202. model := llama.LoadModelFromFile(*mpath, params)
  203. ctxParams := llama.NewContextParams()
  204. lc := llama.NewContextWithModel(model, ctxParams)
  205. if lc == nil {
  206. panic("Failed to create context")
  207. }
  208. var cc *llama.ClipContext
  209. if *ppath != "" {
  210. cc = llama.NewClipContext(*ppath)
  211. if cc == nil {
  212. panic("Failed to create clip context")
  213. }
  214. }
  215. server := &Server{
  216. model: model,
  217. lc: lc,
  218. cc: cc,
  219. parallel: *parallel,
  220. seqs: make([]*Sequence, *parallel),
  221. }
  222. server.cond = sync.NewCond(&server.mu)
  223. ctx, cancel := context.WithCancel(context.Background())
  224. go server.run(ctx)
  225. addr := "127.0.0.1:" + strconv.Itoa(*port)
  226. listener, err := net.Listen("tcp", addr)
  227. if err != nil {
  228. fmt.Println("Listen error:", err)
  229. return
  230. }
  231. defer listener.Close()
  232. httpServer := http.Server{
  233. Handler: http.HandlerFunc(server.handler),
  234. }
  235. log.Println("Server listening on", addr)
  236. if err := httpServer.Serve(listener); err != nil {
  237. log.Fatal("server error:", err)
  238. }
  239. cancel()
  240. }