model.go 6.44 KB
Newer Older
Michael Yang's avatar
llama4  
Michael Yang committed
1
2
3
4
5
package llama4

import (
	"bytes"
	"image"
Michael Yang's avatar
Michael Yang committed
6
	"slices"
Michael Yang's avatar
llama4  
Michael Yang committed
7
8
9
10
11
12
13
14
15
16
17
18

	"github.com/ollama/ollama/fs"
	"github.com/ollama/ollama/kvcache"
	"github.com/ollama/ollama/ml"
	"github.com/ollama/ollama/ml/nn"
	"github.com/ollama/ollama/model"
	"github.com/ollama/ollama/model/input"
)

type Model struct {
	model.Base
	model.BytePairEncoding
Michael Yang's avatar
Michael Yang committed
19
	ImageProcessor
Michael Yang's avatar
llama4  
Michael Yang committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

	*VisionModel `gguf:"v,vision"`
	*Projector   `gguf:"mm"`
	*TextModel
}

type Projector struct {
	Linear1 *nn.Linear `gguf:"linear_1"`
}

func (p *Projector) Forward(ctx ml.Context, visionOutputs ml.Tensor) ml.Tensor {
	return p.Linear1.Forward(ctx, visionOutputs)
}

func New(c fs.Config) (model.Model, error) {
	m := Model{
		BytePairEncoding: model.NewBytePairEncoding(
Michael Yang's avatar
Michael Yang committed
37
38
			c.String("tokenizer.ggml.pretokenizer",
				`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
Michael Yang's avatar
llama4  
Michael Yang committed
39
40
			&model.Vocabulary{
				Values: c.Strings("tokenizer.ggml.tokens"),
Michael Yang's avatar
Michael Yang committed
41
				Types:  c.Ints("tokenizer.ggml.token_type"),
Michael Yang's avatar
llama4  
Michael Yang committed
42
43
44
45
46
				Merges: c.Strings("tokenizer.ggml.merges"),
				BOS:    int32(c.Uint("tokenizer.ggml.bos_token_id")),
				AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
				EOS:    int32(c.Uint("tokenizer.ggml.eos_token_id")),
				AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
Michael Yang's avatar
Michael Yang committed
47
48
49
				// TODO: set EOT to EOS otherwise 0 will stop generation
				EOT:    int32(c.Uint("tokenizer.ggml.eos_token_id")),
				AddEOT: c.Bool("tokenizer.ggml.add_eos_token", false),
Michael Yang's avatar
llama4  
Michael Yang committed
50
51
			},
		),
Michael Yang's avatar
Michael Yang committed
52
53
54
		ImageProcessor: newImageProcessor(c),
		VisionModel:    newVisionModel(c),
		TextModel:      newTextModel(c),
Michael Yang's avatar
llama4  
Michael Yang committed
55
56
57
	}

	m.Cache = kvcache.NewWrapperCache(
Michael Yang's avatar
Michael Yang committed
58
		kvcache.NewChunkedAttentionCache(int32(c.Uint("attention.chunk_size", 8192)), m.Shift),
Michael Yang's avatar
llama4  
Michael Yang committed
59
60
61
62
63
64
		kvcache.NewCausalCache(m.Shift),
	)

	return &m, nil
}

65
func (m *Model) EncodeMultimodal(ctx ml.Context, multimodalData []byte) ([]input.Multimodal, error) {
Michael Yang's avatar
llama4  
Michael Yang committed
66
67
68
69
70
71
72
73
74
	if len(m.VisionModel.Layers) < 1 {
		return nil, model.ErrNoVisionModel
	}

	img, _, err := image.Decode(bytes.NewReader(multimodalData))
	if err != nil {
		return nil, err
	}

Michael Yang's avatar
Michael Yang committed
75
	pixelsLocal, pixelsGlobal, size, err := m.ProcessImage(img)
Michael Yang's avatar
llama4  
Michael Yang committed
76
77
78
79
	if err != nil {
		return nil, err
	}

Michael Yang's avatar
Michael Yang committed
80
	tilesLocal, err := ctx.Input().FromFloatSlice(pixelsLocal, size.X, size.Y, m.numChannels)
Michael Yang's avatar
llama4  
Michael Yang committed
81
82
83
84
	if err != nil {
		return nil, err
	}

Michael Yang's avatar
Michael Yang committed
85
	ratioW, ratioH := size.X/m.imageSize, size.Y/m.imageSize
Michael Yang's avatar
Michael Yang committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

	tilesLocal = tilesLocal.Reshape(ctx, size.X/ratioW, ratioW, size.Y, m.numChannels).Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
	tilesLocal = tilesLocal.Reshape(ctx, size.X/ratioW*size.Y/ratioH, ratioH, ratioW, m.numChannels).Permute(ctx, 0, 3, 2, 1).Contiguous(ctx)
	tilesLocal = tilesLocal.Reshape(ctx, size.X/ratioW, size.Y/ratioH, m.numChannels, ratioH*ratioW)

	pixelValues := tilesLocal

	if len(pixelsGlobal) > 0 {
		tilesGlobal, err := ctx.Input().FromFloatSlice(pixelsGlobal, m.imageSize, m.imageSize, m.numChannels)
		if err != nil {
			return nil, err
		}

		pixelValues = pixelValues.Concat(ctx, tilesGlobal, 3)
	}

Michael Yang's avatar
llama4  
Michael Yang committed
102
103
	visionOutputs := m.VisionModel.Forward(ctx, pixelValues)
	visionOutputs = visionOutputs.Reshape(ctx, visionOutputs.Dim(0), visionOutputs.Dim(1)*visionOutputs.Dim(2)*visionOutputs.Dim(3))
Michael Yang's avatar
Michael Yang committed
104
105
	projectedOutputs := m.Projector.Forward(ctx, visionOutputs)

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
	var multimodal []input.Multimodal
	aspectRatio := image.Point{ratioW, ratioH}

	var offset int
	patchesPerChunk := projectedOutputs.Dim(1)
	if aspectRatio.Y*aspectRatio.X > 1 {
		patchesPerChunk = projectedOutputs.Dim(1) / (aspectRatio.X*aspectRatio.Y + 1)

		for range aspectRatio.Y {
			for x := range aspectRatio.X {
				view := projectedOutputs.View(ctx, projectedOutputs.Stride(1)*offset,
					projectedOutputs.Dim(0), projectedOutputs.Stride(1),
					patchesPerChunk)
				var separator separator
				if x < aspectRatio.X-1 {
					separator.x = true // <|tile_x_separator|>
				} else {
					separator.y = true // <|tile_y_separator|>
				}
				multimodal = append(multimodal, input.Multimodal{Tensor: view, Data: &separator})
				offset += patchesPerChunk
			}
		}
	}
Michael Yang's avatar
Michael Yang committed
130

131
132
133
134
	view := projectedOutputs.View(ctx, projectedOutputs.Stride(1)*offset,
		projectedOutputs.Dim(0), projectedOutputs.Stride(1),
		patchesPerChunk)
	multimodal = append(multimodal, input.Multimodal{Tensor: view, Data: &separator{}})
Michael Yang's avatar
Michael Yang committed
135

136
	return multimodal, nil
Michael Yang's avatar
Michael Yang committed
137
138
}

139
140
141
type separator struct {
	x bool
	y bool
Michael Yang's avatar
llama4  
Michael Yang committed
142
143
}

Michael Yang's avatar
Michael Yang committed
144
func (m *Model) PostTokenize(inputs []input.Input) ([]input.Input, error) {
Michael Yang's avatar
Michael Yang committed
145
146
	var result []input.Input
	for _, inp := range inputs {
147
		if len(inp.Multimodal) == 0 {
Michael Yang's avatar
Michael Yang committed
148
149
150
151
152
153
154
			result = append(result, inp)
			continue
		}

		var imageInputs []input.Input
		imageInputs = append(imageInputs, input.Input{Token: 200080}) // <|image_start|>

155
156
157
158
159
160
161
162
		for i, mm := range inp.Multimodal {
			patchesPerChunk := mm.Tensor.Dim(1)

			if i < len(inp.Multimodal)-1 {
				separator := mm.Data.(*separator)

				imageInputs = append(imageInputs, input.Input{Token: 200092, Multimodal: []input.Multimodal{{Tensor: mm.Tensor}}, MultimodalHash: inp.MultimodalHash, SameBatch: patchesPerChunk}) // <|patch|>
				imageInputs = append(imageInputs, slices.Repeat([]input.Input{{Token: 200092}}, patchesPerChunk-1)...)
Michael Yang's avatar
Michael Yang committed
163

164
165
166
167
168
169
170
171
172
173
174
				if separator.x {
					imageInputs = append(imageInputs, input.Input{Token: 200084}) // <|tile_x_separator|>
				}
				if separator.y {
					imageInputs = append(imageInputs, input.Input{Token: 200085}) // <|tile_y_separator|>
				}
			} else {
				imageInputs = append(imageInputs, input.Input{Token: 200090})                                                                                                                      // <|image|>
				imageInputs = append(imageInputs, input.Input{Token: 200092, Multimodal: []input.Multimodal{{Tensor: mm.Tensor}}, MultimodalHash: inp.MultimodalHash, SameBatch: patchesPerChunk}) // <|patch|>
				imageInputs = append(imageInputs, slices.Repeat([]input.Input{{Token: 200092}}, patchesPerChunk-1)...)
				imageInputs = append(imageInputs, input.Input{Token: 200080}) // <|image_end|>
Michael Yang's avatar
Michael Yang committed
175
176
177
178
179
180
181
			}
		}

		result = append(result, imageInputs...)
	}

	return result, nil
Michael Yang's avatar
Michael Yang committed
182
183
}

Michael Yang's avatar
llama4  
Michael Yang committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
func (m *Model) Forward(ctx ml.Context, batch input.Batch) (ml.Tensor, error) {
	positions, err := ctx.Input().FromIntSlice(batch.Positions, len(batch.Positions))
	if err != nil {
		return nil, err
	}

	outputs, err := ctx.Input().FromIntSlice(batch.Outputs, len(batch.Outputs))
	if err != nil {
		return nil, err
	}

	return m.TextModel.Forward(ctx, batch.Inputs, positions, outputs, batch, m.Cache), nil
}

func init() {
	model.Register("llama4", New)
}