runner.go 15 KB

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