runner.go 24 KB

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