runner.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "log/slog"
  9. "math"
  10. "net"
  11. "net/http"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "github.com/ollama/ollama/api"
  17. "github.com/ollama/ollama/llama"
  18. )
  19. type Sequence struct {
  20. // number of tokens evaluated
  21. nPast int
  22. // batch index
  23. iBatch int
  24. // number of tokens predicted so far
  25. numPredicted int
  26. // tokens left to evaluate
  27. tokens []int
  28. // channel to send responses over
  29. responses chan string
  30. // number of tokens to predict
  31. numPredict int
  32. samplingCtx *llama.SamplingContext
  33. // channel to send back the embedding if embedding only
  34. embedding chan []float32
  35. // stop sequences
  36. stop []string
  37. // true if an embedding are to be returned instead of text generation
  38. embeddingOnly bool
  39. doneReason string
  40. }
  41. // prompt returns true if the prompt is still being processed
  42. // TODO (jmorganca): clean up this logic
  43. func (s *Sequence) prompt() bool {
  44. return s.nPast < len(s.tokens)-1
  45. }
  46. func (s *Server) NewSequence(prompt string, numPredict int, stop []string, params *llama.SamplingParams, embedding bool) *Sequence {
  47. tokens, err := s.lc.Model().Tokenize(prompt, embedding, true)
  48. if err != nil {
  49. panic(err)
  50. }
  51. // truncate to last n tokens
  52. // TODO: this shouldn't happen and will severely impact generation
  53. // quality. instead we should ensure to cut prompt in the API.
  54. if len(tokens) > s.numCtx {
  55. tokens = tokens[:s.numCtx]
  56. }
  57. var sc *llama.SamplingContext
  58. if params != nil {
  59. sc = llama.NewSamplingContext(*params)
  60. for _, t := range tokens {
  61. sc.Accept(s.lc, t, false)
  62. }
  63. }
  64. return &Sequence{
  65. tokens: tokens,
  66. responses: make(chan string, 1),
  67. embedding: make(chan []float32, 1),
  68. samplingCtx: sc,
  69. embeddingOnly: embedding,
  70. stop: stop,
  71. }
  72. }
  73. type Server struct {
  74. model *llama.Model
  75. lc *llama.Context
  76. cc *llama.ClipContext
  77. batchSize int
  78. // parallel is the number of parallel requests to handle
  79. parallel int
  80. // seqs is the list of parallel sequences being evaluated
  81. // TODO (jmorganca): this can probably be moved into run()
  82. seqs []*Sequence
  83. // context window size
  84. numCtx int
  85. mu sync.Mutex
  86. cond *sync.Cond
  87. progress float32
  88. status string
  89. }
  90. func (s *Server) allNil() bool {
  91. for _, item := range s.seqs {
  92. if item != nil {
  93. return false
  94. }
  95. }
  96. return true
  97. }
  98. func (s *Server) run(ctx context.Context) {
  99. // TODO - should this be n_ctx / parallel like the old server.cpp setup?
  100. batch := llama.NewBatch(s.batchSize, 0, s.parallel)
  101. defer batch.Free()
  102. // build up stop sequences as we recognize them
  103. // TODO (jmorganca): simplify this
  104. pieces := make([][]string, s.parallel)
  105. for {
  106. select {
  107. case <-ctx.Done():
  108. return
  109. default:
  110. slog.Info("Processing batch", "seqs", len(s.seqs))
  111. s.mu.Lock()
  112. for s.allNil() {
  113. s.cond.Wait() // Wait until an item is added
  114. }
  115. s.mu.Unlock()
  116. for i, seq := range s.seqs {
  117. if seq == nil {
  118. continue
  119. }
  120. hitLimit := seq.numPredict > 0 && seq.numPredicted > seq.numPredict
  121. // if past the num predict limit
  122. if hitLimit || seq.nPast > s.numCtx {
  123. seq.doneReason = "limit"
  124. close(seq.responses)
  125. s.lc.KvCacheSeqRm(i, 0, -1)
  126. s.seqs[i] = nil
  127. continue
  128. }
  129. for j, t := range seq.tokens {
  130. // todo: make this n_batch
  131. if j > s.batchSize {
  132. break
  133. }
  134. batch.Add(t, seq.nPast, []int{i}, !seq.prompt())
  135. seq.nPast++
  136. }
  137. seq.iBatch = batch.NumTokens() - 1
  138. }
  139. err := s.lc.Decode(batch)
  140. if err != nil {
  141. panic("Failed to decode")
  142. }
  143. for i, seq := range s.seqs {
  144. if seq == nil {
  145. continue
  146. }
  147. // don't sample prompt processing
  148. if seq.prompt() {
  149. continue
  150. }
  151. // if done processing the prompt, generating an embedding and return
  152. if seq.embeddingOnly {
  153. embd := s.lc.GetEmbeddingsSeq(i)
  154. if embd == nil {
  155. embd = s.lc.GetEmbeddingsIth(seq.iBatch)
  156. }
  157. seq.embedding <- embd
  158. close(seq.embedding)
  159. s.lc.KvCacheSeqRm(i, 0, -1)
  160. s.seqs[i] = nil
  161. continue
  162. }
  163. // sample a token
  164. // logits := s.lc.GetLogitsIth(ibatch[i])
  165. // token := s.lc.SampleTokenGreedy(logits)
  166. token := seq.samplingCtx.Sample(s.lc, nil, seq.iBatch)
  167. seq.samplingCtx.Accept(s.lc, token, true)
  168. piece := s.model.TokenToPiece(token)
  169. seq.numPredicted++
  170. slog.Info("sampled", "piece", piece)
  171. // if it's an end of sequence token, break
  172. // TODO: just end this sequence
  173. if s.model.TokenIsEog(token) {
  174. // TODO: end the sequence instead of quitting the pool
  175. s.lc.KvCacheSeqRm(i, 0, -1)
  176. // TODO (jmorganca): we should send this back
  177. // as it's important for the /api/generate context
  178. // seq.responses <- piece
  179. seq.doneReason = "stop"
  180. close(seq.responses)
  181. seq.samplingCtx.Free()
  182. pieces[i] = []string{}
  183. s.seqs[i] = nil
  184. continue
  185. }
  186. seq.tokens = []int{token}
  187. pieces[i] = append(pieces[i], piece)
  188. sequence := strings.Join(pieces[i], "")
  189. if ok, stop := findStop(sequence, seq.stop); ok {
  190. slog.Info("hit stop token", "stop", seq.stop)
  191. truncated := truncateStop(pieces[i], stop)
  192. for _, p := range truncated {
  193. seq.responses <- p
  194. }
  195. s.lc.KvCacheSeqRm(i, 0, -1)
  196. seq.doneReason = "stop"
  197. close(seq.responses)
  198. seq.samplingCtx.Free()
  199. pieces[i] = []string{}
  200. s.seqs[i] = nil
  201. continue
  202. }
  203. if containsStopSuffix(sequence, seq.stop) {
  204. continue
  205. }
  206. for _, p := range pieces[i] {
  207. seq.responses <- p
  208. }
  209. pieces[i] = []string{}
  210. }
  211. batch.Clear()
  212. }
  213. }
  214. }
  215. type CompletionRequest struct {
  216. Prompt string `json:"prompt"`
  217. Images []string `json:"images"`
  218. Grammar string `json:"grammar"`
  219. Stop []string `json:"stop"`
  220. api.Options
  221. }
  222. type CompletionResponse struct {
  223. Token string `json:"token"`
  224. }
  225. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  226. var req CompletionRequest
  227. req.Options = api.DefaultOptions()
  228. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  229. http.Error(w, "Bad request", http.StatusBadRequest)
  230. return
  231. }
  232. // Set the headers to indicate streaming
  233. w.Header().Set("Content-Type", "application/json")
  234. w.Header().Set("Transfer-Encoding", "chunked")
  235. w.WriteHeader(http.StatusOK)
  236. var samplingParams llama.SamplingParams
  237. samplingParams.TopK = req.TopK
  238. samplingParams.TopP = req.TopP
  239. samplingParams.TfsZ = req.TFSZ
  240. samplingParams.TypicalP = req.TypicalP
  241. samplingParams.Temp = req.Temperature
  242. samplingParams.PenaltyRepeat = req.RepeatPenalty
  243. samplingParams.PenaltyFreq = req.FrequencyPenalty
  244. samplingParams.PenaltyPresent = req.PresencePenalty
  245. samplingParams.Mirostat = req.Mirostat
  246. samplingParams.MirostatTau = req.MirostatTau
  247. samplingParams.MirostatEta = req.MirostatEta
  248. samplingParams.PenalizeNl = req.PenalizeNewline
  249. samplingParams.Seed = uint32(req.Seed)
  250. samplingParams.Grammar = req.Grammar
  251. seq := s.NewSequence(req.Prompt, req.NumPredict, req.Stop, &samplingParams, false)
  252. // TODO (jmorganca): add to sequence queue instead of
  253. // failing if a slot isn't available
  254. s.mu.Lock()
  255. for i, sq := range s.seqs {
  256. if sq == nil {
  257. s.seqs[i] = seq
  258. s.cond.Signal()
  259. break
  260. }
  261. }
  262. s.mu.Unlock()
  263. // stream the response
  264. for token := range seq.responses {
  265. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  266. Token: token,
  267. }); err != nil {
  268. log.Println("Failed to encode result:", err)
  269. return
  270. }
  271. flusher, ok := w.(http.Flusher)
  272. if !ok {
  273. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  274. return
  275. }
  276. flusher.Flush()
  277. }
  278. }
  279. type EmbeddingRequest struct {
  280. Content []string `json:"content"`
  281. }
  282. type EmbeddingResponse struct {
  283. Embedding [][]float32 `json:"embedding"`
  284. }
  285. // TODO (jmorganca): is it safe to do this concurrently with decoding?
  286. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  287. var req EmbeddingRequest
  288. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  289. http.Error(w, "Bad request", http.StatusBadRequest)
  290. return
  291. }
  292. w.Header().Set("Content-Type", "application/json")
  293. slog.Debug("embedding request", "content", req.Content)
  294. seqs := make([]*Sequence, len(req.Content))
  295. embeddings := make([][]float32, len(req.Content))
  296. var processed int
  297. for i, content := range req.Content {
  298. seqs[i] = s.NewSequence(content, 0, nil, nil, true)
  299. }
  300. // TODO - refactor to go routines to add seq's and drain the responses
  301. // so we don't stall until each set is iterated through
  302. for processed < len(seqs) {
  303. s.mu.Lock()
  304. for i, sq := range s.seqs {
  305. if processed >= len(seqs) {
  306. break
  307. }
  308. if sq == nil {
  309. s.seqs[i] = seqs[processed]
  310. processed += 1
  311. }
  312. }
  313. s.cond.Signal()
  314. s.mu.Unlock()
  315. for i := range processed {
  316. embeddings[i] = <-seqs[i].embedding
  317. }
  318. }
  319. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  320. Embedding: embeddings,
  321. }); err != nil {
  322. log.Println("Failed to encode result:", err)
  323. return
  324. }
  325. }
  326. type HealthResponse struct {
  327. Status string `json:"status"`
  328. Progress float32 `json:"progress"`
  329. }
  330. // TODO (jmorganca): is it safe to do this concurrently with decoding?
  331. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  332. w.Header().Set("Content-Type", "application/json")
  333. if err := json.NewEncoder(w).Encode(&HealthResponse{
  334. Status: s.status,
  335. Progress: s.progress,
  336. }); err != nil {
  337. log.Println("Failed to encode result:", err)
  338. return
  339. }
  340. }
  341. func main() {
  342. mpath := flag.String("model", "", "Path to model binary file")
  343. ppath := flag.String("projector", "", "Path to projector binary file")
  344. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  345. batchSize := flag.Int("batch-size", 512, "Batch size")
  346. nGpuLayers := flag.Int("num-gpu", 0, "Number of layers to offload to GPU")
  347. mainGpu := flag.Int("main-gpu", 0, "Main GPU")
  348. flashAttention := flag.Bool("flash-attention", false, "Enable flash attention")
  349. numCtx := flag.Int("num-ctx", 2048, "Context (or KV cache) size")
  350. lpath := flag.String("lora", "", "Path to lora layer file")
  351. port := flag.Int("port", 8080, "Port to expose the server on")
  352. threads := flag.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  353. flag.Parse()
  354. server := &Server{
  355. numCtx: *numCtx,
  356. batchSize: *batchSize,
  357. parallel: *parallel,
  358. seqs: make([]*Sequence, *parallel),
  359. status: "loading",
  360. }
  361. // load the model
  362. llama.BackendInit()
  363. params := llama.NewModelParams(*nGpuLayers, *mainGpu, func(progress float32) {
  364. slog.Info("Loading model", "progress %", math.Round(float64(progress*100)))
  365. server.progress = progress
  366. })
  367. server.model = llama.LoadModelFromFile(*mpath, params)
  368. if *lpath != "" {
  369. err := server.model.ApplyLoraFromFile(*lpath, 1.0, "", *threads)
  370. if err != nil {
  371. panic(err)
  372. }
  373. }
  374. ctxParams := llama.NewContextParams(*numCtx, *threads, *flashAttention)
  375. server.lc = llama.NewContextWithModel(server.model, ctxParams)
  376. if *ppath != "" {
  377. server.cc = llama.NewClipContext(*ppath)
  378. }
  379. server.cond = sync.NewCond(&server.mu)
  380. ctx, cancel := context.WithCancel(context.Background())
  381. go server.run(ctx)
  382. addr := "127.0.0.1:" + strconv.Itoa(*port)
  383. listener, err := net.Listen("tcp", addr)
  384. if err != nil {
  385. fmt.Println("Listen error:", err)
  386. return
  387. }
  388. defer listener.Close()
  389. mux := http.NewServeMux()
  390. mux.HandleFunc("/embeddings", server.embeddings)
  391. mux.HandleFunc("/completion", server.completion)
  392. mux.HandleFunc("/health", server.health)
  393. httpServer := http.Server{
  394. Handler: mux,
  395. }
  396. server.status = "ready"
  397. log.Println("Server listening on", addr)
  398. if err := httpServer.Serve(listener); err != nil {
  399. log.Fatal("server error:", err)
  400. }
  401. cancel()
  402. }