runner.go 20 KB

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