runner.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. package newrunner
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "image"
  10. "io"
  11. "log"
  12. "log/slog"
  13. "net"
  14. "net/http"
  15. "os"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "unicode/utf8"
  24. "golang.org/x/sync/semaphore"
  25. "github.com/ollama/ollama/api"
  26. "github.com/ollama/ollama/model"
  27. "github.com/ollama/ollama/runner/common"
  28. "github.com/ollama/ollama/sample"
  29. _ "github.com/ollama/ollama/model/llama"
  30. _ "github.com/ollama/ollama/model/mllama"
  31. )
  32. // input is an element of the prompt to process, either a token or an image
  33. type input struct {
  34. token int32
  35. image image.Image
  36. }
  37. type Sequence struct {
  38. // batch index
  39. iBatch int
  40. // prompt inputs left to evaluate
  41. inputs []input
  42. // inputs that have been added to a batch but not yet submitted to Forward
  43. pendingInputs []input
  44. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  45. pendingResponses []string
  46. // input cache being used by this sequence
  47. cache *InputCacheSlot
  48. // channel to send responses over
  49. responses chan string
  50. // channel to stop decoding (such as if the remote connection is closed)
  51. quit chan bool
  52. // number of tokens to predict
  53. numPredict int
  54. // set of samplers to run on generated logits
  55. samplers []sample.Sampler
  56. // channel to send back the embedding if embedding only
  57. embedding chan []float32
  58. // stop sequences
  59. stop []string
  60. // number of inputs to keep at the beginning when shifting context window
  61. numKeep int32
  62. // true if an embedding are to be returned instead of text generation
  63. embeddingOnly bool
  64. doneReason string
  65. // Metrics
  66. startProcessingTime time.Time
  67. startGenerationTime time.Time
  68. numPredicted int
  69. numPromptInputs int
  70. }
  71. type NewSequenceParams struct {
  72. numPredict int
  73. stop []string
  74. numKeep int32
  75. samplers []sample.Sampler
  76. embedding bool
  77. }
  78. func (s *Server) NewSequence(prompt string, images []ImageData, params NewSequenceParams) (*Sequence, error) {
  79. s.ready.Wait()
  80. startTime := time.Now()
  81. inputs, err := s.inputs(prompt, images)
  82. if err != nil {
  83. return nil, fmt.Errorf("failed to process inputs: %w", err)
  84. } else if len(inputs) == 0 {
  85. return nil, errors.New("no input provided")
  86. }
  87. if params.numKeep < 0 {
  88. params.numKeep = int32(len(inputs))
  89. }
  90. // Ensure that at least 1 input can be discarded during shift
  91. params.numKeep = min(params.numKeep, s.cache.numCtx-1)
  92. if int32(len(inputs)) > s.cache.numCtx {
  93. discard := int32(len(inputs)) - s.cache.numCtx
  94. newInputs := inputs[:params.numKeep]
  95. newInputs = append(newInputs, inputs[params.numKeep+discard:]...)
  96. slog.Warn("truncating input prompt", "limit", s.cache.numCtx, "prompt", len(inputs), "keep", params.numKeep, "new", len(newInputs))
  97. inputs = newInputs
  98. }
  99. // TODO(jessegross): Ingest cached history for grammar
  100. return &Sequence{
  101. inputs: inputs,
  102. numPromptInputs: len(inputs),
  103. startProcessingTime: startTime,
  104. numPredict: params.numPredict,
  105. pendingResponses: make([]string, 0),
  106. responses: make(chan string, 100),
  107. quit: make(chan bool, 1),
  108. embedding: make(chan []float32, 1),
  109. samplers: params.samplers,
  110. embeddingOnly: params.embedding,
  111. stop: params.stop,
  112. numKeep: params.numKeep,
  113. }, nil
  114. }
  115. // inputs processes the prompt and images into a list of inputs
  116. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  117. // decoding images
  118. func (s *Server) inputs(prompt string, images []ImageData) ([]input, error) {
  119. var inputs []input
  120. var parts []string
  121. var matches [][]string
  122. // TODO(jessegross): This can sometimes trigger for matching text in the
  123. // user's prompt. We previously tried to avoid it by only looking for images
  124. // on image models. We don't have a clear indication now but it would be better
  125. // to properly escape it in any case.
  126. re := regexp.MustCompile(`\[img-(\d+)\]`)
  127. parts = re.Split(prompt, -1)
  128. matches = re.FindAllStringSubmatch(prompt, -1)
  129. for i, part := range parts {
  130. // text - tokenize
  131. tokens, err := s.model.(model.TextProcessor).Encode(part)
  132. if err != nil {
  133. return nil, err
  134. }
  135. for _, t := range tokens {
  136. inputs = append(inputs, 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. image, _, err := image.Decode(bytes.NewReader(images[imageIndex].Data))
  152. if err != nil {
  153. return nil, err
  154. }
  155. inputs = append(inputs, input{image: image})
  156. }
  157. }
  158. return inputs, nil
  159. }
  160. type Server struct {
  161. // is the server ready to process requests?
  162. // protects access to model and image
  163. ready sync.WaitGroup
  164. // loaded model
  165. model model.Model
  166. // status for external health reporting - loading, ready to serve, etc.
  167. status ServerStatus
  168. // current progress on loading the model
  169. progress float32
  170. // number of simultaneous requests to handle
  171. parallel int
  172. // maximum number of elements in a batch (per sequence)
  173. // TODO (jmorganca): make this n_batch
  174. batchSize int
  175. // protects access to everything below this line
  176. // this is context state needed for decoding
  177. mu sync.Mutex
  178. // indicates that data is ready for processing
  179. cond *sync.Cond
  180. // the list of simultaneous sequences being evaluated
  181. seqs []*Sequence
  182. // seqs can have a maximum of parallel entries, which
  183. // is enfoced by seqSem
  184. seqsSem *semaphore.Weighted
  185. // KV cache
  186. cache *InputCache
  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 inputIDs []int32
  249. var pos []int32
  250. var outputs []int32
  251. var seqs []int
  252. var image image.Image
  253. for i, seq := range s.seqs {
  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(i, "limit")
  260. continue
  261. }
  262. for j, input := range seq.inputs {
  263. if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+1) > s.cache.numCtx {
  264. if len(seq.pendingInputs) == 0 {
  265. err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  266. if err != nil {
  267. return err
  268. }
  269. } else {
  270. break
  271. }
  272. }
  273. if j >= s.batchSize {
  274. break
  275. }
  276. if input.image != nil {
  277. if image != nil {
  278. break
  279. }
  280. image = input.image
  281. seq.pendingInputs = append(seq.pendingInputs, input)
  282. continue
  283. }
  284. inputIDs = append(inputIDs, input.token)
  285. pos = append(pos, int32(len(seq.cache.Inputs)+len(seq.pendingInputs)))
  286. seqs = append(seqs, seq.cache.Id)
  287. seq.iBatch = len(outputs)
  288. if j+1 == len(seq.inputs) {
  289. outputs = append(outputs, int32(len(inputIDs)-1))
  290. }
  291. seq.pendingInputs = append(seq.pendingInputs, input)
  292. }
  293. seq.inputs = seq.inputs[len(seq.pendingInputs):]
  294. }
  295. if len(inputIDs) == 0 {
  296. return nil
  297. }
  298. var options []model.OptionsFunc
  299. if image != nil {
  300. options = append(options, model.WithImage(image))
  301. }
  302. ctx := s.model.Backend().NewContext()
  303. defer ctx.Close()
  304. logit, err := model.Forward(ctx, s.model, append(options, model.WithCache(s.cache.cache), model.WithInputIDs(inputIDs), model.WithPositions(pos), model.WithOutputs(outputs), model.WithSequences(seqs))...)
  305. if err != nil {
  306. return err
  307. }
  308. f32s := logit.Floats()
  309. for i, seq := range s.seqs {
  310. if seq == nil {
  311. continue
  312. }
  313. // After calling Forward, pending inputs are now in the cache
  314. if len(seq.pendingInputs) > 0 {
  315. seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
  316. seq.pendingInputs = []input{}
  317. }
  318. // don't sample prompt processing
  319. if len(seq.inputs) != 0 {
  320. continue
  321. }
  322. seq.numPredicted++
  323. if seq.numPredicted == 1 {
  324. seq.startGenerationTime = time.Now()
  325. }
  326. // if done processing the prompt, generate an embedding and return
  327. if seq.embeddingOnly {
  328. /*embed := s.lc.GetEmbeddingsSeq(seq.cache.Id)
  329. if embed == nil {
  330. embed = s.lc.GetEmbeddingsIth(seq.iBatch)
  331. }
  332. seq.embedding <- embed*/
  333. s.removeSequence(i, "")
  334. continue
  335. }
  336. vocabSize := len(f32s) / len(outputs)
  337. seqLogits := f32s[seq.iBatch*vocabSize : (seq.iBatch+1)*vocabSize]
  338. // TODO(jessegross): The data type and number of outputs for the samplers seem inconsistent
  339. f64s := make([]float64, vocabSize)
  340. for j, f32 := range seqLogits {
  341. f64s[j] = float64(f32)
  342. }
  343. // do sampling
  344. f64s, err = sample.Sample(f64s, seq.samplers...)
  345. if err != nil {
  346. return err
  347. }
  348. var outputIDs []int32
  349. for _, f64 := range f64s {
  350. if !s.model.(model.TextProcessor).Is(uint32(f64), model.SpecialEOS) {
  351. outputIDs = append(outputIDs, int32(f64))
  352. } else {
  353. s.removeSequence(i, "stop")
  354. continue
  355. }
  356. }
  357. if len(outputIDs) == 0 {
  358. continue
  359. }
  360. piece, err := s.model.(model.TextProcessor).Decode(outputIDs)
  361. if errors.Is(err, io.EOF) {
  362. continue
  363. } else if err != nil {
  364. return err
  365. }
  366. for _, id := range outputIDs {
  367. seq.inputs = append(seq.inputs, input{token: id})
  368. }
  369. seq.pendingResponses = append(seq.pendingResponses, piece)
  370. sequence := strings.Join(seq.pendingResponses, "")
  371. if ok, stop := common.FindStop(sequence, seq.stop); ok {
  372. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  373. var tokenTruncated bool
  374. origLen := len(seq.pendingResponses)
  375. seq.pendingResponses, tokenTruncated = common.TruncateStop(seq.pendingResponses, stop)
  376. newLen := len(seq.pendingResponses)
  377. // Update the cache based on the tokens that will be returned:
  378. // - We have more tokens than are currently in the cache because
  379. // the last ones generated weren't submitted to Forward
  380. // - Remove any stop sequences that we stripped out
  381. // - If truncateStop removed a portion of a token, drop that
  382. // - As defense-in-depth, if truncatedToken didn't find a stop token
  383. // remove the extra ones that we added to the cache len
  384. tokenLen := len(seq.cache.Inputs) + len(outputIDs)
  385. tokenLen -= origLen - newLen
  386. if tokenTruncated {
  387. tokenLen--
  388. }
  389. if origLen == newLen {
  390. tokenLen = len(seq.cache.Inputs)
  391. }
  392. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  393. s.removeSequence(i, "stop")
  394. continue
  395. }
  396. if common.ContainsStopSuffix(sequence, seq.stop) {
  397. continue
  398. }
  399. if common.IncompleteUnicode(sequence) {
  400. continue
  401. }
  402. if !flushPending(seq) {
  403. s.removeSequence(i, "connection")
  404. }
  405. }
  406. return nil
  407. }
  408. // TODO (jmorganca): use structs from the api package to avoid duplication
  409. // this way the api acts as a proxy instead of using a different api for the
  410. // runner
  411. type Options struct {
  412. api.Runner
  413. NumKeep int `json:"n_keep"`
  414. Seed int `json:"seed"`
  415. NumPredict int `json:"n_predict"`
  416. TopK int `json:"top_k"`
  417. TopP float32 `json:"top_p"`
  418. MinP float32 `json:"min_p"`
  419. TypicalP float32 `json:"typical_p"`
  420. RepeatLastN int `json:"repeat_last_n"`
  421. Temperature float32 `json:"temperature"`
  422. RepeatPenalty float32 `json:"repeat_penalty"`
  423. PresencePenalty float32 `json:"presence_penalty"`
  424. FrequencyPenalty float32 `json:"frequency_penalty"`
  425. Mirostat int `json:"mirostat"`
  426. MirostatTau float32 `json:"mirostat_tau"`
  427. MirostatEta float32 `json:"mirostat_eta"`
  428. Stop []string `json:"stop"`
  429. }
  430. type ImageData struct {
  431. Data []byte `json:"data"`
  432. ID int `json:"id"`
  433. AspectRatioID int `json:"aspect_ratio_id"`
  434. }
  435. type CompletionRequest struct {
  436. Prompt string `json:"prompt"`
  437. Images []ImageData `json:"image_data"`
  438. Grammar string `json:"grammar"`
  439. CachePrompt bool `json:"cache_prompt"`
  440. Options
  441. }
  442. type Timings struct {
  443. PredictedN int `json:"predicted_n"`
  444. PredictedMS float64 `json:"predicted_ms"`
  445. PromptN int `json:"prompt_n"`
  446. PromptMS float64 `json:"prompt_ms"`
  447. }
  448. type CompletionResponse struct {
  449. Content string `json:"content"`
  450. Stop bool `json:"stop"`
  451. Model string `json:"model,omitempty"`
  452. Prompt string `json:"prompt,omitempty"`
  453. StoppedLimit bool `json:"stopped_limit,omitempty"`
  454. PredictedN int `json:"predicted_n,omitempty"`
  455. PredictedMS float64 `json:"predicted_ms,omitempty"`
  456. PromptN int `json:"prompt_n,omitempty"`
  457. PromptMS float64 `json:"prompt_ms,omitempty"`
  458. Timings Timings `json:"timings"`
  459. }
  460. func getSamplers(_ CompletionRequest) []sample.Sampler {
  461. // TODO(jessegross): Waiting for sampling code
  462. /*var samplingParams llama.SamplingParams
  463. samplingParams.TopK = req.TopK
  464. samplingParams.TopP = req.TopP
  465. samplingParams.MinP = req.MinP
  466. samplingParams.TypicalP = req.TypicalP
  467. samplingParams.Temp = req.Temperature
  468. samplingParams.RepeatLastN = req.RepeatLastN
  469. samplingParams.PenaltyRepeat = req.RepeatPenalty
  470. samplingParams.PenaltyFreq = req.FrequencyPenalty
  471. samplingParams.PenaltyPresent = req.PresencePenalty
  472. samplingParams.Mirostat = req.Mirostat
  473. samplingParams.MirostatTau = req.MirostatTau
  474. samplingParams.MirostatEta = req.MirostatEta
  475. samplingParams.Seed = uint32(req.Seed)
  476. samplingParams.Grammar = req.Grammar*/
  477. return []sample.Sampler{sample.Greedy()}
  478. }
  479. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  480. var req CompletionRequest
  481. req.Options = Options(api.DefaultOptions())
  482. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  483. http.Error(w, "Bad request", http.StatusBadRequest)
  484. return
  485. }
  486. // Set the headers to indicate streaming
  487. w.Header().Set("Content-Type", "application/json")
  488. w.Header().Set("Transfer-Encoding", "chunked")
  489. flusher, ok := w.(http.Flusher)
  490. if !ok {
  491. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  492. return
  493. }
  494. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  495. numPredict: req.NumPredict,
  496. stop: req.Stop,
  497. numKeep: int32(req.NumKeep),
  498. samplers: getSamplers(req),
  499. embedding: false,
  500. })
  501. if err != nil {
  502. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  503. return
  504. }
  505. // Ensure there is a place to put the sequence, released when removed from s.seqs
  506. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  507. if errors.Is(err, context.Canceled) {
  508. slog.Info("aborting completion request due to client closing the connection")
  509. } else {
  510. slog.Error("Failed to acquire semaphore", "error", err)
  511. }
  512. return
  513. }
  514. s.mu.Lock()
  515. found := false
  516. for i, sq := range s.seqs {
  517. if sq == nil {
  518. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  519. if err != nil {
  520. s.mu.Unlock()
  521. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  522. return
  523. }
  524. s.seqs[i] = seq
  525. s.cond.Signal()
  526. found = true
  527. break
  528. }
  529. }
  530. s.mu.Unlock()
  531. if !found {
  532. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  533. return
  534. }
  535. for {
  536. select {
  537. case <-r.Context().Done():
  538. close(seq.quit)
  539. return
  540. case content, ok := <-seq.responses:
  541. if ok {
  542. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  543. Content: content,
  544. }); err != nil {
  545. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  546. close(seq.quit)
  547. return
  548. }
  549. flusher.Flush()
  550. } else {
  551. // Send the final response
  552. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  553. Stop: true,
  554. StoppedLimit: seq.doneReason == "limit",
  555. Timings: Timings{
  556. PromptN: seq.numPromptInputs,
  557. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  558. PredictedN: seq.numPredicted,
  559. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  560. },
  561. }); err != nil {
  562. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  563. }
  564. return
  565. }
  566. }
  567. }
  568. }
  569. type EmbeddingRequest struct {
  570. Content string `json:"content"`
  571. CachePrompt bool `json:"cache_prompt"`
  572. }
  573. type EmbeddingResponse struct {
  574. Embedding []float32 `json:"embedding"`
  575. }
  576. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  577. var req EmbeddingRequest
  578. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  579. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  580. return
  581. }
  582. w.Header().Set("Content-Type", "application/json")
  583. slog.Debug("embedding request", "content", req.Content)
  584. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  585. if err != nil {
  586. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  587. return
  588. }
  589. // Ensure there is a place to put the sequence, released when removed from s.seqs
  590. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  591. if errors.Is(err, context.Canceled) {
  592. slog.Info("aborting embeddings request due to client closing the connection")
  593. } else {
  594. slog.Error("Failed to acquire semaphore", "error", err)
  595. }
  596. return
  597. }
  598. s.mu.Lock()
  599. found := false
  600. for i, sq := range s.seqs {
  601. if sq == nil {
  602. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  603. if err != nil {
  604. s.mu.Unlock()
  605. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  606. return
  607. }
  608. s.seqs[i] = seq
  609. s.cond.Signal()
  610. found = true
  611. break
  612. }
  613. }
  614. s.mu.Unlock()
  615. if !found {
  616. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  617. return
  618. }
  619. embedding := <-seq.embedding
  620. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  621. Embedding: embedding,
  622. }); err != nil {
  623. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  624. }
  625. }
  626. type HealthResponse struct {
  627. Status string `json:"status"`
  628. Progress float32 `json:"progress"`
  629. }
  630. type ServerStatus int
  631. const (
  632. ServerStatusReady ServerStatus = iota
  633. ServerStatusLoadingModel
  634. ServerStatusError
  635. )
  636. func (s ServerStatus) ToString() string {
  637. switch s {
  638. case ServerStatusReady:
  639. return "ok"
  640. case ServerStatusLoadingModel:
  641. return "loading model"
  642. default:
  643. return "server error"
  644. }
  645. }
  646. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  647. w.Header().Set("Content-Type", "application/json")
  648. if err := json.NewEncoder(w).Encode(&HealthResponse{
  649. Status: s.status.ToString(),
  650. Progress: s.progress,
  651. }); err != nil {
  652. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  653. }
  654. }
  655. type multiLPath []string
  656. func (m *multiLPath) Set(value string) error {
  657. *m = append(*m, value)
  658. return nil
  659. }
  660. func (m *multiLPath) String() string {
  661. return strings.Join(*m, ", ")
  662. }
  663. func (s *Server) loadModel(
  664. mpath string,
  665. lpath multiLPath,
  666. kvCacheType string,
  667. kvSize int,
  668. multiUserCache bool,
  669. ) {
  670. var err error
  671. s.model, err = model.New(mpath)
  672. if err != nil {
  673. panic(err)
  674. }
  675. // TODO(jessegross): LoRA loading
  676. if lpath.String() != "" {
  677. panic("loras are not yet implemented")
  678. }
  679. s.cache, err = NewInputCache(s.model.Backend(), kvCacheType, int32(kvSize), s.parallel, multiUserCache)
  680. if err != nil {
  681. panic(err)
  682. }
  683. s.status = ServerStatusReady
  684. s.ready.Done()
  685. }
  686. func Execute(args []string) error {
  687. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  688. mpath := fs.String("model", "", "Path to model binary file")
  689. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  690. batchSize := fs.Int("batch-size", 512, "Batch size")
  691. _ = fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  692. _ = fs.Int("main-gpu", 0, "Main GPU")
  693. _ = fs.Bool("flash-attn", false, "Enable flash attention")
  694. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  695. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  696. port := fs.Int("port", 8080, "Port to expose the server on")
  697. _ = fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  698. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  699. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  700. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  701. _ = fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  702. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  703. var lpaths multiLPath
  704. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  705. fs.Usage = func() {
  706. fmt.Fprintf(fs.Output(), "Runner usage\n")
  707. fs.PrintDefaults()
  708. }
  709. if err := fs.Parse(args); err != nil {
  710. return err
  711. }
  712. level := slog.LevelInfo
  713. if *verbose {
  714. level = slog.LevelDebug
  715. }
  716. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  717. Level: level,
  718. AddSource: true,
  719. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  720. if attr.Key == slog.SourceKey {
  721. source := attr.Value.Any().(*slog.Source)
  722. source.File = filepath.Base(source.File)
  723. }
  724. return attr
  725. },
  726. })
  727. slog.SetDefault(slog.New(handler))
  728. slog.Info("starting ollama engine")
  729. // TODO(jessegross): Some system info would be useful
  730. server := &Server{
  731. batchSize: *batchSize,
  732. parallel: *parallel,
  733. seqs: make([]*Sequence, *parallel),
  734. seqsSem: semaphore.NewWeighted(int64(*parallel)),
  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, *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. }