runner.go 18 KB

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