runner.go 24 KB

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