runner.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "log/slog"
  10. "net"
  11. "net/http"
  12. "os"
  13. "path/filepath"
  14. "regexp"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "unicode/utf8"
  21. "golang.org/x/sync/semaphore"
  22. "github.com/ollama/ollama/api"
  23. "github.com/ollama/ollama/llama"
  24. )
  25. // input is an element of the prompt to process, either
  26. // a token or an image embedding (generated from a vision projector)
  27. type input struct {
  28. token int
  29. // embed is an image embedding
  30. embed []float32
  31. }
  32. type Sequence struct {
  33. // batch index
  34. iBatch int
  35. // number of tokens predicted so far
  36. numPredicted int
  37. // prompt inputs left to evaluate
  38. inputs []input
  39. // tokens that have been generated but not returned yet (e.g. for stop sequences)
  40. pendingResponses []string
  41. // input cache being used by this sequence
  42. cache *InputCacheSlot
  43. // does this sequence require cross-attention layers to be processed? - if we have seen
  44. // an image for certain multi-modal models
  45. crossAttention bool
  46. // channel to send responses over
  47. responses chan string
  48. // channel to stop decoding (such as if the remote connection is closed)
  49. quit chan bool
  50. // number of tokens to predict
  51. numPredict int
  52. samplingCtx *llama.SamplingContext
  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 int
  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. numDecoded int
  66. numPromptInputs int
  67. }
  68. type NewSequenceParams struct {
  69. numPredict int
  70. stop []string
  71. numKeep int
  72. samplingParams *llama.SamplingParams
  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. inputs, err := s.inputs(prompt, images)
  79. if err != nil {
  80. return nil, fmt.Errorf("failed to process inputs: %w", err)
  81. } else if len(inputs) == 0 {
  82. return nil, errors.New("no input provided")
  83. }
  84. if params.numKeep < 0 {
  85. params.numKeep = len(inputs)
  86. }
  87. if s.model.AddBOSToken() {
  88. params.numKeep += 1
  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 len(inputs) > s.cache.numCtx {
  93. slog.Warn("input exceeds context length", "prompt", len(inputs), "limit", s.cache.numCtx)
  94. }
  95. var sc *llama.SamplingContext
  96. if params.samplingParams != nil {
  97. sc, err = llama.NewSamplingContext(s.model, *params.samplingParams)
  98. if err != nil {
  99. return nil, err
  100. }
  101. for _, input := range inputs {
  102. if input.embed == nil {
  103. sc.Accept(input.token, false)
  104. }
  105. }
  106. }
  107. return &Sequence{
  108. inputs: inputs,
  109. numPromptInputs: len(inputs),
  110. startProcessingTime: startTime,
  111. numPredict: params.numPredict,
  112. pendingResponses: make([]string, 0),
  113. responses: make(chan string, 100),
  114. quit: make(chan bool, 1),
  115. embedding: make(chan []float32, 1),
  116. samplingCtx: sc,
  117. embeddingOnly: params.embedding,
  118. stop: params.stop,
  119. numKeep: params.numKeep,
  120. }, nil
  121. }
  122. // inputs processes the prompt and images into a list of inputs
  123. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  124. // generating image embeddings for each image
  125. func (s *Server) inputs(prompt string, images []ImageData) ([]input, error) {
  126. var inputs []input
  127. re := regexp.MustCompile(`\[img-(\d+)\]`)
  128. parts := re.Split(prompt, -1)
  129. matches := re.FindAllStringSubmatch(prompt, -1)
  130. for i, part := range parts {
  131. // text - tokenize
  132. if strings.TrimSpace(part) != "" {
  133. tokens, err := s.lc.Model().Tokenize(part, i == 0, true)
  134. if err != nil {
  135. return nil, err
  136. }
  137. for _, t := range tokens {
  138. inputs = append(inputs, input{token: t})
  139. }
  140. }
  141. // image - generate image embedding
  142. if i < len(matches) {
  143. n, _ := strconv.Atoi(matches[i][1])
  144. imageIndex := -1
  145. for j := range images {
  146. if images[j].ID == n {
  147. imageIndex = j
  148. break
  149. }
  150. }
  151. if imageIndex < 0 {
  152. return nil, fmt.Errorf("invalid image index: %d", n)
  153. }
  154. embed, err := s.image.NewEmbed(s.lc, images[imageIndex].Data, images[imageIndex].AspectRatioID)
  155. if err != nil {
  156. return nil, err
  157. }
  158. for _, e := range embed {
  159. inputs = append(inputs, input{embed: e})
  160. }
  161. }
  162. }
  163. return inputs, nil
  164. }
  165. type Server struct {
  166. // is the server ready to process requests?
  167. // protects access to model and image
  168. ready sync.WaitGroup
  169. // loaded model
  170. model *llama.Model
  171. // image model context for multi-modal models
  172. image *ImageContext
  173. // status for external health reporting - loading, ready to serve, etc.
  174. status ServerStatus
  175. // current progress on loading the model
  176. progress float32
  177. // number of simultaneous requests to handle
  178. parallel int
  179. // maximum number of elements in a batch (per sequence)
  180. // TODO (jmorganca): make this n_batch
  181. batchSize int
  182. // protects access to everything below this line
  183. // this is context state needed for decoding
  184. mu sync.Mutex
  185. // indicates that data is ready for processing
  186. cond *sync.Cond
  187. // decoding state
  188. lc *llama.Context
  189. // the list of simultaneous sequences being evaluated
  190. seqs []*Sequence
  191. // seqs can have a maximum of parallel entries, which
  192. // is enfoced by seqSem
  193. seqsSem *semaphore.Weighted
  194. // KV cache
  195. cache *InputCache
  196. // next sequence for prompt processing to avoid starvation
  197. nextSeq int
  198. }
  199. func (s *Server) allNil() bool {
  200. for _, item := range s.seqs {
  201. if item != nil {
  202. return false
  203. }
  204. }
  205. return true
  206. }
  207. func flushPending(seq *Sequence) bool {
  208. joined := strings.Join(seq.pendingResponses, "")
  209. seq.pendingResponses = []string{}
  210. // Check if there are any partial UTF-8 characters remaining.
  211. // We already check and queue as we are generating but some may
  212. // still make it here:
  213. // - Sequence is ending, e.g. generation limit has been hit
  214. // - Invalid characters in the middle of a string
  215. // This is a stricter check to ensure we never output invalid Unicode.
  216. for !utf8.ValidString(joined) {
  217. joined = joined[:len(joined)-1]
  218. }
  219. if len(joined) == 0 {
  220. return true
  221. }
  222. select {
  223. case seq.responses <- joined:
  224. return true
  225. case <-seq.quit:
  226. return false
  227. }
  228. }
  229. func (s *Server) removeSequence(seqIndex int, reason string) {
  230. seq := s.seqs[seqIndex]
  231. flushPending(seq)
  232. seq.doneReason = reason
  233. close(seq.responses)
  234. close(seq.embedding)
  235. seq.cache.InUse = false
  236. s.seqs[seqIndex] = nil
  237. }
  238. func (s *Server) run(ctx context.Context) {
  239. s.ready.Wait()
  240. // Logically these batches are used only within the context of processBatch
  241. // but it is better for performance to allocate them once here
  242. tokenBatch, err := llama.NewBatch(s.batchSize, len(s.seqs), 0)
  243. if err != nil {
  244. panic(err)
  245. }
  246. defer tokenBatch.Free()
  247. var embedBatch *llama.Batch
  248. embedBatchSize := s.image.BatchSize(s.batchSize)
  249. if embedBatchSize != 0 {
  250. embedBatch, err = llama.NewBatch(embedBatchSize, len(s.seqs), s.image.EmbedSize(s.lc))
  251. if err != nil {
  252. panic(err)
  253. }
  254. defer embedBatch.Free()
  255. } else {
  256. embedBatch = &llama.Batch{}
  257. }
  258. for {
  259. select {
  260. case <-ctx.Done():
  261. return
  262. default:
  263. s.processBatch(tokenBatch, embedBatch)
  264. tokenBatch.Clear()
  265. embedBatch.Clear()
  266. }
  267. }
  268. }
  269. // TODO (jmorganca): processBatch should be simplified, removing:
  270. // * sampling
  271. // * stop token checking
  272. // * metrics
  273. // these should instead be handled by the handlers
  274. // it should only be responsible for accepting tokens or embeddings and
  275. // processing batches as fast as possible
  276. func (s *Server) processBatch(tokenBatch *llama.Batch, embedBatch *llama.Batch) {
  277. s.mu.Lock()
  278. for s.allNil() {
  279. s.cond.Wait() // Wait until an item is added
  280. }
  281. defer s.mu.Unlock()
  282. var batch *llama.Batch
  283. crossAttention := false
  284. seqIdx := s.nextSeq - 1
  285. for range s.seqs {
  286. seqIdx = (seqIdx + 1) % len(s.seqs)
  287. seq := s.seqs[seqIdx]
  288. if seq == nil {
  289. continue
  290. }
  291. // if past the num predict limit
  292. if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
  293. s.removeSequence(seqIdx, "limit")
  294. continue
  295. }
  296. var numInputsProcessed int
  297. shifted := false
  298. for i, input := range seq.inputs {
  299. if len(seq.cache.Inputs)+1 > s.cache.numCtx {
  300. if !shifted {
  301. s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
  302. shifted = true
  303. } else {
  304. break
  305. }
  306. }
  307. embedding := input.embed != nil
  308. // If we don't currently have a batch, use one of the correct type and
  309. // fill it up as much as possible across all sequences. If we encounter an
  310. // input of the opppsite type, stop for that sequence but then pick up from
  311. // there for the next batch, ensuring that we alternate types
  312. if batch == nil {
  313. if !embedding {
  314. batch = tokenBatch
  315. } else {
  316. batch = embedBatch
  317. seq.crossAttention = s.image.NeedCrossAttention(input)
  318. }
  319. } else if embedding != batch.IsEmbedding() || crossAttention != seq.crossAttention {
  320. s.nextSeq = seqIdx
  321. break
  322. }
  323. if i >= batch.Size() {
  324. break
  325. }
  326. crossAttention = seq.crossAttention
  327. batch.Add(input.token, input.embed, len(seq.cache.Inputs), i+1 == len(seq.inputs), seq.cache.Id)
  328. seq.cache.Inputs = append(seq.cache.Inputs, input)
  329. numInputsProcessed++
  330. }
  331. if numInputsProcessed > 0 {
  332. seq.inputs = seq.inputs[numInputsProcessed:]
  333. seq.iBatch = batch.NumTokens() - 1
  334. }
  335. }
  336. if batch == nil || batch.NumTokens() == 0 {
  337. return
  338. }
  339. s.lc.SetCrossAttention(crossAttention)
  340. err := s.lc.Decode(batch)
  341. if err != nil {
  342. slog.Error("failed to decode batch", "error", err)
  343. return
  344. }
  345. if crossAttention {
  346. // synchronize state to ensure the cross attention batch is complete.
  347. // needed specifically for multi-GPU systems otherwise an inflight
  348. // task may be incorrectly invalidated causing a crash
  349. s.lc.Synchronize()
  350. }
  351. for i, seq := range s.seqs {
  352. if seq == nil {
  353. continue
  354. }
  355. // don't sample prompt processing
  356. if len(seq.inputs) != 0 {
  357. continue
  358. }
  359. seq.numDecoded += 1
  360. if seq.numDecoded == 1 {
  361. seq.startGenerationTime = time.Now()
  362. }
  363. // if done processing the prompt, generate an embedding and return
  364. if seq.embeddingOnly {
  365. embed := s.lc.GetEmbeddingsSeq(i)
  366. if embed == nil {
  367. embed = s.lc.GetEmbeddingsIth(seq.iBatch)
  368. }
  369. seq.embedding <- embed
  370. s.removeSequence(i, "")
  371. continue
  372. }
  373. // sample a token
  374. token := seq.samplingCtx.Sample(s.lc, seq.iBatch)
  375. seq.samplingCtx.Accept(token, true)
  376. piece := s.model.TokenToPiece(token)
  377. seq.numPredicted++
  378. // if it's an end of sequence token, break
  379. if s.model.TokenIsEog(token) {
  380. // TODO (jmorganca): we should send this back
  381. // as it's important for the /api/generate context
  382. // seq.responses <- piece
  383. s.removeSequence(i, "stop")
  384. continue
  385. }
  386. seq.inputs = []input{{token: token}}
  387. seq.pendingResponses = append(seq.pendingResponses, piece)
  388. sequence := strings.Join(seq.pendingResponses, "")
  389. if ok, stop := findStop(sequence, seq.stop); ok {
  390. slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)
  391. var tokenTruncated bool
  392. origLen := len(seq.pendingResponses)
  393. seq.pendingResponses, tokenTruncated = truncateStop(seq.pendingResponses, stop)
  394. newLen := len(seq.pendingResponses)
  395. // Update the cache based on the tokens that will be returned:
  396. // - We have 1 token more than is currently in the cache because
  397. // the last one generated wasn't submitted to Decode
  398. // - Remove any stop sequences that we stripped out
  399. // - If truncateStop removed a portion of a token, drop that
  400. // - As defense-in-depth, if truncatedToken didn't find a stop token
  401. // remove the extra one that we added to the cache len
  402. tokenLen := len(seq.cache.Inputs) + 1
  403. tokenLen -= origLen - newLen
  404. if tokenTruncated || origLen == newLen {
  405. tokenLen--
  406. }
  407. seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
  408. s.removeSequence(i, "stop")
  409. continue
  410. }
  411. if containsStopSuffix(sequence, seq.stop) {
  412. continue
  413. }
  414. if incompleteUnicode(sequence) {
  415. continue
  416. }
  417. if !flushPending(seq) {
  418. s.removeSequence(i, "connection")
  419. }
  420. }
  421. }
  422. // TODO (jmorganca): use structs from the api package to avoid duplication
  423. // this way the api acts as a proxy instead of using a different api for the
  424. // runner
  425. type Options struct {
  426. api.Runner
  427. NumKeep int `json:"n_keep"`
  428. Seed int `json:"seed"`
  429. NumPredict int `json:"n_predict"`
  430. TopK int `json:"top_k"`
  431. TopP float32 `json:"top_p"`
  432. MinP float32 `json:"min_p"`
  433. TFSZ float32 `json:"tfs_z"`
  434. TypicalP float32 `json:"typical_p"`
  435. RepeatLastN int `json:"repeat_last_n"`
  436. Temperature float32 `json:"temperature"`
  437. RepeatPenalty float32 `json:"repeat_penalty"`
  438. PresencePenalty float32 `json:"presence_penalty"`
  439. FrequencyPenalty float32 `json:"frequency_penalty"`
  440. Mirostat int `json:"mirostat"`
  441. MirostatTau float32 `json:"mirostat_tau"`
  442. MirostatEta float32 `json:"mirostat_eta"`
  443. PenalizeNewline bool `json:"penalize_nl"`
  444. Stop []string `json:"stop"`
  445. }
  446. type ImageData struct {
  447. Data []byte `json:"data"`
  448. ID int `json:"id"`
  449. AspectRatioID int `json:"aspect_ratio_id"`
  450. }
  451. type CompletionRequest struct {
  452. Prompt string `json:"prompt"`
  453. Images []ImageData `json:"image_data"`
  454. Grammar string `json:"grammar"`
  455. CachePrompt bool `json:"cache_prompt"`
  456. Options
  457. }
  458. type Timings struct {
  459. PredictedN int `json:"predicted_n"`
  460. PredictedMS float64 `json:"predicted_ms"`
  461. PromptN int `json:"prompt_n"`
  462. PromptMS float64 `json:"prompt_ms"`
  463. }
  464. type CompletionResponse struct {
  465. Content string `json:"content"`
  466. Stop bool `json:"stop"`
  467. Model string `json:"model,omitempty"`
  468. Prompt string `json:"prompt,omitempty"`
  469. StoppedLimit bool `json:"stopped_limit,omitempty"`
  470. PredictedN int `json:"predicted_n,omitempty"`
  471. PredictedMS float64 `json:"predicted_ms,omitempty"`
  472. PromptN int `json:"prompt_n,omitempty"`
  473. PromptMS float64 `json:"prompt_ms,omitempty"`
  474. Timings Timings `json:"timings"`
  475. }
  476. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  477. var req CompletionRequest
  478. req.Options = Options(api.DefaultOptions())
  479. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  480. http.Error(w, "Bad request", http.StatusBadRequest)
  481. return
  482. }
  483. // Set the headers to indicate streaming
  484. w.Header().Set("Content-Type", "application/json")
  485. w.Header().Set("Transfer-Encoding", "chunked")
  486. flusher, ok := w.(http.Flusher)
  487. if !ok {
  488. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  489. return
  490. }
  491. var samplingParams llama.SamplingParams
  492. samplingParams.TopK = req.TopK
  493. samplingParams.TopP = req.TopP
  494. samplingParams.MinP = req.MinP
  495. samplingParams.TfsZ = req.TFSZ
  496. samplingParams.TypicalP = req.TypicalP
  497. samplingParams.Temp = req.Temperature
  498. samplingParams.RepeatLastN = req.RepeatLastN
  499. samplingParams.PenaltyRepeat = req.RepeatPenalty
  500. samplingParams.PenaltyFreq = req.FrequencyPenalty
  501. samplingParams.PenaltyPresent = req.PresencePenalty
  502. samplingParams.Mirostat = req.Mirostat
  503. samplingParams.MirostatTau = req.MirostatTau
  504. samplingParams.MirostatEta = req.MirostatEta
  505. samplingParams.PenalizeNl = req.PenalizeNewline
  506. samplingParams.Seed = uint32(req.Seed)
  507. samplingParams.Grammar = req.Grammar
  508. seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
  509. numPredict: req.NumPredict,
  510. stop: req.Stop,
  511. numKeep: req.NumKeep,
  512. samplingParams: &samplingParams,
  513. embedding: false,
  514. })
  515. if err != nil {
  516. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  517. return
  518. }
  519. // Ensure that a place to put the sequence is available
  520. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  521. slog.Error("Failed to acquire semaphore", "error", err)
  522. return
  523. }
  524. defer s.seqsSem.Release(1)
  525. s.mu.Lock()
  526. for i, sq := range s.seqs {
  527. if sq == nil {
  528. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  529. if err != nil {
  530. s.mu.Unlock()
  531. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  532. return
  533. }
  534. seq.crossAttention = s.image.NeedCrossAttention(seq.cache.Inputs...)
  535. s.seqs[i] = seq
  536. s.cond.Signal()
  537. break
  538. }
  539. }
  540. s.mu.Unlock()
  541. for {
  542. select {
  543. case <-r.Context().Done():
  544. close(seq.quit)
  545. return
  546. case content, ok := <-seq.responses:
  547. if ok {
  548. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  549. Content: content,
  550. }); err != nil {
  551. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  552. close(seq.quit)
  553. return
  554. }
  555. flusher.Flush()
  556. } else {
  557. // Send the final response
  558. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  559. Stop: true,
  560. StoppedLimit: seq.doneReason == "limit",
  561. Timings: Timings{
  562. PromptN: seq.numPromptInputs,
  563. PromptMS: float64(seq.startGenerationTime.Sub(seq.startProcessingTime).Milliseconds()),
  564. PredictedN: seq.numDecoded,
  565. PredictedMS: float64(time.Since(seq.startGenerationTime).Milliseconds()),
  566. },
  567. }); err != nil {
  568. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  569. }
  570. return
  571. }
  572. }
  573. }
  574. }
  575. type EmbeddingRequest struct {
  576. Content string `json:"content"`
  577. CachePrompt bool `json:"cache_prompt"`
  578. }
  579. type EmbeddingResponse struct {
  580. Embedding []float32 `json:"embedding"`
  581. }
  582. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  583. var req EmbeddingRequest
  584. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  585. http.Error(w, fmt.Sprintf("bad request: %s", err), http.StatusBadRequest)
  586. return
  587. }
  588. w.Header().Set("Content-Type", "application/json")
  589. slog.Debug("embedding request", "content", req.Content)
  590. seq, err := s.NewSequence(req.Content, nil, NewSequenceParams{embedding: true})
  591. if err != nil {
  592. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  593. return
  594. }
  595. // Ensure that a place to put the sequence is available
  596. if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
  597. slog.Error("Failed to acquire semaphore", "error", err)
  598. return
  599. }
  600. defer s.seqsSem.Release(1)
  601. s.mu.Lock()
  602. for i, sq := range s.seqs {
  603. if sq == nil {
  604. seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs, req.CachePrompt)
  605. if err != nil {
  606. s.mu.Unlock()
  607. http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
  608. return
  609. }
  610. s.seqs[i] = seq
  611. s.cond.Signal()
  612. break
  613. }
  614. }
  615. s.mu.Unlock()
  616. embedding := <-seq.embedding
  617. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  618. Embedding: embedding,
  619. }); err != nil {
  620. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  621. }
  622. }
  623. type HealthResponse struct {
  624. Status string `json:"status"`
  625. Progress float32 `json:"progress"`
  626. }
  627. type ServerStatus int
  628. const (
  629. ServerStatusReady ServerStatus = iota
  630. ServerStatusLoadingModel
  631. ServerStatusError
  632. )
  633. func (s ServerStatus) ToString() string {
  634. switch s {
  635. case ServerStatusReady:
  636. return "ok"
  637. case ServerStatusLoadingModel:
  638. return "loading model"
  639. default:
  640. return "server error"
  641. }
  642. }
  643. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  644. w.Header().Set("Content-Type", "application/json")
  645. if err := json.NewEncoder(w).Encode(&HealthResponse{
  646. Status: s.status.ToString(),
  647. Progress: s.progress,
  648. }); err != nil {
  649. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  650. }
  651. }
  652. func (s *Server) loadModel(
  653. params llama.ModelParams,
  654. mpath string,
  655. lpath string,
  656. ppath string,
  657. kvSize int,
  658. flashAttention bool,
  659. threads int,
  660. multiUserCache bool,
  661. ) {
  662. llama.BackendInit()
  663. var err error
  664. s.model, err = llama.LoadModelFromFile(mpath, params)
  665. if err != nil {
  666. panic(err)
  667. }
  668. ctxParams := llama.NewContextParams(kvSize, s.batchSize*s.parallel, s.parallel, threads, flashAttention)
  669. s.lc, err = llama.NewContextWithModel(s.model, ctxParams)
  670. if err != nil {
  671. panic(err)
  672. }
  673. if lpath != "" {
  674. err := s.model.ApplyLoraFromFile(s.lc, lpath, 1.0, threads)
  675. if err != nil {
  676. panic(err)
  677. }
  678. }
  679. if ppath != "" {
  680. var err error
  681. s.image, err = NewImageContext(s.lc, ppath)
  682. if err != nil {
  683. panic(err)
  684. }
  685. }
  686. s.cache, err = NewInputCache(s.lc, kvSize, s.parallel, multiUserCache)
  687. if err != nil {
  688. panic(err)
  689. }
  690. s.status = ServerStatusReady
  691. s.ready.Done()
  692. }
  693. func main() {
  694. mpath := flag.String("model", "", "Path to model binary file")
  695. ppath := flag.String("mmproj", "", "Path to projector binary file")
  696. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  697. batchSize := flag.Int("batch-size", 512, "Batch size")
  698. nGpuLayers := flag.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  699. mainGpu := flag.Int("main-gpu", 0, "Main GPU")
  700. flashAttention := flag.Bool("flash-attn", false, "Enable flash attention")
  701. kvSize := flag.Int("ctx-size", 2048, "Context (or KV cache) size")
  702. lpath := flag.String("lora", "", "Path to lora layer file")
  703. port := flag.Int("port", 8080, "Port to expose the server on")
  704. threads := flag.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  705. verbose := flag.Bool("verbose", false, "verbose output (default: disabled)")
  706. noMmap := flag.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  707. mlock := flag.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  708. tensorSplit := flag.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  709. multiUserCache := flag.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
  710. requirements := flag.Bool("requirements", false, "print json requirement information")
  711. flag.Parse()
  712. if *requirements {
  713. printRequirements(os.Stdout)
  714. return
  715. }
  716. level := slog.LevelInfo
  717. if *verbose {
  718. level = slog.LevelDebug
  719. }
  720. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  721. Level: level,
  722. AddSource: true,
  723. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  724. if attr.Key == slog.SourceKey {
  725. source := attr.Value.Any().(*slog.Source)
  726. source.File = filepath.Base(source.File)
  727. }
  728. return attr
  729. },
  730. })
  731. slog.SetDefault(slog.New(handler))
  732. slog.Info("starting go runner")
  733. slog.Info("system", "info", llama.PrintSystemInfo(), "threads", *threads)
  734. server := &Server{
  735. batchSize: *batchSize,
  736. parallel: *parallel,
  737. seqs: make([]*Sequence, *parallel),
  738. seqsSem: semaphore.NewWeighted(int64(*parallel)),
  739. status: ServerStatusLoadingModel,
  740. }
  741. var tensorSplitFloats []float32
  742. if *tensorSplit != "" {
  743. stringFloats := regexp.MustCompile(",").Split(*tensorSplit, -1)
  744. tensorSplitFloats = make([]float32, 0, len(stringFloats))
  745. for _, s := range stringFloats {
  746. f, _ := strconv.ParseFloat(s, 32)
  747. tensorSplitFloats = append(tensorSplitFloats, float32(f))
  748. }
  749. }
  750. params := llama.ModelParams{
  751. NumGpuLayers: *nGpuLayers,
  752. MainGpu: *mainGpu,
  753. UseMmap: !*noMmap && *lpath == "",
  754. UseMlock: *mlock,
  755. TensorSplit: tensorSplitFloats,
  756. Progress: func(progress float32) {
  757. server.progress = progress
  758. },
  759. }
  760. server.ready.Add(1)
  761. go server.loadModel(params, *mpath, *lpath, *ppath, *kvSize, *flashAttention, *threads, *multiUserCache)
  762. server.cond = sync.NewCond(&server.mu)
  763. ctx, cancel := context.WithCancel(context.Background())
  764. go server.run(ctx)
  765. addr := "127.0.0.1:" + strconv.Itoa(*port)
  766. listener, err := net.Listen("tcp", addr)
  767. if err != nil {
  768. fmt.Println("Listen error:", err)
  769. return
  770. }
  771. defer listener.Close()
  772. mux := http.NewServeMux()
  773. mux.HandleFunc("/embedding", server.embeddings)
  774. mux.HandleFunc("/completion", server.completion)
  775. mux.HandleFunc("/health", server.health)
  776. httpServer := http.Server{
  777. Handler: mux,
  778. }
  779. log.Println("Server listening on", addr)
  780. if err := httpServer.Serve(listener); err != nil {
  781. log.Fatal("server error:", err)
  782. }
  783. cancel()
  784. }