runner.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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/ml"
  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/models"
  30. )
  31. // input is an element of the prompt to process, either a token or an image
  32. type input struct {
  33. token int32
  34. image image.Image
  35. }
  36. type Sequence struct {
  37. // batch index
  38. iBatch int
  39. // prompt inputs left to evaluate
  40. inputs []input
  41. // inputs that have been added to a batch but not yet submitted to Forward
  42. pendingInputs []input
  43. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  44. pendingResponses []string
  45. // input cache being used by this sequence
  46. cache *InputCacheSlot
  47. // channel to send responses over
  48. responses chan string
  49. // channel to stop decoding (such as if the remote connection is closed)
  50. quit chan bool
  51. // number of tokens to predict
  52. numPredict int
  53. // sampler with transforms to run on generated logits
  54. sampler sample.Sampler
  55. // channel to send back the embedding if embedding only
  56. embedding chan []float32
  57. // stop sequences
  58. stop []string
  59. // number of inputs to keep at the beginning when shifting context window
  60. numKeep int32
  61. // true if an embedding are to be returned instead of text generation
  62. embeddingOnly bool
  63. doneReason string
  64. // Metrics
  65. startProcessingTime time.Time
  66. startGenerationTime time.Time
  67. numPredicted int
  68. numPromptInputs int
  69. }
  70. type NewSequenceParams struct {
  71. numPredict int
  72. stop []string
  73. numKeep int32
  74. sampler sample.Sampler
  75. embedding bool
  76. }
  77. func (s *Server) NewSequence(prompt string, images []ImageData, params NewSequenceParams) (*Sequence, error) {
  78. s.ready.Wait()
  79. startTime := time.Now()
  80. inputs, err := s.inputs(prompt, images)
  81. if err != nil {
  82. return nil, fmt.Errorf("failed to process inputs: %w", err)
  83. } else if len(inputs) == 0 {
  84. return nil, errors.New("no input provided")
  85. }
  86. if params.numKeep < 0 {
  87. params.numKeep = int32(len(inputs))
  88. }
  89. // Ensure that at least 1 input can be discarded during shift
  90. params.numKeep = min(params.numKeep, s.cache.numCtx-1)
  91. if int32(len(inputs)) > s.cache.numCtx {
  92. discard := int32(len(inputs)) - s.cache.numCtx
  93. newInputs := inputs[:params.numKeep]
  94. newInputs = append(newInputs, inputs[params.numKeep+discard:]...)
  95. slog.Warn("truncating input prompt", "limit", s.cache.numCtx, "prompt", len(inputs), "keep", params.numKeep, "new", len(newInputs))
  96. inputs = newInputs
  97. }
  98. // TODO(jessegross): Ingest cached history for grammar
  99. return &Sequence{
  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(prompt string, images []ImageData) ([]input, error) {
  118. var inputs []input
  119. var parts []string
  120. var matches [][]string
  121. // TODO(jessegross): This can sometimes trigger for matching text in the
  122. // user's prompt. We previously tried to avoid it by only looking for images
  123. // on image models. We don't have a clear indication now but it would be better
  124. // to properly escape it in any case.
  125. re := regexp.MustCompile(`\[img-(\d+)\]`)
  126. parts = re.Split(prompt, -1)
  127. matches = re.FindAllStringSubmatch(prompt, -1)
  128. for i, part := range parts {
  129. // text - tokenize
  130. tokens, err := s.model.(model.TextProcessor).Encode(part, i == 0)
  131. if err != nil {
  132. return nil, err
  133. }
  134. for _, t := range tokens {
  135. inputs = append(inputs, input{token: t})
  136. }
  137. // image - decode and store
  138. if i < len(matches) {
  139. n, _ := strconv.Atoi(matches[i][1])
  140. imageIndex := -1
  141. for j := range images {
  142. if images[j].ID == n {
  143. imageIndex = j
  144. break
  145. }
  146. }
  147. if imageIndex < 0 {
  148. return nil, fmt.Errorf("invalid image index: %d", n)
  149. }
  150. image, _, err := image.Decode(bytes.NewReader(images[imageIndex].Data))
  151. if err != nil {
  152. return nil, err
  153. }
  154. inputs = append(inputs, input{image: image})
  155. }
  156. }
  157. return inputs, nil
  158. }
  159. type Server struct {
  160. // is the server ready to process requests?
  161. // protects access to model and image
  162. ready sync.WaitGroup
  163. // loaded model
  164. model model.Model
  165. // status for external health reporting - loading, ready to serve, etc.
  166. status ServerStatus
  167. // current progress on loading the model
  168. progress float32
  169. // number of simultaneous requests to handle
  170. parallel int
  171. // maximum number of elements in a batch (per sequence)
  172. // TODO (jmorganca): make this n_batch
  173. batchSize int
  174. // protects access to everything below this line
  175. // this is context state needed for decoding
  176. mu sync.Mutex
  177. // indicates that data is ready for processing
  178. cond *sync.Cond
  179. // the list of simultaneous sequences being evaluated
  180. seqs []*Sequence
  181. // seqs can have a maximum of parallel entries, which
  182. // is enfoced by seqSem
  183. seqsSem *semaphore.Weighted
  184. // KV cache
  185. cache *InputCache
  186. // next sequence for prompt processing to avoid starvation
  187. nextSeq int
  188. }
  189. func (s *Server) allNil() bool {
  190. for _, item := range s.seqs {
  191. if item != nil {
  192. return false
  193. }
  194. }
  195. return true
  196. }
  197. func flushPending(seq *Sequence) bool {
  198. joined := strings.Join(seq.pendingResponses, "")
  199. seq.pendingResponses = []string{}
  200. // Check if there are any partial UTF-8 characters remaining.
  201. // We already check and queue as we are generating but some may
  202. // still make it here:
  203. // - Sequence is ending, e.g. generation limit has been hit
  204. // - Invalid characters in the middle of a string
  205. // This is a stricter check to ensure we never output invalid Unicode.
  206. for !utf8.ValidString(joined) {
  207. joined = joined[:len(joined)-1]
  208. }
  209. if len(joined) == 0 {
  210. return true
  211. }
  212. select {
  213. case seq.responses <- joined:
  214. return true
  215. case <-seq.quit:
  216. return false
  217. }
  218. }
  219. func (s *Server) removeSequence(seqIndex int, reason string) {
  220. seq := s.seqs[seqIndex]
  221. flushPending(seq)
  222. seq.doneReason = reason
  223. close(seq.responses)
  224. close(seq.embedding)
  225. seq.cache.InUse = false
  226. s.seqs[seqIndex] = nil
  227. s.seqsSem.Release(1)
  228. }
  229. func (s *Server) run(ctx context.Context) {
  230. s.ready.Wait()
  231. for {
  232. select {
  233. case <-ctx.Done():
  234. return
  235. default:
  236. err := s.processBatch()
  237. if err != nil {
  238. panic(err)
  239. }
  240. }
  241. }
  242. }
  243. func (s *Server) processBatch() error {
  244. s.mu.Lock()
  245. for s.allNil() {
  246. s.cond.Wait() // Wait until an item is added
  247. }
  248. defer s.mu.Unlock()
  249. var options model.Options
  250. imgSeq := -1
  251. seqIdx := s.nextSeq - 1
  252. for range s.seqs {
  253. seqIdx = (seqIdx + 1) % len(s.seqs)
  254. seq := s.seqs[seqIdx]
  255. if seq == nil {
  256. continue
  257. }
  258. // if past the num predict limit
  259. if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
  260. s.removeSequence(seqIdx, "limit")
  261. continue
  262. }
  263. if !s.cache.enabled {
  264. seq.inputs = append(seq.cache.Inputs, seq.inputs...)
  265. seq.cache.Inputs = []input{}
  266. }
  267. for i, input := range seq.inputs {
  268. if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+1) > s.cache.numCtx {
  269. if len(seq.pendingInputs) == 0 {
  270. err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  271. if err != nil {
  272. return err
  273. }
  274. } else {
  275. break
  276. }
  277. }
  278. if i >= s.batchSize {
  279. break
  280. }
  281. // TODO(jessegross): Image inputs need to be rethought - it's
  282. // it doesn't work well for different types of models or multiple sequences
  283. if input.image != nil {
  284. if len(seq.pendingInputs) != len(options.Images) {
  285. break
  286. }
  287. if imgSeq != seqIdx && imgSeq != -1 {
  288. s.nextSeq = seqIdx
  289. break
  290. }
  291. imgSeq = seqIdx
  292. options.Images = append(options.Images, input.image)
  293. seq.pendingInputs = append(seq.pendingInputs, input)
  294. continue
  295. }
  296. options.Inputs = append(options.Inputs, input.token)
  297. options.Positions = append(options.Positions, int32(len(seq.cache.Inputs)+len(seq.pendingInputs)))
  298. options.Sequences = append(options.Sequences, seq.cache.Id)
  299. seq.iBatch = len(options.Outputs)
  300. if i+1 == len(seq.inputs) {
  301. options.Outputs = append(options.Outputs, int32(len(options.Inputs)-1))
  302. }
  303. seq.pendingInputs = append(seq.pendingInputs, input)
  304. }
  305. seq.inputs = seq.inputs[len(seq.pendingInputs):]
  306. }
  307. if len(options.Inputs) == 0 {
  308. return nil
  309. }
  310. ctx := s.model.Backend().NewContext()
  311. defer ctx.Close()
  312. modelOutput, err := model.Forward(ctx, s.model, options)
  313. if err != nil {
  314. return fmt.Errorf("failed to decode batch: %w", err)
  315. }
  316. logits := modelOutput.Floats()
  317. for i, seq := range s.seqs {
  318. if seq == nil {
  319. continue
  320. }
  321. // After calling Forward, pending inputs are now in the cache
  322. if len(seq.pendingInputs) > 0 {
  323. seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
  324. seq.pendingInputs = []input{}
  325. }
  326. // don't sample prompt processing
  327. if len(seq.inputs) != 0 {
  328. if !s.cache.enabled {
  329. return errors.New("caching disabled but unable to fit entire input in a batch")
  330. }
  331. continue
  332. }
  333. seq.numPredicted++
  334. if seq.numPredicted == 1 {
  335. seq.startGenerationTime = time.Now()
  336. }
  337. // if done processing the prompt, generate an embedding and return
  338. if seq.embeddingOnly {
  339. // TODO(jessegross): Embedding support
  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{{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. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  466. numPredict: req.NumPredict,
  467. stop: req.Stop,
  468. numKeep: int32(req.NumKeep),
  469. sampler: sample.Greedy(), // TODO: add support for different samplers when performance is optimized
  470. embedding: false,
  471. })
  472. if err != nil {
  473. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  474. return
  475. }
  476. // Ensure there is a place to put the sequence, released when removed from s.seqs
  477. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  478. if errors.Is(err, context.Canceled) {
  479. slog.Info("aborting completion request due to client closing the connection")
  480. } else {
  481. slog.Error("Failed to acquire semaphore", "error", err)
  482. }
  483. return
  484. }
  485. s.mu.Lock()
  486. found := false
  487. for i, sq := range s.seqs {
  488. if sq == nil {
  489. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  490. if err != nil {
  491. s.mu.Unlock()
  492. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  493. return
  494. }
  495. s.seqs[i] = seq
  496. s.cond.Signal()
  497. found = true
  498. break
  499. }
  500. }
  501. s.mu.Unlock()
  502. if !found {
  503. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  504. return
  505. }
  506. for {
  507. select {
  508. case <-r.Context().Done():
  509. close(seq.quit)
  510. return
  511. case content, ok := <-seq.responses:
  512. if ok {
  513. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  514. Content: content,
  515. }); err != nil {
  516. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  517. close(seq.quit)
  518. return
  519. }
  520. flusher.Flush()
  521. } else {
  522. // Send the final response
  523. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  524. Stop: true,
  525. StoppedLimit: seq.doneReason == "limit",
  526. Timings: Timings{
  527. PromptN: seq.numPromptInputs,
  528. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  529. PredictedN: seq.numPredicted,
  530. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  531. },
  532. }); err != nil {
  533. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  534. }
  535. return
  536. }
  537. }
  538. }
  539. }
  540. type EmbeddingRequest struct {
  541. Content string `json:"content"`
  542. CachePrompt bool `json:"cache_prompt"`
  543. }
  544. type EmbeddingResponse struct {
  545. Embedding []float32 `json:"embedding"`
  546. }
  547. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  548. var req EmbeddingRequest
  549. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  550. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  551. return
  552. }
  553. w.Header().Set("Content-Type", "application/json")
  554. slog.Debug("embedding request", "content", req.Content)
  555. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  556. if err != nil {
  557. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  558. return
  559. }
  560. // Ensure there is a place to put the sequence, released when removed from s.seqs
  561. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  562. if errors.Is(err, context.Canceled) {
  563. slog.Info("aborting embeddings request due to client closing the connection")
  564. } else {
  565. slog.Error("Failed to acquire semaphore", "error", err)
  566. }
  567. return
  568. }
  569. s.mu.Lock()
  570. found := false
  571. for i, sq := range s.seqs {
  572. if sq == nil {
  573. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  574. if err != nil {
  575. s.mu.Unlock()
  576. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  577. return
  578. }
  579. s.seqs[i] = seq
  580. s.cond.Signal()
  581. found = true
  582. break
  583. }
  584. }
  585. s.mu.Unlock()
  586. if !found {
  587. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  588. return
  589. }
  590. embedding := <-seq.embedding
  591. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  592. Embedding: embedding,
  593. }); err != nil {
  594. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  595. }
  596. }
  597. type HealthResponse struct {
  598. Status string `json:"status"`
  599. Progress float32 `json:"progress"`
  600. }
  601. type ServerStatus int
  602. const (
  603. ServerStatusReady ServerStatus = iota
  604. ServerStatusLoadingModel
  605. ServerStatusError
  606. )
  607. func (s ServerStatus) ToString() string {
  608. switch s {
  609. case ServerStatusReady:
  610. return "ok"
  611. case ServerStatusLoadingModel:
  612. return "loading model"
  613. default:
  614. return "server error"
  615. }
  616. }
  617. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  618. w.Header().Set("Content-Type", "application/json")
  619. if err := json.NewEncoder(w).Encode(&HealthResponse{
  620. Status: s.status.ToString(),
  621. Progress: s.progress,
  622. }); err != nil {
  623. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  624. }
  625. }
  626. type multiLPath []string
  627. func (m *multiLPath) Set(value string) error {
  628. *m = append(*m, value)
  629. return nil
  630. }
  631. func (m *multiLPath) String() string {
  632. return strings.Join(*m, ", ")
  633. }
  634. func (s *Server) loadModel(
  635. mpath string,
  636. params ml.BackendParams,
  637. lpath multiLPath,
  638. parallel int,
  639. kvCacheType string,
  640. kvSize int,
  641. multiUserCache bool,
  642. ) {
  643. var err error
  644. s.model, err = model.New(mpath, params)
  645. if err != nil {
  646. panic(err)
  647. }
  648. // TODO(jessegross): LoRA loading
  649. if lpath.String() != "" {
  650. panic("loras are not yet implemented")
  651. }
  652. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, multiUserCache)
  653. if err != nil {
  654. panic(err)
  655. }
  656. if !s.cache.enabled && parallel > 1 {
  657. parallel = 1
  658. slog.Warn("model does not support caching, disabling parallel processing")
  659. }
  660. s.parallel = parallel
  661. s.seqs = make([]*Sequence, s.parallel)
  662. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  663. s.status = ServerStatusReady
  664. s.ready.Done()
  665. }
  666. func Execute(args []string) error {
  667. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  668. mpath := fs.String("model", "", "Path to model binary file")
  669. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  670. batchSize := fs.Int("batch-size", 512, "Batch size")
  671. numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  672. mainGPU := fs.Int("main-gpu", 0, "Main GPU")
  673. flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
  674. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  675. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  676. port := fs.Int("port", 8080, "Port to expose the server on")
  677. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  678. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  679. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  680. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  681. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  682. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  683. var lpaths multiLPath
  684. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  685. fs.Usage = func() {
  686. fmt.Fprintf(fs.Output(), "Runner usage\n")
  687. fs.PrintDefaults()
  688. }
  689. if err := fs.Parse(args); err != nil {
  690. return err
  691. }
  692. level := slog.LevelInfo
  693. if *verbose {
  694. level = slog.LevelDebug
  695. }
  696. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  697. Level: level,
  698. AddSource: true,
  699. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  700. if attr.Key == slog.SourceKey {
  701. source := attr.Value.Any().(*slog.Source)
  702. source.File = filepath.Base(source.File)
  703. }
  704. return attr
  705. },
  706. })
  707. slog.SetDefault(slog.New(handler))
  708. slog.Info("starting ollama engine")
  709. server := &Server{
  710. batchSize: *batchSize,
  711. status: ServerStatusLoadingModel,
  712. }
  713. // TODO(jessegross): Parameters that need to be implemented:
  714. // no-mmap
  715. // mlock
  716. var tensorSplitFloats []float32
  717. if *tensorSplit != "" {
  718. splits := strings.Split(*tensorSplit, ",")
  719. tensorSplitFloats = make([]float32, len(splits))
  720. for i, s := range splits {
  721. f, _ := strconv.ParseFloat(s, 32)
  722. tensorSplitFloats[i] = float32(f)
  723. }
  724. }
  725. params := ml.BackendParams{
  726. NumThreads: *threads,
  727. NumGPULayers: *numGPULayers,
  728. MainGPU: *mainGPU,
  729. TensorSplit: tensorSplitFloats,
  730. FlashAttention: *flashAttention,
  731. }
  732. server.ready.Add(1)
  733. go server.loadModel(*mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  734. server.cond = sync.NewCond(&server.mu)
  735. ctx, cancel := context.WithCancel(context.Background())
  736. defer cancel()
  737. go server.run(ctx)
  738. addr := "127.0.0.1:" + strconv.Itoa(*port)
  739. listener, err := net.Listen("tcp", addr)
  740. if err != nil {
  741. fmt.Println("Listen error:", err)
  742. return err
  743. }
  744. defer listener.Close()
  745. mux := http.NewServeMux()
  746. mux.HandleFunc("/embedding", server.embeddings)
  747. mux.HandleFunc("/completion", server.completion)
  748. mux.HandleFunc("/health", server.health)
  749. httpServer := http.Server{
  750. Handler: mux,
  751. }
  752. log.Println("Server listening on", addr)
  753. if err := httpServer.Serve(listener); err != nil {
  754. log.Fatal("server error:", err)
  755. return err
  756. }
  757. return nil
  758. }