runner.go 28 KB

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