runner.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 seq.sampler.JSONSampler != nil {
  378. _, err = seq.sampler.JSONSampler.UpdateState([]int32{token})
  379. if err != nil {
  380. return fmt.Errorf("failed to update state: %w", err)
  381. }
  382. }
  383. if seq.sampler.PythonSampler != nil {
  384. err = seq.sampler.PythonSampler.UpdateState(token)
  385. if err != nil {
  386. return fmt.Errorf("failed to update state: %w", err)
  387. }
  388. }
  389. // if it's an end of sequence token, break
  390. if s.model.(model.TextProcessor).Is(token, model.SpecialEOS) {
  391. // TODO (jmorganca): we should send this back
  392. // as it's important for the /api/generate context
  393. // seq.responses <- piece
  394. s.removeSequence(i, "stop")
  395. continue
  396. }
  397. piece, err := s.model.(model.TextProcessor).Decode([]int32{token})
  398. if err != nil {
  399. return err
  400. }
  401. seq.inputs = []input.Input{{Token: token}}
  402. seq.pendingResponses = append(seq.pendingResponses, piece)
  403. sequence := strings.Join(seq.pendingResponses, "")
  404. if ok, stop := common.FindStop(sequence, seq.stop); ok {
  405. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  406. var tokenTruncated bool
  407. origLen := len(seq.pendingResponses)
  408. seq.pendingResponses, tokenTruncated = common.TruncateStop(seq.pendingResponses, stop)
  409. newLen := len(seq.pendingResponses)
  410. // Update the cache based on the tokens that will be returned:
  411. // - We have 1 token more than is currently in the cache because
  412. // the last one generated wasn't submitted to Decode
  413. // - Remove any stop sequences that we stripped out
  414. // - If truncateStop removed a portion of a token, drop that
  415. // - As defense-in-depth, if truncatedToken didn't find a stop token
  416. // remove the extra one that we added to the cache len
  417. tokenLen := len(seq.cache.Inputs) + 1
  418. tokenLen -= origLen - newLen
  419. if tokenTruncated || origLen == newLen {
  420. tokenLen--
  421. }
  422. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  423. s.removeSequence(i, "stop")
  424. continue
  425. }
  426. if common.ContainsStopSuffix(sequence, seq.stop) {
  427. continue
  428. }
  429. if common.IncompleteUnicode(sequence) {
  430. continue
  431. }
  432. if !flushPending(seq) {
  433. s.removeSequence(i, "connection")
  434. }
  435. }
  436. return nil
  437. }
  438. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  439. var req llm.CompletionRequest
  440. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  441. http.Error(w, "Bad request", http.StatusBadRequest)
  442. return
  443. }
  444. if req.Options == nil {
  445. opts := api.DefaultOptions()
  446. req.Options = &opts
  447. }
  448. // Set the headers to indicate streaming
  449. w.Header().Set("Content-Type", "application/json")
  450. w.Header().Set("Transfer-Encoding", "chunked")
  451. flusher, ok := w.(http.Flusher)
  452. if !ok {
  453. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  454. return
  455. }
  456. var grammar *sample.Grammar
  457. var err error
  458. if req.Grammar != "" {
  459. grammar, err = sample.NewGrammar(s.vocab, req.Grammar)
  460. if err != nil {
  461. http.Error(w, "failed to load model vocabulary required for format", http.StatusInternalServerError)
  462. return
  463. }
  464. }
  465. // jsonSampler, err := sample.NewJSONSampler(s.model.(model.TextProcessor), nil)
  466. // if err != nil {
  467. // http.Error(w, "failed to load model vocabulary required for format", http.StatusInternalServerError)
  468. // return
  469. // }
  470. // jsonSampler = nil
  471. pythonSampler := &sample.PythonSampler{}
  472. functions := []sample.PythonFunction{
  473. {
  474. Name: "add_two_strings",
  475. Args: []string{"s1", "s2"},
  476. Types: []string{"string", "string"},
  477. },
  478. }
  479. pythonSampler.Init(functions, s.model.(model.TextProcessor))
  480. sampler := sample.NewSampler(
  481. req.Options.Temperature,
  482. req.Options.TopK,
  483. req.Options.TopP,
  484. req.Options.MinP,
  485. req.Options.Seed,
  486. grammar,
  487. nil,
  488. pythonSampler,
  489. // nil,
  490. )
  491. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  492. numPredict: req.Options.NumPredict,
  493. stop: req.Options.Stop,
  494. numKeep: int32(req.Options.NumKeep),
  495. sampler: sampler,
  496. embedding: false,
  497. })
  498. if err != nil {
  499. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  500. return
  501. }
  502. // Ensure there is a place to put the sequence, released when removed from s.seqs
  503. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  504. if errors.Is(err, context.Canceled) {
  505. slog.Info("aborting completion request due to client closing the connection")
  506. } else {
  507. slog.Error("Failed to acquire semaphore", "error", err)
  508. }
  509. return
  510. }
  511. s.mu.Lock()
  512. found := false
  513. for i, sq := range s.seqs {
  514. if sq == nil {
  515. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs)
  516. if err != nil {
  517. s.mu.Unlock()
  518. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  519. return
  520. }
  521. s.seqs[i] = seq
  522. s.cond.Signal()
  523. found = true
  524. break
  525. }
  526. }
  527. s.mu.Unlock()
  528. if !found {
  529. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  530. return
  531. }
  532. for {
  533. select {
  534. case <-r.Context().Done():
  535. close(seq.quit)
  536. return
  537. case content, ok := <-seq.responses:
  538. if ok {
  539. if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
  540. Content: content,
  541. }); err != nil {
  542. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  543. close(seq.quit)
  544. return
  545. }
  546. flusher.Flush()
  547. } else {
  548. // Send the final response
  549. doneReason := "stop"
  550. if seq.doneReason == "limit" {
  551. doneReason = "length"
  552. }
  553. if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
  554. Done: true,
  555. DoneReason: doneReason,
  556. PromptEvalCount: seq.numPromptInputs,
  557. PromptEvalDuration: seq.startGenerationTime.Sub(seq.startProcessingTime),
  558. EvalCount: seq.numPredicted,
  559. EvalDuration: time.Since(seq.startGenerationTime),
  560. }); err != nil {
  561. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  562. }
  563. return
  564. }
  565. }
  566. }
  567. }
  568. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  569. w.Header().Set("Content-Type", "application/json")
  570. if err := json.NewEncoder(w).Encode(&llm.ServerStatusResponse{
  571. Status: s.status,
  572. Progress: s.progress,
  573. }); err != nil {
  574. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  575. }
  576. }
  577. type multiLPath []string
  578. func (m *multiLPath) Set(value string) error {
  579. *m = append(*m, value)
  580. return nil
  581. }
  582. func (m *multiLPath) String() string {
  583. return strings.Join(*m, ", ")
  584. }
  585. func (s *Server) loadModel(
  586. ctx context.Context,
  587. mpath string,
  588. params ml.BackendParams,
  589. lpath multiLPath,
  590. parallel int,
  591. kvCacheType string,
  592. kvSize int,
  593. multiUserCache bool,
  594. ) {
  595. var err error
  596. s.model, err = model.New(ctx, mpath, params)
  597. if err != nil {
  598. panic(err)
  599. }
  600. s.vocab = sample.NewVocab(mpath)
  601. // TODO(jessegross): LoRA loading
  602. if lpath.String() != "" {
  603. panic("loras are not yet implemented")
  604. }
  605. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, s.batchSize, multiUserCache)
  606. if err != nil {
  607. panic(err)
  608. }
  609. if !s.cache.enabled && parallel > 1 {
  610. parallel = 1
  611. slog.Warn("model does not support caching, disabling parallel processing")
  612. }
  613. s.parallel = parallel
  614. s.seqs = make([]*Sequence, s.parallel)
  615. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  616. s.status = llm.ServerStatusReady
  617. s.ready.Done()
  618. }
  619. func Execute(args []string) error {
  620. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  621. mpath := fs.String("model", "", "Path to model binary file")
  622. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  623. batchSize := fs.Int("batch-size", 512, "Batch size")
  624. numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  625. mainGPU := fs.Int("main-gpu", 0, "Main GPU")
  626. flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
  627. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  628. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  629. port := fs.Int("port", 8080, "Port to expose the server on")
  630. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  631. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  632. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  633. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  634. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  635. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  636. var lpaths multiLPath
  637. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  638. fs.Usage = func() {
  639. fmt.Fprintf(fs.Output(), "Runner usage\n")
  640. fs.PrintDefaults()
  641. }
  642. if err := fs.Parse(args); err != nil {
  643. return err
  644. }
  645. level := slog.LevelInfo
  646. if *verbose {
  647. level = slog.LevelDebug
  648. }
  649. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  650. Level: level,
  651. AddSource: true,
  652. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  653. if attr.Key == slog.SourceKey {
  654. source := attr.Value.Any().(*slog.Source)
  655. source.File = filepath.Base(source.File)
  656. }
  657. return attr
  658. },
  659. })
  660. slog.SetDefault(slog.New(handler))
  661. slog.Info("starting ollama engine")
  662. server := &Server{
  663. batchSize: *batchSize,
  664. status: llm.ServerStatusLoadingModel,
  665. }
  666. // TODO(jessegross): Parameters that need to be implemented:
  667. // no-mmap
  668. // mlock
  669. var tensorSplitFloats []float32
  670. if *tensorSplit != "" {
  671. splits := strings.Split(*tensorSplit, ",")
  672. tensorSplitFloats = make([]float32, len(splits))
  673. for i, s := range splits {
  674. f, _ := strconv.ParseFloat(s, 32)
  675. tensorSplitFloats[i] = float32(f)
  676. }
  677. }
  678. params := ml.BackendParams{
  679. Progress: func(progress float32) {
  680. server.progress = progress
  681. },
  682. NumThreads: *threads,
  683. NumGPULayers: *numGPULayers,
  684. MainGPU: *mainGPU,
  685. TensorSplit: tensorSplitFloats,
  686. FlashAttention: *flashAttention,
  687. }
  688. server.ready.Add(1)
  689. ctx, cancel := context.WithCancel(context.Background())
  690. defer cancel()
  691. go server.loadModel(ctx, *mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  692. server.cond = sync.NewCond(&server.mu)
  693. go server.run(ctx)
  694. addr := "127.0.0.1:" + strconv.Itoa(*port)
  695. listener, err := net.Listen("tcp", addr)
  696. if err != nil {
  697. fmt.Println("Listen error:", err)
  698. return err
  699. }
  700. defer listener.Close()
  701. mux := http.NewServeMux()
  702. // TODO: support embeddings
  703. mux.HandleFunc("POST /embedding", func(w http.ResponseWriter, r *http.Request) {
  704. http.Error(w, "this model does not support embeddings", http.StatusNotImplemented)
  705. })
  706. mux.HandleFunc("POST /completion", server.completion)
  707. mux.HandleFunc("GET /health", server.health)
  708. httpServer := http.Server{
  709. Handler: mux,
  710. }
  711. log.Println("Server listening on", addr)
  712. if err := httpServer.Serve(listener); err != nil {
  713. log.Fatal("server error:", err)
  714. return err
  715. }
  716. return nil
  717. }