runner.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. package main
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "log/slog"
  10. "math"
  11. "net"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/ollama/ollama/api"
  22. "github.com/ollama/ollama/llama"
  23. )
  24. // input is an element of the prompt to process, either
  25. // a token or an embedding (e.g. generated from a vision projector)
  26. type input struct {
  27. token int
  28. // embd is an image embedding
  29. // important to note, embd contains a series of embeddings, all backed
  30. // by a single float* buffer
  31. // TODO (jmorganca):
  32. embd *llama.LlavaImageEmbed
  33. }
  34. type Sequence struct {
  35. // number of tokens evaluated
  36. nPast int
  37. // batch index
  38. iBatch int
  39. // number of tokens predicted so far
  40. numPredicted int
  41. // prompt inputs left to evaluate
  42. inputs []input
  43. // channel to send responses over
  44. responses chan string
  45. // number of tokens to predict
  46. numPredict int
  47. samplingCtx *llama.SamplingContext
  48. // channel to send back the embedding if embedding only
  49. embedding chan []float32
  50. // stop sequences
  51. stop []string
  52. // true if an embedding are to be returned instead of text generation
  53. embeddingOnly bool
  54. doneReason string
  55. pieces []string
  56. // Metrics
  57. t_start_process_prompt time.Time
  58. t_start_genereration time.Time
  59. n_decoded int
  60. n_prompt_tokens int
  61. }
  62. // prompt returns true if the prompt is still being processed
  63. // TODO (jmorganca): clean up this logic
  64. func (s *Sequence) isPromptProcessing() bool {
  65. var total int
  66. for _, i := range s.inputs {
  67. if i.embd == nil {
  68. total++
  69. continue
  70. }
  71. total += i.embd.Tokens()
  72. }
  73. return s.nPast < total-1
  74. }
  75. // inputs processes the prompt and images into a list of inputs
  76. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  77. // generating image embeddings for each image
  78. func (s *Server) inputs(prompt string, images []string) ([]input, error) {
  79. var inputs []input
  80. re := regexp.MustCompile(`\[img-(\d+)\]`)
  81. parts := re.Split(prompt, -1)
  82. matches := re.FindAllStringSubmatch(prompt, -1)
  83. for i, part := range parts {
  84. // text - tokenize
  85. if strings.TrimSpace(part) != "" {
  86. tokens, err := s.lc.Model().Tokenize(prompt, false, true)
  87. if err != nil {
  88. return nil, err
  89. }
  90. for _, t := range tokens {
  91. inputs = append(inputs, input{token: t})
  92. }
  93. }
  94. // image - generate image embedding
  95. if i < len(matches) {
  96. n, _ := strconv.Atoi(matches[i][1])
  97. if n < 0 || n >= len(images) {
  98. return nil, fmt.Errorf("invalid image index: %d", n)
  99. }
  100. decoded, err := base64.StdEncoding.DecodeString(images[n])
  101. if err != nil {
  102. // TODO (jmorganca): return an error?
  103. slog.Error("Failed to decode image", "error", err)
  104. return nil, err
  105. }
  106. // Vision models can not be used concurrently
  107. s.clip.mu.Lock()
  108. // todo: check for duplicates so we don't encode the same image twice
  109. slog.Info("encoding image", "n", n)
  110. embd := llama.NewLlavaImageEmbed(s.clip.cc, decoded)
  111. s.clip.mu.Unlock()
  112. inputs = append(inputs, input{embd: embd})
  113. }
  114. }
  115. return inputs, nil
  116. }
  117. func (s *Server) NewSequence(prompt string, images []string, numPredict int, stop []string, params *llama.SamplingParams, embedding bool) (*Sequence, error) {
  118. inputs, err := s.inputs(prompt, images)
  119. if err != nil {
  120. return nil, fmt.Errorf("failed to process inputs: %w", err)
  121. }
  122. var sc *llama.SamplingContext
  123. if params != nil {
  124. sc = llama.NewSamplingContext(*params)
  125. for _, t := range inputs {
  126. if t.embd == nil {
  127. sc.Accept(s.lc, t.token, false)
  128. }
  129. }
  130. }
  131. return &Sequence{
  132. inputs: inputs,
  133. n_prompt_tokens: len(inputs),
  134. responses: make(chan string, 1),
  135. embedding: make(chan []float32, 1),
  136. samplingCtx: sc,
  137. embeddingOnly: embedding,
  138. stop: stop,
  139. }, nil
  140. }
  141. type clip struct {
  142. cc *llama.ClipContext
  143. mu sync.Mutex
  144. }
  145. type Server struct {
  146. model *llama.Model
  147. lc *llama.Context
  148. // required for image embeddings
  149. clip clip
  150. // batchSize is the number of tokens or image embeddings
  151. // to process in a batch
  152. batchSize int
  153. // parallel is the number of parallel requests to handle
  154. parallel int
  155. // seqs is the list of parallel sequences being evaluated
  156. // TODO (jmorganca): this can probably be moved into run()
  157. seqs []*Sequence
  158. // context window size
  159. numCtx int
  160. mu sync.Mutex
  161. cond *sync.Cond
  162. progress float32
  163. status string
  164. }
  165. // waiting is true if there are no sequences to process
  166. func (s *Server) waiting() bool {
  167. for _, item := range s.seqs {
  168. if item != nil {
  169. return false
  170. }
  171. }
  172. return true
  173. }
  174. // processImage processes an image embedding if it's next in any sequence
  175. func (s *Server) processImage() bool {
  176. for _, seq := range s.seqs {
  177. if len(seq.inputs) > 0 && seq.inputs[0].embd != nil {
  178. llama.LlavaEvalImageEmbed(s.lc, seq.inputs[0].embd, s.batchSize, &seq.nPast)
  179. llama.LlavaImageEmbedFree(seq.inputs[0].embd)
  180. seq.iBatch = seq.inputs[0].embd.Tokens() - 1
  181. seq.inputs = seq.inputs[1:]
  182. return true
  183. }
  184. }
  185. return false
  186. }
  187. func (s *Server) run(ctx context.Context) {
  188. batch := llama.NewBatch(s.batchSize, 0, s.parallel)
  189. defer batch.Free()
  190. for {
  191. select {
  192. case <-ctx.Done():
  193. return
  194. default:
  195. s.mu.Lock()
  196. for s.waiting() {
  197. s.cond.Wait()
  198. }
  199. s.mu.Unlock()
  200. // first process an image embedding if is it next on any sequence
  201. // TODO (jmorganca): this will block calls to `Decode` below
  202. // until images are processed
  203. if s.processImage() {
  204. continue
  205. }
  206. // create a token batch to process
  207. for i, seq := range s.seqs {
  208. if seq == nil {
  209. continue
  210. }
  211. hitLimit := seq.numPredict > 0 && seq.numPredicted > seq.numPredict
  212. // if past the num predict limit
  213. // TODO (jmorganca): should context shift
  214. if hitLimit || seq.nPast > s.numCtx {
  215. seq.doneReason = "limit"
  216. close(seq.responses)
  217. s.lc.KvCacheSeqRm(i, 0, -1)
  218. s.seqs[i] = nil
  219. continue
  220. }
  221. if seq.t_start_process_prompt.IsZero() {
  222. seq.t_start_process_prompt = time.Now()
  223. }
  224. for j, t := range seq.inputs {
  225. // break if this is an image embedding to be handled in a follow up batch
  226. if t.embd != nil {
  227. break
  228. }
  229. if j > s.batchSize {
  230. break
  231. }
  232. batch.Add(t.token, seq.nPast, []int{i}, !seq.isPromptProcessing())
  233. seq.nPast++
  234. }
  235. seq.iBatch = batch.NumTokens() - 1
  236. }
  237. if batch.NumTokens() > 0 {
  238. err := s.lc.Decode(batch)
  239. if err != nil {
  240. slog.Error("failed to decode batch", "error", err)
  241. // TODO (jmorganca): handle this better by returning an error
  242. panic(err)
  243. }
  244. }
  245. // sample and send responses
  246. for i, seq := range s.seqs {
  247. if seq == nil {
  248. continue
  249. }
  250. // don't sample while prompt processing
  251. if seq.isPromptProcessing() {
  252. if batch.NumTokens() > 0 {
  253. seq.inputs = seq.inputs[batch.NumTokens():]
  254. } else {
  255. // image case
  256. // TODO (jmorganca): simplify this
  257. seq.inputs = seq.inputs[1:]
  258. }
  259. continue
  260. }
  261. // if done processing the prompt, send an embedding
  262. if seq.embeddingOnly {
  263. embd := s.lc.GetEmbeddingsSeq(i)
  264. if embd == nil {
  265. embd = s.lc.GetEmbeddingsIth(seq.iBatch)
  266. }
  267. seq.embedding <- embd
  268. close(seq.embedding)
  269. s.lc.KvCacheSeqRm(i, 0, -1)
  270. s.seqs[i] = nil
  271. continue
  272. }
  273. token := seq.samplingCtx.Sample(s.lc, nil, seq.iBatch)
  274. seq.samplingCtx.Accept(s.lc, token, true)
  275. seq.n_decoded += 1
  276. if seq.n_decoded == 1 {
  277. seq.t_start_genereration = time.Now()
  278. }
  279. piece := s.model.TokenToPiece(token)
  280. seq.numPredicted++
  281. slog.Debug("sampled", "piece", piece)
  282. // if it's an end of sequence token, break
  283. // TODO: just end this sequence
  284. if s.model.TokenIsEog(token) {
  285. // TODO: end the sequence instead of quitting the pool
  286. s.lc.KvCacheSeqRm(i, 0, -1)
  287. // TODO (jmorganca): we should send this back
  288. // as it's important for the /api/generate context
  289. // seq.responses <- piece
  290. seq.doneReason = "stop"
  291. close(seq.responses)
  292. seq.samplingCtx.Free()
  293. s.seqs[i] = nil
  294. continue
  295. }
  296. seq.inputs = []input{{token: token}}
  297. seq.pieces = append(seq.pieces, piece)
  298. sequence := strings.Join(seq.pieces, "")
  299. if ok, stop := findStop(sequence, seq.stop); ok {
  300. slog.Info("hit stop token", "stop", seq.stop)
  301. truncated := truncateStop(seq.pieces, stop)
  302. for _, p := range truncated {
  303. seq.responses <- p
  304. }
  305. s.lc.KvCacheSeqRm(i, 0, -1)
  306. seq.doneReason = "stop"
  307. close(seq.responses)
  308. seq.samplingCtx.Free()
  309. s.seqs[i] = nil
  310. continue
  311. }
  312. if maybeStop(sequence, seq.stop) {
  313. continue
  314. }
  315. for _, p := range seq.pieces {
  316. seq.responses <- p
  317. }
  318. seq.pieces = []string{}
  319. }
  320. batch.Clear()
  321. }
  322. }
  323. }
  324. // TODO (jmorganca): use structs from the api package to avoid duplication
  325. // this way the api acts as a proxy instead of using a different api for the
  326. // runner
  327. type CompletionRequest struct {
  328. Prompt string `json:"prompt"`
  329. Images []string `json:"images"`
  330. Grammar string `json:"grammar"`
  331. Stop []string `json:"stop"`
  332. api.Options
  333. }
  334. type Timings struct {
  335. PredictedN int `json:"predicted_n"`
  336. PredictedMS float64 `json:"predicted_ms"`
  337. PromptN int `json:"prompt_n"`
  338. PromptMS float64 `json:"prompt_ms"`
  339. }
  340. type CompletionResponse struct {
  341. Content string `json:"content"`
  342. Stop bool `json:"stop"`
  343. Model string `json:"model,omitempty"`
  344. Prompt string `json:"prompt,omitempty"`
  345. StoppedLimit bool `json:"stopped_limit,omitempty"`
  346. PredictedN int `json:"predicted_n,omitempty"`
  347. PredictedMS float64 `json:"predicted_ms,omitempty"`
  348. PromptN int `json:"prompt_n,omitempty"`
  349. PromptMS float64 `json:"prompt_ms,omitempty"`
  350. Timings Timings `json:"timings"`
  351. }
  352. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  353. var req CompletionRequest
  354. req.Options = api.DefaultOptions()
  355. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  356. http.Error(w, "Bad request", http.StatusBadRequest)
  357. return
  358. }
  359. // Set the headers to indicate streaming
  360. w.Header().Set("Content-Type", "application/json")
  361. w.Header().Set("Transfer-Encoding", "chunked")
  362. w.WriteHeader(http.StatusOK)
  363. var samplingParams llama.SamplingParams
  364. samplingParams.TopK = req.TopK
  365. samplingParams.TopP = req.TopP
  366. samplingParams.TfsZ = req.TFSZ
  367. samplingParams.TypicalP = req.TypicalP
  368. samplingParams.Temp = req.Temperature
  369. samplingParams.PenaltyRepeat = req.RepeatPenalty
  370. samplingParams.PenaltyFreq = req.FrequencyPenalty
  371. samplingParams.PenaltyPresent = req.PresencePenalty
  372. samplingParams.Mirostat = req.Mirostat
  373. samplingParams.MirostatTau = req.MirostatTau
  374. samplingParams.MirostatEta = req.MirostatEta
  375. samplingParams.PenalizeNl = req.PenalizeNewline
  376. samplingParams.Seed = uint32(req.Seed)
  377. samplingParams.Grammar = req.Grammar
  378. seq, err := s.NewSequence(req.Prompt, req.Images, req.NumPredict, req.Stop, &samplingParams, false)
  379. if err != nil {
  380. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  381. return
  382. }
  383. // TODO (jmorganca): add to sequence queue instead of
  384. // failing if a slot isn't available
  385. s.mu.Lock()
  386. for i, sq := range s.seqs {
  387. if sq == nil {
  388. s.seqs[i] = seq
  389. s.cond.Signal()
  390. break
  391. }
  392. }
  393. s.mu.Unlock()
  394. // stream the response
  395. for content := range seq.responses {
  396. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  397. Content: content,
  398. }); err != nil {
  399. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  400. return
  401. }
  402. flusher, ok := w.(http.Flusher)
  403. if !ok {
  404. http.Error(w, "could not get flusher", http.StatusInternalServerError)
  405. return
  406. }
  407. flusher.Flush()
  408. }
  409. // Send the stop
  410. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  411. Stop: true,
  412. Timings: Timings{
  413. PromptN: seq.n_prompt_tokens,
  414. PromptMS: float64(seq.t_start_genereration.Sub(seq.t_start_process_prompt).Milliseconds()),
  415. PredictedN: seq.n_decoded,
  416. PredictedMS: float64(time.Since(seq.t_start_genereration).Milliseconds()),
  417. },
  418. }); err != nil {
  419. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  420. return
  421. }
  422. flusher, ok := w.(http.Flusher)
  423. if !ok {
  424. http.Error(w, "could not get flusher", http.StatusInternalServerError)
  425. return
  426. }
  427. flusher.Flush()
  428. }
  429. type EmbeddingRequest struct {
  430. Content []string `json:"content"`
  431. }
  432. type EmbeddingResponse struct {
  433. Embedding [][]float32 `json:"embedding"`
  434. }
  435. // TODO (jmorganca): is it safe to do this concurrently with decoding?
  436. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  437. var req EmbeddingRequest
  438. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  439. http.Error(w, "Bad request", http.StatusBadRequest)
  440. return
  441. }
  442. w.Header().Set("Content-Type", "application/json")
  443. slog.Debug("embedding request", "content", req.Content)
  444. seqs := make([]*Sequence, len(req.Content))
  445. embeddings := make([][]float32, len(req.Content))
  446. var processed int
  447. var err error
  448. for i, content := range req.Content {
  449. seqs[i], err = s.NewSequence(content, nil, 0, nil, nil, true)
  450. if err != nil {
  451. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  452. return
  453. }
  454. }
  455. // TODO - refactor to go routines to add seq's and drain the responses
  456. // so we don't stall until each set is iterated through
  457. for processed < len(seqs) {
  458. s.mu.Lock()
  459. for i, sq := range s.seqs {
  460. if processed >= len(seqs) {
  461. break
  462. }
  463. if sq == nil {
  464. s.seqs[i] = seqs[processed]
  465. processed += 1
  466. }
  467. }
  468. s.cond.Signal()
  469. s.mu.Unlock()
  470. for i := range processed {
  471. embeddings[i] = <-seqs[i].embedding
  472. }
  473. }
  474. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  475. Embedding: embeddings,
  476. }); err != nil {
  477. log.Println("Failed to encode result:", err)
  478. return
  479. }
  480. }
  481. type HealthResponse struct {
  482. Status string `json:"status"`
  483. Progress float32 `json:"progress"`
  484. }
  485. // TODO (jmorganca): is it safe to do this concurrently with decoding?
  486. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  487. w.Header().Set("Content-Type", "application/json")
  488. if err := json.NewEncoder(w).Encode(&HealthResponse{
  489. Status: s.status,
  490. Progress: s.progress,
  491. }); err != nil {
  492. log.Println("Failed to encode result:", err)
  493. return
  494. }
  495. }
  496. func main() {
  497. mpath := flag.String("model", "", "Path to model binary file")
  498. ppath := flag.String("mmproj", "", "Path to projector binary file")
  499. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  500. batchSize := flag.Int("batch-size", 512, "Batch size")
  501. nGpuLayers := flag.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  502. mainGpu := flag.Int("main-gpu", 0, "Main GPU")
  503. flashAttention := flag.Bool("flash-attn", false, "Enable flash attention")
  504. numCtx := flag.Int("ctx-size", 2048, "Context (or KV cache) size")
  505. lpath := flag.String("lora", "", "Path to lora layer file")
  506. port := flag.Int("port", 8080, "Port to expose the server on")
  507. threads := flag.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  508. // TODO not yet implemented but wired to keep the parsing aligned
  509. embedding := flag.Bool("embedding", false, "enable embedding vector output (default: disabled)")
  510. logDisable := flag.Bool("log-disable", false, "disables logging to a file")
  511. verbose := flag.Bool("verbose", false, "verbose output (default: disabled)")
  512. f32 := flag.Bool("memory-f32", false, "use f32 instead of f16 for memory key+value (default: disabled) not recommended: doubles context memory required and no measurable increase in quality")
  513. noMmap := flag.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  514. mlock := flag.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  515. tensorSplit := flag.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  516. flag.Parse()
  517. level := slog.LevelInfo
  518. if *verbose {
  519. level = slog.LevelDebug
  520. }
  521. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  522. Level: level,
  523. AddSource: true,
  524. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  525. if attr.Key == slog.SourceKey {
  526. source := attr.Value.Any().(*slog.Source)
  527. source.File = filepath.Base(source.File)
  528. }
  529. return attr
  530. },
  531. })
  532. slog.SetDefault(slog.New(handler))
  533. // TODO actually implement...
  534. if *embedding {
  535. slog.Warn("embeddings not yet support")
  536. }
  537. if *logDisable {
  538. slog.Info("ignoring --log-disable")
  539. }
  540. if *f32 {
  541. slog.Warn("memory-f32 not yet supported")
  542. }
  543. if *noMmap {
  544. slog.Warn("no-mmap not yet supported")
  545. }
  546. if *mlock {
  547. slog.Warn("mlock not yet supported")
  548. }
  549. if *tensorSplit != "" {
  550. slog.Warn("tensor-split not yet implemented")
  551. }
  552. server := &Server{
  553. numCtx: *numCtx,
  554. batchSize: *batchSize,
  555. parallel: *parallel,
  556. seqs: make([]*Sequence, *parallel),
  557. status: "loading",
  558. }
  559. // load the model
  560. llama.BackendInit()
  561. params := llama.NewModelParams(*nGpuLayers, *mainGpu, func(progress float32) {
  562. slog.Debug("Loading model", "progress %", math.Round(float64(progress*100)))
  563. server.progress = progress
  564. })
  565. server.model = llama.LoadModelFromFile(*mpath, params)
  566. if *lpath != "" {
  567. err := server.model.ApplyLoraFromFile(*lpath, 1.0, "", *threads)
  568. if err != nil {
  569. panic(err)
  570. }
  571. }
  572. ctxParams := llama.NewContextParams(*numCtx, *threads, *flashAttention)
  573. server.lc = llama.NewContextWithModel(server.model, ctxParams)
  574. if *ppath != "" {
  575. server.clip.cc = llama.NewClipContext(*ppath)
  576. }
  577. server.cond = sync.NewCond(&server.mu)
  578. ctx, cancel := context.WithCancel(context.Background())
  579. go server.run(ctx)
  580. addr := "127.0.0.1:" + strconv.Itoa(*port)
  581. listener, err := net.Listen("tcp", addr)
  582. if err != nil {
  583. fmt.Println("Listen error:", err)
  584. return
  585. }
  586. defer listener.Close()
  587. mux := http.NewServeMux()
  588. mux.HandleFunc("/embedding", server.embeddings)
  589. mux.HandleFunc("/completion", server.completion)
  590. mux.HandleFunc("/health", server.health)
  591. httpServer := http.Server{
  592. Handler: mux,
  593. }
  594. server.status = "ok"
  595. log.Println("Server listening on", addr)
  596. if err := httpServer.Serve(listener); err != nil {
  597. log.Fatal("server error:", err)
  598. }
  599. cancel()
  600. }