runner.go 24 KB

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