runner.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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. }
  203. func (s *Server) allNil() bool {
  204. for _, item := range s.seqs {
  205. if item != nil {
  206. return false
  207. }
  208. }
  209. return true
  210. }
  211. func flushPending(seq *Sequence) bool {
  212. joined := strings.Join(seq.pendingResponses, "")
  213. seq.pendingResponses = []string{}
  214. // Check if there are any partial UTF-8 characters remaining.
  215. // We already check and queue as we are generating but some may
  216. // still make it here:
  217. // - Sequence is ending, e.g. generation limit has been hit
  218. // - Invalid characters in the middle of a string
  219. // This is a stricter check to ensure we never output invalid Unicode.
  220. for !utf8.ValidString(joined) {
  221. joined = joined[:len(joined)-1]
  222. }
  223. if len(joined) == 0 {
  224. return true
  225. }
  226. select {
  227. case seq.responses <- joined:
  228. return true
  229. case <-seq.quit:
  230. return false
  231. }
  232. }
  233. func (s *Server) removeSequence(seqIndex int, reason string) {
  234. seq := s.seqs[seqIndex]
  235. flushPending(seq)
  236. seq.doneReason = reason
  237. close(seq.responses)
  238. close(seq.embedding)
  239. seq.cache.InUse = false
  240. seq.ctx.Close()
  241. s.seqs[seqIndex] = nil
  242. s.seqsSem.Release(1)
  243. }
  244. func (s *Server) run(ctx context.Context) {
  245. s.ready.Wait()
  246. for {
  247. select {
  248. case <-ctx.Done():
  249. return
  250. default:
  251. err := s.processBatch()
  252. if err != nil {
  253. panic(err)
  254. }
  255. }
  256. }
  257. }
  258. func (s *Server) processBatch() error {
  259. s.mu.Lock()
  260. for s.allNil() {
  261. s.cond.Wait() // Wait until an item is added
  262. }
  263. defer s.mu.Unlock()
  264. var options input.Options
  265. for i, seq := range s.seqs {
  266. if seq == nil {
  267. continue
  268. }
  269. // if past the num predict limit
  270. if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
  271. s.removeSequence(i, "limit")
  272. continue
  273. }
  274. if !s.cache.enabled {
  275. seq.inputs = append(seq.cache.Inputs, seq.inputs...)
  276. seq.cache.Inputs = []input.Input{}
  277. }
  278. for j, inp := range seq.inputs {
  279. if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+1) > s.cache.numCtx {
  280. if len(seq.pendingInputs) == 0 {
  281. err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  282. if err != nil {
  283. return err
  284. }
  285. } else {
  286. break
  287. }
  288. }
  289. if j >= s.batchSize {
  290. break
  291. }
  292. options.Inputs = append(options.Inputs, inp.Token)
  293. if inp.Multimodal != nil {
  294. options.Multimodal = append(options.Multimodal, input.MultimodalIndex{Index: len(options.Inputs) - 1, Multimodal: inp.Multimodal})
  295. }
  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 j+1 == len(seq.inputs) {
  300. options.Outputs = append(options.Outputs, int32(len(options.Inputs)-1))
  301. }
  302. seq.pendingInputs = append(seq.pendingInputs, inp)
  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. logits := modelOutput.Floats()
  316. for i, seq := range s.seqs {
  317. if seq == nil {
  318. continue
  319. }
  320. // After calling Forward, pending inputs are now in the cache
  321. if len(seq.pendingInputs) > 0 {
  322. seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
  323. seq.pendingInputs = []input.Input{}
  324. }
  325. // don't sample prompt processing
  326. if len(seq.inputs) != 0 {
  327. if !s.cache.enabled {
  328. return errors.New("caching disabled but unable to fit entire input in a batch")
  329. }
  330. continue
  331. }
  332. seq.numPredicted++
  333. if seq.numPredicted == 1 {
  334. seq.startGenerationTime = time.Now()
  335. }
  336. // if done processing the prompt, generate an embedding and return
  337. if seq.embeddingOnly {
  338. // TODO(jessegross): Embedding support
  339. slog.Warn("generation of embedding outputs not yet supported")
  340. s.removeSequence(i, "")
  341. continue
  342. }
  343. // sample a token
  344. vocabSize := len(logits) / len(options.Outputs)
  345. token, err := seq.sampler.Sample(logits[seq.iBatch*vocabSize : (seq.iBatch+1)*vocabSize])
  346. if err != nil {
  347. return fmt.Errorf("failed to sample token: %w", err)
  348. }
  349. // if it's an end of sequence token, break
  350. if s.model.(model.TextProcessor).Is(token, model.SpecialEOS) {
  351. // TODO (jmorganca): we should send this back
  352. // as it's important for the /api/generate context
  353. // seq.responses <- piece
  354. s.removeSequence(i, "stop")
  355. continue
  356. }
  357. piece, err := s.model.(model.TextProcessor).Decode([]int32{token})
  358. if err != nil {
  359. return err
  360. }
  361. seq.inputs = []input.Input{{Token: token}}
  362. seq.pendingResponses = append(seq.pendingResponses, piece)
  363. sequence := strings.Join(seq.pendingResponses, "")
  364. if ok, stop := common.FindStop(sequence, seq.stop); ok {
  365. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  366. var tokenTruncated bool
  367. origLen := len(seq.pendingResponses)
  368. seq.pendingResponses, tokenTruncated = common.TruncateStop(seq.pendingResponses, stop)
  369. newLen := len(seq.pendingResponses)
  370. // Update the cache based on the tokens that will be returned:
  371. // - We have 1 token more than is currently in the cache because
  372. // the last one generated wasn't submitted to Decode
  373. // - Remove any stop sequences that we stripped out
  374. // - If truncateStop removed a portion of a token, drop that
  375. // - As defense-in-depth, if truncatedToken didn't find a stop token
  376. // remove the extra one that we added to the cache len
  377. tokenLen := len(seq.cache.Inputs) + 1
  378. tokenLen -= origLen - newLen
  379. if tokenTruncated || origLen == newLen {
  380. tokenLen--
  381. }
  382. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  383. s.removeSequence(i, "stop")
  384. continue
  385. }
  386. if common.ContainsStopSuffix(sequence, seq.stop) {
  387. continue
  388. }
  389. if common.IncompleteUnicode(sequence) {
  390. continue
  391. }
  392. if !flushPending(seq) {
  393. s.removeSequence(i, "connection")
  394. }
  395. }
  396. return nil
  397. }
  398. // TODO (jmorganca): use structs from the api package to avoid duplication
  399. // this way the api acts as a proxy instead of using a different api for the
  400. // runner
  401. type Options struct {
  402. api.Runner
  403. NumKeep int `json:"n_keep"`
  404. Seed int `json:"seed"`
  405. NumPredict int `json:"n_predict"`
  406. TopK int `json:"top_k"`
  407. TopP float32 `json:"top_p"`
  408. MinP float32 `json:"min_p"`
  409. TypicalP float32 `json:"typical_p"`
  410. RepeatLastN int `json:"repeat_last_n"`
  411. Temperature float32 `json:"temperature"`
  412. RepeatPenalty float32 `json:"repeat_penalty"`
  413. PresencePenalty float32 `json:"presence_penalty"`
  414. FrequencyPenalty float32 `json:"frequency_penalty"`
  415. Mirostat int `json:"mirostat"`
  416. MirostatTau float32 `json:"mirostat_tau"`
  417. MirostatEta float32 `json:"mirostat_eta"`
  418. Stop []string `json:"stop"`
  419. }
  420. type ImageData struct {
  421. Data []byte `json:"data"`
  422. ID int `json:"id"`
  423. AspectRatioID int `json:"aspect_ratio_id"`
  424. }
  425. type CompletionRequest struct {
  426. Prompt string `json:"prompt"`
  427. Images []ImageData `json:"image_data"`
  428. Grammar string `json:"grammar"`
  429. CachePrompt bool `json:"cache_prompt"`
  430. Options
  431. }
  432. type Timings struct {
  433. PredictedN int `json:"predicted_n"`
  434. PredictedMS float64 `json:"predicted_ms"`
  435. PromptN int `json:"prompt_n"`
  436. PromptMS float64 `json:"prompt_ms"`
  437. }
  438. type CompletionResponse struct {
  439. Content string `json:"content"`
  440. Stop bool `json:"stop"`
  441. Model string `json:"model,omitempty"`
  442. Prompt string `json:"prompt,omitempty"`
  443. StoppedLimit bool `json:"stopped_limit,omitempty"`
  444. PredictedN int `json:"predicted_n,omitempty"`
  445. PredictedMS float64 `json:"predicted_ms,omitempty"`
  446. PromptN int `json:"prompt_n,omitempty"`
  447. PromptMS float64 `json:"prompt_ms,omitempty"`
  448. Timings Timings `json:"timings"`
  449. }
  450. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  451. var req CompletionRequest
  452. req.Options = Options(api.DefaultOptions())
  453. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  454. http.Error(w, "Bad request", http.StatusBadRequest)
  455. return
  456. }
  457. // Set the headers to indicate streaming
  458. w.Header().Set("Content-Type", "application/json")
  459. w.Header().Set("Transfer-Encoding", "chunked")
  460. flusher, ok := w.(http.Flusher)
  461. if !ok {
  462. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  463. return
  464. }
  465. sampler := sample.NewSampler(
  466. req.Temperature,
  467. req.TopK,
  468. req.TopP,
  469. req.MinP,
  470. req.Seed,
  471. )
  472. if req.Grammar != "" {
  473. panic("grammars are not yet supported")
  474. }
  475. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  476. numPredict: req.NumPredict,
  477. stop: req.Stop,
  478. numKeep: int32(req.NumKeep),
  479. sampler: sampler,
  480. embedding: false,
  481. })
  482. if err != nil {
  483. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  484. return
  485. }
  486. // Ensure there is a place to put the sequence, released when removed from s.seqs
  487. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  488. if errors.Is(err, context.Canceled) {
  489. slog.Info("aborting completion request due to client closing the connection")
  490. } else {
  491. slog.Error("Failed to acquire semaphore", "error", err)
  492. }
  493. return
  494. }
  495. s.mu.Lock()
  496. found := false
  497. for i, sq := range s.seqs {
  498. if sq == nil {
  499. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  500. if err != nil {
  501. s.mu.Unlock()
  502. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  503. return
  504. }
  505. s.seqs[i] = seq
  506. s.cond.Signal()
  507. found = true
  508. break
  509. }
  510. }
  511. s.mu.Unlock()
  512. if !found {
  513. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  514. return
  515. }
  516. for {
  517. select {
  518. case <-r.Context().Done():
  519. close(seq.quit)
  520. return
  521. case content, ok := <-seq.responses:
  522. if ok {
  523. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  524. Content: content,
  525. }); err != nil {
  526. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  527. close(seq.quit)
  528. return
  529. }
  530. flusher.Flush()
  531. } else {
  532. // Send the final response
  533. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  534. Stop: true,
  535. StoppedLimit: seq.doneReason == "limit",
  536. Timings: Timings{
  537. PromptN: seq.numPromptInputs,
  538. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  539. PredictedN: seq.numPredicted,
  540. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  541. },
  542. }); err != nil {
  543. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  544. }
  545. return
  546. }
  547. }
  548. }
  549. }
  550. type EmbeddingRequest struct {
  551. Content string `json:"content"`
  552. CachePrompt bool `json:"cache_prompt"`
  553. }
  554. type EmbeddingResponse struct {
  555. Embedding []float32 `json:"embedding"`
  556. }
  557. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  558. var req EmbeddingRequest
  559. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  560. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  561. return
  562. }
  563. w.Header().Set("Content-Type", "application/json")
  564. slog.Debug("embedding request", "content", req.Content)
  565. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  566. if err != nil {
  567. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  568. return
  569. }
  570. // Ensure there is a place to put the sequence, released when removed from s.seqs
  571. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  572. if errors.Is(err, context.Canceled) {
  573. slog.Info("aborting embeddings request due to client closing the connection")
  574. } else {
  575. slog.Error("Failed to acquire semaphore", "error", err)
  576. }
  577. return
  578. }
  579. s.mu.Lock()
  580. found := false
  581. for i, sq := range s.seqs {
  582. if sq == nil {
  583. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  584. if err != nil {
  585. s.mu.Unlock()
  586. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  587. return
  588. }
  589. s.seqs[i] = seq
  590. s.cond.Signal()
  591. found = true
  592. break
  593. }
  594. }
  595. s.mu.Unlock()
  596. if !found {
  597. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  598. return
  599. }
  600. embedding := <-seq.embedding
  601. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  602. Embedding: embedding,
  603. }); err != nil {
  604. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  605. }
  606. }
  607. type HealthResponse struct {
  608. Status string `json:"status"`
  609. Progress float32 `json:"progress"`
  610. }
  611. type ServerStatus int
  612. const (
  613. ServerStatusReady ServerStatus = iota
  614. ServerStatusLoadingModel
  615. ServerStatusError
  616. )
  617. func (s ServerStatus) ToString() string {
  618. switch s {
  619. case ServerStatusReady:
  620. return "ok"
  621. case ServerStatusLoadingModel:
  622. return "loading model"
  623. default:
  624. return "server error"
  625. }
  626. }
  627. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  628. w.Header().Set("Content-Type", "application/json")
  629. if err := json.NewEncoder(w).Encode(&HealthResponse{
  630. Status: s.status.ToString(),
  631. Progress: s.progress,
  632. }); err != nil {
  633. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  634. }
  635. }
  636. type multiLPath []string
  637. func (m *multiLPath) Set(value string) error {
  638. *m = append(*m, value)
  639. return nil
  640. }
  641. func (m *multiLPath) String() string {
  642. return strings.Join(*m, ", ")
  643. }
  644. func (s *Server) loadModel(
  645. mpath string,
  646. params ml.BackendParams,
  647. lpath multiLPath,
  648. parallel int,
  649. kvCacheType string,
  650. kvSize int,
  651. multiUserCache bool,
  652. ) {
  653. var err error
  654. s.model, err = model.New(mpath, params)
  655. if err != nil {
  656. panic(err)
  657. }
  658. // TODO(jessegross): LoRA loading
  659. if lpath.String() != "" {
  660. panic("loras are not yet implemented")
  661. }
  662. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, multiUserCache)
  663. if err != nil {
  664. panic(err)
  665. }
  666. if !s.cache.enabled && parallel > 1 {
  667. parallel = 1
  668. slog.Warn("model does not support caching, disabling parallel processing")
  669. }
  670. s.parallel = parallel
  671. s.seqs = make([]*Sequence, s.parallel)
  672. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  673. s.status = ServerStatusReady
  674. s.ready.Done()
  675. }
  676. func Execute(args []string) error {
  677. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  678. mpath := fs.String("model", "", "Path to model binary file")
  679. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  680. batchSize := fs.Int("batch-size", 512, "Batch size")
  681. numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  682. mainGPU := fs.Int("main-gpu", 0, "Main GPU")
  683. flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
  684. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  685. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  686. port := fs.Int("port", 8080, "Port to expose the server on")
  687. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  688. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  689. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  690. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  691. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  692. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  693. var lpaths multiLPath
  694. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  695. fs.Usage = func() {
  696. fmt.Fprintf(fs.Output(), "Runner usage\n")
  697. fs.PrintDefaults()
  698. }
  699. if err := fs.Parse(args); err != nil {
  700. return err
  701. }
  702. level := slog.LevelInfo
  703. if *verbose {
  704. level = slog.LevelDebug
  705. }
  706. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  707. Level: level,
  708. AddSource: true,
  709. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  710. if attr.Key == slog.SourceKey {
  711. source := attr.Value.Any().(*slog.Source)
  712. source.File = filepath.Base(source.File)
  713. }
  714. return attr
  715. },
  716. })
  717. slog.SetDefault(slog.New(handler))
  718. slog.Info("starting ollama engine")
  719. server := &Server{
  720. batchSize: *batchSize,
  721. status: ServerStatusLoadingModel,
  722. }
  723. // TODO(jessegross): Parameters that need to be implemented:
  724. // no-mmap
  725. // mlock
  726. var tensorSplitFloats []float32
  727. if *tensorSplit != "" {
  728. splits := strings.Split(*tensorSplit, ",")
  729. tensorSplitFloats = make([]float32, len(splits))
  730. for i, s := range splits {
  731. f, _ := strconv.ParseFloat(s, 32)
  732. tensorSplitFloats[i] = float32(f)
  733. }
  734. }
  735. params := ml.BackendParams{
  736. NumThreads: *threads,
  737. NumGPULayers: *numGPULayers,
  738. MainGPU: *mainGPU,
  739. TensorSplit: tensorSplitFloats,
  740. FlashAttention: *flashAttention,
  741. }
  742. server.ready.Add(1)
  743. go server.loadModel(*mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  744. server.cond = sync.NewCond(&server.mu)
  745. ctx, cancel := context.WithCancel(context.Background())
  746. defer cancel()
  747. go server.run(ctx)
  748. addr := "127.0.0.1:" + strconv.Itoa(*port)
  749. listener, err := net.Listen("tcp", addr)
  750. if err != nil {
  751. fmt.Println("Listen error:", err)
  752. return err
  753. }
  754. defer listener.Close()
  755. mux := http.NewServeMux()
  756. mux.HandleFunc("/embedding", server.embeddings)
  757. mux.HandleFunc("/completion", server.completion)
  758. mux.HandleFunc("/health", server.health)
  759. httpServer := http.Server{
  760. Handler: mux,
  761. }
  762. log.Println("Server listening on", addr)
  763. if err := httpServer.Serve(listener); err != nil {
  764. log.Fatal("server error:", err)
  765. return err
  766. }
  767. return nil
  768. }