runner.go 26 KB

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