runner.go 26 KB

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