runner.go 25 KB

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