runner.go 20 KB

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