runner.go 25.6 KB
Newer Older
Jesse Gross's avatar
Jesse Gross committed
1
package ollamarunner
2
3

import (
4
	"bytes"
5
6
7
8
9
	"context"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
10
	"hash/maphash"
11
	"image"
12
13
14
15
16
17
18
19
20
21
22
	"log"
	"log/slog"
	"net"
	"net/http"
	"os"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
23
	"unicode/utf8"
24

25
	"golang.org/x/image/bmp"
26
27
	"golang.org/x/sync/semaphore"

28
	"github.com/ollama/ollama/api"
29
	"github.com/ollama/ollama/envconfig"
30
	"github.com/ollama/ollama/llm"
31
	"github.com/ollama/ollama/logutil"
32
	"github.com/ollama/ollama/ml"
Jesse Gross's avatar
Jesse Gross committed
33
	"github.com/ollama/ollama/model"
34
	"github.com/ollama/ollama/model/input"
Jesse Gross's avatar
Jesse Gross committed
35
36
37
38
	"github.com/ollama/ollama/runner/common"
	"github.com/ollama/ollama/sample"

	_ "github.com/ollama/ollama/model/models"
39
40
41
)

type Sequence struct {
42
	// ctxs are used for allocating tensors that last the lifetime of the sequence, such as
43
	// multimodal embeddings
44
	ctxs []ml.Context
45

46
47
48
	// mmStore holds multimodal embeddings to mange memory and enable splitting across batches
	mmStore multimodalStore

49
50
51
52
	// batch index
	iBatch int

	// prompt inputs left to evaluate
53
	inputs []input.Input
54

Jesse Gross's avatar
Jesse Gross committed
55
	// inputs that have been added to a batch but not yet submitted to Forward
56
	pendingInputs []input.Input
57

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
	// tokens that have been generated but not returned yet (e.g. for stop sequences)
	pendingResponses []string

	// input cache being used by this sequence
	cache *InputCacheSlot

	// channel to send responses over
	responses chan string

	// channel to stop decoding (such as if the remote connection is closed)
	quit chan bool

	// number of tokens to predict
	numPredict int

73
74
	// sampler with transforms to run on generated logits
	sampler sample.Sampler
75
76
77
78
79
80
81
82

	// channel to send back the embedding if embedding only
	embedding chan []float32

	// stop sequences
	stop []string

	// number of inputs to keep at the beginning when shifting context window
Jesse Gross's avatar
Jesse Gross committed
83
	numKeep int32
84
85
86
87

	// true if an embedding are to be returned instead of text generation
	embeddingOnly bool

88
	doneReason llm.DoneReason
89
90
91
92

	// Metrics
	startProcessingTime time.Time
	startGenerationTime time.Time
Jesse Gross's avatar
Jesse Gross committed
93
	numPredicted        int
94
95
96
97
	numPromptInputs     int
}

type NewSequenceParams struct {
Jesse Gross's avatar
Jesse Gross committed
98
99
100
	numPredict int
	stop       []string
	numKeep    int32
101
	sampler    sample.Sampler
Jesse Gross's avatar
Jesse Gross committed
102
	embedding  bool
103
104
}

105
func (s *Server) NewSequence(prompt string, images []llm.ImageData, params NewSequenceParams) (*Sequence, error) {
106
107
108
109
	s.ready.Wait()

	startTime := time.Now()

110
	inputs, ctxs, mmStore, err := s.inputs(prompt, images)
111
112
113
114
115
116
117
	if err != nil {
		return nil, fmt.Errorf("failed to process inputs: %w", err)
	} else if len(inputs) == 0 {
		return nil, errors.New("no input provided")
	}

	if params.numKeep < 0 {
Jesse Gross's avatar
Jesse Gross committed
118
		params.numKeep = int32(len(inputs))
119
120
	}

121
122
123
	// Ensure that at least 1 input can be discarded during shift
	params.numKeep = min(params.numKeep, s.cache.numCtx-1)

Jesse Gross's avatar
Jesse Gross committed
124
125
	if int32(len(inputs)) > s.cache.numCtx {
		discard := int32(len(inputs)) - s.cache.numCtx
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
		promptStart := params.numKeep + discard

		// If we need to truncate in the middle of a unbreakable batch, remove the entire batch
		sameBatch := 0
		for i, inp := range inputs {
			if sameBatch > 0 {
				sameBatch--

				if promptStart == int32(i) {
					promptStart++
				}
			} else if promptStart == int32(i) {
				break
			}

			if inp.SameBatch != 0 {
				if int32(i) < params.numKeep {
					return nil, fmt.Errorf("SameBatch may not be specified within numKeep (index: %v numKeep: %v SameBatch: %v)", i, params.numKeep, inp.SameBatch)
				}

				sameBatch = inp.SameBatch
			}
		}

		if promptStart >= int32(len(inputs)) {
			return nil, errors.New("entire prompt removed by truncation")
		}

154
		newInputs := inputs[:params.numKeep]
155
		newInputs = append(newInputs, inputs[promptStart:]...)
156
157

		slog.Warn("truncating input prompt", "limit", s.cache.numCtx, "prompt", len(inputs), "keep", params.numKeep, "new", len(newInputs))
158
		inputs = newInputs
159
160
	}

Jesse Gross's avatar
Jesse Gross committed
161
	// TODO(jessegross): Ingest cached history for grammar
162
163

	return &Sequence{
164
		ctxs:                ctxs,
165
		mmStore:             mmStore,
166
167
168
169
170
171
172
173
		inputs:              inputs,
		numPromptInputs:     len(inputs),
		startProcessingTime: startTime,
		numPredict:          params.numPredict,
		pendingResponses:    make([]string, 0),
		responses:           make(chan string, 100),
		quit:                make(chan bool, 1),
		embedding:           make(chan []float32, 1),
174
		sampler:             params.sampler,
175
176
177
178
179
180
181
182
		embeddingOnly:       params.embedding,
		stop:                params.stop,
		numKeep:             params.numKeep,
	}, nil
}

// inputs processes the prompt and images into a list of inputs
// by splitting the prompt on [img-<n>] tags, tokenizing text and
Jesse Gross's avatar
Jesse Gross committed
183
// decoding images
184
func (s *Server) inputs(prompt string, images []llm.ImageData) ([]input.Input, []ml.Context, multimodalStore, error) {
185
	var inputs []input.Input
186
	var ctxs []ml.Context
187
	var mmStore multimodalStore
188

189
190
191
	var parts []string
	var matches [][]string

192
	multimodalProcessor, visionModel := s.model.(model.MultimodalProcessor)
193

194
195
196
197
	if visionModel {
		re := regexp.MustCompile(`\[img-(\d+)\]`)
		parts = re.Split(prompt, -1)
		matches = re.FindAllStringSubmatch(prompt, -1)
198
		mmStore = newMultimodalStore()
199
200
201
202
203
	} else {
		parts = []string{prompt}
	}

	postTokenize := false
204
205
	for i, part := range parts {
		// text - tokenize
206
		tokens, err := s.model.(model.TextProcessor).Encode(part, i == 0)
207
		if err != nil {
208
			return nil, nil, nil, err
209
		}
210

211
		for _, t := range tokens {
212
			inputs = append(inputs, input.Input{Token: t})
213
214
		}

Jesse Gross's avatar
Jesse Gross committed
215
		// image - decode and store
216
217
218
219
220
221
222
223
224
225
226
227
		if i < len(matches) {
			n, _ := strconv.Atoi(matches[i][1])

			imageIndex := -1
			for j := range images {
				if images[j].ID == n {
					imageIndex = j
					break
				}
			}

			if imageIndex < 0 {
228
				return nil, nil, nil, fmt.Errorf("invalid image index: %d", n)
229
230
			}

231
			ctx := s.model.Backend().NewContext()
232
233
			runtime.SetFinalizer(ctx, func(c ml.Context) { c.Close() })
			ctxs = append(ctxs, ctx)
234
			imageEmbeddings, err := multimodalProcessor.EncodeMultimodal(ctx, images[imageIndex].Data)
Jesse Gross's avatar
Jesse Gross committed
235
			if err != nil {
236
				return nil, nil, nil, err
Jesse Gross's avatar
Jesse Gross committed
237
238
			}

239
240
241
242
			s.multimodalHash.Reset()
			_, _ = s.multimodalHash.Write(images[imageIndex].Data)
			imageHash := s.multimodalHash.Sum64()

243
244
			mmStore.addMultimodal(imageEmbeddings)

245
			inputs = append(inputs, input.Input{Multimodal: imageEmbeddings, MultimodalHash: imageHash})
246
247
248
249
250
251
			postTokenize = true
		}
	}

	if visionModel && postTokenize {
		var err error
252
		inputs, err = multimodalProcessor.PostTokenize(inputs)
253
		if err != nil {
254
			return nil, nil, nil, err
255
256
257
		}
	}

258
	return inputs, ctxs, mmStore, nil
259
260
261
}

type Server struct {
262
263
264
265
266
	// is the server ready to process requests?
	// protects access to model and image
	ready sync.WaitGroup

	// loaded model
Jesse Gross's avatar
Jesse Gross committed
267
	model model.Model
268

269
	// status for external health reporting - loading, ready to serve, etc.
270
	status llm.ServerStatus
271
272
273
274
275
276
277
278

	// current progress on loading the model
	progress float32

	// number of simultaneous requests to handle
	parallel int

	// maximum number of elements in a batch (per sequence)
279
	// TODO (jmorganca): make this n_batch
280
281
	batchSize int

282
283
284
285
286
287
288
289
	// protects access to everything below this line
	// this is context state needed for decoding
	mu sync.Mutex

	// indicates that data is ready for processing
	cond *sync.Cond

	// the list of simultaneous sequences being evaluated
290
291
	seqs []*Sequence

292
293
294
295
	// seqs can have a maximum of parallel entries, which
	// is enfoced by seqSem
	seqsSem *semaphore.Weighted

296
297
298
	// KV cache
	cache *InputCache

299
300
301
	// next sequence for prompt processing to avoid starvation
	nextSeq int

302
303
304
	// multimodalHash generates hashes for comparing equality
	// of non-text data
	multimodalHash maphash.Hash
305
306
307
308
309
310
311
312
313
314
315
316
}

func (s *Server) allNil() bool {
	for _, item := range s.seqs {
		if item != nil {
			return false
		}
	}
	return true
}

func flushPending(seq *Sequence) bool {
317
318
319
320
321
322
323
324
325
326
327
	joined := strings.Join(seq.pendingResponses, "")
	seq.pendingResponses = []string{}

	// Check if there are any partial UTF-8 characters remaining.
	// We already check and queue as we are generating but some may
	// still make it here:
	// - Sequence is ending, e.g. generation limit has been hit
	// - Invalid characters in the middle of a string
	// This is a stricter check to ensure we never output invalid Unicode.
	for !utf8.ValidString(joined) {
		joined = joined[:len(joined)-1]
328
329
	}

330
331
332
333
334
335
336
337
338
339
	if len(joined) == 0 {
		return true
	}

	select {
	case seq.responses <- joined:
		return true
	case <-seq.quit:
		return false
	}
340
341
}

342
func (s *Server) removeSequence(seqIndex int, reason llm.DoneReason) {
343
344
345
346
347
348
349
350
	seq := s.seqs[seqIndex]

	flushPending(seq)
	seq.doneReason = reason
	close(seq.responses)
	close(seq.embedding)
	seq.cache.InUse = false
	s.seqs[seqIndex] = nil
351
	s.seqsSem.Release(1)
352
353
354
355
356
357
358
359
360
361
}

func (s *Server) run(ctx context.Context) {
	s.ready.Wait()

	for {
		select {
		case <-ctx.Done():
			return
		default:
Jesse Gross's avatar
Jesse Gross committed
362
			err := s.processBatch()
363
364
365
			if err != nil {
				panic(err)
			}
366
367
368
369
		}
	}
}

Jesse Gross's avatar
Jesse Gross committed
370
func (s *Server) processBatch() error {
371
372
373
374
375
376
	s.mu.Lock()
	for s.allNil() {
		s.cond.Wait() // Wait until an item is added
	}
	defer s.mu.Unlock()

377
378
379
	ctx := s.model.Backend().NewContext()
	defer ctx.Close()

380
	var batchInputs []int32
Jesse Gross's avatar
Jesse Gross committed
381
	var batch input.Batch
382

383
384
385
386
387
388
	resumeSeq := -1
	seqIdx := s.nextSeq - 1
	for range s.seqs {
		seqIdx = (seqIdx + 1) % len(s.seqs)
		seq := s.seqs[seqIdx]

389
390
391
392
393
		if seq == nil {
			continue
		}

		// if past the num predict limit
394
		if seq.numPredict > 0 && seq.numPredicted >= seq.numPredict {
395
			s.removeSequence(seqIdx, llm.DoneReasonLength)
396
397
398
			continue
		}

Jesse Gross's avatar
Jesse Gross committed
399
400
		if !s.cache.enabled {
			seq.inputs = append(seq.cache.Inputs, seq.inputs...)
401
			seq.cache.Inputs = []input.Input{}
Jesse Gross's avatar
Jesse Gross committed
402
403
		}

404
405
		batchSize := s.batchSize

406
		for i, inp := range seq.inputs {
407
408
			// If we are required to put following inputs into a single batch then extend the
			// batch size. Since we are only extending the size the minimum amount possible, this
409
			// will cause a break if we have existing inputs.
410
411
412
413
414
			minBatch := 1 + inp.SameBatch
			if minBatch > batchSize {
				batchSize = minBatch
			}

415
416
417
418
419
420
421
422
			// Stop if the required batch would put us over the total batch size (including tokens
			// added by other sequences). If we haven't been able to add anything yet then pick up
			// here again for the next batch to avoid starvation, though we can opportunistically
			// check if other sequences can still squeeze something in.
			if len(batchInputs)+minBatch > batchSize {
				if len(seq.pendingInputs) == 0 && resumeSeq == -1 {
					resumeSeq = seqIdx
				}
423
424
				break
			}
Jesse Gross's avatar
Jesse Gross committed
425

426
427
428
429
430
431
432
433
434
435
			// If the sum of our working set (already processed tokens, tokens we added to this
			// batch, required following tokens) exceeds the context size, then trigger a shift
			// now so we don't have to do one later when we can't break the batch.
			if int32(len(seq.cache.Inputs)+len(seq.pendingInputs)+minBatch) > s.cache.numCtx {
				if len(seq.pendingInputs) != 0 {
					break
				}

				err := s.cache.ShiftCacheSlot(seq.cache, seq.numKeep)
				if err != nil {
436
437
438
439
440
441
442
443
444
					var reprocess *ErrReprocessInputs
					if errors.As(err, &reprocess) {
						// Prepend these inputs to the sequence's inputs queue for reprocessing
						seq.inputs = append(reprocess.Inputs, seq.inputs...)
						// Skip this sequence but continue processing the rest
						continue
					} else {
						return err
					}
445
446
447
				}
			}

448
			batchInputs = append(batchInputs, inp.Token)
449
			if inp.Multimodal != nil {
450
				mm, err := seq.mmStore.getMultimodal(s.model.Backend(), ctx, inp.Multimodal, false)
451
452
453
454
				if err != nil {
					return err
				}
				batch.Multimodal = append(batch.Multimodal, input.MultimodalIndex{Index: len(batchInputs) - 1, Multimodal: mm})
455
456
			}

Jesse Gross's avatar
Jesse Gross committed
457
458
			batch.Positions = append(batch.Positions, int32(len(seq.cache.Inputs)+len(seq.pendingInputs)))
			batch.Sequences = append(batch.Sequences, seq.cache.Id)
Jesse Gross's avatar
Jesse Gross committed
459

Jesse Gross's avatar
Jesse Gross committed
460
			seq.iBatch = len(batch.Outputs)
461
			if i+1 == len(seq.inputs) {
462
				batch.Outputs = append(batch.Outputs, int32(len(batchInputs)-1))
Jesse Gross's avatar
Jesse Gross committed
463
			}
464
			seq.pendingInputs = append(seq.pendingInputs, inp)
465
		}
466
467

		seq.inputs = seq.inputs[len(seq.pendingInputs):]
468
469
	}

470
471
472
473
474
475
	if resumeSeq != -1 {
		s.nextSeq = resumeSeq
	} else {
		s.nextSeq = seqIdx + 1
	}

476
	if len(batchInputs) == 0 {
477
		return nil
478
479
	}

480
	modelOutput, err := model.Forward(ctx, s.model, batchInputs, batch)
481
	if err != nil {
482
		return fmt.Errorf("failed to decode batch: %w", err)
483
484
	}

485
	logits := modelOutput.Floats()
486

487
488
489
490
491
	for i, seq := range s.seqs {
		if seq == nil {
			continue
		}

Jesse Gross's avatar
Jesse Gross committed
492
		// After calling Forward, pending inputs are now in the cache
493
494
		if len(seq.pendingInputs) > 0 {
			seq.cache.Inputs = append(seq.cache.Inputs, seq.pendingInputs...)
495
			seq.pendingInputs = []input.Input{}
496
497
		}

498
499
		// don't sample prompt processing
		if len(seq.inputs) != 0 {
Jesse Gross's avatar
Jesse Gross committed
500
501
502
			if !s.cache.enabled {
				return errors.New("caching disabled but unable to fit entire input in a batch")
			}
503
504
505
			continue
		}

Jesse Gross's avatar
Jesse Gross committed
506
507
		seq.numPredicted++
		if seq.numPredicted == 1 {
508
509
510
511
512
			seq.startGenerationTime = time.Now()
		}

		// if done processing the prompt, generate an embedding and return
		if seq.embeddingOnly {
Jesse Gross's avatar
Jesse Gross committed
513
			// TODO(jessegross): Embedding support
514
			slog.Warn("generation of embedding outputs not yet supported")
515
			s.removeSequence(i, llm.DoneReasonStop)
516
			continue
517
518
519
		}

		// sample a token
Jesse Gross's avatar
Jesse Gross committed
520
		vocabSize := len(logits) / len(batch.Outputs)
521
522

		token, err := seq.sampler.Sample(logits[seq.iBatch*vocabSize : (seq.iBatch+1)*vocabSize])
Jesse Gross's avatar
Jesse Gross committed
523
		if err != nil {
524
			return fmt.Errorf("failed to sample token: %w", err)
Jesse Gross's avatar
Jesse Gross committed
525
		}
526
527

		// if it's an end of sequence token, break
Jesse Gross's avatar
Jesse Gross committed
528
		if s.model.(model.TextProcessor).Is(token, model.SpecialEOS) {
529
530
531
532
			// TODO (jmorganca): we should send this back
			// as it's important for the /api/generate context
			// seq.responses <- piece

533
			s.removeSequence(i, llm.DoneReasonStop)
534
535
536
			continue
		}

Jesse Gross's avatar
Jesse Gross committed
537
538
539
540
541
		piece, err := s.model.(model.TextProcessor).Decode([]int32{token})
		if err != nil {
			return err
		}

542
		seq.inputs = []input.Input{{Token: token}}
543
544
545
546

		seq.pendingResponses = append(seq.pendingResponses, piece)
		sequence := strings.Join(seq.pendingResponses, "")

Jesse Gross's avatar
Jesse Gross committed
547
		if ok, stop := common.FindStop(sequence, seq.stop); ok {
548
549
550
551
			slog.Debug("hit stop token", "pending", seq.pendingResponses, "stop", stop)

			var tokenTruncated bool
			origLen := len(seq.pendingResponses)
Jesse Gross's avatar
Jesse Gross committed
552
			seq.pendingResponses, tokenTruncated = common.TruncateStop(seq.pendingResponses, stop)
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
			newLen := len(seq.pendingResponses)

			// Update the cache based on the tokens that will be returned:
			// - We have 1 token more than is currently in the cache because
			// the last one generated wasn't submitted to Decode
			// - Remove any stop sequences that we stripped out
			// - If truncateStop removed a portion of a token, drop that
			// - As defense-in-depth, if truncatedToken didn't find a stop token
			// remove the extra one that we added to the cache len
			tokenLen := len(seq.cache.Inputs) + 1
			tokenLen -= origLen - newLen
			if tokenTruncated || origLen == newLen {
				tokenLen--
			}
			seq.cache.Inputs = seq.cache.Inputs[:tokenLen]
568

569
			s.removeSequence(i, llm.DoneReasonStop)
570
571
572
			continue
		}

Jesse Gross's avatar
Jesse Gross committed
573
		if common.ContainsStopSuffix(sequence, seq.stop) {
574
575
576
			continue
		}

Jesse Gross's avatar
Jesse Gross committed
577
		if common.IncompleteUnicode(sequence) {
578
579
580
581
			continue
		}

		if !flushPending(seq) {
582
			s.removeSequence(i, llm.DoneReasonConnectionClosed)
583
584
		}
	}
585
586

	return nil
587
588
589
}

func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
590
	var req llm.CompletionRequest
591
592
593
594
595
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}

596
597
598
599
600
	if req.Options == nil {
		opts := api.DefaultOptions()
		req.Options = &opts
	}

601
602
603
604
605
606
607
608
609
610
	// Set the headers to indicate streaming
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Transfer-Encoding", "chunked")

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "Streaming not supported", http.StatusInternalServerError)
		return
	}

611
	var grammar *sample.GrammarSampler
612
613
	var err error
	if req.Grammar != "" {
614
		grammar, err = sample.NewGrammarSampler(s.model.(model.TextProcessor), req.Grammar)
615
616
617
618
		if err != nil {
			http.Error(w, "failed to load model vocabulary required for format", http.StatusInternalServerError)
			return
		}
619
		defer grammar.Free()
620
621
	}

622
	sampler := sample.NewSampler(
623
624
625
626
627
		req.Options.Temperature,
		req.Options.TopK,
		req.Options.TopP,
		req.Options.MinP,
		req.Options.Seed,
628
		grammar,
629
630
	)

631
	seq, err := s.NewSequence(req.Prompt, req.Images, NewSequenceParams{
632
633
634
		numPredict: req.Options.NumPredict,
		stop:       req.Options.Stop,
		numKeep:    int32(req.Options.NumKeep),
635
		sampler:    sampler,
Jesse Gross's avatar
Jesse Gross committed
636
		embedding:  false,
637
638
639
640
641
642
	})
	if err != nil {
		http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
		return
	}

643
	// Ensure there is a place to put the sequence, released when removed from s.seqs
644
	if err := s.seqsSem.Acquire(r.Context(), 1); err != nil {
645
646
647
		if errors.Is(err, context.Canceled) {
			slog.Info("aborting completion request due to client closing the connection")
		} else {
648
			http.Error(w, fmt.Sprintf("Failed to acquire semaphore: %v", err), http.StatusInternalServerError)
649
		}
650
651
652
		return
	}

653
	s.mu.Lock()
654
	found := false
655
656
	for i, sq := range s.seqs {
		if sq == nil {
657
			seq.cache, seq.inputs, err = s.cache.LoadCacheSlot(seq.inputs)
658
659
			if err != nil {
				s.mu.Unlock()
660
				s.seqsSem.Release(1)
661
662
663
				http.Error(w, fmt.Sprintf("Failed to load cache: %v", err), http.StatusInternalServerError)
				return
			}
664

665
666
			s.seqs[i] = seq
			s.cond.Signal()
667
			found = true
668
669
670
671
672
			break
		}
	}
	s.mu.Unlock()

673
	if !found {
674
		s.seqsSem.Release(1)
675
676
677
678
		http.Error(w, "could not find an available sequence", http.StatusInternalServerError)
		return
	}

679
680
681
682
683
684
685
	for {
		select {
		case <-r.Context().Done():
			close(seq.quit)
			return
		case content, ok := <-seq.responses:
			if ok {
686
				if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
687
688
689
690
691
692
693
694
695
					Content: content,
				}); err != nil {
					http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
					close(seq.quit)
					return
				}

				flusher.Flush()
			} else {
696
697
				if err := json.NewEncoder(w).Encode(&llm.CompletionResponse{
					Done:               true,
698
					DoneReason:         seq.doneReason,
699
700
701
702
					PromptEvalCount:    seq.numPromptInputs,
					PromptEvalDuration: seq.startGenerationTime.Sub(seq.startProcessingTime),
					EvalCount:          seq.numPredicted,
					EvalDuration:       time.Since(seq.startGenerationTime),
703
704
705
706
707
708
709
710
711
712
713
714
				}); err != nil {
					http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
				}

				return
			}
		}
	}
}

func (s *Server) health(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
715
716
	if err := json.NewEncoder(w).Encode(&llm.ServerStatusResponse{
		Status:   s.status,
717
718
719
720
721
722
		Progress: s.progress,
	}); err != nil {
		http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
	}
}

723
724
725
726
727
728
729
730
731
732
733
type multiLPath []string

func (m *multiLPath) Set(value string) error {
	*m = append(*m, value)
	return nil
}

func (m *multiLPath) String() string {
	return strings.Join(*m, ", ")
}

734
func (s *Server) reserveWorstCaseGraph() error {
735
736
737
	ctx := s.model.Backend().NewContext()
	defer ctx.Close()

738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
	var err error
	inputs := make([]input.Input, s.batchSize)
	mmStore := newMultimodalStore()

	// Multimodal strategy:
	// - Encode a 2048x2048 image. This assumes that a single image of this
	//   size is sufficient to trigger the worst case. This is currently true
	//   because for existing models, only a single image fits in a batch.
	// - Add the embedding to a full batch of tokens - this is necessary because
	//   the model may be looking for non-image data, such as <image> tags.
	// - Run PostTokenize to execute any transformations between generated
	//   embeddings and what the forward pass expects.
	// - The result may now be larger than a batch (images may not fit in a
	//   single batch), so trim based on what will fit and must be grouped together.
	// - Fill out the rest of the space with text tokens.
	if multimodalProcessor, ok := s.model.(model.MultimodalProcessor); ok {
		mmCtx := s.model.Backend().NewContext()
		defer mmCtx.Close()

		img := image.NewGray(image.Rect(0, 0, 2048, 2048))
		var buf bytes.Buffer
		bmp.Encode(&buf, img)

		if inputs[0].Multimodal, err = multimodalProcessor.EncodeMultimodal(mmCtx, buf.Bytes()); err == nil {
			mmStore.addMultimodal(inputs[0].Multimodal)

			inputs, err = multimodalProcessor.PostTokenize(inputs)
			if err != nil {
				return err
			}

			for i, inp := range inputs {
				minBatch := 1 + inp.SameBatch
				if minBatch > s.batchSize {
					inputs = inputs[i:min(i+minBatch, len(inputs))]
					break
				} else if i+minBatch > s.batchSize {
					inputs = inputs[:i]
					break
				}
			}

			if len(inputs) < s.batchSize {
				newInputs := make([]input.Input, s.batchSize)
				copy(newInputs, inputs)
				inputs = newInputs
			}
		}
	}

788
789
	var batch input.Batch

790
	batchInputs := make([]int32, len(inputs))
791
792
	batch.Positions = make([]int32, len(inputs))
	batch.Sequences = make([]int, len(inputs))
793
794
795
796
797
798
799
800
801
802
	for i, inp := range inputs {
		batchInputs[i] = inp.Token
		if inp.Multimodal != nil {
			mm, err := mmStore.getMultimodal(s.model.Backend(), ctx, inp.Multimodal, true)
			if err != nil {
				return err
			}
			batch.Multimodal = append(batch.Multimodal, input.MultimodalIndex{Index: i, Multimodal: mm})
		}

803
804
805
806
807
808
809
810
		batch.Positions[i] = int32(i)
	}

	batch.Outputs = make([]int32, s.parallel)
	for i := range batch.Outputs {
		batch.Outputs[i] = int32(i)
	}

811
	batch.Inputs = ctx.Input().FromIntSlice(batchInputs, len(batchInputs))
812
813
814
815
816
817
818
819
820
821
822
823
824
825

	cache := s.model.Config().Cache
	if cache != nil {
		err := cache.StartForward(ctx, batch, true)
		if err != nil {
			return err
		}
	}

	t, err := s.model.Forward(ctx, batch)
	if err != nil {
		return err
	}

826
	ctx.Forward(t).Reserve()
827
828

	return nil
829
}
830

831
func (s *Server) initModel(
832
	mpath string,
833
	params ml.BackendParams,
834
	lpath multiLPath,
Jesse Gross's avatar
Jesse Gross committed
835
	parallel int,
836
	kvCacheType string,
Jesse Gross's avatar
Jesse Gross committed
837
	kvSize int,
838
	multiUserCache bool,
839
) error {
840
	var err error
841
	s.model, err = model.New(mpath, params)
842
	if err != nil {
843
		return err
844
	}
845

Jesse Gross's avatar
Jesse Gross committed
846
	// TODO(jessegross): LoRA loading
847
	if lpath.String() != "" {
848
		return errors.New("loras are not yet implemented")
849
850
	}

851
	s.cache, err = NewInputCache(s.model, kvCacheType, int32(kvSize), parallel, s.batchSize, multiUserCache)
852
	if err != nil {
853
		return err
854
	}
855

Jesse Gross's avatar
Jesse Gross committed
856
857
858
859
860
861
862
863
864
	if !s.cache.enabled && parallel > 1 {
		parallel = 1
		slog.Warn("model does not support caching, disabling parallel processing")
	}

	s.parallel = parallel
	s.seqs = make([]*Sequence, s.parallel)
	s.seqsSem = semaphore.NewWeighted(int64(s.parallel))

865
866
867
868
869
870
871
872
873
874
875
	return s.reserveWorstCaseGraph()
}

func (s *Server) load(
	ctx context.Context,
	mpath string,
	params ml.BackendParams,
	lpath multiLPath,
	parallel int,
	kvCacheType string,
	kvSize int,
876
877
	multiUserCache bool,
) {
878
	err := s.initModel(mpath, params, lpath, parallel, kvCacheType, kvSize, multiUserCache)
879
880
	if err != nil {
		panic(err)
881
	}
882

883
884
	slog.Debug("memory", "allocated", s.model.Backend().BackendMemory())

885
886
887
888
889
890
891
892
	err = s.model.Backend().Load(ctx,
		func(progress float32) {
			s.progress = progress
		})
	if err != nil {
		panic(err)
	}

893
	s.status = llm.ServerStatusReady
894
895
896
	s.ready.Done()
}

897
898
899
900
901
func Execute(args []string) error {
	fs := flag.NewFlagSet("runner", flag.ExitOnError)
	mpath := fs.String("model", "", "Path to model binary file")
	parallel := fs.Int("parallel", 1, "Number of sequences to handle simultaneously")
	batchSize := fs.Int("batch-size", 512, "Batch size")
902
903
	numGPULayers := fs.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
	mainGPU := fs.Int("main-gpu", 0, "Main GPU")
904
	flashAttention := fs.Bool("flash-attn", false, "Enable flash attention")
905
906
907
	kvSize := fs.Int("ctx-size", 2048, "Context (or KV cache) size")
	kvCacheType := fs.String("kv-cache-type", "", "quantization type for KV cache (default: f16)")
	port := fs.Int("port", 8080, "Port to expose the server on")
908
	threads := fs.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
909
	_ = fs.Bool("verbose", false, "verbose output (default: disabled)")
Jesse Gross's avatar
Jesse Gross committed
910
	_ = fs.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
911
	tensorSplit := fs.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
912
	multiUserCache := fs.Bool("multiuser-cache", false, "optimize input cache algorithm for multiple users")
913

914
	var lpaths multiLPath
915
	fs.Var(&lpaths, "lora", "Path to lora layer file (can be specified multiple times)")
916

917
918
919
920
921
922
	fs.Usage = func() {
		fmt.Fprintf(fs.Output(), "Runner usage\n")
		fs.PrintDefaults()
	}
	if err := fs.Parse(args); err != nil {
		return err
923
	}
924
	slog.SetDefault(logutil.NewLogger(os.Stderr, envconfig.LogLevel()))
Jesse Gross's avatar
Jesse Gross committed
925
	slog.Info("starting ollama engine")
926
927
928

	server := &Server{
		batchSize: *batchSize,
929
		status:    llm.ServerStatusLoadingModel,
930
931
	}

932
933
934
935
936
937
	server.cond = sync.NewCond(&server.mu)
	server.ready.Add(1)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

Jesse Gross's avatar
Jesse Gross committed
938
939
940
	// TODO(jessegross): Parameters that need to be implemented:
	//	no-mmap

941
	var tensorSplitFloats []float32
942
	if *tensorSplit != "" {
943
944
945
		splits := strings.Split(*tensorSplit, ",")
		tensorSplitFloats = make([]float32, len(splits))
		for i, s := range splits {
946
			f, _ := strconv.ParseFloat(s, 32)
947
			tensorSplitFloats[i] = float32(f)
948
		}
949
950
951
	}

	params := ml.BackendParams{
952
953
954
955
956
		NumThreads:     *threads,
		NumGPULayers:   *numGPULayers,
		MainGPU:        *mainGPU,
		TensorSplit:    tensorSplitFloats,
		FlashAttention: *flashAttention,
957
	}
958

959
	go server.load(ctx, *mpath, params, lpaths, *parallel, *kvCacheType, *kvSize, *multiUserCache)
960
961
962
963
964
965
	go server.run(ctx)

	addr := "127.0.0.1:" + strconv.Itoa(*port)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		fmt.Println("Listen error:", err)
966
		return err
967
968
969
970
	}
	defer listener.Close()

	mux := http.NewServeMux()
971
972
973
974
975
976
977
	// TODO: support embeddings
	mux.HandleFunc("POST /embedding", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "this model does not support embeddings", http.StatusNotImplemented)
	})

	mux.HandleFunc("POST /completion", server.completion)
	mux.HandleFunc("GET /health", server.health)
978
979
980
981
982
983
984
985

	httpServer := http.Server{
		Handler: mux,
	}

	log.Println("Server listening on", addr)
	if err := httpServer.Serve(listener); err != nil {
		log.Fatal("server error:", err)
986
		return err
987
988
	}

989
	return nil
990
}