runner.go 11 KB

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