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. "unicode/utf8"
  21. "github.com/ollama/ollama/api"
  22. "github.com/ollama/ollama/llama"
  23. )
  24. // input is an element of the prompt to process, either
  25. // a token or an image embedding (generated from a vision projector)
  26. type input struct {
  27. token int
  28. // embed is an image embedding
  29. embed []float32
  30. }
  31. type Sequence struct {
  32. // number of inputs evaluated
  33. numPast int
  34. // batch index
  35. iBatch int
  36. // number of tokens predicted so far
  37. numPredicted int
  38. // prompt inputs left to evaluate
  39. inputs []input
  40. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  41. pendingResponses []string
  42. // input cache being used by this sequence
  43. cache *InputCacheSlot
  44. // does this sequence require cross-attention layers to be processed? - if we have seen
  45. // an image for certain multi-modal models
  46. crossAttention bool
  47. // channel to send responses over
  48. responses chan string
  49. // channel to stop decoding (such as if the remote connection is closed)
  50. quit chan bool
  51. // number of tokens to predict
  52. numPredict int
  53. samplingCtx *llama.SamplingContext
  54. // channel to send back the embedding if embedding only
  55. embedding chan []float32
  56. // stop sequences
  57. stop []string
  58. // number of inputs to keep at the beginning when shifting context window
  59. numKeep int
  60. // true if an embedding are to be returned instead of text generation
  61. embeddingOnly bool
  62. doneReason string
  63. // Metrics
  64. startProcessingTime time.Time
  65. startGenerationTime time.Time
  66. numDecoded int
  67. numPromptInputs int
  68. }
  69. type NewSequenceParams struct {
  70. numPredict int
  71. stop []string
  72. numKeep int
  73. samplingParams *llama.SamplingParams
  74. embedding bool
  75. }
  76. func (s *Server) NewSequence(prompt string, images []ImageData, params NewSequenceParams) (*Sequence, error) {
  77. s.ready.Wait()
  78. startTime := time.Now()
  79. inputs, err := s.inputs(prompt, images)
  80. if err != nil {
  81. return nil, fmt.Errorf("failed to process inputs: %w", err)
  82. } else if len(inputs) == 0 {
  83. return nil, errors.New("no input provided")
  84. }
  85. if params.numKeep < 0 {
  86. params.numKeep = len(inputs)
  87. }
  88. if !params.embedding {
  89. // Subtracting 4 ensures that at least 1 input can be discarded during shift
  90. params.numKeep = min(params.numKeep, s.cache.numCtx-4)
  91. params.numKeep += s.bosToken
  92. } else {
  93. // Embeddings are 1 shot - just truncate to the context window, without ever shifting
  94. params.numKeep = min(params.numKeep, s.cache.numCtx)
  95. }
  96. // truncate to fit in context window
  97. if len(inputs) > s.cache.numCtx {
  98. slog.Warn("truncating input prompt", "limit", s.cache.numCtx, "prompt", len(inputs), "numKeep", params.numKeep)
  99. newInputs := inputs[:params.numKeep]
  100. newInputs = append(newInputs, inputs[len(inputs)-s.cache.numCtx+params.numKeep:]...)
  101. inputs = newInputs
  102. }
  103. var sc *llama.SamplingContext
  104. if params.samplingParams != nil {
  105. sc = llama.NewSamplingContext(s.model, *params.samplingParams)
  106. for _, input := range inputs {
  107. if input.embed == nil {
  108. sc.Accept(input.token, false)
  109. }
  110. }
  111. }
  112. return &Sequence{
  113. inputs: inputs,
  114. numPromptInputs: len(inputs),
  115. startProcessingTime: startTime,
  116. numPredict: params.numPredict,
  117. pendingResponses: make([]string, 0),
  118. responses: make(chan string, 100),
  119. quit: make(chan bool, 1),
  120. embedding: make(chan []float32, 1),
  121. samplingCtx: sc,
  122. embeddingOnly: params.embedding,
  123. stop: params.stop,
  124. numKeep: params.numKeep,
  125. }, nil
  126. }
  127. // inputs processes the prompt and images into a list of inputs
  128. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  129. // generating image embeddings for each image
  130. func (s *Server) inputs(prompt string, images []ImageData) ([]input, error) {
  131. var inputs []input
  132. re := regexp.MustCompile(`\[img-(\d+)\]`)
  133. parts := re.Split(prompt, -1)
  134. matches := re.FindAllStringSubmatch(prompt, -1)
  135. for i, part := range parts {
  136. // text - tokenize
  137. if strings.TrimSpace(part) != "" {
  138. tokens, err := s.lc.Model().Tokenize(part, i == 0, true)
  139. if err != nil {
  140. return nil, err
  141. }
  142. for _, t := range tokens {
  143. inputs = append(inputs, input{token: t})
  144. }
  145. }
  146. // image - generate image embedding
  147. if i < len(matches) {
  148. n, _ := strconv.Atoi(matches[i][1])
  149. imageIndex := -1
  150. for j := range images {
  151. if images[j].ID == n {
  152. imageIndex = j
  153. break
  154. }
  155. }
  156. if imageIndex < 0 {
  157. return nil, fmt.Errorf("invalid image index: %d", n)
  158. }
  159. embed := s.image.NewEmbed(s.lc, images[imageIndex].Data, images[imageIndex].AspectRatioID)
  160. for _, e := range embed {
  161. inputs = append(inputs, input{embed: e})
  162. }
  163. }
  164. }
  165. return inputs, nil
  166. }
  167. type Server struct {
  168. model *llama.Model
  169. lc *llama.Context
  170. // required for image embeddings
  171. image *ImageContext
  172. // TODO (jmorganca): make this n_batch
  173. batchSize int
  174. // parallel is the number of parallel requests to handle
  175. parallel int
  176. // seqs is the list of parallel sequences being evaluated
  177. // TODO (jmorganca): this can probably be moved into run()
  178. seqs []*Sequence
  179. // KV cache
  180. cache *InputCache
  181. // does this model require a beginning of sequence token?
  182. bosToken int
  183. // next sequence for prompt processing to avoid starvation
  184. nextSeq int
  185. // is the server ready to process requests?
  186. ready sync.WaitGroup
  187. mu sync.Mutex
  188. cond *sync.Cond
  189. progress float32
  190. status ServerStatus
  191. }
  192. func (s *Server) allNil() bool {
  193. for _, item := range s.seqs {
  194. if item != nil {
  195. return false
  196. }
  197. }
  198. return true
  199. }
  200. func (s *Server) shiftContext(seq *Sequence) {
  201. numLeft := seq.numPast - seq.numKeep
  202. numDiscard := numLeft / 2
  203. slog.Debug("context limit hit - shifting", "limit", s.cache.numCtx, "numPast", seq.numPast,
  204. "numKeep", seq.numKeep, "numLeft", numLeft, "numDiscard", numDiscard)
  205. s.cache.ShiftCacheSlot(seq.cache, seq.numKeep, numDiscard, seq.numPast)
  206. seq.numPast -= numDiscard
  207. }
  208. func flushPending(seq *Sequence) bool {
  209. joined := strings.Join(seq.pendingResponses, "")
  210. seq.pendingResponses = []string{}
  211. // Check if there are any partial UTF-8 characters remaining.
  212. // We already check and queue as we are generating but some may
  213. // still make it here:
  214. // - Sequence is ending, e.g. generation limit has been hit
  215. // - Invalid characters in the middle of a string
  216. // This is a stricter check to ensure we never output invalid Unicode.
  217. for !utf8.ValidString(joined) {
  218. joined = joined[:len(joined)-1]
  219. }
  220. if len(joined) == 0 {
  221. return true
  222. }
  223. select {
  224. case seq.responses <- joined:
  225. return true
  226. case <-seq.quit:
  227. return false
  228. }
  229. }
  230. func (s *Server) removeSequence(seqIndex int, reason string) {
  231. seq := s.seqs[seqIndex]
  232. flushPending(seq)
  233. seq.doneReason = reason
  234. close(seq.responses)
  235. close(seq.embedding)
  236. seq.cache.InUse = false
  237. s.seqs[seqIndex] = nil
  238. }
  239. func (s *Server) run(ctx context.Context) {
  240. s.ready.Wait()
  241. // Logically these batches are used only within the context of processBatch
  242. // but it is better for performance to allocate them once here
  243. tokenBatch := llama.NewBatch(s.batchSize, len(s.seqs), 0)
  244. defer tokenBatch.Free()
  245. var embedBatch *llama.Batch
  246. embedBatchSize := s.image.BatchSize(s.batchSize)
  247. if embedBatchSize != 0 {
  248. embedBatch = llama.NewBatch(embedBatchSize, len(s.seqs), s.image.EmbedSize(s.lc))
  249. defer embedBatch.Free()
  250. } else {
  251. embedBatch = &llama.Batch{}
  252. }
  253. for {
  254. select {
  255. case <-ctx.Done():
  256. return
  257. default:
  258. s.processBatch(tokenBatch, embedBatch)
  259. tokenBatch.Clear()
  260. embedBatch.Clear()
  261. }
  262. }
  263. }
  264. // TODO (jmorganca): processBatch should be simplified, removing:
  265. // * sampling
  266. // * stop token checking
  267. // * metrics
  268. // these should instead be handled by the handlers
  269. // it should only be responsible for accepting tokens or embeddings and
  270. // processing batches as fast as possible
  271. func (s *Server) processBatch(tokenBatch *llama.Batch, embedBatch *llama.Batch) {
  272. s.mu.Lock()
  273. for s.allNil() {
  274. s.cond.Wait() // Wait until an item is added
  275. }
  276. defer s.mu.Unlock()
  277. var batch *llama.Batch
  278. crossAttention := false
  279. seqIdx := s.nextSeq - 1
  280. for range s.seqs {
  281. seqIdx = (seqIdx + 1) % len(s.seqs)
  282. seq := s.seqs[seqIdx]
  283. if seq == nil {
  284. continue
  285. }
  286. // if past the num predict limit
  287. if seq.numPredict > 0 && seq.numPredicted > seq.numPredict {
  288. s.removeSequence(seqIdx, "limit")
  289. continue
  290. }
  291. if seq.numPast+len(seq.inputs) > s.cache.numCtx {
  292. s.shiftContext(seq)
  293. }
  294. var numInputsProcessed int
  295. for i, input := range seq.inputs {
  296. embedding := input.embed != nil
  297. // If we don't currently have a batch, use one of the correct type and
  298. // fill it up as much as possible across all sequences. If we encounter an
  299. // input of the opppsite type, stop for that sequence but then pick up from
  300. // there for the next batch, ensuring that we alternate types
  301. if batch == nil {
  302. if !embedding {
  303. batch = tokenBatch
  304. } else {
  305. batch = embedBatch
  306. seq.crossAttention = s.image.NeedCrossAttention(input)
  307. }
  308. } else if embedding != batch.IsEmbedding() || crossAttention != seq.crossAttention {
  309. s.nextSeq = seqIdx
  310. break
  311. }
  312. if i >= batch.Size() {
  313. break
  314. }
  315. crossAttention = seq.crossAttention
  316. batch.Add(input.token, input.embed, seq.numPast, numInputsProcessed+1 == len(seq.inputs), seq.cache.Id)
  317. seq.numPast++
  318. numInputsProcessed++
  319. }
  320. if numInputsProcessed > 0 {
  321. seq.cache.Inputs = append(seq.cache.Inputs, seq.inputs[:numInputsProcessed]...)
  322. seq.inputs = seq.inputs[numInputsProcessed:]
  323. seq.iBatch = batch.NumTokens() - 1
  324. }
  325. }
  326. if batch == nil || batch.NumTokens() == 0 {
  327. return
  328. }
  329. s.lc.SetCrossAttention(crossAttention)
  330. err := s.lc.Decode(batch)
  331. if err != nil {
  332. slog.Error("failed to decode batch", "error", err)
  333. return
  334. }
  335. for i, seq := range s.seqs {
  336. if seq == nil {
  337. continue
  338. }
  339. // don't sample prompt processing
  340. if len(seq.inputs) != 0 {
  341. continue
  342. }
  343. seq.numDecoded += 1
  344. if seq.numDecoded == 1 {
  345. seq.startGenerationTime = time.Now()
  346. }
  347. // if done processing the prompt, generate an embedding and return
  348. if seq.embeddingOnly {
  349. embed := s.lc.GetEmbeddingsSeq(i)
  350. if embed == nil {
  351. embed = s.lc.GetEmbeddingsIth(seq.iBatch)
  352. }
  353. seq.embedding <- embed
  354. s.removeSequence(i, "")
  355. continue
  356. }
  357. // sample a token
  358. token := seq.samplingCtx.Sample(s.lc, seq.iBatch)
  359. seq.samplingCtx.Accept(token, true)
  360. piece := s.model.TokenToPiece(token)
  361. seq.numPredicted++
  362. // if it's an end of sequence token, break
  363. if s.model.TokenIsEog(token) {
  364. // TODO (jmorganca): we should send this back
  365. // as it's important for the /api/generate context
  366. // seq.responses <- piece
  367. s.removeSequence(i, "stop")
  368. continue
  369. }
  370. seq.inputs = []input{{token: token}}
  371. seq.pendingResponses = append(seq.pendingResponses, piece)
  372. sequence := strings.Join(seq.pendingResponses, "")
  373. if ok, stop := findStop(sequence, seq.stop); ok {
  374. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  375. var tokenTruncated bool
  376. origLen := len(seq.pendingResponses)
  377. seq.pendingResponses, tokenTruncated = truncateStop(seq.pendingResponses, stop)
  378. newLen := len(seq.pendingResponses)
  379. // Update the cache based on the tokens that will be returned:
  380. // - We have 1 token more than is currently in the cache because
  381. // the last one generated wasn't submitted to Decode
  382. // - Remove any stop sequences that we stripped out
  383. // - If truncateStop removed a portion of a token, drop that
  384. // - As defense-in-depth, if truncatedToken didn't find a stop token
  385. // remove the extra one that we added to the cache len
  386. tokenLen := len(seq.cache.Inputs) + 1
  387. tokenLen -= origLen - newLen
  388. if tokenTruncated || origLen == newLen {
  389. tokenLen--
  390. }
  391. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  392. s.removeSequence(i, "stop")
  393. continue
  394. }
  395. if containsStopSuffix(sequence, seq.stop) {
  396. continue
  397. }
  398. if incompleteUnicode(sequence) {
  399. continue
  400. }
  401. if !flushPending(seq) {
  402. s.removeSequence(i, "connection")
  403. }
  404. }
  405. }
  406. // TODO (jmorganca): use structs from the api package to avoid duplication
  407. // this way the api acts as a proxy instead of using a different api for the
  408. // runner
  409. type Options struct {
  410. api.Runner
  411. NumKeep int `json:"n_keep"`
  412. Seed int `json:"seed"`
  413. NumPredict int `json:"n_predict"`
  414. TopK int `json:"top_k"`
  415. TopP float32 `json:"top_p"`
  416. MinP float32 `json:"min_p"`
  417. TFSZ float32 `json:"tfs_z"`
  418. TypicalP float32 `json:"typical_p"`
  419. RepeatLastN int `json:"repeat_last_n"`
  420. Temperature float32 `json:"temperature"`
  421. RepeatPenalty float32 `json:"repeat_penalty"`
  422. PresencePenalty float32 `json:"presence_penalty"`
  423. FrequencyPenalty float32 `json:"frequency_penalty"`
  424. Mirostat int `json:"mirostat"`
  425. MirostatTau float32 `json:"mirostat_tau"`
  426. MirostatEta float32 `json:"mirostat_eta"`
  427. PenalizeNewline bool `json:"penalize_nl"`
  428. Stop []string `json:"stop"`
  429. }
  430. type ImageData struct {
  431. Data []byte `json:"data"`
  432. ID int `json:"id"`
  433. AspectRatioID int `json:"aspect_ratio_id"`
  434. }
  435. type CompletionRequest struct {
  436. Prompt string `json:"prompt"`
  437. Images []ImageData `json:"image_data"`
  438. Grammar string `json:"grammar"`
  439. CachePrompt bool `json:"cache_prompt"`
  440. Options
  441. }
  442. type Timings struct {
  443. PredictedN int `json:"predicted_n"`
  444. PredictedMS float64 `json:"predicted_ms"`
  445. PromptN int `json:"prompt_n"`
  446. PromptMS float64 `json:"prompt_ms"`
  447. }
  448. type CompletionResponse struct {
  449. Content string `json:"content"`
  450. Stop bool `json:"stop"`
  451. Model string `json:"model,omitempty"`
  452. Prompt string `json:"prompt,omitempty"`
  453. StoppedLimit bool `json:"stopped_limit,omitempty"`
  454. PredictedN int `json:"predicted_n,omitempty"`
  455. PredictedMS float64 `json:"predicted_ms,omitempty"`
  456. PromptN int `json:"prompt_n,omitempty"`
  457. PromptMS float64 `json:"prompt_ms,omitempty"`
  458. Timings Timings `json:"timings"`
  459. }
  460. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  461. var req CompletionRequest
  462. req.Options = Options(api.DefaultOptions())
  463. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  464. http.Error(w, "Bad request", http.StatusBadRequest)
  465. return
  466. }
  467. // Set the headers to indicate streaming
  468. w.Header().Set("Content-Type", "application/json")
  469. w.Header().Set("Transfer-Encoding", "chunked")
  470. flusher, ok := w.(http.Flusher)
  471. if !ok {
  472. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  473. return
  474. }
  475. var samplingParams llama.SamplingParams
  476. samplingParams.TopK = req.TopK
  477. samplingParams.TopP = req.TopP
  478. samplingParams.MinP = req.MinP
  479. samplingParams.TfsZ = req.TFSZ
  480. samplingParams.TypicalP = req.TypicalP
  481. samplingParams.Temp = req.Temperature
  482. samplingParams.RepeatLastN = req.RepeatLastN
  483. samplingParams.PenaltyRepeat = req.RepeatPenalty
  484. samplingParams.PenaltyFreq = req.FrequencyPenalty
  485. samplingParams.PenaltyPresent = req.PresencePenalty
  486. samplingParams.Mirostat = req.Mirostat
  487. samplingParams.MirostatTau = req.MirostatTau
  488. samplingParams.MirostatEta = req.MirostatEta
  489. samplingParams.PenalizeNl = req.PenalizeNewline
  490. samplingParams.Seed = uint32(req.Seed)
  491. samplingParams.Grammar = req.Grammar
  492. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  493. numPredict: req.NumPredict,
  494. stop: req.Stop,
  495. numKeep: req.NumKeep,
  496. samplingParams: &samplingParams,
  497. embedding: false,
  498. })
  499. if err != nil {
  500. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  501. return
  502. }
  503. // TODO (jmorganca): add to sequence queue instead of
  504. // failing if a slot isn't available
  505. s.mu.Lock()
  506. for i, sq := range s.seqs {
  507. if sq == nil {
  508. seq.cache, seq.inputs, seq.numPast, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  509. if err != nil {
  510. s.mu.Unlock()
  511. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  512. return
  513. }
  514. seq.crossAttention = s.image.NeedCrossAttention(seq.cache.Inputs...)
  515. s.seqs[i] = seq
  516. s.cond.Signal()
  517. break
  518. }
  519. }
  520. s.mu.Unlock()
  521. for {
  522. select {
  523. case <-r.Context().Done():
  524. close(seq.quit)
  525. return
  526. case content, ok := <-seq.responses:
  527. if ok {
  528. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  529. Content: content,
  530. }); err != nil {
  531. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  532. close(seq.quit)
  533. return
  534. }
  535. flusher.Flush()
  536. } else {
  537. // Send the final response
  538. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  539. Stop: true,
  540. StoppedLimit: seq.doneReason == "limit",
  541. Timings: Timings{
  542. PromptN: seq.numPromptInputs,
  543. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  544. PredictedN: seq.numDecoded,
  545. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  546. },
  547. }); err != nil {
  548. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  549. }
  550. return
  551. }
  552. }
  553. }
  554. }
  555. type EmbeddingRequest struct {
  556. Content string `json:"content"`
  557. CachePrompt bool `json:"cache_prompt"`
  558. }
  559. type EmbeddingResponse struct {
  560. Embedding []float32 `json:"embedding"`
  561. }
  562. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  563. var req EmbeddingRequest
  564. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  565. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  566. return
  567. }
  568. w.Header().Set("Content-Type", "application/json")
  569. slog.Debug("embedding request", "content", req.Content)
  570. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  571. if err != nil {
  572. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  573. return
  574. }
  575. // TODO (jessegross): Wait for a free slot instead of failing and blocking forever
  576. s.mu.Lock()
  577. for i, sq := range s.seqs {
  578. if sq == nil {
  579. seq.cache, seq.inputs, seq.numPast, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  580. if err != nil {
  581. s.mu.Unlock()
  582. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  583. return
  584. }
  585. s.seqs[i] = seq
  586. s.cond.Signal()
  587. break
  588. }
  589. }
  590. s.mu.Unlock()
  591. embedding := <-seq.embedding
  592. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  593. Embedding: embedding,
  594. }); err != nil {
  595. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  596. }
  597. }
  598. type HealthResponse struct {
  599. Status string `json:"status"`
  600. Progress float32 `json:"progress"`
  601. }
  602. type ServerStatus int
  603. const (
  604. ServerStatusReady ServerStatus = iota
  605. ServerStatusLoadingModel
  606. ServerStatusError
  607. )
  608. func (s ServerStatus) ToString() string {
  609. switch s {
  610. case ServerStatusReady:
  611. return "ok"
  612. case ServerStatusLoadingModel:
  613. return "loading model"
  614. default:
  615. return "server error"
  616. }
  617. }
  618. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  619. w.Header().Set("Content-Type", "application/json")
  620. if err := json.NewEncoder(w).Encode(&HealthResponse{
  621. Status: s.status.ToString(),
  622. Progress: s.progress,
  623. }); err != nil {
  624. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  625. }
  626. }
  627. func (s *Server) loadModel(
  628. params llama.ModelParams,
  629. mpath string,
  630. lpath string,
  631. ppath string,
  632. kvSize int,
  633. flashAttention bool,
  634. threads int,
  635. multiUserCache bool,
  636. ) {
  637. llama.BackendInit()
  638. var err error
  639. s.model, err = llama.LoadModelFromFile(mpath, params)
  640. if err != nil {
  641. panic(err)
  642. }
  643. ctxParams := llama.NewContextParams(kvSize, s.batchSize*s.parallel, s.parallel, threads, flashAttention)
  644. s.lc, err = llama.NewContextWithModel(s.model, ctxParams)
  645. if err != nil {
  646. panic(err)
  647. }
  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.image, err = NewImageContext(s.lc, 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.Info("system", "info", 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. }