runner.go 17 KB

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