runner.go 27 KB

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