runner.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. for i, seq := range s.seqs {
  362. if seq == nil {
  363. continue
  364. }
  365. // After calling Decode, pending inputs are now in the cache
  366. if len(seq.pendingInputs) > 0 {
  367. seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
  368. seq.pendingInputs = []input{}
  369. }
  370. // don't sample prompt processing
  371. if len(seq.inputs) != 0 {
  372. continue
  373. }
  374. seq.numDecoded += 1
  375. if seq.numDecoded == 1 {
  376. seq.startGenerationTime = time.Now()
  377. }
  378. // if done processing the prompt, generate an embedding and return
  379. if seq.embeddingOnly {
  380. embed := s.lc.GetEmbeddingsSeq(seq.cache.Id)
  381. if embed == nil {
  382. embed = s.lc.GetEmbeddingsIth(seq.iBatch)
  383. }
  384. seq.embedding <- embed
  385. s.removeSequence(i, "")
  386. continue
  387. }
  388. // sample a token
  389. token := seq.samplingCtx.Sample(s.lc, seq.iBatch)
  390. seq.samplingCtx.Accept(token, true)
  391. piece := s.model.TokenToPiece(token)
  392. seq.numPredicted++
  393. // if it's an end of sequence token, break
  394. if s.model.TokenIsEog(token) {
  395. // TODO (jmorganca): we should send this back
  396. // as it's important for the /api/generate context
  397. // seq.responses <- piece
  398. s.removeSequence(i, "stop")
  399. continue
  400. }
  401. seq.inputs = []input{{token: token}}
  402. seq.pendingResponses = append(seq.pendingResponses, piece)
  403. sequence := strings.Join(seq.pendingResponses, "")
  404. if ok, stop := findStop(sequence, seq.stop); ok {
  405. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  406. var tokenTruncated bool
  407. origLen := len(seq.pendingResponses)
  408. seq.pendingResponses, tokenTruncated = truncateStop(seq.pendingResponses, stop)
  409. newLen := len(seq.pendingResponses)
  410. // Update the cache based on the tokens that will be returned:
  411. // - We have 1 token more than is currently in the cache because
  412. // the last one generated wasn't submitted to Decode
  413. // - Remove any stop sequences that we stripped out
  414. // - If truncateStop removed a portion of a token, drop that
  415. // - As defense-in-depth, if truncatedToken didn't find a stop token
  416. // remove the extra one that we added to the cache len
  417. tokenLen := len(seq.cache.Inputs) + 1
  418. tokenLen -= origLen - newLen
  419. if tokenTruncated || origLen == newLen {
  420. tokenLen--
  421. }
  422. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  423. s.removeSequence(i, "stop")
  424. continue
  425. }
  426. if containsStopSuffix(sequence, seq.stop) {
  427. continue
  428. }
  429. if incompleteUnicode(sequence) {
  430. continue
  431. }
  432. if !flushPending(seq) {
  433. s.removeSequence(i, "connection")
  434. }
  435. }
  436. return nil
  437. }
  438. // TODO (jmorganca): use structs from the api package to avoid duplication
  439. // this way the api acts as a proxy instead of using a different api for the
  440. // runner
  441. type Options struct {
  442. api.Runner
  443. NumKeep int `json:"n_keep"`
  444. Seed int `json:"seed"`
  445. NumPredict int `json:"n_predict"`
  446. TopK int `json:"top_k"`
  447. TopP float32 `json:"top_p"`
  448. MinP float32 `json:"min_p"`
  449. TypicalP float32 `json:"typical_p"`
  450. RepeatLastN int `json:"repeat_last_n"`
  451. Temperature float32 `json:"temperature"`
  452. RepeatPenalty float32 `json:"repeat_penalty"`
  453. PresencePenalty float32 `json:"presence_penalty"`
  454. FrequencyPenalty float32 `json:"frequency_penalty"`
  455. Mirostat int `json:"mirostat"`
  456. MirostatTau float32 `json:"mirostat_tau"`
  457. MirostatEta float32 `json:"mirostat_eta"`
  458. Stop []string `json:"stop"`
  459. }
  460. type ImageData struct {
  461. Data []byte `json:"data"`
  462. ID int `json:"id"`
  463. AspectRatioID int `json:"aspect_ratio_id"`
  464. }
  465. type CompletionRequest struct {
  466. Prompt string `json:"prompt"`
  467. Images []ImageData `json:"image_data"`
  468. Grammar string `json:"grammar"`
  469. CachePrompt bool `json:"cache_prompt"`
  470. Options
  471. }
  472. type Timings struct {
  473. PredictedN int `json:"predicted_n"`
  474. PredictedMS float64 `json:"predicted_ms"`
  475. PromptN int `json:"prompt_n"`
  476. PromptMS float64 `json:"prompt_ms"`
  477. }
  478. type CompletionResponse struct {
  479. Content string `json:"content"`
  480. Stop bool `json:"stop"`
  481. Model string `json:"model,omitempty"`
  482. Prompt string `json:"prompt,omitempty"`
  483. StoppedLimit bool `json:"stopped_limit,omitempty"`
  484. PredictedN int `json:"predicted_n,omitempty"`
  485. PredictedMS float64 `json:"predicted_ms,omitempty"`
  486. PromptN int `json:"prompt_n,omitempty"`
  487. PromptMS float64 `json:"prompt_ms,omitempty"`
  488. Timings Timings `json:"timings"`
  489. }
  490. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  491. var req CompletionRequest
  492. req.Options = Options(api.DefaultOptions())
  493. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  494. http.Error(w, "Bad request", http.StatusBadRequest)
  495. return
  496. }
  497. // Set the headers to indicate streaming
  498. w.Header().Set("Content-Type", "application/json")
  499. w.Header().Set("Transfer-Encoding", "chunked")
  500. flusher, ok := w.(http.Flusher)
  501. if !ok {
  502. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  503. return
  504. }
  505. var samplingParams llama.SamplingParams
  506. samplingParams.TopK = req.TopK
  507. samplingParams.TopP = req.TopP
  508. samplingParams.MinP = req.MinP
  509. samplingParams.TypicalP = req.TypicalP
  510. samplingParams.Temp = req.Temperature
  511. samplingParams.RepeatLastN = req.RepeatLastN
  512. samplingParams.PenaltyRepeat = req.RepeatPenalty
  513. samplingParams.PenaltyFreq = req.FrequencyPenalty
  514. samplingParams.PenaltyPresent = req.PresencePenalty
  515. samplingParams.Mirostat = req.Mirostat
  516. samplingParams.MirostatTau = req.MirostatTau
  517. samplingParams.MirostatEta = req.MirostatEta
  518. samplingParams.Seed = uint32(req.Seed)
  519. samplingParams.Grammar = req.Grammar
  520. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  521. numPredict: req.NumPredict,
  522. stop: req.Stop,
  523. numKeep: req.NumKeep,
  524. samplingParams: &samplingParams,
  525. embedding: false,
  526. })
  527. if err != nil {
  528. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  529. return
  530. }
  531. // Ensure there is a place to put the sequence, released when removed from s.seqs
  532. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  533. if errors.Is(err, context.Canceled) {
  534. slog.Info("aborting completion request due to client closing the connection")
  535. } else {
  536. slog.Error("Failed to acquire semaphore", "error", err)
  537. }
  538. return
  539. }
  540. s.mu.Lock()
  541. found := false
  542. for i, sq := range s.seqs {
  543. if sq == nil {
  544. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  545. if err != nil {
  546. s.mu.Unlock()
  547. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  548. return
  549. }
  550. seq.crossAttention = s.image.NeedCrossAttention(seq.cache.Inputs...)
  551. s.seqs[i] = seq
  552. s.cond.Signal()
  553. found = true
  554. break
  555. }
  556. }
  557. s.mu.Unlock()
  558. if !found {
  559. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  560. return
  561. }
  562. for {
  563. select {
  564. case <-r.Context().Done():
  565. close(seq.quit)
  566. return
  567. case content, ok := <-seq.responses:
  568. if ok {
  569. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  570. Content: content,
  571. }); err != nil {
  572. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  573. close(seq.quit)
  574. return
  575. }
  576. flusher.Flush()
  577. } else {
  578. // Send the final response
  579. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  580. Stop: true,
  581. StoppedLimit: seq.doneReason == "limit",
  582. Timings: Timings{
  583. PromptN: seq.numPromptInputs,
  584. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  585. PredictedN: seq.numDecoded,
  586. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  587. },
  588. }); err != nil {
  589. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  590. }
  591. return
  592. }
  593. }
  594. }
  595. }
  596. type EmbeddingRequest struct {
  597. Content string `json:"content"`
  598. CachePrompt bool `json:"cache_prompt"`
  599. }
  600. type EmbeddingResponse struct {
  601. Embedding []float32 `json:"embedding"`
  602. }
  603. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  604. var req EmbeddingRequest
  605. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  606. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  607. return
  608. }
  609. w.Header().Set("Content-Type", "application/json")
  610. slog.Debug("embedding request", "content", req.Content)
  611. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  612. if err != nil {
  613. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  614. return
  615. }
  616. // Ensure there is a place to put the sequence, released when removed from s.seqs
  617. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  618. if errors.Is(err, context.Canceled) {
  619. slog.Info("aborting embeddings request due to client closing the connection")
  620. } else {
  621. slog.Error("Failed to acquire semaphore", "error", err)
  622. }
  623. return
  624. }
  625. s.mu.Lock()
  626. found := false
  627. for i, sq := range s.seqs {
  628. if sq == nil {
  629. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  630. if err != nil {
  631. s.mu.Unlock()
  632. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  633. return
  634. }
  635. s.seqs[i] = seq
  636. s.cond.Signal()
  637. found = true
  638. break
  639. }
  640. }
  641. s.mu.Unlock()
  642. if !found {
  643. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  644. return
  645. }
  646. embedding := <-seq.embedding
  647. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  648. Embedding: embedding,
  649. }); err != nil {
  650. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  651. }
  652. }
  653. type HealthResponse struct {
  654. Status string `json:"status"`
  655. Progress float32 `json:"progress"`
  656. }
  657. type ServerStatus int
  658. const (
  659. ServerStatusReady ServerStatus = iota
  660. ServerStatusLoadingModel
  661. ServerStatusError
  662. )
  663. func (s ServerStatus) ToString() string {
  664. switch s {
  665. case ServerStatusReady:
  666. return "ok"
  667. case ServerStatusLoadingModel:
  668. return "loading model"
  669. default:
  670. return "server error"
  671. }
  672. }
  673. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  674. w.Header().Set("Content-Type", "application/json")
  675. if err := json.NewEncoder(w).Encode(&HealthResponse{
  676. Status: s.status.ToString(),
  677. Progress: s.progress,
  678. }); err != nil {
  679. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  680. }
  681. }
  682. type multiLPath []string
  683. func (m *multiLPath) Set(value string) error {
  684. *m = append(*m, value)
  685. return nil
  686. }
  687. func (m *multiLPath) String() string {
  688. return strings.Join(*m, ", ")
  689. }
  690. func (s *Server) loadModel(
  691. params llama.ModelParams,
  692. mpath string,
  693. lpath multiLPath,
  694. ppath string,
  695. kvSize int,
  696. kvCacheType string,
  697. flashAttention bool,
  698. threads int,
  699. multiUserCache bool,
  700. ) {
  701. llama.BackendInit()
  702. var err error
  703. s.model, err = llama.LoadModelFromFile(mpath, params)
  704. if err != nil {
  705. panic(err)
  706. }
  707. ctxParams := llama.NewContextParams(kvSize, s.batchSize*s.parallel, s.parallel, threads, flashAttention, kvCacheType)
  708. s.lc, err = llama.NewContextWithModel(s.model, ctxParams)
  709. if err != nil {
  710. panic(err)
  711. }
  712. if lpath.String() != "" {
  713. for _, path := range lpath {
  714. err := s.model.ApplyLoraFromFile(s.lc, path, 1.0, threads)
  715. if err != nil {
  716. panic(err)
  717. }
  718. }
  719. }
  720. if ppath != "" {
  721. var err error
  722. s.image, err = NewImageContext(s.lc, ppath)
  723. if err != nil {
  724. panic(err)
  725. }
  726. }
  727. s.cache, err = NewInputCache(s.lc, kvSize, s.parallel, multiUserCache)
  728. if err != nil {
  729. panic(err)
  730. }
  731. s.status = ServerStatusReady
  732. s.ready.Done()
  733. }
  734. func Execute(args []string) error {
  735. if args[0] == "runner" {
  736. args = args[1:]
  737. }
  738. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  739. mpath := fs.String("model", "", "Path to model binary file")
  740. ppath := fs.String("mmproj", "", "Path to projector binary file")
  741. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  742. batchSize := fs.Int("batch-size", 512, "Batch size")
  743. nGpuLayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  744. mainGpu := fs.Int("main-gpu", 0, "Main GPU")
  745. flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
  746. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  747. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  748. port := fs.Int("port", 8080, "Port to expose the server on")
  749. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  750. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  751. noMmap := fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  752. mlock := fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  753. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  754. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  755. var lpaths multiLPath
  756. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  757. fs.Usage = func() {
  758. fmt.Fprintf(fs.Output(), "Runner usage\n")
  759. fs.PrintDefaults()
  760. }
  761. if err := fs.Parse(args); err != nil {
  762. return err
  763. }
  764. level := slog.LevelInfo
  765. if *verbose {
  766. level = slog.LevelDebug
  767. llama.EnableDebug()
  768. }
  769. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  770. Level: level,
  771. AddSource: true,
  772. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  773. if attr.Key == slog.SourceKey {
  774. source := attr.Value.Any().(*slog.Source)
  775. source.File = filepath.Base(source.File)
  776. }
  777. return attr
  778. },
  779. })
  780. slog.SetDefault(slog.New(handler))
  781. slog.Info("starting go runner")
  782. slog.Info("system", "info", llama.PrintSystemInfo(), "threads", *threads)
  783. server := &Server{
  784. batchSize: *batchSize,
  785. parallel: *parallel,
  786. seqs: make([]*Sequence, *parallel),
  787. seqsSem: semaphore.NewWeighted(int64(*parallel)),
  788. status: ServerStatusLoadingModel,
  789. }
  790. var tensorSplitFloats []float32
  791. if *tensorSplit != "" {
  792. stringFloats := regexp.MustCompile(",").Split(*tensorSplit, -1)
  793. tensorSplitFloats = make([]float32, 0, len(stringFloats))
  794. for _, s := range stringFloats {
  795. f, _ := strconv.ParseFloat(s, 32)
  796. tensorSplitFloats = append(tensorSplitFloats, float32(f))
  797. }
  798. }
  799. params := llama.ModelParams{
  800. NumGpuLayers: *nGpuLayers,
  801. MainGpu: *mainGpu,
  802. UseMmap: !*noMmap && lpaths.String() == "",
  803. UseMlock: *mlock,
  804. TensorSplit: tensorSplitFloats,
  805. Progress: func(progress float32) {
  806. server.progress = progress
  807. },
  808. }
  809. server.ready.Add(1)
  810. go server.loadModel(params, *mpath, lpaths, *ppath, *kvSize, *kvCacheType, *flashAttention, *threads, *multiUserCache)
  811. server.cond = sync.NewCond(&server.mu)
  812. ctx, cancel := context.WithCancel(context.Background())
  813. go server.run(ctx)
  814. addr := "127.0.0.1:" + strconv.Itoa(*port)
  815. listener, err := net.Listen("tcp", addr)
  816. if err != nil {
  817. fmt.Println("Listen error:", err)
  818. cancel()
  819. return err
  820. }
  821. defer listener.Close()
  822. mux := http.NewServeMux()
  823. mux.HandleFunc("/embedding", server.embeddings)
  824. mux.HandleFunc("/completion", server.completion)
  825. mux.HandleFunc("/health", server.health)
  826. httpServer := http.Server{
  827. Handler: mux,
  828. }
  829. log.Println("Server listening on", addr)
  830. if err := httpServer.Serve(listener); err != nil {
  831. log.Fatal("server error:", err)
  832. return err
  833. }
  834. cancel()
  835. return nil
  836. }