runner.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. package ollamarunner
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "image"
  10. "log"
  11. "log/slog"
  12. "net"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "unicode/utf8"
  23. "golang.org/x/sync/semaphore"
  24. "github.com/ollama/ollama/api"
  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. // input is an element of the prompt to process, either a token or an image
  31. type input struct {
  32. token int32
  33. image image.Image
  34. }
  35. type Sequence struct {
  36. // batch index
  37. iBatch int
  38. // prompt inputs left to evaluate
  39. inputs []input
  40. // inputs that have been added to a batch but not yet submitted to Forward
  41. pendingInputs []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. // set of samplers to run on generated logits
  53. samplers []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. samplers []sample.Sampler
  74. embedding bool
  75. }
  76. func (s *Server) NewSequence(prompt string, images []ImageData, params NewSequenceParams) (*Sequence, error) {
  77. s.ready.Wait()
  78. startTime := time.Now()
  79. inputs, err := s.inputs(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. 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. samplers: params.samplers,
  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(prompt string, images []ImageData) ([]input, error) {
  117. var inputs []input
  118. var parts []string
  119. var matches [][]string
  120. // TODO(jessegross): This can sometimes trigger for matching text in the
  121. // user's prompt. We previously tried to avoid it by only looking for images
  122. // on image models. We don't have a clear indication now but it would be better
  123. // to properly escape it in any case.
  124. re := regexp.MustCompile(`\[img-(\d+)\]`)
  125. parts = re.Split(prompt, -1)
  126. matches = re.FindAllStringSubmatch(prompt, -1)
  127. for i, part := range parts {
  128. // text - tokenize
  129. tokens, err := s.model.(model.TextProcessor).Encode(part)
  130. if err != nil {
  131. return nil, err
  132. }
  133. for _, t := range tokens {
  134. inputs = append(inputs, input{token: t})
  135. }
  136. // image - decode and store
  137. if i < len(matches) {
  138. n, _ := strconv.Atoi(matches[i][1])
  139. imageIndex := -1
  140. for j := range images {
  141. if images[j].ID == n {
  142. imageIndex = j
  143. break
  144. }
  145. }
  146. if imageIndex < 0 {
  147. return nil, fmt.Errorf("invalid image index: %d", n)
  148. }
  149. image, _, err := image.Decode(bytes.NewReader(images[imageIndex].Data))
  150. if err != nil {
  151. return nil, err
  152. }
  153. inputs = append(inputs, input{image: image})
  154. }
  155. }
  156. return inputs, nil
  157. }
  158. type Server struct {
  159. // is the server ready to process requests?
  160. // protects access to model and image
  161. ready sync.WaitGroup
  162. // loaded model
  163. model model.Model
  164. // status for external health reporting - loading, ready to serve, etc.
  165. status ServerStatus
  166. // current progress on loading the model
  167. progress float32
  168. // number of simultaneous requests to handle
  169. parallel int
  170. // maximum number of elements in a batch (per sequence)
  171. // TODO (jmorganca): make this n_batch
  172. batchSize int
  173. // protects access to everything below this line
  174. // this is context state needed for decoding
  175. mu sync.Mutex
  176. // indicates that data is ready for processing
  177. cond *sync.Cond
  178. // the list of simultaneous sequences being evaluated
  179. seqs []*Sequence
  180. // seqs can have a maximum of parallel entries, which
  181. // is enfoced by seqSem
  182. seqsSem *semaphore.Weighted
  183. // KV cache
  184. cache *InputCache
  185. // next sequence for prompt processing to avoid starvation
  186. nextSeq int
  187. }
  188. func (s *Server) allNil() bool {
  189. for _, item := range s.seqs {
  190. if item != nil {
  191. return false
  192. }
  193. }
  194. return true
  195. }
  196. func flushPending(seq *Sequence) bool {
  197. joined := strings.Join(seq.pendingResponses, "")
  198. seq.pendingResponses = []string{}
  199. // Check if there are any partial UTF-8 characters remaining.
  200. // We already check and queue as we are generating but some may
  201. // still make it here:
  202. // - Sequence is ending, e.g. generation limit has been hit
  203. // - Invalid characters in the middle of a string
  204. // This is a stricter check to ensure we never output invalid Unicode.
  205. for !utf8.ValidString(joined) {
  206. joined = joined[:len(joined)-1]
  207. }
  208. if len(joined) == 0 {
  209. return true
  210. }
  211. select {
  212. case seq.responses <- joined:
  213. return true
  214. case <-seq.quit:
  215. return false
  216. }
  217. }
  218. func (s *Server) removeSequence(seqIndex int, reason string) {
  219. seq := s.seqs[seqIndex]
  220. flushPending(seq)
  221. seq.doneReason = reason
  222. close(seq.responses)
  223. close(seq.embedding)
  224. seq.cache.InUse = false
  225. s.seqs[seqIndex] = nil
  226. s.seqsSem.Release(1)
  227. }
  228. func (s *Server) run(ctx context.Context) {
  229. s.ready.Wait()
  230. for {
  231. select {
  232. case <-ctx.Done():
  233. return
  234. default:
  235. err := s.processBatch()
  236. if err != nil {
  237. panic(err)
  238. }
  239. }
  240. }
  241. }
  242. func (s *Server) processBatch() error {
  243. s.mu.Lock()
  244. for s.allNil() {
  245. s.cond.Wait() // Wait until an item is added
  246. }
  247. defer s.mu.Unlock()
  248. var options model.Options
  249. imgSeq := -1
  250. seqIdx := s.nextSeq - 1
  251. for range s.seqs {
  252. seqIdx = (seqIdx + 1) % len(s.seqs)
  253. seq := s.seqs[seqIdx]
  254. if seq == nil {
  255. continue
  256. }
  257. // if past the num predict limit
  258. if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
  259. s.removeSequence(seqIdx, "limit")
  260. continue
  261. }
  262. if !s.cache.enabled {
  263. seq.inputs = append(seq.cache.Inputs, seq.inputs...)
  264. seq.cache.Inputs = []input{}
  265. }
  266. for i, input := range seq.inputs {
  267. if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+1) > s.cache.numCtx {
  268. if len(seq.pendingInputs) == 0 {
  269. err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  270. if err != nil {
  271. return err
  272. }
  273. } else {
  274. break
  275. }
  276. }
  277. if i >= s.batchSize {
  278. break
  279. }
  280. // TODO(jessegross): Image inputs need to be rethought - it's
  281. // it doesn't work well for different types of models or multiple sequences
  282. if input.image != nil {
  283. if len(seq.pendingInputs) != len(options.Images) {
  284. break
  285. }
  286. if imgSeq != seqIdx && imgSeq != -1 {
  287. s.nextSeq = seqIdx
  288. break
  289. }
  290. imgSeq = seqIdx
  291. options.Images = append(options.Images, input.image)
  292. seq.pendingInputs = append(seq.pendingInputs, input)
  293. continue
  294. }
  295. options.Inputs = append(options.Inputs, input.token)
  296. options.Positions = append(options.Positions, int32(len(seq.cache.Inputs)+len(seq.pendingInputs)))
  297. options.Sequences = append(options.Sequences, seq.cache.Id)
  298. seq.iBatch = len(options.Outputs)
  299. if i+1 == len(seq.inputs) {
  300. options.Outputs = append(options.Outputs, int32(len(options.Inputs)-1))
  301. }
  302. seq.pendingInputs = append(seq.pendingInputs, input)
  303. }
  304. seq.inputs = seq.inputs[len(seq.pendingInputs):]
  305. }
  306. if len(options.Inputs) == 0 {
  307. return nil
  308. }
  309. ctx := s.model.Backend().NewContext()
  310. defer ctx.Close()
  311. modelOutput, err := model.Forward(ctx, s.model, options)
  312. if err != nil {
  313. return fmt.Errorf("failed to decode batch: %w", err)
  314. }
  315. f32s := modelOutput.Floats()
  316. // TODO(jessegross): This will no longer be necessary once the sampling interface takes f32s
  317. logits := make([]float64, len(f32s))
  318. for i, f32 := range f32s {
  319. logits[i] = float64(f32)
  320. }
  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{}
  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. s.removeSequence(i, "")
  345. continue
  346. }
  347. // sample a token
  348. vocabSize := len(f32s) / len(options.Outputs)
  349. tokens, err := sample.Sample(logits[seq.iBatch*vocabSize:(seq.iBatch+1)*vocabSize], seq.samplers...)
  350. if err != nil {
  351. return err
  352. }
  353. // TODO(jessegross): Sampler will output a single int32 in the future
  354. token := int32(tokens[0])
  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{{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. // TODO (jmorganca): use structs from the api package to avoid duplication
  405. // this way the api acts as a proxy instead of using a different api for the
  406. // runner
  407. type Options struct {
  408. api.Runner
  409. NumKeep int `json:"n_keep"`
  410. Seed int `json:"seed"`
  411. NumPredict int `json:"n_predict"`
  412. TopK int `json:"top_k"`
  413. TopP float32 `json:"top_p"`
  414. MinP float32 `json:"min_p"`
  415. TypicalP float32 `json:"typical_p"`
  416. RepeatLastN int `json:"repeat_last_n"`
  417. Temperature float32 `json:"temperature"`
  418. RepeatPenalty float32 `json:"repeat_penalty"`
  419. PresencePenalty float32 `json:"presence_penalty"`
  420. FrequencyPenalty float32 `json:"frequency_penalty"`
  421. Mirostat int `json:"mirostat"`
  422. MirostatTau float32 `json:"mirostat_tau"`
  423. MirostatEta float32 `json:"mirostat_eta"`
  424. Stop []string `json:"stop"`
  425. }
  426. type ImageData struct {
  427. Data []byte `json:"data"`
  428. ID int `json:"id"`
  429. AspectRatioID int `json:"aspect_ratio_id"`
  430. }
  431. type CompletionRequest struct {
  432. Prompt string `json:"prompt"`
  433. Images []ImageData `json:"image_data"`
  434. Grammar string `json:"grammar"`
  435. CachePrompt bool `json:"cache_prompt"`
  436. Options
  437. }
  438. type Timings struct {
  439. PredictedN int `json:"predicted_n"`
  440. PredictedMS float64 `json:"predicted_ms"`
  441. PromptN int `json:"prompt_n"`
  442. PromptMS float64 `json:"prompt_ms"`
  443. }
  444. type CompletionResponse struct {
  445. Content string `json:"content"`
  446. Stop bool `json:"stop"`
  447. Model string `json:"model,omitempty"`
  448. Prompt string `json:"prompt,omitempty"`
  449. StoppedLimit bool `json:"stopped_limit,omitempty"`
  450. PredictedN int `json:"predicted_n,omitempty"`
  451. PredictedMS float64 `json:"predicted_ms,omitempty"`
  452. PromptN int `json:"prompt_n,omitempty"`
  453. PromptMS float64 `json:"prompt_ms,omitempty"`
  454. Timings Timings `json:"timings"`
  455. }
  456. func getSamplers(_ CompletionRequest) []sample.Sampler {
  457. // TODO(jessegross): Waiting for sampling code
  458. /*samplingParams.TopK = req.TopK
  459. samplingParams.TopP = req.TopP
  460. samplingParams.MinP = req.MinP
  461. samplingParams.TypicalP = req.TypicalP
  462. samplingParams.Temp = req.Temperature
  463. samplingParams.RepeatLastN = req.RepeatLastN
  464. samplingParams.PenaltyRepeat = req.RepeatPenalty
  465. samplingParams.PenaltyFreq = req.FrequencyPenalty
  466. samplingParams.PenaltyPresent = req.PresencePenalty
  467. samplingParams.Mirostat = req.Mirostat
  468. samplingParams.MirostatTau = req.MirostatTau
  469. samplingParams.MirostatEta = req.MirostatEta
  470. samplingParams.Seed = uint32(req.Seed)
  471. samplingParams.Grammar = req.Grammar*/
  472. return []sample.Sampler{sample.Greedy()}
  473. }
  474. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  475. var req CompletionRequest
  476. req.Options = Options(api.DefaultOptions())
  477. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  478. http.Error(w, "Bad request", http.StatusBadRequest)
  479. return
  480. }
  481. // Set the headers to indicate streaming
  482. w.Header().Set("Content-Type", "application/json")
  483. w.Header().Set("Transfer-Encoding", "chunked")
  484. flusher, ok := w.(http.Flusher)
  485. if !ok {
  486. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  487. return
  488. }
  489. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  490. numPredict: req.NumPredict,
  491. stop: req.Stop,
  492. numKeep: int32(req.NumKeep),
  493. samplers: getSamplers(req),
  494. embedding: false,
  495. })
  496. if err != nil {
  497. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  498. return
  499. }
  500. // Ensure there is a place to put the sequence, released when removed from s.seqs
  501. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  502. if errors.Is(err, context.Canceled) {
  503. slog.Info("aborting completion request due to client closing the connection")
  504. } else {
  505. slog.Error("Failed to acquire semaphore", "error", err)
  506. }
  507. return
  508. }
  509. s.mu.Lock()
  510. found := false
  511. for i, sq := range s.seqs {
  512. if sq == nil {
  513. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  514. if err != nil {
  515. s.mu.Unlock()
  516. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  517. return
  518. }
  519. s.seqs[i] = seq
  520. s.cond.Signal()
  521. found = true
  522. break
  523. }
  524. }
  525. s.mu.Unlock()
  526. if !found {
  527. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  528. return
  529. }
  530. for {
  531. select {
  532. case <-r.Context().Done():
  533. close(seq.quit)
  534. return
  535. case content, ok := <-seq.responses:
  536. if ok {
  537. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  538. Content: content,
  539. }); err != nil {
  540. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  541. close(seq.quit)
  542. return
  543. }
  544. flusher.Flush()
  545. } else {
  546. // Send the final response
  547. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  548. Stop: true,
  549. StoppedLimit: seq.doneReason == "limit",
  550. Timings: Timings{
  551. PromptN: seq.numPromptInputs,
  552. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  553. PredictedN: seq.numPredicted,
  554. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  555. },
  556. }); err != nil {
  557. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  558. }
  559. return
  560. }
  561. }
  562. }
  563. }
  564. type EmbeddingRequest struct {
  565. Content string `json:"content"`
  566. CachePrompt bool `json:"cache_prompt"`
  567. }
  568. type EmbeddingResponse struct {
  569. Embedding []float32 `json:"embedding"`
  570. }
  571. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  572. var req EmbeddingRequest
  573. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  574. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  575. return
  576. }
  577. w.Header().Set("Content-Type", "application/json")
  578. slog.Debug("embedding request", "content", req.Content)
  579. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  580. if err != nil {
  581. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  582. return
  583. }
  584. // Ensure there is a place to put the sequence, released when removed from s.seqs
  585. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  586. if errors.Is(err, context.Canceled) {
  587. slog.Info("aborting embeddings request due to client closing the connection")
  588. } else {
  589. slog.Error("Failed to acquire semaphore", "error", err)
  590. }
  591. return
  592. }
  593. s.mu.Lock()
  594. found := false
  595. for i, sq := range s.seqs {
  596. if sq == nil {
  597. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  598. if err != nil {
  599. s.mu.Unlock()
  600. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  601. return
  602. }
  603. s.seqs[i] = seq
  604. s.cond.Signal()
  605. found = true
  606. break
  607. }
  608. }
  609. s.mu.Unlock()
  610. if !found {
  611. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  612. return
  613. }
  614. embedding := <-seq.embedding
  615. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  616. Embedding: embedding,
  617. }); err != nil {
  618. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  619. }
  620. }
  621. type HealthResponse struct {
  622. Status string `json:"status"`
  623. Progress float32 `json:"progress"`
  624. }
  625. type ServerStatus int
  626. const (
  627. ServerStatusReady ServerStatus = iota
  628. ServerStatusLoadingModel
  629. ServerStatusError
  630. )
  631. func (s ServerStatus) ToString() string {
  632. switch s {
  633. case ServerStatusReady:
  634. return "ok"
  635. case ServerStatusLoadingModel:
  636. return "loading model"
  637. default:
  638. return "server error"
  639. }
  640. }
  641. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  642. w.Header().Set("Content-Type", "application/json")
  643. if err := json.NewEncoder(w).Encode(&HealthResponse{
  644. Status: s.status.ToString(),
  645. Progress: s.progress,
  646. }); err != nil {
  647. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  648. }
  649. }
  650. type multiLPath []string
  651. func (m *multiLPath) Set(value string) error {
  652. *m = append(*m, value)
  653. return nil
  654. }
  655. func (m *multiLPath) String() string {
  656. return strings.Join(*m, ", ")
  657. }
  658. func (s *Server) loadModel(
  659. mpath string,
  660. lpath multiLPath,
  661. parallel int,
  662. kvCacheType string,
  663. kvSize int,
  664. multiUserCache bool,
  665. ) {
  666. var err error
  667. s.model, err = model.New(mpath)
  668. if err != nil {
  669. panic(err)
  670. }
  671. slog.Info("system", "info", s.model.Backend().SystemInfo() /* "threads", *threads */)
  672. // TODO(jessegross): LoRA loading
  673. if lpath.String() != "" {
  674. panic("loras are not yet implemented")
  675. }
  676. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, multiUserCache)
  677. if err != nil {
  678. panic(err)
  679. }
  680. if !s.cache.enabled && parallel > 1 {
  681. parallel = 1
  682. slog.Warn("model does not support caching, disabling parallel processing")
  683. }
  684. s.parallel = parallel
  685. s.seqs = make([]*Sequence, s.parallel)
  686. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  687. s.status = ServerStatusReady
  688. s.ready.Done()
  689. }
  690. func Execute(args []string) error {
  691. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  692. mpath := fs.String("model", "", "Path to model binary file")
  693. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  694. batchSize := fs.Int("batch-size", 512, "Batch size")
  695. _ = fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  696. _ = fs.Int("main-gpu", 0, "Main GPU")
  697. _ = fs.Bool("flash-attn", false, "Enable flash attention")
  698. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  699. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  700. port := fs.Int("port", 8080, "Port to expose the server on")
  701. _ = fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  702. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  703. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  704. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  705. _ = fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  706. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  707. var lpaths multiLPath
  708. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  709. fs.Usage = func() {
  710. fmt.Fprintf(fs.Output(), "Runner usage\n")
  711. fs.PrintDefaults()
  712. }
  713. if err := fs.Parse(args); err != nil {
  714. return err
  715. }
  716. level := slog.LevelInfo
  717. if *verbose {
  718. level = slog.LevelDebug
  719. }
  720. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  721. Level: level,
  722. AddSource: true,
  723. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  724. if attr.Key == slog.SourceKey {
  725. source := attr.Value.Any().(*slog.Source)
  726. source.File = filepath.Base(source.File)
  727. }
  728. return attr
  729. },
  730. })
  731. slog.SetDefault(slog.New(handler))
  732. slog.Info("starting ollama engine")
  733. server := &Server{
  734. batchSize: *batchSize,
  735. status: ServerStatusLoadingModel,
  736. }
  737. // TODO(jessegross): Parameters that need to be implemented:
  738. // n-gpu-layers
  739. // main-gpu
  740. // flash-attn
  741. // threads
  742. // no-mmap
  743. // mlock
  744. // tensor-split
  745. /*var tensorSplitFloats []float32
  746. if *tensorSplit != "" {
  747. stringFloats := regexp.MustCompile(",").Split(*tensorSplit, -1)
  748. tensorSplitFloats = make([]float32, 0, len(stringFloats))
  749. for _, s := range stringFloats {
  750. f, _ := strconv.ParseFloat(s, 32)
  751. tensorSplitFloats = append(tensorSplitFloats, float32(f))
  752. }
  753. }*/
  754. server.ready.Add(1)
  755. go server.loadModel(*mpath, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  756. server.cond = sync.NewCond(&server.mu)
  757. ctx, cancel := context.WithCancel(context.Background())
  758. go server.run(ctx)
  759. addr := "127.0.0.1:" + strconv.Itoa(*port)
  760. listener, err := net.Listen("tcp", addr)
  761. if err != nil {
  762. fmt.Println("Listen error:", err)
  763. cancel()
  764. return err
  765. }
  766. defer listener.Close()
  767. mux := http.NewServeMux()
  768. mux.HandleFunc("/embedding", server.embeddings)
  769. mux.HandleFunc("/completion", server.completion)
  770. mux.HandleFunc("/health", server.health)
  771. httpServer := http.Server{
  772. Handler: mux,
  773. }
  774. log.Println("Server listening on", addr)
  775. if err := httpServer.Serve(listener); err != nil {
  776. log.Fatal("server error:", err)
  777. return err
  778. }
  779. cancel()
  780. return nil
  781. }