mirror of
https://github.com/ollama/ollama.git
synced 2025-11-12 02:27:58 +01:00
* TEMPORARY: Update the llama.cpp upstream to my fork's Granite Four branch
This will be redone once my branch is merged upstream in llama.cpp
* feat: Update all patches
There are a number that are no longer needed at all:
- 0003-embeddings: Embeddings entirely overhauled on master
- 0008-ensure-KV-cache-is-fully-defragmented: KV caching entirely
overhauled on master
- 0019-metal-add-mean-kernel-14267: Merged upstream
- 0020-CUDA-add-mean-operation-14313: Merged upstream
* feat: Sync llama.cpp and ggml
* fix: Update rsync-filter for all moved/new/removed files
* fix: Add files missing from sync
* fix: Update ggml rsync-filter for new ggml-cpu/arch subdirs
* fix: Add ggml files missing from sync
* fix: Narrow llama.cpp rsync-filter to not include mtmd main tool cpp files
* fix: Remove mtmd main cpp files
* fix: Add missing include in sampling_ext.cpp
* fix: Update llama.go to use mtmd instead of clip/llava
* fix: Add patch for mtmd_input_text
* chore: Ignore *.patched in the patch directory
* fix: Fix support for arch-specific ggml-cpu source files with new arrangement
In https://github.com/ggml-org/llama.cpp/pull/13892, all arch-specific
implementations were split out into a nested tree structure under
ggml-cpu/arch. This conflicts with standard CGO layout where all
arch-specific source files are expected to live in the same directory as
the parent go module and use suffixes based on GOOS and GOARCH. As such,
there were really two options for getting this to work:
1. Add a patch on top of the GGML sync to rearrange the files to match the
GO layout convention
2. Use CGO directives to conditionally include the nested source files in
the compilation units
This commit does (2) in order to minimize the set of changes needed on top
of the upstream file layout. To get this to work, there are two key things
needed:
1. In cpu.go, #cgo directives are added to explicitly set __${GOARCH}__ in
the preprocessor directives
2. In arch-impls.c|cpp, use an #ifdef | #elif defined | #endif chain to
explicitly include the .c|.cpp files for the given architecture from the
nested directory
* fix: Use mtmd_helper to correctly load the bitmap for the image
* fix: Apply patch for mtmd_text_input
* fix: Add missing stb to llama.cpp rsync-filter
* fix: Add sync'ed stb vendored header
* fix: Use c++17 and include vendor for go wrapper modules
* fix: Update patch 0015 for upstream implementation of uuid
* feat: Bump to the latest tip of the branch
* fix: Update patches for bump
* feat: Bump back to the cenral repo and point at the latest master
This includes granite 4 and a number of other model architectures!
* fix: Revert changes to ggml export GPU UUID patch
* fix: Add patch for GGML_VERSION and GGML_COMMIT constants
* feat: Sync all patched code
* build: Include cmake/common.cmake in ggml sync
* build: Add top-level include for GNUINstallDirs in CMakeLists.txt
This is used to populate CMAKE_INSTALL_BINDIR
* fix: Add a patch to avoid power throttling API on non-msvc windows builds
* fix: Sync patch changes for ggml-cpu.c
* feat: Bump llama.cpp to 4a4f42
This picks up support for Kimi K2 and PLaMO-2
* feat: Sync llama.cpp
* fix: Handle multi-chunk image encodings from mtmd
* fix: Re-number patches after merge with `main`
* feat: Bump to 41e78c in the makefile
* fix: Fix Solar and argsort/copy patches after bump
* fix: Remove Gemma3n CUDA Graphs patch
It was implemented upstream:
https://github.com/ggml-org/llama.cpp/pull/14741
* feat: Sync llama.cpp / ggml after latest bump
* build: Remove unnecessary CFLAGS definitions in cpu.go
* fix: Remove unnecessary additions in the rsync-filter
* fix: Remove unused vendored code for chat template parsing
* Revert "fix: Remove Gemma3n CUDA Graphs patch"
This reverts commit d724caced3.
* fix: Update 0020 CUDA Graphs for gemma3n to keep both llama.cpp and ollama fixes
https://github.com/ollama/ollama/pull/11195#issuecomment-3137312394
* fix: Sync ggml-cuda.cu after keeping both style cuda graph fixes for gemma3n
* unwind mxfp4 patch
Prepare to bump ggml with their impl for mxfp4
* bump
* fix windows build error
* Convert tensors at load time
Repack the mxfp4 tensors as ggmls kernels expect them to be.
* convert mlp bf16 to f32
* buffer the conversion better
* reshape earlier
* openai swiglu
* add ids
* split qkv, gate_up
* fix nested alt tags
* fast attention
* remove debug messages
* fix lint
* remove redundant test
* remap values only if source/target are different
* add back i32->i32 copy
* refactor cpu quants
* clean up vendor
* update patch instructions
* clean up patches
* remove webgpu
* update mem
* also handle gpt-oss
* revert convert changes
---------
Signed-off-by: Gabe Goodhart <ghart@us.ibm.com>
Co-authored-by: Gabe Goodhart <ghart@us.ibm.com>
Co-authored-by: Daniel Hiltgen <daniel@ollama.com>
381 lines
11 KiB
Go
381 lines
11 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"slices"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"github.com/ollama/ollama/api"
|
|
"github.com/ollama/ollama/logutil"
|
|
)
|
|
|
|
type harmonyParserState int
|
|
|
|
const (
|
|
harmonyParserState_LookingForMessageStart harmonyParserState = iota
|
|
harmonyParserState_ParsingHeader
|
|
harmonyParserState_ParsingContent
|
|
)
|
|
|
|
func shouldUseHarmony(model Model) bool {
|
|
if slices.Contains([]string{"gptoss", "gpt-oss"}, model.Config.ModelFamily) {
|
|
// heuristic to check whether the template expects to be parsed via harmony:
|
|
// search for harmony tags that are nearly always used
|
|
if model.Template.Contains("<|start|>") && model.Template.Contains("<|end|>") {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func (s harmonyParserState) String() string {
|
|
switch s {
|
|
// we're looking for the message start tag
|
|
case harmonyParserState_LookingForMessageStart:
|
|
return "LookingForMessageStart"
|
|
case harmonyParserState_ParsingHeader:
|
|
return "ParsingHeader"
|
|
case harmonyParserState_ParsingContent:
|
|
return "ParsingContent"
|
|
default:
|
|
return "Unknown"
|
|
}
|
|
}
|
|
|
|
type HarmonyParser struct {
|
|
state harmonyParserState
|
|
MessageStartTag string
|
|
MessageEndTag string
|
|
HeaderEndTag string
|
|
acc strings.Builder
|
|
lifetimeAcc strings.Builder
|
|
}
|
|
|
|
type HarmonyEvent interface {
|
|
isHarmonyEvent()
|
|
}
|
|
|
|
type HarmonyEventMessageStart struct{}
|
|
|
|
func (HarmonyEventMessageStart) isHarmonyEvent() {}
|
|
|
|
type HarmonyEventHeaderComplete struct {
|
|
Header HarmonyHeader
|
|
}
|
|
|
|
func (HarmonyEventHeaderComplete) isHarmonyEvent() {}
|
|
|
|
type HarmonyEventContentEmitted struct {
|
|
Content string
|
|
}
|
|
|
|
func (HarmonyEventContentEmitted) isHarmonyEvent() {}
|
|
|
|
type HarmonyEventMessageEnd struct{}
|
|
|
|
func (HarmonyEventMessageEnd) isHarmonyEvent() {}
|
|
|
|
type HarmonyHeader struct {
|
|
Role string
|
|
Channel string
|
|
Recipient string
|
|
}
|
|
|
|
func (s *HarmonyParser) AddImplicitStart() {
|
|
s.acc.WriteString("<|start|>assistant")
|
|
}
|
|
|
|
func (s *HarmonyParser) AddImplicitStartOrPrefill(lastMessage *api.Message) {
|
|
if lastMessage != nil && lastMessage.Role == "assistant" {
|
|
// handle prefilling conditions
|
|
if lastMessage.Content != "" {
|
|
s.acc.WriteString("<|start|>assistant<|channel|>final<|message|>")
|
|
return
|
|
} else if lastMessage.Thinking != "" {
|
|
s.acc.WriteString("<|start|>assistant<|channel|>analysis<|message|>")
|
|
return
|
|
}
|
|
}
|
|
s.AddImplicitStart()
|
|
}
|
|
|
|
func (s *HarmonyParser) AddContent(content string) []HarmonyEvent {
|
|
s.lifetimeAcc.WriteString(content)
|
|
s.acc.WriteString(content)
|
|
|
|
var events []HarmonyEvent
|
|
|
|
keepLooping := true
|
|
// we loop because we might pass through multiple parsing states in a single
|
|
// call to addContent, and we want to make sure callers don't have to wait for
|
|
// data that's already unambiguous
|
|
for keepLooping {
|
|
var newEvents []HarmonyEvent
|
|
newEvents, keepLooping = eat(s)
|
|
events = append(events, newEvents...)
|
|
}
|
|
|
|
return events
|
|
}
|
|
|
|
// the additional bool return is true iff we should continue eating
|
|
func eat(s *HarmonyParser) ([]HarmonyEvent, bool) {
|
|
switch s.state {
|
|
case harmonyParserState_LookingForMessageStart:
|
|
// does the acc contain the message start tag?
|
|
if strings.Contains(s.acc.String(), s.MessageStartTag) {
|
|
// split the acc into the message start tag and the rest
|
|
split := strings.SplitN(s.acc.String(), s.MessageStartTag, 2)
|
|
before := split[0]
|
|
if before != "" {
|
|
slog.Warn("harmony parser: found message start tag in the middle of the content", "content", s.acc.String())
|
|
}
|
|
after := split[1]
|
|
s.acc.Reset()
|
|
s.acc.WriteString(after)
|
|
s.state = harmonyParserState_ParsingHeader
|
|
return []HarmonyEvent{HarmonyEventMessageStart{}}, true
|
|
}
|
|
|
|
// no match, so we keep accumulating
|
|
return nil, false
|
|
case harmonyParserState_ParsingHeader:
|
|
if strings.Contains(s.acc.String(), s.HeaderEndTag) {
|
|
split := strings.SplitN(s.acc.String(), s.HeaderEndTag, 2)
|
|
header := split[0]
|
|
after := split[1]
|
|
s.acc.Reset()
|
|
s.acc.WriteString(after)
|
|
s.state = harmonyParserState_ParsingContent
|
|
return []HarmonyEvent{HarmonyEventHeaderComplete{Header: s.parseHeader(header)}}, true
|
|
}
|
|
return nil, false
|
|
case harmonyParserState_ParsingContent:
|
|
if strings.Contains(s.acc.String(), s.MessageEndTag) {
|
|
// if we already have the message end tag, we can emit the content up to it
|
|
split := strings.SplitN(s.acc.String(), s.MessageEndTag, 2)
|
|
content := split[0]
|
|
after := split[1]
|
|
s.acc.Reset()
|
|
s.acc.WriteString(after)
|
|
s.state = harmonyParserState_LookingForMessageStart
|
|
events := []HarmonyEvent{}
|
|
if content != "" {
|
|
events = append(events, HarmonyEventContentEmitted{Content: content})
|
|
}
|
|
events = append(events, HarmonyEventMessageEnd{})
|
|
return events, true
|
|
} else if overlapLen := overlap(s.acc.String(), s.MessageEndTag); overlapLen > 0 {
|
|
// if our suffix contains the start of the message end tag, we can emit
|
|
// the content up to the start of the message end tag
|
|
content := s.acc.String()[:len(s.acc.String())-overlapLen]
|
|
remaining := s.acc.String()[len(s.acc.String())-overlapLen:]
|
|
s.acc.Reset()
|
|
s.acc.WriteString(remaining)
|
|
// emit the content we know isn't part of the message end tag, and keep
|
|
// accumulating to disambiguate the rest
|
|
if content == "" {
|
|
return nil, false
|
|
}
|
|
return []HarmonyEvent{HarmonyEventContentEmitted{Content: content}}, false
|
|
} else {
|
|
// no end tag, so it's still normal content that we can immediately emit
|
|
content := s.acc.String()
|
|
if content == "" {
|
|
return nil, false
|
|
}
|
|
s.acc.Reset()
|
|
return []HarmonyEvent{HarmonyEventContentEmitted{Content: content}}, false
|
|
}
|
|
}
|
|
|
|
return nil, false
|
|
}
|
|
|
|
func (s *HarmonyParser) parseHeader(raw string) HarmonyHeader {
|
|
harmonyHeader := HarmonyHeader{}
|
|
|
|
// if `<|constrain|>` is present, ensure it has a space before it so it gets
|
|
// parsed as a separate token, even if the model didn't include the space
|
|
if strings.Contains(raw, "<|constrain|>") {
|
|
raw = strings.Replace(raw, "<|constrain|>", " <|constrain|>", 1)
|
|
raw = strings.TrimSpace(raw)
|
|
}
|
|
|
|
// look for the optional channel tag, which is `<|channel|>` followed by the
|
|
// channel name, all without any whitespace
|
|
channelIndex := strings.Index(raw, "<|channel|>")
|
|
if channelIndex != -1 {
|
|
before := raw[:channelIndex]
|
|
after := raw[channelIndex+len("<|channel|>"):]
|
|
// the channel name is `after` all the way up to the first (if any) whitespace character
|
|
idx := strings.IndexFunc(after, func(r rune) bool {
|
|
return unicode.IsSpace(r)
|
|
})
|
|
if idx == -1 {
|
|
idx = len(after)
|
|
}
|
|
harmonyHeader.Channel = after[:idx]
|
|
after = after[idx:]
|
|
// now we remove the channel tag from the raw string to further process
|
|
raw = before + after
|
|
raw = strings.TrimSpace(raw)
|
|
}
|
|
|
|
// split the header into whitespace-separated tokens
|
|
tokens := strings.Fields(raw)
|
|
|
|
// the first token is treated as the role
|
|
if len(tokens) == 0 {
|
|
slog.Error("harmony parser: missing role in header", "header", raw)
|
|
return harmonyHeader
|
|
}
|
|
role := tokens[0]
|
|
tokens = tokens[1:]
|
|
// special case: if role starts with to= then it's a tool call
|
|
if strings.HasPrefix(role, "to=") {
|
|
harmonyHeader.Recipient = role[3:]
|
|
harmonyHeader.Role = "tool"
|
|
} else {
|
|
harmonyHeader.Role = role
|
|
}
|
|
|
|
// the recipient (if any) can be specified before or after the channel tag, so
|
|
// we check it at the end once we've already parsed the channel and role
|
|
if harmonyHeader.Recipient == "" && len(tokens) > 0 && strings.HasPrefix(tokens[0], "to=") {
|
|
harmonyHeader.Recipient = tokens[0][3:]
|
|
}
|
|
|
|
return harmonyHeader
|
|
}
|
|
|
|
// longest overlap between suffix of s and prefix of delim
|
|
func overlap(s, delim string) int {
|
|
max := min(len(delim), len(s))
|
|
for i := max; i > 0; i-- {
|
|
if strings.HasSuffix(s, delim[:i]) {
|
|
return i
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// harmonyMessageState represents the current state of message processing
|
|
type harmonyMessageState int
|
|
|
|
const (
|
|
harmonyMessageState_Normal harmonyMessageState = iota
|
|
harmonyMessageState_Thinking
|
|
harmonyMessageState_ToolCalling
|
|
)
|
|
|
|
// HarmonyMessageHandler processes harmony events and accumulates content appropriately.
|
|
// This is a higher level interface that maps harmony concepts into ollama concepts
|
|
type HarmonyMessageHandler struct {
|
|
state harmonyMessageState
|
|
harmonyParser *HarmonyParser
|
|
}
|
|
|
|
// NewHarmonyMessageHandler creates a new message handler
|
|
func NewHarmonyMessageHandler() *HarmonyMessageHandler {
|
|
return &HarmonyMessageHandler{
|
|
state: harmonyMessageState_Normal,
|
|
harmonyParser: &HarmonyParser{
|
|
MessageStartTag: "<|start|>",
|
|
MessageEndTag: "<|end|>",
|
|
HeaderEndTag: "<|message|>",
|
|
},
|
|
}
|
|
}
|
|
|
|
// AddContent processes the content and returns the content, thinking, and tool content.
|
|
// content and thinking are already fully parsed, but tool content still needs to be passed to the tool parser
|
|
func (h *HarmonyMessageHandler) AddContent(content string, toolParser *HarmonyToolCallAccumulator) (string, string, string) {
|
|
contentSb := strings.Builder{}
|
|
thinkingSb := strings.Builder{}
|
|
toolContentSb := strings.Builder{}
|
|
|
|
events := h.harmonyParser.AddContent(content)
|
|
for _, event := range events {
|
|
switch event := event.(type) {
|
|
case HarmonyEventHeaderComplete:
|
|
slog.Log(context.TODO(), logutil.LevelTrace, "harmony event header complete", "header", event.Header)
|
|
switch event.Header.Channel {
|
|
case "analysis":
|
|
if event.Header.Recipient != "" {
|
|
h.state = harmonyMessageState_ToolCalling
|
|
// event.Header.Recipient is the tool name, something like
|
|
// "browser.search" for a built-in, or "functions.calc" for a
|
|
// custom one
|
|
toolParser.SetToolName(event.Header.Recipient)
|
|
} else {
|
|
h.state = harmonyMessageState_Thinking
|
|
}
|
|
case "commentary":
|
|
if event.Header.Recipient != "" {
|
|
h.state = harmonyMessageState_ToolCalling
|
|
toolParser.SetToolName(event.Header.Recipient)
|
|
} else {
|
|
h.state = harmonyMessageState_Normal
|
|
}
|
|
case "final":
|
|
h.state = harmonyMessageState_Normal
|
|
}
|
|
case HarmonyEventContentEmitted:
|
|
slog.Log(context.TODO(), logutil.LevelTrace, "harmony event content", "content", event.Content, "state", h.state)
|
|
if h.state == harmonyMessageState_Normal {
|
|
contentSb.WriteString(event.Content)
|
|
} else if h.state == harmonyMessageState_Thinking {
|
|
thinkingSb.WriteString(event.Content)
|
|
} else if h.state == harmonyMessageState_ToolCalling {
|
|
toolContentSb.WriteString(event.Content)
|
|
}
|
|
case HarmonyEventMessageEnd:
|
|
h.state = harmonyMessageState_Normal
|
|
}
|
|
}
|
|
return contentSb.String(), thinkingSb.String(), toolContentSb.String()
|
|
}
|
|
|
|
func (h *HarmonyMessageHandler) CreateToolParser() *HarmonyToolCallAccumulator {
|
|
return &HarmonyToolCallAccumulator{
|
|
state: harmonyToolCallState_Normal,
|
|
currentToolName: nil,
|
|
}
|
|
}
|
|
|
|
type harmonyToolCallState int
|
|
|
|
const (
|
|
harmonyToolCallState_Normal harmonyToolCallState = iota
|
|
harmonyToolCallState_ToolCalling
|
|
)
|
|
|
|
type HarmonyToolCallAccumulator struct {
|
|
state harmonyToolCallState
|
|
acc strings.Builder
|
|
currentToolName *string
|
|
}
|
|
|
|
func (a *HarmonyToolCallAccumulator) SetToolName(toolName string) {
|
|
a.currentToolName = &toolName
|
|
}
|
|
|
|
func (a *HarmonyToolCallAccumulator) Add(content string) {
|
|
a.acc.WriteString(content)
|
|
}
|
|
|
|
func (a *HarmonyToolCallAccumulator) Drain() (*string, string) {
|
|
str := a.acc.String()
|
|
a.state = harmonyToolCallState_Normal
|
|
a.acc.Reset()
|
|
return a.currentToolName, str
|
|
}
|
|
|
|
func (a *HarmonyToolCallAccumulator) Content() string {
|
|
return a.acc.String()
|
|
}
|