runner.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "log/slog"
  10. "net"
  11. "net/http"
  12. "os"
  13. "path/filepath"
  14. "regexp"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/ollama/ollama/api"
  21. "github.com/ollama/ollama/llama"
  22. )
  23. // input is an element of the prompt to process, either
  24. // a token or an image embedding (generated from a vision projector)
  25. type input struct {
  26. token int
  27. // embed is an image embedding
  28. embed []float32
  29. }
  30. type Sequence struct {
  31. // number of inputs evaluated
  32. numPast int
  33. // batch index
  34. iBatch int
  35. // number of tokens predicted so far
  36. numPredicted int
  37. // prompt inputs left to evaluate
  38. inputs []input
  39. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  40. pendingResponses []string
  41. // input cache being used by this sequence
  42. cache *InputCacheSlot
  43. // channel to send responses over
  44. responses chan string
  45. // channel to stop decoding (such as if the remote connection is closed)
  46. quit chan bool
  47. // number of tokens to predict
  48. numPredict int
  49. samplingCtx *llama.SamplingContext
  50. // channel to send back the embedding if embedding only
  51. embedding chan []float32
  52. // stop sequences
  53. stop []string
  54. // number of inputs to keep at the beginning when shifting context window
  55. numKeep int
  56. // true if an embedding are to be returned instead of text generation
  57. embeddingOnly bool
  58. doneReason string
  59. // Metrics
  60. startProcessingTime time.Time
  61. startGenerationTime time.Time
  62. numDecoded int
  63. numPromptInputs int
  64. }
  65. type NewSequenceParams struct {
  66. numPredict int
  67. stop []string
  68. numKeep int
  69. samplingParams *llama.SamplingParams
  70. embedding bool
  71. }
  72. func (s *Server) NewSequence(prompt string, images []ImageData, params NewSequenceParams) (*Sequence, error) {
  73. s.ready.Wait()
  74. startTime := time.Now()
  75. inputs, err := s.inputs(prompt, images)
  76. if err != nil {
  77. return nil, fmt.Errorf("failed to process inputs: %w", err)
  78. } else if len(inputs) == 0 {
  79. return nil, errors.New("no input provided")
  80. }
  81. if params.numKeep < 0 {
  82. params.numKeep = len(inputs)
  83. }
  84. if !params.embedding {
  85. // Subtracting 4 ensures that at least 1 input can be discarded during shift
  86. params.numKeep = min(params.numKeep, s.cache.numCtx-4)
  87. params.numKeep += s.bosToken
  88. } else {
  89. // Embeddings are 1 shot - just truncate to the context window, without ever shifting
  90. params.numKeep = min(params.numKeep, s.cache.numCtx)
  91. }
  92. // truncate to fit in context window
  93. if len(inputs) > s.cache.numCtx {
  94. slog.Warn("truncating input prompt", "limit", s.cache.numCtx, "prompt", len(inputs), "numKeep", params.numKeep)
  95. newInputs := inputs[:params.numKeep]
  96. newInputs = append(newInputs, inputs[len(inputs)-s.cache.numCtx+params.numKeep:]...)
  97. inputs = newInputs
  98. }
  99. var sc *llama.SamplingContext
  100. if params.samplingParams != nil {
  101. sc = llama.NewSamplingContext(s.model, *params.samplingParams)
  102. for _, input := range inputs {
  103. if input.embed == nil {
  104. sc.Accept(input.token, false)
  105. }
  106. }
  107. }
  108. return &Sequence{
  109. inputs: inputs,
  110. numPromptInputs: len(inputs),
  111. startProcessingTime: startTime,
  112. numPredict: params.numPredict,
  113. pendingResponses: make([]string, 0),
  114. responses: make(chan string, 100),
  115. quit: make(chan bool, 1),
  116. embedding: make(chan []float32, 1),
  117. samplingCtx: sc,
  118. embeddingOnly: params.embedding,
  119. stop: params.stop,
  120. numKeep: params.numKeep,
  121. }, nil
  122. }
  123. // inputs processes the prompt and images into a list of inputs
  124. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  125. // generating image embeddings for each image
  126. func (s *Server) inputs(prompt string, images []ImageData) ([]input, error) {
  127. var inputs []input
  128. re := regexp.MustCompile(`\[img-(\d+)\]`)
  129. parts := re.Split(prompt, -1)
  130. matches := re.FindAllStringSubmatch(prompt, -1)
  131. for i, part := range parts {
  132. // text - tokenize
  133. if strings.TrimSpace(part) != "" {
  134. tokens, err := s.lc.Model().Tokenize(part, i == 0, true)
  135. if err != nil {
  136. return nil, err
  137. }
  138. for _, t := range tokens {
  139. inputs = append(inputs, input{token: t})
  140. }
  141. }
  142. // image - generate image embedding
  143. if i < len(matches) {
  144. n, _ := strconv.Atoi(matches[i][1])
  145. imageIndex := -1
  146. for j := range images {
  147. if images[j].ID == n {
  148. imageIndex = j
  149. break
  150. }
  151. }
  152. if imageIndex < 0 {
  153. return nil, fmt.Errorf("invalid image index: %d", n)
  154. }
  155. hash := s.cache.HashImage(images[imageIndex].Data)
  156. // Vision models cannot be accessed concurrently
  157. s.clip.mu.Lock()
  158. embed, err := s.cache.FindImage(hash)
  159. if err != nil {
  160. embed = llama.NewLlavaImageEmbed(s.lc, s.clip.cc, images[imageIndex].Data)
  161. s.cache.AddImage(hash, embed)
  162. }
  163. s.clip.mu.Unlock()
  164. for _, e := range embed {
  165. inputs = append(inputs, input{embed: e})
  166. }
  167. }
  168. }
  169. if s.clip.cc != nil {
  170. var embed [][]float32
  171. if s.clip.cc.IsMllama && len(images) >= 1 {
  172. hash := s.cache.HashImage(images[0].Data)
  173. s.clip.mu.Lock()
  174. var err error
  175. embed, err = s.cache.FindImage(hash)
  176. if err != nil {
  177. embed = llama.NewMllamaImageEmbed(s.lc, s.clip.cc, images[0].Data, images[0].AspectRatioID)
  178. s.cache.AddImage(hash, embed)
  179. }
  180. s.clip.mu.Unlock()
  181. }
  182. s.mu.Lock()
  183. llama.MllamaSetCrossAttn(s.lc, s.clip.cc, embed)
  184. s.mu.Unlock()
  185. }
  186. return inputs, nil
  187. }
  188. type clip struct {
  189. cc *llama.ClipContext
  190. mu sync.Mutex
  191. }
  192. type Server struct {
  193. model *llama.Model
  194. lc *llama.Context
  195. // required for image embeddings
  196. clip clip
  197. batchSize int
  198. // parallel is the number of parallel requests to handle
  199. parallel int
  200. // seqs is the list of parallel sequences being evaluated
  201. // TODO (jmorganca): this can probably be moved into run()
  202. seqs []*Sequence
  203. // KV cache
  204. cache *InputCache
  205. // does this model require a beginning of sequence token?
  206. bosToken int
  207. // next sequence for prompt processing to avoid starvation
  208. nextSeq int
  209. // is the server ready to process requests?
  210. ready sync.WaitGroup
  211. mu sync.Mutex
  212. cond *sync.Cond
  213. progress float32
  214. status ServerStatus
  215. }
  216. func (s *Server) allNil() bool {
  217. for _, item := range s.seqs {
  218. if item != nil {
  219. return false
  220. }
  221. }
  222. return true
  223. }
  224. func (s *Server) shiftContext(seq *Sequence) {
  225. numLeft := seq.numPast - seq.numKeep
  226. numDiscard := numLeft / 2
  227. slog.Debug("context limit hit - shifting", "limit", s.cache.numCtx, "numPast", seq.numPast,
  228. "numKeep", seq.numKeep, "numLeft", numLeft, "numDiscard", numDiscard)
  229. s.cache.ShiftCacheSlot(seq.cache, seq.numKeep, numDiscard, seq.numPast)
  230. seq.numPast -= numDiscard
  231. }
  232. func flushPending(seq *Sequence) bool {
  233. for _, p := range seq.pendingResponses {
  234. select {
  235. case seq.responses <- p:
  236. case <-seq.quit:
  237. seq.pendingResponses = []string{}
  238. return false
  239. }
  240. }
  241. seq.pendingResponses = []string{}
  242. return true
  243. }
  244. func (s *Server) removeSequence(seqIndex int, reason string) {
  245. seq := s.seqs[seqIndex]
  246. flushPending(seq)
  247. seq.doneReason = reason
  248. close(seq.responses)
  249. close(seq.embedding)
  250. seq.cache.InUse = false
  251. if s.clip.cc != nil {
  252. llama.MllamaSetCrossAttn(s.lc, s.clip.cc, nil)
  253. }
  254. s.seqs[seqIndex] = nil
  255. }
  256. func (s *Server) run(ctx context.Context) {
  257. s.ready.Wait()
  258. // logically these batches are used only within the context of processBatch
  259. // but it is better for performance to allocate them once here
  260. tokenBatch := llama.NewBatch(s.batchSize*len(s.seqs), 0, len(s.seqs))
  261. defer tokenBatch.Free()
  262. embedBatch := llama.NewBatch(s.batchSize*len(s.seqs), s.lc.Model().NEmbd(), len(s.seqs))
  263. defer embedBatch.Free()
  264. for {
  265. select {
  266. case <-ctx.Done():
  267. return
  268. default:
  269. s.processBatch(tokenBatch, embedBatch)
  270. tokenBatch.Clear()
  271. embedBatch.Clear()
  272. }
  273. }
  274. }
  275. // TODO (jmorganca): processBatch should be simplified, removing:
  276. // * sampling
  277. // * stop token checking
  278. // * metrics
  279. // these should instead be handled by the handlers
  280. // it should only be responsible for accepting tokens or embeddings and
  281. // processing batches as fast as possible
  282. func (s *Server) processBatch(tokenBatch *llama.Batch, embedBatch *llama.Batch) {
  283. s.mu.Lock()
  284. for s.allNil() {
  285. s.cond.Wait() // Wait until an item is added
  286. }
  287. defer s.mu.Unlock()
  288. var batch *llama.Batch
  289. seqIdx := s.nextSeq - 1
  290. for range s.seqs {
  291. seqIdx = (seqIdx + 1) % len(s.seqs)
  292. seq := s.seqs[seqIdx]
  293. if seq == nil {
  294. continue
  295. }
  296. // if past the num predict limit
  297. if seq.numPredict > 0 && seq.numPredicted > seq.numPredict {
  298. s.removeSequence(seqIdx, "limit")
  299. continue
  300. }
  301. if seq.numPast+len(seq.inputs) > s.cache.numCtx {
  302. s.shiftContext(seq)
  303. }
  304. var numInputsProcessed int
  305. for i, input := range seq.inputs {
  306. embedding := input.embed != nil
  307. // If we don't currently have a batch, use one of the correct type and
  308. // fill it up as much as possible across all sequences. If we encounter an
  309. // input of the opppsite type, stop for that sequence but then pick up from
  310. // there for the next batch, ensuring that we alternate types
  311. if batch == nil {
  312. if !embedding {
  313. batch = tokenBatch
  314. } else {
  315. batch = embedBatch
  316. }
  317. } else if embedding != batch.IsEmbedding() {
  318. s.nextSeq = seqIdx
  319. break
  320. }
  321. // todo: make this n_batch
  322. if i >= s.batchSize {
  323. break
  324. }
  325. batch.Add(input.token, input.embed, seq.numPast, []int{seq.cache.Id}, numInputsProcessed+1 == len(seq.inputs))
  326. seq.numPast++
  327. numInputsProcessed++
  328. }
  329. if numInputsProcessed > 0 {
  330. seq.cache.Inputs = append(seq.cache.Inputs, seq.inputs[:numInputsProcessed]...)
  331. seq.inputs = seq.inputs[numInputsProcessed:]
  332. seq.iBatch = batch.NumTokens() - 1
  333. }
  334. }
  335. if batch == nil || batch.NumTokens() == 0 {
  336. return
  337. }
  338. err := s.lc.Decode(batch)
  339. if err != nil {
  340. slog.Error("failed to decode batch", "error", err)
  341. return
  342. }
  343. for i, seq := range s.seqs {
  344. if seq == nil {
  345. continue
  346. }
  347. // don't sample prompt processing
  348. if len(seq.inputs) != 0 {
  349. continue
  350. }
  351. seq.numDecoded += 1
  352. if seq.numDecoded == 1 {
  353. seq.startGenerationTime = time.Now()
  354. }
  355. // if done processing the prompt, generate an embedding and return
  356. if seq.embeddingOnly {
  357. embed := s.lc.GetEmbeddingsSeq(i)
  358. if embed == nil {
  359. embed = s.lc.GetEmbeddingsIth(seq.iBatch)
  360. }
  361. seq.embedding <- embed
  362. s.removeSequence(i, "")
  363. continue
  364. }
  365. // sample a token
  366. token := seq.samplingCtx.Sample(s.lc, seq.iBatch)
  367. seq.samplingCtx.Accept(token, true)
  368. piece := s.model.TokenToPiece(token)
  369. seq.numPredicted++
  370. // if it's an end of sequence token, break
  371. if s.model.TokenIsEog(token) {
  372. // TODO (jmorganca): we should send this back
  373. // as it's important for the /api/generate context
  374. // seq.responses <- piece
  375. s.removeSequence(i, "stop")
  376. continue
  377. }
  378. seq.inputs = []input{{token: token}}
  379. seq.pendingResponses = append(seq.pendingResponses, piece)
  380. sequence := strings.Join(seq.pendingResponses, "")
  381. if ok, stop := findStop(sequence, seq.stop); ok {
  382. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  383. var tokenTruncated bool
  384. origLen := len(seq.pendingResponses)
  385. seq.pendingResponses, tokenTruncated = truncateStop(seq.pendingResponses, stop)
  386. newLen := len(seq.pendingResponses)
  387. // Update the cache based on the tokens that will be returned:
  388. // - We have 1 token more than is currently in the cache because
  389. // the last one generated wasn't submitted to Decode
  390. // - Remove any stop sequences that we stripped out
  391. // - If truncateStop removed a portion of a token, drop that
  392. // - As defense-in-depth, if truncatedToken didn't find a stop token
  393. // remove the extra one that we added to the cache len
  394. tokenLen := len(seq.cache.Inputs) + 1
  395. tokenLen -= origLen - newLen
  396. if tokenTruncated || origLen == newLen {
  397. tokenLen--
  398. }
  399. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  400. s.removeSequence(i, "stop")
  401. continue
  402. }
  403. if containsStopSuffix(sequence, seq.stop) {
  404. continue
  405. }
  406. if incompleteUnicode(sequence) {
  407. continue
  408. }
  409. if !flushPending(seq) {
  410. s.removeSequence(i, "connection")
  411. }
  412. }
  413. }
  414. // TODO (jmorganca): use structs from the api package to avoid duplication
  415. // this way the api acts as a proxy instead of using a different api for the
  416. // runner
  417. type Options struct {
  418. api.Runner
  419. NumKeep int `json:"n_keep"`
  420. Seed int `json:"seed"`
  421. NumPredict int `json:"n_predict"`
  422. TopK int `json:"top_k"`
  423. TopP float32 `json:"top_p"`
  424. MinP float32 `json:"min_p"`
  425. TFSZ float32 `json:"tfs_z"`
  426. TypicalP float32 `json:"typical_p"`
  427. RepeatLastN int `json:"repeat_last_n"`
  428. Temperature float32 `json:"temperature"`
  429. RepeatPenalty float32 `json:"repeat_penalty"`
  430. PresencePenalty float32 `json:"presence_penalty"`
  431. FrequencyPenalty float32 `json:"frequency_penalty"`
  432. Mirostat int `json:"mirostat"`
  433. MirostatTau float32 `json:"mirostat_tau"`
  434. MirostatEta float32 `json:"mirostat_eta"`
  435. PenalizeNewline bool `json:"penalize_nl"`
  436. Stop []string `json:"stop"`
  437. }
  438. type ImageData struct {
  439. Data []byte `json:"data"`
  440. ID int `json:"id"`
  441. AspectRatioID int `json:"aspect_ratio_id"`
  442. }
  443. type CompletionRequest struct {
  444. Prompt string `json:"prompt"`
  445. Images []ImageData `json:"image_data"`
  446. Grammar string `json:"grammar"`
  447. CachePrompt bool `json:"cache_prompt"`
  448. Options
  449. }
  450. type Timings struct {
  451. PredictedN int `json:"predicted_n"`
  452. PredictedMS float64 `json:"predicted_ms"`
  453. PromptN int `json:"prompt_n"`
  454. PromptMS float64 `json:"prompt_ms"`
  455. }
  456. type CompletionResponse struct {
  457. Content string `json:"content"`
  458. Stop bool `json:"stop"`
  459. Model string `json:"model,omitempty"`
  460. Prompt string `json:"prompt,omitempty"`
  461. StoppedLimit bool `json:"stopped_limit,omitempty"`
  462. PredictedN int `json:"predicted_n,omitempty"`
  463. PredictedMS float64 `json:"predicted_ms,omitempty"`
  464. PromptN int `json:"prompt_n,omitempty"`
  465. PromptMS float64 `json:"prompt_ms,omitempty"`
  466. Timings Timings `json:"timings"`
  467. }
  468. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  469. var req CompletionRequest
  470. req.Options = Options(api.DefaultOptions())
  471. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  472. http.Error(w, "Bad request", http.StatusBadRequest)
  473. return
  474. }
  475. // Set the headers to indicate streaming
  476. w.Header().Set("Content-Type", "application/json")
  477. w.Header().Set("Transfer-Encoding", "chunked")
  478. flusher, ok := w.(http.Flusher)
  479. if !ok {
  480. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  481. return
  482. }
  483. var samplingParams llama.SamplingParams
  484. samplingParams.TopK = req.TopK
  485. samplingParams.TopP = req.TopP
  486. samplingParams.MinP = req.MinP
  487. samplingParams.TfsZ = req.TFSZ
  488. samplingParams.TypicalP = req.TypicalP
  489. samplingParams.Temp = req.Temperature
  490. samplingParams.RepeatLastN = req.RepeatLastN
  491. samplingParams.PenaltyRepeat = req.RepeatPenalty
  492. samplingParams.PenaltyFreq = req.FrequencyPenalty
  493. samplingParams.PenaltyPresent = req.PresencePenalty
  494. samplingParams.Mirostat = req.Mirostat
  495. samplingParams.MirostatTau = req.MirostatTau
  496. samplingParams.MirostatEta = req.MirostatEta
  497. samplingParams.PenalizeNl = req.PenalizeNewline
  498. samplingParams.Seed = uint32(req.Seed)
  499. samplingParams.Grammar = req.Grammar
  500. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  501. numPredict: req.NumPredict,
  502. stop: req.Stop,
  503. numKeep: req.NumKeep,
  504. samplingParams: &samplingParams,
  505. embedding: false,
  506. })
  507. if err != nil {
  508. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  509. return
  510. }
  511. // TODO (jmorganca): add to sequence queue instead of
  512. // failing if a slot isn't available
  513. s.mu.Lock()
  514. for i, sq := range s.seqs {
  515. if sq == nil {
  516. seq.cache, seq.inputs, seq.numPast, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  517. if err != nil {
  518. s.mu.Unlock()
  519. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  520. return
  521. }
  522. s.seqs[i] = seq
  523. s.cond.Signal()
  524. break
  525. }
  526. }
  527. s.mu.Unlock()
  528. for {
  529. select {
  530. case <-r.Context().Done():
  531. close(seq.quit)
  532. return
  533. case content, ok := <-seq.responses:
  534. if ok {
  535. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  536. Content: content,
  537. }); err != nil {
  538. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  539. close(seq.quit)
  540. return
  541. }
  542. flusher.Flush()
  543. } else {
  544. // Send the final response
  545. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  546. Stop: true,
  547. StoppedLimit: seq.doneReason == "limit",
  548. Timings: Timings{
  549. PromptN: seq.numPromptInputs,
  550. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  551. PredictedN: seq.numDecoded,
  552. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  553. },
  554. }); err != nil {
  555. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  556. }
  557. return
  558. }
  559. }
  560. }
  561. }
  562. type EmbeddingRequest struct {
  563. Content string `json:"content"`
  564. CachePrompt bool `json:"cache_prompt"`
  565. }
  566. type EmbeddingResponse struct {
  567. Embedding []float32 `json:"embedding"`
  568. }
  569. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  570. var req EmbeddingRequest
  571. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  572. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  573. return
  574. }
  575. w.Header().Set("Content-Type", "application/json")
  576. slog.Debug("embedding request", "content", req.Content)
  577. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  578. if err != nil {
  579. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  580. return
  581. }
  582. // TODO (jessegross): Wait for a free slot instead of failing and blocking forever
  583. s.mu.Lock()
  584. for i, sq := range s.seqs {
  585. if sq == nil {
  586. seq.cache, seq.inputs, seq.numPast, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  587. if err != nil {
  588. s.mu.Unlock()
  589. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  590. return
  591. }
  592. s.seqs[i] = seq
  593. s.cond.Signal()
  594. break
  595. }
  596. }
  597. s.mu.Unlock()
  598. embedding := <-seq.embedding
  599. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  600. Embedding: embedding,
  601. }); err != nil {
  602. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  603. }
  604. }
  605. type HealthResponse struct {
  606. Status string `json:"status"`
  607. Progress float32 `json:"progress"`
  608. }
  609. type ServerStatus int
  610. const (
  611. ServerStatusReady ServerStatus = iota
  612. ServerStatusLoadingModel
  613. ServerStatusError
  614. )
  615. func (s ServerStatus) ToString() string {
  616. switch s {
  617. case ServerStatusReady:
  618. return "ok"
  619. case ServerStatusLoadingModel:
  620. return "loading model"
  621. default:
  622. return "server error"
  623. }
  624. }
  625. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  626. w.Header().Set("Content-Type", "application/json")
  627. if err := json.NewEncoder(w).Encode(&HealthResponse{
  628. Status: s.status.ToString(),
  629. Progress: s.progress,
  630. }); err != nil {
  631. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  632. }
  633. }
  634. func (s *Server) loadModel(
  635. params llama.ModelParams,
  636. mpath string,
  637. lpath string,
  638. ppath string,
  639. kvSize int,
  640. flashAttention bool,
  641. threads int,
  642. multiUserCache bool,
  643. ) {
  644. llama.BackendInit()
  645. s.model = llama.LoadModelFromFile(mpath, params)
  646. ctxParams := llama.NewContextParams(kvSize, s.batchSize*s.parallel, s.parallel, threads, flashAttention)
  647. s.lc = llama.NewContextWithModel(s.model, ctxParams)
  648. if lpath != "" {
  649. err := s.model.ApplyLoraFromFile(s.lc, lpath, 1.0, threads)
  650. if err != nil {
  651. panic(err)
  652. }
  653. }
  654. if s.model.AddBOSToken() {
  655. s.bosToken = 1
  656. }
  657. if ppath != "" {
  658. var err error
  659. s.clip.cc, err = llama.NewClipContext(ppath)
  660. if err != nil {
  661. panic(err)
  662. }
  663. }
  664. s.cache = NewInputCache(s.lc, kvSize, s.parallel, multiUserCache)
  665. s.status = ServerStatusReady
  666. s.ready.Done()
  667. }
  668. func main() {
  669. mpath := flag.String("model", "", "Path to model binary file")
  670. ppath := flag.String("mmproj", "", "Path to projector binary file")
  671. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  672. batchSize := flag.Int("batch-size", 512, "Batch size")
  673. nGpuLayers := flag.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  674. mainGpu := flag.Int("main-gpu", 0, "Main GPU")
  675. flashAttention := flag.Bool("flash-attn", false, "Enable flash attention")
  676. kvSize := flag.Int("ctx-size", 2048, "Context (or KV cache) size")
  677. lpath := flag.String("lora", "", "Path to lora layer file")
  678. port := flag.Int("port", 8080, "Port to expose the server on")
  679. threads := flag.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  680. verbose := flag.Bool("verbose", false, "verbose output (default: disabled)")
  681. noMmap := flag.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  682. mlock := flag.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  683. tensorSplit := flag.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  684. multiUserCache := flag.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  685. // Expose requirements as a JSON output to stdout
  686. requirements := flag.Bool("requirements", false, "print json requirement information")
  687. // These are either ignored by llama.cpp or have no significance to us
  688. _ = flag.Bool("embedding", false, "enable embedding vector output (default: disabled)")
  689. _ = flag.Bool("log-disable", false, "disables logging to a file")
  690. _ = 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")
  691. flag.Parse()
  692. if *requirements {
  693. printRequirements(os.Stdout)
  694. return
  695. }
  696. level := slog.LevelInfo
  697. if *verbose {
  698. level = slog.LevelDebug
  699. }
  700. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  701. Level: level,
  702. AddSource: true,
  703. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  704. if attr.Key == slog.SourceKey {
  705. source := attr.Value.Any().(*slog.Source)
  706. source.File = filepath.Base(source.File)
  707. }
  708. return attr
  709. },
  710. })
  711. slog.SetDefault(slog.New(handler))
  712. slog.Info("starting go runner")
  713. slog.Debug("system info", "cpu", llama.PrintSystemInfo(), "threads", *threads)
  714. server := &Server{
  715. batchSize: *batchSize,
  716. parallel: *parallel,
  717. seqs: make([]*Sequence, *parallel),
  718. status: ServerStatusLoadingModel,
  719. }
  720. var tensorSplitFloats []float32
  721. if *tensorSplit != "" {
  722. stringFloats := regexp.MustCompile(",").Split(*tensorSplit, -1)
  723. tensorSplitFloats = make([]float32, 0, len(stringFloats))
  724. for _, s := range stringFloats {
  725. f, _ := strconv.ParseFloat(s, 32)
  726. tensorSplitFloats = append(tensorSplitFloats, float32(f))
  727. }
  728. }
  729. params := llama.ModelParams{
  730. NumGpuLayers: *nGpuLayers,
  731. MainGpu: *mainGpu,
  732. UseMmap: !*noMmap && *lpath == "",
  733. UseMlock: *mlock,
  734. TensorSplit: tensorSplitFloats,
  735. Progress: func(progress float32) {
  736. server.progress = progress
  737. },
  738. }
  739. server.ready.Add(1)
  740. go server.loadModel(params, *mpath, *lpath, *ppath, *kvSize, *flashAttention, *threads, *multiUserCache)
  741. server.cond = sync.NewCond(&server.mu)
  742. ctx, cancel := context.WithCancel(context.Background())
  743. go server.run(ctx)
  744. addr := "127.0.0.1:" + strconv.Itoa(*port)
  745. listener, err := net.Listen("tcp", addr)
  746. if err != nil {
  747. fmt.Println("Listen error:", err)
  748. return
  749. }
  750. defer listener.Close()
  751. mux := http.NewServeMux()
  752. mux.HandleFunc("/embedding", server.embeddings)
  753. mux.HandleFunc("/completion", server.completion)
  754. mux.HandleFunc("/health", server.health)
  755. httpServer := http.Server{
  756. Handler: mux,
  757. }
  758. log.Println("Server listening on", addr)
  759. if err := httpServer.Serve(listener); err != nil {
  760. log.Fatal("server error:", err)
  761. }
  762. cancel()
  763. }