runner.go 25 KB

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