runner.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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)
  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. sampler, err := sample.NewSampler(
  466. req.Temperature,
  467. req.TopK,
  468. req.TopP,
  469. req.MinP,
  470. req.Seed,
  471. )
  472. if err != nil {
  473. http.Error(w, fmt.Sprintf("Failed to create sampler: %v", err), http.StatusInternalServerError)
  474. return
  475. }
  476. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  477. numPredict: req.NumPredict,
  478. stop: req.Stop,
  479. numKeep: int32(req.NumKeep),
  480. sampler: sampler,
  481. embedding: false,
  482. })
  483. if err != nil {
  484. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  485. return
  486. }
  487. // Ensure there is a place to put the sequence, released when removed from s.seqs
  488. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  489. if errors.Is(err, context.Canceled) {
  490. slog.Info("aborting completion request due to client closing the connection")
  491. } else {
  492. slog.Error("Failed to acquire semaphore", "error", err)
  493. }
  494. return
  495. }
  496. s.mu.Lock()
  497. found := false
  498. for i, sq := range s.seqs {
  499. if sq == nil {
  500. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  501. if err != nil {
  502. s.mu.Unlock()
  503. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  504. return
  505. }
  506. s.seqs[i] = seq
  507. s.cond.Signal()
  508. found = true
  509. break
  510. }
  511. }
  512. s.mu.Unlock()
  513. if !found {
  514. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  515. return
  516. }
  517. for {
  518. select {
  519. case <-r.Context().Done():
  520. close(seq.quit)
  521. return
  522. case content, ok := <-seq.responses:
  523. if ok {
  524. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  525. Content: content,
  526. }); err != nil {
  527. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  528. close(seq.quit)
  529. return
  530. }
  531. flusher.Flush()
  532. } else {
  533. // Send the final response
  534. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  535. Stop: true,
  536. StoppedLimit: seq.doneReason == "limit",
  537. Timings: Timings{
  538. PromptN: seq.numPromptInputs,
  539. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  540. PredictedN: seq.numPredicted,
  541. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  542. },
  543. }); err != nil {
  544. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  545. }
  546. return
  547. }
  548. }
  549. }
  550. }
  551. type EmbeddingRequest struct {
  552. Content string `json:"content"`
  553. CachePrompt bool `json:"cache_prompt"`
  554. }
  555. type EmbeddingResponse struct {
  556. Embedding []float32 `json:"embedding"`
  557. }
  558. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  559. var req EmbeddingRequest
  560. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  561. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  562. return
  563. }
  564. w.Header().Set("Content-Type", "application/json")
  565. slog.Debug("embedding request", "content", req.Content)
  566. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  567. if err != nil {
  568. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  569. return
  570. }
  571. // Ensure there is a place to put the sequence, released when removed from s.seqs
  572. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  573. if errors.Is(err, context.Canceled) {
  574. slog.Info("aborting embeddings request due to client closing the connection")
  575. } else {
  576. slog.Error("Failed to acquire semaphore", "error", err)
  577. }
  578. return
  579. }
  580. s.mu.Lock()
  581. found := false
  582. for i, sq := range s.seqs {
  583. if sq == nil {
  584. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  585. if err != nil {
  586. s.mu.Unlock()
  587. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  588. return
  589. }
  590. s.seqs[i] = seq
  591. s.cond.Signal()
  592. found = true
  593. break
  594. }
  595. }
  596. s.mu.Unlock()
  597. if !found {
  598. http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
  599. return
  600. }
  601. embedding := <-seq.embedding
  602. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  603. Embedding: embedding,
  604. }); err != nil {
  605. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  606. }
  607. }
  608. type HealthResponse struct {
  609. Status string `json:"status"`
  610. Progress float32 `json:"progress"`
  611. }
  612. type ServerStatus int
  613. const (
  614. ServerStatusReady ServerStatus = iota
  615. ServerStatusLoadingModel
  616. ServerStatusError
  617. )
  618. func (s ServerStatus) ToString() string {
  619. switch s {
  620. case ServerStatusReady:
  621. return "ok"
  622. case ServerStatusLoadingModel:
  623. return "loading model"
  624. default:
  625. return "server error"
  626. }
  627. }
  628. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  629. w.Header().Set("Content-Type", "application/json")
  630. if err := json.NewEncoder(w).Encode(&HealthResponse{
  631. Status: s.status.ToString(),
  632. Progress: s.progress,
  633. }); err != nil {
  634. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  635. }
  636. }
  637. type multiLPath []string
  638. func (m *multiLPath) Set(value string) error {
  639. *m = append(*m, value)
  640. return nil
  641. }
  642. func (m *multiLPath) String() string {
  643. return strings.Join(*m, ", ")
  644. }
  645. func (s *Server) loadModel(
  646. mpath string,
  647. params ml.BackendParams,
  648. lpath multiLPath,
  649. parallel int,
  650. kvCacheType string,
  651. kvSize int,
  652. multiUserCache bool,
  653. ) {
  654. var err error
  655. s.model, err = model.New(mpath, params)
  656. if err != nil {
  657. panic(err)
  658. }
  659. slog.Info("system", "info", s.model.Backend().SystemInfo(), "threads", params.NumThreads)
  660. // TODO(jessegross): LoRA loading
  661. if lpath.String() != "" {
  662. panic("loras are not yet implemented")
  663. }
  664. s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, multiUserCache)
  665. if err != nil {
  666. panic(err)
  667. }
  668. if !s.cache.enabled && parallel > 1 {
  669. parallel = 1
  670. slog.Warn("model does not support caching, disabling parallel processing")
  671. }
  672. s.parallel = parallel
  673. s.seqs = make([]*Sequence, s.parallel)
  674. s.seqsSem = semaphore.NewWeighted(int64(s.parallel))
  675. s.status = ServerStatusReady
  676. s.ready.Done()
  677. }
  678. func Execute(args []string) error {
  679. fs := flag.NewFlagSet("runner", flag.ExitOnError)
  680. mpath := fs.String("model", "", "Path to model binary file")
  681. parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
  682. batchSize := fs.Int("batch-size", 512, "Batch size")
  683. numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  684. mainGPU := fs.Int("main-gpu", 0, "Main GPU")
  685. _ = fs.Bool("flash-attn", false, "Enable flash attention")
  686. kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
  687. kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
  688. port := fs.Int("port", 8080, "Port to expose the server on")
  689. threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  690. verbose := fs.Bool("verbose", false, "verbose output (default: disabled)")
  691. _ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  692. _ = fs.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  693. tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  694. multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  695. var lpaths multiLPath
  696. fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
  697. fs.Usage = func() {
  698. fmt.Fprintf(fs.Output(), "Runner usage\n")
  699. fs.PrintDefaults()
  700. }
  701. if err := fs.Parse(args); err != nil {
  702. return err
  703. }
  704. level := slog.LevelInfo
  705. if *verbose {
  706. level = slog.LevelDebug
  707. }
  708. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  709. Level: level,
  710. AddSource: true,
  711. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  712. if attr.Key == slog.SourceKey {
  713. source := attr.Value.Any().(*slog.Source)
  714. source.File = filepath.Base(source.File)
  715. }
  716. return attr
  717. },
  718. })
  719. slog.SetDefault(slog.New(handler))
  720. slog.Info("starting ollama engine")
  721. server := &Server{
  722. batchSize: *batchSize,
  723. status: ServerStatusLoadingModel,
  724. }
  725. // TODO(jessegross): Parameters that need to be implemented:
  726. // flash-attn
  727. // no-mmap
  728. // mlock
  729. var tensorSplitFloats []float32
  730. if *tensorSplit != "" {
  731. splits := strings.Split(*tensorSplit, ",")
  732. tensorSplitFloats = make([]float32, len(splits))
  733. for i, s := range splits {
  734. f, _ := strconv.ParseFloat(s, 32)
  735. tensorSplitFloats[i] = float32(f)
  736. }
  737. }
  738. params := ml.BackendParams{
  739. NumThreads: *threads,
  740. NumGPULayers: *numGPULayers,
  741. MainGPU: *mainGPU,
  742. TensorSplit: tensorSplitFloats,
  743. }
  744. server.ready.Add(1)
  745. go server.loadModel(*mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
  746. server.cond = sync.NewCond(&server.mu)
  747. ctx, cancel := context.WithCancel(context.Background())
  748. go server.run(ctx)
  749. addr := "127.0.0.1:" + strconv.Itoa(*port)
  750. listener, err := net.Listen("tcp", addr)
  751. if err != nil {
  752. fmt.Println("Listen error:", err)
  753. cancel()
  754. return err
  755. }
  756. defer listener.Close()
  757. mux := http.NewServeMux()
  758. mux.HandleFunc("/embedding", server.embeddings)
  759. mux.HandleFunc("/completion", server.completion)
  760. mux.HandleFunc("/health", server.health)
  761. httpServer := http.Server{
  762. Handler: mux,
  763. }
  764. log.Println("Server listening on", addr)
  765. if err := httpServer.Serve(listener); err != nil {
  766. log.Fatal("server error:", err)
  767. return err
  768. }
  769. cancel()
  770. return nil
  771. }