runner.go 24 KB

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