runner.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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 batch input.Batch
  282. for i, seq := range s.seqs {
  283. if seq == nil {
  284. continue
  285. }
  286. // if past the num predict limit
  287. if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
  288. s.removeSequence(i, "limit")
  289. continue
  290. }
  291. if !s.cache.enabled {
  292. seq.inputs = append(seq.cache.Inputs, seq.inputs...)
  293. seq.cache.Inputs = []input.Input{}
  294. }
  295. batchSize := s.batchSize
  296. for j, inp := range seq.inputs {
  297. // If we are required to put following inputs into a single batch then extend the
  298. // batch size. Since we are only extending the size the minimum amount possible, this
  299. // will cause a break if we have pending inputs.
  300. minBatch := 1 + inp.SameBatch
  301. if minBatch > batchSize {
  302. batchSize = minBatch
  303. }
  304. if len(seq.pendingInputs)+minBatch > batchSize {
  305. break
  306. }
  307. // If the sum of our working set (already processed tokens, tokens we added to this
  308. // batch, required following tokens) exceeds the context size, then trigger a shift
  309. // now so we don't have to do one later when we can't break the batch.
  310. if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+minBatch) > s.cache.numCtx {
  311. if len(seq.pendingInputs) != 0 {
  312. break
  313. }
  314. err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  315. if err != nil {
  316. return err
  317. }
  318. }
  319. batch.Inputs = append(batch.Inputs, inp.Token)
  320. if inp.Multimodal != nil {
  321. batch.Multimodal = append(batch.Multimodal, input.MultimodalIndex{Index: len(batch.Inputs) - 1, Multimodal: inp.Multimodal})
  322. }
  323. batch.Positions = append(batch.Positions, int32(len(seq.cache.Inputs)+len(seq.pendingInputs)))
  324. batch.Sequences = append(batch.Sequences, seq.cache.Id)
  325. seq.iBatch = len(batch.Outputs)
  326. if j+1 == len(seq.inputs) {
  327. batch.Outputs = append(batch.Outputs, int32(len(batch.Inputs)-1))
  328. }
  329. seq.pendingInputs = append(seq.pendingInputs, inp)
  330. }
  331. seq.inputs = seq.inputs[len(seq.pendingInputs):]
  332. }
  333. if len(batch.Inputs) == 0 {
  334. return nil
  335. }
  336. ctx := s.model.Backend().NewContext()
  337. defer ctx.Close()
  338. modelOutput, err := model.Forward(ctx, s.model, batch)
  339. if err != nil {
  340. return fmt.Errorf("failed to decode batch: %w", err)
  341. }
  342. logits := modelOutput.Floats()
  343. for i, seq := range s.seqs {
  344. if seq == nil {
  345. continue
  346. }
  347. // After calling Forward, pending inputs are now in the cache
  348. if len(seq.pendingInputs) > 0 {
  349. seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
  350. seq.pendingInputs = []input.Input{}
  351. }
  352. // don't sample prompt processing
  353. if len(seq.inputs) != 0 {
  354. if !s.cache.enabled {
  355. return errors.New("caching disabled but unable to fit entire input in a batch")
  356. }
  357. continue
  358. }
  359. seq.numPredicted++
  360. if seq.numPredicted == 1 {
  361. seq.startGenerationTime = time.Now()
  362. }
  363. // if done processing the prompt, generate an embedding and return
  364. if seq.embeddingOnly {
  365. // TODO(jessegross): Embedding support
  366. slog.Warn("generation of embedding outputs not yet supported")
  367. s.removeSequence(i, "")
  368. continue
  369. }
  370. // sample a token
  371. vocabSize := len(logits) / len(batch.Outputs)
  372. token, err := seq.sampler.Sample(logits[seq.iBatch*vocabSize : (seq.iBatch+1)*vocabSize])
  373. if err != nil {
  374. return fmt.Errorf("failed to sample token: %w", err)
  375. }
  376. // if it's an end of sequence token, break
  377. if s.model.(model.TextProcessor).Is(token, model.SpecialEOS) {
  378. // TODO (jmorganca): we should send this back
  379. // as it's important for the /api/generate context
  380. // seq.responses <- piece
  381. s.removeSequence(i, "stop")
  382. continue
  383. }
  384. piece, err := s.model.(model.TextProcessor).Decode([]int32{token})
  385. if err != nil {
  386. return err
  387. }
  388. seq.inputs = []input.Input{{Token: token}}
  389. seq.pendingResponses = append(seq.pendingResponses, piece)
  390. sequence := strings.Join(seq.pendingResponses, "")
  391. if ok, stop := common.FindStop(sequence, seq.stop); ok {
  392. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  393. var tokenTruncated bool
  394. origLen := len(seq.pendingResponses)
  395. seq.pendingResponses, tokenTruncated = common.TruncateStop(seq.pendingResponses, stop)
  396. newLen := len(seq.pendingResponses)
  397. // Update the cache based on the tokens that will be returned:
  398. // - We have 1 token more than is currently in the cache because
  399. // the last one generated wasn't submitted to Decode
  400. // - Remove any stop sequences that we stripped out
  401. // - If truncateStop removed a portion of a token, drop that
  402. // - As defense-in-depth, if truncatedToken didn't find a stop token
  403. // remove the extra one that we added to the cache len
  404. tokenLen := len(seq.cache.Inputs) + 1
  405. tokenLen -= origLen - newLen
  406. if tokenTruncated || origLen == newLen {
  407. tokenLen--
  408. }
  409. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  410. s.removeSequence(i, "stop")
  411. continue
  412. }
  413. if common.ContainsStopSuffix(sequence, seq.stop) {
  414. continue
  415. }
  416. if common.IncompleteUnicode(sequence) {
  417. continue
  418. }
  419. if !flushPending(seq) {
  420. s.removeSequence(i, "connection")
  421. }
  422. }
  423. return nil
  424. }
  425. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  426. var req llm.CompletionRequest
  427. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  428. http.Error(w, "Bad request", http.StatusBadRequest)
  429. return
  430. }
  431. if req.Options == nil {
  432. opts := api.DefaultOptions()
  433. req.Options = &opts
  434. }
  435. // Set the headers to indicate streaming
  436. w.Header().Set("Content-Type", "application/json")
  437. w.Header().Set("Transfer-Encoding", "chunked")
  438. flusher, ok := w.(http.Flusher)
  439. if !ok {
  440. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  441. return
  442. }
  443. var grammar *sample.Grammar
  444. var err error
  445. if req.Grammar != "" {
  446. grammar, err = sample.NewGrammar(s.vocab, req.Grammar)
  447. if err != nil {
  448. http.Error(w, "failed to load model vocabulary required for format", http.StatusInternalServerError)
  449. return
  450. }
  451. }
  452. sampler := sample.NewSampler(
  453. req.Options.Temperature,
  454. req.Options.TopK,
  455. req.Options.TopP,
  456. req.Options.MinP,
  457. req.Options.Seed,
  458. grammar,
  459. )
  460. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  461. numPredict: req.Options.NumPredict,
  462. stop: req.Options.Stop,
  463. numKeep: int32(req.Options.NumKeep),
  464. sampler: sampler,
  465. embedding: false,
  466. })
  467. if err != nil {
  468. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  469. return
  470. }
  471. // Ensure there is a place to put the sequence, released when removed from s.seqs
  472. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  473. if errors.Is(err, context.Canceled) {
  474. slog.Info("aborting completion request due to client closing the connection")
  475. } else {
  476. slog.Error("Failed to acquire semaphore", "error", err)
  477. }
  478. return
  479. }
  480. s.mu.Lock()
  481. found := false
  482. for i, sq := range s.seqs {
  483. if sq == nil {
  484. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs)
  485. if err != nil {
  486. s.mu.Unlock()
  487. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  488. return
  489. }
  490. s.seqs[i] = seq
  491. s.cond.Signal()
  492. found = true
  493. break
  494. }
  495. }
  496. s.mu.Unlock()
  497. if !found {
  498. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  499. return
  500. }
  501. for {
  502. select {
  503. case <-r.Context().Done():
  504. close(seq.quit)
  505. return
  506. case content, ok := <-seq.responses:
  507. if ok {
  508. if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
  509. Content: content,
  510. }); err != nil {
  511. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  512. close(seq.quit)
  513. return
  514. }
  515. flusher.Flush()
  516. } else {
  517. // Send the final response
  518. doneReason := "stop"
  519. if seq.doneReason == "limit" {
  520. doneReason = "length"
  521. }
  522. if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
  523. Done: true,
  524. DoneReason: doneReason,
  525. PromptEvalCount: seq.numPromptInputs,
  526. PromptEvalDuration: seq.startGenerationTime.Sub(seq.startProcessingTime),
  527. EvalCount: seq.numPredicted,
  528. EvalDuration: time.Since(seq.startGenerationTime),
  529. }); err != nil {
  530. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  531. }
  532. return
  533. }
  534. }
  535. }
  536. }
  537. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  538. w.Header().Set("Content-Type", "application/json")
  539. if err := json.NewEncoder(w).Encode(&llm.ServerStatusResponse{
  540. Status: s.status,
  541. Progress: s.progress,
  542. }); err != nil {
  543. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  544. }
  545. }
  546. type multiLPath []string
  547. func (m *multiLPath) Set(value string) error {
  548. *m = append(*m, value)
  549. return nil
  550. }
  551. func (m *multiLPath) String() string {
  552. return strings.Join(*m, ", ")
  553. }
  554. func (s *Server) loadModel(
  555. mpath string,
  556. params ml.BackendParams,
  557. lpath multiLPath,
  558. parallel int,
  559. kvCacheType string,
  560. kvSize int,
  561. multiUserCache bool,
  562. ) {
  563. var err error
  564. s.model, err = model.New(mpath, params)
  565. if err != nil {
  566. panic(err)
  567. }
  568. s.vocab = sample.NewVocab(mpath)
  569. // TODO(jessegross): LoRA loading
  570. if lpath.String() != "" {
  571. panic("loras are not yet implemented")
  572. }
  573. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, multiUserCache)
  574. if err != nil {
  575. panic(err)
  576. }
  577. if !s.cache.enabled && parallel > 1 {
  578. parallel = 1
  579. slog.Warn("model does not support caching, disabling parallel processing")
  580. }
  581. s.parallel = parallel
  582. s.seqs = make([]*Sequence, s.parallel)
  583. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  584. s.status = llm.ServerStatusReady
  585. s.ready.Done()
  586. }
  587. func Execute(args []string) error {
  588. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  589. mpath := fs.String("model", "", "Path to model binary file")
  590. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  591. batchSize := fs.Int("batch-size", 512, "Batch size")
  592. numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  593. mainGPU := fs.Int("main-gpu", 0, "Main GPU")
  594. flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
  595. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  596. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  597. port := fs.Int("port", 8080, "Port to expose the server on")
  598. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  599. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  600. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  601. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  602. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  603. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  604. var lpaths multiLPath
  605. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  606. fs.Usage = func() {
  607. fmt.Fprintf(fs.Output(), "Runner usage\n")
  608. fs.PrintDefaults()
  609. }
  610. if err := fs.Parse(args); err != nil {
  611. return err
  612. }
  613. level := slog.LevelInfo
  614. if *verbose {
  615. level = slog.LevelDebug
  616. }
  617. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  618. Level: level,
  619. AddSource: true,
  620. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  621. if attr.Key == slog.SourceKey {
  622. source := attr.Value.Any().(*slog.Source)
  623. source.File = filepath.Base(source.File)
  624. }
  625. return attr
  626. },
  627. })
  628. slog.SetDefault(slog.New(handler))
  629. slog.Info("starting ollama engine")
  630. server := &Server{
  631. batchSize: *batchSize,
  632. status: llm.ServerStatusLoadingModel,
  633. }
  634. // TODO(jessegross): Parameters that need to be implemented:
  635. // no-mmap
  636. // mlock
  637. var tensorSplitFloats []float32
  638. if *tensorSplit != "" {
  639. splits := strings.Split(*tensorSplit, ",")
  640. tensorSplitFloats = make([]float32, len(splits))
  641. for i, s := range splits {
  642. f, _ := strconv.ParseFloat(s, 32)
  643. tensorSplitFloats[i] = float32(f)
  644. }
  645. }
  646. params := ml.BackendParams{
  647. NumThreads: *threads,
  648. NumGPULayers: *numGPULayers,
  649. MainGPU: *mainGPU,
  650. TensorSplit: tensorSplitFloats,
  651. FlashAttention: *flashAttention,
  652. }
  653. server.ready.Add(1)
  654. go server.loadModel(*mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  655. server.cond = sync.NewCond(&server.mu)
  656. ctx, cancel := context.WithCancel(context.Background())
  657. defer cancel()
  658. go server.run(ctx)
  659. addr := "127.0.0.1:" + strconv.Itoa(*port)
  660. listener, err := net.Listen("tcp", addr)
  661. if err != nil {
  662. fmt.Println("Listen error:", err)
  663. return err
  664. }
  665. defer listener.Close()
  666. mux := http.NewServeMux()
  667. // TODO: support embeddings
  668. mux.HandleFunc("POST /embedding", func(w http.ResponseWriter, r *http.Request) {
  669. http.Error(w, "this model does not support embeddings", http.StatusNotImplemented)
  670. })
  671. mux.HandleFunc("POST /completion", server.completion)
  672. mux.HandleFunc("GET /health", server.health)
  673. httpServer := http.Server{
  674. Handler: mux,
  675. }
  676. log.Println("Server listening on", addr)
  677. if err := httpServer.Serve(listener); err != nil {
  678. log.Fatal("server error:", err)
  679. return err
  680. }
  681. return nil
  682. }