runner.go 24 KB

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