embed.go 1.49 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
5
6
package gemma3

import (
	"github.com/ollama/ollama/fs"
	"github.com/ollama/ollama/ml"
	"github.com/ollama/ollama/ml/nn"
7
	"github.com/ollama/ollama/ml/nn/pooling"
Michael Yang's avatar
Michael Yang committed
8
9
10
11
12
13
	"github.com/ollama/ollama/model"
	"github.com/ollama/ollama/model/input"
)

type embedModel struct {
	model.Base
14
	model.SentencePiece
Michael Yang's avatar
Michael Yang committed
15
16

	*TextModel
17
	poolingType pooling.Type
Michael Yang's avatar
Michael Yang committed
18
19
20
21
22
23

	Dense [2]*nn.Linear `gguf:"dense"`
}

func (m *embedModel) Forward(ctx ml.Context, batch input.Batch) (ml.Tensor, error) {
	hiddenStates := m.TextModel.Forward(ctx, batch, m.Cache)
Michael Yang's avatar
Michael Yang committed
24
	hiddenStates = m.poolingType.Forward(ctx, hiddenStates)
Michael Yang's avatar
Michael Yang committed
25
26
27
	for _, dense := range m.Dense {
		hiddenStates = dense.Forward(ctx, hiddenStates)
	}
28
	hiddenStates = hiddenStates.L2Norm(ctx, 1e-12)
Michael Yang's avatar
Michael Yang committed
29
30
31
32
33
	return hiddenStates, nil
}

func newEmbedModel(c fs.Config) (model.Model, error) {
	m := &embedModel{
34
		SentencePiece: model.NewSentencePiece(
Michael Yang's avatar
Michael Yang committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
			&model.Vocabulary{
				Values: c.Strings("tokenizer.ggml.tokens"),
				Scores: c.Floats("tokenizer.ggml.scores"),
				Types:  c.Ints("tokenizer.ggml.token_type"),
				AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
				BOS:    []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
				AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
				EOS: append(
					[]int32{
						int32(c.Uint("tokenizer.ggml.eos_token_id")),
						int32(c.Uint("tokenizer.ggml.eot_token_id", 106)),
					},
					c.Ints("tokenizer.ggml.eos_token_ids")...,
				),
			},
		),
		TextModel:   newTextModel(c),
52
		poolingType: pooling.Type(c.Uint("pooling_type", 0)),
Michael Yang's avatar
Michael Yang committed
53
54
55
56
	}

	return m, nil
}