add cohere2 models

This commit is contained in:
Patrick Devine 2025-01-15 19:49:17 -08:00
parent 021817e59a
commit 453d65a8ab
9 changed files with 476 additions and 0 deletions

View File

@ -193,6 +193,8 @@ func ConvertModel(fsys fs.FS, ws io.WriteSeeker) error {
conv = &bertModel{}
case "CohereForCausalLM":
conv = &commandrModel{}
case "Cohere2ForCausalLM":
conv = &cohere2Model{}
default:
return errors.New("unsupported architecture")
}

View File

@ -0,0 +1,85 @@
package convert
import (
"cmp"
"github.com/ollama/ollama/llm"
)
type cohere2Model struct {
ModelParameters
MaxPositionEmbeddings uint32 `json:"max_position_embeddings"`
HiddenSize uint32 `json:"hidden_size"`
HiddenLayers uint32 `json:"num_hidden_layers"`
IntermediateSize uint32 `json:"intermediate_size"`
NumAttentionHeads uint32 `json:"num_attention_heads"`
NumKeyValueHeads uint32 `json:"num_key_value_heads"`
LayerNormEPS float32 `json:"layer_norm_eps"`
RopeTheta float32 `json:"rope_theta"`
UseQKNorm bool `json:"use_qk_norm"`
MaxLength uint32 `json:"model_max_length"`
LogitScale float32 `json:"logit_scale"`
NCtx uint32 `json:"n_ctx"`
SlidingWindow uint32 `json:"sliding_window"`
HeadDim uint32 `json:"head_dim"`
RotaryPct float32 `json:"rotary_pct"`
VocabSize uint32 `json:"vocab_size"`
}
var _ ModelConverter = (*cohere2Model)(nil)
func (p *cohere2Model) KV(t *Tokenizer) llm.KV {
kv := p.ModelParameters.KV(t)
kv["general.architecture"] = "cohere2"
kv["general.name"] = "C4Ai Command R7B"
kv["cohere2.context_length"] = cmp.Or(p.MaxLength, p.MaxPositionEmbeddings, p.NCtx)
kv["cohere2.embedding_length"] = p.HiddenSize
kv["cohere2.block_count"] = p.HiddenLayers
kv["cohere2.feed_forward_length"] = p.IntermediateSize
kv["cohere2.attention.head_count"] = p.NumAttentionHeads
kv["cohere2.attention.head_count_kv"] = p.NumKeyValueHeads
kv["cohere2.attention.key_length"] = p.HeadDim
kv["cohere2.attention.layer_norm_epsilon"] = p.LayerNormEPS
kv["cohere2.attention.sliding_window"] = p.SlidingWindow
kv["cohere2.attention.value_length"] = p.HeadDim
kv["cohere2.max_position_embeddings"] = cmp.Or(p.MaxLength, p.MaxPositionEmbeddings)
kv["cohere2.logit_scale"] = p.LogitScale
kv["cohere2.rope.dimension_count"] = uint32(p.RotaryPct * float32(p.HiddenSize / p.NumAttentionHeads))
kv["cohere2.rope.freq_base"] = p.RopeTheta
kv["cohere2.rope.scaling.type"] = "none"
kv["cohere2.vocab_size"] = p.VocabSize
return kv
}
func (p *cohere2Model) Tensors(ts []Tensor) []llm.Tensor {
var out []llm.Tensor
for _, t := range ts {
out = append(out, llm.Tensor{
Name: t.Name(),
Kind: t.Kind(),
Shape: t.Shape(),
WriterTo: t,
})
}
return out
}
func (p *cohere2Model) Replacements() []string {
return []string{
"self_attn.q_norm", "attn_q_norm",
"self_attn.k_norm", "attn_k_norm",
"model.layers", "blk",
"input_layernorm", "attn_norm",
"mlp.down_proj", "ffn_down",
"mlp.gate_proj", "ffn_gate",
"mlp.up_proj", "ffn_up",
"self_attn.k_proj", "attn_k",
"self_attn.o_proj", "attn_output",
"self_attn.q_proj", "attn_q",
"self_attn.v_proj", "attn_v",
"model.norm", "output_norm",
"model.embed_tokens", "token_embd",
}
}

View File

@ -29,6 +29,8 @@ type tensorData struct {
Shape []int `json:"shape"`
}
var generate string
func convertFull(t *testing.T, fsys fs.FS) (*os.File, llm.KV, *llm.Tensors) {
t.Helper()
@ -91,6 +93,7 @@ func generateResultsJSON(t *testing.T, f *os.File, kv llm.KV, tensors *llm.Tenso
func TestMain(m *testing.M) {
var level slog.Level
flag.TextVar(&level, "level", slog.LevelInfo, "log level")
flag.StringVar(&generate, "generate", "", "generate model data")
flag.Parse()
slog.SetLogLoggerLevel(level)
os.Exit(m.Run())
@ -110,6 +113,7 @@ func TestConvertModel(t *testing.T) {
"gemma-2-9b-it",
"Qwen2.5-0.5B-Instruct",
"c4ai-command-r-v01",
"c4ai-command-r7b-12-2024",
}
for i := range cases {
@ -127,6 +131,19 @@ func TestConvertModel(t *testing.T) {
f, kv, tensors := convertFull(t, os.DirFS(p))
actual := generateResultsJSON(t, f, kv, tensors)
if generate != "" && generate == tt {
outFile := filepath.Join("testdata", fmt.Sprintf("%s.json", tt))
data, err := json.MarshalIndent(actual, "", " ")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(outFile, data, 0644); err != nil {
t.Fatal(err)
}
t.Logf("Generated expected results for %s", tt)
return
}
expectFile, err := os.Open(filepath.Join("testdata", fmt.Sprintf("%s.json", tt)))
if err != nil {
t.Fatal(err)

File diff suppressed because one or more lines are too long

69
template/cohere2.gotmpl Normal file
View File

@ -0,0 +1,69 @@
{{- if or .Tools .System }}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>
{{- if .Tools }}# Safety Preamble
The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
# System Preamble
## Basic Rules
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
{{ if .System }}# User Preamble
{{ .System }}
{{- end }}
## Available Tools
Here is a list of tools that you have available to you:
{{- range .Tools }}
```python
def {{ .Function.Name }}(
{{- range $name, $property := .Function.Parameters.Properties }}{{ $name }}: {{ $property.Type }}, {{ end }}) -> List[Dict]:
'''{{ .Function.Description }}
{{- if .Function.Parameters.Properties }}
Args:
{{- range $name, $property := .Function.Parameters.Properties }}
{{ $name }} ({{ $property.Type }}): {{ $property.Description }}
{{- end }}
{{- end }}
'''
pass
```
{{- end }}
{{- else if .System }}{{ .System }}
{{- end }}<|END_OF_TURN_TOKEN|>
{{- end }}
{{- range $i, $_ := .Messages }}
{{- $last := eq (len (slice $.Messages $i)) 1 }}
{{- if eq .Role "user" }}<|START_OF_TURN_TOKEN|><|USER_TOKEN|>{{ .Content }}
{{- if $.Tools }}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Write 'Action:' followed by a json-formatted list of actions that you want to perform in order to produce a good response to the user's last input. You can use any of the supplied tools any number of times, but you should aim to execute the minimum number of necessary actions for the input. You should use the `directly-answer` tool if calling the other tools is unnecessary. The list of actions you want to call should be formatted as a list of json objects, for example:
```json
[
{
"tool_name": title of the tool in the specification,
"parameters": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters
}
]```
{{- end }}
{{- else if eq .Role "assistant" }}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>
{{- if .Content }}{{ .Content }}
{{- else if .ToolCalls }}
Action: ```json
[
{{- range .ToolCalls }}
{
"tool_name": "{{ .Function.Name }}",
"parameters": {{ .Function.Arguments }}
}
{{- end }}
]```
{{- end }}
{{- else if eq .Role "tool" }}<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><results>
console_output: {{ .Content }}
</results>
{{- end }}
{{- if not $last }}<|END_OF_TURN_TOKEN|>
{{- else }}
{{- if ne .Role "assistant" }}<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>{{- end }}
{{- end }}
{{- end }}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>You are a helpful assistant.<|END_OF_TURN_TOKEN|><|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hello, how are you?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>I'm doing great. How can I help you today?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>I'd like to show off how chat templating works!<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>

1
template/testdata/cohere2.gotmpl/user vendored Normal file
View File

@ -0,0 +1 @@
<|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hello, how are you?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>

View File

@ -0,0 +1 @@
<|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hello, how are you?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>I'm doing great. How can I help you today?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>I'd like to show off how chat templating works!<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>