runner.go 26 KB

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