runner.go 23 KB

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