runner.go 28 KB

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