runner.go 25 KB

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