runner.go 15 KB

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