runner.go 28 KB

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