runner.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. package ollamarunner
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "flag"
  7. "fmt"
  8. "hash/maphash"
  9. "log"
  10. "log/slog"
  11. "net"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "unicode/utf8"
  22. "golang.org/x/sync/semaphore"
  23. "github.com/ollama/ollama/api"
  24. "github.com/ollama/ollama/llm"
  25. "github.com/ollama/ollama/ml"
  26. "github.com/ollama/ollama/model"
  27. "github.com/ollama/ollama/model/input"
  28. "github.com/ollama/ollama/runner/common"
  29. "github.com/ollama/ollama/sample"
  30. _ "github.com/ollama/ollama/model/models"
  31. )
  32. type contextList struct {
  33. list []ml.Context
  34. }
  35. type Sequence struct {
  36. // ctxs are used for allocating tensors that last the lifetime of the sequence, such as
  37. // multimodal embeddings
  38. ctxs *contextList
  39. // batch index
  40. iBatch int
  41. // prompt inputs left to evaluate
  42. inputs []input.Input
  43. // inputs that have been added to a batch but not yet submitted to Forward
  44. pendingInputs []input.Input
  45. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  46. pendingResponses []string
  47. // input cache being used by this sequence
  48. cache *InputCacheSlot
  49. // channel to send responses over
  50. responses chan string
  51. // channel to stop decoding (such as if the remote connection is closed)
  52. quit chan bool
  53. // number of tokens to predict
  54. numPredict int
  55. // sampler with transforms to run on generated logits
  56. sampler sample.Sampler
  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 int32
  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. numPredicted int
  70. numPromptInputs int
  71. }
  72. type NewSequenceParams struct {
  73. numPredict int
  74. stop []string
  75. numKeep int32
  76. sampler sample.Sampler
  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, ctxs, 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 = int32(len(inputs))
  90. }
  91. // TODO(jessegross): We should ensure that we always leave minBatch of context space to shift,
  92. // otherwise we might truncate or split the batch against the model's wishes
  93. // Ensure that at least 1 input can be discarded during shift
  94. params.numKeep = min(params.numKeep, s.cache.numCtx-1)
  95. if int32(len(inputs)) > s.cache.numCtx {
  96. discard := int32(len(inputs)) - s.cache.numCtx
  97. newInputs := inputs[:params.numKeep]
  98. newInputs = append(newInputs, inputs[params.numKeep+discard:]...)
  99. slog.Warn("truncating input prompt", "limit", s.cache.numCtx, "prompt", len(inputs), "keep", params.numKeep, "new", len(newInputs))
  100. inputs = newInputs
  101. }
  102. // TODO(jessegross): Ingest cached history for grammar
  103. return &Sequence{
  104. ctxs: ctxs,
  105. inputs: inputs,
  106. numPromptInputs: len(inputs),
  107. startProcessingTime: startTime,
  108. numPredict: params.numPredict,
  109. pendingResponses: make([]string, 0),
  110. responses: make(chan string, 100),
  111. quit: make(chan bool, 1),
  112. embedding: make(chan []float32, 1),
  113. sampler: params.sampler,
  114. embeddingOnly: params.embedding,
  115. stop: params.stop,
  116. numKeep: params.numKeep,
  117. }, nil
  118. }
  119. // inputs processes the prompt and images into a list of inputs
  120. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  121. // decoding images
  122. func (s *Server) inputs(prompt string, images []llm.ImageData) ([]input.Input, *contextList, error) {
  123. var inputs []input.Input
  124. var parts []string
  125. var matches [][]string
  126. multimodalProcessor, visionModel := s.model.(model.MultimodalProcessor)
  127. if visionModel {
  128. re := regexp.MustCompile(`\[img-(\d+)\]`)
  129. parts = re.Split(prompt, -1)
  130. matches = re.FindAllStringSubmatch(prompt, -1)
  131. } else {
  132. parts = []string{prompt}
  133. }
  134. var contexts contextList
  135. runtime.AddCleanup(&contexts, func(ctxs []ml.Context) {
  136. for _, ctx := range ctxs {
  137. ctx.Close()
  138. }
  139. }, contexts.list)
  140. postTokenize := false
  141. for i, part := range parts {
  142. // text - tokenize
  143. tokens, err := s.model.(model.TextProcessor).Encode(part, i == 0)
  144. if err != nil {
  145. return nil, nil, err
  146. }
  147. for _, t := range tokens {
  148. inputs = append(inputs, input.Input{Token: t})
  149. }
  150. // image - decode and store
  151. if i < len(matches) {
  152. n, _ := strconv.Atoi(matches[i][1])
  153. imageIndex := -1
  154. for j := range images {
  155. if images[j].ID == n {
  156. imageIndex = j
  157. break
  158. }
  159. }
  160. if imageIndex < 0 {
  161. return nil, nil, fmt.Errorf("invalid image index: %d", n)
  162. }
  163. ctx := s.model.Backend().NewContext()
  164. contexts.list = append(contexts.list, ctx)
  165. imageEmbeddings, err := multimodalProcessor.EncodeMultimodal(ctx, images[imageIndex].Data)
  166. if err != nil {
  167. return nil, nil, err
  168. }
  169. s.multimodalHash.Reset()
  170. _, _ = s.multimodalHash.Write(images[imageIndex].Data)
  171. imageHash := s.multimodalHash.Sum64()
  172. inputs = append(inputs, input.Input{Multimodal: imageEmbeddings, MultimodalHash: imageHash})
  173. postTokenize = true
  174. }
  175. }
  176. if visionModel && postTokenize {
  177. var err error
  178. inputs, err = multimodalProcessor.PostTokenize(inputs)
  179. if err != nil {
  180. return nil, nil, err
  181. }
  182. }
  183. return inputs, &contexts, nil
  184. }
  185. type Server struct {
  186. // is the server ready to process requests?
  187. // protects access to model and image
  188. ready sync.WaitGroup
  189. // loaded model
  190. model model.Model
  191. // status for external health reporting - loading, ready to serve, etc.
  192. status llm.ServerStatus
  193. // current progress on loading the model
  194. progress float32
  195. // number of simultaneous requests to handle
  196. parallel int
  197. // maximum number of elements in a batch (per sequence)
  198. // TODO (jmorganca): make this n_batch
  199. batchSize int
  200. // protects access to everything below this line
  201. // this is context state needed for decoding
  202. mu sync.Mutex
  203. // indicates that data is ready for processing
  204. cond *sync.Cond
  205. // the list of simultaneous sequences being evaluated
  206. seqs []*Sequence
  207. // seqs can have a maximum of parallel entries, which
  208. // is enfoced by seqSem
  209. seqsSem *semaphore.Weighted
  210. // KV cache
  211. cache *InputCache
  212. // multimodalHash generates hashes for comparing equality
  213. // of non-text data
  214. multimodalHash maphash.Hash
  215. // vocab is a llama.cpp vocab required for gammar-based
  216. // constrained generation (json mode, structured outputs)
  217. // TODO: this is temporary until Ollama sampling supports
  218. // constrained generation
  219. vocab *sample.Vocab
  220. }
  221. func (s *Server) allNil() bool {
  222. for _, item := range s.seqs {
  223. if item != nil {
  224. return false
  225. }
  226. }
  227. return true
  228. }
  229. func flushPending(seq *Sequence) bool {
  230. joined := strings.Join(seq.pendingResponses, "")
  231. seq.pendingResponses = []string{}
  232. // Check if there are any partial UTF-8 characters remaining.
  233. // We already check and queue as we are generating but some may
  234. // still make it here:
  235. // - Sequence is ending, e.g. generation limit has been hit
  236. // - Invalid characters in the middle of a string
  237. // This is a stricter check to ensure we never output invalid Unicode.
  238. for !utf8.ValidString(joined) {
  239. joined = joined[:len(joined)-1]
  240. }
  241. if len(joined) == 0 {
  242. return true
  243. }
  244. select {
  245. case seq.responses <- joined:
  246. return true
  247. case <-seq.quit:
  248. return false
  249. }
  250. }
  251. func (s *Server) removeSequence(seqIndex int, reason string) {
  252. seq := s.seqs[seqIndex]
  253. flushPending(seq)
  254. seq.doneReason = reason
  255. close(seq.responses)
  256. close(seq.embedding)
  257. seq.cache.InUse = false
  258. s.seqs[seqIndex] = nil
  259. s.seqsSem.Release(1)
  260. }
  261. func (s *Server) run(ctx context.Context) {
  262. s.ready.Wait()
  263. for {
  264. select {
  265. case <-ctx.Done():
  266. return
  267. default:
  268. err := s.processBatch()
  269. if err != nil {
  270. panic(err)
  271. }
  272. }
  273. }
  274. }
  275. func (s *Server) processBatch() error {
  276. s.mu.Lock()
  277. for s.allNil() {
  278. s.cond.Wait() // Wait until an item is added
  279. }
  280. defer s.mu.Unlock()
  281. var batchInputs []int32
  282. var batch input.Batch
  283. for i, seq := range s.seqs {
  284. if seq == nil {
  285. continue
  286. }
  287. // if past the num predict limit
  288. if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
  289. s.removeSequence(i, "limit")
  290. continue
  291. }
  292. if !s.cache.enabled {
  293. seq.inputs = append(seq.cache.Inputs, seq.inputs...)
  294. seq.cache.Inputs = []input.Input{}
  295. }
  296. batchSize := s.batchSize
  297. for j, inp := range seq.inputs {
  298. // If we are required to put following inputs into a single batch then extend the
  299. // batch size. Since we are only extending the size the minimum amount possible, this
  300. // will cause a break if we have pending inputs.
  301. minBatch := 1 + inp.SameBatch
  302. if minBatch > batchSize {
  303. batchSize = minBatch
  304. }
  305. if len(seq.pendingInputs)+minBatch > batchSize {
  306. break
  307. }
  308. // If the sum of our working set (already processed tokens, tokens we added to this
  309. // batch, required following tokens) exceeds the context size, then trigger a shift
  310. // now so we don't have to do one later when we can't break the batch.
  311. if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+minBatch) > s.cache.numCtx {
  312. if len(seq.pendingInputs) != 0 {
  313. break
  314. }
  315. err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  316. if err != nil {
  317. return err
  318. }
  319. }
  320. batchInputs = append(batchInputs, inp.Token)
  321. if inp.Multimodal != nil {
  322. batch.Multimodal = append(batch.Multimodal, input.MultimodalIndex{Index: len(batchInputs) - 1, Multimodal: inp.Multimodal})
  323. }
  324. batch.Positions = append(batch.Positions, int32(len(seq.cache.Inputs)+len(seq.pendingInputs)))
  325. batch.Sequences = append(batch.Sequences, seq.cache.Id)
  326. seq.iBatch = len(batch.Outputs)
  327. if j+1 == len(seq.inputs) {
  328. batch.Outputs = append(batch.Outputs, int32(len(batchInputs)-1))
  329. }
  330. seq.pendingInputs = append(seq.pendingInputs, inp)
  331. }
  332. seq.inputs = seq.inputs[len(seq.pendingInputs):]
  333. }
  334. if len(batchInputs) == 0 {
  335. return nil
  336. }
  337. ctx := s.model.Backend().NewContext()
  338. defer ctx.Close()
  339. modelOutput, err := model.Forward(ctx, s.model, batchInputs, batch)
  340. if err != nil {
  341. return fmt.Errorf("failed to decode batch: %w", err)
  342. }
  343. logits := modelOutput.Floats()
  344. for i, seq := range s.seqs {
  345. if seq == nil {
  346. continue
  347. }
  348. // After calling Forward, pending inputs are now in the cache
  349. if len(seq.pendingInputs) > 0 {
  350. seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
  351. seq.pendingInputs = []input.Input{}
  352. }
  353. // don't sample prompt processing
  354. if len(seq.inputs) != 0 {
  355. if !s.cache.enabled {
  356. return errors.New("caching disabled but unable to fit entire input in a batch")
  357. }
  358. continue
  359. }
  360. seq.numPredicted++
  361. if seq.numPredicted == 1 {
  362. seq.startGenerationTime = time.Now()
  363. }
  364. // if done processing the prompt, generate an embedding and return
  365. if seq.embeddingOnly {
  366. // TODO(jessegross): Embedding support
  367. slog.Warn("generation of embedding outputs not yet supported")
  368. s.removeSequence(i, "")
  369. continue
  370. }
  371. // sample a token
  372. vocabSize := len(logits) / len(batch.Outputs)
  373. token, err := seq.sampler.Sample(logits[seq.iBatch*vocabSize : (seq.iBatch+1)*vocabSize])
  374. if err != nil {
  375. return fmt.Errorf("failed to sample token: %w", err)
  376. }
  377. // if it's an end of sequence token, break
  378. if s.model.(model.TextProcessor).Is(token, model.SpecialEOS) {
  379. // TODO (jmorganca): we should send this back
  380. // as it's important for the /api/generate context
  381. // seq.responses <- piece
  382. s.removeSequence(i, "stop")
  383. continue
  384. }
  385. piece, err := s.model.(model.TextProcessor).Decode([]int32{token})
  386. if err != nil {
  387. return err
  388. }
  389. seq.inputs = []input.Input{{Token: token}}
  390. seq.pendingResponses = append(seq.pendingResponses, piece)
  391. sequence := strings.Join(seq.pendingResponses, "")
  392. if ok, stop := common.FindStop(sequence, seq.stop); ok {
  393. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  394. var tokenTruncated bool
  395. origLen := len(seq.pendingResponses)
  396. seq.pendingResponses, tokenTruncated = common.TruncateStop(seq.pendingResponses, stop)
  397. newLen := len(seq.pendingResponses)
  398. // Update the cache based on the tokens that will be returned:
  399. // - We have 1 token more than is currently in the cache because
  400. // the last one generated wasn't submitted to Decode
  401. // - Remove any stop sequences that we stripped out
  402. // - If truncateStop removed a portion of a token, drop that
  403. // - As defense-in-depth, if truncatedToken didn't find a stop token
  404. // remove the extra one that we added to the cache len
  405. tokenLen := len(seq.cache.Inputs) + 1
  406. tokenLen -= origLen - newLen
  407. if tokenTruncated || origLen == newLen {
  408. tokenLen--
  409. }
  410. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  411. s.removeSequence(i, "stop")
  412. continue
  413. }
  414. if common.ContainsStopSuffix(sequence, seq.stop) {
  415. continue
  416. }
  417. if common.IncompleteUnicode(sequence) {
  418. continue
  419. }
  420. if !flushPending(seq) {
  421. s.removeSequence(i, "connection")
  422. }
  423. }
  424. return nil
  425. }
  426. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  427. var req llm.CompletionRequest
  428. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  429. http.Error(w, "Bad request", http.StatusBadRequest)
  430. return
  431. }
  432. if req.Options == nil {
  433. opts := api.DefaultOptions()
  434. req.Options = &opts
  435. }
  436. // Set the headers to indicate streaming
  437. w.Header().Set("Content-Type", "application/json")
  438. w.Header().Set("Transfer-Encoding", "chunked")
  439. flusher, ok := w.(http.Flusher)
  440. if !ok {
  441. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  442. return
  443. }
  444. var grammar *sample.Grammar
  445. var err error
  446. if req.Grammar != "" {
  447. grammar, err = sample.NewGrammar(s.vocab, req.Grammar)
  448. if err != nil {
  449. http.Error(w, "failed to load model vocabulary required for format", http.StatusInternalServerError)
  450. return
  451. }
  452. }
  453. sampler := sample.NewSampler(
  454. req.Options.Temperature,
  455. req.Options.TopK,
  456. req.Options.TopP,
  457. req.Options.MinP,
  458. req.Options.Seed,
  459. grammar,
  460. )
  461. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  462. numPredict: req.Options.NumPredict,
  463. stop: req.Options.Stop,
  464. numKeep: int32(req.Options.NumKeep),
  465. sampler: sampler,
  466. embedding: false,
  467. })
  468. if err != nil {
  469. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  470. return
  471. }
  472. // Ensure there is a place to put the sequence, released when removed from s.seqs
  473. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  474. if errors.Is(err, context.Canceled) {
  475. slog.Info("aborting completion request due to client closing the connection")
  476. } else {
  477. slog.Error("Failed to acquire semaphore", "error", err)
  478. }
  479. return
  480. }
  481. s.mu.Lock()
  482. found := false
  483. for i, sq := range s.seqs {
  484. if sq == nil {
  485. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs)
  486. if err != nil {
  487. s.mu.Unlock()
  488. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  489. return
  490. }
  491. s.seqs[i] = seq
  492. s.cond.Signal()
  493. found = true
  494. break
  495. }
  496. }
  497. s.mu.Unlock()
  498. if !found {
  499. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  500. return
  501. }
  502. for {
  503. select {
  504. case <-r.Context().Done():
  505. close(seq.quit)
  506. return
  507. case content, ok := <-seq.responses:
  508. if ok {
  509. if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
  510. Content: content,
  511. }); err != nil {
  512. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  513. close(seq.quit)
  514. return
  515. }
  516. flusher.Flush()
  517. } else {
  518. // Send the final response
  519. doneReason := "stop"
  520. if seq.doneReason == "limit" {
  521. doneReason = "length"
  522. }
  523. if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
  524. Done: true,
  525. DoneReason: doneReason,
  526. PromptEvalCount: seq.numPromptInputs,
  527. PromptEvalDuration: seq.startGenerationTime.Sub(seq.startProcessingTime),
  528. EvalCount: seq.numPredicted,
  529. EvalDuration: time.Since(seq.startGenerationTime),
  530. }); err != nil {
  531. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  532. }
  533. return
  534. }
  535. }
  536. }
  537. }
  538. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  539. w.Header().Set("Content-Type", "application/json")
  540. if err := json.NewEncoder(w).Encode(&llm.ServerStatusResponse{
  541. Status: s.status,
  542. Progress: s.progress,
  543. }); err != nil {
  544. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  545. }
  546. }
  547. type multiLPath []string
  548. func (m *multiLPath) Set(value string) error {
  549. *m = append(*m, value)
  550. return nil
  551. }
  552. func (m *multiLPath) String() string {
  553. return strings.Join(*m, ", ")
  554. }
  555. func (s *Server) loadModel(
  556. mpath string,
  557. params ml.BackendParams,
  558. lpath multiLPath,
  559. parallel int,
  560. kvCacheType string,
  561. kvSize int,
  562. multiUserCache bool,
  563. ) {
  564. var err error
  565. s.model, err = model.New(mpath, params)
  566. if err != nil {
  567. panic(err)
  568. }
  569. s.vocab = sample.NewVocab(mpath)
  570. // TODO(jessegross): LoRA loading
  571. if lpath.String() != "" {
  572. panic("loras are not yet implemented")
  573. }
  574. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, s.batchSize, multiUserCache)
  575. if err != nil {
  576. panic(err)
  577. }
  578. if !s.cache.enabled && parallel > 1 {
  579. parallel = 1
  580. slog.Warn("model does not support caching, disabling parallel processing")
  581. }
  582. s.parallel = parallel
  583. s.seqs = make([]*Sequence, s.parallel)
  584. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  585. s.status = llm.ServerStatusReady
  586. s.ready.Done()
  587. }
  588. func Execute(args []string) error {
  589. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  590. mpath := fs.String("model", "", "Path to model binary file")
  591. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  592. batchSize := fs.Int("batch-size", 512, "Batch size")
  593. numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  594. mainGPU := fs.Int("main-gpu", 0, "Main GPU")
  595. flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
  596. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  597. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  598. port := fs.Int("port", 8080, "Port to expose the server on")
  599. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  600. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  601. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  602. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  603. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  604. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  605. var lpaths multiLPath
  606. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  607. fs.Usage = func() {
  608. fmt.Fprintf(fs.Output(), "Runner usage\n")
  609. fs.PrintDefaults()
  610. }
  611. if err := fs.Parse(args); err != nil {
  612. return err
  613. }
  614. level := slog.LevelInfo
  615. if *verbose {
  616. level = slog.LevelDebug
  617. }
  618. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  619. Level: level,
  620. AddSource: true,
  621. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  622. if attr.Key == slog.SourceKey {
  623. source := attr.Value.Any().(*slog.Source)
  624. source.File = filepath.Base(source.File)
  625. }
  626. return attr
  627. },
  628. })
  629. slog.SetDefault(slog.New(handler))
  630. slog.Info("starting ollama engine")
  631. server := &Server{
  632. batchSize: *batchSize,
  633. status: llm.ServerStatusLoadingModel,
  634. }
  635. // TODO(jessegross): Parameters that need to be implemented:
  636. // no-mmap
  637. // mlock
  638. var tensorSplitFloats []float32
  639. if *tensorSplit != "" {
  640. splits := strings.Split(*tensorSplit, ",")
  641. tensorSplitFloats = make([]float32, len(splits))
  642. for i, s := range splits {
  643. f, _ := strconv.ParseFloat(s, 32)
  644. tensorSplitFloats[i] = float32(f)
  645. }
  646. }
  647. params := ml.BackendParams{
  648. Progress: func(progress float32) {
  649. server.progress = progress
  650. },
  651. NumThreads: *threads,
  652. NumGPULayers: *numGPULayers,
  653. MainGPU: *mainGPU,
  654. TensorSplit: tensorSplitFloats,
  655. FlashAttention: *flashAttention,
  656. }
  657. server.ready.Add(1)
  658. go server.loadModel(*mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  659. server.cond = sync.NewCond(&server.mu)
  660. ctx, cancel := context.WithCancel(context.Background())
  661. defer cancel()
  662. go server.run(ctx)
  663. addr := "127.0.0.1:" + strconv.Itoa(*port)
  664. listener, err := net.Listen("tcp", addr)
  665. if err != nil {
  666. fmt.Println("Listen error:", err)
  667. return err
  668. }
  669. defer listener.Close()
  670. mux := http.NewServeMux()
  671. // TODO: support embeddings
  672. mux.HandleFunc("POST /embedding", func(w http.ResponseWriter, r *http.Request) {
  673. http.Error(w, "this model does not support embeddings", http.StatusNotImplemented)
  674. })
  675. mux.HandleFunc("POST /completion", server.completion)
  676. mux.HandleFunc("GET /health", server.health)
  677. httpServer := http.Server{
  678. Handler: mux,
  679. }
  680. log.Println("Server listening on", addr)
  681. if err := httpServer.Serve(listener); err != nil {
  682. log.Fatal("server error:", err)
  683. return err
  684. }
  685. return nil
  686. }